Skip to content

[Fix] HiCache: carry registered Mamba slot side states (Qwen4-Exp PLE) through the host tier - #39862

Merged
ispobock merged 7 commits into
sgl-project:mainfrom
JarJarBeatyourattitude:hicache-mamba-slot-side-states
Oct 4, 2026
Merged

ispobock merged 7 commits into
sgl-project:mainfrom
JarJarBeatyourattitude:hicache-mamba-slot-side-states

Conversation

@JarJarBeatyourattitude

@JarJarBeatyourattitude JarJarBeatyourattitude commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

MambaPool.register_slot_state attaches state that lives in the same physical checkpoint slot as conv/temporal but is neither per-layer nor a field of mamba_cache. Qwen4-Exp registers two of them (python/sglang/srt/mem_cache/memory_pool.py, _init_mamba_pool): the PLE short-conv window [num_slots, 10240, 9] bf16 and the PLE N-gram token history [num_slots, 2] int64.

Every other mover of a slot already carries them:

mover carries side state
MambaPool.copy_from (device CoW) sibling.copy_slots(...)
MambaPool.clear_slots (fresh slot) sibling.reset_slots(...)
MambaPool.get_cpu_copy / load_cpu_copy sibling.get_cpu_slots(...) / load_cpu_slots(...)
MambaPool._iter_transfer_state_entries (RDMA / PD) sibling.iter_transfer_state_entries()
MambaPoolHost (HiCache L2/L3) no

MambaPoolHost reaches into device_pool.mamba_cache.conv and .temporal directly, so a checkpoint written to the host tier loses those rows. Nothing zeroes them on the way back either: the load-back path allocates its destination slot in MambaComponent.prepare_load_back, which sets req.kv.mamba_pool_idx directly instead of going through HybridReqToTokenPool.alloc_mamba, so mamba_needs_clear stays False. A slot restored from the host tier therefore keeps the previous occupant's PLE state, and _prepare_ple_batch prepends that other request's token history to the batch.

Measurement

Qwen4-Exp (Qwen3.8-Flash-Next, 36 GDN + 12 full-attention layers) on 1x RTX PRO 6000, sglang 2929a399 + a LoRA-enablement delta only (nothing in mem_cache/), served with:

--enable-hierarchical-cache --hicache-size 96 --hicache-write-policy write_through \
--hicache-mem-layout page_first --hicache-io-backend direct \
--max-mamba-cache-size 48 --mamba-radix-cache-strategy extra_buffer --page-size 64

Every component of a Mamba checkpoint was fingerprinted on both legs of the host round trip. Four restores:

component restored correctly, before after
temporal (GDN SSM state) 4 / 4 4 / 4
conv0 (GDN conv state) 4 / 4 4 / 4
ShortConvPool.ple_short_conv 0 / 4 4 / 4
NGramPool.ple_ngram 0 / 4 4 / 4

Verbatim from the trace of one restore, before the change:

backup   from device slot 19 : ngram = [11, 321]
before   destination slot 29 : ngram = [310, 279]     <- the previous occupant
after    destination slot 29 : ngram = [310, 279]     <- unchanged by the restore
                               temporal, conv0 : exactly the backup's values

Cost

184,336 bytes per checkpoint against 58.8 MB of conv+SSM state, i.e. 0.3%. At --hicache-size 96 the host pool goes from 945 checkpoints to 942 (size_per_token 58,834,944 -> 59,019,280, confirmed on the running serve).

What is in the change

  • pool_host/mamba.py: collect the registered entries at init; one pinned host buffer per entry, with its own dtype and its own slot axis; both transfer legs; the L3 whole-page payload; host capacity accounting.
  • pool_host/mamba.py: refuse the zero-copy storage metadata paths (get_page_buffer_meta, is_stride_page_aligned) when side states are present, rather than silently omitting them; reject a page written by an older build with a clear error instead of failing inside a reshape half-way through a restore; and handle one flat page now holding components of different element sizes (an int64 row can start at a byte offset its own dtype cannot be viewed at).
  • memory_pool.py: get_ngram_context is read once per forward before the decoder-layer loop, so unlike short_conv_layer_cache it has no per-layer barrier of its own. Since the host tier now restores side state on the first Mamba layer's transfer, it waits for that layer.

A model that registers no slot side states takes an unchanged path: slot_state_entries is empty, no buffer is allocated, get_size_per_token is unchanged and both legs are a no-op (covered by a test).

Test

test/registered/unit/mem_cache/test_hicache_mamba_slot_side_states.py, CPU, 5 cases:

python -m unittest test.registered.unit.mem_cache.test_hicache_mamba_slot_side_states -v
  • the round trip through the real backup_from_device_all_layer / load_to_device_per_layer call sites (the CUDA conv/temporal kernels are stubbed; the side-state legs run for real),
  • the L3 page carries the rows and restores them,
  • get_size_per_token accounts for them,
  • a short page is refused rather than half-applied,
  • a model with no side state is unaffected.

What this does NOT fix

This is not a fix for #39830. On the same build, with this change applied and verified live, a host-restored prefix still produces wrong output: 0/10 usable answers against 10/10 cold and 10/10 device-hit on the same prompts in the same process. A watchword planted at token ~0 of the prompt is recalled 3/3 cold and 3/3 on a device hit and 0/3 out of the host tier, while 48 of 48 sampled KV rows come back byte-identical to their backup — so the restored bytes are right and the model still cannot read the prefix it was given. That is a separate defect; the diagnosis so far is in #39830.


CI States

Latest PR Test (Base): ⏳ Run #37139559257
Latest PR Test (Extra): ✅ Run #37139559111
Latest PR Test (AMD ROCm 10): ❌ Run #37139559347

…st tier

`MambaPool.register_slot_state` attaches state that lives in the same physical
checkpoint slot as conv/temporal but is neither per-layer nor a field of
`mamba_cache`. Qwen4-Exp registers two of them: the PLE short-conv window
(`[num_slots, 10240, 9]` bf16) and the PLE N-gram token history
(`[num_slots, 2]` int64).

Every other mover of a slot already carries them:

    MambaPool.copy_from            -> sibling.copy_slots(...)    (device CoW)
    MambaPool.clear_slots          -> sibling.reset_slots(...)   (fresh slot)
    MambaPool.get_cpu_copy         -> sibling.get_cpu_slots(...) (CPU offload)
    MambaPool.load_cpu_copy        -> sibling.load_cpu_slots(...)
    MambaPool._iter_transfer_state_entries -> sibling.iter_...   (RDMA / PD)

`MambaPoolHost` did not. It reaches into `device_pool.mamba_cache.conv` and
`.temporal` directly, so a checkpoint written to the host tier lost those rows,
and a slot restored from host kept whatever the PREVIOUS OCCUPANT of that slot
left in them. Nothing zeroes them either: the load-back path allocates its
destination slot in `MambaComponent.prepare_load_back`, which sets
`req.kv.mamba_pool_idx` directly instead of going through
`HybridReqToTokenPool.alloc_mamba`, so `mamba_needs_clear` stays False.

Measured on a Qwen4-Exp (`Qwen3.8-Flash-Next`) serve with
`--enable-hierarchical-cache --hicache-size 96 --hicache-write-policy
write_through --hicache-mem-layout page_first --hicache-io-backend direct`,
by fingerprinting every component of a Mamba checkpoint on both legs of the
host round trip. Four restores, before this change:

    component                    restored correctly   wrong
    temporal (GDN SSM state)              4             0
    conv0    (GDN conv state)             4             0
    ShortConvPool.ple_short_conv          0             4
    NGramPool.ple_ngram                   0             4

The N-gram row backed up was `[11, 321]`; the destination slot held
`[310, 279]` before the restore and still held `[310, 279]` after it -- the
previous occupant's last two token ids, which `_prepare_ple_batch` then
prepends to the batch and conditions the per-layer embedding lookup on. After
this change all four components restore 4/4.

The cost is 184,336 bytes per checkpoint against 58.8 MB of conv+SSM state
(0.3%): the host pool shrinks from 945 to 942 checkpoints at
`--hicache-size 96`.

`get_ngram_context` is read once per forward BEFORE the decoder-layer loop, so
unlike `short_conv_layer_cache` it has no per-layer barrier of its own; since
the host tier now restores side state on the first Mamba layer's transfer, it
waits for that layer.

The L3 whole-page path carries the new rows too. Zero-copy storage metadata
(`get_page_buffer_meta`, `is_stride_page_aligned`) is refused when side states
are present rather than silently omitting them, and a page written by an older
build is rejected with a clear error instead of failing inside a reshape
half-way through a restore.

Test: `test/registered/unit/mem_cache/test_hicache_mamba_slot_side_states.py`
(CPU, 5 cases) -- the round trip through the real `backup_from_device_all_layer`
/ `load_to_device_per_layer` call sites, the L3 page, the size accounting, the
short-page refusal, and a model with no side state, which must be unaffected.

NOTE: this is NOT a fix for sgl-project#39830. On the same build, with this change applied
and verified live (`size_per_token` 58,834,944 -> 59,019,280, all four
components restoring), a host-restored prefix still produces wrong output:
0/10 usable answers against 10/10 cold and 10/10 device-hit. See the issue for
the rest of the diagnosis.
@github-actions github-actions Bot added hicache Hierarchical Caching for SGLang memory-pool labels Sep 16, 2026
detain pushed a commit to detain/sglang that referenced this pull request Sep 17, 2026
…st tier

`MambaPool.register_slot_state` attaches state that lives in the same physical
checkpoint slot as conv/temporal but is neither per-layer nor a field of
`mamba_cache`. Qwen4-Exp registers two of them: the PLE short-conv window
(`[num_slots, 10240, 9]` bf16) and the PLE N-gram token history
(`[num_slots, 2]` int64).

Every other mover of a slot already carries them:

    MambaPool.copy_from            -> sibling.copy_slots(...)    (device CoW)
    MambaPool.clear_slots          -> sibling.reset_slots(...)   (fresh slot)
    MambaPool.get_cpu_copy         -> sibling.get_cpu_slots(...) (CPU offload)
    MambaPool.load_cpu_copy        -> sibling.load_cpu_slots(...)
    MambaPool._iter_transfer_state_entries -> sibling.iter_...   (RDMA / PD)

`MambaPoolHost` did not. It reaches into `device_pool.mamba_cache.conv` and
`.temporal` directly, so a checkpoint written to the host tier lost those rows,
and a slot restored from host kept whatever the PREVIOUS OCCUPANT of that slot
left in them. Nothing zeroes them either: the load-back path allocates its
destination slot in `MambaComponent.prepare_load_back`, which sets
`req.kv.mamba_pool_idx` directly instead of going through
`HybridReqToTokenPool.alloc_mamba`, so `mamba_needs_clear` stays False.

Measured on a Qwen4-Exp (`Qwen3.8-Flash-Next`) serve with
`--enable-hierarchical-cache --hicache-size 96 --hicache-write-policy
write_through --hicache-mem-layout page_first --hicache-io-backend direct`,
by fingerprinting every component of a Mamba checkpoint on both legs of the
host round trip. Four restores, before this change:

    component                    restored correctly   wrong
    temporal (GDN SSM state)              4             0
    conv0    (GDN conv state)             4             0
    ShortConvPool.ple_short_conv          0             4
    NGramPool.ple_ngram                   0             4

The N-gram row backed up was `[11, 321]`; the destination slot held
`[310, 279]` before the restore and still held `[310, 279]` after it -- the
previous occupant's last two token ids, which `_prepare_ple_batch` then
prepends to the batch and conditions the per-layer embedding lookup on. After
this change all four components restore 4/4.

The cost is 184,336 bytes per checkpoint against 58.8 MB of conv+SSM state
(0.3%): the host pool shrinks from 945 to 942 checkpoints at
`--hicache-size 96`.

`get_ngram_context` is read once per forward BEFORE the decoder-layer loop, so
unlike `short_conv_layer_cache` it has no per-layer barrier of its own; since
the host tier now restores side state on the first Mamba layer's transfer, it
waits for that layer.

The L3 whole-page path carries the new rows too. Zero-copy storage metadata
(`get_page_buffer_meta`, `is_stride_page_aligned`) is refused when side states
are present rather than silently omitting them, and a page written by an older
build is rejected with a clear error instead of failing inside a reshape
half-way through a restore.

Test: `test/registered/unit/mem_cache/test_hicache_mamba_slot_side_states.py`
(CPU, 5 cases) -- the round trip through the real `backup_from_device_all_layer`
/ `load_to_device_per_layer` call sites, the L3 page, the size accounting, the
short-page refusal, and a model with no side state, which must be unaffected.

NOTE: this is NOT a fix for sgl-project#39830. On the same build, with this change applied
and verified live (`size_per_token` 58,834,944 -> 59,019,280, all four
components restoring), a host-restored prefix still produces wrong output:
0/10 usable answers against 10/10 cold and 10/10 device-hit. See the issue for
the rest of the diagnosis.

(cherry picked from commit 891293b)

Upstream-PR: sgl-project#39862
detain added a commit to detain/sglang that referenced this pull request Sep 17, 2026
The upstream mamba pool-host unit tests build a MambaPoolHost with
__new__ and set only the fields they exercise, so the attributes that
PR sgl-project#39862 introduces in __init__ are absent. Every method that reads
them then raises AttributeError instead of taking the documented
"model registers no slot side states" no-op path:

  test_hicache_host_register.py::test_mamba_page_layouts_use_per_buffer_page_granularity
  test_hicache_staged_write_back_dispatch.py::test_mamba_kernel_npu_backup_then_load_roundtrip

Both pass on upstream main and regressed when sgl-project#39862 was cherry-picked
onto it; the second surfaced only after the 2026-09-17 upstream merge
brought in the NPU mamba test (sgl-project#32500). Empty class-level defaults
restore the no-op path; __init__ always rebinds both.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
detain added a commit to detain/sglang that referenced this pull request Sep 17, 2026
…revise HiCache caveat

Adds a single-line `STACK:` identifier near the top -- main plus each PR
and each local change in build order:

  main+pr36787+pr37275+pr38144+pr38209+pr36644+local_sm120_integration
      +pr39807+pr39862+pr39809+mambapoolhost_newinit_fix+pr39893
      +qsa_test_context_isolation

sgl-project#39893 fixes the QSA-indexer half of issue sgl-project#39830; sgl-project#39862 already in the
stack fixes the PLE half. The caveat no longer says "do not enable
HiCache" but states what is and is not established: both PRs are needed,
each was measured with the other applied, the numbers are the author's on
1x B200, and nothing has been run end-to-end with HiCache on this host.

Commits that touch only stack.txt are excluded from the numbered list, so
regenerating the manifest does not keep adding entries to it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
detain added a commit to detain/sglang that referenced this pull request Sep 17, 2026
…eads alive

The sgl-project#39862/sgl-project#39893 author's closing caveat on sgl-project#39830 was that a page which
exists but cannot be (de)serialized -- e.g. a storage directory written by a
build with the old, shorter page layout -- raised from inside the daemon
storage threads, which only catch queue.Empty. One corrupt page therefore
killed the prefetch or backup thread silently, disabling that tier for the
rest of the serve and leaking the operation's host allocation.

- HiCacheFile.get: OSError (short read included) now returns None like a
  missing file, keeping the tensor-or-None contract.
- _read_page/_write_page: the flat-page deserialize/serialize legs
  (set_from_flat_data_page raises ValueError on incompatible layouts by
  design, per sgl-project#39862) are wrapped per page and reported as misses;
  _batch_io_v2 routes every page through _safe_page_op so a bad page
  truncates the prefix instead of skipping the rest of the batch.
  Warnings are rate-limited (_BAD_PAGE_WARN_BUDGET) -- a stale directory
  can hold thousands of such pages.
- prefetch_io_aux / prefetch_thread / prefetch_thread_func hit-query /
  backup_thread loops (base and hybrid controller): per-operation
  Exception guards that follow the existing failure signaling (batch
  miss, zero sidecar hits, partial progress) and ALWAYS emit the same
  acks -- the prefetch sync thread MIN-reduces PrefetchAcks pairwise
  across ranks, so ack-count parity is load-bearing; the hit-count
  all_reduce is kept outside the guard so a locally failed query still
  participates with a zero rather than desyncing collectives.

Tests: +7 cases in test_hicache_file_lru_unit.py (truncated page,
raising set_from_flat_data_page, mixed good/bad batch, write-side).
CPU-only; 41 pass. py_compile clean; formatters not installed in this
venv, formatting deferred to CI.

Refs: sgl-project#39830
@detain

detain commented Sep 17, 2026 •

Copy link
Copy Markdown

awesome pr .. i might have fixed the remaining issues with it .. testing it out on my current main + #36787 +#37275 +#38144 +#38209 +#36644 +local_sm120_integration +#39807 +#39862 +#39809 +mambapoolhost_newinit_fix +#39893 +qsa_test_context_isolation +qsa_hicache_residual_fixes stack @ https://github.com/detain/sglang/tree/stack-36644-core

using 4 RTX 6000 Blackwell Max-Q Pro Workstation Edition cards with the FP8 model, my cmd line is

SGLANG_ENABLE_HEALTH_ENDPOINT_GENERATION=false \
SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 \
SGLANG_QSA_PREFILL_GEOMETRY=tuned \
sglang serve \
  --model-path Qwen/Qwen3.8-Flash-Next-FP8 \
  --tp 4 \
  --ep 4 \
  --mem-fraction-static 0.88 \
  --chunked-prefill-size 8192 \
  --kv-cache-dtype fp8_e4m3 \
  --page-size 128 \
  --linear-attn-prefill-backend triton \
  --linear-attn-decode-backend flashinfer \
  --mamba-ssm-dtype bfloat16 \
  --reasoning-parser auto \
  --tool-call-parser auto \
  --host 0.0.0.0 \
  --port 30000 \
  --json-model-override-args '{"text_config": {"rope_parameters": {"mrope_interleaved": true, "mrope_section": [11, 11, 10], "rope_type": "yarn", "rope_theta": 10000000, "partial_rotary_factor": 0.25, "factor": 4.0, "original_max_position_embeddings": 262144}}}' \
  --context-length 1000000 \
  --ple-offload-embedding \
  --speculative-algorithm NEXTN \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --enable-linear-replayssm-spec  \
  --enable-cache-report \
  --enable-metrics \
  --enable-mfu-metrics \
  --chat-template chat_template.jinja \
  --enable-hierarchical-cache \
  --hicache-size 10 \
  --hicache-io-backend direct \
  --hicache-mem-layout page_first \
  --hicache-storage-backend file \
  --hicache-storage-prefetch-policy timeout \
  --mamba-radix-cache-strategy extra_buffer

loving this model and the work you guys are doing!

@alphabetc1 alphabetc1 self-assigned this Sep 30, 2026
@alphabetc1 alphabetc1 added run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) labels Oct 2, 2026
@ispobock
ispobock merged commit 5606fb8 into sgl-project:main Oct 4, 2026
193 of 218 checks passed
detain added a commit to detain/sglang that referenced this pull request Oct 10, 2026
Brings in 699 upstream commits up to 87845cd (sgl-project#43301, 2026-10-09).

Conflict resolutions (67 files):
- multimodal_gen quality tiers: adopt upstream exact/lossless/high migration
  (old lossless=bit-exact -> new "exact"; fusion moves into "lossless", which is
  now the DEFAULT). Migrated the stack's teacache guard (minimax_h3) to the
  "exact" tier and ltx_2 mask-skip to quality_allows(q, "lossless").
- video saving: take upstream's one-pass _save_video_ffmpeg (plugin-free),
  superseding the stack's PyAV/ffmpeg-pipe two-pass path (c16d89e/1b66dcb374);
  video_api generate_audio re-expressed over their request_extra_value.
- teacache: union API -- keep our get_thresh/get_skip_boundaries/is_step_boundary
  alongside their get_skip_step_range (wanvideo/longcat/minimax + tests use all).
- orchestrator.py: kept OURS wholesale (their refactor targets classic
  dispatchers our DAG sgl-project#139 removed); glm_distributed NotImplementedError lives in
  scheduler_mixin.
- schedule_batch: retained our grammar_needs_sync field.
- pool_host / mamba naming: took theirs.
- unified_radix_cache: took their prefix-hit API, re-porting our bounded-evict
  logic into allocate_storage_hit.
- hybrid_cache_controller: kept sgl-project#39830 degrade-to-miss guard over their changes.
- hybrid_pool_assembler: took theirs (sgl-project#39893 absorbed our earlier patch).
- qwen4_exp: rebuilt stage-boundary logic + re-applied PLE deltas.
- qsa_sparse_attn_backend: integrated upstream CP / breakable-graphs /
  verify-fusion over our SM120 triton-decode and FP8-descale paths.
- sgl-project#38480 + sgl-project#39862 arrived via upstream (stack dupes dropped).
- tests: upstream deleted test_scheduler_decision_batch_params; ported that
  coverage to test_scheduler_grammar_mixed_tail_sync.py.
- quantization import test (merge fallout): upstream renamed kitchen_int8 ->
  convrot_int8 and dropped the package-level config-class __getattr__ shim, so
  test_quantization_imports now asserts get_quantization_config dispatch against
  the concrete modules (canonical convrot names) plus an explicit
  kitchen_int8->convrot alias check.

Deferred: GPU end-to-end verification owed (all 4 GPUs are running production
servers; this battery was CPU-forced). Stack fixes land live only after the next
diffusion/AR server restarts.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) hicache Hierarchical Caching for SGLang memory-pool run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants