defblocked_attention(Q:torch.Tensor,K:torch.Tensor,V:torch.Tensor,scale=None,div:int=4,use_rel_pos:bool=True,rel_pos_h:torch.Tensor=None,rel_pos_w:torch.Tensor=None):"""
note:
1. Q and K should be in the same shape
2. H and H must be divisable by `div`
3. Q, K, V must on the same device
"""B, H, W, C=Q.shapeassert(H//div*div==HandW//div*div==W)ifscaleisNone:scale=C**-0.5ifuse_rel_pos:Rh=get_rel_pos(H,H,rel_pos_h).view(div,H//div,div,H//div,C).permute(0,2,1,3,4)Rw=get_rel_pos(W,W,rel_pos_w).view(W,W,C)Q=Q.view(B,div,H//div,W,C).permute(1,0,2,3,4)K=K.view(B,div,H//div,W,C).permute(1,0,2,3,4)V=V.view(B,div,H//div,W,C).permute(1,0,2,3,4)x=torch.zeros((B,H,W,C),dtype=torch.float32,device=Q.device)foriinrange(div):s=torch.zeros((B,H//div,W,div),dtype=torch.float32,device=Q.device)m=torch.zeros((B,H//div,W,div),dtype=torch.float32,device=Q.device)y=torch.zeros((B,H//div,W,C,div),dtype=torch.float32,device=Q.device)forpinrange(div):t=torch.einsum('bijc,bpqc->bijpq',Q[i]*scale,K[p])ifuse_rel_pos:t+=torch.einsum('bijc,ipc->bijp',Q[i],Rh[i, p]).view(B,H//div,W,H//div,1)t+=torch.einsum('bijc,jqc->bijq',Q[i],Rw).view(B,H//div,W,1,W)m[:, :, :, p], _=torch.max(t.view(B,H//div,W,-1),dim=-1)t=torch.exp(t-(m[:, :, :, p]).view(B,H//div,W,1,1)).view(B,H//div,W,H//div,W)s[:, :, :, p]=torch.sum(t.view(B,H//div,W,-1),dim=-1)y[:, :, :, :, p]=torch.einsum('bijpq,bpqc->bijc',t,V[p])real_m, _=torch.max(m,dim=-1)forpinrange(div):s[:, :, :, p]*=torch.exp(m[:, :, :, p]-real_m)y[:, :, :, :, p]*=torch.exp(m[:, :, :, p]-real_m).view(B,H//div,W,1)x[:, i*(H//div):(i+1)*(H//div), :, :]=torch.sum(y,dim=-1)/torch.sum(s,dim=-1).view(B,H//div,W,1)returnx