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

Class Block

models_mamba.py:67–141  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

65
66
67class Block(nn.Module):
68 def __init__(
69 self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
70 ):
71 """
72 Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
73
74 This Block has a slightly different structure compared to a regular
75 prenorm Transformer block.
76 The standard block is: LN -> MHA/MLP -> Add.
77 [Ref: https://arxiv.org/abs/2002.04745]
78 Here we have: Add -> LN -> Mixer, returning both
79 the hidden_states (output of the mixer) and the residual.
80 This is purely for performance reasons, as we can fuse add and LayerNorm.
81 The residual needs to be provided (except for the very first block).
82 """
83 super().__init__()
84 self.residual_in_fp32 = residual_in_fp32
85 self.fused_add_norm = fused_add_norm
86 self.mixer = mixer_cls(dim)
87 self.norm = norm_cls(dim)
88 self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
89 if self.fused_add_norm:
90 assert RMSNorm is not None, "RMSNorm import fails"
91 assert isinstance(
92 self.norm, (nn.LayerNorm, RMSNorm)
93 ), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
94
95 def forward(
96 self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
97 ):
98 r"""Pass the input through the encoder layer.
99
100 Args:
101 hidden_states: the sequence to the encoder layer (required).
102 residual: hidden_states = Mixer(LN(residual))
103 """
104 if not self.fused_add_norm:
105 if residual is None:
106 residual = hidden_states
107 else:
108 residual = residual + self.drop_path(hidden_states)
109
110 hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
111 if self.residual_in_fp32:
112 residual = residual.to(torch.float32)
113 else:
114 fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
115 if residual is None:
116 hidden_states, residual = fused_add_norm_fn(
117 hidden_states,
118 self.norm.weight,
119 self.norm.bias,
120 residual=residual,
121 prenorm=True,
122 residual_in_fp32=self.residual_in_fp32,
123 eps=self.norm.eps,
124 )

Callers 1

create_blockFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…