hidden_states: (B, L, D) Returns: same shape as hidden_states
(self, hidden_states, inference_params=None)
| 134 | ) |
| 135 | |
| 136 | def forward(self, hidden_states, inference_params=None): |
| 137 | """ |
| 138 | hidden_states: (B, L, D) |
| 139 | Returns: same shape as hidden_states |
| 140 | """ |
| 141 | batch, seqlen, dim = hidden_states.shape |
| 142 | |
| 143 | conv_state, ssm_state = None, None |
| 144 | if inference_params is not None: |
| 145 | conv_state, ssm_state = self._get_states_from_cache(inference_params, batch) |
| 146 | if inference_params.seqlen_offset > 0: |
| 147 | # The states are updated inplace |
| 148 | out, _, _ = self.step(hidden_states, conv_state, ssm_state) |
| 149 | return out |
| 150 | |
| 151 | # We do matmul and transpose BLH -> HBL at the same time |
| 152 | xz = rearrange( |
| 153 | self.in_proj.weight @ rearrange(hidden_states, "b l d -> d (b l)"), |
| 154 | "d (b l) -> b d l", |
| 155 | l=seqlen, |
| 156 | ) |
| 157 | if self.in_proj.bias is not None: |
| 158 | xz = xz + rearrange(self.in_proj.bias.to(dtype=xz.dtype), "d -> d 1") |
| 159 | |
| 160 | A = -torch.exp(self.A_log.float()) # (d_inner, d_state) |
| 161 | # In the backward pass we write dx and dz next to each other to avoid torch.cat |
| 162 | if self.use_fast_path and inference_params is None: # Doesn't support outputting the states |
| 163 | out = mamba_inner_fn( |
| 164 | xz, |
| 165 | self.conv1d.weight, |
| 166 | self.conv1d.bias, |
| 167 | self.x_proj.weight, |
| 168 | self.dt_proj.weight, |
| 169 | self.out_proj.weight, |
| 170 | self.out_proj.bias, |
| 171 | A, |
| 172 | None, # input-dependent B |
| 173 | None, # input-dependent C |
| 174 | self.D.float(), |
| 175 | delta_bias=self.dt_proj.bias.float(), |
| 176 | delta_softplus=True, |
| 177 | ) |
| 178 | else: |
| 179 | x, z = xz.chunk(2, dim=1) |
| 180 | # Compute short convolution |
| 181 | if conv_state is not None: |
| 182 | # If we just take x[:, :, -self.d_conv :], it will error if seqlen < self.d_conv |
| 183 | # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise. |
| 184 | conv_state.copy_(F.pad(x, (self.d_conv - x.shape[-1], 0))) # Update state (B D W) |
| 185 | if causal_conv1d_fn is None: |
| 186 | x = self.act(self.conv1d(x)[..., :seqlen]) |
| 187 | else: |
| 188 | assert self.activation in ["silu", "swish"] |
| 189 | x = causal_conv1d_fn( |
| 190 | x=x, |
| 191 | weight=rearrange(self.conv1d.weight, "d 1 w -> d w"), |
| 192 | bias=self.conv1d.bias, |
| 193 | activation=self.activation, |
nothing calls this directly
no test coverage detected