(self, x)
| 184 | padding=0) |
| 185 | |
| 186 | def forward(self, x): |
| 187 | h_ = x |
| 188 | h_ = self.norm(h_) |
| 189 | q = self.q(h_) |
| 190 | k = self.k(h_) |
| 191 | v = self.v(h_) |
| 192 | |
| 193 | # compute attention |
| 194 | b,c,h,w = q.shape |
| 195 | q = q.reshape(b,c,h*w) |
| 196 | q = q.permute(0,2,1) # b,hw,c |
| 197 | k = k.reshape(b,c,h*w) # b,c,hw |
| 198 | w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] |
| 199 | w_ = w_ * (int(c)**(-0.5)) |
| 200 | w_ = torch.nn.functional.softmax(w_, dim=2) |
| 201 | |
| 202 | # attend to values |
| 203 | v = v.reshape(b,c,h*w) |
| 204 | w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) |
| 205 | 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] |
| 206 | h_ = h_.reshape(b,c,h,w) |
| 207 | |
| 208 | h_ = self.proj_out(h_) |
| 209 | |
| 210 | return x+h_ |
| 211 | |
| 212 | class MemoryEfficientAttnBlock(nn.Module): |
| 213 | """ |
nothing calls this directly
no outgoing calls
no test coverage detected