Skip to content

[Fix] cache: don't stamp a Mamba checkpoint on a shorter insert key - #39209

Closed
he-yufeng wants to merge 5 commits into
sgl-project:mainfrom
he-yufeng:fix/mamba-checkpoint-key-alignment
Closed

he-yufeng wants to merge 5 commits into
sgl-project:mainfrom
he-yufeng:fix/mamba-checkpoint-key-alignment

Conversation

@he-yufeng

@he-yufeng he-yufeng commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Fixes #38815. In a joint Full/SWA/Mamba cache, cache_finished_req (and the unfinished twin) truncates the insert key to the smallest component boundary (effective_cache_len = min(...) across component prepare hooks). An SWA branch at 96 leaves the insert leaf at 96, while MambaComponent.prepare_for_caching_req has already attached the Mamba state tracked at 192 to the insert params. Both commit implementations then stamped state192 onto key96, and the reporter's H200 repro shows the consequence: a warm-cache request hitting 96 resumes from the wrong state, with diverged logprobs in all three input groups.

Changes

The Mamba value now carries the seqlen it was produced at through InsertParams — Python side, the Rust binding, and the Rust in-flight InsertWalkState — and both commit sites skip the stamp when the inserted key's token length doesn't match it (atom length plus the bigram overlap for EAGLE keys):

  • python/sglang/srt/mem_cache/unified_cache/components/mamba_component.py: commit_insert_component_data returns early on misalignment; cleanup_after_caching_req treats a skipped value as not-inserted on both the finished and unfinished paths (int8 slot freed, ping-pong slot not kept).
  • rust/sglang-radix-tree/src/components/mamba.rs: same guard in the Rust component, so the Rust TreeCore deployment the reporter reproduced on is covered.
  • python/sglang/srt/mem_cache/rust_tree_core/adapter.py and rust/sglang-radix-tree/src/python_bindings.rs: mamba_value_seqlen threaded through the binding (defaulted None, so non-tracked inserts keep legacy behavior).

A truncated finish therefore simply doesn't checkpoint that state instead of caching a wrong one. This is strictly safer: the resume falls back to recomputation on the existing no-checkpoint path instead of resuming from a later state.

Test plan

  • New Rust unit test misaligned_mamba_value_is_not_stamped in src/tests/components/mamba.rs: key96 + seqlen192 leaves zero Mamba values in the tree; the same leaf then accepts the value once seqlen matches its position.
  • New Python unit test test/registered/unit/mem_cache/test_mamba_value_alignment.py (registered base-a-test-cpu): misaligned not stamped, aligned stamped, untracked value keeps legacy behavior.
  • Verified locally on this Mac: full Rust suite cargo test -p sglang-radix-tree 847 passed / 0 failed (torch 2.11 build venv, CPU); Python component tests 3/3; existing Python Mamba suites test_mamba_path_state_cap + test_mamba_donated_alloc_ratio 16 passed with no regressions.
  • Not run locally (no GPU): the KL-level suites (test_unified_radix_cache_kl_mamba, _kl_swa, _kl_hybrid_bitexact) — those exercise this path on real models and are the right CI coverage for it.

AI disclosure: this change was prepared with AI assistance (Kimi); the mechanism trace, both fixes, and every verification command above were run as stated.


CI States

Latest PR Test (Base): ❌ Run #42067560773
Latest PR Test (Extra): ❌ Run #42067561090
Latest PR Test (AMD ROCm 10): ❌ Run #42067561091

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (76e06fe). The unified cache area moved a lot since this branch (session_id threading, FULL pin helpers, read-only FULL prefix match), and 11 of 12 files overlapped, so a few notes on how the replay was checked:

  • Only one textual conflict: the InsertParamsBinding pyo3 signature. Resolved as the union (session_id = None and mamba_value_seqlen = None both kept, order matches the fn parameters).
  • Hunk audit of the replay against the pre-rebase diff: identical +/- counts on all 12 files, nothing silently dropped. Upstream's additions don't intersect the stamp path.
  • cargo test in rust/sglang-radix-tree: 868 passed, 0 failed (includes the alignment cases).
  • The Python regression test turned out to have been written against wrong module paths (components.mamba_component / components.tree_component) and had never actually run; fixed the imports in the third commit and it now executes for real. 3 passed on this branch. Against pre-fix main the untracked 96-key insert gets stamped with the 192-state (the bug from [Bug] SWA branching attaches a later Mamba checkpoint to an earlier prefix #38815 reproduces), while the tracked misaligned insert is now skipped and the aligned one still stamps.

Still needs the run-ci label from a maintainer for the full suite.

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Second ping, four weeks after the first. Re-verified on current main (9380920): the joint Full/SWA/Mamba insert still truncates the key to the minimum component boundary while MambaComponent.prepare_for_caching_req attaches the state tracked at the longer mamba_last_track_seqlen, so the tree can hold a Mamba checkpoint addressed by a key shorter than the sequence it describes (#38815). The fix spans the Python components and the Rust tree adapter. Could a maintainer add the run-ci label and take a look?

detain added a commit to detain/sglang that referenced this pull request Oct 15, 2026
…ert key (sgl-project#38815 correctness) [batch-apply-h 2026-10-15]

Carry the producing seqlen through InsertParams/mamba_value_seqlen in both
tree cores; commit_insert skips the stamp when the truncated leaf's token
length (atom + bigram overlap) mismatches; cleanup treats a skipped value as
not-inserted (int8 slot freed, ping-pong slot not kept). Net-diff squash of
PR commits f0ce2243f0+c176425910+f6a390f7d9 (1e825c0b15 empty retrigger);
applies clean onto drifted tree. Python sites land over our replayssm
write-pos cap (seqlen recorded post-cap = value's true position) and over
entry-169 int8/ping-pong cleanup branches.
detain added a commit to detain/sglang that referenced this pull request Oct 19, 2026
…refill cache updates before preparing the next batch

Wrong-output class (family of stack entry 196/sgl-project#39209). With
`extra_buffer`(+lazy) and overlap scheduling, `event_loop_overlap` can call
`get_next_batch_to_run()` — which captures `req_to_token` for the next batch —
BEFORE the previous prefill's radix insertion (still sitting in `result_queue`)
has replaced the request's private KV slots with canonical tree slots and freed
the duplicates. The first dependent decode/verify step then reads a prefix
mapping that no longer exists.

Fix (upstream): before preparing the next batch, ask
`_has_pending_mamba_cache_update()` whether the head of `result_queue` is an
extend batch with a tracked, unfinished, non-retracted, non-skip-insert
request; if so, `pop_and_process()` first and skip the overlap path for that
iteration (`disable_overlap_for_batch` forced False, the "process the last
batch" branch skipped since the queue was already drained).

Gate is deliberately conservative — returns False (behaviour byte-identical to
today) for DP/MLP-sync ranks (they need a rank-agreement decision the PR does
not make), for `tree_cache.disable`, and for caches without
`enable_mamba_extra_buffer`.

Applied cleanly on our tree (`git apply -3`, scheduler.py region at
event_loop_overlap; our prewarm/engine-init lines untouched). Brings upstream's
CPU test test/registered/unit/managers/test_mamba_prefill_cache_boundary.py
(5P/12sub, mocks the loop via an unbound `Scheduler.event_loop_overlap`).

NEEDS A GPU A/B: this adds a synchronisation point (an early
`pop_and_process()` + result drain) into the overlap hot path for hybrid
`extra_buffer` prefills, so throughput/TTFT of prod Qwen3.8-Flash-Next must be
measured after restart; rollback = revert this commit.

(cherry picked from commit 93ea0732ba88fd6fa3d5272495878dfcae274b71)
@he-yufeng
he-yufeng force-pushed the fix/mamba-checkpoint-key-alignment branch from 1e825c0 to 7e1a795 Compare October 21, 2026 16:07
@he-yufeng

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (8e3e298) and resolved the conflict in rust/sglang-radix-tree/src/components/mamba.rs by keeping main's commit_insert_component_data structure and re-adding the guard that skips stamping a Mamba checkpoint when the insert key covers fewer tokens than mamba_value_seqlen.

Verification on the pushed head (7e1a795eb5):

  • cargo check and cargo test for sglang-radix-tree against libtorch 2.11.0 (the version tch 0.24 pins): 932 passed, 0 failed, including the randomized Mamba-core invariant suites.
  • The Python regression test/registered/unit/mem_cache/test_mamba_value_alignment.py (real MambaComponent.commit against the test's minimal fake tree core): 3 passed on CPU.

@github-actions

This comment has been minimized.

A shared insert truncates the key to the smallest component boundary
(effective_cache_len = min of the component prepare hooks), so an SWA
branch at 96 leaves the leaf at 96 while the Mamba value was produced at
its own track seqlen of 192. Both commit sites then stamped state192
onto key96, and a later request resuming from 96 read the wrong state
(sgl-project#38815).

The value now carries the seqlen it was produced at through InsertParams
(Python, the Rust binding, and the Rust walk state), and both commit
implementations skip the stamp when the inserted key's token length
doesn't match it (atom length plus the bigram overlap). Cleanup treats
the skipped value as not-inserted: the int8 slot is freed and the
ping-pong slot isn't kept, so a truncated finish simply doesn't
checkpoint that state instead of caching a wrong one.

Fixes sgl-project#38815
@he-yufeng
he-yufeng force-pushed the fix/mamba-checkpoint-key-alignment branch from 7e1a795 to b013ace Compare October 22, 2026 03:23
@he-yufeng

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (8dc7f98) to clear the conflict from #45439 (the custom-tree-core refactor restructured python_bindings.rs). The binding field, signature, and both InsertParams construction sites are re-applied onto the refactored file, and the refactor's new insert_overlap_step_ construction now also forwards mamba_value_seqlen from the walk state, so the guard keeps working on the overlap path too.

Verified on the pushed head (b013ace): cargo test for sglang-radix-tree passes 943/943 against libtorch 2.11.0, and the Python regression test_mamba_value_alignment.py passes 3/3 on CPU.

@github-actions

This comment has been minimized.

@he-yufeng he-yufeng changed the title fix(cache): don't stamp a Mamba checkpoint on a shorter insert key [Fix] cache: don't stamp a Mamba checkpoint on a shorter insert key Oct 22, 2026
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
… (+test re-anchors)

Re-plants the fork-hunks patch (replant/...components__mamba.py.fork-hunks.patch)
onto the #46970x component rewrite. B3 marker consumed in
unified_cache/components/mamba.py.

Per-hunk state:
- entry 216 (prefix-lock release before the donation retry): ALREADY ABSORBED
  at the merge inside the old _alloc_mamba_slot; the replant keeps it verbatim
  while renaming to _try_alloc_mamba_slot -> Optional (test-verified shape).
- entry 198 (sgl-project#37612): match-path COW failure raises MambaCowAllocError
  (class definition survived the merge; the RAISER was the dropped half).
  CROSS-NOTE FOR B4: the prefill-admission CATCHER (the merge dropped it too;
  test_scheduler_hybrid_ssm_admission_retry.py in managers awaits it — B4 zone).
- entry 197 (sgl-project#37943): donation with a pinned pool SKIPS the boundary
  checkpoint + rate-limited capacity warning (_record_skipped_checkpoint;
  available-count via req_to_token_pool.mamba_allocator, the fork's accessor —
  the merge's storage abstraction offers no equivalent that survives the
  duck-typed harnesses).
- entry 196 (sgl-project#39209): _mamba_value_misaligned + mamba_value_seqlen stamped at
  BOTH prepare sites (the InsertParams field survived the merge unused);
  commit refuses to stamp, cleanup frees the misaligned value.
- entry 30 (sgl-project#39830 fencing, the L2 half): _token_depth/_record_host_ckpt_pos/
  _host_ckpt_position_ok/_poison_stale_host_ckpt + prepare_load_back
  PrepareLoadBackResult(rejected=True) (the URC unwind rode B3-3) + the two
  record sites (BACKUP_HOST attach, LOAD_BACK attach). Host-pool surface
  (ckpt_pos_buffer/record_ckpt_pos/get_ckpt_pos in pool_host/mamba.py)
  verified PRESENT (survived) — not duplicated. _poison call adapted to the
  widened _evict_component_and_detach_lru signature (cache_actions positional).
- entry 90: alloc_prefetch_staging shortfall reclaim (MAMBA half; the SWA half
  rode B3-4; the host-group half rode B3-4).
- class-level tallies (_ckpt_pos_rejects/_skipped_checkpoint_count) follow the
  established __new__-harness convention.

Test re-anchors (B2 owns this file's markers; these are the fork-case
mechanical repairs its re-home left needing after the component landed):
- test_mamba_donated_alloc_ratio.py: _RatioCache stub gained the
  req_to_token_pool the storage now routes donate through (+ the lazy-boundary
  batch stub carries token_to_kv_pool_allocator, schedule_batch.py:3661).
- test_hicache_mamba_ckpt_pos_fence.py: the evict_and_detach mirror updated to
  the post-#4697x positional cache_actions.

ACTUALS (damage -> after):
  test_mamba_donated_alloc_ratio   13P/8F/10sub -> ** 17P/0F/14sub ** (295 pin 16P/14sub: AT OR ABOVE)
  test_hicache_mamba_ckpt_pos_fence 12P/3F -> ** 15P/0F ** (entry-30 pin "fence 15P" EXACT)
  test_mamba_value_alignment        2P/1F -> 3P/0F (entry-196 guard)
  test_mamba_path_state_cap         5P/5S unmoved (honest CUDA skips; entry 199 half rides the URC already landed)
  test_hicache_mamba_sizing          30P/0F/17sub (unmoved, B3-4 verified)
Lint: ruff format+F821/E9/F401 clean; py_compile+import OK. No GPU; no push.
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
…18 (bindings + mamba guard + test module) — CPU-verified-clean; compilation = ENV DEBT

B3 markers consumed: python_bindings.rs, components/mamba.rs,
tests/unified_tree_core.rs. All three replant patches applied in full:

- python_bindings.rs (114/196/199):
  * InsertParamsBinding gains mamba_value_seqlen (struct field, pyo3
    signature, new(), Ok()) and BOTH insert paths forward it to the core
    (whose InsertParams already carries the field). ** ADAPTER-CONTRACT
    REPAIR: rust_tree_core/adapter.py:837 ALREADY passes
    mamba_value_seqlen=params.mamba_value_seqlen -- at the merged tip that
    kwarg hit an unexpected-argument error on EVERY mamba insert through the
    rust core. The binding half of the fork delta was load-bearing. **
  * parent_node_id exposed on the binding (both the tree_core_methods macro
    and the catch_native_panic wrapper); the cfg(inspection)
    inspect_get_parent_node_id variants DELETED — the core renamed the
    method (unified_tree_core.rs:4283 parent_node_id) and adapter.py:1083
    already calls self._binding.parent_node_id (also a merged-tip break,
    same repair family; URC's B3-3 _ancestors_first walks ride it too).
- components/mamba.rs (196): the sgl-project#39209 misalignment guard in
  commit_insert_component_data — key.atom_len() + K::IS_BIGRAM vs
  mamba_value_seqlen, early-return without stamping (the rust twin of the
  Python component's guard planted in B3-5).
- tests/unified_tree_core.rs (114/196/199/218): the write-back
  defer-test rename hunk was VERIFIED ALREADY PRESENT (the merged file
  carries the post-patch form: no execute_backup_kv_for_test helper,
  write_back_defers_swa_window_backup_until_eviction with the empty-backups
  asserts — dedupe, not duplicated); planted the missing halves: the two
  tc.inspect_get_parent_node_id -> tc.parent_node_id renames (stale refs to
  the DELETED core method = guaranteed compile error as merged) and
  mamba_value_seqlen: None in all THREE InsertParams literals.

CPU-CHECKABLE STATE (per dispatch: no GPU, cargo env broken, do not chase):
  rustfmt --edition 2024 --check: exit 0 on all three files (after trailing
  -newline normalization) -> syntax/format clean.
  grep-consistency: zero remaining inspect_get_parent_node_id refs in-tree
  (src+tests), every InsertParams literal carries the new field, adapter's
  two call sites (parent_node_id, mamba_value_seqlen) now match the binding.
  cargo check: FAILS IN THE DOCUMENTED ENV CLASS — torch-sys build-script
  "Cannot find a libtorch install"; with LIBTORCH pointed at the venv torch
  2.14.1 the tch 0.24.0 C++ shim fails compiling torch_api_generated.cpp
  (tch-vs-torch version gap at this seat, NOT crate code). Entry-310's
  verdict stands: UNMEASURABLE from this seat, pre-merge byte-identical;
  the 932P/0F pin CARRIES UNVERIFIED -> recorded as the batch's rust debt
  (session 3 / any seat with a matching libtorch must run cargo test -p
  sglang-radix-tree; the python-binding contract repair is meanwhile
  importable-provable once the env exists).
No GPU executed; no push.
…t-key-alignment

# Conflicts:
#	python/sglang/srt/mem_cache/rust_tree_core/adapter.py
#	python/sglang/srt/mem_cache/unified_cache/components/mamba.py
#	rust/sglang-radix-tree/src/python_bindings.rs
#	rust/sglang-radix-tree/src/tests/components/base.rs
#	rust/sglang-radix-tree/src/tests/components/full.rs
#	rust/sglang-radix-tree/src/tests/components/mamba.rs
#	rust/sglang-radix-tree/src/tests/components/swa.rs
#	rust/sglang-radix-tree/src/tests/unified_tree_core.rs
#	rust/sglang-radix-tree/src/unified_tree_core.rs
@github-actions

This comment has been minimized.

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Superseded by #37584 (bd45cd50ca9). The SWA prepare hook now returns None when Mamba is enabled, leaving the insertion length to the recurrent checkpoint instead of shortening a checkpoint at 192 to the SWA branch at 96.

I checked the current finished and unfinished paths, including the EAGLE overlap, against the historical prepare method. Non-Mamba SWA branching still chooses its own boundary. Closing in favor of the landed producer-side fix rather than adding a second checkpoint-length contract to both tree cores.

@he-yufeng he-yufeng closed this Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] SWA branching attaches a later Mamba checkpoint to an earlier prefix

2 participants