Skip to content

[Fix] HiCache: Include indexer pools in hybrid host memory budgets - #44462

Open
gitover22 wants to merge 1 commit into
sgl-project:mainfrom
gitover22:fix/hicache-indexer-budgets
Open

gitover22 wants to merge 1 commit into
sgl-project:mainfrom
gitover22:fix/hicache-indexer-budgets

Conversation

@gitover22

@gitover22 gitover22 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Two hybrid HiCache paths leave indexer host buffers outside their memory budget:

  • Auto-sizing unwraps QSATokenToKVPool as a HybridLinearKVPool, counting full KV but omitting the compressed index keys that QSAIndexerPoolHost also mirrors. The resolved ratio can therefore exceed the available host budget.
  • For hybrid Mamba + DSA with an explicit --hicache-size, the KV/Mamba split already includes DSA index bytes. The assembler gives that entire KV-group share to the MLA host pool, then allocates the declared indexer beside it. A 100 GB regression case produces about 110.31 GB before this fix.

Modifications

  • Count QSA compressed keys for target and draft host mirrors. Exclude the request-local key/RoPE state, which has no host mirror.
  • Reserve declared indexer bytes within the MLA group's explicit budget before choosing its token capacity. Account for skipped index layers, layer sharding, packed draft layers, and index page geometry.
  • Keep the existing allocation page rounding and ratio-mode behavior.

Tests

CPU execution on Linux with Python 3.12 and PyTorch 2.11.0+cu128 (GPUs hidden).

CPU unit tests: 84 passed, 65 subtests passed, 2 CUDA transfer tests skipped.

CUDA_VISIBLE_DEVICES=999 SGLANG_RUST_BUILD_MODE=never SGLANG_BUILD_RUST_EXTS=none \
  PYTHONPATH=python python -m pytest -q \
  test/registered/unit/mem_cache/test_hicache_auto_size.py \
  test/registered/unit/mem_cache/test_hybrid_pool_assembler.py \
  test/registered/unit/mem_cache/test_host_memory.py \
  test/registered/unit/mem_cache/test_dsa_pool_host_unit.py \
  test/registered/unit/mem_cache/test_mem_pool_host.py

The new regressions fail against the unmodified production files from f7ad4345b8 and pass with these changes. Coverage includes QSA packed/sidecar drafts and DSA 64/256-token pages, skipped index layers, packed drafts, and both ranks of an uneven layer shard. Large buffer shapes use meta tensors and allocator-only host pools.

Accuracy Tests

No model-forward or numerical changes. No model accuracy run was performed.

Speed Tests and Profiling

Not run; this changes startup capacity accounting, not inference kernels.

Checklist

  • Formatting and import order checked with Ruff and isort; git diff --check passed.
  • Added regression tests and ran the existing related CPU tests.
  • Registered-test lint passed.
  • No documentation update needed; no new flags or APIs.
  • GPU end-to-end validation.

CI States

Latest PR Test (Base): ❌ Run #38718738974
Latest PR Test (Extra): ❌ Run #38718739275
Latest PR Test (AMD ROCm 10): ❌ Run #38718738842

@github-actions github-actions Bot added the hicache Hierarchical Caching for SGLang label Oct 15, 2026
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
…mily + S-EXT1 + riders + S-RACE + LLGUARD/ENVREG), S-EXT1 and S-RACE items CLOSED, entry-256's raw-env deviation and LL-vs-PCIe-IPC collision warning both marked CLOSED with the BOOT_DELTA (h') needle in landing terms, sgl-project#35617 left as the sole FAM-A7 survivor, sgl-project#44732 re-pointed to the operator's merge-sgl-project#5 answer, and the KV-ROUTE DECISION RECORD added (HOLD NVFP4-KV until armed PCIe-IPC is measured post-merge; preferred-if-ever sequence merge -> sgl-project#43356-delta -> sgl-project#46452 NOT sgl-project#43240 -> optional sgl-project#43471 -> fork BUILD-A QSA FP4 reads (template sgl-project#38724) -> BUILD-B L3 scale sidecar -> one GPU window; sgl-project#46141 template, sgl-project#44462 NEXT, MXFP4 declined, entry-247 re-sync watch-string modelopt_e4m3_k32)
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
… C closure -- the post-merge port queue is now decided

ARRIVAL SCAN (git log 12dc623..2a6c204 --grep) + LIVE gh STATE +
head-sha comparison for EVERY deferred item. Verdicts:
  RELEASED-BY-MERGE: sgl-project#42689 (@ 7a632cf in-range -- the SECTION-B
    cherry is now redundant; behavior note rides the restart).
  CLOSED (C-items whose PRs arrived and whose integration this stack
    performed): C1 (the dedicated merge week WAS merge sgl-project#5; all eight
    precursor PRs in-range), C2 (sgl-project#44993/sgl-project#44994 -- B5), C3 (sgl-project#45232/
    sgl-project#45236/sgl-project#45334 -- B2), C4 (sgl-project#45238/sgl-project#45241/sgl-project#45242 -- B3), C5 (sgl-project#44912/
    sgl-project#44913 -- arrived; entry-230 canary re-planted as its guard),
    C9 (sgl-project#39727 -- verified OPT-IN, no purge; BOOT_DELTA anti-needle),
    C0a (arrival shas already recorded at entry 310 -- Section C now
    carries NO open code-integration items: C6/C10 retain only their
    explicitly-named docs/boot-measurement remainders, re-stated).
  STILL-OPEN: sgl-project#44342 (head unchanged; auto-merge comfort LOST to
    #46970x), sgl-project#46153/sgl-project#37106/sgl-project#32479/sgl-project#45391 (gh CONFLICTING -- stale
    bases, rebase before any port), sgl-project#41624/sgl-project#42525/sgl-project#42660/sgl-project#44462/sgl-project#35617
    (open, heads unchanged), sgl-project#46191/sgl-project#39845-class (watch-list, none in
    range).
  HOLD STANDS (operator decision, binding): sgl-project#43356/sgl-project#46452/sgl-project#43240/
    sgl-project#43471 KV route -- step-1 'MERGE sgl-project#5 lands first' is NOW MET; the
    sequence may be re-visited ONLY with the post-merge PCIe-IPC
    measurement at an operator sitting. sgl-project#44732: the 'one purge if done
    WITH the merge' premise LAPSED when merge sgl-project#5 completed without it
    -- later execution costs the SAME single purge once; no penalty,
    no haste. Recorded for the operator, not decided by B6.
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
…n hybrid host memory budgets

sgl-project#44462 (OPEN @ head
46b69b8, gh-verified fresh; base
f7ad434 predates merge sgl-project#5 -- this is an ADAPTED PORT, not a pick;
git log --grep 44462 origin/main: EMPTY, not released-by-merge).

Premise (holds post-merge): the QSA compressed-K host mirror and the
DECLARED DSA INDEXER sidecar are invisible to HiCache host sizing -- the
ratio path undercounts device bytes (over-provisions host) and the
explicit --hicache-size path on the MLA route lets _split_hicache_size
weight the KV pool by get_kv_size_bytes() (which includes DSA index
bytes) while the MLA host allocates only KV rows and the declared
indexer host then charges its rows AGAIN out of the same budget: the
test scaffold's 100 GB cap over-commits to 106.9 GB.

SUBSUMED BY OUR POST-MERGE TREE (not ported, recorded): the PR base's
SWAKVPool/HybridLinearKVPool isinstance branches in _pool_bytes -- the
#46970x merge took the layer_router/_sub_pool_views chain that replaces
them; the existing qsa_pool index-bytes block in
build_hybrid_mamba_stack (context, not content, of the PR diff).

SURVIVING HUNKS (4 files, adapted):
* hicache_auto_size._pool_bytes: QSATokenToKVPool branch BEFORE the
  router resolution (a QSA pool otherwise collapses to its full_kv_pool
  view -- compressed-K invisible). Only compressed keys have a host
  mirror (pool_host/qsa.py QSAIndexerPoolHost mirrors exactly
  qsa_compressed_k_buffer_pool, anchored to the KV host page count);
  the request-local key/rope state in get_kv_size_bytes() stays device.
* hybrid_pool_assembler._mla_host_kv_fraction + call site. DEVIATION:
  placed AFTER entry-219's --hicache-mamba-size-gb override (which
  REPLACES kv_host_size; the PR-base slot, immediately after
  _split_hicache_size, would leave the knob path -- the one entry 219
  re-armed -- unreserved).
* NO DOUBLE-COUNT (entry-295 precedent semantics -- persistent
  checkpoints only): the fraction reads config.pools[1:] = DECLARED
  sidecars only; the QSA INDEXER entry is manual (not declared) and
  QSA is use_mla=False, so the two reservations are mutually exclusive
  by construction. sidecar layers = owned live layers + packed drafts
  == DSAIndexerPoolHost.size_per_token exactly. MambaPool
  host_capacity_bytes (entry 295) is preferred by every budget reader
  and carries no indexer bytes -- untouched. host_capacity_bytes on the
  MLA/DSA pools is None (class default), so the split keeps
  get_kv_size_bytes (with index) -- the fraction's premise is TRUE in
  our tree, not subsumed.
* test_hicache_auto_size: 2 QSA tests RE-ANCHORED to the post-#46970x
  _estimate_hicache_bytes API: holds_state_slots + allocator.state.pool
  replace req_to_token_pool.mamba_pool; SimpleNamespace idiom; the QSA
  mock carries the real KVLayerRouter full-view route (gate +
  _draft_bytes SLIDING_WINDOW probe); the 2800-byte and budget*0.95/1200
  arithmetic PRESERVED VERBATIM.
* test_hybrid_pool_assembler: explicit-budget test RE-ANCHORED:
  MLAHostAllocation ctor (is_dummy=dummy path skips psutil booking),
  mamba_allocator -> token_to_kv_pool_allocator.state_slots (sgl-project#44968),
  mamba_layer_mapping arg GONE (derived from DevicePoolInfo.layer_ids),
  start_layer=0 added, dummy_mamba_host gains the mamba_info positional,
  dummy_kv_host mirrors the per-rank ceil-shard layer count the
  fraction charges (the PR's ctor-computed row made the shard subTests
  fail under the old shape).

BATTERY ACTUALS (CVD=9, prod venv, PYTHONPATH=wt/python; baseline
measured at 78783f0 BEFORE the edit):
  hicache_auto_size       3P/2sub -> 5P/4sub EXACT (+2P/+2sub)
  hybrid_pool_assembler  52P/36sub -> 53P/41sub EXACT (+1P/+5sub)
  hicache_mamba_sizing   30P/17sub UNMOVED
  explicit_budget         5P EXACT;  draft_budget 11P EXACT
  kv_cache_configurator   decode_table 2P, mamba_budget 4P/2sub,
                          npu_indexer 1P UNMOVED; draft_gate 10P+4F =
                          the documented cargo/torch-sys ENV class,
                          byte-identical baseline->after
  model_executor pool_configurator 71P/4S/34sub UNMOVED
  RED-at-base PROVEN per hunk: auto_size tests red without the QSA
  branch (3F); assembler test all 5 subTests red without the fraction.
  uvx [email protected] check + format --check: CLEAN (4 files);
  check_registered_tests.py rc=0; import sglang OK (module-level
  qsa_kv_pool import in hicache_auto_size: no cycle).
  No flags added -> server_args battery N/A; hicache_best_practices:
  no collectible test, docs untouched by the PR.

GPU-WINDOW DEBT: real-boot --hicache auto-size dump comparison
(entry-243 practice) -- the 106.9G->100G numbers above are test-scaffold
arithmetic, NOT prod capacity claims until a boot dump is read.

(cherry picked from commit b72c72f3677c669b6d95cf8888e721400774f2ba)
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
…gl-project#44462(317)/sgl-project#44342-trunk(318) in both the FAM-A3b block and the B6 re-triage verdicts; 10 dated corrections (mergeable flips: sgl-project#46191 REAL -> WATCH-HIGH with the re-derive-vs-QSA_RING_GROUPS=2 instruction, sgl-project#39845 DISPUTED as UNKNOWN-not-true plus the general 'UNKNOWN is no signal' rule; sgl-project#44344 -> SECTION R DOA with the entry-268 unconditional-clear subsumption citation and the mergeable-is-a-trap note; sgl-project#42525 target path moved fla->linear; sgl-project#45520 STILL OPEN -> re-apply rule ARMED FOR MERGE sgl-project#6; b12x-package archived claim DISPUTED with the frozen cutlass-dsl==4.8.0 pin risk standing; sgl-project#46153+sgl-project#41624 gated as ONE QAD bundle; sgl-project#37106 PARKED on eroded motivation with named revive conditions; sgl-project#32479 gated behind the PCIe-IPC measurement and DE-COUPLED from sgl-project#45391; sgl-project#44462's NEXT note spent); NEW S-item S-B12XDENSE filed
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
… commits since 2a6c204 @ merge-sgl-project#5)

Conflicts: 110 files (106 content / 4 add-add / 0 modify/delete) at the settled
321 tip 2d87757 -- vs merge sgl-project#5's 167; the smaller count despite 950 commits
(merge sgl-project#5: 1,120) is the merge-era's re-plant landing INSIDE upstream's new
window (many fork families -- qwen4 varlen, fast_file, hicache-liveness, the
209-218 controller semantics -- now collide as DUAL IMPLEMENTATIONS: upstream
grew the same families independently in the window). By class: A 7
(auto-takes-upstream, dedupe-verified), B 36 (mechanical union/custom splices),
C 46 (upstream structure taken, fork hunks extracted for re-plant), D 21
(fork-owned flips + dual-impl adjudications, incl. the whole fast_file family).
228 conflict regions total: 69 union (all def/class-collision-checked), 118
take-upstream (104 marked, 14 dedupe-verified), 25 keep-fork (17 fold-marked,
8 strict supersets), 16 custom import/region splices.

121 TODO(merge6) markers planted (tree census): b1 12 / b2 23 / b3 18 / b4 39 /
b5 17 / b6 12. (Resolver census at region-resolution was 117; the cascade-repair
grafts below added the rest.) REPLANT INVENTORY: /tmp/opencode/merge6-dossier/
replant/ -- per conflicted file: <name>.fork-hunks.patch (full 2a6c..321 delta),
<name>.upstream-side.patch (full 2a6c..eb73 delta), <name>.ours-dropped.txt /
<name>.theirs-dropped.txt region snapshots, MANIFEST.tsv (file, zone, regions,
kinds, fork-hunk counts, per-region notes). Work records (conflict census JSON,
decision tables, class table, logs) under .../work/.

D-list outcomes (must-not-auto-resolve, handled deliberately):
- sgl-project#45520 (entry 302): STILL OPEN upstream at eb73a50 (gh-verified + ZERO
  "sgl-project#45520" strings in the +950 window). Entry-230's fail-safe layer is UNTOUCHED
  and stays (standard.py warn-once + published-auto guards intact; the re-apply
  rule armed in CAVEATS was NOT needed this merge).
- sgl-project#44590 (entry 228): the window did NOT move the floor further -- upstream
  pyproject stays sglang-kernel==0.4.10 (absorbed at merge sgl-project#5 via sgl-project#43922) and
  the engine assert_pkg_version stays 0.4.9 in BOTH trees; the
  _load_inline_fragment_probes_available() probe never existed on either side
  (docs-mention only). Nothing to re-assert; both pins kept byte-identical.
- flashinfer_cutlass.py (fork-owned per merge-sgl-project#5 flip): did NOT conflict; 56
  b12x refs intact, dispatcher reads untouched.
- modelopt_quant sgl-project#44993/sgl-project#44994-ERA B12X W4A16 arms: the fork's
  defer-swizzle/b12x conditions at L2941-2996 are CONTESTED against upstream's
  skip_swizzled_blockscales rewrite -> took upstream, b5 markers + region
  snapshots (boot-integrity fields live in the fork-owned cutlass file, which
  survived; the b12x selection ARMS need the B5-style re-plant).
- DUAL-IMPLEMENTATION FAMILIES (the new pattern of this merge; upstream grew
  the same features the fork replanted -- take-upstream + fold-diff replant,
  NEVER a silent pick): kernels/ops/mamba/qwen4_short_conv.py + its test suite,
  srt/models/qwen4_exp.py varlen trio, mem_cache/storage/fast_file/fast_file_store.py +
  test_hicache_fast_file_unit.py, test_hicache_sidecar_restore.py,
  fused_moe_triton/layer.py nvfp4-deferred clause,
  tokenizer_manager _validate_top_logprobs_num, hicache_best_practices.mdx.
  All fork-side versions snapshotted; replant batches diff
  ours-dropped.txt against the taken upstream.
- environ.py: took upstream's SGLANG_EXACT_CHUNK_FILL removal; kept ONLY the
  fork-added SGLANG_SPLIT_PREFILL_AT_MAMBA_FORK line (custom splice).
- entry-219 gauge schema: per-pool hicache_host_pool_{used,total}_tokens names
  SURVIVED the auto-merge (metrics_collector/hicache_pool_stats/metrics_reporter/
  urc all intact); the marked b3 controller regions must RE-VERIFY the producer
  dict end-to-end at re-plant, not assume it.

Cascading silent-auto-merge repairs (files NOT in the conflict set, broken by
auto-merge splices -- all found by the ruff-F821/check_* gates, all fixed here):
utils/common.py upstream prune RE-HOMED the fork's get_mixed_precision_moe_quant_algos
into configs/quant_utils.py (next to the moved siblings) + the make_layers
empty_cache into layers/utils/layer_list.py, importers rewired;
mem_cache/pool_host/base.py silently LOST the entry-sgl-project#44462-era
host_memory_budget_bytes() helper whose caller survived -- grafted back;
model_executor/runner/eager_runner.py CP helpers retargeted to upstream's NEW
layers/cp/utils (cp_shard_model_inputs/cp_gather_after_forward) replacing the
retired runner_utils.cp_extend pair; runner/flashinfer_autotune.py + qsa/mqa.py +
modelopt_quant.py import retargets for the utils/device + layers/dp_attention
move; mem_cache/memory_pool.py lossless-verify tuple buffers re-grafted around
upstream's replayssm skip-chain; unified_radix_cache.py host-capacity deadline
preamble re-grafted (marker kept); qwen4_exp.py _use_qwen4_direct_decode
re-grafted (its kernels survived); qwen4_exp_ple_table.py _HOST_PAGE_TABLES
memo dict re-grafted; rotary_embedding/factory.py get_rope param restored;
multimodal_gen forward_context teacache_plan param restored + server_args.py
Literal import; parallel_executor.py rebuilt as fork-owned + upstream's
raise_if_cancelled guards folded into the fork loop structure;
hybrid_cache_controller.py _reduce_prefetch_ack if/zero_ splice repaired;
python_bindings.rs pyo3 signature REORDERED to match the unioned fn new()
argument order (mamba_value_seqlen position -- a positional-bind footgun, fixed
pre-commit); test_io_struct.py get_context/MAX_PARALLEL_SAMPLES imports;
stat_loggers_di + test_flashinfer_autotune_sync + fused_lora_compose +
tp_worker + compressed_tensors + minimax_h3 + hc_mix + scheduler_mixin +
pool_configurator + scheduler/tokenizer_manager import prunes/grafts.

Gates at commit (CVD=9, prod venv, worktree PYTHONPATH): import sglang OK;
check_registered_tests / check_no_bare_pytest_main / check_no_registered_tests_in_package
ALL rc=0; ruff (F401,F821,F823,UP037 @ v0.17.1 vs pinned 0.15.1) ZERO new errors
on the 3,269 merge-touched .py -- the residual 161 are BYTE-IDENTICAL INHERITED
rows present at BOTH parents (kernels/aot, api_types, mm entrypoints/utils, etc.;
0.17-only detections, not merge damage); ruff format clean on the same set;
py_compile clean; CARGO sglang-radix-tree check+test GREEN: 966 passed / 0 failed
/ 1 ignored (vs merge-sgl-project#5-era 943P -- upstream grew the suite +23; NOTE the crate
is now `exclude`d from the rust/ workspace with extension-manifests metadata --
`cargo -p sglang-radix-tree` from rust/ no longer works; run inside the crate).

NON-ADOPTIONS honored: sglang-kernel floor 0.4.9 (engine assert) untouched;
sgl-project#45520 not brought (fail-safe layer intact by rule).

Re-plant batches owed (per marker zones): B2-2026 test re-home (23), B3-2026
mem_cache/controllers/rust (18), B4-2026 scheduler/managers/runner (39),
B5-2026 moe/quant/kernels/qwen4 (17), B6-2026 environ/arg_groups/docs re-pins
(12), B1-2026 diffusion folds (12). PROD BOOT FORBIDDEN until the B3/B4 zones
re-plant the entry-209/218 controller semantics (the trailing_endpoint gate will
read RED at this commit, exactly as at merge-sgl-project#5's damage state).
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…ion + evidence: the 5 explicit_budget F's are OUR contract, upstream's premise is FALSE in this architecture; mem_cache budget files green (assembler 5/5 subtests back; named run 108P/0F/89sub) EVIDENCE THE DECISION: test_explicit_budget_includes_declared_indexer_and_packed_draft measures the FINISHED host group (kv.size x (kv.size_per_token + indexer.size_per_token) + mamba) against the 100 GB --hicache-size ceiling and lands 106.9 GB with the KEY_ROWS-only deduction -- byte-for-byte the leak shape entry 317 was ported to close, i.e. the paged DSA sidecar host bytes are accounted NOWHERE else post-sgl-project#47714 (a4e51e2); "DSA indexers sit on top" was an explicit widening of the footprint, and entries 219/317 make staying inside the ceiling the whole point of the declared-indexer reservation. FIX (hybrid_pool_assembler.py, upstream structure INTACT): new _reserve_declared_indexer_bytes runs the fork's sgl-project#44462-era reservation (per-token MLA host row vs sum of non-KEY_ROWS sidecar host rates) as its OWN multiplicative step, placed after the entry-219 knob re-plant exactly like the merge-sgl-project#5 arm; _kv_budget_index_bytes and the sgl-project#47714 KEY_ROWS block are NOT touched, and the two are disjoint by key_layout so no sidecar is ever charged twice (entry-317 no-double-count proof restated on the new config shape). Rates mirror the REAL builders: DSAIndexerPoolHost.size_per_token == len(packed buffers) x kernel_page_bytes//page_size (owned live layers + packed drafts -- _prepare_sidecar packs exactly the host's buffers), anchor row == build_kv_host_pool's per-rank ceil-share + drafts (the same equality entry 317 pinned verbatim, which is why the +/-1-page assertions close without retuning). CROSS-CHECK while in there: the collective/digest order KV->IDX->Mamba is INTACT -- _build_pool_entries emits the KV anchor then sidecars in declaration order, and build_hybrid_mamba_stack appends mamba last (entries == [KV, INDEXER, MAMBA]); the stack-declares-indexer test pins the same shape. Test file: the B2 triage note (contract-change placeholder) replaced with the landed-record note. B3's region@1377 comment corrected in place (it claimed the sgl-project#47714 helper generalized to every sidecar; it did not). Named batteries: hybrid_pool_assembler + explicit_budget(5P) + mamba_sizing(30P/17sub) + draft_budget + storage_prefetch_lifecycle + buffer_mode_sidecar + kv_cache_configurator_mamba_budget green pre-commit; full mem_cache dir in the post-land phase (target 2970P+/24F). ruff ruleset+format clean; four check_* rc=0.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hicache Hierarchical Caching for SGLang

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant