Skip to content

[HiCache][Dsv4] Don't cache C128 State pool in L3 - #27293

Merged
hzh0425 merged 3 commits into
sgl-project:mainfrom
vladnosiv:do-not-backup-c128-state
Jun 8, 2026
Merged

hzh0425 merged 3 commits into
sgl-project:mainfrom
vladnosiv:do-not-backup-c128-state

Conversation

@vladnosiv

@vladnosiv vladnosiv commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The C128 State Pool is added to the list of pools for HiCache. However, due to the fact that the page size is 256 and is divisible by 128, the tail is actually empty on the cache hit boundary. And accordingly, it is never consumed during a cache hit. At the same time, slots are being allocated now anyway, and this leads to an overhead of ~0.54GB/1M tokens in the L3 cache.

Modifications

Accuracy Tests

TBD


CI States

Latest PR Test (Base): ✅ Run #27112416213
Latest PR Test (Extra): ✅ Run #27112416180

Signed-off-by: Vladislav Nosivskoy <[email protected]>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@hzh0425

hzh0425 commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

Could you provide some Accuracy Comparison, include AIME25 (Repeat16), GPQA, MMLU

@hzh0425 hzh0425 self-assigned this Jun 5, 2026
@vladnosiv

Copy link
Copy Markdown
Contributor Author

Setup: V4-Flash, UnifiedTree, HiCache, MoonCake Store 512GB

Empty L3:

== aime25 ==
30 examples x 16 repeats  |  1093.1s  |  7170 tok/s  |  7.8M tokens

* pass@1[avg-of-16]  =  92.29% +/- 3.98% (SEM 1.00%)
  pass@16            =  100.00%
  majority@16        =  100.00%
  no_answer          =  6.88%  [warn: consider --max-tokens]

Second pass (hot L3, cache flushed):

== aime25 ==
30 examples x 16 repeats  |  1072.5s  |  7292 tok/s  |  7.8M tokens

* pass@1[avg-of-16]  =  91.88% +/- 4.21% (SEM 1.05%)
  pass@16            =  100.00%
  majority@16        =  100.00%
  no_answer          =  7.29%  [warn: consider --max-tokens]

@vladnosiv

Copy link
Copy Markdown
Contributor Author

GPQA

Cold L3:

====================
  Repeat: 8, mean: 0.876
  Scores: ['0.884', '0.874', '0.884', '0.874', '0.879', '0.874', '0.884', '0.859']
  Mean latency: 1675.265 s
  ====================
  Output throughput: 1266.469 token/s

Re-run after flush_cache

====================
  Repeat: 8, mean: 0.875
  Scores: ['0.843', '0.874', '0.869', '0.874', '0.889', '0.894', '0.879', '0.879']
  Mean latency: 1598.752 s
  ====================
  Output throughput: 1304.548 token/s

@vladnosiv

Copy link
Copy Markdown
Contributor Author

MMLU

Cold L3:

====================
Repeat: 2, mean: 0.911
Scores: ['0.910', '0.912']
Mean latency: 332.963 s
====================
Output throughput: 1230.252 token/s

Hot L3:

====================
Repeat: 2, mean: 0.906
Scores: ['0.904', '0.908']
Mean latency: 356.418 s
====================
Output throughput: 1185.905 token/s

@vladnosiv

Copy link
Copy Markdown
Contributor Author

Now C128 State offloaded but it's never effectively read:

  1. The state buffer is read inside c128_forward (kv_buf):

const auto src = j < buffer_len ? kv_buf : kv_start;
kv[i] = gmem_in.load(src + j * Trait::kElementSize);
score[i] = gmem_in.load(src + j * Trait::kElementSize + Trait::kScoreOffset);

  1. During prefill, c128_forward is called only in the method flash_c128_prefill

    if (plan.is_invalid()) return;
    const auto kv_src = kv_input + plan.ragged_id * Trait::kElementSize;
    // Compact output: one row per compress plan, indexed by `global_pid`.
    const auto kv_out = kv_output + global_pid * Trait::kHeadDim;
    const auto kv_buf = kv_buffer + plan.read_page_1 * Trait::kPageElementSize;
    PDLWaitPrimary<kUsePDL>();
    c128_forward<Trait, kUsePDL>(kv_buf, kv_src, kv_out, score_bias, plan.buffer_len);

  2. The forward call occurs only if the plan is valid

  3. Filling out a prefill plan:

    // Path 2: general prefill (long extend_len). Iterate batches in an outer loop;
    // the whole block sweeps each batch's tokens in parallel.

if ((position + 1) % cr == 0) {
const int32_t buffer_len = window_size - min(j + 1, window_size);
const uint32_t out_idx = atomicAdd(&counter_c, 1u);
params.plan_c[out_idx] = {
.seq_len = static_cast<uint32_t>(position + 1),
.ragged_id = static_cast<uint16_t>(ragged_id),
.buffer_len = static_cast<uint16_t>(buffer_len),
.read_page_0 = -1,
.read_page_1 = static_cast<int32_t>(batch_id),
};

  1. When a cache hit, we get:
    const int32_t pl = s_prefix_len[batch_id];
    const int32_t sl = s_seq_len[batch_id];
    const int32_t el = sl - pl;
    const int32_t last_c_pos = (sl / cr) * cr;
    const int32_t first_w_pos = min(last_c_pos - (is_overlap ? cr : 0), sl - params.mtp_pad);
    for (int32_t j = static_cast<int32_t>(tx); j < el; j += static_cast<int32_t>(block_size)) {
pl = out_cache_hit_len (% 256 == 0) => pl = 128 * h

The condition (position + 1) % cr == 0 (cr = 128) is fulfilled when position = 128 * k + 127, position = pl + j => j = 128 * t + 127 =>

const int32_t buffer_len = window_size - min(j + 1, window_size);

buffer_len = 128 - min(128, 128) = 0 => on state read condition j < buffer_len is not fullfilled => We are not reading the STATE buffer for cached data:

const auto src = j < buffer_len ? kv_buf : kv_start;
kv[i] = gmem_in.load(src + j * Trait::kElementSize);
score[i] = gmem_in.load(src + j * Trait::kElementSize + Trait::kScoreOffset);

@hzh0425

hzh0425 commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator

/rerun-group radix_cache/unified_radix_tree

@github-actions

github-actions Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Results for /rerun-group radix_cache/unified_radix_tree:

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

cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_hicache_pp_kl.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_cp.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_dsv4.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_mamba.py

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

cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_full.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_swa.py

🚀 8-gpu-h200 (1 test): ✅ View workflow run

cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_nightly.py

@hzh0425 hzh0425 left a comment

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.

Make sense to me, @ispobock could you take a double check?

@hzh0425 hzh0425 added run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) labels Jun 8, 2026
@hzh0425

hzh0425 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

/rerun-group radix_cache/unified_radix_tree

@hzh0425

hzh0425 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

/rerun-test test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py

@github-actions

github-actions Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Results for /rerun-group radix_cache/unified_radix_tree:

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

cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_hicache_pp_kl.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_cp.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_dsv4.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_mamba.py

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

cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_full.py
cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_swa.py

🚀 8-gpu-h200 (1 test): ✅ View workflow run

cd test/ && python3 registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_nightly.py

@github-actions

github-actions Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Results for /rerun-test test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py:

🚀 1-gpu-5090 (1 test): ✅ View workflow run

cd test/ && python3 registered/unit/mem_cache/test_unified_radix_cache_unittest.py

@ispobock ispobock left a comment

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.

Looks reasonable to me. @vladnosiv thanks for the good catch and test results. The AIME25 results is lower than expected. If you can set max_tokens to 200k, the scores may be higher.

@vladnosiv

vladnosiv commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor Author

@ispobock @hzh0425

AIME25, max-tokens=384k

== aime25 ==
30 examples x 16 repeats  |  2739.0s  |  3499 tok/s  |  9.6M tokens

* pass@1[avg-of-16]  =  97.08% +/- 3.19% (SEM 0.80%)
  pass@16            =  100.00%
  majority@16        =  100.00%
  no_answer          =  0.62%

/flush_cache

== aime25 ==
30 examples x 16 repeats  |  2467.5s  |  3829 tok/s  |  9.4M tokens

* pass@1[avg-of-16]  =  96.04% +/- 4.08% (SEM 1.02%)
  pass@16            =  100.00%
  majority@16        =  100.00%
  no_answer          =  1.04%

@hzh0425
hzh0425 merged commit 62c505a into sgl-project:main Jun 8, 2026
249 of 275 checks passed
hzwzwzw pushed a commit to hzwzwzw/sglang that referenced this pull request Jun 15, 2026
hzwzwzw added a commit to hzwzwzw/sglang that referenced this pull request Jul 2, 2026
…-project#601 and sgl-project#628

Merge target: d958a63 "Return bad request for malformed DSV4 tool
arguments (sgl-project#602)". Excludes b4de164 (sgl-project#601 "Fix DSV4 C128 state
mapping lifecycle") and f59f166 (sgl-project#628 "Sync clean SM90 FP8+FP4
MegaMoE from main") per user instruction.

Brings in 13 upstream commits including:
- 3e31718 [HiCache] DeepSeek-V4 host-mem L2 + NVMe/disk L3 (sgl-project#564)
- 6dddb6d Fix DSv4 draft extend replay forward batch (sgl-project#569)
- 9d212a9 add observability (sgl-project#570)
- 104a38d Bytedance/deepseek v4 fix draft extend padding (sgl-project#573)
- d958a63 Return bad request for malformed DSV4 tool arguments (sgl-project#602)
- 8 docker/codex build hardening commits

Conflict resolutions (all 8 files stability-critical, memory-related):

1. tree_component.py / full_component.py / swa_component.py / mamba_component.py
   -- commit_hicache_transfer signature: keep HEAD's typed
   (insert_result, pool_storage_result) kwargs. Callers in
   unified_radix_cache.py explicitly pass these; their **kw variant
   is strictly a superset but less safe.
   Also drop their side's manual `kw.get(...)` extraction in mamba
   PREFETCH branch since the params are now directly bound.

2. hybrid_cache_controller.py -- extra_host_mem_release_queues type
   annotation: keep HEAD's Queue[torch.Tensor] (more precise).

3. swa_memory_pool.py -- their side added a full duplicate
   SWATokenToKVPoolAllocator class inline in this file, but our fork
   moved the class to allocator/swa.py in an earlier refactor. Drop
   their duplicate; instead apply sgl-project#573's free_swa fix (guard against
   negative sentinels and out-of-range indices, expand page-aligned
   free) directly to allocator/swa.py where the class actually lives.

4. hybrid_pool_assembler.py:
   - kvcache.compress_state_pools indexing: keep either form (addition
     is commutative); use HEAD's ordering for local consistency.
   - C128 state pool registration: keep HEAD's explicit non-registration
     with the "C128 State pool intentionally not registered" comment.
     Our HEAD's upstream sgl-project#27293 deliberately opted out; their side (from
     before sgl-project#601) still registers it. Silently reintroducing the pool
     would regress the fix and pressure host memory.
   - attach_hybrid_pool_to_unified_cache body: keep HEAD's
     _select_strategy(...).build() dispatch (from upstream sgl-project#26295)
     over their 245-line inline if-elif chain. Our _DeepSeekV4Strategy
     already handles the deepseek_v4 stack; the strategy signature
     already accepts storage_backend / storage_extra_config /
     storage_prefetch_threshold.

5. unified_radix_cache.py (24 conflicts) -- keep HEAD wholesale:
   - HEAD has 10 methods theirs lacks (all from upstream sgl-project#26881,
     sgl-project#27285, sgl-project#27391, sgl-project#27489, sgl-project#27554, sgl-project#27655 L3 support + our PR sgl-project#27010
     port: prefetch_sync_thread, ack-driven sync, handle_prefetch_result,
     _drain_async_work, _finish_write_through_ack, etc.)
   - Their only extra method (terminate_prefetch(rid)) was deliberately
     removed by our PR sgl-project#27010 port.
   - HEAD's load_back_threshold=10 matches hi_mamba_radix_cache and
     hiradix_cache (theirs=256 was an inconsistent local tuning).
   - HEAD passes total_len to InsertResult (dataclass field exists) and
     priority to UnifiedTreeNode (LRU correctness).
   - HEAD's write_backup early-returns on written==0 (upstream sgl-project#27108
     safety fix); theirs drops the check.
   - HEAD's _drain_queue is blocking with qsize MIN-reduce (our PR
     sgl-project#27010's lockstep drain); theirs is old get_nowait+Empty pattern
     that would desync PP/TP.
   - sgl-project#564's L2/L3 additions in this file are functionally covered by
     upstream sgl-project#26881 (already in HEAD via ep_main). No net feature
     loss from taking HEAD.

Verified: AST parse OK for all 9 mem_cache files, compileall exit=0
on managers + mem_cache trees.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
hzwzwzw added a commit to hzwzwzw/sglang that referenced this pull request Jul 13, 2026
…gg abort + double-free + DSv4 PP SWA + HiSparse tail

Seven upstream-merged bug/stability fixes for HiCache and DSv4 PP.
All adapted where our fork's structure differs (HostKVCache lives
inline in memory_pool_host.py rather than pool_host/base.py; some
fill_ids semantics differ).

- sgl-project#29823 (1e80d93) fix draft host pool allocator type
  kv_cache_builder.py: pass allocator_type=server_args.hicache_storage_backend
  into the draft host pool kwargs so the draft path uses the same
  allocator kind as target (was defaulting to None -> wrong allocator
  under storage-backed setups).

- sgl-project#26009 (f4029d0) clear storage reset state
  cache_controller.py reset(): also clear host_mem_release_queue and
  reset prefetch_tokens_occupied so no stale credit / stale slots survive
  a scheduler reset.

- sgl-project#27291 (b7ae714) fix SWA L3 cache miss due to prefetch/hit len mismatch
  scheduler.py: prefetch computes new_input_tokens up to
  _compute_max_prefix_len(len(fill_ids)) rather than the raw tail --
  the storage prefetch key was overshooting SWA-window match_prefix by
  up to page_size, causing systematic L3 misses on full-prefix reuse.
  Upstream uses full_untruncated_fill_ids; our fork uses fill_ids
  (equivalent surface, no _untruncated variant).

- sgl-project#30053 (48ba79c) release HiCache prefetch resources on disagg-prefill
  bootstrap-queue abort
  scheduler.py: when aborting a bootstrap-queued disagg-prefill req,
  also call tree_cache.release_aborted_request(req.rid) so its
  in-flight L2/L3 prefetch resources are released. Previously they
  leaked until process shutdown.

- sgl-project#29310 (bd2a5db) detect double-free / double-alloc in HostKVCache
  memory_pool_host.py HostKVCache: track a per-slot slot_used bool
  tensor; alloc asserts none of the returned slots is already used,
  free asserts every freed slot is currently used. Turns silent
  double-free (which corrupts the free_slots list and eventually
  causes phantom slot reuse) into a loud assertion at the call site.

- sgl-project#29106 (c1b5c7e) fix DSv4 PP HiCache SWA allocation and layer mapping
  deepseek_v4_memory_pool.py: size the SWA sub-pool by stage_layer_num
  (= len(stage_ratios)) instead of the model-global layer_num, matching
  the c4/c128 sub-pools which are already stage-local; add
  get_swa_raw_buffer(layer_id) helper that goes through _swa_local_layer_id
  for consistency.
  hybrid_pool_assembler.py: assert that swa_kv_pool.kv_buffer length
  matches transfer_layer_num (catches the mismatch that sgl-project#29106 fixes at
  the source); rename the misnamed c4_state_global_layers list --
  previously it held LOCAL layer ids but was later indexed with
  compress_state_pools[layer_id + start_layer]. Introduce a proper
  c4_state_local_layers (for c4_state_mapping keys) and a true
  c4_state_global_layers list, and index compress_state_pools /
  indexer_compress_state_pools by the real global id (no offset). Drop
  unused c128_state_mapping / c128_state_global_layers now that C128 is
  not registered with HiCache (upstream sgl-project#27293, already in base).

- sgl-project#30408 (1d8e3c2) fix DSV4 HiSparse SWA tail allocation forwarding
  disaggregation/decode.py DecodePreallocQueue:
  - Admission-control available_size for hisparse now uses
    logical_attn_allocator.full_available_size() when the SWA-tail
    prealloc path is active and that method exists, matching the
    allocation actually issued below.
  - _pre_alloc direct-to-host branch now routes through
    alloc_extend_swa_tail (with swa_tail_len and swa_evicted_seqlen
    bookkeeping) when the SWA-tail path is active; falls back to the
    original alloc_logical_only otherwise. Keeps our fork's
    mem_pool_host.alloc(fill_len) call (upstream uses
    alloc_paged_token_slots but our host pool exposes .alloc()).

Verified: AST parse OK, compileall OK across managers + mem_cache trees.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
luoroger37 added a commit to bytedance-iaas/sglang that referenced this pull request Jul 16, 2026
Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants