Skip to content

[HiCache] feat: add draft KV cache backing for L2/L3#21125

Merged
xiezhq-hermann merged 17 commits intosgl-project:mainfrom
alphabetc1:feat/hicache_spec_2
Apr 29, 2026
Merged

[HiCache] feat: add draft KV cache backing for L2/L3#21125
xiezhq-hermann merged 17 commits intosgl-project:mainfrom
alphabetc1:feat/hicache_spec_2

Conversation

@alphabetc1
Copy link
Copy Markdown
Collaborator

@alphabetc1 alphabetc1 commented Mar 22, 2026

Motivation

see #16964

Root Cause

In speculative decoding, the draft and target models share a req_to_token_pool (KV cache index mapping) but maintain separate KV cache pools.

When both HiCache and speculative decoding are enabled, the target KV cache may be loaded back from L2/L3. The shared index table is updated accordingly, but the draft model’s KV cache is not updated. As a result, the draft model reads incorrect KV, leading to accept length regression.

A natural alternative would be to re-run draft prefill to regenerate its KV cache after the target load_back. However, in speculative decoding the draft prefill depends on target hidden states (fc(concat(embed(token_{i+1}), target_hidden_state_i))). When KV is loaded back from L2/L3, the target prefill stage is skipped and the full hidden states are not produced, so the draft model cannot perform prefill.

Solution

This PR supports paired offload/load_back of the target and draft KV caches to/from L2/L3 (based on #17338).

How wo reproduce:

1. launch with spec+hicache
SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR=/root/code/tmp/sglang_hicache_file_test \
python3 -m sglang.launch_server \
  --model /models/ZhipuAI/GLM-4.7-FP8/ \
  --enable-hierarchical-cache \
  --hicache-io-backend direct \
  --hicache-mem-layout page_first_direct \
  --hicache-write-policy write_through --host 0.0.0.0 \
  --mem-fraction-static 0.55 --page-size 64 \
  --port 7000 \
  --reasoning-parser glm45 \
  --served-model-name GLM-4.7 \
  --speculative-algorithm EAGLE \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 8 \
  --speculative-num-steps 7 \
  --tool-call-parser glm47 \
  --tp 8 \
  --trust-remote-code \
  --model-loader-extra-config '{"enable_multithread_load": true, "num_threads": 64}' \
  --hicache-size 60 \
  --hicache-storage-prefetch-policy wait_complete \
  --hicache-storage-backend file \
   --speculative-draft-model-quantization compressed-tensors

2. send request to write target kvcache
 python3 -m sglang.bench_serving \
    --backend sglang-oai \
    --dataset-name random \
    --num-prompts 1 \
    --model /models/ZhipuAI/GLM-4.7-FP8/ \
    --dataset-path /root/code/datasets/ShareGPT_V3_unfiltered_cleaned_split.json \
    --random-input-len 150000 \
    --random-output-len 1024 \
    --random-range-ratio 0.3 \
    --max-concurrency 1 \
    --warmup-requests 0 \
    --seed 77 \
    --host 0.0.0.0 --port 7000

3. cleanup L1 kvcache(relaunch sglang)

4. benchmark with long prefix hit
 python3 -m sglang.bench_serving \
    --backend sglang-oai \
    --dataset-name random \
    --num-prompts 1 \
    --model /models/ZhipuAI/GLM-4.7-FP8/ \
    --dataset-path /root/code/datasets/ShareGPT_V3_unfiltered_cleaned_split.json \
    --random-input-len 150000 \
    --random-output-len 1024 \
    --random-range-ratio 0.3 \
    --max-concurrency 1 \
    --warmup-requests 0 \
    --seed 77 \
    --host 0.0.0.0 --port 7000

benchmark result before this feature(draft L2/L3kvcache):

============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     1
Benchmark duration (s):                  11.29
Total input tokens:                      92831
Total input text tokens:                 92831
Total generated tokens:                  914
Total generated tokens (retokenized):    914
Request throughput (req/s):              0.09
Input token throughput (tok/s):          8224.80
Output token throughput (tok/s):         80.98
Peak output token throughput (tok/s):    29.00
Peak concurrent requests:                1
Total token throughput (tok/s):          8305.78
Concurrency:                             1.00
Accept length:                           3.07
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   11278.09
Median E2E Latency (ms):                 11278.09
P90 E2E Latency (ms):                    11278.09
P99 E2E Latency (ms):                    11278.09
---------------Time to First Token----------------
Mean TTFT (ms):                          365.38
Median TTFT (ms):                        365.38
P99 TTFT (ms):                           365.38
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          11.95
Median TPOT (ms):                        11.95
P99 TPOT (ms):                           11.95
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.95
Median ITL (ms):                         11.65
P95 ITL (ms):                            18.40
P99 ITL (ms):                            18.80
Max ITL (ms):                            35.02
==================================================

benchmark result after this feature(draft L2/L3kvcache):
accelt length 3.07->6.94

============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     1
Benchmark duration (s):                  5.29
Total input tokens:                      92831
Total input text tokens:                 92831
Total generated tokens:                  914
Total generated tokens (retokenized):    914
Request throughput (req/s):              0.19
Input token throughput (tok/s):          17533.77
Output token throughput (tok/s):         172.63
Peak output token throughput (tok/s):    29.00
Peak concurrent requests:                1
Total token throughput (tok/s):          17706.40
Concurrency:                             1.00
Accept length:                           6.94
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5286.52
Median E2E Latency (ms):                 5286.52
P90 E2E Latency (ms):                    5286.52
P99 E2E Latency (ms):                    5286.52
---------------Time to First Token----------------
Mean TTFT (ms):                          409.57
Median TTFT (ms):                        409.57
P99 TTFT (ms):                           409.57
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.34
Median TPOT (ms):                        5.34
P99 TPOT (ms):                           5.34
---------------Inter-Token Latency----------------
Mean ITL (ms):                           5.34
Median ITL (ms):                         5.01
P95 ITL (ms):                            7.54
P99 ITL (ms):                            8.74
Max ITL (ms):                            54.88
==================================================

Modifications

Accuracy Tests

Benchmarking and Profiling

Checklist

Review Process

  1. Ping Merge Oncalls to start the PR flow. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • /tag-run-ci-label, /rerun-failed-ci, /tag-and-rerun-ci
  4. After green CI and required approvals, ask Merge Oncalls to merge.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a draft KV cache backing for the HiCache system, specifically targeting L2/L3 caches. This enhancement addresses a regression issue in speculative decoding where the draft model could see stale or incorrect slot indices after a load_back operation. The changes ensure that the draft KV pool is properly synchronized with the main KV cache, improving the accuracy and stability of speculative decoding.

Highlights

  • HiCache Draft KV Pool: Introduces a draft KV cache backing for L2/L3 HiCache to improve speculative decoding accuracy by ensuring draft KV is restored to correct indices after load_back operations.
  • Integration with HiRadixCache and HiMambaRadixCache: The draft KV pool functionality is integrated into both HiRadixCache and HiMambaRadixCache via a mixin class, providing a unified approach for managing draft KV in hierarchical caches.
  • Hooks for Write, Load, and Evict Operations: The changes include hooks into the HiCache write, load, and evict paths to manage the draft KV pool, ensuring consistency between the main and draft KV caches.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for backing up the draft model's KV cache to L2 (host) and L3 (storage) when using HiCache with speculative decoding. This is achieved by a new HiCacheDraftMixin that hooks into HiCache's data movement operations (write, load, evict) to synchronize the draft KV cache with the main model's KV cache. The changes are well-integrated into HiRadixCache and HiMambaRadixCache. My main feedback is to refactor a piece of duplicated logic in the scheduler for better maintainability.

Comment thread python/sglang/srt/managers/scheduler.py Outdated
@xiezhq-hermann xiezhq-hermann added run-ci hicache Hierarchical Caching for SGLang labels Mar 23, 2026
@alphabetc1
Copy link
Copy Markdown
Collaborator Author

alphabetc1 commented Mar 24, 2026

/rerun-failed-ci 1

Comment thread python/sglang/srt/managers/cache_controller.py
@ovowei
Copy link
Copy Markdown
Contributor

ovowei commented Mar 28, 2026

can this work for eagle3?

@alphabetc1
Copy link
Copy Markdown
Collaborator Author

can this work for eagle3?

yes. but may not work well for multi-layer eagle

@alphabetc1
Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@ykwd
Copy link
Copy Markdown
Contributor

ykwd commented Apr 13, 2026

Thanks for this work. Is this pr compatible with DSA model (#21259) ?

@alphabetc1
Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@alphabetc1 alphabetc1 force-pushed the feat/hicache_spec_2 branch from ec43b6d to 3cfdf1a Compare April 22, 2026 08:06
@alphabetc1 alphabetc1 changed the title [HiCache] feat: add draft KV cache backing for L2/L3 [HiCache] feat: add draft KV cache backing for L2/L3 (v1) Apr 22, 2026
@alphabetc1 alphabetc1 force-pushed the feat/hicache_spec_2 branch from 3cfdf1a to ec43b6d Compare April 22, 2026 12:00
@alphabetc1 alphabetc1 changed the title [HiCache] feat: add draft KV cache backing for L2/L3 (v1) [HiCache] feat: add draft KV cache backing for L2/L3 Apr 22, 2026
@alphabetc1 alphabetc1 force-pushed the feat/hicache_spec_2 branch from ec43b6d to 3cfdf1a Compare April 27, 2026 08:30
@alphabetc1
Copy link
Copy Markdown
Collaborator Author

/rerun-test test_hicache_storage.py test_hicache_variants.py test_hicache_storage_3fs_backend.py test_hicache_storage_file_backend.py test_hicache_storage_mooncake_backend.py test_hicache_storage_runtime_attach_detach.py test_hicache_spec_file_storage.py

@github-actions
Copy link
Copy Markdown
Contributor

1-gpu-5090 (1 test): View workflow run

cd test/ && python3 registered/hicache/test_hicache_storage.py

1-gpu-h100 (2 tests): View workflow run

cd test/ && python3 registered/hicache/test_hicache_variants.py
cd test/ && python3 registered/hicache/test_hicache_spec_file_storage.py

2-gpu-h100 (4 tests): View workflow run

cd test/ && python3 registered/hicache/test_hicache_storage_3fs_backend.py
cd test/ && python3 registered/hicache/test_hicache_storage_file_backend.py
cd test/ && python3 registered/hicache/test_hicache_storage_mooncake_backend.py
cd test/ && python3 registered/hicache/test_hicache_storage_runtime_attach_detach.py

@alphabetc1
Copy link
Copy Markdown
Collaborator Author

alphabetc1 commented Apr 29, 2026

1-gpu-5090 (1 test): View workflow run

cd test/ && python3 registered/hicache/test_hicache_storage.py

1-gpu-h100 (2 tests): View workflow run

cd test/ && python3 registered/hicache/test_hicache_variants.py
cd test/ && python3 registered/hicache/test_hicache_spec_file_storage.py

2-gpu-h100 (4 tests): View workflow run

cd test/ && python3 registered/hicache/test_hicache_storage_3fs_backend.py
cd test/ && python3 registered/hicache/test_hicache_storage_file_backend.py
cd test/ && python3 registered/hicache/test_hicache_storage_mooncake_backend.py
cd test/ && python3 registered/hicache/test_hicache_storage_runtime_attach_detach.py
image

ALL hicache ci passed & local ci passed

@xiezhq-hermann xiezhq-hermann merged commit 2c41ef4 into sgl-project:main Apr 29, 2026
104 of 123 checks passed
@hnyls2002 hnyls2002 mentioned this pull request Apr 29, 2026
vguduruTT pushed a commit to vguduruTT/sglang that referenced this pull request May 2, 2026
@alphabetc1 alphabetc1 deleted the feat/hicache_spec_2 branch May 7, 2026 03:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants