Repository navigation
Conversation
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
[Fix]: Validate DeepSeek V4 index cache pattern
# Conflicts: # python/sglang/srt/layers/attention/dsv4/indexer.py # python/sglang/srt/models/deepseek_v4.py
# 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
|
Please update indexcache usage to the playground and configuration tips part of deepseek v4 cookbok (https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-V4#hw=b200&variant=flash&quant=fp4&strategy=low-latency&nodes=single) |
| alt_streams=self.alt_streams_indexer, | ||
| rotary_emb=getattr(self, "rotary_emb", None), | ||
| ) | ||
| c4_layer_ids = [ |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| q_out: Optional[torch.Tensor] = None, | ||
| x_quant=None, | ||
| ) -> torch.Tensor: | ||
| prev_topk_indices: Optional[torch.Tensor] = None, |
There was a problem hiding this comment.
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] = NoneCreate 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 NoneThere was a problem hiding this comment.
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]]: |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
Can we create a different forward path if topk is skipped
There was a problem hiding this comment.
Done. I added a separate _forward_c4_indexer_skip_topk path and route to it when skip_topk is enabled with cached topk indices.
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
|
|
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. |
…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).
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
index_topk_freqandindex_topk_patterntoDeepSeekV4Config.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
AIME2025
GPQA Diamond
Speed Tests and Profiling
Test in H800, TP=4, index_topk_freq=4.
Server start command:
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:
Checklist
CI States
Latest PR Test (Base): ❌ Run #28215809677
Latest PR Test (Extra): ❌ Run #28215809585