Can you explain why swap the axis after the softmax in this Non-Local block for images?…
- User
Can you explain why swap the axis after the softmax in this Non-Local block for images?
pythonclass NonLocalBlock(nn.Module): def __init__(self, channels): super(NonLocalBlock, self).__init__() self.in_channels = channels self.gn = nn.BatchNorm2d(channels) self.q = nn.Conv2d(channels, channels, 1, 1, 0) self.k = nn.Conv2d(channels, channels, 1, 1, 0) self.v = nn.Conv2d(channels, channels, 1, 1, 0) self.proj_out = nn.Conv2d(channels, channels, 1, 1, 0) def forward(self, x): h_ = self.gn(x) q = self.q(h_) k = self.k(h_) v = self.v(h_) b, c, h, w = q.shape q = q.reshape(b, c, h*w) # b, c, h*w q = q.permute(0, 2, 1) # b, h*w, c k = k.reshape(b, c, h*w) v = v.reshape(b, c, h*w) attn = torch.bmm(q, k) # (b,h*w,c)x(b,c,h*w) -> (b,h*w,h*w) attn = attn * (int(c)**(-0.5)) # scale by sqrt(d_model) if you will attn = F.softmax(attn, dim=2) attn = attn.permute(0, 2, 1) # I am not sure why this swap, since it's (b,h*w,h*w) A = torch.bmm(v, attn) # (b,c,h*w) (b,h*w,h*w) -> (b,c,h*w) A = A.reshape(b, c, h, w) return x + A - Assistant