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

Class AttnBlock

sat/sgm/modules/autoencoding/vqvae/movq_modules.py:164–199  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

162
163
164class AttnBlock(nn.Module):
165 def __init__(self, in_channels, zq_ch=None, add_conv=False):
166 super().__init__()
167 self.in_channels = in_channels
168
169 self.norm = Normalize(in_channels, zq_ch, add_conv=add_conv)
170 self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
171 self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
172 self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
173 self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
174
175 def forward(self, x, zq):
176 h_ = x
177 h_ = self.norm(h_, zq)
178 q = self.q(h_)
179 k = self.k(h_)
180 v = self.v(h_)
181
182 # compute attention
183 b, c, h, w = q.shape
184 q = q.reshape(b, c, h * w)
185 q = q.permute(0, 2, 1) # b,hw,c
186 k = k.reshape(b, c, h * w) # b,c,hw
187 w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
188 w_ = w_ * (int(c) ** (-0.5))
189 w_ = torch.nn.functional.softmax(w_, dim=2)
190
191 # attend to values
192 v = v.reshape(b, c, h * w)
193 w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
194 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]
195 h_ = h_.reshape(b, c, h, w)
196
197 h_ = self.proj_out(h_)
198
199 return x + h_
200
201
202class MOVQDecoder(nn.Module):

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected