A Mamba mixer can run over a whole sequence (training, prompt processing) or one token at a time from two fixed-size caches (generation). Implement both modes for a single layer with batch size 1, and make them agree exactly.
Weights. W is a dict of numpy arrays with exactly these keys and shapes (model width D, inner width ED, state size N, conv width K, delta rank R; read the sizes off the shapes):
"in_proj": (2*ED, D), no bias"conv_w": (ED, K) and "conv_b": (ED,), the depthwise causal convolution"x_proj": (R + 2*N, ED), no bias"dt_proj_w": (ED, R) and "dt_proj_b": (ED,)"A_log": (ED, N), with "D": (ED,), the skip parameter"out_proj": (D, ED), no biasOne token goes through, in this order:
ED entries are , the last ED are .K-1 values of , oldest first) followed by the current ; , then with .R), (next N), (last N).(ED,).(ED, N), and .empty_cache(W) returns (conv_state, ssm_state) of zeros with shapes (ED, K-1) and (ED, N).
mamba_step(u, W, conv_state, ssm_state) processes one token and returns (out, new_conv_state, new_ssm_state). The new conv state holds the last K-1 values of (before the convolution). Do not modify the arguments in place.
mamba_forward(U, W) takes U of shape (L, D), starts from empty caches, and returns (Y, conv_state, ssm_state): Y has shape (L, D), and the caches are what mamba_step needs to continue the sequence. Running mamba_forward on a prefix and then mamba_step on the remaining tokens must reproduce mamba_forward on the whole sequence, even for prefixes shorter than K-1.
dt_proj bias goes inside the softplus, after the low-rank projection; the low-rank dt itself has no bias.