nnterp · encyclopedia mamba · nnterp.families.mamba

family mamba

Mamba

The block

01 · the residual stream

One block of the stack. Hover any part for its nnterp name; click to pin the card.

embed_tokenstoken_embeddings
→
layers× 24
→
normfinal_norm_output
→
lm_headlm_head_output
→
logitsthe output
i = 0

identity layers[i].input + linear_attn.attention_output == layer_output

The API

02 · support()

Values, by host

⚠︎ marks a value this checkpoint has only under some load: hover it for the condition.

model MambaForCausalLMlayoutwhat it isread at
logits Logits [batch seq vocab_size] The logits the model returns, after anything it does past lm_head (a softcap, a scale)

the module's own output

token_embeddings Residual [batch seq hidden_size] The embedding module's output; layers[0].input is what enters the first block

the child module embed_tokens's output

final_norm_output Residual [batch seq hidden_size] The residual stream after the final norm, what lm_head reads

the child module norm's output

lm_head_output Logits [batch seq vocab_size] The head's logits before anything the model does past lm_head (a softcap, a scale)

the child module lm_head's output

next_token_probs NextTokenProbs [batch vocab_size] The next-token distribution at the last position; derived, read-only

the module's own output

input_ids Tokens [batch seq] The token ids the model was called with

the module's own input

attention_mask Tokens [batch seq] The attention mask the model was called with; zeros are padding

the module's own input

input_size scalar [batch, seq] of the current call; read-only

the module's own input

model.layers[i] MambaBlocklayoutwhat it isread at
layer_input Residual [batch seq hidden_size] The residual stream entering the block

the module's own input

attention_norm_output Residual [batch seq hidden_size] The normed stream entering the attention

the child module input_layernorm's output

layer_mid scalar Unavailable: a state-space block: one sublayer, the mixer, so there is no stream between sublayers and no MLP

nowhere: the family does not serve it

mlp_norm_output scalar Unavailable: a state-space block: one sublayer, the mixer, so there is no stream between sublayers and no MLP

nowhere: the family does not serve it

mlp_input scalar Unavailable: a state-space block: one sublayer, the mixer, so there is no stream between sublayers and no MLP

nowhere: the family does not serve it

layer_output Residual [batch seq hidden_size] The residual stream leaving the block, a tensor even when the block returns a tuple

the module's own output

model.layers[i].linear_attn MambaMixerlayoutwhat it isread at
attention_output Residual [batch seq hidden_size] What the mixer adds to the residual stream

the module's own output

⚠︎state ScanState [batch channels state_dim] The state after one token of the prompt; iterate it with tracer.iter; needs route_kernels(family, 'torch')

inside the forward: at or inside the kernel this call runs (a prompt's chunked one or a decode step's recurrent one)

⚠︎states ScanStates [batch seq channels state_dim] The state after every token of this call; needs route_kernels(family, 'torch')

computed from other values read in the same call

⚠︎attention_queries ScanQK [batch seq groups state_dim] C, the vector each token reads the state with

inside the forward: the arguments of the kernel this call runs (a prompt's chunked one or a decode step's recurrent one), argument C

⚠︎attention_keys ScanQK [batch seq groups state_dim] B, the vector each token writes into the state with

inside the forward: the arguments of the kernel this call runs (a prompt's chunked one or a decode step's recurrent one), argument B

⚠︎attention_values ScanValues [batch seq channels] x, the input the scan writes into the state

inside the forward: the arguments of the kernel this call runs (a prompt's chunked one or a decode step's recurrent one), argument x

⚠︎betas ScanSteps [batch seq channels] The step size dt = softplus(dt + dt_bias), per token and channel; derived, read-only

computed from other values read in the same call

⚠︎decays ScanDecays [batch seq channels state_dim] The per-token log decay dt * A of the state; derived, read-only

computed from other values read in the same call

⚠︎state_input ScanState | None [batch channels state_dim] The state entering the layer on a decode step (a copy of the cache's buffer), None on a prompt

inside the forward: the arguments of the kernel this call runs (a prompt's chunked one or a decode step's recurrent one), the element that call returns it in

⚠︎attention_head_outputs ScanValues [batch seq channels] y = C.h + D.x, the scan's read of the state before the gate and out_proj

inside the forward: at or inside the kernel this call runs (a prompt's chunked one or a decode step's recurrent one)

⚠︎state_output ScanState [batch channels state_dim] The state leaving the layer

inside the forward: at or inside the kernel this call runs (a prompt's chunked one or a decode step's recurrent one), the element that call returns it in

Printout

What print(model) shows on state-spaces/mamba-130m-hf: the native modules, standard names and every standard value with its layout.

MambaForCausalLM(
  (lm_head): Linear(in_features=768, out_features=50280, bias=False)
  (generator): Generator(
    (streamer): Streamer()
  )
  (embed_tokens): Embedding(50280, 768)
  (layers): ModuleList(
    (0-23): 24 x MambaBlock(
      (input_layernorm/norm): MambaRMSNorm(768, eps=1e-05)
      (linear_attn/mixer): MambaMixer(
        (conv1d): Conv1d(1536, 1536, kernel_size=(4,), stride=(1,), padding=(3,), groups=1536)
        (act): SiLUActivation()
        (in_proj): Linear(in_features=768, out_features=3072, bias=False)
        (x_proj): Linear(in_features=1536, out_features=80, bias=False)
        (dt_proj): Linear(in_features=48, out_features=1536, bias=True)
        (out_proj): Linear(in_features=1536, out_features=768, bias=False)
        (attention_queries) -> ScanQK [batch seq groups state_dim]: C, the vector each token reads the state with
        (attention_keys) -> ScanQK [batch seq groups state_dim]: B, the vector each token writes into the state with
        (attention_values) -> ScanValues [batch seq channels]: x, the input the scan writes into the state
        (betas) -> ScanSteps [batch seq channels]: The step size dt = softplus(dt + dt_bias), per token and channel; derived, read-only
        (decays) -> ScanDecays [batch seq channels state_dim]: The per-token log decay dt * A of the state; derived, read-only
        (state_input) -> ScanState | None [batch channels state_dim]: The state entering the layer on a decode step (a copy of the cache's buffer), None on a prompt
        (attention_head_outputs) -> ScanValues [batch seq channels]: y = C.h + D.x, the scan's read of the state before the gate and out_proj
        (state_output) -> ScanState [batch channels state_dim]: The state leaving the layer
        (state) -> ScanState [batch channels state_dim]: The state after one token of the prompt; iterate it with tracer.iter; needs route_kernels(family, 'torch')
        (states) -> ScanStates [batch seq channels state_dim]: The state after every token of this call; needs route_kernels(family, 'torch')
        (attention_output) -> Residual [batch seq hidden_size]: What the mixer adds to the residual stream
      )
      (layer_mid): Unavailable: a state-space block: one sublayer, the mixer, so there is no stream between sublayers and no MLP
      (layer_input) -> Residual [batch seq hidden_size]: The residual stream entering the block
      (attention_norm_output) -> Residual [batch seq hidden_size]: The normed stream entering the attention
      (mlp_norm_output) -> Residual [batch seq hidden_size]: The normed stream entering the MLP
      (mlp_input) -> Residual [batch seq hidden_size]: What the MLP is called with
      (layer_output) -> Residual [batch seq hidden_size]: The residual stream leaving the block, a tensor even when the block returns a tuple
    )
  )
  (norm): MambaRMSNorm(768, eps=1e-05)
  (logits) -> Logits [batch seq vocab_size]: The logits the model returns, after anything it does past lm_head (a softcap, a scale)
  (token_embeddings) -> Residual [batch seq hidden_size]: The embedding module's output; layers[0].input is what enters the first block
  (final_norm_output) -> Residual [batch seq hidden_size]: The residual stream after the final norm, what lm_head reads
  (lm_head_output) -> Logits [batch seq vocab_size]: The head's logits before anything the model does past lm_head (a softcap, a scale)
  (next_token_probs) -> NextTokenProbs [batch vocab_size]: The next-token distribution at the last position; derived, read-only
  (input_ids) -> Tokens [batch seq]: The token ids the model was called with
  (attention_mask) -> Tokens [batch seq]: The attention mask the model was called with; zeros are padding
  (input_size): [batch, seq] of the current call; read-only
)

Config

model.num_layers24
model.hidden_size768
model.vocab_size50280
model.intermediate_size1536
architecturesMambaForCausalLM
num_hidden_layers24
hidden_size768
intermediate_size1536
vocab_size50280
hidden_actsilu
tie_word_embeddingsTrue
dtypefloat32
n_layer24
layer_norm_epsilon1e-05
state_size16
expand2
conv_kernel4
residual_in_fp32True
d_model768
d_inner1536
time_step_min0.001

The Notes

03 · what to know before you run

attention_head_outputs is read before the gate

out = h + mixer(norm(h))
mixer: y = scan(x, dt, A, B, C) + D * x     # x: attention_values; y: attention_head_outputs
       return out_proj(y * silu(z))         # attention_output

A channel's term in attention_output is out_proj applied to y * silu(z), so attribute through out_proj.input, not attention_head_outputs.

C and B are shared by every channel

attention_queries (C) and attention_keys (B) are one vector per token, [batch, seq, 1, state_size], read by every channel of the mixer, so an edit to either reaches all of them.

The pattern is rebuilt from the scan's values

There is no attention_probabilities. Per channel the scan is a causal linear map over tokens, and the served values give its weights exactly:

y_t        = sum_s alpha[t, s] * x_s + D * x_t
alpha[t, s] = C_t . (exp(decays_{s+1} + ... + decays_t) * betas_s * B_s)

The decay term is [seq, seq, channels, state_size]; on a long prompt, slice the channels.

From the family module

04 · nnterp/families/mamba.py

Mamba (MambaForCausalLM): Mamba-1, a pure state-space model.

Its tree is backbone.{embeddings, layers[i].{norm, mixer}, norm_f} plus lm_head. A block is a pre-norm and a selective-scan mixer, nothing else: layer_output = input + mixer(norm(input)), so there is no self_attn and no mlp, and the identity is input + linear_attn.attention_output == layer_output. The mixer answers to linear_attn, the standard name of a recurrent mixer, and carries the SelectiveScan values; the block's norm answers to input_layernorm.

The kernels: with mamba_ssm installed the forward dispatches the scan and the decode step to its compiled CUDA kernels, which have no source to read inside and do not run on CPU; nnterp.route_kernels(model.family, "torch") before the first trace binds them to transformers' pure-torch functions. With residual_in_fp32 the block adds in float32, so layer_output is float32 whatever the load dtype; the model casts the stream to lm_head's dtype and returns float32 logits, and so does the family's project_on_vocab. The config's intermediate_size is the mixer's inner width (expand * hidden_size, the channels of the state); there are no attention heads, so the head sizes have nothing to read.