Skip to content

[Perf] hicache: MLA/DSA host dedup with rotating layer owners (opt-in) - #42009

Open
nbommi19 wants to merge 11 commits into
sgl-project:mainfrom
nbommi19:hicache-rank-shard-d2h-idle-sync
Open

nbommi19 wants to merge 11 commits into
sgl-project:mainfrom
nbommi19:hicache-rank-shard-d2h-idle-sync

Conversation

@nbommi19

@nbommi19 nbommi19 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Reworked to reuse the existing code. Rotating host-layer ownership is now an option of the #36800 primitives (MLAHostDedupBroadcaster, MLAHostDedupContext, the MLA/DSA host pools). It is switched on through the factory's existing enabled= argument and adds no new classes. This PR is now only the host dedup: the chunked D2H backup issue and the idle-sync skip were dropped from it. Rebased on current main.

Motivation

Every attention-TP rank holds the same MLA latent KV and DSA index keys. As a result, HiCache backs up, stores and loads back the same bytes on every rank, and stores each token once per rank. #36800 landed the dedup primitives, but nothing in HiCache uses them yet; today only the Mooncake linker does. #26691 (closed) used a single source rank, which then carried every host copy and every broadcast.

What is reused

Need Existing code
Enable switch and dedup state maybe_create_mla_host_dedup_context(..., enabled=), MLAHostDedupContext
Eligibility (MLA/DSA, non-FP4, CUDA, more than one rank) mla_host_dedup_eligible, mla_dedup_rank_and_size
Broadcast group and DP attention MLAHostDedupBroadcaster.build (group from attn_tp_group; warm-up unchanged)
Per-layer broadcast with the page index computed on device _bcast_layer, broadcast_loaded_layer, prepare_broadcast
Host pools store only their own layers The MLA host pool's captured device-buffer info (#40917), filtered to this rank's layers (layer % size == rank); the DSA indexer pool's compact _live_target_layers
Layer-wait hook on the forward stream LayerDoneCounter gets the same on_layer_ready callback as the Mooncake linker's counter
Config validation handle_hicache, next to the --enable-linker-mla-dedup check

What is new

  • Rotating owners. MLAHostDedupBroadcaster(rotate_owners=True) broadcasts layer slot s (each KV layer, then each layer that holds index keys) from dedup rank s % size, using group_src. build() forwards constructor arguments, and the Mooncake linker passes none, so its behavior is unchanged.
  • Two fixes in the primitives. Shared-top-k index layers (0-row placeholders) are skipped, where main raises in index_select. The index-key staging buffer is sized in pages, its row unit.
  • Load-back. Each rank loads only its own layers. The forward broadcasts each layer from its owner through the layer-wait hook, on the forward stream, right after it waits for that layer's H2D copy. Later layers therefore keep loading while earlier ones compute. The load's ack event is recorded again after the last broadcast, so the ack and the allocator's transfer fence cover the broadcasts.
  • Host capacity. MLATokenToKVPoolHost(dedup_rank=, dedup_size=) stores KV layers rank, rank + size, and so on. Token capacity is sized by the largest share, so every rank holds the same tokens. Packed MTP draft layers stay on every rank. The DSA indexer pool keeps its share of the index layers.
  • One server argument: --enable-mla-hicache-host-dedup. handle_hicache rejects it unless the L2 tier uses direct I/O with page_first_direct, on one node and one PP stage, with no storage backend, hisparse, attention CP/DCP or PD decode. Attaching a storage backend at runtime is rejected too.

Off by default: with the flag unset, no context or group is created and every path is unchanged.

Accuracy and performance

All GPU numbers below were measured on this PR's head (0f5738164e), applied to the SGLang nightly at 7224fce1. Every arm uses the same build; the control simply leaves the flag off.

Setup

  • Model and serving: GLM-5.2 FP8 at TP8 on one node with 8× B300, with EAGLE (3 steps, top-k 1, 4 draft tokens).
  • HiCache L2: write_back, direct I/O, page_first_direct.
  • Prefill and memory: 8192-token chunked prefill; mem-fraction-static 0.92; max running requests = 2 × concurrency.
  • Workload: agentic-coding trace replay, with a 20-minute measurement window per arm. Throughput runs use a fixed synthetic acceptance length; GSM8K uses real acceptance.
  • Noise: one run per arm, so treat differences under about 5% as noise.

Performance

Arm p90 tok/s per user tok/s per GPU TTFT p50 / p90 (s) Cache hit Pinned host memory (node)
c32, dedup off (control), 270 GB/rank 27.21 10,585 2.30 / 26.21 93.1% 2,655 GB (host pool full)
c32, dedup on, 270 GB/rank (7.18× host tokens) 45.77 (+68%) 14,859 (+40%) 0.60 / 6.80 (−74%) 95.4% ≈ 2,595 GB (pool 33% used at peak)
c32, dedup on, 38 GB/rank (≈ same host tokens as control) 31.38 (+15%) 10,952 (+3.5%) 1.74 / 20.52 (−22%) 92.5% 372 GB (−86%)
c32, single owner (rank 0 owns every layer; diagnostic switch, not in this PR), 270 GB/rank 25.18 10,355 2.11 / 28.47 93.0% ≈ 361 GB
c16, dedup off (control) 87.39 8,438 0.28 / 1.73 95.8% 2,655 GB
c16, dedup on, 270 GB/rank 87.33 (−0.1%) 8,385 (−0.6%) 0.27 / 1.58 95.8% ≈ 2,595 GB

Reading the table:

  • Where the c32 gain comes from: about +15% p90 from cheaper backup and eviction at equal capacity. Eviction drops from 13.9% to 8.3% of the window per rank, and backup from 8.6% to 1.2%, because each rank backs up about 1/8 of the layers. The rest comes from 7.18× host capacity in the same memory.
  • Rotating owners matter: a single owner puts all backup and eviction on rank 0. It lands 20% behind rotation at equal host tokens on p90, and 7.5% behind the control.
  • c16: the host path is about 3% of the window with dedup off, so there is little to recover.
  • Cost: the per-layer broadcasts run on the forward stream and are not overlapped. They took 11.6% of a 283K-token load-back forward and 25–27% of a 107K-token one, mostly waiting on peer ranks. With HiCache on, main keeps index keys for all 78 layers on host, although only 21 have their own; that is 13.6% of broadcast bytes. Index-K elision under HiCache ([Perf] Elide redundant DSA index-K storage with HiCache L2 #41057) would remove it.

Accuracy (GSM8K 5-shot, stress)

The device KV pool was capped at 131,072 tokens. Pass 1 runs at concurrency 32. Pass 2 runs at concurrency 64 and reloads 96.5% of prompt tokens from host: 1,287,488 tokens loaded back on every rank with dedup on.

Arm Pass 1 strict / flexible Pass 2 strict / flexible
Dedup off 0.9674 / 0.9704 0.9674 / 0.9689
Dedup on 0.9682 / 0.9697 0.9689 / 0.9712

Per-document McNemar, off vs on: p ≥ 0.61 for every pass and filter.

Engagement

  • Every rank logs the broadcaster setup and warm-up and owns 9–10 of the 78 KV layers. With a single owner, ranks 1–7 own 0.
  • A profile shows one broadcast per layer during load-back, issued from the layer-wait hook just before that layer's attention (57/57) or index-key store (21/21).
  • No collective or watchdog errors in any arm.

Unit tests in test_mla_host_dedup_primitives.py:

  • per-layer broadcast source, including the placeholder skip;
  • index staging size;
  • a multi-process gloo restore through the layer-wait hook;
  • DP attention over the attention-TP group;
  • host-pool layer mapping, including the draft layer;
  • capacity sizing.

With the flag off, the existing host-pool, assembler, write-back and server-args suites give the same results as main.

Reproduction

Hardware and image

  • Hardware: one node with 8× B300 and 2.4 TB of host DRAM for the KV host tier.
  • Image: lmsysorg/sglang:nightly-dev-cu13-20261013-7224fce1 (sha256:20d36eeb32df0418a165641b51399fd4dc5239dad57f9b8d1f9974c4c9263ca6), with this PR applied.

Server. Dedup-on arm at concurrency 32; the control arm drops --enable-mla-hicache-host-dedup.

SGLANG_SIMULATE_ACC_LEN=2.99 SGLANG_SIMULATE_ACC_METHOD=match-expected \
SGLANG_SIMULATE_ACC_TOKEN_MODE=real-draft-token SGLANG_TIMEOUT_KEEP_ALIVE=900 \
python3 -m sglang.launch_server --model-path zai-org/GLM-5.2-FP8 \
  --served-model-name zai-org/GLM-5.2-FP8 --trust-remote-code \
  --tp-size 8 --ep-size 1 --quantization fp8 --kv-cache-dtype fp8_e4m3 --bf16-gemm-backend cutedsl \
  --chunked-prefill-size 8192 --max-prefill-tokens 8192 --mem-fraction-static 0.92 \
  --max-running-requests 64 --cuda-graph-max-bs-decode 64 \
  --speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --tool-call-parser glm47 --reasoning-parser glm45 \
  --enable-hierarchical-cache --hicache-size 270 --hicache-write-policy write_back \
  --hicache-io-backend direct --hicache-mem-layout page_first_direct \
  --enable-mla-hicache-host-dedup --enable-metrics --watchdog-timeout 1800

Other arms

  • Equal host tokens: --hicache-size 38.
  • Concurrency 16: --max-running-requests 32 --cuda-graph-max-bs-decode 32.
  • Single owner: a local diagnostic switch that gives every layer to rank 0. It is not part of this PR.

The three SGLANG_SIMULATE_ACC_* variables fix the speculative acceptance length for the throughput runs, following the AgentX synthetic-acceptance rule. GSM8K runs leave them unset and use real verification.

Benchmark. InferenceX AgentX replay, benchmarks/srt_agentic.sh from SemiAnalysisAI/InferenceX at 1570a54f, with its agentic-coding trace set:

MODEL=zai-org/GLM-5.2-FP8 CONC=32 KV_OFFLOADING=dram TOTAL_CPU_DRAM_GB=2399 \
AIPERF_EXPERIMENTAL_FAST=1 RUN_EVAL=false EVAL_ONLY=false \
bash benchmarks/srt_agentic.sh

AIPERF_EXPERIMENTAL_FAST=1 is the shortened replay, which gives the 20-minute window.

GSM8K stress. Same server, without the SGLANG_SIMULATE_ACC_* variables and with --max-total-tokens 131072 to cap the device KV pool. Then run InferenceX's eval path, lm-eval GSM8K 5-shot, at concurrency 32 and then 64:

MODEL=zai-org/GLM-5.2-FP8 RUN_EVAL=true EVAL_ONLY=true EVAL_CONC="32 64" \
bash benchmarks/srt_agentic.sh

Related: #36800, #26691 (closed).

Checklist

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ⊘ Skipped in Run #46985371439 -- its commit has no run-ci approval, or the run predates the labels; a maintainer's /approve-ci approves this commit and reruns it, or /rerun-failed-ci reruns an approved one.
Latest PR Test (Extra): ⊘ Skipped -- add the run-ci-nv-extra label to opt in.
Latest PR Test (AMD ROCm 10): ⚠️ Run #46985375564

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

@YAMY1234 YAMY1234 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.

Thanks for putting this together. Rotating the owner per layer is a real improvement over the rank-0-only dedup: it spreads D2H/H2D traffic across ranks and still gives ~tp_size x unique host capacity. A few things I'd like to see addressed before this moves out of draft (inline comments below).

Tests. The multi-process simulations from the description aren't in the PR. Could you add unit cases for owner rotation, shard layer mapping and host capacity sizing to the existing test_mla_host_dedup_primitives.py, plus the end-to-end accuracy run (GSM8K with forced eviction/load-back) on the combined branch?

Comment thread python/sglang/srt/environ.py Resolved
Comment thread python/sglang/srt/managers/scheduler.py Resolved
@nbommi19
nbommi19 force-pushed the hicache-rank-shard-d2h-idle-sync branch from b9e28fd to 7e939a8 Compare October 5, 2026 17:52
@nbommi19 nbommi19 changed the title [HiCache] Rank-sharded host tier, chunked D2H backup issue and idle-sync skip (opt-in) [HiCache] MLA/DSA host dedup with rotating layer owners, chunked D2H backup issue and idle-sync skip (opt-in) Oct 5, 2026
…oject#36800 primitives

Every attention-TP rank holds the same MLA latent KV (and DSA index keys), so
HiCache backs up, stores and loads back the same bytes on every rank.
--enable-mla-hicache-host-dedup feeds the existing enabled= switch of
maybe_create_mla_host_dedup_context, so the HiCache L2 tier uses the sgl-project#36800
primitives, with each layer's host copy owned by one rank in turn rather than
all by one source rank:

- Primitives: MLAHostDedupBroadcaster(rotate_owners=True) broadcasts layer
  slot s (each KV layer, then each layer holding index keys) from dedup rank
  s % size; _bcast_layer takes the per-layer owner as its group_src. Without
  rotate_owners every path keeps its single-source behavior, and build()
  forwards constructor arguments, so the Mooncake linker adapter is unchanged.
  Shared-top-k index layers (0-row placeholders) are skipped, and the
  index-key staging is sized in pages, its row unit.
- Backup (D2H): the MLA host pool takes dedup_rank/dedup_size and reuses its
  layer-ownership hooks (_is_device_layer_owned, _host_layer_index) to store
  only its own layers; packed MTP draft layers stay on every rank. Token
  capacity is sized by the largest share, so every rank holds the same tokens
  and the radix tree stays replicated. The DSA indexer host pool keeps only
  its own index layers.
- Load-back (H2D): a rank loads only its own layers. The forward broadcasts
  each layer from its owner through the HiCache layer-wait hook
  (LayerDoneCounter.on_layer_ready, as on the Mooncake linker's counter), on
  the forward stream right after its wait for that layer's H2D copy. Each
  layer is broadcast once, in layer order, at the same point of the forward
  on every rank, so later layers keep loading while earlier ones compute. The
  load's ack event is recorded again after the last broadcast, so the ack and
  the allocator's transfer fence cover the broadcasts.
- DP attention: owners and the broadcast group follow the attention-TP group
  through the existing mla_dedup_rank_and_size and build().

handle_hicache rejects the flag unless the L2 tier is direct I/O with
page_first_direct on one node and PP stage, without a storage backend,
hisparse, attention CP/DCP or PD decode; a runtime storage attach is rejected
too. Off by default: no context or group is created and every path is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nbommi19
nbommi19 force-pushed the hicache-rank-shard-d2h-idle-sync branch from 7e939a8 to 0f57381 Compare October 13, 2026 05:01
@nbommi19 nbommi19 changed the title [HiCache] MLA/DSA host dedup with rotating layer owners, chunked D2H backup issue and idle-sync skip (opt-in) [HiCache] MLA/DSA host dedup with rotating layer owners (opt-in) Oct 13, 2026
@YAMY1234

Copy link
Copy Markdown
Collaborator

Current code LGTM! Could you add accuracy and performance comparison data in the PR description? Thanks @nbommi19

@YAMY1234

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

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

@nvpohanh nvpohanh 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.

[by Claude Code] Severity: style | Confidence: High

Issue

The Accuracy and Performance sections give results and describe the setup in prose, but someone else cannot rerun them. The description does not include:

  • the GPU type (it says only "one 8-GPU node");
  • the full server launch commands for the control and dedup arms, including the --hicache-size/--hicache-ratio values and the EAGLE flags;
  • the benchmark command, the source of the agentic-coding trace, and how the fixed synthetic acceptance length was set;
  • the GSM8K command, and the flag that capped the device KV pool at 131,072 tokens.

Fix

Please add these commands and the GPU type to the description.

],
),
] = "page_first"
enable_mla_hicache_host_dedup: A[

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.

[by Claude Code] Severity: functional | Confidence: High

Issue

This adds --enable-mla-hicache-host-dedup, but docs/docs/advanced_features/server_arguments.mdx has no row for it, and the flag is not in server_arguments_undocumented.txt. So test_server_args_docs_coverage.py::test_no_new_undocumented_flags fails at the head commit. It fails locally, and it fails in CI job base-a-test-cpu (4) (https://github.com/sgl-project/sglang/actions/runs/38349327312/job/115620190596), which blocks the later CI stages.

Fix

Add a row for the flag to server_arguments.mdx, next to --hicache-mem-layout, and reuse this help text. Do not add it to the allow list, because that list may only shrink.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the row next to --hicache-mem-layout, reusing the help text, in cf4301d. test_server_args_docs_coverage.py passes locally (4/4).

torch.distributed.destroy_process_group()


class TestMLAHostDedupRotatingOwners(unittest.TestCase):

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.

[by Claude Code] Severity: style | Confidence: Medium

Issue

The new tests run on CPU with mocks or gloo. No test launches a server with --enable-mla-hicache-host-dedup, so CI never runs the real path: HiCacheController.start_loading calling start_load, the LayerDoneCounter.wait_until hook, the NCCL group_src broadcasts, and the owned-layer page_first_direct copies. If a later change reads KV without calling wait_until, each rank reads stale KV for every layer it does not own, and no test fails.

Fix

Add a TP2 MLA case like TestHiCacheStoragePageFirstDirectIO in test/registered/hicache/test_hicache_storage_file_backend.py, but without a storage backend. Use a small device pool so prompts are evicted and loaded back, then check GSM8K accuracy on a second pass.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added test/registered/hicache/test_hicache_mla_host_dedup.py in cf4301d.

  • Server: a TP2 MLA server (DEFAULT_MLA_MODEL_NAME_FOR_TEST) with direct I/O, page_first_direct, write_back and --max-total-tokens 16384, so GSM8K prompts are evicted to host and loaded back.
  • Checks: it runs GSM8K twice and asserts that sglang:load_back_tokens_total grew during the second pass, so the owner broadcast really ran. Both passes must stay above 0.6 and within 0.05 of each other.
  • CI: registered for 2-GPU CI (base-b, 2-gpu-large). There are no GPUs where I prepared it, so CI is its first run.

…to-end test

Add the flag's row to server_arguments.mdx, next to --hicache-mem-layout, as
test_server_args_docs_coverage requires.

Add test_hicache_mla_host_dedup.py: a TP2 MLA server with direct I/O,
page_first_direct, write-back and a small device pool, so GSM8K prompts are
evicted to the host tier and the second pass loads them back through the
owner broadcast. It checks that load-back happened
(sglang:load_back_tokens_total) and that accuracy holds across both passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

1 similar comment
@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

agiping added a commit to Infrawaves/sglang that referenced this pull request Oct 23, 2026
* feat(hicache): keep one MLA KV host copy per node

MLA latent KV is identical on every TP rank, but each rank kept its own
HiCache host copy and read it from L3 on its own, so a 4-GPU node held
and fetched 4 copies of the same data.

With --enable-mla-hicache-per-node, only the first rank on each node
(leader) keeps a real MLA host pool and loads from L3; the other local
ranks use the allocator-only host pool from sgl-project#36800. During the forward,
the per-layer HiCache wait hook (as in sgl-project#42009) broadcasts each loaded
MLA layer from the leader to the local GPUs over NCCL/NVLink, so the
broadcast overlaps with compute. KDA/Mamba state, L3 keys and L3 layout
are unchanged, so existing L3 data stays valid.

The leader's host pool and budget are sized for the whole node; all
ranks size the allocator the same so the radix tree stays consistent.
PD decode, DCP, FP4 MLA and single-rank nodes fall back to per-rank
copies with a warning. The flag is off by default.

Co-Authored-By: Claude <[email protected]>

* fix(hicache): fix three node-leader MLA dedup bugs

Three bugs in the --enable-mla-hicache-per-node path.

1. Chunked-prefix prefill read prefix KV before the leader's broadcast

   A follower's device KV comes only from the leader's broadcast, and that
   broadcast is sent from the layer-wait hook (LayerDoneCounter.wait_until).
   The trtllm_mla eager prefill takes MHA_CHUNKED_KV and reads prefix KV
   through HybridLinearKVPool.get_mla_kv_buffer, which, unlike the other
   reads on that pool, did not wait. The inner MLA pool does not wait
   either: the hybrid pool clears its counter to None. So a follower read
   stale rows for that layer and gave wrong output with no error.

   get_mla_kv_buffer now waits on the model layer id before swapping in
   the compact id, as get_key_buffer does. This also fixes the same
   missing wait on H2D for the non-dedup path.

2. Explicit --hicache-ratio/--hicache-size could pin past host memory

   Followers build an allocator-only MLA pool with no memory check and
   go straight on to the Mamba host pool, whose check reads live free
   memory while the leader is still pinning. With an explicit size there
   is no budget snapshot, so an oversized config could fail while pinning
   (or be killed) instead of with "Not enough host memory available".

   Every rank now waits on a gloo barrier over the TP CPU group before
   the Mamba pool is built. Followers block until all leaders have
   pinned, so the check sees real free memory. Gloo, not NCCL, since
   pinning can outlast the NCCL watchdog. No new process group.

3. GB200/GB300: the leader's pool was sized for two Graces

   A tray has two Graces, each its own NUMA node, and the scheduler is
   membind-ed to its GPU's node. The leader's budget is the whole tray's
   free memory, but it can only pin from one Grace, so the default
   auto-sized pool asked for about twice what that node can give.

   auto_size_hicache halves the per-rank budget when the flag is on and
   is_mnnvl_fabric_device() is true; the MIN all-reduce keeps every
   rank's ratio equal. Limits: Mamba host capacity is halved too, and an
   explicit ratio/size is not covered.

Not run: no GPU available, only checked with py_compile.

Co-Authored-By: Claude <[email protected]>

* fix(hicache): interleave the MLA leader's host pool over its NUMA nodes

The previous commit fixed GB200/GB300 by halving the auto-size budget.
That was wrong in two ways:

- auto_size_hicache overrides the global hicache_ratio, and the Mamba
  host pool reads the same value (MambaPoolHost in
  build_hybrid_mamba_stack), so Mamba host capacity was halved too.
- An explicit --hicache-ratio/--hicache-size never reaches
  auto_size_hicache, so the leader still pinned the whole tray's share
  on one Grace.

The real constraint is per NUMA node, not per host. With the same
ratio, the tray's total is unchanged by this feature; what changed is
that the leader, membind-ed to its GPU's node, pins every follower's
share there. A GB300 tray has two Graces, each its own node, so the
leader's node took twice its share.

Spread the leader's MLA host pool over the nodes its ranks are bound
to instead:

- build_for_node all-gathers each rank's NUMA node and cpuset-allowed
  nodes over the TP CPU group. The node comes from
  get_numa_node_if_available, the same query the launcher binds with.
- leader_host_shares derives the multiplier from that layout, not a
  constant. If the group spans several nodes, every rank is bound and
  the leader may allocate on all of them, the pool is interleaved over
  them and the multiplier is (fewest ranks on a node) x (node count):
  2 x 2 = 4 on a GB300 tray. Even interleave puts the same amount on
  every node, so this keeps each node at or below its own ranks'
  share. A group on one node, or with NUMA binding off, keeps the
  group size and is not interleaved. If the leader cannot reach every
  node, or binding is mixed, it falls back to the ranks on its own
  node. The minimum over all groups is used so every rank sizes its
  allocator the same.
- numa_utils.interleave_memory sets MPOL_INTERLEAVE on the calling
  thread for the leader's pool build only, then restores the previous
  policy, mode flags included. It must wrap the allocation: the HiCache
  mmap is pre-faulted, so mbind afterwards would not move the pages. It
  raises if the policy cannot be set, since the pool was sized for it.
- leader_budget_scope uses the same multiplier and enters the
  interleave scope.

With the same ratio, no NUMA node holds more host memory than without
the flag. Mamba is unchanged, explicit ratio/size and auto-sizing are
both covered, and KV cache capacity stays 4x on GB300. L3 reads stay
at one per tray.

Trade-off: the leader's H2D now reads half its pages from the other
node (Grace-Grace link on GB300, the socket link on dual-socket x86).
Dual-socket x86 hosts with binding on are interleaved too, with the
multiplier going from 4 to 8. Neither link's bandwidth was measured.
Not checked: whether the Mooncake/UMBP host allocators fault pages in
this process, which the policy needs.

The halving in hicache_auto_size.py is reverted.

Not run: no GPU available, only checked with py_compile; the multiplier
and nodemask logic were checked on GB300, single-NUMA, dual-socket,
uneven and restricted-cpuset layouts in isolation.

Co-Authored-By: Claude <[email protected]>

* feat(hicache): add shm mode for per-node MLA host copy

--enable-mla-hicache-per-node keeps one MLA KV HiCache host copy per node.
SGLANG_MLA_HICACHE_PER_NODE_MODE now selects how followers get the KV:

- broadcast (default): unchanged #72 behaviour. Followers keep an
  allocator-only host pool and the leader broadcasts each loaded layer
  over NCCL from the layer-wait hook.
- shm: the leader allocates the MLA host pool in a memfd (interleaved over
  the node's NUMA nodes by the existing leader_budget_scope) and sends the
  fd to same-host followers over an abstract Unix socket (SCM_RIGHTS).
  Every rank maps and pins the same pages and does its own H2D, so the
  forward path is the same as without the flag.

In both modes only the leader writes the shared copy: followers skip the
anchor D2H, use a page-get stub for L3 prefetch (the leader's count wins
through the existing all_reduce(MIN)), and do not register the buffer with
Mooncake. shm rejects --hicache-write-policy write_back at startup and on
attach-storage: write-back eviction syncs locally, so a follower could load
shared pages before the leader's D2H into them lands.

Also adds benchmark/hicache/bench_h2d_numa.py, which compares HiCache-style
page-gather H2D from one interleaved shared buffer against per-GPU private
local buffers, one process per GPU.

Not run: no GPU here; checked with py_compile, ruff and isort only.

* fix(hicache): tighten per-node MLA host sharing

Reject pipeline parallelism for per-node MLA HiCache and check mode agreement
on the WORLD CPU group before entering mode-specific collectives.

Close shared-buffer descriptors and bootstrap sockets on success and failure.
Derive the controller's follower role from the MLA host pool, skip unused
follower D2H staging, and avoid follower MLA existence queries while retaining
rank-sharded Mamba checks.

Add focused regression coverage, including cold/preloaded module identity
handling in the Mooncake fixtures.

Validation: Python compilation, formatting/import-order checks, no new Ruff
diagnostics, and isolated before/after source probes. Registered tests could
not collect because torch/msgspec are unavailable; GPU/distributed/Mooncake
integration remains untested.

* fix(hicache): bound the shm fd wait and guard one-shot setup

Three gaps in the per-node MLA HiCache startup path:

- A follower waited for the leader's shared host buffer with no timeout,
  so a stuck leader hung it forever. The wait now uses --dist-timeout,
  or 120 minutes (the gloo group default) when it is unset, and raises
  a RuntimeError that points at the leader's log.
- NodeSharedHostTensorAllocator closes its sockets after the first
  exchange, so a second allocate() raised IndexError on a follower and
  returned an unshared buffer on the leader. It now rejects a second
  call explicitly.
- In broadcast mode, the one-rank-per-node early return leaked the NCCL
  group it had just created. Every rank takes that return together, so
  each now destroys its own handle before returning.

Adds unit tests for all three.

Not run: torch is unavailable locally; checked with py_compile only.

Co-Authored-By: Claude <[email protected]>

* refactor(hicache): rework per-node MLA host sharing setup

Share one initialization path between broadcast and shm, replace the socket
handoff, fix L3 configuration at startup, and trim the feature to its
contracts.

- Both modes: the leader sizes a memfd without prefaulting it, followers
  reopen it via /proc/<pid>/fd/<fd>, each rank prefaults a contiguous
  page-aligned share with MADV_POPULATE_WRITE, and no rank registers before
  every share is populated. Broadcast followers then drop the mapping and
  keep dummy slot metadata. The leader's FD stays open until that fence;
  open and mapped-size failures abort every rank.
- Leave NUMA placement to deployment: remove the leader interleave, the NUMA
  benchmark and their helpers.
- With the flag on, reject runtime L3 attach/detach and policy updates.
  Reject at startup Mooncake standalone_storage, PD decode, DCP, stacks
  other than hybrid MLA + Mamba/KDA, and non-CUDA or FP4 MLA pools.
- Replace SGLANG_MLA_HICACHE_PER_NODE_MODE with
  --mla-hicache-per-node-mode {broadcast,shm}; drop the WORLD mode agreement.
- NodeSharedHostTensorAllocator takes this node's ranks and the cache group
  and derives its index, size and leader.
- Make host-pool parameters explicit and keep allocation fences in the
  assembler.
- Cover the hybrid MLA read waiting on its layer load.
- Trim tests to contract-level guards and comments to unstated contracts.

---------

Co-authored-by: yifei she <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Nozom1ff <[email protected]>
Co-authored-by: Zhengbo Wang <[email protected]>
Re-apply MLA host dedup onto the buffer-info MLA host pool (sgl-project#40917): the
pool keeps the owned target layers by filtering its MLABufferInfo, so the
existing per-layer slot maps, owned-layer load skip and all-layer backup
carry the rotation. Append the flag's positional slot after main's fields
(sgl-project#44991), and keep the dedup storage-attach guard next to the DCP L3 checks
(sgl-project#41187).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 4a328a4.

Approve preview

@nbommi19 nbommi19 changed the title [HiCache] MLA/DSA host dedup with rotating layer owners (opt-in) [Perf] hicache: MLA/DSA host dedup with rotating layer owners (opt-in) Oct 24, 2026
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, fix the PR title if the title check fails, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] @nbommi19, the relevant CI failure appears to be caused by this PR: https://github.com/sgl-project/sglang/actions/runs/40470954044/job/122082501569. Four base-a-test-cpu shards fail with AttributeError: 'HiCacheController' object has no attribute 'mla_dedup', raised from the new if self.mla_dedup is not None: checks in HiCacheController.attach_storage_backend and start_loading. The affected tests (test_hicache_file_lru_unit.py, test_hicache_storage_registration_hook.py, test_hicache_dcp_host_pool.py, test_sharded_dsa_hicache.py) build controllers without calling __init__. A class-level default such as mla_dedup = None on HiCacheController (or giving the test stubs that attribute) should fix them. Could you please fix it? Thanks!

…llers

Unit tests that build HiCacheController without __init__ (test_hicache_file_lru_unit,
test_hicache_storage_registration_hook, test_hicache_dcp_host_pool) failed with
AttributeError on the new mla_dedup checks in attach_storage_backend and
start_loading. Add a class-level None default, and give the SimpleNamespace stub
in test_sharded_dsa_hicache the same attribute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] @nbommi19, following up on my comment above: I pushed 79ebb5a to fix that CI failure. It adds a class-level mla_dedup = None default on HiCacheController, so controllers built without __init__ take the non-dedup path. It also adds mla_dedup=None to the SimpleNamespace stub in test_sharded_dsa_hicache.py. Feel free to revert it if you'd prefer a different fix.

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, fix the PR title if the title check fails, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

test_hicache_nixl_storage.py::TestNixlUnified::test_dsa_indexer_bounce_round_trip_preserves_every_byte
builds DSAIndexerPoolHost with a SimpleNamespace anchor host. This PR makes
DSAIndexerPoolHost read anchor_host.dedup_size (MLATokenToKVPoolHost defaults it
to 1), so the stub now needs the same field to take the non-dedup path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] @nbommi19, I pushed 689829d to fix the relevant CI failure https://github.com/sgl-project/sglang/actions/runs/40478066424/job/122115983374 with a small test-only change: test_hicache_nixl_storage.py::TestNixlUnified::test_dsa_indexer_bounce_round_trip_preserves_every_byte failed with AttributeError: 'types.SimpleNamespace' object has no attribute 'dedup_size' at pool_host/dsa.py:188. This PR makes DSAIndexerPoolHost read anchor_host.dedup_size (which MLATokenToKVPoolHost defaults to 1), so the test's SimpleNamespace anchor stub now sets dedup_size=1 to take the non-dedup path. Feel free to revert it if you'd prefer a different fix. I couldn't run the test locally because NIXL isn't installed here; CI will confirm.

@nvpohanh nvpohanh added the bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) label Oct 27, 2026
@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] @nbommi19, the relevant CI failure appears to be caused by this PR: https://github.com/sgl-project/sglang/actions/runs/40487266050/job/122238057509. The PR's new e2e test test/registered/hicache/test_hicache_mla_host_dedup.py fails in setUpClass because the server dies while building the MLA host pool: MLATokenToKVPoolHost._dedup_buffer_info (pool_host/mla.py:302) does buffer_info.data_ptrs[positions] on a CUDA uint64 tensor, which raises NotImplementedError: "index_cuda" not implemented for 'UInt64'. Selecting the per-layer pointers another way (for example, rebuilding the pointer table from the selected buffers, or indexing a CPU/int64 view) should fix it. Could you please fix it? Thanks!

luke396 pushed a commit to luke396/sglang that referenced this pull request Oct 28, 2026
MLA latent KV is identical on every TP rank, but each rank kept its own
HiCache host copy and read it from L3 on its own, so a 4-GPU node held
and fetched 4 copies of the same data.

With --enable-mla-hicache-per-node, only the first rank on each node
(leader) keeps a real MLA host pool and loads from L3; the other local
ranks use the allocator-only host pool from sgl-project#36800. During the forward,
the per-layer HiCache wait hook (as in sgl-project#42009) broadcasts each loaded
MLA layer from the leader to the local GPUs over NCCL/NVLink, so the
broadcast overlaps with compute. KDA/Mamba state, L3 keys and L3 layout
are unchanged, so existing L3 data stays valid.

The leader's host pool and budget are sized for the whole node; all
ranks size the allocator the same so the radix tree stays consistent.
PD decode, DCP, FP4 MLA and single-rank nodes fall back to per-rank
copies with a warning. The flag is off by default.

Co-Authored-By: Claude <[email protected]>
Nozom1ff pushed a commit to Nozom1ff/sglang that referenced this pull request Oct 29, 2026
MLA latent KV is identical on every TP rank, but each rank kept its own
HiCache host copy and read it from L3 on its own, so a 4-GPU node held
and fetched 4 copies of the same data.

With --enable-mla-hicache-per-node, only the first rank on each node
(leader) keeps a real MLA host pool and loads from L3; the other local
ranks use the allocator-only host pool from sgl-project#36800. During the forward,
the per-layer HiCache wait hook (as in sgl-project#42009) broadcasts each loaded
MLA layer from the leader to the local GPUs over NCCL/NVLink, so the
broadcast overlaps with compute. KDA/Mamba state, L3 keys and L3 layout
are unchanged, so existing L3 data stays valid.

The leader's host pool and budget are sized for the whole node; all
ranks size the allocator the same so the radix tree stays consistent.
PD decode, DCP, FP4 MLA and single-rank nodes fall back to per-rank
copies with a warning. The flag is off by default.

Co-Authored-By: Claude <[email protected]>
YAMY1234 and others added 3 commits December 1, 2026 17:16
Resolve conflicts in:
- python/sglang/srt/arg_groups/field_order.py
- python/sglang/srt/managers/cache_controller.py
- python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py
- python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py
- python/sglang/srt/mem_cache/pool_host/dsa.py
- python/sglang/srt/mem_cache/pool_host/mla.py
- test/registered/unit/mem_cache/test_hybrid_pool_assembler.py
- test/registered/unit/mem_cache/test_mla_host_dedup_primitives.py
- test/registered/unit/server_args/test_server_args.py

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflicts in:
- python/sglang/srt/arg_groups/field_order.py

Keep main parameter order and append the opt-in MLA host dedup field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) documentation Improvements or additions to documentation 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.

3 participants