MCPcopy Create free account
hub / github.com/lingeringlight/START / Block

Class Block

models/mamba_simple.py:337–393  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

335
336
337class Block(nn.Module):
338 def __init__(
339 self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False
340 ):
341 """
342 Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
343
344 This Block has a slightly different structure compared to a regular
345 prenorm Transformer block.
346 The standard block is: LN -> MHA/MLP -> Add.
347 [Ref: https://arxiv.org/abs/2002.04745]
348 Here we have: Add -> LN -> Mixer, returning both
349 the hidden_states (output of the mixer) and the residual.
350 This is purely for performance reasons, as we can fuse add and LayerNorm.
351 The residual needs to be provided (except for the very first block).
352 """
353 super().__init__()
354 self.residual_in_fp32 = residual_in_fp32
355 self.fused_add_norm = fused_add_norm
356 self.mixer = mixer_cls(dim)
357 self.norm = norm_cls(dim)
358 if self.fused_add_norm:
359 assert RMSNorm is not None, "RMSNorm import fails"
360 assert isinstance(
361 self.norm, (nn.LayerNorm, RMSNorm)
362 ), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
363
364 def forward(
365 self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
366 ):
367 r"""Pass the input through the encoder layer.
368
369 Args:
370 hidden_states: the sequence to the encoder layer (required).
371 residual: hidden_states = Mixer(LN(residual))
372 """
373 if not self.fused_add_norm:
374 residual = (hidden_states + residual) if residual is not None else hidden_states
375 hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
376 if self.residual_in_fp32:
377 residual = residual.to(torch.float32)
378 else:
379 fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
380 hidden_states, residual = fused_add_norm_fn(
381 hidden_states,
382 self.norm.weight,
383 self.norm.bias,
384 residual=residual,
385 prenorm=True,
386 residual_in_fp32=self.residual_in_fp32,
387 eps=self.norm.eps,
388 )
389 hidden_states = self.mixer(hidden_states, inference_params=inference_params)
390 return hidden_states, residual
391
392 def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
393 return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…