Skip to content

[TRTLLM-17229][feat] Extend the mixed-precision KV cache to speculative decoding and the sparse MLA backends - #21021

Merged
Hudayday merged 138 commits into
NVIDIA:mainfrom
Hudayday:kvcm-mixed-precision-sparse-managers-20261022
Nov 4, 2026
Merged

Hudayday merged 138 commits into
NVIDIA:mainfrom
Hudayday:kvcm-mixed-precision-sparse-managers-20261022

Conversation

@Hudayday

@Hudayday Hudayday commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Description

PR #20452 added the First-N/Last-N mixed-precision KV cache for the standard
KVCacheManagerV2: every full-attention layer stores its history in NVFP4,
the first mixed_precision_first_n and last mixed_precision_last_n tokens
stay in the attention dtype in a retained-token twin layer, and attention runs
on a staging copy. It rejected speculative decoding, the hybrid Mamba manager
and every sparse-attention backend. This PR lifts those three limits.

Speculative decoding (MTP, NGram, Eagle one-model).
We modified it so that the draft KV dtype depends on the kind of drafter:

  • MTP layers in the target manager (e.g. with attention DP): they are target-shaped attention layers, so they go mixed like the target. On dsa/deepseek_v4 that means the backend's NVFP4 pool plus fp8 first_n/last_n twins. DeepSeek-V4's MTP layer is sliding-window only, so it keeps no twin.
  • MTP layers in a separate draft manager (the default without attention DP): the draft kv_cache_config keeps the mixed dtype, so the draft manager builds its own twins. For the draft forward, the DSA and dense metadata swap in the draft manager's twin page table or staging copy.
  • Replacement MTP heads: they keep the target's KV dtype, so they go mixed as well.
  • Drafters with their own architecture (Eagle3, DFlash, external drafters): they keep a plain cache, because the draft kv_cache_config drops the mixed dtype. On dsa/deepseek_v4 their KV no longer inherits the target's NVFP4. It follows the retained dtype instead: fp8, or unquantized when the retained dtype is float16/bfloat16.
  • A model that sets draft_kv_cache_quant_algo_override (e.g. MiniMax-M3): the override still wins in every case.

Hybrid Mamba manager (Qwen3.5, Kimi-K3). A manager class opts in with
_supports_mixed_precision_kv; the hybrid manager appends the retained-token
layer group after its recurrent-state and attention layers and keeps the new
layer ids out of its Mamba layer mask. No kernel changes: these models use the
existing staging path.

image

Sparse MLA backends (GLM-5.2 DSA, DeepSeek-V4). These backends keep their
history in a native NVFP4 pool and already dequantize the rows their top-k
selected into an FP8 scratch before attention, so they get no staging copy.
The manager keeps the NVFP4 pool as the low-precision pool and appends the
retained-token twin in the high-precision dtype next to it (one twin per
compressed-history layer on DeepSeek-V4, keyed by compression ratio).

  • Write side: the DSA append and generation RoPE paths store each new row in
    the twin through a small Triton row-store kernel driven by the twin's page
    table; the DeepSeek-V4 compressor writes the twin with a second call of the
    native compressor_postprocess_scatter, with the twin's page table and a
    row mask that excludes pages the twin does not hold.
  • Read side: after the backend's gather, overlay_retained_rows copies the
    twin's rows over the dequantized scratch rows of the retained tokens, so the
    attention kernels and the NVFP4 path are unchanged.
  • Indexer caches are not touched. DeepSeek-V4.1 (CSA2) is not supported: its
    pool format is natively NVFP4.

Public options are unchanged (kv_cache_config.dtype=mixed_nvfp4_<dtype>,
mixed_precision_first_n, mixed_precision_last_n). The sparse-attention and
speculative-decoding rejections in validate_mixed_precision_kv are removed,
the KV cache doc lists the supported managers, and the retained-dtype unit
test's model-config stand-in gains the sparse_attention_config attribute the
loader now reads.

Follow-up (not in this PR): fold the overlay into the native NVFP4 gather
kernels so the read side needs no extra kernel.

Test Coverage

Unit tests: tests/unittest/_torch/attention/test_mixed_precision_backends.py
(speculative configs accepted except dynamic tree, one-model draft manager
keeps a plain dtype, staging lengths follow the device-side KV-length
correction on both backends, DeepSeek-V4 retained-row mask),
tests/unittest/_torch/executor/kv_cache/test_mixed_precision_kv_cache.py
(appended draft layers stay native),
tests/unittest/_torch/executor/kv_cache/test_mamba_cache_manager.py (hybrid
manager appends the retained group; page tables).

Dev Engineer Review

The change extends mixed-precision KV caching to supported speculative decoding, hybrid Mamba managers, and sparse MLA backends. Sparse backends retain selected rows in higher precision and overlay them on gathered NVFP4 history. Dynamic-tree drafting and DeepSeek-V4.1 (CSA2) remain unsupported.

Verify retained-row indexing, page-table mappings, dtype scaling, and sparse context and generation overlays. Also verify staging-length corrections, draft-layer dtype, and hybrid-manager layer placement. Test execution results were not supplied.

QA Engineer Review

Three test files changed:

  • test_mixed_precision_backends.py adds coverage for speculative configurations, draft-cache configuration, staging-length corrections, and retained-row behavior during sparse draft forwards.
  • test_mixed_precision_kv_cache.py adds test_appended_draft_layers_stay_native, which checks that appended draft layers retain their native dtype.
  • test_mamba_cache_manager.py adds test_v2_hybrid_mixed_precision_appends_retained_group, which checks retained-layer mapping, buffers, page-table entries, and cache validity.

test_mixed_precision_kv_cache.py is listed in tests/integration/test_lists/test-db/l0_b200.yml. The CI list includes a different test from test_mamba_cache_manager.py, not the added mixed-precision test. The backend test file is not listed in the inspected CI or manual-QA lists. test_mixed_precision_retained_dtype_must_match_model_dtype is marked SKIP in tests/integration/test_lists/waives.txt.

Coverage verdict: needs follow-up. The supplied test summary does not establish dedicated numerical coverage of sparse retained-row writes and overlays. Test execution results are unavailable.

Per-File QA Perspective

Source files

  • docs/source/features/kvcache.md — Verify documented manager and backend requirements and compatibility limits against runtime behavior.
  • tensorrt_llm/_torch/attention/backends/flashinfer.py — Verify speculative-decoding offsets update staging lengths only for the active cache manager.
  • tensorrt_llm/_torch/attention/backends/interface.py — Verify staging views are hidden when uninitialized, missing the requested layer, or associated with another manager.
  • tensorrt_llm/_torch/attention/backends/sparse/deepseek_v4/backend.py — Verify retained rows overlay gathered rows on generation and context/mixed-input paths.
  • tensorrt_llm/_torch/attention/backends/sparse/deepseek_v4/cache_manager.py — Verify retained twin-layer page size, window, sink count, reuse policy, and speculative-layer cutoff.
  • tensorrt_llm/_torch/attention/backends/sparse/deepseek_v4/compressor.py — Verify eligible compressed rows are stored and indexer compressors remain unchanged.
  • tensorrt_llm/_torch/attention/backends/sparse/deepseek_v4/metadata.py — Verify retained page tables map to the correct high-precision layers and are cleared for draft preparation.
  • tensorrt_llm/_torch/attention/backends/sparse/dsa/backend.py — Verify context and generation overlays use the correct request and index inputs.
  • tensorrt_llm/_torch/attention/backends/sparse/dsa/cache_manager.py — Verify mixed-precision opt-in preserves the native NVFP4 pool.
  • tensorrt_llm/_torch/attention/backends/sparse/dsa/metadata.py — Verify retained page tables and context positions are prepared only when high-precision layers exist.
  • tensorrt_llm/_torch/attention/backends/sparse/dsa/module.py — Verify context appends store retained rows after the paged cache append.
  • tensorrt_llm/_torch/attention/backends/sparse/mixed_precision_retained_rows.py — Verify retained-row writes, overlays, scaling, and masking when pools or retained pages are unavailable.
  • tensorrt_llm/_torch/attention/backends/trtllm.py — Verify staging lengths refresh from corrected KV lengths only for the active manager.
  • tensorrt_llm/_torch/attention/mla.py — Verify generation stores retained rows after the fused RoPE/cache-update path.
  • tensorrt_llm/_torch/pyexecutor/_util.py — Verify one-model draft-cache configurations select fp8 for FP8 targets and auto otherwise.
  • tensorrt_llm/_torch/pyexecutor/kv_cache/kv_cache_manager_v2.py — Verify manager opt-in, native NVFP4 storage, draft-layer exclusion, retained-pool initialization, and page-table filling.
  • tensorrt_llm/_torch/pyexecutor/kv_cache/mamba_cache_manager.py — Verify hybrid-manager opt-in preserves Mamba layer masking and forwards buffer options.
  • tensorrt_llm/_torch/pyexecutor/model_loader.py — Verify mixed cache requests map to NVFP4 for sparse DSA and DeepSeek-V4 without changing other dtype mappings.
  • tensorrt_llm/llmapi/llm_args.py — Verify supported speculative and sparse configurations are accepted while dynamic-tree speculation and other documented restrictions remain rejected.

Test files

  • tests/unittest/_torch/attention/test_mixed_precision_backends.py — Covers speculative configuration, draft-cache behavior, retained-row draft masking, and staging-length updates. It is absent from the inspected CI and manual-QA lists; one test is marked skipped in waives.txt.
  • tests/unittest/_torch/executor/kv_cache/test_mixed_precision_kv_cache.py — Checks appended draft-layer dtype and mixed-precision cache behavior. The file is listed in tests/integration/test_lists/test-db/l0_b200.yml.
  • tests/unittest/_torch/executor/kv_cache/test_mamba_cache_manager.py — Checks hybrid-manager retained-layer mapping, buffers, page table, and cache validity. The inspected CI list includes a different test from this file, not the added mixed-precision test.

Keep full history and First/Last storage in REQUIRED lifecycle groups. Reuse native matching, commits, offload and eviction without new C++ state or a separate replay policy. Stage a standard paged cache for TRTLLM and FlashInfer, and write new KV to both pools. Leave high windows to the raw-copy cold codec.

Signed-off-by: tianruih <[email protected]>
Reuse existing dtype layout accounting and native SWA policy. Leave recurrent and existing window state unchanged. Keep shared Attention input preparation beside the backends; remove the redundant view type, cold-page extension and draft documentation.

Signed-off-by: tianruih <[email protected]>
Reuse existing dtype layout accounting and native SWA policy. Leave recurrent and existing window state unchanged. Keep shared Attention input preparation beside the backends; remove the redundant view type, cold-page extension and draft documentation.

Signed-off-by: tianruih <[email protected]>
Materialize native KV directly from the paged high or low/scales pools and
quantize all new tokens directly back into low/scales and retained high pages.
Reuse FlashInfer block quantizers and CUTLASS conversion/copy primitives in
the kernel directory. Remove four copy kernels and six codec workspaces.
Attention dtype, quantization configuration, fusion, and FMHA dispatch stay
on the existing native path.

Validate 24 dtype/layout/stride/KV-factor cases with strict whole-pool byte
checks and CUDA Graph replays changing page tables and lengths. Six focused
source tests also pass through standalone kernel loading; the installed
native binding lacks PoolRebalanceConfig, so full backend tests are pending.

The FP8 codec matches FlashInfer's public CuTe quantizer. Compared with the
native CUDA quantizer, all observed differences are exact FP4 midpoints with
equal minimum quantization error caused by reciprocal evaluation order.
Keep the existing codec rather than introduce another rounding implementation.
FlashInfer PR 3387 is related precision work, not a confirmed fix for this case.

Signed-off-by: tianruih <[email protected]>
- An explicit max_tokens is converted to a quota that also pays for the
  mixed-precision high layers, in the base manager (dense, hybrid, DSA) and
  in DeepSeek-V4's own conversion; the low pool no longer ends up far below
  max_tokens.
- The target/draft split, when it weighs per-request spend, prices a mixed
  full-attention layer as its NVFP4 history plus a first/last-token window the
  fixed cost already funds, as the per-token cost does.
- pool_ratio counts the mixed-precision high group only when it is a group of
  its own: with no sink and the retained window of a sliding-window layer, the
  high layers join that group.
- Reject mixed-precision KV on DSA and DeepSeek-V4 where NVFP4 sparse MLA is
  unavailable (SM107), instead of falling back to FP8 with an unread high pool.
- Tests: the draft staging lengths inside a CUDA graph, staging that covers
  the allocated capacity, and the DSA mixed-precision high page table.
- The DSA generation store test checks where each row lands and that k_pe is
  rotated, instead of comparing against a RoPE reference.

Signed-off-by: tianruih <[email protected]>
@Hudayday
Hudayday requested a review from a team as a code owner November 2, 2026 11:53
…lass hook and trim the PR

- Disaggregated transfer and KV cache sharing name every layer through
  get_disagg_global_layer_ids, which KVCacheManagerV2 sets whenever
  mixed-precision KV is on, also on a pipeline rank without mixed-precision
  layers: each layer gets twice the id it has without mixed-precision KV, and
  the mixed-precision high layer of model layer L gets 2L + 1. The
  disaggregation and KV cache sharing modules and their tests are back to main.
- Remove the pool-sizing changes of the previous commit (max_tokens quota,
  per-request pricing of the target/draft split, pool_ratio group counting)
  and the peer setting check; keep the fixes for crashes and silently wrong
  results, and the startup rejections (sleep_config, qwen4_exp, SM107).
- Simplify without changing behavior: one mixed-precision high row store for
  context and generation, one lookup for a layer's mixed-precision high pool
  and page table, the compressed-row mask launched inline, a class attribute
  for mixed-precision support, no wrapper for the mixed-precision high page
  table, and no guards for staging states that cannot occur.
- Follow the coding guidelines: Google-style docstrings for helpers called
  from other files, single backticks, plain-English comments, `X | None`.
- Tests stay functional and cover MTP (in the target manager, a separate
  draft manager, CUDA graph, overlap-scheduler corrections), Eagle3, DSA,
  DeepSeek-V4, the hybrid managers, the disaggregated layer ids and the
  startup rejections. Drop the tests that compared kernel output values
  (high row stores, overlay, compressed-row mask) and the checks of the
  removed pool sizing.

Signed-off-by: tianruih <[email protected]>
@Hudayday

Hudayday commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82026 [ run ] triggered by Bot. Commit: 3589699 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82026 [ run ] completed with state FAILURE. Commit: 3589699
/LLM/main/L0_MergeRequest_PR pipeline #67665 completed with status: 'UNSTABLE'

CI Report

⚠️ Multi-GPU Label Required:
Multi-GPU tests require the ci: full pre-merge approved label on this PR. Either:

  • Wait for the PR to be fully approved — the label is added automatically once approval is complete. Having unresolved open comments is fine, or
  • If needed, ask a member of NVIDIA/trt-llm-ci-approvers to add the label manually.
    Then re-trigger CI with the same bot command (no rebase needed).

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

…layer record

- KVCacheManagerV2 already records which of its layers belong to a drafter;
  under a layer_mask it now finds them too, from the model config's layer
  count. Mixed-precision KV keeps the layers that a drafter other than MTP
  adds to the manager on a plain cache through this record, instead of a
  separate first-drafter-layer check. The error for a missing
  pretrained_config goes away: every caller that can enable mixed-precision
  KV passes it.
- Rename _mixed_precision_native_pool to _own_pool_is_mixed_precision_low.

Signed-off-by: tianruih <[email protected]>
@Hudayday

Hudayday commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82174 [ run ] triggered by Bot. Commit: 959caf5 Link to invocation

- Find the plain draft layers, and so read the speculative decoding mode,
  only when mixed-precision KV is on, as before; managers without it never
  needed the mode and their test stand-ins do not provide it.
- Comments and test names follow the draft-layer record and the renamed
  flag; the custom-manager test says a subclass must opt in.

Signed-off-by: tianruih <[email protected]>
@Hudayday

Hudayday commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements.

@Hudayday
Hudayday enabled auto-merge (squash) November 3, 2026 04:33
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82190 [ run ] triggered by Bot. Commit: fc3f08f Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82174 [ run ] completed with state ABORTED. Commit: 959caf5

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82190 [ run ] completed with state SUCCESS. Commit: fc3f08f
/LLM/main/L0_MergeRequest_PR pipeline #67820 completed with status: 'UNSTABLE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

@Hudayday

Hudayday commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82302 [ run ] triggered by Bot. Commit: fc3f08f Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #82302 [ run ] completed with state SUCCESS. Commit: fc3f08f
/LLM/main/L0_MergeRequest_PR pipeline #67923 completed with status: 'SUCCESS'

CI Report

Link to invocation

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

Labels

api-compatible Accepted LLM API contract change that is backwards-compatible ci: full pre-merge approved

Projects

None yet

Development

Successfully merging this pull request may close these issues.