MCPcopy Create free account
hub / github.com/dek924/PerX2CT / AttnBlock

Class AttnBlock

x2ct_nerf/modules/diffusionmodules/model.py:229–280  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

227
228
229class AttnBlock(nn.Module):
230 def __init__(self, in_channels):
231 super().__init__()
232 self.in_channels = in_channels
233
234 self.norm = Normalize(in_channels)
235 self.q = torch.nn.Conv2d(in_channels,
236 in_channels,
237 kernel_size=1,
238 stride=1,
239 padding=0)
240 self.k = torch.nn.Conv2d(in_channels,
241 in_channels,
242 kernel_size=1,
243 stride=1,
244 padding=0)
245 self.v = torch.nn.Conv2d(in_channels,
246 in_channels,
247 kernel_size=1,
248 stride=1,
249 padding=0)
250 self.proj_out = torch.nn.Conv2d(in_channels,
251 in_channels,
252 kernel_size=1,
253 stride=1,
254 padding=0)
255
256 def forward(self, x):
257 h_ = x
258 h_ = self.norm(h_)
259 q = self.q(h_)
260 k = self.k(h_)
261 v = self.v(h_)
262
263 # compute attention
264 b, c, h, w = q.shape
265 q = q.reshape(b, c, h*w)
266 q = q.permute(0, 2, 1) # b,hw,c
267 k = k.reshape(b, c, h*w) # b,c,hw
268 w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
269 w_ = w_ * (int(c)**(-0.5))
270 w_ = torch.nn.functional.softmax(w_, dim=2)
271
272 # attend to values
273 v = v.reshape(b, c, h*w)
274 w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
275 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]
276 h_ = h_.reshape(b, c, h, w)
277
278 h_ = self.proj_out(h_)
279
280 return x+h_
281
282
283class Model(nn.Module):

Callers 7

__init__Method · 0.70
__init__Method · 0.70
__init__Method · 0.70
__init__Method · 0.70
__init__Method · 0.70
__init__Method · 0.70
__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected