Mamba-style selective state-space scan with zero-order-hold discretization

State-space layers such as S4 and Mamba (Gu and Dao, 2023) process a sequence with a linear recurrence instead of attention. A continuous system h' = A h + B x is discretized with a step size delta. In Mamba's selective version, delta, B and C depend on the current input, so the layer can choose what to remember. This problem uses a diagonal A and the exact zero-order-hold formulas for both A and B as written below.

Write ssm_scan(x, delta, A, B, C). Shapes: x (T, D) with D channels, delta (T, D) positive step sizes, A (D, N) strictly negative (diagonal state matrix per channel), B (T, N) and C (T, N) shared across channels.
For t = 0..T-1, with state h of shape (D, N) starting at zeros:
- Abar = exp(delta[t][:, None] * A)
- Bbar = (Abar - 1) / A * B[t][None, :]
- h = Abar * h + Bbar * x[t][:, None]
- y[t] = h @ C[t], shape (D,)
Return (y, h) where y has shape (T, D) and h is the final state.

Signaturedef ssm_scan(x, delta, A, B, C)

Understand the idea

A state-space layer reads a sequence with a simple linear memory update instead of attention. A step size delta discretises it: a large delta forgets the old state faster and absorbs more of the new input. In the selective version delta, B and C change with each input. Worked example: one channel, one state, A = -1, delta = ln 2 = 0.6931, B = C = 1, x = [2, 2]. Abar = exp(0.6931 * -1) = 0.5. Bbar = (0.5 - 1) / (-1) * 1 = 0.5. Step 0: h = 0.5 * 0 + 0.5 * 2 = 1, y = 1. Step 1: h = 0.5 * 1 + 0.5 * 2 = 1.5, y = 1.5. Rule per step, with h of shape (D, N): Abar = exp(delta[t] * A) per channel and state; Bbar = (Abar - 1) / A * B[t]; h = Abar * h + Bbar * x[t] per channel; y[t] = h C[t]. This exact zero-order-hold form for B is what the problem asks for, not the first-order shortcut delta * B. It is the core of Mamba.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: 6 steps, 3 channels, state 4ssm_scan(_x, _dt, _A, _B, _C)
  • Sample 2: final state onlyssm_scan(_x, _dt, _A, _B, _C)[1]