Skip to content

[Fix] hicache: Include logical KV dtype in storage keys - #38362

Merged
ispobock merged 14 commits into
sgl-project:mainfrom
stmatengss:stmatengss/mooncake-kvcache-dtype-cb2a
Nov 14, 2026
Merged

ispobock merged 14 commits into
sgl-project:mainfrom
stmatengss:stmatengss/mooncake-kvcache-dtype-cb2a

Conversation

@stmatengss

@stmatengss stmatengss commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Two instances sharing a model name and storage backend can address the same cache objects even when their logical KV dtypes differ. BF16 versus FP16, or FP8 E4M3 versus E5M2, can therefore load incompatible bytes without reporting a miss.

Modifications

  • Append one resolved logical KV dtype to storage_model_name(), alongside the existing storage_format_tag. The controller reads the existing token KV device view's dtype, so E4M3 and E5M2 remain distinct even when both use uint8 backing buffers. Plain and routed device pools use the same path.
  • Raise a clear error when the dtype is missing or unresolved, including a literal auto; device views already carry the resolved dtype.
  • Keep the change in the shared model namespace. Mooncake, File, NIXL, EIC, and other model-keyed backends inherit isolation without changing tenants or requiring a newer Mooncake client. DCP/shard identity and unified chunk metadata remain intact.
  • No per-host-pool dtype API, layout/device-pool-info dtype fields, or NPU pool changes. The final diff contains seven files: controller logic, a File comment, documentation, and focused tests/fixture adjustments.
  • Cover cross-dtype File misses, same-dtype readback through fresh readers, preservation of format tags, and explicit failure for unresolved dtypes.

Existing untyped objects become cold and are repopulated under the new keys; there is no fallback to untyped objects. Other representation/layout differences still require distinct extra_backend_tag values where they are not already encoded.

Related work

This extends the shared model-namespace path used for host layouts in #44732. It overlaps #36420's model-keyed backend changes; the overlapping changes should be consolidated before merge. HF3FS does not use the model namespace and still needs its dedicated path/metadata-key change. This PR introduces no dtype-specific tenants for #44844's tenant-migration fallback.

Validation

On commit 49d8432cdc90ad60d32e14c0573bdbe894c4dbda, with Python 3.12 / PyTorch 2.14.1:

  • 54 tests passed: storage format/dtype tests plus all test_mooncake*.py suites.
  • 184 tests passed: hybrid pool assembly, TestDSAIndexerPoolInfo, declared parts, DCP hosts, unified keys, storage identity, and the complete HiCache L3 object-layout suite.
  • All applicable pre-commit hooks passed. The six focused storage-format tests also passed again after formatting.
  • The File regression fails with the original model-name implementation at the main merge-base dfaca5681d, reproducing key collisions for both ordinary and page-envelope storage. It passes with this fix.

238 tests passed locally. Tests ran on macOS with real CPU tensors and File IO, fake Mooncake clients, and a bounded host-memory budget/portable CPU allocation adapter for host-pool suites. The same-dtype File check uses a fresh backend reader; live server flush, distributed Mooncake, GPU inference, and model accuracy were not rerun locally. Hosted CI results must be checked against this new head; earlier-head results are not validation of this revision.

Speed Tests and Profiling

Not run. Dtype namespacing happens during storage configuration; the transfer path is unchanged.

Checklist

  • Format code with pre-commit.
  • Add and run regression tests.
  • Update documentation.
  • Run live GPU accuracy and performance benchmarks.

CI States

Latest PR Test (Base): ✅ Run #43162546242
Latest PR Test (Extra): ❌ Run #43162545981
Latest PR Test (AMD ROCm 10): ❌ Run #43162546053

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

Two SGLang instances sharing one Mooncake store with the same model
but different --kv-cache-dtype could reuse the wrong cache bytes.
Compose the logical device dtype into Mooncake tenant_id instead of
prefixing object keys, and require mooncake-transfer-engine>=0.3.12.

Co-authored-by: Teng Ma <[email protected]>
@cursor
cursor Bot force-pushed the stmatengss/mooncake-kvcache-dtype-cb2a branch from 2c7831e to 60d307e Compare October 11, 2026 16:04
stmatengss and others added 3 commits October 12, 2026 01:00
Preserve per-rank SSD offload directories alongside the shared tenant-aware setup helper. Adapt the dtype regression fixture to the current storage host-pool format interface.

Validation: all 42 Mooncake CPU unit tests and pre-commit checks on the six PR files passed. Live Mooncake and GPU integration tests were not run.
Signed-off-by: Teng Ma <[email protected]>
Reuse the existing Mooncake setup and tenant compatibility paths instead of refactoring KV and embedding initialization. Keep the shared logical-dtype config field and a single tenant composition helper. Consolidate dtype regressions into the existing tenant test fixture and shorten the documentation.

Validation: 38 Mooncake CPU unit tests and pre-commit on all five PR files passed. Live Mooncake and GPU tests were not run.
Signed-off-by: Teng Ma <[email protected]>
dp_rank=dp_rank,
extra_config=storage_backend_extra_config,
# Host buffers may store different FP8 formats as uint8 bytes.
kv_cache_dtype=str(self.mem_pool_device.dtype).removeprefix("torch."),

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.

which data type should we refer exactly when we are talking about dtype? Isn't host memory type aligned with the storage exactly? Would using device type cause confusion?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Here dtype means the logical KV-cache encoding. The host pool uses device_pool.store_dtype, which is uint8 for both E4M3 and E5M2. mem_pool_device.dtype preserves that distinction, and the bytes are copied unchanged to Mooncake. It represents the KV-cache format, not the model’s compute dtype.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fix it in the latest commit

"Please upgrade Mooncake to use non-default "
"Mooncake tenants with SGLang."
"Upgrade with: pip install -U "
"'mooncake-transfer-engine>=0.3.12'."

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Why we need mooncake-transfer-engine>=0.3.12

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.

+1

@stmatengss stmatengss added the run-ci-extra CI: also run the extra suite (requires run-ci) label Oct 14, 2026
@stmatengss stmatengss changed the title [HiCache] Isolate Mooncake KV objects by kv_cache_dtype via tenant_id [Fix] hicache: Isolate Mooncake KV objects by storage dtype via tenant_id Oct 14, 2026
stmatengss and others added 3 commits October 29, 2026 18:15
Resolve the host-pool import conflicts with the current host-memory
preflight helper. Carry the mirrored K/V store and value dtypes on
page-envelope layouts so tenant isolation still applies after host
construction moved off the device pool.

Co-authored-by: Teng Ma <[email protected]>

@xiezhq-hermann xiezhq-hermann 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 @stmatengss for keeping this up to date, and sorry for the slow design answer. The bug is real on current main. Take two instances with the same model name (and extra_backend_tag) but different persisted KV dtypes: bf16 vs fp16, or fp8 e4m3 vs e5m2 (both stored as uint8). They get the same Mooncake key and tenant. _batch_postprocess counts any positive read as a hit, so the second instance can load pages in the wrong format and nothing reports an error. Your host-side get_storage_dtype() / value_dtype plumbing is the right answer to "which dtype is actually persisted", and I'd like to keep it.

I don't think tenant_id is the right place for it, though:

  1. It doesn't isolate anything with a default master. Tenants only separate objects when the master runs with --enable_multi_tenants=true and a quota policy that registers every composed tenant. With multi-tenancy off, Mooncake ignores the request tenant and everything stays in the default namespace (see the note in the Mooncake README). So the most common setup still collides.
  2. It breaks existing deployments. The default tenant becomes dtype_<x>, so in embedded mode setup() now receives tenant_id for every MHA/MLA host pool, and a client without that parameter fails at startup. I checked this on fd511a8 with a stub client whose setup() rejects tenant_id: main starts, and this branch raises the new >=0.3.12 RuntimeError. The AMD wheel still pins mooncake-transfer-engine-non-cuda==0.3.8.post1. Existing multi-tenant quota policies would also have to register <tenant>_dtype_*. Standalone mooncake_clients would need a restart with the composed --tenant_id, and nothing checks that they match: the branch only logs a warning at startup.
  3. It covers Mooncake only. File, HF3FS, NIXL, EIC and the other backends have the same gap. See the TODO in HiCacheFile._init_config_suffix and the "KV format and host layout are not yet in the keys" note in the Mooncake README.
  4. Existing objects go cold anyway (which is why #44844 exists), so keeping the object keys unchanged doesn't make migration any easier.

Could you move the persisted dtype into the backend-agnostic storage key instead? For example, storage_model_name() could append get_storage_dtype() next to storage_format_tag. That is the same path #44732 uses for host layouts, and the unified key scheme already carries the logical dtype in KVCacheNamespace. Then the tenant composition, the >=0.3.12 requirement (which also settles the open question in the review thread) and the README section can all go. Every backend that keys on the model name (Mooncake, File, NIXL, EIC, ...) would get the fix with no master configuration, at the cost of one cold-cache warmup, the same cost #44732 accepts. HF3FS doesn't key on the model name today, so it needs its own change either way. #36420 instead adds the dtype to each backend's keys directly (File, NIXL, EIC, HF3FS and Mooncake); please coordinate so that the dtype plumbing lands only once. Once the dtype is in the key, #44844 should no longer be needed.

Two more things on the current head:

  • base-a-test-cpu is red on fd511a8 because of this change. Test stubs built with object.__new__ / SimpleNamespace have no .dtype or get_storage_dtype(). Locally on fd511a8 these fail; all of them pass on main:
    • test_hybrid_pool_assembler.py, 18 tests: 'DSATokenToKVPool' / 'MLATokenToKVPool' object has no attribute 'dtype'.
    • test_mem_pool_host.py::TestDSAIndexerPoolInfo, 4 tests: the same error.
    • kv/test_declared_parts.py::test_file_cache_keeps_rank_local_draft_inside_mla_pages: the stub sets the class UnifiedPageEnvelopeHostPool as storage_host_pool, so get_storage_dtype() is called unbound.
    • test_hicache_l3_object_layout.py::test_deepseek_v4_uses_rank_replicated_storage_config.
  • UnifiedPageEnvelopeHostPool.get_storage_dtype() falls back to uint8 when the layout doesn't carry store_dtype / value_dtype, which puts e4m3 and e5m2 back in the same namespace. I'd rather a missing pair fail loudly; the same applies to getattr(storage_config, "kv_cache_dtype", None).

cc @alphabetc1 (#44844) @wuhangxian (#36420)

@stmatengss stmatengss changed the title [Fix] hicache: Isolate Mooncake KV objects by storage dtype via tenant_id [Fix] hicache: Include persisted KV dtype in storage keys Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @xiezhq-hermann for the detailed review. Updated in 7f2efb2ccd.

  • Moved the persisted dtype into storage_model_name(), alongside storage_format_tag. Model-keyed backends (Mooncake, File, NIXL, EIC, etc.) now inherit the isolation through the shared path, including with a default Mooncake master.
  • Kept the host-side get_storage_dtype() / value_dtype plumbing, including distinct E4M3, E5M2 and E4M3FNUZ encodings for raw uint8 buffers. Page envelopes now raise an explicit error when the encoding metadata is missing.
  • Removed dtype-specific tenant composition, the >=0.3.12 requirement introduced by this PR, and the composed-tenant standalone warning/documentation. Configured tenants retain their existing behavior. The separate HiCacheStorageConfig.kv_cache_dtype field and its permissive getattr fallback are also gone.
  • Fixed the incomplete test fixtures you identified in hybrid pool assembly, TestDSAIndexerPoolInfo, declared-parts File storage, and the DeepSeek V4 L3 layout test.

Existing objects become cold under the new keys; there is no fallback to untyped objects. I also updated the PR title/body and documented the overlap with #36420: this PR supplies the shared host-dtype/model-key path, while HF3FS still needs its dedicated file/metadata-key change. The overlapping plumbing should be consolidated before merge. This version introduces no dtype-specific tenants for #44844's proposed tenant-migration fallback.

Validation on this commit:

Local CPU coverage Result
Storage dtype/format and all Mooncake unit suites 61 passed
Hybrid pool assembly, DSA host info, declared parts, DCP hosts, unified keys and storage identity 158 passed
Complete HiCache L3 object-layout suite 26 passed

That is 245 tests passed, plus all applicable pre-commit checks. The new regressions were also run against pre-fix fd511a817a: File key collisions, acceptance of missing envelope metadata, and default/explicit Mooncake tenant incompatibility reproduced there and pass with this change.

Local tests used Python 3.12 / PyTorch 2.14.1 on macOS, real CPU tensors/File IO, fake Mooncake clients, and a bounded host-memory budget with a portable CPU allocation adapter for the host-pool suites. They do not establish live distributed Mooncake or GPU model-accuracy validation.

Hosted CI has now passed all 10 base-a-test-cpu partitions in the Base run, and lint passed. Overall CI is not fully green yet: NPU/MLX jobs have failures, opt-in gates report missing labels, and other jobs remain queued/running.

@xiezhq-hermann

Copy link
Copy Markdown
Collaborator

Thanks @stmatengss for the quick and thorough rework, and sorry: I'm going to walk back part of what I asked for on 11-09. Seeing the result, threading a per-pool get_storage_dtype() through every host pool type and the page-envelope layout (14 production files, plus the NPU pool) is more surface than this case justifies. The collision only happens when two deployments with the same model name but different KV dtypes share one store, and a single server-level value is enough to tell them apart.

Could you shrink it to this?

  • In storage_model_name(), append the server's resolved logical KV cache dtype: one value per server, e.g. the device KV pool's dtype (which already distinguishes float8_e4m3fn from float8_e5m2, both stored as uint8), or the resolved --kv-cache-dtype with auto mapped to the model dtype.
  • Drop the get_storage_dtype() methods, the layout / device_pool_info dtype fields and the NPU change.
  • Keep failing loudly if the value can't be resolved, and keep a focused test: bf16 vs fp16 and e4m3 vs e5m2 give different names, the same dtype gives the same name.

The Mooncake-side cleanup you already did (no tenant composition, no version requirement) can stay as it is. The end-to-end behaviour I verified on 7f2efb2 (instances with different dtypes sharing one File store don't hit each other's pages, and the same dtype still hits after a flush) is what the smaller version should keep. Sorry for the churn.

@stmatengss stmatengss changed the title [Fix] hicache: Include persisted KV dtype in storage keys [Fix] hicache: Include logical KV dtype in storage keys Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@xiezhq-hermann Updated in 49d8432cdc following your latest suggestion.

  • storage_model_name() now takes one resolved logical KV dtype from the existing device token-KV view. E4M3/E5M2 remain distinct despite their shared uint8 backing type; missing or unresolved values raise a clear error.
  • Removed all get_storage_dtype() methods, added layout/device_pool_info fields, and NPU changes, together with their now-unnecessary test fixtures. The full PR is down from 23 files to 7 files.
  • Kept the Mooncake cleanup: no dtype-specific tenant composition or added client-version requirement. Format tags and the shared backend model-key path are preserved.

Validation on this revision: 238 local CPU tests passed (54 storage-format/Mooncake tests + 184 related host-pool, DCP, unified-key, storage-identity and L3-layout tests), and all applicable pre-commit hooks passed. The focused File test verifies BF16/FP16 and E4M3/E5M2 isolation plus same-dtype persisted-byte readback through fresh readers. It reproduces collisions with the original main model-name implementation and passes with this revision. Plain/routed controller paths and missing/unresolved dtype errors are covered too.

These are macOS CPU tests with real File IO, fake Mooncake clients, and a bounded portable allocation adapter for host-pool tests. I have not rerun the live server flush/GPU experiment you described; the local same-dtype check uses a fresh backend reader. New-head hosted CI is still in progress. The Extra/AMD Extra/MLU gate logs currently report missing opt-in labels (run-ci-nv-extra, run-ci-amd-extra, run-ci-mlu), so I am not claiming full CI completion.

@stmatengss

Copy link
Copy Markdown
Collaborator Author

Let me double-check all these changes

@alphabetc1

Copy link
Copy Markdown
Collaborator

/rerun-test -c

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🚀 ubuntu-latest (4 tests): ✅ View workflow run

cd test/ && python3 registered/hicache/test_hicache_l3_object_layout.py  # base-a
cd test/ && python3 registered/unit/mem_cache/test_hicache_dcp_host_pool.py  # base-a
cd test/ && python3 registered/unit/mem_cache/test_hicache_storage_format_tag.py  # base-a
cd test/ && python3 registered/unit/mem_cache/test_hicache_unified_key_scheme.py  # base-a

@ispobock
ispobock merged commit a05c729 into sgl-project:main Nov 14, 2026
207 of 217 checks passed
Ifelseer pushed a commit to Ifelseer/sglang that referenced this pull request Nov 22, 2026
Two servers sharing the same HiCache file backend directory can silently
reuse each other's KV pages whenever the key does not distinguish the
page layout. The original report (sgl-project#51045) covers one flavour: same
model, same dtype, page layout differing. fp16 and bf16 pages are the
same size, so nothing rejects the stale key, and the reader applies
KV values written under a different layout -- returning clearly
corrupt text with HTTP 200.

The dtype half of the bug was fixed by sgl-project#38362 by folding the logical
KV dtype into the storage namespace (via storage_model_name). The
remaining gap is layout: HiCacheStorageConfig.is_page_first_layout
describes the byte order within a page, and the file backend's
config_suffix does not yet include it. hicache_storage.py's TODO
already noted that "Other layout differences still need
extra_backend_tag", and while simm / mooncake / umbp / npu_memcache
honor that key, HiCacheFile does not.

Fold the layout tag and the user-supplied extra_backend_tag into
the per-rank file suffix, between the pp sharding markers and the
CP sharding markers. The position keeps CP rank/size as the trailing
portion of the suffix so existing endswith assertions stay valid.

The tag format is intentionally short: `_page1st` for page-first
layout, `_bkt<tag>` for the extra_backend_tag passthrough. The
suffix is on the filename, not on the metadata channel, so the
tag has to be grep-friendly and short.

Tests cover the four namespaces produced by the (layout, extra_tag)
matrix and assert they are pairwise disjoint. The lru_file_evictor
only manages files under the current suffixes, so files written
under a previous layout stay on disk; operators migrating a shared
directory need to purge or rotate it instead of expecting the new
key to overwrite the old one. This is documented in the comment
above the suffix write.

Fixes: sgl-project#51045
dg1kjd added a commit to dg1kjd/sglang-sxm2 that referenced this pull request Dec 1, 2026
… level 2 follows upstream PR 52724.

Qwen3.8-Flash-Next disk tier: the previous release said the serve script
empties the host cache's disk tier once when the weights change. It did
not. Since upstream sgl-project/sglang#38362 the page files carry the KV
dtype in their names (_<served name>-dtype_<dtype>_<rank>_<tp>.bin), and
the script's file pattern matched none of them. So after a switch to the
QAD checkpoint, pages computed with the previous weights stayed, and an
engine could load them when a prompt prefix matched. The pattern now
matches both name forms, and the page epoch is 3: the first launch after
this update removes this model's pages once, whatever wrote them, and
recomputes them on demand.

Hybrid cache level 2 (models with linear-attention layers:
Qwen3.8-Flash-Next, GLM-5.3-Flash, SenseNova-Loop-9B): the prompt-end fix
from the previous release is replaced by upstream sgl-project/sglang#52724
(Ruilin Gao), which covers both of its cases. One difference: a prompt
whose last chunk is a single 64-token step (k x 4096 + 64 tokens) now
resumes at the end of the previous chunk instead of being recomputed.
Checked on Qwen3.8-Flash-Next with the same weights as the previous
release: the other resume points, the 24-turn agent loop at 32K (23 of 23
turns resume at the previous prompt end), sibling sessions sharing a 6K
preamble and the repeat check are unchanged. The state kept for such a
prompt gives bit-identical greedy tokens and logprobs to a resume from an
ordinary prompt end at the same depth. Upstream's slot-lease unit test
expects no state from a complete prompt and fails on the PR; ours expects
the prompt-end state.

GLM-5.3-Flash docs: the first tool turn after a cold 190K-token prompt
takes 0.82 s.

Greedy decode (merge_sorted, tok/s): GLM-5.3-Flash 206.0 (205.9),
SenseNova-Loop-9B 70.2 (70.2); the repeat check's output is unchanged on
both.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation hicache Hierarchical Caching for SGLang memory-pool mooncake npu 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.

6 participants