Mamba (Mamba-1): forward of several tokens over a primed cache restarts the selective scan from zero and returns wrong logits
System Info
transformers 5.20.2, torch 2.14.1+cpu, float32, CPU (reference PyTorch paths: mamba_ssm and causal_conv1d not installed). Code reviewed against main on 31 Oct 2026; the dispatch below is unchanged there.
Who can help?
@vasqu (reviewed the Mamba-2 equivalent in #46084 / #46741)
Reproduction
A multi-token forward over a primed Mamba-1 cache silently restarts the selective scan from a zero state.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "state-spaces/mamba-130m-hf"
tok = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32).eval()
ids = tok("The quick brown fox jumps over the lazy dog because it wanted to see", return_tensors="pt").input_ids
n = ids.shape[1]; h = n // 2
with torch.no_grad():
full = model(ids, use_cache=True).logits[0, h:]
out = model(ids[:, :h], use_cache=True)
chunk = model(ids[:, h:], cache_params=out.cache_params, use_cache=True).logits[0]
out = model(ids[:, :h], use_cache=True); cache, steps = out.cache_params, []
for t in range(h, n):
o = model(ids[:, t:t + 1], cache_params=cache, use_cache=True)
cache = o.cache_params; steps.append(o.logits[0, -1])
step = torch.stack(steps)
print((full - step).abs().max().item()) # 2.6e-04 token-by-token over the cache: correct
print((full - chunk).abs().max().item()) # 115.9 chunk over the cache: wrong
print((full.argmax(-1) == chunk.argmax(-1)).float().mean().item()) # 0.714
Output (14 tokens, split at 7):
max |full - token-by-token| = 0.000263
max |full - chunked| = 115.897
argmax agree (chunked) = 0.714
Cause
In MambaMixer the recurrent path is taken only when seq_len == 1:
if recurrent_state is not None and seq_len == 1:
scan_output = mamba_selective_state_update(recurrent_state, ...)
else:
scan_result = mamba_selective_scan(..., return_last_state=output_final_state, ...)
The conv path for seq_len > 1 correctly prepends the cached inputs (update_conv_state), but mamba_selective_scan always starts from zeros (# "Initial hidden state" is not supported by the kernel path, so use the same zero initialization as the kernel) and then overwrites the cached recurrent state with the result. So any chunked prefill, or any multi-turn use that passes a kept cache together with several new ids, computes the new chunk as if it were the start of the sequence, with no error or warning.
This is the Mamba-1 counterpart of #46032 (Mamba-2, fixed by #46084 and #46741). #46741 notes that it leaves the Mamba-1 path out. #31909 reported a related symptom for Mamba-1 and was closed as "not supported"; today the call is accepted and returns wrong logits.
Expected behavior
Either seed the full-sequence scan from the cached recurrent_state (the reference loop only needs ssm_state initialised from the cache instead of zeros; the kernel path can take the same approach as #46084, or fall back to the reference loop when an initial state is present), or raise when cache_params holds a previous state and seq_len > 1.
Found by a conformance suite for stateful model execution (prefill, chunked and token-by-token decode must agree); a 20-line change seeding the reference scan from the cached state brings chunked logits back within float32 rounding of the single prefill.
Reproduced on main...chunked differs by ~116 vs 2e-4 for token-by-token on mamba-130m, same as the issue
I plan to seed the scan from the cached state, the way #46084 did for mamba 2, plus a regression test. Also, the same code is in falcon_mamba, jamba and zamba and I plan to cover those as well
@vasqu / @ArthurZucker can I take this one?
@JohnnyTeutonic happy to leave it to you if you were planning to send your fix, just let me know
Thanks for reproducing it, please go ahead. Good catch on falcon_mamba, jamba and zamba carrying the same code. Happy to test the PR against the chunked, truncate and snapshot traces that caught it.
In general not opposed to fixing BUT
- The current PR is gonna be super slow no? It is a loop going over every time step, so 1 by 1
- Mamba1 is in general a bit limited in providing initial states iirc
- I wouldnt see this as high prio for now 🤔
@vasqu
- Agreed, I just ran some code to benchmark things. The per token loop did add significant overhead. Tbh I didn't expect it to be this slow (worst case was 3x without kernels. With kernels it went up to 109x for a 1024-token chunk on mamba-130m on a L4). The alternative that has already been proposed in the PR should work much better as it does things parallelly.
- Yup, that was mainly the reason I didn't go ahead with the seeding logic. The kernel has no input for a starting state
- Understandable and happy to wait or re-work it
But please do let me know if you'd like me try the alternative approach and update the PR.
Unsure about the current direction, if anyone wants to we could update the docs for now to make this notable to users. It's kind of bound to the kernel implementation so unless we start fixing on that side it's gonna be hard ig
This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.
Please note that issues that do not follow the contributing guidelines are likely to be ignored.
I tested the zero-state scan plus cached-state correction proposed in #50250, using a local Mamba-1 prototype based on 5a94ac9. This work used AI assistance.
For each token, the correction is exp(A * cumsum(softplus(dt + dt_bias))) * initial_state. Project it through that token’s C and apply the SiLU gate to correct the output, then add the final state correction to the scan’s returned state. I compute the correction in 64-token blocks to bound the temporary batch × channels × tokens × state tensor.
On a randomly initialized two-layer Mamba (hidden size 16, state size 8, batch size 2, 193 tokens), 16 CPU cases passed across two seeds, FP32/BF16, and four chunk schedules. They check logits, final recurrent state, and crop(-1)/replay with two intermediate states recorded. Maximum FP32 logit error versus full prefill was 9.54e-7. BF16 reached 0.03125 under atol/rtol=0.04 for logits and 0.02 for states. Unchanged main fails the shorter FP32 chunk test with a 0.00220 logit error, while token-by-token execution agrees within 4.77e-7.
This is preliminary numerical evidence for the proposed alternative. I have only exercised the reference CPU path for Mamba-1. GPU kernels, realistic performance, and FalconMamba/Jamba/Zamba remain unvalidated.
Would this prototype and its regression cases be useful for continuing #50250? I can share them with the existing author if the maintainers want to pursue that direction.