(self, x)
| 166 | |
| 167 | |
| 168 | def forward(self, x): |
| 169 | h_ = x |
| 170 | h_ = self.norm(h_) |
| 171 | q = self.q(h_) |
| 172 | k = self.k(h_) |
| 173 | v = self.v(h_) |
| 174 | |
| 175 | # compute attention |
| 176 | b,c,h,w = q.shape |
| 177 | q = q.reshape(b,c,h*w) |
| 178 | q = q.permute(0,2,1) # b,hw,c |
| 179 | k = k.reshape(b,c,h*w) # b,c,hw |
| 180 | w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] |
| 181 | w_ = w_ * (int(c)**(-0.5)) |
| 182 | w_ = torch.nn.functional.softmax(w_, dim=2) |
| 183 | |
| 184 | # attend to values |
| 185 | v = v.reshape(b,c,h*w) |
| 186 | w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) |
| 187 | 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] |
| 188 | h_ = h_.reshape(b,c,h,w) |
| 189 | |
| 190 | h_ = self.proj_out(h_) |
| 191 | |
| 192 | return x+h_ |
| 193 | |
| 194 | |
| 195 | class Model(nn.Module): |
nothing calls this directly
no outgoing calls
no test coverage detected