MCPcopy Create free account
hub / github.com/bbaaii/DreamDiffusion / AttnBlock

Class AttnBlock

code/dc_ldm/modules/diffusionmodules/model.py:150–202  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers 2

make_attnFunction · 0.85
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected