Skip to content

[Fix] mamba: Give a lazy boundary snapshot its own slot instead of overwriting the keep slot - #48328

Merged
hnyls2002 merged 19 commits into
mainfrom
lsyin/sched-pr21
Nov 5, 2026
Merged

hnyls2002 merged 19 commits into
mainfrom
lsyin/sched-pr21

Conversation

@hnyls2002

@hnyls2002 hnyls2002 commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

With the lazy Mamba extra buffer, a request at a tracking boundary takes a second state slot for the new snapshot. When no slot was free, the forward wrote the new state into the keep slot, the slot that holds the last checkpoint and may be handed to the radix tree at finish. One slot then meant both "the checkpoint at mamba_last_track_seqlen" and "this step's write destination". The scheduler covered this by dropping the checkpoint at launch (mamba_last_track_seqlen = None) and, at finish, predicting whether an in-flight step would still write the keep slot, with a mixed-forward exception on top.

Now the keep slot is never a write destination:

  • The boundaries of a batch get their second slots through alloc_tracking_slots (mem_cache/allocation.py), which evicts the shortfall from the tree once, as ensure_mamba_capacity does for request slots (locked nodes are never evicted), then allocates.
  • Only if that also fails does the boundary skip its snapshot: decode clears the row's track-mask bit, speculative verify plans position -1 (the scatter skips it and the result path does not promote it), and the keep slot keeps its checkpoint.
  • A verify step whose row has no track destination (-1, from a skip or from a freed row) commits no snapshot even when it crosses a boundary, so no backend sees a crossing with nowhere to write. Before, the Ascend hybrid linear attention verify update wrote the pool's last row for such a row.
  • Removed: the launch-time mamba_last_track_seqlen = None, the finish-time predictions of an in-flight write to the keep slot (decode and verify), the mamba_untracked_decode_batch_idx field that fed one of them, and the failed-prealloc branch of the mixed-forward undo.
  • Kept: the verify finish check for a keep slot this step's scatter wrote (a just-promoted keep written by the next overlapped crossing), which is known exactly when the result is processed.

Measurements

Qwen3-Next-80B-A3B-Instruct, TP2 on GB300, --mamba-radix-cache-strategy extra_buffer_lazy --page-size 64, multi-turn generated-shared-prefix benchmark (2048 requests, 4 turns, each turn resends the earlier answers, 64 concurrent). "Skip only" is this PR without the eviction. The eviction arm was measured with one eviction per failing row; the PR now evicts the batch shortfall at once, which frees the same number of states.

config arm turn >= 2 hit rate (%) uncached tokens per turn >= 2 (tokens) output throughput (tok/s) boundary slot failures (%)
--max-mamba-cache-size 512 main 84.8 / 84.9 386 / 382 6597 / 6791 88 / 91
skip only 74.2 / 74.2 653 / 653 6735 / 6667 90 / 90
this PR 84.3 / 84.9 397 / 381 6726 / 6819 5 / 5
same + NEXTN (3 steps, 4 draft tokens) main 83.7 413 3342 96
skip only 74.2 653 3297 96
this PR 84.4 396 3401 28
default Mamba cache size main 84.8 385 6775 46
  • Once the tree fills the state pool, most boundaries find no free slot (46% even at the default pool size), so the fallback path is the common one under lazy tracking. Skipping alone loses about 10 points of turn >= 2 hit rate; with the eviction the hit rate and throughput match main.
  • Failures for this PR count attempts that still failed after the eviction. Repeat noise is about 0.1-0.4 points of hit rate and 100-200 tok/s.

Test plan

  • New unit tests: a failed decode prealloc clears the mask bit and keeps the checkpoint length; a failed verify plan gives -1 and no promote; a -1 position maps to track index -1; a crossing row with no destination commits no snapshot; the eviction frees a slot before the boundary would skip (decode and verify).
  • The unit tests of the changed sites pass locally.
  • To run on GPU: test_mamba_cache_kl.py, the lazy allocation-failure classes in test_qwen3_next_models_extra.py, and TestQwen3NextMTPLazyV2 in test_qwen3_next_models_mtp.py.

CI States

Latest PR Test (Base): 🚫 Run #41939053155
Latest PR Test (Extra): ❌ Run #41939053077
Latest PR Test (AMD ROCm 10): 🚫 Run #41939052992

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

@github-actions github-actions Bot added hicache Hierarchical Caching for SGLang unified-radix-cache labels Nov 4, 2026
@hnyls2002 hnyls2002 changed the title [Fix] mamba: Skip a lazy boundary snapshot instead of overwriting the keep slot [Fix] mamba: Give a lazy boundary snapshot its own slot instead of overwriting the keep slot Nov 4, 2026
@hnyls2002

hnyls2002 commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

/rerun-test test_qwen3_next_models_extra.py test_qwen3_next_models_mtp.py test_qwen3_next_models.py test_mamba_cache_kl.py test_unified_radix_cache_kl_hybrid_bitexact.py registered/e2e/speculative/test_dflash_dp_attention.py
(4 tries)

@hnyls2002

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

🚀 1-gpu-h100 (2 tests): ❌ View workflow run

cd test/ && python3 registered/radix_cache/test_mamba_cache_kl.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_hybrid_bitexact.py

🚀 4-gpu-h100 (4 tests): ❌ View workflow run

cd test/ && python3 registered/e2e/models/test_qwen3_next_models_extra.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models_mtp.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models.py
cd test/ && python3 registered/e2e/speculative/test_dflash_dp_attention.py

🚀 ubuntu-latest (7 tests): ✅ View workflow run

cd test/ && python3 registered/unit/managers/test_batch_result_processor_mamba_boundary.py
cd test/ && python3 registered/unit/managers/test_mix_with_running_mamba_track.py
cd test/ && python3 registered/unit/managers/test_req_kv_lengths.py
cd test/ && python3 registered/unit/spec/test_ngram_mamba_verify_update.py
cd test/ && python3 registered/unit/managers/test_batch_result_processor_spec_grammar.py
cd test/ && python3 registered/unit/mem_cache/test_mamba_capacity.py
cd test/ && python3 registered/unit/mem_cache/test_dsv4_c4_state_lifecycle.py

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Nov 4, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

🚀 4-gpu-h100 (4 tests): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_qwen3_next_models_extra.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models_mtp.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models.py
cd test/ && python3 registered/e2e/speculative/test_dflash_dp_attention.py

🚀 1-gpu-h100 (2 tests): ❌ View workflow run

cd test/ && python3 registered/radix_cache/test_mamba_cache_kl.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_hybrid_bitexact.py

)


def mask_rows_without_track_slot(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DSpark's verify commit (dspark_worker_v2.py:1538) still passes mamba_steps_to_track to update_mamba_state_after_mtp_verify without this mask. CUDA skips a -1 slot in the kernel, but the Ascend backend does conv_states[:, mamba_track_indices] = ... and writes the last row. Apply it there too?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good catch. Instead of masking each writer, a row without a track slot now points at the reserved slot 0 (the padding slot nothing reads), so DSpark, Inkling and the Ascend path need no -1 handling; the mask helper is gone (8ccb346).

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

🚀 4-gpu-h100 (4 tests): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_qwen3_next_models_extra.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models_mtp.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models.py
cd test/ && python3 registered/e2e/speculative/test_dflash_dp_attention.py

🚀 1-gpu-h100 (2 tests): ❌ View workflow run

cd test/ && python3 registered/radix_cache/test_mamba_cache_kl.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_hybrid_bitexact.py

# Conflicts:
#	python/sglang/srt/managers/scheduler_components/batch_result_processor.py
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

🚀 4-gpu-h100 (4 tests): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_qwen3_next_models_extra.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models_mtp.py
cd test/ && python3 registered/e2e/models/test_qwen3_next_models.py
cd test/ && python3 registered/e2e/speculative/test_dflash_dp_attention.py

🚀 1-gpu-h100 (2 tests): ❌ View workflow run

cd test/ && python3 registered/radix_cache/test_mamba_cache_kl.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_hybrid_bitexact.py

@hnyls2002
hnyls2002 merged commit 02db123 into main Nov 5, 2026
40 of 44 checks passed
@hnyls2002
hnyls2002 deleted the lsyin/sched-pr21 branch November 5, 2026 00:08
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…edule_batch grammar-mixed -- 15/39 markers consumed

- grammar_needs_sync RE-PLANTED (entry-122 mixed-tail arm) folded INTO
  upstream's in-window is_none gate (both live inside the predicate now; the
  single scheduler caller is should_process_last_batch_early, C1).
- sgl-project#43484/entry-266 CLASSIC ledger RE-PLANTED onto the renamed helpers:
  _update_prefill_budget gains state_slots_charge (slot-unit debit, the
  unified chain stays byte-for-byte factor-1 on the budget), threaded at all
  5 call sites + _commit_prefill_admission; add_one_req's gate regains the
  required_state_slots > rem_mamba_slots OR-arm (266(c) isinstance/MagicMock
  discipline untouched -- seed block was already consistent).
- sgl-project#46643 fix(2/3) consistency VERIFIED against b3's fix(1) re-plant in
  prefill_budget.available_chunk_tokens (fork cap/defer form intact, zero
  edits; the guards-every-policy comment restored where the fork had it).
- entry-270 gate RE-PLANTED: select-time _mamba_fork_split_len cut (chunk_
  tokens_limit & not has_chunked_req & new_chunked_req is None) in
  _select_prefill_admission, the continuation-path fork split in
  _add_chunked_req, the leaves-budget-behind OTHER return after commit, and
  the truncation_align_size kwarg chain add_chunked_req -> _add_chunked_req
  (entry-177; the scheduler call site had already survived -- TypeError
  class from b3 handoff).
- entry-269/177 composition RE-PLANTED in add_one_req_ignore_eos chunked
  branch: floor -> page-align -> cache-alignment LCM, empty-cut guard.
- _state_slot_reserve_for_req -> upstream _state_slots_for_req rename ADOPTED
  (charge == reserve semantics preserved through the budget's own
  slot*cost conversion; helper note 'renamed upstream' resolved).

Test seams re-pinned (no weakening): mixed_mamba_track -> sgl-project#48328 reserved-
slot-0 untracked padding + GDNAttnBackend.state_pool view binding; prefill_
adder host-hit-select call -> window_host_hit_lengths rename.

Targeted: 98P/0F/118sub (prefill_adder+grammar_sync+mixed_track+boundary).
Gates: ruff repo ruleset + format; registration trio rc=0 (unchanged set).
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…arkers consumed; both named classes dead

- brp sgl-project#46272 id-set RE-PLANTED at the two sites the take-upstream reverted to
  O(B) req-in-list scans: the finish-side _prepare_kv_cache_release predicate
  and the checkpoint elif now consume the per-row is_decoding_req id-set (the
  sgl-project#49253 deferred kv_ops shape kept -- fork predicate onto upstream structure;
  entry-265 interlock re-verified: mamba_untracked_decode_batch_idx + its brp
  arm were DELETED upstream by sgl-project#48328 (02db123) together with the
  next==last hazard they guarded -> ADOPTED, mixed_track tests re-pinned).
- detokenizer: ADOPTED sgl-project#47338 (add6f6d) state-machine move; the fork's
  sent_offset anti-retreat max() clamp RE-PLANTED at its new home
  (DetokenizeState.step) -- test_detokenizer_stream_offsets.py 6F -> 7P/3sub,
  driving _update_detokenize_states + the header-seeded state table.
- io_struct: ADOPTED upstream's env-bounded validate_n gate (sgl-project#44047
  b2616ca subsumes the entry-157 static-128 loop; both validator helpers
  stay unit-tested in test_sampling_params) -- the dossier's
  'entry-265 brp track field' label on region@551 is a misattribution
  (the field never lived in io_struct; verified by fork-delta audit).
  4 fork-era normalization tests re-pinned to the new contract
  (above-max bound, null-n, beam message, per-element bound).
- tokenizer_manager: DEDUPE candidate resolved as the union -- upstream's
  return_logprob gate (the mask-validation tests prove the disabled-row
  design) + the fork's shared validate_top_logprobs_num delegation; the
  fork-era io_struct top_logprobs test re-pinned to return_logprob=True.
- brp mixed_token_ids_logprob ctor seam: enable_overlap fields retired by
  sgl-project#49019 (d1d317c); harness follows the merged class (still_in_batch,
  kv_weight_version_tracker, request_retirer, forward_iter,
  still_in_batch_rows, real LogprobResultProcessor). 3P.
- test_sampling_params test_beam_n_below_one_raises message regex re-pinned
  (validate_n now fires before the beam branch); its sibling
  test_n_bounds vs test_n_above_max_raises double-gate tension in
  sampling_params.verify is PRE-EXISTING cascade damage (union of both
  gates), outside every battery dir -- handed to B6 (env registration).

Targeted: 158P + 128sub (io_struct+mask+rid+brp+detok) + sampling sweep.
Gates: ruff repo ruleset + format; registration trio rc=0.
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…uards + SPLIT retirement -- markers 2-8/17 consumed (6)

VARLEN-PREFILL DUAL IMPL (markers qwen4_short_conv:608, qwen4_exp:697/698/1643):
The take-upstream resolution kept upstream's simpler packed-varlen family and
dropped the fork's residual fold, but the fork's residual PLUMBING survived:
_short_conv's caller passes residual=gated_value and every other arm folds it.
As merged, the fused EXTEND/MIXED arm returned F.silu(conv_output) and SILENTLY
DROPPED THE RESIDUAL -- a wrong-output class. Re-planted the fork's kernel
family VERBATIM (residual_ptr + HAS_RESIDUAL fold with the two low-precision
materialization points, enable_fp_fusion=False, fp16 in the gate, the residual
guard in can_fuse, the predicate + call-site residual args) and KEPT upstream's
in-window improvement (token = program_id(0).to(tl.int64)); post-plant diff vs
the fork parent shows that tweak as the only delta.

SPLIT_PREFILL retired, not re-planted (marker names it the DUAL's other half):
upstream sgl-project#43898 ("scheduler: Remove PD multiplexing") deleted the enum member
and every producer in-window; b4 already consumed the schedule_batch producer.
The two surviving fork-kept reads (qwen4_exp :425/:759) referenced a member
that no longer exists -> AttributeError at the first batch build (dead-on-
arrival). Removed the two dead names; the mode has no way to be produced.

PREFETCH GUARDS (marker qwen4_exp:1970, the host-staging DOA class): the take-
upstream body called lookup_ids.record_stream() unconditionally and gathered
via gather() -- but the host-staging route sets lookup_ids=None (AttributeError)
and its table RAISES RuntimeError("use gather_staged") on bare gather(). Re-
planted the fork's None guard, the eager-buffer record_stream under
not _is_capturing(), and the gather_staged arm, carried on the merged
get_device_module() idiom.

B3 HANDOFF CONSUMED (marker qwen4_exp_ple_table:413 + :407 + :27): b3 fixed the
rename mechanically; the region's final state is UPSTREAM'S OWN refinement of
the fork's own upstreamed helper (sgl-project#48689: device_reads_pageable_memory +
cudaDevAttrPageableMemoryAccess=88, widening the fail-loud check to HMM devices
-- our discrete Blackwells). Adopted upstream whole; the fail-loud raises on
unreadable/unsupported devices STAND (documented here, not tidied). The memo
dict is present (upstream's own lines). :27: contested docstring resolved to
upstream's fuller text (behavior-neutral).

REGISTRATION GAP FOUND: sgl-project#48689's check_file_backend_supported reads
envs.SGLANG_QWEN4_PLE_FILE_SKIP_DEVICE_CHECK but the merge lost the environ.py
registration (upstream has it at environ.py:313; no zone marker covers it) --
the file backend died AttributeError on EVERY boot. Restored next to its
siblings.

Test seam (entry-313 B5-2(iii) item, test-only): packed_short_conv stubs
get_attn_backend().linear_attn_backend.state_tracking_indices for upstream's
sgl-project#48328-era _ple_track_targets retarget (eager physical == batch field, the
test's own domain); file 2P/1S green.

Remaining named spec/models classes ATTRIBUTED, not weakened: the 4 ngram
get_cuda_graph_max_batch_size mock-target subFs (utils.common -> layers.
dp_attention relocation) and the ple_staging/replayssm stub gaps for the
#4800x runner_ids / supports_shared_read_events backend attributes are TEST
RE-HOME items of the entry-314 B2 lineage -- labeled for the b2 brief.

Spec dir after C1+C2: **405P/5F/27S/258sub** (was 396P/20F at b4 HEAD; C1
killed the 15-F rope TypeError class, none of these 5 are b5-lineage).

Gates: ruff repo ruleset + format rc=0 on the 5 touched files; py_compile;
registration trio + check_opt_in_ci_tiers rc=0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hicache Hierarchical Caching for SGLang run-ci CI: run the baseline test suite on this PR unified-radix-cache

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants