Skip to content

[Feature] Enable DeepSeek V4 index cache - #26274

Open
ChefWu551 wants to merge 12 commits into
sgl-project:mainfrom
ChefWu551:enable_dsv4_indexcache
Open

ChefWu551 wants to merge 12 commits into
sgl-project:mainfrom
ChefWu551:enable_dsv4_indexcache

Conversation

@ChefWu551

@ChefWu551 ChefWu551 commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Enables DeepSeek V4 C4 indexer top-k reuse through an index cache.
Input 256K output 100 throughput improved by 17%.
This pr #25276 is deprecated due to outdated code.

Modifications

  • Add index_topk_freq and index_topk_pattern to DeepSeekV4Config.
  • Allow DeepSeek V4 C4 indexer layers to reuse previous raw top-k indices.
  • Convert cached raw C4 indices back to sparse page indices before attention.
  • Preserve compatibility with indexer top-k capture and HiSparse page translation.
  • Handle decoder outputs with cached top-k metadata in DeepSeek V4 NextN.

Accuracy Tests

Evaluate DeepSeek-V4-Flash on Ceval, AIME2025 and GPQA Diamond. There is a small accuracy drop with indexCache=4: AIME2025 decreases from 0.5667 to 0.5333, and GPQA Diamond decreases from 0.7576 to 0.7273. CEval also shows a slight drop from 0.9161 to 0.9116.

CEval

Dataset Samples Configuration Accuracy
CEval 1,346 Non-IndexCache 91.61%
CEval 1,346 IndexCache=4 91.16%

AIME2025

Dataset Samples Configuration Accuracy
AIME2025 (think max) 30 official ~95%
AIME2025 (think max) 30 IndexCache=4 96.665%
# indexCache=4
## fist time test
root@sglang-dsv4-flash-wyf-n-4-7d-667dcd9f7c-r6j9n:/sgl-workspace/sgl-eval-main# sgl-eval run aime25 \
>   --model DeepSeek-V4-Flash \
>   --n-repeats 1 \
>   --max-tokens 200000 \
>   --temperature 1.0 \  
>   --top-p 1.0 \        
>   --thinking \
>   --out-dir /nas/disk2/wyf/tmp/logs \
>   --base-url http://127.0.0.1:30000/v1    
Run directory: /nas/disk2/wyf/tmp/logs/sgl_eval_aime25_20260601-025553
aime25: 100%|██████████████████████████████████████████████████████████████████████████████████████████████| 30/30 [46:56<00:00, 93.89s/it, acc=100.00%]== aime25 ==
30 examples (single-shot)  |  2816.8s  |  313 tok/s  |  882K tokens

* score  =  100.00%

Metrics: /nas/disk2/wyf/tmp/logs/sgl_eval_aime25_20260601-025553/metrics.json
Predictions: /nas/disk2/wyf/tmp/logs/sgl_eval_aime25_20260601-025553  (1 jsonl file(s))


## second time test
root@sglang-dsv4-flash-wyf-n-4-7d-667dcd9f7c-r6j9n:/sgl-workspace/sgl-eval-main# sgl-eval run aime25   --model DeepSeek-V4-Flash   --n-repeats 1   
--max-tokens 200000   --temperature 1.0   --top-p 1.0   --thinking   --out-dir /nas/disk2/wyf/tmp/logs   --base-url http://127.0.0.1:30000/v1      
Run directory: /nas/disk2/wyf/tmp/logs/sgl_eval_aime25_20260601-035936
aime25: 100%|██████████████████████████████████████████████████████████████████████████████████████████████| 30/30 [57:07<00:00, 114.26s/it, acc=93.33%]== aime25 ==
30 examples (single-shot)  |  3427.9s  |  345 tok/s  |  1.2M tokens

* score  =  93.33%

Metrics: /nas/disk2/wyf/tmp/logs/sgl_eval_aime25_20260601-035936/metrics.json
Predictions: /nas/disk2/wyf/tmp/logs/sgl_eval_aime25_20260601-035936  (1 jsonl file(s))   

GPQA Diamond

Dataset Samples Configuration Accuracy
GPQA Diamond (think max) 198 official 88.1%
GPQA Diamond (think max) 198 IndexCache=4 87.88%
sgl-eval run gpqa \
  --model DeepSeek-V4-Flash \
  --n-repeats 1 \
  --num-threads 4 \
  --max-tokens 200000 \
  --temperature 1.0 \
  --top-p 1.0 \
  --thinking \
  --out-dir /nas/disk2/wyf/tmp/logs \
  --base-url http://127.0.0.1:30000/v1

# indexCache=4
root@sglang-dsv4-flash-wyf-n-4-7d-667dcd9f7c-r6j9n:/sgl-workspace# tail -f test_gpqa.log 
nohup: ignoring input
Run directory: /nas/disk2/wyf/tmp/logs/sgl_eval_gpqa_20260601-131651
gpqa: 100%|██████████| 198/198 [3:42:29<00:00, 67.42s/it, acc=87.88%]   
== gpqa ==
198 examples (single-shot)  |  13349.4s  |  448 tok/s  |  6.0M tokens

* score  =  87.88%

Metrics: /nas/disk2/wyf/tmp/logs/sgl_eval_gpqa_20260601-131651/metrics.json
Predictions: /nas/disk2/wyf/tmp/logs/sgl_eval_gpqa_20260601-131651  (1 jsonl file(s))

Speed Tests and Profiling

Test in H800, TP=4, index_topk_freq=4.
Server start command:

python3 -m sglang.launch_server \
  --trust-remote-code \
  --model-path /nas/disk6/DeepSeek-V4-Flash/DeepSeek-V4-Flash/DeepSeek-V4-Flash-FP8 \
  --tp 4 \
  --mem-fraction-static 0.8 \
  --cuda-graph-max-bs 16 \
  --moe-runner-backend marlin \
  --host 0.0.0.0 \
  --json-model-override-args '{"index_topk_freq": 4}' \
  --port 30000

Improvement effect:

20K: +3.3% to +3.9% throughput, ~3% E2E latency reduction
60K: +4.4% to +5.8% throughput, ~4% to 6% latency reduction
100K: +6.4% to +8.4% throughput, ~6% to 8% latency reduction
256K: +16.4% to +17.9% throughput, ~14% to 15% latency reduction

Specific data:

Input/Output Length Configuration Concurrency TTFT TPOT E2E Output Throughput (tok/s) TTFT Reduction vs Non-IndexCache TPOT Reduction vs Non-IndexCache E2E Reduction vs Non-IndexCache Throughput Gain vs Non-IndexCache
20K/100 Non-IndexCache 1 1151.79 7.78 1834.98 48.38 - - - -
20K/100 Non-IndexCache 3 1414.42 26.17 4005.91 77.22 - - - -
20K/100 Non-IndexCache 5 1842.18 42.60 5999.68 80.42 - - - -
20K/100 indexCache=4 1 1079.34 7.83 1766.91 50.24 6.29% -0.64% 3.71% 3.84%
20K/100 indexCache=4 3 1359.20 25.36 3871.33 79.90 3.90% 3.09% 3.36% 3.47%
20K/100 indexCache=4 5 1872.22 40.56 5808.49 83.06 -1.63% 4.79% 3.19% 3.28%
60K/100 Non-IndexCache 1 3480.04 7.85 4257.67 23.48 - - - -
60K/100 Non-IndexCache 3 6713.29 38.97 10571.72 28.37 - - - -
60K/100 Non-IndexCache 5 9904.70 71.39 16972.22 29.45 - - - -
60K/100 indexCache=4 1 3297.55 7.90 4079.33 24.51 5.24% -0.64% 4.19% 4.39%
60K/100 indexCache=4 3 6363.19 37.13 10038.82 29.88 5.22% 4.72% 5.04% 5.32%
60K/100 indexCache=4 5 9366.54 67.33 16032.51 31.17 5.43% 5.69% 5.54% 5.84%
100K/100 Non-IndexCache 1 5985.66 7.97 6774.23 14.76 - - - -
100K/100 Non-IndexCache 3 11659.75 63.24 17920.68 16.74 - - - -
100K/100 Non-IndexCache 5 17197.75 119.29 29007.45 17.23 - - - -
100K/100 indexCache=4 1 5584.14 7.89 6365.44 15.71 6.71% 1.00% 6.03% 6.44%
100K/100 indexCache=4 3 10785.29 58.55 16581.62 18.09 7.50% 7.42% 7.47% 8.06%
100K/100 indexCache=4 5 15848.98 110.15 26753.53 18.68 7.84% 7.66% 7.77% 8.42%
256K/100 Non-IndexCache 1 19090.68 8.31 19913.42 5.02 - - - -
256K/100 Non-IndexCache 3 36836.83 186.98 55348.12 5.42 - - - -
256K/100 indexCache=4 1 16274.44 8.47 17113.34 5.84 14.75% -1.93% 14.06% 16.33%
256K/100 indexCache=4 3 31279.71 158.23 46944.92 6.39 15.09% 15.38% 15.18% 17.90%

Checklist


CI States

Latest PR Test (Base): ❌ Run #28215809677
Latest PR Test (Extra): ❌ Run #28215809585

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

Copy link
Copy Markdown
Contributor

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 a mechanism to skip top-k calculations in the DeepSeek V4 model by reusing indices from previous layers, controlled by frequency or specific patterns. It includes a new utility for transforming raw indices to page indices and updates the indexer and model layers to propagate and return top-k indices. Feedback was provided regarding the robustness of the pattern-matching logic for skipping layers, suggesting clearer error handling for cases where the provided pattern length is insufficient.

Comment thread python/sglang/srt/models/deepseek_v4.py Outdated
Comment on lines +338 to +358
if len(self.index_topk_pattern) == len(config.compress_ratios):
pattern_idx = layer_id
has_next_pattern = layer_id < len(self.index_topk_pattern) - 1
next_pattern_idx = layer_id + 1
else:
assert c4_layer_rank < len(self.index_topk_pattern), (
f"index_topk_pattern length {len(self.index_topk_pattern)} "
f"is too short for c4_layer_rank={c4_layer_rank}"
)
pattern_idx = c4_layer_rank
has_next_pattern = (
c4_layer_rank < len(self.index_topk_pattern) - 1
)
next_pattern_idx = c4_layer_rank + 1
self.skip_topk = self.index_topk_pattern[pattern_idx] == "S"
if has_next_pattern:
self.next_skip_topk = (
self.index_topk_pattern[next_pattern_idx] == "S"
)
else:
self.next_skip_topk = False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The logic for determining skip_topk and next_skip_topk using index_topk_pattern assumes that the pattern is either the same length as config.compress_ratios or long enough to cover all C4 layers. While there is an assertion for the latter, it might be beneficial to handle cases where the pattern is shorter than expected more gracefully or provide a clearer error message.

@ChefWu551 ChefWu551 May 26, 2026 •

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.

[Fix]: Validate DeepSeek V4 index cache pattern

wuyuefeng added 2 commits May 26, 2026 09:07
# Conflicts:
#	python/sglang/srt/layers/attention/dsv4/indexer.py
#	python/sglang/srt/models/deepseek_v4.py
@ChefWu551 ChefWu551 mentioned this pull request May 27, 2026
24 of 36 tasks
wuyuefeng added 3 commits June 2, 2026 09:49
# Conflicts:
#	python/sglang/srt/models/deepseek_v4.py
#	python/sglang/srt/models/deepseek_v4_nextn.py
# Conflicts:
#	python/sglang/srt/layers/attention/dsv4/indexer.py
@Fridge003

Copy link
Copy Markdown
Collaborator

Comment thread python/sglang/srt/models/deepseek_v4.py Outdated
alt_streams=self.alt_streams_indexer,
rotary_emb=getattr(self, "rotary_emb", None),
)
c4_layer_ids = [

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.

Can we extract the logics for computing skip_topk and next_skip_topk as standalone util functions.
Also we need to add a unit test that protect their behavior, like whether the index_topk_freq is computed correctly, or index_topk_pattern is parsed correctly

@ChefWu551 ChefWu551 Jun 25, 2026 •

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.

Done. The skip_topk / next_skip_topk logic is now extracted into utils, and unit tests for index_topk_freq / index_topk_pattern have passed.

Comment thread python/sglang/srt/models/deepseek_v4.py Outdated
q_out: Optional[torch.Tensor] = None,
x_quant=None,
) -> torch.Tensor:
prev_topk_indices: Optional[torch.Tensor] = None,

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.

I feel passing prev_topk_indices across multiple function calling will be invasive and risky.
How about creating a global buffer for storing the previous topk results, and update it when next_skip_topk is True.

For example,

@dataclass
class Dsv4IndexTopkState:
    prev: Optional[torch.Tensor] = None

Create it once in DeepseekV4Model.forward, pass topk_state down to DeepseekV4DecoderLayer / MQALayer, and let MQALayer consume/update it internally:

prev = topk_state.prev if self.skip_topk else None

topk = self.indexer(
    ...,
    prev_topk_indices=prev,
    skip_topk=bool(self.skip_topk),
    return_topk_indices=bool(self.next_skip_topk),
)

if self.next_skip_topk is not None:
    topk_state.prev = topk if self.next_skip_topk else None

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.

Refactored this to use a per-forward Dsv4IndexTopkState. It is created in DeepseekV4Model.forward and consumed/updated inside MQALayer, so prev_topk_indices is no longer passed through the outer call chain.

I used msgspec.Struct to match the repo convention, and the state is scoped to one forward call.

x_quant=None,
) -> torch.Tensor:
prev_topk_indices: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:

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.

Also add an e2e test for dsv4 flash + indexer cache, and register it as extra test.
Similar to this one test/registered/8-gpu-models/test_deepseek_v32_indexcache.py

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.

Done.
E2E unit tests with IndexCache were executed and all passed.

out_raw_indices.copy_(raw_indices)


def transform_raw_c4_indices_to_page_indices(

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.

Can we create a triton kernel for this function so it doesn't cost too much time.
Meanwhile we need a unit test for this kernel

@ChefWu551 ChefWu551 Jun 25, 2026 •

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.

Done.

Added a Triton kernel for the C4 index transform, with tests against the Torch reference.
Micro benchmark: 0.1348 ms -> 0.0220 ms, about 6.14x faster.

)
return q, weights, c4_indexer_kv_cache

def forward_c4_indexer(

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.

Can we create a different forward path if topk is skipped

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.

Done. I added a separate _forward_c4_indexer_skip_topk path and route to it when skip_topk is enabled with cached topk indices.

wuyuefeng added 4 commits June 17, 2026 18:23
Document the user-facing IndexCache configuration in the DeepSeek V4 cookbook and playground command generation.

Extract skip_topk and next_skip_topk computation into DeepSeek common utilities, and add unit coverage for index_topk_freq and index_topk_pattern parsing.
Add an H200 extra CI e2e test that launches DeepSeek-V4-Flash FP8 with IndexCache enabled.

Cover both index_topk_freq=4 and index_topk_pattern through real server startup and GSM8K accuracy evaluation.
# Conflicts:
#	docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V4.mdx
#	docs_new/src/snippets/_playground.jsx
#	python/sglang/srt/models/deepseek_v4.py
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Jun 25, 2026
@ChefWu551

Copy link
Copy Markdown
Contributor Author

@feng397

feng397 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Thanks for the original IndexCache implementation. I have forward-ported it to the latest main and adapted it to the current DeepSeek V4 interfaces, with additional PD, CP, HiSparse, and HiCache coverage. New PR: #32771. Hope we can work together to move this forward.

@b8zhong b8zhong mentioned this pull request Aug 5, 2026
15 of 41 tasks
Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 10, 2026
…ripped PD/disaggregation files)

Forward-port of sgl-project#26274 by ChefWu551, adapted by feng397 (sgl-project#32771).
Enables DSV4 C4 indexer top-k reuse: producer (F) layers compute raw
top-k, shared (S) layers skip indexer/compressor/logits/topk and reuse
cached indices via Triton raw→page-index transform.

Config: --json-model-override-args '{"index_topk_freq": N}' (default 1=off)
Performance: +7-18% throughput (scales with context length)
Accuracy: AIME2025 94.2%→90.0% at freq=4 (use freq=2 for conservative)

DSpark compatible: draft model has compress_ratio=0 (no C4 layers),
IndexCache only affects target model C4 attention. topk_state threaded
transparently through model.forward().

Stripped from PR: 4 disaggregation files (base/conn.py, common/conn.py,
decode.py, prefill.py) + 3 PD test files — not needed for non-PD deploy.
Conflict resolved in indexer.py: kept both _forward_oversize_varlen_chunked
(from 9303e26) and _match_num_queries/_forward_c4_indexer_skip_topk (from PR).

TBO and PP>1 rejected at startup (neither used in deployment).

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

deepseek documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants