The Recurrence at the Heart of Mamba
Mamba's S6 layer runs an independent N-dimensional linear recurrence for every batch element and every one of the ED channels, with parameters that change at every token. Implement the sequential reference scan in the conventions of the released selective_scan_ref (with the sequence axis second instead of last).
selective_scan(u, delta, A, B, C, D)
- Shapes (here
B as a dimension is the batch size, and B as an argument is the input matrix): u and delta are (B, L, ED), A is (ED, N), B and C are (B, L, N), D is (ED,).
- Discretisation: zero-order hold for A and the Euler rule for B, exactly as in the reference code:
Aˉb,t,d,n=exp(Δb,t,dAd,n),Bˉb,t,d,nub,t,d=Δb,t,dBb,t,nub,t,d
- Recurrence, starting from a zero state hb,−1=0 of shape
(ED, N) per batch element:
hb,t,d,n=Aˉb,t,d,nhb,t−1,d,n+Δb,t,dBb,t,nub,t,d
- Output with the skip connection:
yb,t,d=n∑Cb,t,nhb,t,d,n+Ddub,t,d
- Return
(y, last_state): y of shape (B, L, ED) and the state after the final token, of shape (B, ED, N).
Hints
- Loop over the
L time steps only; batch, channels and state dimensions are all elementwise and can be vectorised.
B and C carry no channel axis. They are shared by all ED channels of a token, so they broadcast over that axis.
- The skip term Du does not pass through the state, so it does not appear in
last_state.