(self, x)
| 176 | |
| 177 | |
| 178 | def forward(self, x): |
| 179 | h_ = x |
| 180 | h_ = self.norm(h_) |
| 181 | q = self.q(h_) |
| 182 | k = self.k(h_) |
| 183 | v = self.v(h_) |
| 184 | |
| 185 | # compute attention |
| 186 | b,c,h,w = q.shape |
| 187 | q = q.reshape(b,c,h*w) |
| 188 | q = q.permute(0,2,1).contiguous() # b,hw,c |
| 189 | k = k.reshape(b,c,h*w) # b,c,hw |
| 190 | w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] |
| 191 | w_ = w_ * (int(c)**(-0.5)) |
| 192 | w_ = torch.nn.functional.softmax(w_, dim=2) |
| 193 | |
| 194 | # attend to values |
| 195 | v = v.reshape(b,c,h*w) |
| 196 | w_ = w_.permute(0,2,1).contiguous() # b,hw,hw (first hw of k, second of q) |
| 197 | h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] |
| 198 | h_ = h_.reshape(b,c,h,w) |
| 199 | |
| 200 | h_ = self.proj_out(h_) |
| 201 | |
| 202 | return x+h_ |
| 203 | |
| 204 | |
| 205 | def make_attn(in_channels, attn_type="vanilla"): |
nothing calls this directly
no outgoing calls
no test coverage detected