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

Method step

models/mamba_simple.py:248–293  ·  view source on GitHub ↗
(self, hidden_states, conv_state, ssm_state)

Source from the content-addressed store, hash-verified

246 return out
247
248 def step(self, hidden_states, conv_state, ssm_state):
249 dtype = hidden_states.dtype
250 assert hidden_states.shape[1] == 1, "Only support decoding with 1 token at a time for now"
251 xz = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
252 x, z = xz.chunk(2, dim=-1) # (B D)
253
254 # Conv step
255 if causal_conv1d_update is None:
256 conv_state.copy_(torch.roll(conv_state, shifts=-1, dims=-1)) # Update state (B D W)
257 conv_state[:, :, -1] = x
258 x = torch.sum(conv_state * rearrange(self.conv1d.weight, "d 1 w -> d w"), dim=-1) # (B D)
259 if self.conv1d.bias is not None:
260 x = x + self.conv1d.bias
261 x = self.act(x).to(dtype=dtype)
262 else:
263 x = causal_conv1d_update(
264 x,
265 conv_state,
266 rearrange(self.conv1d.weight, "d 1 w -> d w"),
267 self.conv1d.bias,
268 self.activation,
269 )
270
271 x_db = self.x_proj(x) # (B dt_rank+2*d_state)
272 dt, B, C = torch.split(x_db, [self.dt_rank, self.d_state, self.d_state], dim=-1)
273 # Don't add dt_bias here
274 dt = F.linear(dt, self.dt_proj.weight) # (B d_inner)
275 A = -torch.exp(self.A_log.float()) # (d_inner, d_state)
276
277 # SSM step
278 if selective_state_update is None:
279 # Discretize A and B
280 dt = F.softplus(dt + self.dt_proj.bias.to(dtype=dt.dtype))
281 dA = torch.exp(torch.einsum("bd,dn->bdn", dt, A))
282 dB = torch.einsum("bd,bn->bdn", dt, B)
283 ssm_state.copy_(ssm_state * dA + rearrange(x, "b d -> b d 1") * dB)
284 y = torch.einsum("bdn,bn->bd", ssm_state.to(dtype), C)
285 y = y + self.D.to(dtype) * x
286 y = y * self.act(z) # (B D)
287 else:
288 y = selective_state_update(
289 ssm_state, x, dt, A, B, C, self.D, z=z, dt_bias=self.dt_proj.bias, dt_softplus=True
290 )
291
292 out = self.out_proj(y)
293 return out.unsqueeze(1), conv_state, ssm_state
294
295 def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
296 device = self.out_proj.weight.device

Callers 4

forwardMethod · 0.95
mainFunction · 0.45
mainFunction · 0.45
train_one_epochFunction · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected