MCPcopy Create free account
hub / github.com/IceClear/StableSR / AttnBlock

Class AttnBlock

ldm/modules/diffusionmodules/model.py:188–240  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

186
187
188class AttnBlock(nn.Module):
189 def __init__(self, in_channels):
190 super().__init__()
191 self.in_channels = in_channels
192
193 self.norm = Normalize(in_channels)
194 self.q = torch.nn.Conv2d(in_channels,
195 in_channels,
196 kernel_size=1,
197 stride=1,
198 padding=0)
199 self.k = torch.nn.Conv2d(in_channels,
200 in_channels,
201 kernel_size=1,
202 stride=1,
203 padding=0)
204 self.v = torch.nn.Conv2d(in_channels,
205 in_channels,
206 kernel_size=1,
207 stride=1,
208 padding=0)
209 self.proj_out = torch.nn.Conv2d(in_channels,
210 in_channels,
211 kernel_size=1,
212 stride=1,
213 padding=0)
214
215
216 def forward(self, x):
217 h_ = x
218 h_ = self.norm(h_)
219 q = self.q(h_)
220 k = self.k(h_)
221 v = self.v(h_)
222
223 # compute attention
224 b,c,h,w = q.shape
225 q = q.reshape(b,c,h*w)
226 q = q.permute(0,2,1) # b,hw,c
227 k = k.reshape(b,c,h*w) # b,c,hw
228 w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
229 w_ = w_ * (int(c)**(-0.5))
230 w_ = torch.nn.functional.softmax(w_, dim=2)
231
232 # attend to values
233 v = v.reshape(b,c,h*w)
234 w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
235 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]
236 h_ = h_.reshape(b,c,h,w)
237
238 h_ = self.proj_out(h_)
239
240 return x+h_
241
242class MemoryEfficientAttnBlock(nn.Module):
243 def __init__(self, in_channels):

Callers 2

make_attnFunction · 0.85
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected