Skip to content

[HiCache] Add MLA host-dedup primitives - #36800

Merged
hzh0425 merged 6 commits into
sgl-project:mainfrom
HZY-Wade:hzy/mla-host-dedup-primitives
Sep 8, 2026
Merged

hzh0425 merged 6 commits into
sgl-project:mainfrom
HZY-Wade:hzy/mla-host-dedup-primitives

Conversation

@HZY-Wade

@HZY-Wade HZY-Wade commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

MLA/DSA target KV is replicated across attention-TP ranks. Deduplicating the host copy needs two reusable building blocks before the feature can be wired into Unified HiCache: an allocator-only peer host pool and a dedicated layerwise NCCL broadcaster.

Changes

  • Add allocator-only MLA and DSA host-pool modes. The default remains is_dummy=False, so existing HiCache behavior is unchanged.
  • Add the dedicated attention-TP broadcaster, eligibility/storage checks and lifecycle context.
  • Prebuild both current HiCache storage synchronization-group sets to keep communicator creation order consistent.
  • Add SGLANG_MLA_DEDUP_CHUNK_TOKENS with a 2048-token default.
  • Add focused CPU unit tests for allocator metadata, staging reuse, chunk validation, NCCL warmup, DSA logical page order and cleanup.

This is the primitives-only extraction from #26691. It does not add a CLI flag or connect dedup to the scheduler/controller; those integration changes remain in #26691.

Validation

  • 9 passed, 2 skipped plus 2 subtests.
  • Full pre-commit checks passed.

Acknowledgments

We would like to thank the following contributors for their valuable contributions to the MLA Host Cache Deduplication work, including technical discussions, implementation feedback, compatibility validation, testing, and issue diagnosis:

Their contributions helped improve the correctness, robustness, performance, and production readiness of the implementation.


CI States

Latest PR Test (Base): ✅ Run #33937274000
Latest PR Test (Extra): ❌ Run #33937274041
Latest PR Test (AMD ROCm 7.2): ❌ Run #33937274108

@github-actions github-actions Bot added the hicache Hierarchical Caching for SGLang label Aug 28, 2026
@HZY-Wade
HZY-Wade force-pushed the hzy/mla-host-dedup-primitives branch 2 times, most recently from 5da2144 to 7d6130b Compare August 28, 2026 06:20
@HZY-Wade
HZY-Wade force-pushed the hzy/mla-host-dedup-primitives branch from 7d6130b to 54439ba Compare August 29, 2026 12:45
@hzh0425 hzh0425 self-assigned this Sep 1, 2026
@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 Sep 1, 2026
@HZY-Wade
HZY-Wade force-pushed the hzy/mla-host-dedup-primitives branch from 5ec6575 to a9a01d3 Compare September 1, 2026 05:56
@HZY-Wade

HZY-Wade commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@HZY-Wade

HZY-Wade commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@hzh0425
hzh0425 merged commit 8a0863c into sgl-project:main Sep 8, 2026
326 of 377 checks passed
rchalamala added a commit to modal-projects/sglang that referenced this pull request Sep 25, 2026
Add --enable-mla-hicache-host-dedup (requires --enable-hierarchical-cache,
--dcp-size=1, and L2-only or file storage; conflicts with
--enable-dsa-cache-layer-split) and extend the upstream MLA host-dedup
primitives with the opt-in gating layer: fail-closed support validation,
dummy-rank selection, node-aggregate host-budget estimation/enforcement
(SGLANG_HICACHE_HOST_BUDGET_GIB cap), build-time NCCL warmup pre-paying
the communicator's first-collective allocation (KV chunk plus full DSA
indexer staging), and optional CUDA-event trace instrumentation. The
sgl-project#36800 API (MLAHostDedupContext, env-sized chunks, page-aligned indexer
preparation) is preserved and extended, not replaced. The prebuilt
prefetch sync groups include the pipeline-parallel group, matching
HiCacheController._create_sync_groups. Indexer broadcasts skip layers
that reuse the previous layer's top-k (0-row placeholder buffers),
keeping collectives rank-aligned. HostPoolGroup gains the extra-pool
transfer split (load_extra_to_device_per_layer /
backup_extra_from_device_all_layer) as reserved group-level surface, and
DSAIndexerPoolHost tracks the anchor DCP placement.
nbommi19 added a commit to nbommi19/sglang that referenced this pull request Oct 13, 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]>
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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hicache Hierarchical Caching for SGLang run-ci CI: run the baseline test suite on this PR 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.

2 participants