MCPcopy Create free account
hub / github.com/OpenDriveLab/ReSim / AttnBlock2D

Class AttnBlock2D

sat/sgm/modules/autoencoding/vqvae/movq_dec_3d_dev.py:179–220  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

177
178
179class AttnBlock2D(nn.Module):
180 def __init__(self, in_channels, zq_ch=None, add_conv=False):
181 super().__init__()
182 self.in_channels = in_channels
183
184 self.norm = Normalize3D(in_channels, zq_ch, add_conv=add_conv)
185 self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
186 self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
187 self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
188 self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
189
190 def forward(self, x, zq):
191 h_ = x
192 h_ = self.norm(h_, zq)
193
194 t = h_.shape[2]
195 h_ = rearrange(h_, "b c t h w -> (b t) c h w")
196
197 q = self.q(h_)
198 k = self.k(h_)
199 v = self.v(h_)
200
201 # compute attention
202 b, c, h, w = q.shape
203 q = q.reshape(b, c, h * w)
204 q = q.permute(0, 2, 1) # b,hw,c
205 k = k.reshape(b, c, h * w) # b,c,hw
206 w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
207 w_ = w_ * (int(c) ** (-0.5))
208 w_ = torch.nn.functional.softmax(w_, dim=2)
209
210 # attend to values
211 v = v.reshape(b, c, h * w)
212 w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
213 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]
214 h_ = h_.reshape(b, c, h, w)
215
216 h_ = self.proj_out(h_)
217
218 h_ = rearrange(h_, "(b t) c h w -> b c t h w", t=t)
219
220 return x + h_
221
222
223class MOVQDecoder3D(nn.Module):

Callers 2

__init__Method · 0.70
__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected