Mamba-style selective state-space blocks #
Mamba replaces quadratic attention with a linear-time selective state-space recurrence. In full models, the token controls discretization and input/output state parameters.
This file exposes two layers:
MambaBlockSpec: a compact theorem-friendly diagonal SSM block for scan laws and kernel validation.SelectiveMambaBlockSpec: a fuller Mamba-style block with input/gate projections, causal depthwise convolution, SiLU, token-dependentDelta/B/C, diagonal selective scan, gated output, and output projection.
The compact block is intentionally retained: it is the smallest reusable core for proving scan algebra and for validating CUDA kernels. The full block builds the paper-style Mamba dataflow on top of the same affine-scan idea.
- recurrent selective scan (
h ← A ⊙ h + B ⊙ x_state), - a gated state readout,
- tokenwise input/output projections.
Implementation status #
nn.mamba uses the trainable selective block in NN/Runtime/Autograd/Model/Layers/Mamba.lean.
The recurrence in NN/Runtime/Autograd/Model/Mamba.lean follows the
SelectiveMambaBlockSpec dataflow through generic differentiable operations: causal depthwise
convolution and SiLU produce the feature used for softplus time steps and token-dependent B/C,
then the diagonal state update feeds the skip connection, SiLU gate, and output projection.
The runtime stores logA, so this Spec's rate tensor corresponds to exp(logA). It uses the
dense time-step projection described below and does not call a fused variable-coefficient scan.
The layer has eleven trainable parameter tensors. Its expanded channel count is
innerWidth = expansion * hiddenWidth, where hiddenWidth is the output feature width.
Expansion, state width, and convolution width determine the saved tensor shapes. Checkpoints from
the former gated recurrence use a different parameter layout and cannot be loaded into this layer
unchanged. Each layer call starts with zero recurrent state and empty convolution history;
Runtime.Autograd.Model.Mamba.runArray accepts and returns both a state tensor of shape
[innerWidth, stateWidth] and newest-first projected-token history for continuation across chunks.
The causality (prefix-preservation) theorems in
NN/MLTheory/Proofs/StateSpace/MambaCausality.lean concern MambaBlockSpec.runArray,
SelectiveMambaBlockSpec.runArray, and SelectiveMambaBlockSpec.runArrayWithHistory, built on
the scan algebra in NN/MLTheory/Proofs/StateSpace/Scan.lean. They do not establish equivalence
between the generic differentiable runtime and these Spec runners or prove its gradients.
PyTorch import caveats #
convKernelis indexed(tap, channel)with taps newest-first; PyTorch's depthwiseconv1dweight is(channel, 1, tap)with taps oldest-first, so import needs a transpose and a reversal.dtProjis one squareinnerDim × innerDimmap; the reference model'sdt_rankfactorization (x_projthendt_proj) is not represented and must be multiplied out before loading.bProjandcProjare stored as separateinnerDim × stateDimmatrices; the reference model packsB,C, and thedtinput into onex_projoutput.
References:
- Gu, Dao. "Mamba: Linear-Time Sequence Modeling with Selective State Spaces", COLM 2024.
- Dao, Gu. "Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality" (Mamba-2), ICML 2024.
Parameters for a compact diagonal Mamba-style block.
- inProj : TorchLean.Tensor α [inputDim, stateDim]
Input projection into SSM state channels.
- gateProj : TorchLean.Tensor α [inputDim, stateDim]
Gate projection. The gate is
sigmoid(x @ gateProj). - outProj : TorchLean.Tensor α [stateDim, outputDim]
Output projection from gated state channels.
- ssm : Spec.Dynamics.DiagonalSSM α stateDim
Diagonal state-space core.
Instances For
Input-to-state projection.
Instances For
Token-dependent sigmoid gate.
Instances For
One Mamba-style token step, returning (new_state, output).
Instances For
Run an array of tokens through the recurrent block.
Instances For
An empty token sequence leaves the hidden state untouched and emits nothing.
A Mamba recurrent pass emits one output token per input token.
Parameters for a fuller Mamba-style selective SSM block.
Shape conventions:
inputDim: token/input feature width,innerDim: expanded channel width used by Mamba's convolution and SSM path,stateDim: per-channel diagonal SSM state size,outputDim: output feature width,convWidth: causal depthwise-convolution width.
The recurrence state has shape [innerDim, stateDim]. This mirrors the common implementation
view of Mamba where each expanded channel carries a small diagonal state vector.
- xProj : TorchLean.Tensor α [inputDim, innerDim]
Content/input projection
x -> x_path. - zProj : TorchLean.Tensor α [inputDim, innerDim]
Gate projection
x -> z_path. - convKernel : TorchLean.Tensor α [convWidth, innerDim]
Causal depthwise-convolution kernel, indexed by
(tap, channel)with tap0applied to the current token and taptto the tokentsteps back. PyTorch'sconv1dweight of shape(innerDim, 1, convWidth)stores taps oldest-first along its last axis, so importing a checkpoint requires transposing to(tap, channel)and reversing the tap axis. - convBias : TorchLean.Tensor α [innerDim]
Causal depthwise-convolution bias.
- dtProj : TorchLean.Tensor α [innerDim, innerDim]
Projection from activated convolution features to per-channel time steps
Delta.This is a single square map. The reference implementation factors it through a low-rank bottleneck as
x_proj(innerDim -> dt_rank) followed bydt_proj(dt_rank -> innerDim); the product of those two matrices can be loaded here, but the factorization itself is not modelled. - dtBias : TorchLean.Tensor α [innerDim]
Bias before the
softplustime-step nonlinearity. - A : TorchLean.Tensor α [innerDim, stateDim]
Positive diagonal state rates
A[d,n]used asexp(-Delta[d] * A[d,n]). - bProj : TorchLean.Tensor α [innerDim, stateDim]
Token-dependent input-state projection
B_t = u_t @ bProj. - cProj : TorchLean.Tensor α [innerDim, stateDim]
Token-dependent state-output projection
C_t = u_t @ cProj. - dSkip : TorchLean.Tensor α [innerDim]
Per-channel residual/skip coefficient.
- outProj : TorchLean.Tensor α [innerDim, outputDim]
Output projection from expanded channels to output features.
Instances For
Projection feeding the content path before convolution and selective state updates.
Instances For
Projection feeding the multiplicative gate path in the selective state-space block.
Instances For
SiLU/Swish applied channelwise.
Instances For
Causal depthwise convolution from a newest-first history of projected tokens.
history[0] is the current projected token, history[1] is the previous token, etc. Missing
history entries are treated as zero padding.
Instances For
Token-dependent positive time steps Delta = softplus(u @ dtProj + dtBias).
Instances For
Token-dependent input-state vector B_t.
Instances For
Token-dependent state-output vector C_t.
Instances For
One selective diagonal SSM update:
h'[d,n] = exp(-Delta[d] * A[d,n]) * h[d,n] + (Delta[d] * B_t[n]) * u[d].
Instances For
Read out expanded channels from the updated state using C_t, plus the Mamba skip path.
Instances For
One full Mamba token step from an already-updated convolution history.
The history argument is newest-first and must include the current projected content token.
Instances For
One recurrent step while carrying the newest-first convolution history.
The carried history is truncated to the convWidth most recent projected tokens. Older entries
can never be read by causalDepthwiseConv, so dropping them changes no output while keeping the
state size bounded over arbitrarily long sequences.
Instances For
Recurrent runner from an existing state and newest-first convolution history.
Instances For
Run a sequence through the full selective Mamba block.
Instances For
With no tokens the convolution history is never consulted and the state is returned as is.
Same for the selective block: no tokens in, no tokens out.
The full Mamba recurrent pass emits one output token per input token.
The public full Mamba runner emits one output token per input token.