MCPcopy Create free account
hub / github.com/DSL-Lab/StreamSplat / ResAttBlock

Class ResAttBlock

model/transformer_utils.py:256–299  ·  view source on GitHub ↗

Attention block.

Source from the content-addressed store, hash-verified

254 return attn_output, None
255
256class ResAttBlock(nn.Module):
257 """
258 Attention block.
259 """
260 def __init__(self, d_model, n_head, window_size=None, drop_path_rate=0.0):
261 super().__init__()
262 self.attn = MultiHeadAttention(d_model, d_model, d_model, d_model, n_head)
263 self.layernorm1 = LayerNorm(d_model)
264 self.mlp = nn.Sequential(OrderedDict([
265 ("c_fc", nn.Linear(d_model, d_model * 4, bias=False)),
266 ("silu", nn.SiLU(inplace=True)),
267 ("c_proj", nn.Linear(d_model * 4, d_model, bias=False))
268 ]))
269 self.layernorm2 = LayerNorm(d_model)
270 self.window_size = window_size
271
272 def attention(self, x, index):
273 attn_mask = None
274 if self.window_size is not None:
275 l = x.shape[1]
276 assert l % self.window_size == 0
277 if index % 2 == 0:
278 x = rearrange(x, 'b (p w) c -> (b p) w c', w=self.window_size)
279 x = self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
280 x = rearrange(x, '(b l) w c -> b (l w) c', l=l//self.window_size, w=self.window_size)
281 else:
282 x = torch.roll(x, shifts=self.window_size//2, dims=1)
283 x = rearrange(x, 'b (p w) c -> (b p) w c', w=self.window_size)
284 x = self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
285 x = rearrange(x, '(b l) w c -> b (l w) c', l=l//self.window_size, w=self.window_size)
286 x = torch.roll(x, shifts=-self.window_size//2, dims=1)
287 else:
288 x = self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
289 return x
290
291 def forward(self, x, index, condition=None):
292 # no condition in encoder, its a dummy argument
293 y = self.layernorm1(x)
294 y = self.attention(y, index)
295 x = x.type(torch.float32) + y # residual in fp32
296 y = self.layernorm2(x)
297 y = self.mlp(y)
298 x = x.type(torch.float32) + y # residual in fp32
299 return x
300
301class ConditionalResAttBlock(nn.Module):
302 def __init__(self, d_model, n_head, window_size=None, drop_path_rate=0.0):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected