From 9b959b86577c082c0b2bf9e2c22263255a36ad83 Mon Sep 17 00:00:00 2001 From: Roger Wang Date: Thu, 10 Sep 2026 05:16:26 -0700 Subject: [PATCH] [Model] DeepSeek-V4.1-Flash Model Definitions (#56228) Signed-off-by: Roger Wang Signed-off-by: zjy0516 Co-authored-by: Kimi Code Co-authored-by: zjy0516 Co-authored-by: Codex --- tests/models/test_deepseek_v4_mega_moe.py | 58 +- tests/parser/engine/trace_builder.py | 57 +- .../kernels/attention/dsa/candidate_blocks.py | 234 +++ .../model_executor/kernels/linear/__init__.py | 18 +- .../kernels/linear/mxfp8/Mxfp8LinearKernel.py | 2 +- .../kernels/linear/mxfp8/deep_gemm.py | 128 ++ .../kernels/linear/mxfp8/flashinfer.py | 52 +- vllm/model_executor/kernels/mhc/tilelang.py | 200 +++ .../kernels/mhc/tilelang_kernels.py | 85 +- vllm/model_executor/kernels/mhc/torch.py | 42 + vllm/model_executor/kernels/mhc/triton.py | 46 +- vllm/model_executor/kernels/mhc/warmup.py | 74 + .../fused_moe/router/fused_moe_router.py | 4 + .../layers/quantization/modelopt.py | 30 +- .../layers/sparse_attn_indexer.py | 101 +- .../common/ops/fused_inv_rope_fp8_quant.py | 175 ++- vllm/models/deepseek_v4/common/vision.py | 95 +- vllm/models/deepseek_v4/nvidia/model.py | 66 +- .../nvidia/ops/fused_indexer_q_cutedsl.py | 10 +- vllm/models/deepseek_v4/nvidia/ops/o_proj.py | 50 +- vllm/models/deepseek_v4_1/__init__.py | 20 + vllm/models/deepseek_v4_1/amd/__init__.py | 2 + vllm/models/deepseek_v4_1/amd/dspark.py | 546 +++++++ vllm/models/deepseek_v4_1/amd/model.py | 1086 ++++++++++++++ vllm/models/deepseek_v4_1/amd/rocm.py | 905 ++++++++++++ vllm/models/deepseek_v4_1/amd/vl_model.py | 357 +++++ vllm/models/deepseek_v4_1/attention.py | 1225 ++++++++++++++++ vllm/models/deepseek_v4_1/common/__init__.py | 2 + vllm/models/deepseek_v4_1/common/engram.py | 1033 ++++++++++++++ .../deepseek_v4_1/common/ops/__init__.py | 42 + .../deepseek_v4_1/common/ops/cache_utils.py | 1254 +++++++++++++++++ .../common/ops/fused_compress_quant_cache.py | 383 +++++ .../common/ops/indexer_k_store.py | 253 ++++ .../deepseek_v4_1/common/ops/query_quant.py | 142 ++ vllm/models/deepseek_v4_1/common/rope.py | 53 + vllm/models/deepseek_v4_1/compressor.py | 323 +++++ vllm/models/deepseek_v4_1/nvidia/__init__.py | 2 + vllm/models/deepseek_v4_1/nvidia/dspark.py | 558 ++++++++ .../deepseek_v4_1/nvidia/flashinfer_sparse.py | 908 ++++++++++++ vllm/models/deepseek_v4_1/nvidia/flashmla.py | 387 +++++ vllm/models/deepseek_v4_1/nvidia/model.py | 1111 +++++++++++++++ .../deepseek_v4_1/nvidia/model_state.py | 98 ++ vllm/models/deepseek_v4_1/nvidia/vl_model.py | 357 +++++ vllm/models/deepseek_v4_1/quant_config.py | 229 +++ vllm/models/deepseek_v4_1/sparse_mla.py | 231 +++ vllm/v1/attention/backends/mla/sparse_swa.py | 54 +- vllm/v1/attention/backends/registry.py | 10 + 47 files changed, 12902 insertions(+), 196 deletions(-) create mode 100644 vllm/model_executor/kernels/attention/dsa/candidate_blocks.py create mode 100644 vllm/model_executor/kernels/linear/mxfp8/deep_gemm.py create mode 100644 vllm/model_executor/kernels/mhc/warmup.py create mode 100644 vllm/models/deepseek_v4_1/__init__.py create mode 100644 vllm/models/deepseek_v4_1/amd/__init__.py create mode 100644 vllm/models/deepseek_v4_1/amd/dspark.py create mode 100644 vllm/models/deepseek_v4_1/amd/model.py create mode 100644 vllm/models/deepseek_v4_1/amd/rocm.py create mode 100644 vllm/models/deepseek_v4_1/amd/vl_model.py create mode 100644 vllm/models/deepseek_v4_1/attention.py create mode 100644 vllm/models/deepseek_v4_1/common/__init__.py create mode 100644 vllm/models/deepseek_v4_1/common/engram.py create mode 100644 vllm/models/deepseek_v4_1/common/ops/__init__.py create mode 100644 vllm/models/deepseek_v4_1/common/ops/cache_utils.py create mode 100644 vllm/models/deepseek_v4_1/common/ops/fused_compress_quant_cache.py create mode 100644 vllm/models/deepseek_v4_1/common/ops/indexer_k_store.py create mode 100644 vllm/models/deepseek_v4_1/common/ops/query_quant.py create mode 100644 vllm/models/deepseek_v4_1/common/rope.py create mode 100644 vllm/models/deepseek_v4_1/compressor.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/__init__.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/dspark.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/flashinfer_sparse.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/flashmla.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/model.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/model_state.py create mode 100644 vllm/models/deepseek_v4_1/nvidia/vl_model.py create mode 100644 vllm/models/deepseek_v4_1/quant_config.py create mode 100644 vllm/models/deepseek_v4_1/sparse_mla.py diff --git a/tests/models/test_deepseek_v4_mega_moe.py b/tests/models/test_deepseek_v4_mega_moe.py index f3c70dc88a..4e95904f6b 100644 --- a/tests/models/test_deepseek_v4_mega_moe.py +++ b/tests/models/test_deepseek_v4_mega_moe.py @@ -169,7 +169,18 @@ def test_deepseek_v4_mega_moe_weight_loader_uses_ep_expert_ownership(): assert torch.count_nonzero(experts.w13_weight[1]) == 0 -def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(monkeypatch): +@pytest.mark.parametrize( + "hidden_size,intermediate_size,block_size,fused", + [ + pytest.param(128, 512, 128, True, id="aligned-block128"), + pytest.param(5120, 2304, 32, False, id="deepseek-v41-flash"), + ], +) +def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights( + monkeypatch, hidden_size, intermediate_size, block_size, fused +): + """V4.1-Flash's routed padding must preserve the serial shared-expert fallback.""" + class FakeDeepGemm: transformed_dims: list[tuple[int, int]] = [] scale_inputs: list[tuple[int, ...]] = [] @@ -216,8 +227,8 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(monkeypatch num_local_experts=1, experts_start_idx=0, top_k=1, - hidden_size=128, - intermediate_size=128, + hidden_size=hidden_size, + intermediate_size=intermediate_size, num_shared_experts=1, ) experts._check_runtime_supported = lambda: None @@ -232,24 +243,49 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(monkeypatch shared_experts = SimpleNamespace( gate_up_proj=SimpleNamespace( - weight=fp8_parameter(256, 128), - weight_block_size=(128, 128), - weight_scale_inv=scale_parameter(2, 1, dtype=torch.float8_e8m0fnu), + weight=fp8_parameter(2 * intermediate_size, hidden_size), + weight_block_size=(block_size, block_size), + weight_scale_inv=scale_parameter( + 2 * intermediate_size // block_size, + hidden_size // block_size, + dtype=torch.float8_e8m0fnu, + ), ), down_proj=SimpleNamespace( - weight=fp8_parameter(128, 128), - weight_block_size=(128, 128), - weight_scale_inv=scale_parameter(1, 1, dtype=torch.float8_e8m0fnu), + weight=fp8_parameter(hidden_size, intermediate_size), + weight_block_size=(block_size, block_size), + weight_scale_inv=scale_parameter( + hidden_size // block_size, + intermediate_size // block_size, + dtype=torch.float8_e8m0fnu, + ), ), ) monkeypatch.setattr("vllm.utils.deep_gemm._import_deep_gemm", lambda: FakeDeepGemm) original_gate_up_ptr = shared_experts.gate_up_proj.weight.data_ptr() + original_down_ptr = shared_experts.down_proj.weight.data_ptr() experts.finalize_weights(shared_experts) + assert FakeDeepGemm.scale_inputs[-2:] == [ + (1, 2 * intermediate_size, hidden_size // 32), + (1, hidden_size, intermediate_size // 32), + ] + assert experts.has_fused_shared_experts is fused + if not fused: + assert experts.intermediate_size == 2560 + assert FakeDeepGemm.transformed_dims == [(3, 3)] + assert experts.num_shared_experts == 0 + assert shared_experts.gate_up_proj.weight.data_ptr() == original_gate_up_ptr + assert shared_experts.down_proj.weight.data_ptr() == original_down_ptr + assert shared_experts.gate_up_proj.weight.shape == ( + 2 * intermediate_size, + hidden_size, + ) + assert shared_experts.down_proj.weight.shape == (hidden_size, intermediate_size) + return + assert FakeDeepGemm.transformed_dims == [(3, 3), (2, 2)] - assert FakeDeepGemm.scale_inputs[-2:] == [(1, 256, 4), (1, 128, 4)] - assert experts.has_fused_shared_experts assert shared_experts.gate_up_proj.weight.data_ptr() != original_gate_up_ptr assert ( experts._transformed_shared_l1_weights[0].data_ptr() diff --git a/tests/parser/engine/trace_builder.py b/tests/parser/engine/trace_builder.py index 6d5415dfda..36e347fc57 100644 --- a/tests/parser/engine/trace_builder.py +++ b/tests/parser/engine/trace_builder.py @@ -31,6 +31,7 @@ from vllm.entrypoints.openai.chat_completion.protocol import ( from vllm.parser.engine.registered_adapters import ( DeepSeekV4Parser, DeepSeekV32Parser, + DeepSeekV41Parser, Gemma4Parser, Glm47MoeParser, InklingParser, @@ -658,7 +659,7 @@ _DSV4_VOCAB: dict[str, int] = { } -def _dsv4_param_text(key: str, value: Any) -> str: +def _dsv4_param_text(key: str, value: Any, dsml: str = _DSML) -> str: is_string = isinstance(value, str) if is_string: val_str = value @@ -670,36 +671,39 @@ def _dsv4_param_text(key: str, value: Any) -> str: val_str = json.dumps(value, ensure_ascii=False) string_attr = "true" if is_string else "false" return ( - f'<{_DSML}parameter name="{key}" string="{string_attr}">' - f"{val_str}\n" + f'<{dsml}parameter name="{key}" string="{string_attr}">' + f"{val_str}\n" ) -def _dsv4_tool_text(tc: ToolCallSpec) -> str: - parts = [f'<{_DSML}invoke name="{tc.name}">\n'] +def _dsv4_tool_text(tc: ToolCallSpec, dsml: str = _DSML) -> str: + parts = [f'<{dsml}invoke name="{tc.name}">\n'] for key, value in tc.arguments.items(): - parts.append(_dsv4_param_text(key, value)) - parts.append(f"\n") + parts.append(_dsv4_param_text(key, value, dsml)) + parts.append(f"\n") return "".join(parts) def _dsml_tool_segs( scenario: Scenario, tag: str, + dsml: str = _DSML, ) -> list[tuple[str, bool]]: if not scenario.tool_calls: return [] parts = ["\n"] for tc in scenario.tool_calls: - parts.append(_dsv4_tool_text(tc)) + parts.append(_dsv4_tool_text(tc, dsml)) return [ - (f"<{_DSML}{tag}>", True), + (f"<{dsml}{tag}>", True), ("".join(parts), False), - (f"", True), + (f"", True), ] -def _dsv4_segments(scenario: Scenario, thinking: bool) -> list[tuple[str, bool]]: +def _dsv4_segments( + scenario: Scenario, thinking: bool, *, v41: bool = False +) -> list[tuple[str, bool]]: segs: list[tuple[str, bool]] = [] if thinking: @@ -716,13 +720,31 @@ def _dsv4_segments(scenario: Scenario, thinking: bool) -> list[tuple[str, bool]] if scenario.content is not None: segs.append((scenario.content, False)) - segs.extend(_dsml_tool_segs(scenario, "tool_calls")) + segs.extend( + _dsml_tool_segs(scenario, "calls", f"{_DSML} ") + if v41 + else _dsml_tool_segs(scenario, "tool_calls") + ) return segs -def _build_deepseek_v4(scenario: Scenario, validate: bool = True) -> Sample: +def _build_deepseek_v4( + scenario: Scenario, validate: bool = True, *, v41: bool = False +) -> Sample: thinking = scenario.reasoning is not None chat_kwargs = {"thinking": thinking} + parser_cls = DeepSeekV41Parser if v41 else DeepSeekV4Parser + model = "deepseek_v41" if v41 else "deepseek_v4" + vocab = ( + { + "": 128821, + "": 128822, + f"<{_DSML} calls>": 128823, + f"": 128824, + } + if v41 + else _DSV4_VOCAB + ) if thinking: expected_reasoning: str | None = scenario.reasoning or "" @@ -730,10 +752,10 @@ def _build_deepseek_v4(scenario: Scenario, validate: bool = True) -> Sample: expected_reasoning = None sample = _make_sample( - sample_id=f"deepseek_v4-{scenario.id}", + sample_id=f"{model}-{scenario.id}", description=scenario.description, - vocab=_DSV4_VOCAB, - segments=_dsv4_segments(scenario, thinking), + vocab=vocab, + segments=_dsv4_segments(scenario, thinking, v41=v41), expected_reasoning=expected_reasoning, expected_content=_qwen3_expected_content(scenario), expected_tool_calls=_expected_tc(scenario), @@ -744,7 +766,7 @@ def _build_deepseek_v4(scenario: Scenario, validate: bool = True) -> Sample: kwargs = {} if chat_kwargs: kwargs["chat_template_kwargs"] = chat_kwargs - _validate_sample(sample, DeepSeekV4Parser, **kwargs) + _validate_sample(sample, parser_cls, **kwargs) return sample @@ -1025,6 +1047,7 @@ def _build_inkling(scenario: Scenario, validate: bool = True) -> Sample: _BUILDERS: dict[str, Any] = { "deepseek_v32": _build_deepseek_v32, "deepseek_v4": _build_deepseek_v4, + "deepseek_v41": functools.partial(_build_deepseek_v4, v41=True), "gemma4": _build_gemma4, "minimax_m2": _build_minimax_m2, "nemotron_v3": _build_nemotron_v3, diff --git a/vllm/model_executor/kernels/attention/dsa/candidate_blocks.py b/vllm/model_executor/kernels/attention/dsa/candidate_blocks.py new file mode 100644 index 0000000000..efc7c418ca --- /dev/null +++ b/vllm/model_executor/kernels/attention/dsa/candidate_blocks.py @@ -0,0 +1,234 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import torch + +from vllm.triton_utils import tl, triton + + +@triton.jit +def _max_with_nan(a, b): + return tl.maximum(a, b, propagate_nan=tl.PropagateNan.ALL) + + +@triton.jit(do_not_specialize=["width", "nblocks"]) +def _block_scores_kernel( + logits, + starts, + ends, + scores, + stride_row, + stride_col, + stride_start, + stride_end, + width, + nblocks, + BLOCK_SIZE: tl.constexpr, + HAS_STARTS: tl.constexpr, + ROW_REPEAT: tl.constexpr, + TILE: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + blocks = tl.program_id(1) * TILE + tl.arange(0, TILE) + start = tl.load(starts + row // ROW_REPEAT * stride_start) if HAS_STARTS else 0 + end = tl.load(ends + row // ROW_REPEAT * stride_end) + offsets = tl.arange(0, triton.next_power_of_2(BLOCK_SIZE)) + cols = start + blocks[:, None] * BLOCK_SIZE + offsets[None, :] + values = tl.load( + logits + row * stride_row + cols * stride_col, + (blocks[:, None] < nblocks) + & (offsets[None, :] < BLOCK_SIZE) + & (cols < end) + & (cols < width), + other=-float("inf"), + ) + reduced = tl.reduce(values, 1, _max_with_nan) + reduced = tl.where( + (end > start) & (blocks == (end - start - 1) // BLOCK_SIZE), + float("inf"), + reduced, + ) + tl.store(scores + row * nblocks + blocks, reduced, blocks < nblocks) + + +@triton.jit(do_not_specialize=["k"]) +def _store_candidates_kernel( + values, + indices, + output, + out_stride_row, + out_stride_col, + k, + OUT_K: tl.constexpr, + TILE: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + cols = tl.program_id(1) * TILE + tl.arange(0, TILE) + value = tl.load(values + row * k + cols, cols < k, other=-float("inf")) + index = tl.load(indices + row * k + cols, cols < k, other=-1) + tl.store( + output + row * out_stride_row + cols * out_stride_col, + tl.where(value > -float("inf"), index, -1), + cols < OUT_K, + ) + + +@triton.jit(do_not_specialize=["width", "nblocks"]) +def _candidate_flags_kernel( + candidates, + starts, + flags, + stride_row, + stride_col, + stride_start, + width, + nblocks, + BLOCK_SIZE: tl.constexpr, + K: tl.constexpr, + HAS_STARTS: tl.constexpr, + ROW_REPEAT: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + offsets = tl.arange(0, 1024) + for tile in range(tl.cdiv(nblocks + 1, 1024)): + slots = tile * 1024 + offsets + tl.store(flags + row * (nblocks + 1) + slots, 0, slots <= nblocks) + start = tl.load(starts + row // ROW_REPEAT * stride_start) if HAS_STARTS else 0 + cols = tl.arange(0, triton.next_power_of_2(K)) + block = tl.load( + candidates + row * stride_row + cols * stride_col, cols < K, other=-1 + ).to(tl.int64) + # Preserve the packed-column clamp for candidates beyond the logits width. + block = tl.where(start + block * BLOCK_SIZE >= width, nblocks, block) + tl.debug_barrier() + tl.store(flags + row * (nblocks + 1) + block, 1, (cols < K) & (block >= 0)) + + +@triton.jit(do_not_specialize=["width", "nblocks"]) +def _mask_candidates_kernel( + logits, + starts, + ends, + flags, + stride_row, + stride_col, + stride_start, + stride_end, + width, + nblocks, + BLOCK_SIZE: tl.constexpr, + HAS_STARTS: tl.constexpr, + ROW_REPEAT: tl.constexpr, + TILE: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + cols = tl.program_id(1) * TILE + tl.arange(0, TILE) + start = tl.load(starts + row // ROW_REPEAT * stride_start) if HAS_STARTS else 0 + end = tl.load(ends + row // ROW_REPEAT * stride_end) + valid = (cols >= start) & (cols < end) & (cols < width) + block = (cols - start) // BLOCK_SIZE + keep = tl.load(flags + row * (nblocks + 1) + block, valid, other=0) + edge = tl.load(flags + row * (nblocks + 1) + nblocks) + keep = (keep != 0) | ((cols == width - 1) & (edge != 0)) + tl.store( + logits + row * stride_row + cols * stride_col, + -float("inf"), + (cols < width) & ~(valid & keep), + ) + + +def select_candidate_blocks( + logits: torch.Tensor, + row_ks: torch.Tensor | None, + row_ke: torch.Tensor, + topk_blocks: int, + block_size: int, + out: torch.Tensor, + row_repeat: int = 1, +) -> None: + """Select local block IDs by maximum score, pinning each row's newest block. + + Row bounds are in packed column space; absent starts mean zero. + Decode rows share bounds in groups of ``row_repeat``. Output is -1 padded. + """ + assert logits.is_cuda + rows, width = logits.shape + if not rows: + return + if not width: + out.fill_(-1) + return + nblocks = triton.cdiv(width, block_size) + scores = logits.new_empty((rows, nblocks)) + _block_scores_kernel[(rows, triton.cdiv(nblocks, 128))]( + logits, + row_ks, + row_ke, + scores, + *logits.stride(), + row_ks.stride(0) if row_ks is not None else 0, + row_ke.stride(0), + width, + nblocks, + block_size, + row_ks is not None, + row_repeat, + 128, + ) + # Keep the existing top-k tie behavior. + top = scores.topk(min(topk_blocks, nblocks), dim=-1) + _store_candidates_kernel[(rows, triton.cdiv(topk_blocks, 256))]( + top.values, + top.indices, + out, + *out.stride(), + top.values.shape[1], + topk_blocks, + 256, + ) + + +def apply_candidate_mask( + logits: torch.Tensor, + row_ks: torch.Tensor | None, + row_ke: torch.Tensor, + candidate_blocks: torch.Tensor, + block_size: int, + row_repeat: int = 1, +) -> None: + """Mask packed logits outside causal bounds and request-local candidates.""" + assert logits.is_cuda + rows, width = logits.shape + if not rows or not width: + return + nblocks = triton.cdiv(width, block_size) + flags = torch.empty((rows, nblocks + 1), device=logits.device, dtype=torch.uint8) + start_stride = row_ks.stride(0) if row_ks is not None else 0 + _candidate_flags_kernel[(rows,)]( + candidate_blocks, + row_ks, + flags, + *candidate_blocks.stride(), + start_stride, + width, + nblocks, + block_size, + candidate_blocks.shape[1], + row_ks is not None, + row_repeat, + ) + _mask_candidates_kernel[(rows, triton.cdiv(width, 1024))]( + logits, + row_ks, + row_ke, + flags, + *logits.stride(), + start_stride, + row_ke.stride(0), + width, + nblocks, + block_size, + row_ks is not None, + row_repeat, + 1024, + ) diff --git a/vllm/model_executor/kernels/linear/__init__.py b/vllm/model_executor/kernels/linear/__init__.py index f8e4f5ecb4..9c52e7b413 100644 --- a/vllm/model_executor/kernels/linear/__init__.py +++ b/vllm/model_executor/kernels/linear/__init__.py @@ -109,6 +109,9 @@ from vllm.model_executor.kernels.linear.mxfp8 import ( from vllm.model_executor.kernels.linear.mxfp8.b12x import ( B12xMxfp8LinearKernel, ) +from vllm.model_executor.kernels.linear.mxfp8.deep_gemm import ( + DeepGemmMxfp8BmmLinearKernel, +) from vllm.model_executor.kernels.linear.mxfp8.emulation import ( EmulationMxfp8LinearKernel, ) @@ -301,6 +304,7 @@ _LINEAR_BACKEND_KERNEL_MAP: dict[str, set[type]] = { }, "deep_gemm": { DeepGemmFp8BlockScaledMMKernel, + DeepGemmMxfp8BmmLinearKernel, }, "torch": { PerTensorTorchFP8ScaledMMLinearKernel, @@ -851,13 +855,21 @@ def choose_mp_linear_kernel( ) -def init_mxfp8_linear_kernel() -> Mxfp8LinearKernel: +def init_mxfp8_linear_kernel(*, bmm_batch_size: int | None = None) -> Mxfp8LinearKernel: """Select and instantiate the best MXFP8 linear kernel for the current platform.""" - config = Mxfp8LinearLayerConfig() + config = Mxfp8LinearLayerConfig(bmm_batch_size=bmm_batch_size) platform = current_platform._enum - possible = list(_POSSIBLE_MXFP8_KERNELS.get(platform, [])) + possible: list[type[Mxfp8LinearKernel]] + if bmm_batch_size is not None: + possible = ( + [DeepGemmMxfp8BmmLinearKernel, EmulationMxfp8LinearKernel] + if current_platform.is_cuda() + else [] + ) + else: + possible = list(_POSSIBLE_MXFP8_KERNELS.get(platform, [])) # Apply --linear-backend filtering when set. possible = _resolve_backend_kernels(possible, "MXFP8") diff --git a/vllm/model_executor/kernels/linear/mxfp8/Mxfp8LinearKernel.py b/vllm/model_executor/kernels/linear/mxfp8/Mxfp8LinearKernel.py index c8b8582c0e..3fe34029e5 100644 --- a/vllm/model_executor/kernels/linear/mxfp8/Mxfp8LinearKernel.py +++ b/vllm/model_executor/kernels/linear/mxfp8/Mxfp8LinearKernel.py @@ -17,7 +17,7 @@ class Mxfp8LinearLayerConfig: uint8 (E8M0) per-block scales at block size 32. """ - pass + bmm_batch_size: int | None = None class Mxfp8LinearKernel(ABC): diff --git a/vllm/model_executor/kernels/linear/mxfp8/deep_gemm.py b/vllm/model_executor/kernels/linear/mxfp8/deep_gemm.py new file mode 100644 index 0000000000..b74f11497b --- /dev/null +++ b/vllm/model_executor/kernels/linear/mxfp8/deep_gemm.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import torch + +from vllm.model_executor.layers.quantization.utils.fp8_utils import ( + deepgemm_post_process_fp8_weight_block, + per_token_group_quant_fp8_packed_for_deepgemm, +) +from vllm.model_executor.utils import replace_parameter +from vllm.platforms import current_platform +from vllm.utils.deep_gemm import ( + fp8_einsum, + is_deep_gemm_supported, +) +from vllm.utils.torch_utils import direct_register_custom_op + +from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig + + +class DeepGemmMxfp8BmmLinearKernel(Mxfp8LinearKernel): + """Grouped MXFP8 einsum with per-row, 32-element weight scales.""" + + def __init__(self, config: Mxfp8LinearLayerConfig): + super().__init__(config) + self.recipe = (1, 1, 32) + + @classmethod + def is_supported( + cls, compute_capability: int | None = None + ) -> tuple[bool, str | None]: + if not current_platform.is_cuda() or not is_deep_gemm_supported(): + return False, "DeepGEMM BMM requires a supported CUDA device." + if not current_platform.is_device_capability_family(100): + return False, "DeepGEMM MXFP8 BMM requires Blackwell." + return True, None + + @classmethod + def can_implement(cls, config: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]: + if config.bmm_batch_size is None or config.bmm_batch_size <= 0: + return False, "DeepGEMM BMM requires a positive batch size." + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + weight = layer.weight.data + if weight.ndim == 3: + return + scale = layer.weight_scale.data + assert weight.dtype == torch.float8_e4m3fn and weight.ndim == 2 + assert scale.shape == (weight.shape[0], weight.shape[1] // 32) + assert self.config.bmm_batch_size is not None + weight, scale = deepgemm_post_process_fp8_weight_block( + wq=weight, + ws=scale, + quant_block_shape=(1, 32), + use_e8m0=False, + is_bmm=True, + bmm_batch_size=self.config.bmm_batch_size, + ) + replace_parameter(layer, "weight", weight) + replace_parameter(layer, "weight_scale", scale) + layer.weight_block_size = [1, 32] + + def apply_weights( + self, + layer: torch.nn.Module, + x: torch.Tensor | tuple[torch.Tensor, torch.Tensor], + bias: torch.Tensor | None = None, + ) -> torch.Tensor: + """Project [tokens, groups, K] input to [tokens, groups, N].""" + if isinstance(x, tuple): + q_input, input_scale = x + else: + tokens, groups, k = x.shape + q_input, input_scale = per_token_group_quant_fp8_packed_for_deepgemm( + x.reshape(tokens, groups * k), + group_size=32, + use_ue8m0=True, + ) + q_input = q_input.view(tokens, groups, k) + input_scale = input_scale.view(tokens, groups, k // 128) + output = torch.ops.vllm.deepgemm_mxfp8_bmm( + q_input, input_scale, layer.weight, layer.weight_scale, list(self.recipe) + ) + if bias is not None: + output = output + bias.view(output.shape[1:]) + return output + + +def _deepgemm_mxfp8_bmm_fake( + x: torch.Tensor, + x_scale: torch.Tensor, + weight: torch.Tensor, + weight_scale: torch.Tensor, + recipe: list[int], +) -> torch.Tensor: + return torch.empty( + (x.shape[0], weight.shape[0], weight.shape[1]), + device=x.device, + dtype=torch.bfloat16, + ) + + +def _deepgemm_mxfp8_bmm( + x: torch.Tensor, + x_scale: torch.Tensor, + weight: torch.Tensor, + weight_scale: torch.Tensor, + recipe: list[int], +) -> torch.Tensor: + output = torch.empty( + (x.shape[0], weight.shape[0], weight.shape[1]), + device=x.device, + dtype=torch.bfloat16, + ) + fp8_einsum( + "bhr,hdr->bhd", + (x, x_scale), + (weight, weight_scale), + output, + recipe=tuple(recipe), + ) + return output + + +direct_register_custom_op( + "deepgemm_mxfp8_bmm", _deepgemm_mxfp8_bmm, fake_impl=_deepgemm_mxfp8_bmm_fake +) diff --git a/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py b/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py index 6ea9138de9..02700a0ced 100644 --- a/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py +++ b/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py @@ -4,11 +4,19 @@ import torch from torch.nn.parameter import Parameter +from vllm.model_executor.layers.fusion.quant_activation import ( + QuantizedActivation, + as_quantized_activation, +) from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( MXFP8_BLOCK_SIZE, mxfp8_e4m3_quantize, swizzle_mxfp8_scale, ) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + QuantKey, + kMxfp8Dynamic, +) from vllm.platforms import current_platform from vllm.utils import flashinfer as vllm_flashinfer from vllm.utils.flashinfer import has_flashinfer, has_flashinfer_cutedsl @@ -35,6 +43,10 @@ class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel): def can_implement(cls, c: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]: return True, None + def input_quant_key(self) -> QuantKey: + # Activations use FlashInfer's F8_128x4 swizzled scale layout. + return kMxfp8Dynamic + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: weight = layer.weight.data # [N, K] N, K = weight.shape @@ -51,16 +63,13 @@ class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel): def apply_weights( self, layer: torch.nn.Module, - x: torch.Tensor, + x: torch.Tensor | QuantizedActivation, bias: torch.Tensor | None = None, ) -> torch.Tensor: weight = layer.weight weight_scale = layer.weight_scale - out_dtype = x.dtype N, K = weight.shape - input_shape = x.shape - input_2d = x.view(-1, K) min_dim = 128 assert min_dim <= K, ( @@ -75,9 +84,16 @@ class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel): f"out_features is too small for mm_mxfp8." ) - input_mxfp8, input_scale = mxfp8_e4m3_quantize( - input_2d, is_sf_swizzled_layout=True - ) + qa = as_quantized_activation(x, self.input_quant_key()) + if qa is not None: + input_mxfp8, input_scale = qa.data, qa.scale + out_dtype, input_shape = qa.orig_dtype, qa.orig_shape + else: + assert isinstance(x, torch.Tensor) + out_dtype, input_shape = x.dtype, x.shape + input_mxfp8, input_scale = mxfp8_e4m3_quantize( + x.view(-1, K), is_sf_swizzled_layout=True + ) if not weight.is_contiguous(): weight = weight.contiguous() @@ -118,6 +134,10 @@ class FlashInferCutedslMxfp8LinearKernel(Mxfp8LinearKernel): def can_implement(cls, c: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]: return True, None + def input_quant_key(self) -> QuantKey: + # Activations use FlashInfer's F8_128x4 swizzled scale layout. + return kMxfp8Dynamic + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: weight = layer.weight.data # [N, K] N, K = weight.shape @@ -135,16 +155,13 @@ class FlashInferCutedslMxfp8LinearKernel(Mxfp8LinearKernel): def apply_weights( self, layer: torch.nn.Module, - x: torch.Tensor, + x: torch.Tensor | QuantizedActivation, bias: torch.Tensor | None = None, ) -> torch.Tensor: weight = layer.weight # [K, N], column-major weight_scale = layer.weight_scale - out_dtype = x.dtype K, N = weight.shape - input_shape = x.shape - input_2d = x.view(-1, K) min_dim = 128 assert min_dim <= K, ( @@ -159,9 +176,16 @@ class FlashInferCutedslMxfp8LinearKernel(Mxfp8LinearKernel): f"out_features is too small for mm_mxfp8." ) - input_mxfp8, input_scale = mxfp8_e4m3_quantize( - input_2d, is_sf_swizzled_layout=True - ) + qa = as_quantized_activation(x, self.input_quant_key()) + if qa is not None: + input_mxfp8, input_scale = qa.data, qa.scale + out_dtype, input_shape = qa.orig_dtype, qa.orig_shape + else: + assert isinstance(x, torch.Tensor) + out_dtype, input_shape = x.dtype, x.shape + input_mxfp8, input_scale = mxfp8_e4m3_quantize( + x.view(-1, K), is_sf_swizzled_layout=True + ) output = vllm_flashinfer.mm_mxfp8( input_mxfp8, diff --git a/vllm/model_executor/kernels/mhc/tilelang.py b/vllm/model_executor/kernels/mhc/tilelang.py index c3c773d07f..c4fe6dd163 100644 --- a/vllm/model_executor/kernels/mhc/tilelang.py +++ b/vllm/model_executor/kernels/mhc/tilelang.py @@ -87,6 +87,190 @@ def _tilelang_hc_prenorm_gemm( ) +def mhc_pre_delayed_tilelang( + residual: torch.Tensor, + fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + rms_eps: float, + hc_pre_eps: float, + hc_sinkhorn_eps: float, + hc_post_mult_value: float, + sinkhorn_repeat: int, + pre_mix: torch.Tensor | None = None, + x: torch.Tensor | None = None, + norm_weight: torch.Tensor | None = None, + norm_eps: float = 1e-6, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Run mHC pre with a carried pre-mix and return the next pre-mix. + + Args: + residual: BF16 residual streams of shape (tokens, hc_mult, hidden_size). + fn: FP32 projection of shape (hc_mult * (hc_mult + 2), input_size). + hc_scale: FP32 scales of shape (3,). + hc_base: FP32 bias of shape (hc_mult * (hc_mult + 2),). + rms_eps: RMS normalization epsilon. + hc_pre_eps: Pre-mix epsilon. + hc_sinkhorn_eps: Sinkhorn epsilon. + hc_post_mult_value: Post-mix multiplier. + sinkhorn_repeat: Number of Sinkhorn iterations. + pre_mix: FP32 coefficients from the previous sublayer, or None to + select residual stream zero at model entry. + x: Optional BF16 projection input of shape (tokens, input_size), for + the first layer's broadcast embedding and summed projection. + norm_weight: Optional BF16 RMSNorm weight for the collapsed input. + norm_eps: RMSNorm epsilon for the collapsed input. + + Returns: + Post and residual coefficients, optionally normalized BF16 layer input, + and the next FP32 pre-mix, with shapes (tokens, hc_mult, 1), + (tokens, hc_mult, hc_mult), (tokens, hidden_size), and (tokens, hc_mult). + """ + from vllm.model_executor.kernels.mhc.tilelang_kernels import ( + mhc_pre_big_fuse_tilelang, + ) + from vllm.model_executor.kernels.mhc.warmup import ( + MHC_PRE_NORM_KERNEL, + compute_mhc_pre_num_splits, + ) + from vllm.utils.deep_gemm import ( + is_deep_gemm_supported, + tf32_hc_prenorm_gemm, + ) + + assert residual.ndim == 3 and residual.dtype == torch.bfloat16 + assert residual.is_contiguous() + num_tokens, hc_mult, hidden_size = residual.shape + if x is None: + x = residual.view(num_tokens, hc_mult * hidden_size) + assert x.ndim == 2 and x.dtype == torch.bfloat16 and x.is_contiguous() + assert x.shape[0] == num_tokens + input_size = x.shape[1] + mix_size = hc_mult * (hc_mult + 2) + assert fn.shape == (mix_size, input_size) and fn.dtype == torch.float32 + assert hc_scale.shape == (3,) and hc_scale.dtype == torch.float32 + assert hc_base.shape == (mix_size,) and hc_base.dtype == torch.float32 + if pre_mix is not None: + assert pre_mix.shape == (num_tokens, hc_mult) + assert pre_mix.dtype == torch.float32 and pre_mix.is_contiguous() + + next_pre_mix = torch.empty( + num_tokens, hc_mult, dtype=torch.float32, device=residual.device + ) + post = torch.empty_like(next_pre_mix) + comb = torch.empty( + num_tokens, hc_mult * hc_mult, dtype=torch.float32, device=residual.device + ) + layer_input = torch.empty( + num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device + ) + outputs = ( + post.unsqueeze(-1), + comb.view(num_tokens, hc_mult, hc_mult), + layer_input, + next_pre_mix, + ) + if num_tokens == 0: + return outputs + + use_deep_gemm = is_deep_gemm_supported() + n_splits = ( + compute_mhc_pre_num_splits(input_size, num_tokens) if use_deep_gemm else 1 + ) + mixes = torch.empty( + n_splits, num_tokens, mix_size, dtype=torch.float32, device=residual.device + ) + sqrsum = torch.empty( + n_splits, num_tokens, dtype=torch.float32, device=residual.device + ) + if use_deep_gemm: + tf32_hc_prenorm_gemm(x, fn, mixes, sqrsum, n_splits) + else: + _tilelang_hc_prenorm_gemm(x, fn, mixes, sqrsum, input_size, 1) + if norm_weight is not None: + assert norm_weight.shape == (hidden_size,) + assert norm_weight.dtype == torch.bfloat16 and norm_weight.is_contiguous() + MHC_PRE_NORM_KERNEL( + mixes, + sqrsum, + hc_scale, + hc_base, + residual, + post, + comb, + layer_input, + norm_weight, + pre_mix if pre_mix is not None else post, + next_pre_mix, + hidden_size=hidden_size, + rms_eps=rms_eps, + hc_pre_eps=hc_pre_eps, + hc_sinkhorn_eps=hc_sinkhorn_eps, + hc_post_mult_value=hc_post_mult_value, + sinkhorn_repeat=sinkhorn_repeat, + norm_eps=norm_eps, + hc_mult=hc_mult, + use_pre_mix_in=pre_mix is not None, + save_pre_mix=True, + rms_numel=input_size, + ) + return outputs + mhc_pre_big_fuse_tilelang( + mixes, + sqrsum, + hc_scale, + hc_base, + residual, + post, + comb, + layer_input, + pre_mix if pre_mix is not None else post, + next_pre_mix, + hidden_size, + rms_eps, + hc_pre_eps, + hc_sinkhorn_eps, + hc_post_mult_value, + sinkhorn_repeat, + n_splits, + hc_mult, + use_pre_mix_in=pre_mix is not None, + save_pre_mix=True, + rms_numel=input_size, + ) + return outputs + + +def _mhc_pre_delayed_tilelang_fake( + residual: torch.Tensor, + fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + rms_eps: float, + hc_pre_eps: float, + hc_sinkhorn_eps: float, + hc_post_mult_value: float, + sinkhorn_repeat: int, + pre_mix: torch.Tensor | None = None, + x: torch.Tensor | None = None, + norm_weight: torch.Tensor | None = None, + norm_eps: float = 1e-6, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + num_tokens, hc_mult, hidden_size = residual.shape + return ( + torch.empty( + num_tokens, hc_mult, 1, dtype=torch.float32, device=residual.device + ), + torch.empty( + num_tokens, hc_mult, hc_mult, dtype=torch.float32, device=residual.device + ), + torch.empty( + num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device + ), + torch.empty(num_tokens, hc_mult, dtype=torch.float32, device=residual.device), + ) + + def mhc_pre_tilelang( residual: torch.Tensor, fn: torch.Tensor, @@ -219,6 +403,9 @@ def mhc_pre_tilelang( post_mix, comb_mix, layer_input, + # Pre-mix buffers are unused in V4 mode. + post_mix, + post_mix, hidden_size, rms_eps, hc_pre_eps, @@ -239,6 +426,8 @@ def mhc_pre_tilelang( comb_mix, layer_input, norm_weight, + post_mix, + post_mix, hidden_size, rms_eps, hc_pre_eps, @@ -622,6 +811,9 @@ def mhc_fused_post_pre_tilelang( post_mix_cur, comb_mix_cur, layer_input_cur, + # Pre-mix buffers are unused in V4 mode. + post_mix_cur, + post_mix_cur, hidden_size, rms_eps, hc_pre_eps, @@ -642,6 +834,8 @@ def mhc_fused_post_pre_tilelang( comb_mix_cur, layer_input_cur, norm_weight, + post_mix_cur, + post_mix_cur, hidden_size, rms_eps, hc_pre_eps, @@ -762,6 +956,12 @@ def _hc_head_fused_kernel_tilelang_fake( ) +direct_register_custom_op( + op_name="mhc_pre_delayed_tilelang", + op_func=mhc_pre_delayed_tilelang, + mutates_args=[], + fake_impl=_mhc_pre_delayed_tilelang_fake, +) direct_register_custom_op( op_name="mhc_pre_tilelang", op_func=mhc_pre_tilelang, diff --git a/vllm/model_executor/kernels/mhc/tilelang_kernels.py b/vllm/model_executor/kernels/mhc/tilelang_kernels.py index 925f4631a5..1c23d152b9 100644 --- a/vllm/model_executor/kernels/mhc/tilelang_kernels.py +++ b/vllm/model_executor/kernels/mhc/tilelang_kernels.py @@ -38,6 +38,8 @@ def mhc_pre_big_fuse_tilelang( post_mix, comb_mix, layer_input, + pre_mix_in, + pre_mix_out, hidden_size: int, rms_eps: float, hc_pre_eps: float, @@ -46,11 +48,20 @@ def mhc_pre_big_fuse_tilelang( sinkhorn_repeat: int, n_splits: int = 16, hc_mult: int = 4, + use_pre_mix_in: bool = False, + save_pre_mix: bool = False, + rms_numel: int = 0, ): - """Deeply fused kernels, everything other than gemm & sqrsum in mHC pre block.""" + """Fuse coefficient generation and residual collapse after the projection. + + With save_pre_mix, store the new pre-mix and collapse with pre_mix_in, + or select stream zero when use_pre_mix_in is false. + """ num_tokens = T.dynamic("num_tokens") hc_mult3 = hc_mult * (2 + hc_mult) hidden_block = math.gcd(512, hidden_size) + if rms_numel == 0: + rms_numel = hc_mult * hidden_size gemm_out_mul: T.Tensor[[n_splits, num_tokens, hc_mult3], T.float32] # type: ignore[no-redef, valid-type] gemm_out_sqrsum: T.Tensor[[n_splits, num_tokens], T.float32] # type: ignore[no-redef, valid-type] @@ -62,6 +73,9 @@ def mhc_pre_big_fuse_tilelang( comb_mix: T.Tensor[[num_tokens, hc_mult * hc_mult], T.float32] # type: ignore[no-redef, valid-type] layer_input: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type] + pre_mix_in: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type] + pre_mix_out: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type] + with T.Kernel(num_tokens, threads=96) as i: if ENABLE_PDL: T.pdl_sync() @@ -73,7 +87,7 @@ def mhc_pre_big_fuse_tilelang( rms[0] = 0 for i_split in T.serial(n_splits): rms[0] += gemm_out_sqrsum[i_split, i] - rms[0] = T.rsqrt(rms[0] / (hc_mult * hidden_size) + rms_eps) + rms[0] = T.rsqrt(rms[0] / rms_numel + rms_eps) for j in T.Parallel(hc_mult3): mixes[j] = 0 for i_split in T.serial(n_splits): @@ -87,6 +101,11 @@ def mhc_pre_big_fuse_tilelang( # _pre_split_mixes_fwd (post & comb) cm = T.alloc_fragment((hc_mult, hc_mult), T.float32) for j in T.Parallel(hc_mult): + if save_pre_mix: + pre_mix_out[i, j] = ( + T.sigmoid(mixes_shared[j] * hc_scale[0] + hc_base[j]) + + hc_pre_eps + ) post_mix[i, j] = ( T.sigmoid( mixes_shared[j + hc_mult] * hc_scale[1] + hc_base[j + hc_mult] @@ -137,12 +156,15 @@ def mhc_pre_big_fuse_tilelang( # _pre_split_mixes_fwd (pre) pre_mix_shared = T.alloc_shared(hc_mult, T.float32) for j in T.Parallel(hc_mult): - pre_mix_shared[j] = ( - T.sigmoid( - mixes_shared[j] * hc_scale[0] + hc_base[j], + if use_pre_mix_in: + pre_mix_shared[j] = pre_mix_in[i, j] + elif save_pre_mix: + pre_mix_shared[j] = T.if_then_else(j == 0, 1.0, 0.0) + else: + pre_mix_shared[j] = ( + T.sigmoid(mixes_shared[j] * hc_scale[0] + hc_base[j]) + + hc_pre_eps ) - + hc_pre_eps - ) ################################################################### # _pre_apply_mix_fwd for i0_h in T.Pipelined(hidden_size // hidden_block, num_stages=2): @@ -179,6 +201,8 @@ def mhc_pre_big_fuse_with_norm_tilelang( comb_mix, layer_input, norm_weight, + pre_mix_in, + pre_mix_out, hidden_size: int, rms_eps: float, hc_pre_eps: float, @@ -189,11 +213,16 @@ def mhc_pre_big_fuse_with_norm_tilelang( n_splits: int = 16, hc_mult: int = 4, gemm_last_dim: int = -1, + use_pre_mix_in: bool = False, + save_pre_mix: bool = False, + rms_numel: int = 0, ): num_tokens = T.dynamic("num_tokens") hc_mult3 = hc_mult * (2 + hc_mult) if gemm_last_dim < 0: gemm_last_dim = hc_mult3 + if rms_numel == 0: + rms_numel = hc_mult * hidden_size hidden_block = math.gcd(1024, hidden_size) gemm_out_mul: T.Tensor[[n_splits, num_tokens, gemm_last_dim], T.float32] # type: ignore[no-redef, valid-type] @@ -206,6 +235,9 @@ def mhc_pre_big_fuse_with_norm_tilelang( layer_input: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type] norm_weight: T.Tensor[[hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type] + pre_mix_in: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type] + pre_mix_out: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type] + with T.Kernel(num_tokens, threads=96) as i: rms = T.alloc_fragment(1, T.float32) mixes = T.alloc_fragment(hc_mult3, T.float32) @@ -217,7 +249,7 @@ def mhc_pre_big_fuse_with_norm_tilelang( for i_split in T.serial(n_splits): rms[0] += gemm_out_sqrsum[i_split, i] - rms[0] = T.rsqrt(rms[0] / (hc_mult * hidden_size) + rms_eps) + rms[0] = T.rsqrt(rms[0] / rms_numel + rms_eps) for j in T.Parallel(hc_mult3): mixes[j] = 0 for i_split in T.serial(n_splits): @@ -229,6 +261,11 @@ def mhc_pre_big_fuse_with_norm_tilelang( if T.get_thread_binding() < 32: cm = T.alloc_fragment((hc_mult, hc_mult), T.float32) for j in T.Parallel(hc_mult): + if save_pre_mix: + pre_mix_out[i, j] = ( + T.sigmoid(mixes_shared[j] * hc_scale[0] + hc_base[j]) + + hc_pre_eps + ) post_mix[i, j] = ( T.sigmoid( mixes_shared[j + hc_mult] * hc_scale[1] + hc_base[j + hc_mult] @@ -270,12 +307,15 @@ def mhc_pre_big_fuse_with_norm_tilelang( else: pre_mix_shared = T.alloc_shared(hc_mult, T.float32) for j in T.Parallel(hc_mult): - pre_mix_shared[j] = ( - T.sigmoid( - mixes_shared[j] * hc_scale[0] + hc_base[j], + if use_pre_mix_in: + pre_mix_shared[j] = pre_mix_in[i, j] + elif save_pre_mix: + pre_mix_shared[j] = T.if_then_else(j == 0, 1.0, 0.0) + else: + pre_mix_shared[j] = ( + T.sigmoid(mixes_shared[j] * hc_scale[0] + hc_base[j]) + + hc_pre_eps ) - + hc_pre_eps - ) # Pass 1: stash unnormalized weighted-sum output in shared memory # as bf16 (matches the rounding that RMSNorm would see) while @@ -298,9 +338,18 @@ def mhc_pre_big_fuse_with_norm_tilelang( for i1_h in T.Parallel(hidden_block): ol[i1_h] += pre * xl[i_hc, i1_h] - for i1_h in T.Parallel(hidden_block): - sumsq_per_pos[i1_h] += ol[i1_h] * ol[i1_h] - output_shared[i0_h * hidden_block + i1_h] = T.bfloat16(ol[i1_h]) + if save_pre_mix: + # Keep the BF16 boundary before the delayed input RMSNorm. + rounded = T.alloc_fragment(hidden_block, T.bfloat16) + T.copy(ol, rounded) + for i1_h in T.Parallel(hidden_block): + value = T.float32(rounded[i1_h]) + sumsq_per_pos[i1_h] += value * value + output_shared[i0_h * hidden_block + i1_h] = rounded[i1_h] + else: + for i1_h in T.Parallel(hidden_block): + sumsq_per_pos[i1_h] += ol[i1_h] * ol[i1_h] + output_shared[i0_h * hidden_block + i1_h] = T.bfloat16(ol[i1_h]) sumsq = T.alloc_fragment(1, T.float32) T.reduce_sum(sumsq_per_pos, sumsq, dim=0) @@ -704,7 +753,7 @@ def hc_prenorm_gemm_tilelang( for it in T.serial(k_iters): i_k = i_s * k_per_split + it * n_thr + tid - x_val = x[i_n, i_k] + x_val = T.cast(x[i_n, i_k], T.float32) for i_o in T.unroll(tile_n): out_idx = i_t * tile_n + i_o if out_idx < n_out: @@ -794,7 +843,7 @@ def hc_prenorm_gemm_block_m_tilelang( for i_m in T.unroll(block_m): token_idx = i_mt * block_m + i_m if token_idx < num_tokens: - x_val = x[token_idx, i_k] + x_val = T.cast(x[token_idx, i_k], T.float32) for i_o in T.unroll(tile_n): acc[i_m, i_o] += x_val * fn_val[i_o] if i_t == 0: diff --git a/vllm/model_executor/kernels/mhc/torch.py b/vllm/model_executor/kernels/mhc/torch.py index 1a54ce4ad2..9c57cc169c 100644 --- a/vllm/model_executor/kernels/mhc/torch.py +++ b/vllm/model_executor/kernels/mhc/torch.py @@ -3,6 +3,48 @@ import torch +def mhc_pre_delayed_torch( + residual: torch.Tensor, + fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + rms_eps: float, + hc_pre_eps: float, + hc_sinkhorn_eps: float, + hc_post_mult_value: float, + sinkhorn_repeat: int, + pre_mix: torch.Tensor | None = None, + x: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Reference for mHC pre using coefficients from the previous sublayer.""" + hc_mult = residual.shape[1] + x = (residual.flatten(1) if x is None else x).float() + mixes = (x @ fn.t()) * torch.rsqrt(x.square().mean(-1, keepdim=True) + rms_eps) + pre = ( + torch.sigmoid(mixes[:, :hc_mult] * hc_scale[0] + hc_base[:hc_mult]) + hc_pre_eps + ) + post = ( + torch.sigmoid( + mixes[:, hc_mult : 2 * hc_mult] * hc_scale[1] + + hc_base[hc_mult : 2 * hc_mult] + ) + * hc_post_mult_value + ) + comb = mixes[:, 2 * hc_mult :].view(-1, hc_mult, hc_mult) * hc_scale[2] + comb = comb + hc_base[2 * hc_mult :].view(1, hc_mult, hc_mult) + comb = torch.softmax(comb, dim=-1) + hc_sinkhorn_eps + comb = comb / (comb.sum(dim=-2, keepdim=True) + hc_sinkhorn_eps) + for _ in range(sinkhorn_repeat - 1): + comb = comb / (comb.sum(dim=-1, keepdim=True) + hc_sinkhorn_eps) + comb = comb / (comb.sum(dim=-2, keepdim=True) + hc_sinkhorn_eps) + layer_input = ( + residual[:, 0] + if pre_mix is None + else (pre_mix.unsqueeze(-1) * residual.float()).sum(dim=1).to(residual.dtype) + ) + return post.unsqueeze(-1), comb, layer_input, pre + + def mhc_pre_torch( residual: torch.Tensor, fn: torch.Tensor, diff --git a/vllm/model_executor/kernels/mhc/triton.py b/vllm/model_executor/kernels/mhc/triton.py index facb6813ca..d94d71a6ea 100644 --- a/vllm/model_executor/kernels/mhc/triton.py +++ b/vllm/model_executor/kernels/mhc/triton.py @@ -78,7 +78,7 @@ def _hc_head_reduce_store_kernel( out_stride_h: tl.constexpr, BLOCK_H: tl.constexpr, ): - token_idx = tl.program_id(0) + token_idx = tl.program_id(0).to(tl.int64) block_idx = tl.program_id(1) offsets = block_idx * BLOCK_H + tl.arange(0, BLOCK_H) mask = offsets < hidden_size @@ -105,6 +105,42 @@ def _hc_head_reduce_store_kernel( ) +def hc_collapse_triton(x: Tensor, pre_mix: Tensor) -> Tensor: + """Collapse BF16 residual streams with FP32 pre-mix coefficients.""" + assert x.ndim == 3 and x.dtype == torch.bfloat16 + num_tokens, hc_mult, hidden_size = x.shape + assert pre_mix.shape == (num_tokens, hc_mult) + assert pre_mix.dtype == torch.float32 + out = torch.empty(num_tokens, hidden_size, dtype=x.dtype, device=x.device) + if num_tokens == 0: + return out + + block_h = 1024 + _hc_head_reduce_store_kernel[(num_tokens, triton.cdiv(hidden_size, block_h))]( + pre_mix, + x, + out, + hidden_size, + hc_mult, + pre_mix.stride(0), + pre_mix.stride(1), + x.stride(0), + x.stride(1), + x.stride(2), + out.stride(0), + out.stride(1), + BLOCK_H=block_h, + num_warps=4, + # Preserve the separate FP32 multiply and sum in the Torch reference. + enable_fp_fusion=False, + ) + return out + + +def _hc_collapse_triton_fake(x: Tensor, pre_mix: Tensor) -> Tensor: + return torch.empty(x.shape[0], x.shape[2], dtype=x.dtype, device=x.device) + + def hc_head_reduce_triton_kernel( x: torch.Tensor, hc_fn: torch.Tensor, @@ -172,3 +208,11 @@ direct_register_custom_op( op_func=_hc_head_triton, mutates_args=["out"], ) + + +direct_register_custom_op( + op_name="hc_collapse_triton", + op_func=hc_collapse_triton, + mutates_args=[], + fake_impl=_hc_collapse_triton_fake, +) diff --git a/vllm/model_executor/kernels/mhc/warmup.py b/vllm/model_executor/kernels/mhc/warmup.py new file mode 100644 index 0000000000..6a42ca6222 --- /dev/null +++ b/vllm/model_executor/kernels/mhc/warmup.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from dataclasses import asdict, dataclass +from typing import Any + +from vllm.model_executor.kernels.mhc.tilelang_kernels import ( + compute_num_split, + mhc_pre_big_fuse_with_norm_tilelang, +) +from vllm.model_executor.warmup.jit_warmup import VllmJitKernel +from vllm.platforms import current_platform +from vllm.utils.deep_gemm import is_deep_gemm_supported +from vllm.utils.math_utils import cdiv + + +def compute_mhc_pre_num_splits(input_size: int, num_tokens: int) -> int: + splits = compute_num_split(64, input_size, cdiv(num_tokens, 64)) + # Bound both GEMM and fused-normalization specializations during startup. + return 1 if splits == 1 else 4 if splits <= 4 else 16 + + +class MHCPreNormKernel(VllmJitKernel["MHCPreNormKernel.CompileKey"]): + @dataclass(frozen=True) + class CompileKey: + hidden_size: int + rms_eps: float + hc_pre_eps: float + hc_sinkhorn_eps: float + hc_post_mult_value: float + sinkhorn_repeat: int + norm_eps: float + n_splits: int + hc_mult: int + use_pre_mix_in: bool + rms_numel: int + save_pre_mix: bool = True + + kernel: Any = staticmethod(mhc_pre_big_fuse_with_norm_tilelang) + + def dispatch(self, *, n_splits, **fields) -> CompileKey: # type: ignore[override] + return self.CompileKey(n_splits=n_splits, **fields) + + def get_warmup_keys(self, *, max_tokens: int, **fields) -> list[CompileKey]: + # The split heuristic changes only at 64-token boundaries. + splits = ( + sorted( + { + compute_mhc_pre_num_splits(fields["rms_numel"], num_tokens) + for num_tokens in range(1, max_tokens + 1, 64) + } + ) + if is_deep_gemm_supported() + else [1] + ) + return self._trace_dispatch(self.dispatch)(n_splits=splits, **fields) + + def compile(self, compile_key: CompileKey) -> None: + if compile_key not in self._compiled_cache: + self._compiled_cache[compile_key] = self.kernel.compile( + **asdict(compile_key) + ) + + def __call__(self, *tensors, **fields): + compile_key = self.dispatch( + n_splits=tensors[0].shape[0], + **fields, + ) + if not current_platform.is_cuda(): + return self.kernel(*tensors, **asdict(compile_key)) + return self._get_or_compile(compile_key)(*tensors) + + +MHC_PRE_NORM_KERNEL = MHCPreNormKernel() diff --git a/vllm/model_executor/layers/fused_moe/router/fused_moe_router.py b/vllm/model_executor/layers/fused_moe/router/fused_moe_router.py index 306f9c1999..f87b7d3ae8 100644 --- a/vllm/model_executor/layers/fused_moe/router/fused_moe_router.py +++ b/vllm/model_executor/layers/fused_moe/router/fused_moe_router.py @@ -18,6 +18,10 @@ class FusedMoERouter(ABC): def __init__(self, eplb_state: EplbLayerState | None = None): self._routing_replay_out: torch.Tensor | None = None self.eplb_state = eplb_state + # Deepseek V4.1 vision checkpoints carry a second per-expert routing + # bias for image sentinel tokens; attached by model code when present. + self.bias_vl: torch.Tensor | None = None + self.image_sentinel_lo: int = 0 @abstractmethod def set_capture_fn( diff --git a/vllm/model_executor/layers/quantization/modelopt.py b/vllm/model_executor/layers/quantization/modelopt.py index 59292ec990..8dce13c3ce 100644 --- a/vllm/model_executor/layers/quantization/modelopt.py +++ b/vllm/model_executor/layers/quantization/modelopt.py @@ -1821,6 +1821,7 @@ class CkptCtx: """Per-checkpoint facts a QuantKey cannot carry.""" group_size: int | None = None + scale_block_size: tuple[int, int] | None = None @dataclass(frozen=True) @@ -2153,6 +2154,23 @@ class KMxfp8Static(QuantKeyScheme): key = kMxfp8Static + @staticmethod + def get_scale_weight_loader(weight_loader: Callable, ctx: CkptCtx) -> Callable: + block_rows, block_cols = ctx.scale_block_size or (1, MXFP8_BLOCK_SIZE) + if block_rows < 1 or block_cols != MXFP8_BLOCK_SIZE: + raise NotImplementedError( + f"MXFP8 checkpoint scale block {ctx.scale_block_size} is unsupported" + ) + + def scaled_loader(param, loaded_weight, *args, **kwargs): + assert loaded_weight.dtype in (torch.uint8, torch.float8_e8m0fnu) + loaded_weight = loaded_weight.view(torch.uint8).repeat_interleave( + block_rows, dim=0 + ) + return weight_loader(param, loaded_weight, *args, **kwargs) + + return scaled_loader if block_rows > 1 else weight_loader + def create_weights(self, layer, role, ctx, shapes, wl) -> None: if role is not WEIGHT: self.reject(role) @@ -2171,6 +2189,7 @@ class KMxfp8Static(QuantKeyScheme): input_dim=1, output_dim=0, ) + scale_loader = self.get_scale_weight_loader(wl, ctx) self.register_params( layer, "weight_scale", @@ -2180,10 +2199,11 @@ class KMxfp8Static(QuantKeyScheme): ), MXFP8_SCALE_DTYPE, ModelWeightParameter, - wl, + scale_loader, input_dim=1, output_dim=0, ) + layer.weight_block_size = [1, MXFP8_BLOCK_SIZE] def process(self, layer, role) -> None: if role is not WEIGHT: @@ -2194,6 +2214,8 @@ class KMxfp8Static(QuantKeyScheme): # the fp8 asserts when the weight is already >=2-byte. if layer.weight.element_size() >= 2: return + if getattr(layer, "is_bmm", False) and layer.weight.ndim == 3: + return assert layer.weight.ndim == 2 and layer.weight.dtype == MXFP8_VALUE_DTYPE assert layer.weight_scale.ndim == 2 assert layer.weight_scale.dtype == MXFP8_SCALE_DTYPE @@ -2255,7 +2277,9 @@ def select_linear_kernel( # after #50273); W4A4 → use_a16=False. return init_nvfp4_linear_kernel(use_a16=spec.activation is None) if w.scale.dtype == MXFP8_SCALE_DTYPE: - return init_mxfp8_linear_kernel() + return init_mxfp8_linear_kernel( + bmm_batch_size=getattr(layer, "bmm_batch_size", None) + ) # fp8 family: init_fp8 routes block-vs-plain itself off the activation key, # and needs a real key -- weight-only fp8 is not a ModelOpt format. act = spec.activation @@ -2482,6 +2506,8 @@ class ModelOptLinearMethod(LinearMethodBase): persistent=False, ) layer._nvfp4_group_size_for_gather = self.ctx.group_size + if self.spec.weight == kMxfp8Static and getattr(layer, "is_bmm", False): + self.kernel = init_mxfp8_linear_kernel(bmm_batch_size=layer.bmm_batch_size) self.kernel.process_weights_after_loading(layer) def apply(self, layer, x, bias=None): diff --git a/vllm/model_executor/layers/sparse_attn_indexer.py b/vllm/model_executor/layers/sparse_attn_indexer.py index 72a9a2d5a9..7d656f06e8 100644 --- a/vllm/model_executor/layers/sparse_attn_indexer.py +++ b/vllm/model_executor/layers/sparse_attn_indexer.py @@ -13,6 +13,12 @@ from vllm.distributed import get_dcp_group, get_pcp_group from vllm.forward_context import get_forward_context from vllm.logger import init_logger from vllm.model_executor.custom_op import CustomOp +from vllm.model_executor.kernels.attention.dsa.candidate_blocks import ( + apply_candidate_mask as _apply_candidate_mask, +) +from vllm.model_executor.kernels.attention.dsa.candidate_blocks import ( + select_candidate_blocks as _select_candidate_blocks, +) from vllm.model_executor.layers.quantization.utils.quant_utils import ( get_fp8_min_max, ) @@ -316,6 +322,9 @@ def sparse_attn_indexer( dcp_world_size: int = 1, cp_kv_cache_interleave_size: int = 1, skip_topk_buffer_clear: bool = False, + candidate_blocks: torch.Tensor | None = None, + candidate_block_size: int = 0, + candidate_write: bool = False, ) -> torch.Tensor: # careful! this will be None in dummy run forward_context = get_forward_context() @@ -323,6 +332,14 @@ def sparse_attn_indexer( fp8_dtype = current_platform.fp8_dtype() k_cache_prefix = _resolve_layer_name(k_cache_prefix) + if candidate_blocks is not None: + # Candidate blocks are request-local; the DCP-sharded logits layout + # would need per-rank translation that is not implemented. + assert dcp_world_size == 1, ( + "v4.1 two-level candidate filtering is not supported with DCP." + ) + assert candidate_block_size > 0 + # assert isinstance(attn_metadata, dict) if not isinstance(attn_metadata, dict): # Reserve workspace for indexer during profiling run @@ -361,6 +378,9 @@ def sparse_attn_indexer( use_pcp, dense_mha_metadata_layer_name, use_fp4_cache, + candidate_blocks=candidate_blocks, + candidate_block_size=candidate_block_size, + candidate_write=candidate_write, ) attn_metadata_narrowed = attn_metadata[k_cache_prefix] assert isinstance(attn_metadata_narrowed, DeepseekV32IndexerMetadata) @@ -506,6 +526,30 @@ def sparse_attn_indexer( clean_logits=False, ) num_rows = logits.shape[0] + if candidate_blocks is not None: + # Two-level selection (v4.1): the candidate source + # publishes its top blocks; later indexers mask their + # scores to them. Both before the row top-k. + chunk_candidates = candidate_blocks[ + chunk.token_start : chunk.token_end + ] + if candidate_write: + _select_candidate_blocks( + logits, + cu_seqlen_ks, + cu_seqlen_ke, + chunk_candidates.shape[1], + candidate_block_size, + chunk_candidates, + ) + else: + _apply_candidate_mask( + logits, + cu_seqlen_ks, + cu_seqlen_ke, + chunk_candidates, + candidate_block_size, + ) ops.top_k_per_row_prefill( logits, cu_seqlen_ks, @@ -612,6 +656,34 @@ def sparse_attn_indexer( indices=decode_metadata.indices, ) num_rows = logits.shape[0] + if candidate_blocks is not None: + # Two-level selection (v4.1) on the decode logits; columns are + # request-local compressed positions. seq_lens is (B, next_n) + # for native spec decode (per-row effective lens) and (B, 1) + # otherwise. + vis = seq_lens.reshape(-1) + row_repeat = next_n if vis.numel() != num_rows else 1 + vis = vis[:num_rows] + decode_candidates = candidate_blocks[:num_rows] + if candidate_write: + _select_candidate_blocks( + logits, + None, + vis, + decode_candidates.shape[1], + candidate_block_size, + decode_candidates, + row_repeat, + ) + else: + _apply_candidate_mask( + logits, + None, + vis, + decode_candidates, + candidate_block_size, + row_repeat, + ) topk_indices = topk_indices_buffer[:num_padded_tokens, :topk_tokens] use_cooperative_topk = ( @@ -712,6 +784,9 @@ def sparse_attn_indexer_fake( dcp_world_size: int = 1, cp_kv_cache_interleave_size: int = 1, skip_topk_buffer_clear: bool = False, + candidate_blocks: torch.Tensor | None = None, + candidate_block_size: int = 0, + candidate_write: bool = False, ) -> torch.Tensor: return topk_indices_buffer @@ -719,7 +794,7 @@ def sparse_attn_indexer_fake( direct_register_custom_op( op_name="sparse_attn_indexer", op_func=sparse_attn_indexer, - mutates_args=["topk_indices_buffer"], + mutates_args=["topk_indices_buffer", "candidate_blocks"], fake_impl=sparse_attn_indexer_fake, dispatch_key=current_platform.dispatch_key, ) @@ -751,6 +826,9 @@ class SparseAttnIndexer(CustomOp): skip_k_cache_insert: bool = False, use_fp4_cache: bool = False, compress_ratio: int = 1, + candidate_blocks: torch.Tensor | None = None, + candidate_block_size: int = 0, + candidate_write: bool = False, ): super().__init__() self.k_cache = k_cache @@ -764,6 +842,11 @@ class SparseAttnIndexer(CustomOp): self.skip_k_cache_insert = skip_k_cache_insert self.use_fp4_cache = use_fp4_cache self.compress_ratio = compress_ratio + # v4.1 two-level selection: the candidate source indexer writes the + # top candidate blocks here; later indexers mask their scores with it. + self.candidate_blocks = candidate_blocks + self.candidate_block_size = candidate_block_size + self.candidate_write = candidate_write self.dense_mha_metadata_layer_name = "" # DCP scalars are constant for the run; resolve them here (config is set # during model construction) and pass them into the custom op, rather @@ -871,6 +954,9 @@ class SparseAttnIndexer(CustomOp): self.dcp_rank, self.dcp_world_size, self.cp_kv_cache_interleave_size, + candidate_blocks=self.candidate_blocks, + candidate_block_size=self.candidate_block_size, + candidate_write=self.candidate_write, ) def forward_xpu( @@ -893,12 +979,16 @@ class SparseAttnIndexer(CustomOp): assert isinstance(q_quant, torch.Tensor), ( "AMD sparse_attn_indexer expects a single FP8 q_quant tensor" ) - from vllm.platforms.rocm import on_gfx11 + from vllm.platforms.rocm import on_gfx11, on_gfx950 if ( rocm_aiter_ops.is_enabled() or rocm_aiter_ops.is_rdna_aiter_enabled() or on_gfx11() + # The so-called AITER sparse indexer op has a native gfx950 path: + # its cache insert, MQA logits, and top-k fallbacks are implemented + # by local Triton/C++ kernels and do not require the aiter package. + or on_gfx950() ): return torch.ops.vllm.rocm_aiter_sparse_attn_indexer( hidden_states, @@ -916,10 +1006,13 @@ class SparseAttnIndexer(CustomOp): self.topk_indices_buffer, skip_k_cache_insert=self.skip_k_cache_insert, compress_ratio=self.compress_ratio, + candidate_blocks=self.candidate_blocks, + candidate_block_size=self.candidate_block_size, + candidate_write=self.candidate_write, ) raise RuntimeError( - "Sparse attention indexer ROCm path is only supported on AITER. " - "Please enable aiter with VLLM_ROCM_USE_AITER=1" + "Sparse attention indexer ROCm path requires AITER or a supported " + "native architecture (gfx950/gfx11)." ) def forward_cpu( diff --git a/vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py b/vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py index 87323926ef..948d84be5c 100644 --- a/vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py +++ b/vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py @@ -32,37 +32,39 @@ class FusedInvRopeFP8QuantKernel( fp8_max: float quant_group_size: int chunks_per_head: int - rope_start: int + nope_dim: int half_rope: int tma_aligned_scales: bool launch_pdl: bool + quantize: bool @staticmethod # scale_stride_k = align(num_tokens, 4) is only 4-aligned, so its Triton int # class varies with batch size; not specialized so one warmup key covers all - # (int64-cast, scalar addressing only, so perf-neutral). + # (int64-cast, so perf-neutral). @triton.jit(do_not_specialize=["num_tokens", "scale_stride_k"]) def kernel( o_ptr, positions_ptr, cos_sin_cache_ptr, - fp8_ptr, + out_ptr, scale_ptr, num_tokens, heads_per_group: tl.constexpr, o_stride_token, o_stride_head, cache_stride_pos, - fp8_stride_group, - fp8_stride_token, + out_stride_group, + out_stride_token, scale_stride_group, scale_stride_k, fp8_max: tl.constexpr, eps: tl.constexpr, QUANT_GROUP_SIZE: tl.constexpr, CHUNKS_PER_HEAD: tl.constexpr, - ROPE_START: tl.constexpr, + NOPE_DIM: tl.constexpr, HALF_ROPE: tl.constexpr, + QUANTIZE: tl.constexpr, TMA_ALIGNED_SCALES: tl.constexpr, launch_pdl: tl.constexpr, ): @@ -74,8 +76,8 @@ class FusedInvRopeFP8QuantKernel( o_stride_token = o_stride_token.to(tl.int64) o_stride_head = o_stride_head.to(tl.int64) cache_stride_pos = cache_stride_pos.to(tl.int64) - fp8_stride_group = fp8_stride_group.to(tl.int64) - fp8_stride_token = fp8_stride_token.to(tl.int64) + out_stride_group = out_stride_group.to(tl.int64) + out_stride_token = out_stride_token.to(tl.int64) scale_stride_group = scale_stride_group.to(tl.int64) scale_stride_k = scale_stride_k.to(tl.int64) @@ -88,14 +90,18 @@ class FusedInvRopeFP8QuantKernel( tl.extra.cuda.gdc_wait() # Padding rows in the TMA-aligned scale buffer: fill with zero and skip quant. if pid_token >= num_tokens: + if not QUANTIZE: + return if TMA_ALIGNED_SCALES: + packed_offsets = tl.arange(0, CHUNKS_PER_HEAD // 4) scale_addr = ( scale_ptr + g * scale_stride_group + pid_token - + head_in_group * scale_stride_k + + (head_in_group * (CHUNKS_PER_HEAD // 4) + packed_offsets) + * scale_stride_k ) - tl.store(scale_addr, tl.zeros((), dtype=tl.int32)) + tl.store(scale_addr, tl.zeros((CHUNKS_PER_HEAD // 4,), dtype=tl.int32)) else: block_offsets = tl.arange(0, CHUNKS_PER_HEAD) qb_indices = qb_start + block_offsets @@ -114,9 +120,7 @@ class FusedInvRopeFP8QuantKernel( offsets = tl.arange(0, HEAD_DIM) x = tl.load(input_base + offsets).to(tl.float32) - rope_abs_start: tl.constexpr = ( - CHUNKS_PER_HEAD - 1 - ) * QUANT_GROUP_SIZE + ROPE_START + rope_abs_start: tl.constexpr = NOPE_DIM pos = tl.load(positions_ptr + pid_token) cache_base = cos_sin_cache_ptr + pos * cache_stride_pos is_rope = offsets >= rope_abs_start @@ -134,6 +138,16 @@ class FusedInvRopeFP8QuantKernel( rotated = tl.where(is_even, x_add, x_sub) x = tl.where(is_rope, rotated, x) + if not QUANTIZE: + out_base = ( + out_ptr + + g * out_stride_group + + pid_token * out_stride_token + + qb_start * QUANT_GROUP_SIZE + ) + tl.store(out_base + offsets, x) + return + x_2d = tl.reshape(tl.abs(x), (CHUNKS_PER_HEAD, QUANT_GROUP_SIZE)) block_absmax = tl.maximum(tl.max(x_2d, axis=1), eps) scale_raw = block_absmax * (1.0 / fp8_max) @@ -148,25 +162,31 @@ class FusedInvRopeFP8QuantKernel( ) x_quant = tl.clamp(x / scales_exp, -fp8_max, fp8_max).to(tl.float8e4nv) - fp8_base = ( - fp8_ptr - + g * fp8_stride_group - + pid_token * fp8_stride_token + out_base = ( + out_ptr + + g * out_stride_group + + pid_token * out_stride_token + qb_start * QUANT_GROUP_SIZE ) - tl.store(fp8_base + offsets, x_quant) + tl.store(out_base + offsets, x_quant) block_offsets = tl.arange(0, CHUNKS_PER_HEAD) qb_indices = qb_start + block_offsets if TMA_ALIGNED_SCALES: scale_bits = scales.to(tl.int32, bitcast=True) ue8m0_bytes = (scale_bits >> 23) & 0xFF - packed_val = tl.sum(ue8m0_bytes << (block_offsets * 8)) + packed_val = tl.sum( + tl.reshape(ue8m0_bytes, (CHUNKS_PER_HEAD // 4, 4)) + << (tl.arange(0, 4)[None, :] * 8), + axis=1, + ) + packed_offsets = tl.arange(0, CHUNKS_PER_HEAD // 4) scale_addr = ( scale_ptr + g * scale_stride_group + pid_token - + head_in_group * scale_stride_k + + (head_in_group * (CHUNKS_PER_HEAD // 4) + packed_offsets) + * scale_stride_k ) tl.store(scale_addr, packed_val) else: @@ -188,7 +208,7 @@ class FusedInvRopeFP8QuantKernel( quant_group_size: int, runtime_fp8_max: float | None = None, runtime_chunks_per_head: int | None = None, - runtime_rope_start: int | None = None, + runtime_nope_dim: int | None = None, runtime_half_rope: int | None = None, **compile_key_fields: bool, ) -> CompileKey: @@ -202,11 +222,7 @@ class FusedInvRopeFP8QuantKernel( if runtime_chunks_per_head is not None else head_dim // quant_group_size ) - rope_start = ( - runtime_rope_start - if runtime_rope_start is not None - else nope_dim % quant_group_size - ) + nope_dim = runtime_nope_dim if runtime_nope_dim is not None else nope_dim half_rope = ( runtime_half_rope if runtime_half_rope is not None else rope_dim // 2 ) @@ -216,7 +232,7 @@ class FusedInvRopeFP8QuantKernel( fp8_max=fp8_max, quant_group_size=quant_group_size, chunks_per_head=chunks_per_head, - rope_start=rope_start, + nope_dim=nope_dim, half_rope=half_rope, ) @@ -250,11 +266,12 @@ class FusedInvRopeFP8QuantKernel( quant_group_size=128, tma_aligned_scales=capability.major >= 10, launch_pdl=current_platform.is_arch_support_pdl(), + quantize=True, ) def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]: head_dim = compile_key.chunks_per_head * compile_key.quant_group_size - fp8_dim = compile_key.heads_per_group * head_dim + out_dim = compile_key.heads_per_group * head_dim scale_dtype = torch.int32 if compile_key.tma_aligned_scales else torch.float32 return dict( o=TritonWarmupTensor( @@ -266,10 +283,10 @@ class FusedInvRopeFP8QuantKernel( torch.float32, shape=(1, compile_key.half_rope * 2), ), - fp8_buf=TritonWarmupTensor( - torch.float8_e4m3fn, - shape=(compile_key.heads_per_group, 1, fp8_dim), - strides=(fp8_dim, fp8_dim, 1), + out_buf=TritonWarmupTensor( + torch.float8_e4m3fn if compile_key.quantize else torch.bfloat16, + shape=(compile_key.heads_per_group, 1, out_dim), + strides=(out_dim, out_dim, 1), ), scale_buf=TritonWarmupTensor( scale_dtype, @@ -280,9 +297,10 @@ class FusedInvRopeFP8QuantKernel( heads_per_group=compile_key.heads_per_group, quant_group_size=compile_key.quant_group_size, chunks_per_head=compile_key.chunks_per_head, - rope_start=compile_key.rope_start, + nope_dim=compile_key.nope_dim, half_rope=compile_key.half_rope, tma_aligned_scales=compile_key.tma_aligned_scales, + quantize=compile_key.quantize, fp8_max=compile_key.fp8_max, launch_pdl=compile_key.launch_pdl, grid=(1, compile_key.heads_per_group), @@ -294,35 +312,37 @@ class FusedInvRopeFP8QuantKernel( o: torch.Tensor, positions: torch.Tensor, cos_sin_cache: torch.Tensor, - fp8_buf: torch.Tensor, + out_buf: torch.Tensor, scale_buf: torch.Tensor, num_tokens: int, *, heads_per_group: int, quant_group_size: int, chunks_per_head: int, - rope_start: int, + nope_dim: int, half_rope: int, tma_aligned_scales: bool, + quantize: bool, fp8_max: float, launch_pdl: bool, grid: tuple[int, int], ) -> LaunchSpec: return grid, dict( - fp8_ptr=fp8_buf, + out_ptr=out_buf, scale_ptr=scale_buf, o_stride_token=o.stride(0), o_stride_head=o.stride(1), cache_stride_pos=cos_sin_cache.stride(0), - fp8_stride_group=fp8_buf.stride(0), - fp8_stride_token=fp8_buf.stride(1), - scale_stride_group=scale_buf.stride(0), - scale_stride_k=scale_buf.stride(2), + out_stride_group=out_buf.stride(0), + out_stride_token=out_buf.stride(1), + scale_stride_group=scale_buf.stride(0) if quantize else 0, + scale_stride_k=scale_buf.stride(2) if quantize else 0, eps=1e-10, QUANT_GROUP_SIZE=quant_group_size, CHUNKS_PER_HEAD=chunks_per_head, - ROPE_START=rope_start, + NOPE_DIM=nope_dim, HALF_ROPE=half_rope, + QUANTIZE=quantize, TMA_ALIGNED_SCALES=tma_aligned_scales, launch_pdl=launch_pdl, num_stages=1, @@ -340,6 +360,7 @@ def fused_inv_rope_fp8_quant( rope_dim: int = 64, quant_group_size: int = 128, tma_aligned_scales: bool = False, + quantize: bool = True, ) -> tuple[torch.Tensor, torch.Tensor]: """Fused inverse RoPE + block-scaled FP8 quantization. @@ -354,10 +375,11 @@ def fused_inv_rope_fp8_quant( quant_group_size: FP8 quantization block size (default 128). tma_aligned_scales: Output INT32 packed UE8M0 for SM100 (True) or FP32 for SM90 (False). + quantize: Quantize the rotated output to FP8 and return its scales. Returns: - o_fp8: [T, G, D] float8_e4m3fn, strides (D, T*D, 1). - o_scale: Pre-transformed scale tensor for fp8_einsum. + Rotated output in [T, G, D] and its FP8 scales. The scale tensor is + empty when quantization is disabled. """ from vllm.utils.deep_gemm import get_tma_aligned_size @@ -365,7 +387,6 @@ def fused_inv_rope_fp8_quant( assert num_heads == n_groups * heads_per_group assert head_dim == nope_dim + rope_dim assert head_dim % quant_group_size == 0 - assert nope_dim % quant_group_size == (quant_group_size - rope_dim) assert rope_dim % 2 == 0 assert cos_sin_cache.shape[-1] == rope_dim assert cos_sin_cache.dtype == torch.float32 @@ -377,23 +398,26 @@ def fused_inv_rope_fp8_quant( fp8_dtype = torch.float8_e4m3fn fp8_max = torch.finfo(fp8_dtype).max - tma_aligned_T = get_tma_aligned_size(num_tokens, 4) - if tma_aligned_scales: + tma_aligned_T = get_tma_aligned_size(num_tokens, 4) if quantize else num_tokens + if quantize and tma_aligned_scales: + assert chunks_per_head % 4 == 0 packed_sf_k = (num_scale_blocks + 3) // 4 scale_inner = packed_sf_k - else: + elif quantize: scale_inner = num_scale_blocks + else: + scale_inner = 0 # Run kernel through a custom op so inductor sees an opaque boundary. # It's a pytorch bug, see https://github.com/vllm-project/vllm/issues/41106 - fp8_buf, scale_buf = torch.ops.vllm.fused_inv_rope_fp8_quant_kernel( + out_buf, scale_buf = torch.ops.vllm.fused_inv_rope_fp8_quant_kernel( o, positions, cos_sin_cache, heads_per_group, quant_group_size, chunks_per_head, - nope_dim % quant_group_size, + nope_dim, rope_dim // 2, tma_aligned_scales, fp8_max, @@ -402,8 +426,11 @@ def fused_inv_rope_fp8_quant( n_groups, d, scale_inner, + quantize, ) - return fp8_buf.transpose(0, 1), scale_buf.transpose(0, 1) + output = out_buf.transpose(0, 1) + scales = scale_buf.transpose(0, 1) if quantize else scale_buf + return output, scales def _fused_inv_rope_fp8_quant_kernel_impl( @@ -413,7 +440,7 @@ def _fused_inv_rope_fp8_quant_kernel_impl( heads_per_group: int, quant_group_size: int, chunks_per_head: int, - rope_start: int, + nope_dim: int, half_rope: int, tma_aligned_scales: bool, fp8_max: float, @@ -422,41 +449,46 @@ def _fused_inv_rope_fp8_quant_kernel_impl( n_groups: int, d: int, scale_inner: int, + quantize: bool, ) -> tuple[torch.Tensor, torch.Tensor]: - fp8_buf = torch.empty( - (n_groups, num_tokens, d), - dtype=torch.float8_e4m3fn, - device=o.device, - ) scale_dtype = torch.int32 if tma_aligned_scales else torch.float32 - scale_buf = torch.empty( - n_groups * scale_inner * tma_aligned_T, - dtype=scale_dtype, + out_buf = torch.empty( + (n_groups, num_tokens, d), + dtype=torch.float8_e4m3fn if quantize else o.dtype, device=o.device, - ).as_strided( - (n_groups, num_tokens, scale_inner), - (scale_inner * tma_aligned_T, 1, tma_aligned_T), ) + if quantize: + scale_buf = torch.empty( + n_groups * scale_inner * tma_aligned_T, + dtype=scale_dtype, + device=o.device, + ).as_strided( + (n_groups, num_tokens, scale_inner), + (scale_inner * tma_aligned_T, 1, tma_aligned_T), + ) + else: + scale_buf = torch.empty(0, dtype=scale_dtype, device=o.device) grid = (tma_aligned_T, n_groups * heads_per_group) launch_pdl = current_platform.is_arch_support_pdl() _FUSED_INV_ROPE_FP8_QUANT_KERNEL( o, positions, cos_sin_cache, - fp8_buf, + out_buf, scale_buf, num_tokens, heads_per_group=heads_per_group, quant_group_size=quant_group_size, chunks_per_head=chunks_per_head, - rope_start=rope_start, + nope_dim=nope_dim, half_rope=half_rope, tma_aligned_scales=tma_aligned_scales, + quantize=quantize, fp8_max=fp8_max, launch_pdl=launch_pdl, grid=grid, ) - return fp8_buf, scale_buf + return out_buf, scale_buf def _fused_inv_rope_fp8_quant_kernel_fake( @@ -466,7 +498,7 @@ def _fused_inv_rope_fp8_quant_kernel_fake( heads_per_group: int, quant_group_size: int, chunks_per_head: int, - rope_start: int, + nope_dim: int, half_rope: int, tma_aligned_scales: bool, fp8_max: float, @@ -475,13 +507,16 @@ def _fused_inv_rope_fp8_quant_kernel_fake( n_groups: int, d: int, scale_inner: int, + quantize: bool, ) -> tuple[torch.Tensor, torch.Tensor]: - fp8_buf = torch.empty( + scale_dtype = torch.int32 if tma_aligned_scales else torch.float32 + out_buf = torch.empty( (n_groups, num_tokens, d), - dtype=torch.float8_e4m3fn, + dtype=torch.float8_e4m3fn if quantize else o.dtype, device=o.device, ) - scale_dtype = torch.int32 if tma_aligned_scales else torch.float32 + if not quantize: + return out_buf, torch.empty(0, dtype=scale_dtype, device=o.device) scale_buf = torch.empty( n_groups * scale_inner * tma_aligned_T, dtype=scale_dtype, @@ -490,7 +525,7 @@ def _fused_inv_rope_fp8_quant_kernel_fake( (n_groups, num_tokens, scale_inner), (scale_inner * tma_aligned_T, 1, tma_aligned_T), ) - return fp8_buf, scale_buf + return out_buf, scale_buf direct_register_custom_op( diff --git a/vllm/models/deepseek_v4/common/vision.py b/vllm/models/deepseek_v4/common/vision.py index a54c35e52c..46468897e5 100644 --- a/vllm/models/deepseek_v4/common/vision.py +++ b/vllm/models/deepseek_v4/common/vision.py @@ -11,13 +11,18 @@ embed and norms are replicated, so the residual stream is full-width on every rank. """ +import itertools from functools import lru_cache import torch import torch.nn.functional as F from torch import nn -from vllm.distributed import get_tensor_model_parallel_world_size +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, + tensor_model_parallel_all_gather, +) from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.attention.mm_encoder_attention import ( MMEncoderAttention, @@ -29,7 +34,10 @@ from vllm.model_executor.layers.linear import ( ReplicatedLinear, RowParallelLinear, ) -from vllm.model_executor.models.vision import is_vit_use_data_parallel +from vllm.model_executor.models.vision import ( + get_load_balance_assignment, + is_vit_use_data_parallel, +) @lru_cache(8) @@ -206,6 +214,7 @@ class DeepseekV4Aligner(nn.Module): super().__init__() use_data_parallel = is_vit_use_data_parallel(config.vision_n_heads) self.downsample_ratio = config.vision_downsample_ratio + self.out_dim = config.hidden_size in_dim = config.vision_dim * self.downsample_ratio**2 self.w1 = ColumnParallelLinear( in_dim, @@ -230,3 +239,85 @@ class DeepseekV4Aligner(nn.Module): hidden, _ = self.w1(x) out, _ = self.w2(F.gelu(hidden)) return out + + +def run_dp_sharded_vision_tower( + vision_model: DeepseekV4ViT, + aligner: DeepseekV4Aligner, + patches: torch.Tensor, + vit_grid: list[list[int]], +) -> list[torch.Tensor]: + """Run the ViT + aligner with images sharded across TP ranks. + + Every rank holds the full tower weights (``--mm-encoder-tp-mode data``) + and receives the full ``patches`` batch. Images are assigned to ranks by + patch count (greedy load balancing), each rank encodes only its share, + and per-image embeddings are exchanged with one padded all-gather and + returned in the original image order. + + Args: + vision_model: The (weight-replicated) ViT tower. + aligner: The (weight-replicated) spatial-merge projector. + patches: ``(sum(n_vit_h * n_vit_w), 3, p, p)`` patches of all images. + vit_grid: ``[n_vit_h, n_vit_w]`` per image. + + Returns: + One ``(n_aligner_rows, hidden_size)`` embedding tensor per image. + """ + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + + sizes = [h * w for h, w in vit_grid] + cum_patches = [0, *itertools.accumulate(sizes)] + image_to_tp_rank, gpu_sample_counts, _ = get_load_balance_assignment(sizes, tp_size) + cum_sample_counts = [0, *itertools.accumulate(gpu_sample_counts)] + + # Rows the aligner emits per image: each grid dim is padded up to a + # multiple of the merge ratio before r x r patches fold into one row. + r = aligner.downsample_ratio + rows_per_image = [-(-h // r) * -(-w // r) for h, w in vit_grid] + + def rank_image_idxs(g: int) -> list[int]: + return image_to_tp_rank[cum_sample_counts[g] : cum_sample_counts[g + 1]] + + # All-gather needs one shape on every rank; pad each rank's packed + # output to the largest per-rank row count (computable locally). + max_rows = max( + sum(rows_per_image[i] for i in rank_image_idxs(g)) for g in range(tp_size) + ) + + local_embeds = [ + aligner( + vision_model( + patches[cum_patches[i] : cum_patches[i + 1]], + vit_grid[i][0], + vit_grid[i][1], + ), + vit_grid[i][0], + vit_grid[i][1], + ) + for i in rank_image_idxs(tp_rank) + ] + if local_embeds: + embeds_local = torch.cat(local_embeds, dim=0) + else: + embeds_local = patches.new_zeros((0, aligner.out_dim)) + if embeds_local.shape[0] < max_rows: + embeds_local = torch.cat( + [ + embeds_local, + embeds_local.new_zeros( + (max_rows - embeds_local.shape[0], embeds_local.shape[1]) + ), + ], + dim=0, + ) + gathered = tensor_model_parallel_all_gather(embeds_local.contiguous(), dim=0) + + out: list[torch.Tensor] = [None] * len(vit_grid) # type: ignore[list-item] + for g in range(tp_size): + offset = g * max_rows + for i in rank_image_idxs(g): + out[i] = gathered[offset : offset + rows_per_image[i]] + offset += rows_per_image[i] + return out diff --git a/vllm/models/deepseek_v4/nvidia/model.py b/vllm/models/deepseek_v4/nvidia/model.py index be4e87e776..021001b9ce 100644 --- a/vllm/models/deepseek_v4/nvidia/model.py +++ b/vllm/models/deepseek_v4/nvidia/model.py @@ -368,9 +368,17 @@ class DeepseekV4MegaMoEExperts(nn.Module): gate_up = shared_experts.gate_up_proj down = shared_experts.down_proj gate_up_weight = gate_up.weight.data - gate_up_scale = gate_up.weight_scale_inv.data + gate_up_scale = ( + gate_up.weight_scale + if hasattr(gate_up, "weight_scale") + else gate_up.weight_scale_inv + ).data down_weight = down.weight.data - down_scale = down.weight_scale_inv.data + down_scale = ( + down.weight_scale + if hasattr(down, "weight_scale") + else down.weight_scale_inv + ).data # MegaMoE's shared FP8 MMA consumes a 1x32 scale for every weight row, # while the checkpoint uses coarser block-FP8 scales (usually @@ -507,6 +515,23 @@ class DeepseekV4MegaMoEExperts(nn.Module): if self._transformed_l1_weights is None: self._check_runtime_supported() + # MegaMoE's 1x32 activation scales need 16-byte TMA rows, so + # pad each gate/up half and the down projection to a multiple of 512. + padded_size = (self.intermediate_size + 511) // 512 * 512 + padding = padded_size - self.intermediate_size + if padding: + for param in (self.w13_weight, self.w13_weight_scale): + gate_up = param.data.unflatten(1, (2, self.intermediate_size)) + param.data = torch.nn.functional.pad( + gate_up, (0, 0, 0, padding) + ).flatten(1, 2) + self.w2_weight.data = torch.nn.functional.pad( + self.w2_weight.data, (0, padding // 2) + ) + self.w2_weight_scale.data = torch.nn.functional.pad( + self.w2_weight_scale.data, (0, padding // 32) + ) + self.intermediate_size = padded_size w13_scale = deep_gemm.transform_sf_into_required_layout( self._ue8m0_uint8_to_float(self.w13_weight_scale.data).contiguous(), 2 * self.intermediate_size, @@ -752,6 +777,11 @@ class DeepseekV4MoE(nn.Module): vllm_config: VllmConfig, prefix: str = "", use_sequence_parallel: bool = False, + *, + num_hash_layers: int, + n_routed_experts: int | None = None, + n_activated_experts: int | None = None, + image_sentinel_lo: int = IMAGE_SENTINEL_BASE_ID, ): super().__init__() @@ -774,8 +804,14 @@ class DeepseekV4MoE(nn.Module): self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0) self.hidden_size = config.hidden_size - self.n_routed_experts = config.n_routed_experts - self.n_activated_experts = config.num_experts_per_tok + self.n_routed_experts = ( + config.n_routed_experts if n_routed_experts is None else n_routed_experts + ) + self.n_activated_experts = ( + config.num_experts_per_tok + if n_activated_experts is None + else n_activated_experts + ) self.moe_intermediate_size = config.moe_intermediate_size self.swiglu_limit = config.swiglu_limit self.renormalize = config.norm_topk_prob @@ -793,7 +829,7 @@ class DeepseekV4MoE(nn.Module): self.gate = GateLinear( input_size=config.hidden_size, - output_size=config.n_routed_experts, + output_size=self.n_routed_experts, bias=False, out_dtype=torch.float32, prefix=f"{prefix}.gate", @@ -805,9 +841,9 @@ class DeepseekV4MoE(nn.Module): # Image tokens borrow five consecutive reserved in-vocab ids starting # at IMAGE_SENTINEL_BASE_ID; 0 disables vision routing (text model). self.image_sentinel_lo = ( - IMAGE_SENTINEL_BASE_ID if getattr(config, "vision_n_layers", 0) > 0 else 0 + image_sentinel_lo if getattr(config, "vision_n_layers", 0) > 0 else 0 ) - is_hash_moe = extract_layer_index(prefix) < config.num_hash_layers + is_hash_moe = extract_layer_index(prefix) < num_hash_layers self.hash_indices_dtype = torch.int64 if self.use_mega_moe else torch.int32 if is_hash_moe: # hash MoE doesn't use e_score_correction_bias @@ -816,8 +852,8 @@ class DeepseekV4MoE(nn.Module): self.gate.tid2eid = nn.Parameter( torch.randint( 0, - config.n_routed_experts, - (config.vocab_size, config.num_experts_per_tok), + self.n_routed_experts, + (config.vocab_size, self.n_activated_experts), dtype=self.hash_indices_dtype, ), requires_grad=False, @@ -828,7 +864,7 @@ class DeepseekV4MoE(nn.Module): # Vision checkpoints ship a gate bias on hash layers too (it is # unused for routing there; image tokens use bias_vl instead). self.gate.e_score_correction_bias = nn.Parameter( - torch.empty(config.n_routed_experts, dtype=torch.float32), + torch.empty(self.n_routed_experts, dtype=torch.float32), requires_grad=False, ) @@ -837,7 +873,7 @@ class DeepseekV4MoE(nn.Module): # instead of e_score_correction_bias / the hash table. Created on # every MoE layer, hash layers included. self.gate.bias_vl = nn.Parameter( - torch.empty(config.n_routed_experts, dtype=torch.float32), + torch.empty(self.n_routed_experts, dtype=torch.float32), requires_grad=False, ) @@ -874,7 +910,6 @@ class DeepseekV4MoE(nn.Module): eplb_config = vllm_config.parallel_config.eplb_config self.n_redundant_experts = eplb_config.num_redundant_experts - self.n_routed_experts = config.n_routed_experts self.n_shared_experts = config.n_shared_experts or 0 self.n_logical_experts = self.n_routed_experts self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts @@ -922,7 +957,7 @@ class DeepseekV4MoE(nn.Module): num_local_experts=self.n_local_physical_experts, experts_start_idx=self.physical_expert_start, num_logical_experts=self.n_logical_experts, - top_k=config.num_experts_per_tok, + top_k=self.n_activated_experts, hidden_size=config.hidden_size, intermediate_size=config.moe_intermediate_size, num_shared_experts=(self.n_shared_experts if fuse_shared_experts else 0), @@ -961,8 +996,8 @@ class DeepseekV4MoE(nn.Module): self.experts = FusedMoEFactory( shared_experts=self.shared_experts, gate=self.gate, - num_experts=config.n_routed_experts, - top_k=config.num_experts_per_tok, + num_experts=self.n_routed_experts, + top_k=self.n_activated_experts, hidden_size=config.hidden_size, intermediate_size=config.moe_intermediate_size, renormalize=config.norm_topk_prob, @@ -1120,6 +1155,7 @@ class DeepseekV4DecoderLayer(nn.Module): vllm_config, prefix=f"{prefix}.ffn", use_sequence_parallel=self.use_sequence_parallel, + num_hash_layers=config.num_hash_layers, ) self.attn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps) diff --git a/vllm/models/deepseek_v4/nvidia/ops/fused_indexer_q_cutedsl.py b/vllm/models/deepseek_v4/nvidia/ops/fused_indexer_q_cutedsl.py index 3bd5e1b52f..16e98abf23 100644 --- a/vllm/models/deepseek_v4/nvidia/ops/fused_indexer_q_cutedsl.py +++ b/vllm/models/deepseek_v4/nvidia/ops/fused_indexer_q_cutedsl.py @@ -165,9 +165,13 @@ class IndexerQRopeQuantKernel: # NOTE: token_id may exceed bounds, hence we need to add load/store guards # we can't do early exit because CuteDSL doesn't support it. and we also need # all threads in a warp to be active since we utilize warp shuffle later. - # must_in_bounds is constexpr, True when 1 threadblock fit within 1 token - # position. the compiler will remove bounds check when that happens. - must_in_bounds = cutlass.const_expr(self.tb_size % self.threads_per_token == 0) + # must_in_bounds is constexpr, True when a token spans a whole number of + # threadblocks. Then num_tokens * threads_per_token is always a multiple of + # tb_size, so the trailing block never straddles num_tokens and the compiler + # removes the bounds check. Otherwise the guard has to stay: e.g. 32 heads + # with coarsen=4 needs 64 threads per token, so an odd num_tokens leaves half + # of the last block addressing token num_tokens. + must_in_bounds = cutlass.const_expr(self.threads_per_token % self.tb_size == 0) in_bounds = must_in_bounds or (token_id < num_tokens) cp_op = cute.nvgpu.CopyUniversalOp() diff --git a/vllm/models/deepseek_v4/nvidia/ops/o_proj.py b/vllm/models/deepseek_v4/nvidia/ops/o_proj.py index b064fbe9cd..72ce43b46c 100644 --- a/vllm/models/deepseek_v4/nvidia/ops/o_proj.py +++ b/vllm/models/deepseek_v4/nvidia/ops/o_proj.py @@ -10,17 +10,18 @@ from vllm.platforms import current_platform from vllm.utils.deep_gemm import fp8_einsum -def compute_fp8_einsum_recipe() -> tuple[tuple[int, int, int], bool]: +def compute_fp8_einsum_recipe( + block_size: int = 128, +) -> tuple[tuple[int, int, int], bool]: """fp8_einsum recipe + scale layout for the current GPU arch. - SM90: FP32 block scales stay [g, r/128, d/128] → sfb_gran_mn=128. - SM100: INT32 packed scales become [g, r, ...] → sfb_gran_mn=1. + SM90 keeps block-row FP32 scales. SM100 uses packed per-row E8M0 scales. Returns ``(einsum_recipe, tma_aligned_scales)`` for ``deep_gemm_fp8_o_proj``. """ cap = current_platform.get_device_capability() assert cap is not None, "DeepseekV4 attention requires a CUDA device" - einsum_recipe = (1, 128, 128) if cap.major <= 9 else (1, 1, 128) + einsum_recipe = (1, 128, 128) if cap.major <= 9 else (1, 1, block_size) tma_aligned_scales = cap.major >= 10 return einsum_recipe, tma_aligned_scales @@ -40,12 +41,13 @@ def deep_gemm_fp8_o_proj( einsum_recipe: tuple[int, int, int], tma_aligned_scales: bool, ) -> torch.Tensor: - """O projection: inverse RoPE + FP8 quant + einsum + wo_b. + """O projection: inverse RoPE + grouped wo_a + wo_b. - Shared by the FlashMLA and FlashInfer CUDA backends. ``einsum_recipe`` / - ``tma_aligned_scales`` come from ``compute_fp8_einsum_recipe``. + Shared by the FlashMLA and FlashInfer CUDA backends. The attention + layer selects the recipe at initialization. """ - o_fp8, o_scale = fused_inv_rope_fp8_quant( + use_fp8 = wo_a.weight.dtype == torch.float8_e4m3fn + o_proj_input, o_scale = fused_inv_rope_fp8_quant( o, positions, cos_sin_cache, @@ -53,21 +55,33 @@ def deep_gemm_fp8_o_proj( heads_per_group=heads_per_group, nope_dim=nope_dim, rope_dim=rope_dim, + quant_group_size=einsum_recipe[2], tma_aligned_scales=tma_aligned_scales, + quantize=use_fp8, ) z = torch.empty( (o.shape[0], n_groups, o_lora_rank), device=o.device, dtype=torch.bfloat16, ) - weight_scale = ( - wo_a.weight_scale if hasattr(wo_a, "weight_scale") else wo_a.weight_scale_inv - ) - fp8_einsum( - "bhr,hdr->bhd", - (o_fp8, o_scale), - (wo_a.weight, weight_scale), - z, - recipe=einsum_recipe, - ) + if use_fp8: + weight_scale = ( + wo_a.weight_scale + if hasattr(wo_a, "weight_scale") + else wo_a.weight_scale_inv + ) + fp8_einsum( + "bhr,hdr->bhd", + (o_proj_input, o_scale), + (wo_a.weight, weight_scale), + z, + recipe=einsum_recipe, + ) + else: + grouped_weight = wo_a.weight.view(n_groups, o_lora_rank, -1) + torch.bmm( + o_proj_input.transpose(0, 1), + grouped_weight.transpose(1, 2), + out=z.transpose(0, 1), + ) return wo_b(z.flatten(1)) diff --git a/vllm/models/deepseek_v4_1/__init__.py b/vllm/models/deepseek_v4_1/__init__.py new file mode 100644 index 0000000000..b69e1c6dcd --- /dev/null +++ b/vllm/models/deepseek_v4_1/__init__.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepSeek V4.1 hardware-isolated model entry point.""" + +from vllm.platforms import current_platform + +from .quant_config import DeepseekV4FP8Config + +if current_platform.is_rocm(): + from .amd.dspark import DSparkDeepseekV4ForCausalLM + from .amd.vl_model import DeepseekV41ForCausalLM +else: + from .nvidia.dspark import DSparkDeepseekV4ForCausalLM + from .nvidia.vl_model import DeepseekV41ForCausalLM + +__all__ = [ + "DSparkDeepseekV4ForCausalLM", + "DeepseekV4FP8Config", + "DeepseekV41ForCausalLM", +] diff --git a/vllm/models/deepseek_v4_1/amd/__init__.py b/vllm/models/deepseek_v4_1/amd/__init__.py new file mode 100644 index 0000000000..208f01a7cb --- /dev/null +++ b/vllm/models/deepseek_v4_1/amd/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/deepseek_v4_1/amd/dspark.py b/vllm/models/deepseek_v4_1/amd/dspark.py new file mode 100644 index 0000000000..3a6cef8aa7 --- /dev/null +++ b/vllm/models/deepseek_v4_1/amd/dspark.py @@ -0,0 +1,546 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DSpark draft model for DeepSeek-V4.1 (semi-autoregressive speculative decoding). + +See: qwen3_dspark.py for base architecture. This one is specialized to the +DSV4.1 DSpark, which reuses the target model's architecture similarly to MTP. +Its weights ship in the target checkpoint under the ``mtp.{0,1,2}.*`` prefix. + +To implement non-causal attention, we leverage the sparse attention implementation to +include the future query tokens in the top-k indices for each query token. +""" + +from collections.abc import Iterable + +import regex as re +import torch +import torch.nn as nn + +import vllm.envs as envs +from vllm.config import VllmConfig, get_current_vllm_config +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, +) +from vllm.forward_context import get_forward_context, is_forward_context_available +from vllm.logger import init_logger +from vllm.model_executor.kernels.mhc.torch import mhc_post_torch +from vllm.model_executor.layers.fused_moe import ( + fused_moe_make_expert_params_mapping, +) +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.linear import ReplicatedLinear +from vllm.model_executor.layers.logits_processor import LogitsProcessor +from vllm.model_executor.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, +) +from vllm.model_executor.model_loader.weight_utils import default_weight_loader +from vllm.model_executor.models.qwen3_dspark import ( + DSparkConfidenceHead, + DSparkMarkovHead, +) +from vllm.model_executor.models.utils import maybe_prefix +from vllm.models.common.ops.sequence_parallel import ( + sp_all_gather, + sp_padding_mask, + sp_shard, +) + +from .model import ( + DeepseekV4DecoderLayer, + DeepseekV4Model, + _linear_scale_param_name, + _use_sequence_parallel, +) + +logger = init_logger(__name__) + +# MoE expert scale suffix differs by expert dtype (mirrors deepseek_v4 loaders): +# fp4 experts register ``.weight_scale``; block-fp8 experts ``.weight_scale_inv``. +_EXPERT_SCALE_RE = re.compile(r"\.experts\.\d+\.w[123]\.scale$") + + +class DSparkDeepseekV4Model(nn.Module): + def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: + super().__init__() + assert vllm_config.speculative_config is not None + config = vllm_config.speculative_config.draft_model_config.hf_config + self.config = config + self.hidden_size = config.hidden_size + self.hc_mult = config.hc_mult + self.hc_eps = config.hc_eps + self.rms_norm_eps = config.rms_norm_eps + self.num_hidden_layers = config.num_hidden_layers + self.target_layer_ids = tuple(config.dspark_target_layer_ids) + self.use_sequence_parallel = _use_sequence_parallel(vllm_config) + + self.num_dspark_layers = ( + getattr(config, "n_mtp_layers", None) + or getattr(config, "num_nextn_predict_layers", None) + or 3 + ) + + # Shared with the target (aliased by the speculator's loading utility). + self.embed_tokens = VocabParallelEmbedding( + config.vocab_size, + config.hidden_size, + prefix=maybe_prefix(prefix, "embed_tokens"), + ) + + self.main_proj = ReplicatedLinear( + config.hidden_size * len(self.target_layer_ids), + config.hidden_size, + bias=False, + return_bias=False, + quant_config=vllm_config.quant_config, + prefix=maybe_prefix(prefix, "main_proj"), + ) + self.main_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.topk_indices_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + config.index_topk, + dtype=torch.int32, + ) + + current_vllm_config = get_current_vllm_config() + self.layers = nn.ModuleList( + [ + DeepseekV4DecoderLayer( + current_vllm_config, + prefix=maybe_prefix(prefix, f"layers.{self.num_hidden_layers + i}"), + topk_indices_buffer=self.topk_indices_buffer, + ) + for i in range(self.num_dspark_layers) + ] + ) + + # Heads: final norm, and the Markov + confidence heads. + # Loaded from the "final" MTP layer weights (mtp.*) in the target + # checkpoint. v4.1 has no learned hc_head: the hc copies are + # collapsed with a pre-mix derived from the last layer's hc_ffn + # projection at the end of forward(). + self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + draft_vocab_size = ( + getattr(config, "draft_vocab_size", None) or config.vocab_size + ) + self.markov_head = DSparkMarkovHead( + config.vocab_size, + draft_vocab_size, + config.dspark_markov_rank, + prefix=maybe_prefix(prefix, "markov_head"), + ) + self.confidence_head: DSparkConfidenceHead | None = None + if getattr(config, "enable_confidence_head", True): + self.confidence_head = DSparkConfidenceHead( + config.hidden_size + config.dspark_markov_rank, + prefix=maybe_prefix(prefix, "confidence_head"), + ) + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.embed_tokens(input_ids) + + def combine_hidden_states(self, aux_hidden_states: torch.Tensor) -> torch.Tensor: + """main_x = main_norm(main_proj(concat of target aux hidden states)). + + ``aux_hidden_states`` is [T, hidden_size * len(target_layer_ids)]. + """ + return self.main_norm(self.main_proj(aux_hidden_states)) + + @torch.inference_mode() + def precompute_and_store_context_kv( + self, + main_x: torch.Tensor, + context_positions: torch.Tensor, + context_slot_mappings: list[torch.Tensor | None] | None = None, + ) -> None: + """Insert the sliding-window context KV for every draft layer. + + Mirrors the reference DSparkAttention: each layer derives its context KV + from the SAME projected target hidden ``main_x``, via that layer's own + ``wkv`` + ``kv_norm`` + RoPE + quant, then writes it at the + layer's context slots. + + ``context_slot_mappings`` is a per-layer list (each entry is the context + slot mapping for that layer's kv-cache group, since the hybrid manager may + place draft layers in different groups). ``None`` (or a ``None`` entry) + runs the projection to reserve workspace but writes nothing (profiling). + """ + for i, layer in enumerate(self.layers): + slot_mapping = ( + None if context_slot_mappings is None else context_slot_mappings[i] + ) + attn = layer.attn + # Optimized DSV4 MLA path: wkv part of the fused wq_a|wkv projection + # (q_lora part discarded), then RoPE/quant/insert via the fused op. + qr_kv, _ = attn.fused_wqa_wkv(main_x) + kv = qr_kv[..., attn.q_lora_rank :] + kv = attn.kv_norm(kv) + if slot_mapping is None: + continue + _insert_context_kv(attn, kv, context_positions, slot_mapping) + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None = None, + ) -> torch.Tensor: + if inputs_embeds is None: + inputs_embeds = self.embed_input_ids(input_ids) + full_num_tokens = positions.shape[0] + if self.use_sequence_parallel: + if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available(): + forward_context = get_forward_context() + forward_context.is_padding = sp_padding_mask( + forward_context.is_padding, inputs_embeds + ) + inputs_embeds = sp_shard(inputs_embeds) + input_ids = sp_shard(input_ids) + # Expand to hc_mult copies for hyper-connections ([T, H] -> [T, hc, H]). + hidden_states = inputs_embeds.unsqueeze(-2).repeat(1, self.hc_mult, 1) + + residual = post_mix = res_mix = pre_mix = None + for layer in self.layers: + hidden_states, residual, post_mix, res_mix, pre_mix = layer( + hidden_states, + positions, + input_ids, + pre_mix, + post_mix, + res_mix, + residual, + ) + hidden_states = mhc_post_torch(hidden_states, residual, post_mix, res_mix) + if self.use_sequence_parallel: + hidden_states = sp_all_gather(hidden_states)[:full_num_tokens] + pre_mix = sp_all_gather(pre_mix)[:full_num_tokens] + # Collapse the hc copies with the pre-mix from the last layer's FFN + # mixes — the mix the reference forward_head applies (hc_pre with the + # last block's ffn pre-mix). Return the PRE-norm head hidden; + # compute_logits applies self.norm. + hidden_states = DeepseekV4DecoderLayer._hc_collapse(hidden_states, pre_mix) + return hidden_states + + +def _insert_context_kv( + attn: nn.Module, + kv: torch.Tensor, + positions: torch.Tensor, + slot_mapping: torch.Tensor, +) -> None: + """RoPE + quant + paged-cache insert of (already kv_norm'd) context KV. + + Reuses the DSV4 fused insert ops (which also process a query; we pass a dummy + query and discard it, since context tokens have no query). Mirrors + ``DeepseekV4Attention._fused_qnorm_rope_kv_insert``. + """ + swa_cache = attn.swa_cache_layer.kv_cache + block_size = attn.swa_cache_layer.block_size + cos_sin_cache = attn.rotary_emb.cos_sin_cache + cache_dtype = swa_cache.dtype + n_ctx = kv.shape[0] + dummy_q = torch.zeros( + (n_ctx, attn.n_local_heads, attn.head_dim), + dtype=kv.dtype, + device=kv.device, + ) + if cache_dtype == torch.uint8: + # fp8_ds_mla UE8M0 paged layout + swa_2d = swa_cache.view(swa_cache.shape[0], -1) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert( + dummy_q, + kv, + swa_2d, + slot_mapping, + positions, + cos_sin_cache, + attn.padded_heads, + attn.eps, + block_size, + ) + elif cache_dtype == torch.bfloat16: + swa_3d = swa_cache.view(-1, block_size, attn.head_dim) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert( + dummy_q, + kv, + swa_3d, + slot_mapping, + positions, + cos_sin_cache, + attn.eps, + block_size, + ) + else: # per-tensor fp8 (torch.float8_e4m3fn) + # TODO(ben): double-check if this is being dispatched correctly for FI backend + swa_3d = swa_cache.view(-1, block_size, attn.head_dim) + dummy_q_fp8 = torch.zeros_like(dummy_q, dtype=torch.float8_e4m3fn) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_fp8_insert( + dummy_q, + kv, + dummy_q_fp8, + swa_3d, + slot_mapping, + positions, + cos_sin_cache, + attn._flashinfer_fp8_kv_scale, + attn._flashinfer_fp8_q_scale_inv, + attn.eps, + block_size, + ) + + +class DSparkDeepseekV4ForCausalLM(nn.Module): + # Draft weights ship in the target checkpoint (mtp.*) without embed/head, so + # load_dspark_model always aliases the target's. + has_own_embed_tokens = False + has_own_lm_head = False + # Full-vocab draft: draft ids are target ids, no remapping needed. + draft_id_to_target_id = None + + def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: + super().__init__() + assert vllm_config.speculative_config is not None + self.draft_model_config = vllm_config.speculative_config.draft_model_config + self.config = self.draft_model_config.hf_config + self.quant_config = vllm_config.quant_config + self.linear_scale_name = _linear_scale_param_name( + vllm_config, getattr(self.config, "expert_dtype", "fp4") + ) + self.pad_shared_expert = getattr( + self.quant_config, "weight_block_size", None + ) is not None and not _use_sequence_parallel(vllm_config) + self.model = DSparkDeepseekV4Model( + vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") + ) + # Shared with the target (aliased by the speculator's load utility). + self.lm_head = ParallelLMHead( + self.config.vocab_size, + self.config.hidden_size, + prefix=maybe_prefix(prefix, "lm_head"), + ) + self.logits_processor = LogitsProcessor(self.config.vocab_size) + + # --- Hooks used by the speculator ------------------------------------- + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.model.embed_input_ids(input_ids) + + def combine_hidden_states(self, aux_hidden_states: torch.Tensor) -> torch.Tensor: + return self.model.combine_hidden_states(aux_hidden_states) + + def get_draft_kv_cache_layer_names(self) -> list[str]: + # DSV4 MLA path: each draft layer's sliding-window cache is a separate + # layer, named by its prefix. + return [layer.attn.swa_cache_layer.prefix for layer in self.model.layers] + + def precompute_and_store_context_kv( + self, + context_states: torch.Tensor, + context_positions: torch.Tensor, + context_slot_mappings: list[torch.Tensor | None] | None = None, + ) -> None: + self.model.precompute_and_store_context_kv( + context_states, context_positions, context_slot_mappings + ) + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None = None, + ) -> torch.Tensor: + # Returns the pre-norm collapsed head hidden ([T, hidden_size]). + return self.model(input_ids, positions, inputs_embeds) + + def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + """Base logits U_k = lm_head(norm(head_hidden)).""" + return self.logits_processor(self.lm_head, self.model.norm(hidden_states)) + + def compute_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + # Full-vocab draft: base logits, no d2t scatter. + return self.compute_logits(hidden_states) + + def map_draft_to_target(self, draft_ids: torch.Tensor) -> torch.Tensor: + return draft_ids # full-vocab: draft ids are target ids + + def markov_embed(self, token_ids: torch.Tensor) -> torch.Tensor: + return self.model.markov_head.embed(token_ids) + + def markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor: + return self.model.markov_head.bias(markov_embed, self.logits_processor) + + def compute_confidence( + self, head_hidden: torch.Tensor, markov_embed: torch.Tensor + ) -> torch.Tensor: + """Per-position acceptance probability for each drafted token.""" + assert self.model.confidence_head is not None + return torch.sigmoid(self.model.confidence_head(head_hidden, markov_embed)) + + # --- Weight loading ---------------------------------------------------- + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + """Load the ``mtp.{0,1,2}.*`` draft weights from the target checkpoint. + + Non-mtp weights (embed/head/main layers) belong to the target model and + are skipped here. ``embed_tokens``/``lm_head`` are aliased from the target. + """ + # Draft MoE layers use the dspark_* expert counts, not the + # backbone's (see DeepseekV4MoE and the reference + # ModelArgs.get_moe_config). + n_draft_experts = ( + getattr(self.config, "dspark_n_routed_experts", 0) + or self.config.n_routed_experts + ) + expert_mapping = fused_moe_make_expert_params_mapping( + self, + ckpt_gate_proj_name="w1", + ckpt_down_proj_name="w2", + ckpt_up_proj_name="w3", + num_experts=n_draft_experts, + ) + expert_scale_suffix = ( + ".weight_scale" + if getattr(self.config, "expert_dtype", "fp4") == "fp4" + else ".weight_scale_inv" + ) + + # (param_name, ckpt_shard_name, shard_id) for non-expert stacked params. + stacked_params_mapping = [ + ("gate_up_proj", "w1", 0), + ("gate_up_proj", "w3", 1), + ("attn.fused_wqa_wkv", "attn.wq_a", 0), + ("attn.fused_wqa_wkv", "attn.wkv", 1), + ] + + params_dict = dict(self.named_parameters()) + loaded_params: set[str] = set() + loaded_confidence_head = False + + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + n_local_head = self.config.num_attention_heads // tp_size + head_start = n_local_head * tp_rank + head_end = n_local_head * (tp_rank + 1) + + for name, loaded_weight in weights: + mapped = self._remap_dspark_name(name) + if mapped is None: + continue + name = mapped + if "confidence_head." in name: + loaded_confidence_head = True + + # ``.scale`` -> per-method scale suffix. + if name.endswith(".scale"): + suffix = ( + expert_scale_suffix + if _EXPERT_SCALE_RE.search(name) + else f".{self.linear_scale_name}" + ) + name = name.removesuffix(".scale") + suffix + if ".shared_experts.w2" in name: + name = name.replace(".shared_experts.w2", ".shared_experts.down_proj") + if self.pad_shared_expert and ".shared_experts." in name: + loaded_weight = DeepseekV4Model._pad_shared_expert_weight( + self.quant_config, name, loaded_weight + ) + + # E8M0 expert scales: keep raw exponent bytes. + if ".experts." in name: + if ( + "weight_scale" in name + and loaded_weight.dtype == torch.float8_e8m0fnu + ): + loaded_weight = loaded_weight.view(torch.uint8) + for param_name, weight_name, expert_id, shard_id in expert_mapping: + if weight_name not in name: + continue + name_mapped = name.replace(weight_name, param_name) + param = params_dict[name_mapped] + success = param.weight_loader( + param, + loaded_weight, + name_mapped, + shard_id=shard_id, + expert_id=expert_id, + return_success=True, + ) + if success: + loaded_params.add(name_mapped) + break + continue + + # Stacked rules only apply to decoder-layer weights. Head-stack params + # (main_proj/norm/markov_head/confidence_head) load directly — + # otherwise e.g. "markov_w1" would collide with the "w1" shard rule. + is_layer_param = name.startswith("model.layers.") + for param_name, weight_name, stacked_shard_id in stacked_params_mapping: + if not is_layer_param or weight_name not in name: + continue + name = name.replace(weight_name, param_name) + param = params_dict[name] + param.weight_loader(param, loaded_weight, stacked_shard_id) + loaded_params.add(name) + break + else: + if "attn_sink" in name: + narrow = loaded_weight[head_start:head_end] + params_dict[name][: narrow.shape[0]].copy_(narrow) + loaded_params.add(name) + continue + if name.endswith(".ffn.gate.bias"): + name = name.replace( + ".ffn.gate.bias", ".ffn.gate.e_score_correction_bias" + ) + param = params_dict[name] + weight_loader = getattr(param, "weight_loader", default_weight_loader) + weight_loader(param, loaded_weight) + loaded_params.add(name) + + if self.model.confidence_head is not None and not loaded_confidence_head: + self.model.confidence_head = None + self.process_weights_after_loading() + logger.info_once("DSpark draft model loaded: %d params", len(loaded_params)) + return loaded_params + + def process_weights_after_loading(self) -> None: + # ROCm linears and fused-MoE runners finalize their own quantized + # parameters. NVIDIA-only MegaMoE/WO-A requantization is not needed. + return + + def _remap_dspark_name(self, name: str) -> str | None: + """Map a checkpoint ``mtp.{i}.*`` name to this model's parameter path. + + Returns None for non-mtp weights (owned by the target model). + """ + m = re.match(r"mtp\.(\d+)\.(.*)", name) + if m is None: + return None + stage = int(m.group(1)) + rest = m.group(2) + if rest.startswith("confidence_head.") and self.model.confidence_head is None: + return None + # The checkpoint calls the Markov head's factors ``embed``/``head``; + # DSparkMarkovHead registers them as ``markov_w1``/``markov_w2``. + if rest.startswith("markov_head.embed."): + return "model.markov_head.markov_w1." + rest.removeprefix( + "markov_head.embed." + ) + if rest.startswith("markov_head.head."): + return "model.markov_head.markov_w2." + rest.removeprefix( + "markov_head.head." + ) + # Head-stack params live at model level (mtp.last), context combiner at + # model level (mtp.0); everything else is a per-layer decoder block. + head_prefixes = ( + "norm.", + "markov_head.", + "confidence_head.", + ) + if rest.startswith(("main_proj.", "main_norm.")) or rest.startswith( + head_prefixes + ): + return f"model.{rest}" + return f"model.layers.{stage}.{rest}" diff --git a/vllm/models/deepseek_v4_1/amd/model.py b/vllm/models/deepseek_v4_1/amd/model.py new file mode 100644 index 0000000000..069ff5f931 --- /dev/null +++ b/vllm/models/deepseek_v4_1/amd/model.py @@ -0,0 +1,1086 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import typing +from collections.abc import Callable, Iterable +from itertools import islice + +import regex as re +import torch +import torch.nn as nn + +import vllm.envs as envs +from vllm.config import VllmConfig +from vllm.distributed import ( + get_pp_group, + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, +) +from vllm.forward_context import get_forward_context, is_forward_context_available +from vllm.logger import init_logger +from vllm.model_executor.kernels.mhc.torch import ( + mhc_post_torch, + mhc_pre_delayed_torch, +) +from vllm.model_executor.layers.fused_moe import ( + fused_moe_make_expert_params_mapping, +) +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.logits_processor import LogitsProcessor +from vllm.model_executor.layers.quantization import QuantizationConfig +from vllm.model_executor.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, +) +from vllm.model_executor.model_loader.weight_utils import default_weight_loader +from vllm.model_executor.models.interfaces import ( + EagleModelMixin, + MixtureOfExperts, + SupportsEagle3, + SupportsLoRA, + SupportsPP, +) +from vllm.model_executor.models.utils import ( + AutoWeightsLoader, + PPMissingLayer, + WeightsMapper, + extract_layer_index, + is_pp_missing_parameter, + make_layers, + maybe_prefix, +) +from vllm.models.common.ops.sequence_parallel import ( + sp_all_gather, + sp_padding_mask, + sp_reduce_scatter, + sp_shard, +) +from vllm.models.deepseek_v4.amd.model import ( + DeepseekV4MoE as DeepseekV4MoEBase, +) +from vllm.models.deepseek_v4_1.amd.rocm import DeepseekV41ROCMAiterMLAAttention +from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention +from vllm.sequence import IntermediateTensors +from vllm.utils.math_utils import cdiv +from vllm.v1.attention.backends.registry import AttentionBackendEnum +from vllm.v1.worker.ubatching import dbo_current_ubatch_id + +from ..common.engram import Engram, EngramLayout, NgramHashState +from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask + +if typing.TYPE_CHECKING: + from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata + +logger = init_logger(__name__) + + +class DeepseekV4MoE(DeepseekV4MoEBase): + def __init__( + self, + vllm_config: VllmConfig, + prefix: str = "", + use_sequence_parallel: bool = False, + ): + config = vllm_config.model_config.hf_config + n_routed_experts = config.n_routed_experts + n_activated_experts = config.num_experts_per_tok + if extract_layer_index(prefix) >= config.num_hidden_layers: + n_routed_experts = ( + getattr(config, "dspark_n_routed_experts", 0) or n_routed_experts + ) + n_activated_experts = ( + getattr(config, "dspark_num_experts_per_tok", 0) or n_activated_experts + ) + # The reused ROCm V4 MoE reads expert counts from the HF config. Draft + # layers use V4.1's smaller DSpark expert set, so temporarily expose + # the per-layer counts while constructing the module, then restore the + # shared config for the remaining backbone layers. + old_routed = config.n_routed_experts + old_activated = config.num_experts_per_tok + old_hash_layers = getattr(config, "num_hash_layers", None) + config.n_routed_experts = n_routed_experts + config.num_experts_per_tok = n_activated_experts + config.num_hash_layers = 0 + try: + super().__init__(vllm_config, prefix=prefix) + finally: + config.n_routed_experts = old_routed + config.num_experts_per_tok = old_activated + if old_hash_layers is None: + delattr(config, "num_hash_layers") + else: + config.num_hash_layers = old_hash_layers + + # The V4.1 checkpoint contains a second per-expert routing bias for + # image sentinel tokens. The reused ROCm V4 MoE predates this field, + # so register it here and attach the same Parameter to the router, + # matching the CUDA V4.1 implementation. Text tokens continue to use + # e_score_correction_bias. + self.gate.bias_vl = None + self.image_sentinel_lo = 0 + if getattr(config, "vision_n_layers", 0) > 0: + self.gate.bias_vl = nn.Parameter( + torch.empty(self.n_routed_experts, dtype=torch.float32), + requires_grad=False, + ) + self.image_sentinel_lo = IMAGE_SENTINEL_BASE_ID + self.experts.router.bias_vl = self.gate.bias_vl + self.experts.router.image_sentinel_lo = self.image_sentinel_lo + self.use_mega_moe = False + # Expose the MixtureOfExperts protocol fields expected by the V4.1 + # outer model. The current ROCm runner has no redundant EPLB copies, + # so logical and physical expert counts are identical. + self.n_logical_experts = self.n_routed_experts + self.n_physical_experts = self.n_routed_experts + self.n_local_physical_experts = self.n_local_experts + self.n_redundant_experts = 0 + + +def _select_dsv4_attn_cls(vllm_config: VllmConfig) -> type[DeepseekV4Attention]: + """Pick the ROCm sparse-MLA implementation for DeepSeek V4.1.""" + backend = vllm_config.attention_config.backend + if backend is not None and ( + backend is not AttentionBackendEnum.ROCM_FLASHMLA_SPARSE_DSV4 + ): + raise ValueError( + f"{backend.name} is not supported for DeepSeek V4.1 on ROCm; " + "use ROCM_FLASHMLA_SPARSE_DSV4." + ) + return DeepseekV41ROCMAiterMLAAttention + + +def _use_sequence_parallel(vllm_config: VllmConfig) -> bool: + # The ROCm fused-MoE path currently uses ordinary tensor/expert parallel. + return False + + +class DeepseekV4DecoderLayer(nn.Module): + def __init__( + self, + vllm_config, + prefix, + topk_indices_buffer: torch.Tensor | None = None, + aux_stream_list: list[torch.cuda.Stream] | None = None, + candidate_block_buffer: torch.Tensor | None = None, + engram_layout: EngramLayout | None = None, + ): + super().__init__() + config = vllm_config.model_config.hf_config + self.hidden_size = config.hidden_size + self.use_sequence_parallel = _use_sequence_parallel(vllm_config) + + self.engram: Engram | None = None + if engram_layout is not None: + layer_id = extract_layer_index(prefix) + if layer_id in engram_layout.layer_ids: + self.engram = Engram( + config, + vllm_config.quant_config, + engram_layout, + engram_layout.layer_ids.index(layer_id), + use_sequence_parallel=self.use_sequence_parallel, + prefix=f"{prefix}.engram", + ) + + self.rms_norm_eps = config.rms_norm_eps + self.attn = _select_dsv4_attn_cls(vllm_config)( + vllm_config, + prefix=f"{prefix}.attn", + topk_indices_buffer=topk_indices_buffer, + aux_stream_list=aux_stream_list, + candidate_block_buffer=candidate_block_buffer, + ) + if self.use_sequence_parallel: + self.attn.wo_b.reduce_results = False + self.ffn = DeepseekV4MoE( + vllm_config, + prefix=f"{prefix}.ffn", + use_sequence_parallel=self.use_sequence_parallel, + ) + + self.attn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps) + self.ffn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps) + self.hc_mult = config.hc_mult + self.hc_sinkhorn_iters = config.hc_sinkhorn_iters + self.hc_eps = config.hc_eps + self.hc_post_alpha = 2.0 + mix_hc = (2 + self.hc_mult) * self.hc_mult + hc_dim = self.hc_mult * self.hidden_size + self.hc_attn_fn = nn.Parameter( + torch.empty( + (mix_hc, hc_dim), + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_attn_fn_broadcast: torch.Tensor | None = None + self.hc_ffn_fn = nn.Parameter( + torch.empty( + (mix_hc, hc_dim), + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_attn_base = nn.Parameter( + torch.empty( + mix_hc, + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_ffn_base = nn.Parameter( + torch.empty( + mix_hc, + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_attn_scale = nn.Parameter( + torch.empty( + 3, + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_ffn_scale = nn.Parameter( + torch.empty( + 3, + dtype=torch.float32, + ), + requires_grad=False, + ) + + @staticmethod + def _hc_collapse(x: torch.Tensor, pre_mix: torch.Tensor) -> torch.Tensor: + """Reference hyper-connection collapse used by DSpark on ROCm.""" + return (pre_mix.unsqueeze(-1) * x.float()).sum(dim=1).to(x.dtype) + + def forward( + self, + x: torch.Tensor, + positions: torch.Tensor, + input_ids: torch.Tensor | None, + pre_mix: torch.Tensor | None = None, + post_mix: torch.Tensor | None = None, + res_mix: torch.Tensor | None = None, + residual: torch.Tensor | None = None, + engram_hashes: torch.Tensor | None = None, + engram_mask: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + # The reference collapses each sublayer's input with the *previous* + # sublayer's pre-mix: attention uses the pre-mix carried in (identity + # for the first layer), the FFN uses this layer's attention pre-mix. + if residual is None: + if x.dim() == 2: + # First layer: the stream is the embedding broadcast to hc + # copies and the identity pre-mix selects copy 0. + assert self.hc_attn_fn_broadcast is not None + residual = x.unsqueeze(1).expand(-1, self.hc_mult, -1).contiguous() + post_mix, res_mix, x, attn_pre = mhc_pre_delayed_torch( + residual, + self.hc_attn_fn_broadcast, + self.hc_attn_scale, + self.hc_attn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + x=x, + ) + else: + residual = x + post_mix, res_mix, x, attn_pre = mhc_pre_delayed_torch( + residual, + self.hc_attn_fn, + self.hc_attn_scale, + self.hc_attn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + pre_mix=pre_mix, + ) + else: + residual = mhc_post_torch(x, residual, post_mix, res_mix) + if self.engram is not None and engram_hashes is not None: + # Engram injection happens between the previous sublayer's + # post and this block's pre, on the full hc stream, so the + # mix coefficients see the injected stream. + residual = self.engram( + residual, + engram_hashes[:, self.engram.layer_hash_index], + engram_mask, + ) + post_mix, res_mix, x, attn_pre = mhc_pre_delayed_torch( + residual, + self.hc_attn_fn, + self.hc_attn_scale, + self.hc_attn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + pre_mix=pre_mix, + ) + x = self.attn_norm(x) + + if self.use_sequence_parallel: + x = sp_all_gather(x)[: positions.shape[0]] + + x = self.attn(positions, x, None) + if self.use_sequence_parallel: + x = sp_reduce_scatter(x) + + residual = mhc_post_torch(x, residual, post_mix, res_mix) + post_mix, res_mix, x, ffn_pre = mhc_pre_delayed_torch( + residual, + self.hc_ffn_fn, + self.hc_ffn_scale, + self.hc_ffn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + pre_mix=attn_pre, + ) + x = self.ffn_norm(x) + x = self.ffn(x, input_ids) + return x, residual, post_mix, res_mix, ffn_pre + + +class DeepseekV4Model(nn.Module, EagleModelMixin): + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): + super().__init__() + + config = vllm_config.model_config.hf_config + quant_config = vllm_config.quant_config + self.config = config + self.quant_config = quant_config + self.parallel_config = vllm_config.parallel_config + self.use_mega_moe = False + self.use_sequence_parallel = _use_sequence_parallel(vllm_config) + if self.use_mega_moe and not vllm_config.parallel_config.enable_expert_parallel: + raise NotImplementedError( + "DeepSeek V4 MegaMoE currently requires expert parallel. " + "Enable it with --enable-expert-parallel, or pick a different " + "moe backend." + ) + self.vocab_size = config.vocab_size + self.hc_eps = config.hc_eps + self.hc_mult = config.hc_mult + self.hc_dim = self.hc_mult * config.hidden_size + self.rms_norm_eps = config.rms_norm_eps + + # Three aux streams: one per non-default input GEMM in + # DeepseekV4Attention._run_parallel_input_projections + # (compressor kv_score, indexer.weights_proj). fused_wqa_wkv stays on + # the default stream. + aux_stream_list = [torch.cuda.Stream() for _ in range(3)] + + # Reserved topk indices buffer for all Indexer layers to reuse. + self.topk_indices_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + config.index_topk, + dtype=torch.int32, + ) + + # Two-level candidate filtering: the indexer at + # candidate_source_layer_id publishes the top candidate blocks of + # compressed positions here; later ratio-1 indexers (24/28/32/36) + # mask their scores with it. + candidate_source_layer = getattr(config, "candidate_source_layer_id", -1) + candidate_topk_blocks = getattr(config, "candidate_topk_blocks", 0) + if candidate_source_layer >= 0 and candidate_topk_blocks > 0: + self.candidate_block_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + candidate_topk_blocks, + dtype=torch.int32, + ) + else: + self.candidate_block_buffer = None + + if get_pp_group().is_first_rank: + self.embed_tokens = VocabParallelEmbedding( + config.vocab_size, + config.hidden_size, + quant_config=quant_config, + prefix=f"{prefix}.embed_tokens", + ) + else: + self.embed_tokens = PPMissingLayer() + + self.engram_layout = EngramLayout.from_config(config) + + self.start_layer, self.end_layer, self.layers = make_layers( + config.num_hidden_layers, + lambda prefix: DeepseekV4DecoderLayer( + vllm_config, + prefix=prefix, + topk_indices_buffer=self.topk_indices_buffer, + aux_stream_list=aux_stream_list, + candidate_block_buffer=self.candidate_block_buffer, + engram_layout=self.engram_layout, + ), + prefix=f"{prefix}.layers", + ) + + # The n-gram hash needs a slot-keyed rolling store of compressed ids + # (chunked prefill / decode lookback); key it off the first local + # layer's sliding-window KV cache. Only PP ranks owning an engram + # layer need it. + self.engram_hash: NgramHashState | None = None + self.engram_swa_prefix: str | None = None + if self.engram_layout is not None: + local_engram = any( + isinstance(layer, DeepseekV4DecoderLayer) and layer.engram is not None + for layer in islice(self.layers, self.start_layer, self.end_layer) + ) + if local_engram: + first_layer = next( + iter(islice(self.layers, self.start_layer, self.end_layer)) + ) + swa_cache_module = first_layer.attn.swa_cache_layer + self.engram_hash = NgramHashState( + vllm_config, self.engram_layout, swa_cache_module + ) + self.engram_swa_prefix = swa_cache_module.prefix + + if get_pp_group().is_last_rank: + self.norm = RMSNorm(config.hidden_size, self.rms_norm_eps) + else: + self.norm = PPMissingLayer() + + spec_config = vllm_config.speculative_config + needs_mtp_hidden_states = spec_config is not None and ( + spec_config.use_eagle() or spec_config.uses_draft_model() + ) + if get_pp_group().is_last_rank and needs_mtp_hidden_states: + self._mtp_hidden_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + self.hc_dim, + dtype=vllm_config.model_config.dtype, + ) + else: + self._mtp_hidden_buffer = None + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.embed_tokens(input_ids) + + def make_empty_intermediate_tensors( + self, + batch_size: int, + dtype: torch.dtype, + device: torch.device, + ) -> IntermediateTensors: + # PP intermediate tensors carry the multi-stream hidden_states + # of shape (num_tokens, hc_mult, hidden_size) — V4 expands the + # token embedding to hc_mult streams before the first decoder + # layer and keeps that shape until the final hc collapse — plus the + # (num_tokens, hc_mult) pre-mix the next rank's first layer needs + # for its attention collapse. + return IntermediateTensors( + { + "hidden_states": torch.zeros( + (batch_size, self.hc_mult, self.config.hidden_size), + dtype=dtype, + device=device, + ), + "pre_mix": torch.zeros( + (batch_size, self.hc_mult), + dtype=torch.float32, + device=device, + ), + } + ) + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + intermediate_tensors: IntermediateTensors | None, + inputs_embeds: torch.Tensor | None = None, + lookback_token_ids: torch.Tensor | None = None, + ) -> torch.Tensor | IntermediateTensors: + if get_pp_group().is_first_rank: + if inputs_embeds is not None: + hidden_states = inputs_embeds + else: + hidden_states = self.embed_input_ids(input_ids) + else: + assert intermediate_tensors is not None + hidden_states = intermediate_tensors["hidden_states"] + + if self.use_mega_moe: + input_ids = input_ids.to(torch.int64) + + # Engram n-gram hashes for the whole (flattened) batch, computed once + # on the full token stream — before any sequence-parallel sharding — + # and consumed by the engram layers (1 and 14) below. Skipped on + # profile runs (KV cache unbound -> no slot space to key the rolling + # compressed-id cache into). + engram_hashes: torch.Tensor | None = None + engram_mask: torch.Tensor | None = None + if ( + self.engram_hash is not None + and input_ids is not None + and is_forward_context_available() + ): + attn_metadata = get_forward_context().attn_metadata + if isinstance(attn_metadata, list): + attn_metadata = attn_metadata[dbo_current_ubatch_id()] + if isinstance(attn_metadata, dict) and self.engram_hash.ensure_cache(): + assert self.engram_swa_prefix is not None + swa_metadata = typing.cast( + "DeepseekSparseSWAMetadata", attn_metadata[self.engram_swa_prefix] + ) + # Image-span tokens are dead: they break n-grams (hash op + # takes True=dead) and their gate is zeroed (Engram.forward + # takes True=keep). + image_mask = image_sentinel_mask(input_ids) + engram_mask = ~image_mask + if lookback_token_ids is None: + if not self.engram_hash.use_slot_cache: + raise NotImplementedError( + "engram needs `lookback_token_ids` from the model " + "runner (the DBO/ubatch wrapper drops model kwargs)" + ) + num_reqs = swa_metadata.num_decodes + swa_metadata.num_prefills + lookback_token_ids = input_ids.new_full( + (num_reqs, self.engram_hash.lookback_depth), -1 + ) + engram_hashes = self.engram_hash( + input_ids, + positions, + swa_metadata.query_start_loc, + image_mask, + lookback_token_ids, + image_sentinel_mask(lookback_token_ids), + swa_metadata.slot_mapping, + swa_metadata.block_table, + ) + # Gather all Engram rows before entering the decoder layers. + for layer in islice(self.layers, self.start_layer, self.end_layer): + engram = getattr(layer, "engram", None) + if engram is not None: + engram.prepare_embeddings( + engram_hashes[:, engram.layer_hash_index] + ) + + full_num_tokens = positions.shape[0] + if self.use_sequence_parallel: + if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available(): + forward_context = get_forward_context() + forward_context.is_padding = sp_padding_mask( + forward_context.is_padding, hidden_states + ) + hidden_states = sp_shard(hidden_states) + input_ids = sp_shard(input_ids) + + residual, post_mix, res_mix = None, None, None + pre_mix: torch.Tensor | None = None + if not get_pp_group().is_first_rank: + assert intermediate_tensors is not None + pre_mix = intermediate_tensors["pre_mix"] + aux_hidden_states: list[torch.Tensor] = [] + final_aux_recon: torch.Tensor | None = None # avoid duplicate mhc_post call + for idx, layer in enumerate( + islice(self.layers, self.start_layer, self.end_layer), + start=self.start_layer, + ): + hidden_states, residual, post_mix, res_mix, pre_mix = layer( + hidden_states, + positions, + input_ids, + pre_mix, + post_mix, + res_mix, + residual, + engram_hashes, + engram_mask, + ) + if idx + 1 in self.aux_hidden_state_layers: + # Reconstruct the aux hidden state for draft models + aux_recon = mhc_post_torch(hidden_states, residual, post_mix, res_mix) + aux_hidden_state = aux_recon.mean(dim=1) + if self.use_sequence_parallel: + aux_hidden_state = sp_all_gather(aux_hidden_state)[:full_num_tokens] + aux_hidden_states.append(aux_hidden_state) + final_aux_recon = aux_recon + if layer is not None: + # Reuse if the last layer was captured as an aux hidden state + if self.end_layer in self.aux_hidden_state_layers: + hidden_states = final_aux_recon + else: + hidden_states = mhc_post_torch( + hidden_states, residual, post_mix, res_mix + ) + + if not get_pp_group().is_last_rank: + return IntermediateTensors( + {"hidden_states": hidden_states, "pre_mix": pre_mix} + ) + + if self.use_sequence_parallel: + hidden_states = sp_all_gather(hidden_states)[:full_num_tokens] + pre_mix = sp_all_gather(pre_mix)[:full_num_tokens] + + if self._mtp_hidden_buffer is not None: + num_tokens = hidden_states.shape[0] + self._mtp_hidden_buffer[:num_tokens].copy_(hidden_states.flatten(1)) + + # Collapse the hc copies with the pre-mix from the last layer's FFN + # mixes — the mix the reference applies via + # ``last_layer.hc_pre(h, pre_mix)`` (v4.1 has no learned hc_head). + assert pre_mix is not None + hidden_states = ( + (pre_mix.unsqueeze(-1) * hidden_states.float()) + .sum(dim=1) + .to(hidden_states.dtype) + ) + hidden_states = self.norm(hidden_states) + if len(aux_hidden_states) > 0: + return hidden_states, aux_hidden_states + return hidden_states + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + stacked_params_mapping = [ + # (param_name, shard_name, shard_id) + ("gate_up_proj", "w1", 0), + ("gate_up_proj", "w3", 1), + ("attn.fused_wqa_wkv", "attn.wq_a", 0), + ("attn.fused_wqa_wkv", "attn.wkv", 1), + ("compressor.fused_wkv_wgate", "compressor.wkv", 0), + ("compressor.fused_wkv_wgate", "compressor.wgate", 1), + ] + params_dict = dict(self.named_parameters()) + loaded_params: set[str] = set() + + def _resolve_param_name(name: str) -> str: + """Resolve scale naming across ROCm FP8 and MXFP8 methods.""" + if name.endswith("_inv"): + direct_name = name.removesuffix("_inv") + if direct_name in params_dict: + return direct_name + inv_name = f"{name}_inv" + if name not in params_dict and inv_name in params_dict: + return inv_name + return name + + # TP for attention + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + n_head = self.config.num_attention_heads + n_local_head = n_head // tp_size + head_rank_start = n_local_head * tp_rank + head_rank_end = n_local_head * (tp_rank + 1) + + # Pre-compute expert mapping ONCE. + expert_mapping = self.get_expert_mapping() + + # Block-FP8 shared experts: pad the intermediate up to the TP-uniform + # block count so the standard loaders below slice it evenly (trailing + # ranks land on the zero pad). SP / unquantized ones need no padding. + pad_shared_expert = ( + getattr(self.quant_config, "weight_block_size", None) is not None + and not self.use_sequence_parallel + ) + + for name, loaded_weight in weights: + if name.startswith(("vision.", "aligner.", "image_")): + # Vision weights are loaded by the outer multimodal wrapper. + logger.warning_once("Skipping non-text weight: %s", name) + continue + if pad_shared_expert and ".shared_experts." in name: + loaded_weight = self._pad_shared_expert_weight( + self.quant_config, name, loaded_weight + ) + for param_name, weight_name, shard_id in stacked_params_mapping: + # Skip non-stacked layers and experts (experts handled below). + if ".experts." in name: + continue + if weight_name not in name: + continue + name = name.replace(weight_name, param_name) + + if is_pp_missing_parameter(name, self): + break + if name not in params_dict: + head, _, leaf = name.rpartition(".") + suffixed = f"{head}.base_layer.{leaf}" + if suffixed in params_dict: + name = suffixed + name = _resolve_param_name(name) + param = params_dict[name] + weight_loader = param.weight_loader + weight_loader(param, loaded_weight, shard_id) + loaded_params.add(name) + break + else: + if ".experts." in name: + # E8M0 scales are stored as float8_e8m0fnu in + # checkpoints but the MoE param is uint8. copy_() + # would do a numeric conversion (e.g. 2^-7 → 0), + # destroying the raw exponent bytes. + if ( + "weight_scale" in name + and loaded_weight.dtype == torch.float8_e8m0fnu + ): + loaded_weight = loaded_weight.view(torch.uint8) + for mapping in expert_mapping: + param_name, weight_name, expert_id, expert_shard_id = mapping + if weight_name not in name: + continue + name_mapped = name.replace(weight_name, param_name) + if is_pp_missing_parameter(name_mapped, self): + continue + name_mapped = _resolve_param_name(name_mapped) + param = params_dict[name_mapped] + # We should ask the weight loader to return success or not + # here since otherwise we may skip experts with other + # available replicas. + weight_loader = typing.cast( + Callable[..., bool], param.weight_loader + ) + success = weight_loader( + param, + loaded_weight, + name_mapped, + shard_id=expert_shard_id, + expert_id=expert_id, + return_success=True, + ) + if success: + name = name_mapped + break + loaded_params.add(name_mapped) + continue + elif "attn_sink" in name: + if is_pp_missing_parameter(name, self): + continue + narrow_weight = loaded_weight[head_rank_start:head_rank_end] + n = narrow_weight.shape[0] + params_dict[name][:n].copy_(narrow_weight) + loaded_params.add(name) + continue + else: + if is_pp_missing_parameter(name, self): + continue + # Non-LoRA params on a LoRA-wrapped module live at + # ``.base_layer.``; the checkpoint is plain. + if name not in params_dict: + head, _, leaf = name.rpartition(".") + suffixed = f"{head}.base_layer.{leaf}" + if suffixed in params_dict: + name = suffixed + name = _resolve_param_name(name) + param = params_dict[name] + weight_loader = getattr( + param, "weight_loader", default_weight_loader + ) + weight_loader(param, loaded_weight) + loaded_params.add(name) + continue + + return loaded_params + + @staticmethod + def _pad_shared_expert_weight( + quant_config: QuantizationConfig | None, + name: str, + loaded_weight: torch.Tensor, + ) -> torch.Tensor: + """Zero-pad a block-FP8 shared-expert weight/scale on its intermediate + axis so the standard TP loaders split it into even, block-aligned shards + (trailing ranks get the zero pad). gate (w1)/up (w3) [I, H] pad dim 0; + down (w2 -> down_proj) [H, I] pads dim 1. + """ + block_size = getattr(quant_config, "weight_block_size", None) + assert block_size is not None + # Round the intermediate axis up to a whole number of TP shards. The axis + # is in elements for weights (step = block) and in blocks for scales. + step = ( + 1 if name.endswith(("weight_scale_inv", "weight_scale")) else block_size[0] + ) + dim = 1 if ".down_proj." in name else 0 + mult = get_tensor_model_parallel_world_size() * step + pad = cdiv(loaded_weight.shape[dim], mult) * mult - loaded_weight.shape[dim] + if pad == 0: + return loaded_weight + pad_shape = list(loaded_weight.shape) + pad_shape[dim] = pad + return torch.cat([loaded_weight, loaded_weight.new_zeros(pad_shape)], dim=dim) + + def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + # Params for weights, fp8 weight scales, fp8 activation scales + # (param_name, weight_name, expert_id, shard_id) + return fused_moe_make_expert_params_mapping( + self, + ckpt_gate_proj_name="w1", + ckpt_down_proj_name="w2", + ckpt_up_proj_name="w3", + num_experts=self.config.n_routed_experts, + ) + + def finalize_mega_moe_weights(self) -> None: + return + + def finalize_mhc_broadcast_weights(self) -> None: + if not get_pp_group().is_first_rank or self.start_layer >= self.end_layer: + return + layer = self.layers[self.start_layer] + if isinstance(layer, DeepseekV4DecoderLayer): + broadcast = ( + layer.hc_attn_fn.detach() + .view(-1, layer.hc_mult, layer.hidden_size) + .sum(dim=1) + ) + if layer.hc_attn_fn_broadcast is None: + layer.hc_attn_fn_broadcast = broadcast + else: + layer.hc_attn_fn_broadcast.copy_(broadcast) + + +def _linear_scale_param_name(vllm_config: VllmConfig, expert_dtype: str) -> str: + """Parameter name the linear quant method registers for weight scales. + + Native MXFP8 checkpoints ([32, 32] blocks with MXFP4 experts) route linear + layers through ModelOptLinearMethod, which registers ``weight_scale``; + block-FP8 linear layers register ``weight_scale_inv``. + """ + use_mxfp8 = ( + getattr(vllm_config.quant_config, "weight_block_size", None) == [32, 32] + and expert_dtype == "fp4" + ) + return "weight_scale" if use_mxfp8 else "weight_scale_inv" + + +def _make_deepseek_v4_weights_mapper( + expert_dtype: str, linear_scale_name: str = "weight_scale_inv" +) -> WeightsMapper: + if expert_dtype == "fp4": + # MXFP4 experts use Mxfp4MoEMethod, which registers scales as + # ``w{1,2,3}_weight_scale`` (no _inv suffix). Linear scales use the + # parameter name registered by their quantization method. + scale_regex = { + # ``.base_layer.``-namespace variant (LoRA-wrapped experts). + re.compile( + r"(\.experts\.\d+\.w[123]\.base_layer)\.scale$" + ): r"\1.weight_scale", + re.compile(r"(\.experts\.\d+\.w[123])\.scale$"): r"\1.weight_scale", + # The ``embed.weight`` -> ``embed_tokens.weight`` suffix rule + # renames the engram fp8 table but not its scale; route the + # scale explicitly to the same module. + re.compile(r"(engram\.embed)\.scale$"): r"\1_tokens.weight_scale_inv", + re.compile(r"\.scale$"): f".{linear_scale_name}", + } + else: + # FP8 experts use Fp8MoEMethod (block_quant=True), which registers + # scales as ``w{13,2}_weight_scale_inv``. Map all ``.scale`` keys + # there. + scale_regex = { + # ``.base_layer.``-namespace variant of the above. + re.compile( + r"(\.experts\.\d+\.w[123]\.base_layer)\.scale$" + ): r"\1.weight_scale_inv", + # Same engram reroute as the fp4 branch above. + re.compile(r"(engram\.embed)\.scale$"): r"\1_tokens.weight_scale_inv", + re.compile(r"\.scale$"): f".{linear_scale_name}", + } + return WeightsMapper( + orig_to_new_prefix={ + "layers.": "model.layers.", + "embed.": "model.embed.", + "norm.": "model.norm.", + "mtp.": "model.mtp.", + }, + orig_to_new_regex=scale_regex, + orig_to_new_suffix={ + "head.weight": "lm_head.weight", + "embed.weight": "embed_tokens.weight", + ".ffn.gate.bias": ".ffn.gate.e_score_correction_bias", + }, + orig_to_new_substr={ + ".shared_experts.w2": ".shared_experts.down_proj", + "mtp.": None, + # The v4.1 checkpoint declares the VL arch even for text-only + # use; the text backbone drops the vision-tower weights. + "vision.": None, + "aligner.": None, + "image_": None, + }, + ) + + +class DeepseekV4MixtureOfExperts(MixtureOfExperts): + moe_mlp_layers: list["DeepseekV4MoE"] + + def extract_moe_parameters(self, example_moe: "DeepseekV4MoE | None") -> None: + if example_moe is None: + self.num_moe_layers = 0 + self.num_expert_groups = 0 + self.num_logical_experts = 0 + self.num_physical_experts = 0 + self.num_local_physical_experts = 0 + self.num_routed_experts = 0 + self.num_shared_experts = 0 + self.num_redundant_experts = 0 + return + self.num_logical_experts = example_moe.n_logical_experts + self.num_physical_experts = example_moe.n_physical_experts + self.num_local_physical_experts = example_moe.n_local_physical_experts + self.num_routed_experts = example_moe.n_routed_experts + self.num_shared_experts = example_moe.n_shared_experts + self.num_redundant_experts = example_moe.n_redundant_experts + + def update_physical_experts_metadata( + self, + num_physical_experts: int, + num_local_physical_experts: int, + ) -> None: + assert self.num_local_physical_experts == num_local_physical_experts + self.num_physical_experts = num_physical_experts + self.num_local_physical_experts = num_local_physical_experts + self.num_redundant_experts = num_physical_experts - self.num_logical_experts + for moe in self.moe_mlp_layers: + moe.n_local_physical_experts = num_local_physical_experts + moe.n_physical_experts = num_physical_experts + moe.n_redundant_experts = self.num_redundant_experts + moe.experts.update_expert_map() + + +class DeepseekV41LLMForCausalLM( + nn.Module, + SupportsPP, + SupportsEagle3, + SupportsLoRA, + DeepseekV4MixtureOfExperts, +): + model_cls = DeepseekV4Model + + # Default mapper assumes the original FP4-expert checkpoint layout. + # Overridden per-instance in __init__ when expert_dtype != "fp4". + hf_to_vllm_mapper = _make_deepseek_v4_weights_mapper("fp4") + + packed_modules_mapping = { + "gate_up_proj": ["w1", "w3"], + "fused_wqa_wkv": ["wq_a", "wkv"], + "fused_wkv_wgate": ["wkv", "wgate"], + } + + # The MTP draft head is not LoRA-adapted. + lora_skip_prefixes = ["mtp."] + + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): + super().__init__() + + config = vllm_config.model_config.hf_config + self.config = config + expert_dtype = getattr(config, "expert_dtype", "fp4") + self.hf_to_vllm_mapper = _make_deepseek_v4_weights_mapper( + expert_dtype, _linear_scale_param_name(vllm_config, expert_dtype) + ) + + self.model = self.model_cls( + vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") + ) + if get_pp_group().is_last_rank: + self.lm_head = ParallelLMHead( + config.vocab_size, + config.hidden_size, + prefix=maybe_prefix(prefix, "lm_head"), + ) + else: + self.lm_head = PPMissingLayer() + self.logits_processor = LogitsProcessor(config.vocab_size) + self.make_empty_intermediate_tensors = ( # type: ignore[method-assign] + self.model.make_empty_intermediate_tensors + ) + + self.set_moe_parameters() + + def set_moe_parameters(self) -> None: + self.num_expert_groups = getattr(self.config, "n_group", 1) + self.num_moe_layers = self.config.num_hidden_layers + self.moe_layers: list[nn.Module] = [] + self.moe_mlp_layers: list[DeepseekV4MoE] = [] + example_moe: DeepseekV4MoE | None = None + for layer in self.model.layers: + if isinstance(layer, PPMissingLayer): + continue + if not isinstance(layer, DeepseekV4DecoderLayer): + continue + if isinstance(layer.ffn, DeepseekV4MoE): + example_moe = layer.ffn + self.moe_mlp_layers.append(layer.ffn) + self.moe_layers.append(layer.ffn.experts) + + self.num_moe_layers = len(self.moe_layers) + self.extract_moe_parameters(example_moe) + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.model.embed_input_ids(input_ids) + + def compute_logits( + self, + hidden_states: torch.Tensor, + ) -> torch.Tensor | None: + logits = self.logits_processor(self.lm_head, hidden_states) + return logits + + def compute_logits_local( + self, + hidden_states: torch.Tensor, + ) -> torch.Tensor: + return self.logits_processor(self.lm_head, hidden_states, skip_gather=True) + + @staticmethod + def get_model_state_cls(): + from ..nvidia.model_state import DeepseekV41ModelState + + return DeepseekV41ModelState + + @property + def token_lookback_depth(self) -> int: + """Tokens before a chunk start the engram hash needs; the model runner + passes them as `lookback_token_ids`.""" + engram_hash = self.model.engram_hash + return engram_hash.lookback_depth if engram_hash is not None else 0 + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + intermediate_tensors: IntermediateTensors | None = None, + inputs_embeds: torch.Tensor | None = None, + lookback_token_ids: torch.Tensor | None = None, + ) -> torch.Tensor | IntermediateTensors: + hidden_states = self.model( + input_ids, + positions, + intermediate_tensors, + inputs_embeds, + lookback_token_ids=lookback_token_ids, + ) + return hidden_states + + def get_mtp_target_hidden_states(self) -> torch.Tensor | None: + """Pre-collapse residual stream buffer (max_num_batched_tokens, + hc_mult * hidden_size) for the MTP draft model. Populated by + forward(); valid after each target step.""" + return getattr(self.model, "_mtp_hidden_buffer", None) + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + loader = AutoWeightsLoader(self) + loaded_params = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) + self.process_weights_after_loading() + return loaded_params + + def process_weights_after_loading(self) -> None: + self.model.finalize_mega_moe_weights() + self.model.finalize_mhc_broadcast_weights() + + def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + return self.model.get_expert_mapping() diff --git a/vllm/models/deepseek_v4_1/amd/rocm.py b/vllm/models/deepseek_v4_1/amd/rocm.py new file mode 100644 index 0000000000..9271e7ae5a --- /dev/null +++ b/vllm/models/deepseek_v4_1/amd/rocm.py @@ -0,0 +1,905 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import functools +from dataclasses import dataclass +from typing import cast + +import torch + +from vllm.distributed import ( + get_tensor_model_parallel_world_size, + tensor_model_parallel_all_reduce, +) +from vllm.forward_context import get_forward_context +from vllm.logger import init_logger +from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention +from vllm.models.deepseek_v4_1.common.ops import dequantize_and_gather_k_cache +from vllm.models.deepseek_v4_1.sparse_mla import ( + DeepseekV4FlashMLAMetadata, + DeepseekV4SparseMLABackend, + DeepseekV4SparseMLAMetadataBuilder, + DeepseekV41SparseSWAMetadataBuilder, +) +from vllm.platforms import current_platform +from vllm.platforms.rocm import _ON_GFX950 +from vllm.triton_utils import tl, triton +from vllm.v1.attention.backend import ( + CommonAttentionMetadata, +) +from vllm.v1.attention.backends.mla.sparse_swa import ( + DeepseekSparseSWABackend, + DeepseekSparseSWAMetadata, +) +from vllm.v1.attention.ops.rocm_aiter_mla_sparse import ( + build_ragged_indices_from_dense, + rocm_inv_rope_einsum, + rocm_sparse_attn_decode, + rocm_sparse_attn_prefill, +) +from vllm.v1.worker.workspace import current_workspace_manager + +logger = init_logger(__name__) + + +def _trust_dsv4_extra_cache_nan_free( + kv_cache_dtype: str, + has_kv_transfer: bool, + has_extra_cache: bool, +) -> bool: + return ( + _ON_GFX950 + and kv_cache_dtype == "fp8_ds_mla" + and not has_kv_transfer + and has_extra_cache + ) + + +def _build_indptr_from_lengths(lengths: torch.Tensor) -> torch.Tensor: + lengths = lengths.to(dtype=torch.int32).contiguous() + indptr = torch.zeros(lengths.shape[0] + 1, dtype=torch.int32, device=lengths.device) + torch.cumsum(lengths, dim=0, out=indptr[1:]) + return indptr + + +def apply_pre_quantized_block_scaled_mm( + linear: torch.nn.Module, + x_fp8: torch.Tensor, + x_scale: torch.Tensor, +) -> torch.Tensor: + """Block-scaled fp8 GEMM on pre-quantized activations. + + The fused q/kv norm kernel writes fp8 qr + per-1x128 scales; this + drives the linear's block-scaled GEMM directly with them, bypassing + apply_weights which would re-quantize the fp8 input. Only valid for + the wq_b-style column/replicated linears: their output is the local + TP shard, so no all-reduce is needed. + """ + from vllm.model_executor.kernels.linear.scaled_mm.BlockScaledMMLinearKernel import ( + FP8BlockParams, + ) + + params = FP8BlockParams.from_layer(linear) + weight_scale = ( + params.weight_scale + if params.weight_scale_inv is None + else params.weight_scale_inv + ) + kernel = linear.quant_method.fp8_linear + out = kernel.apply_block_scaled_mm( + A=x_fp8, B=params.weight, As=x_scale, Bs=weight_scale + ) + return out.to(dtype=kernel.config.out_dtype) + + +# ROCm sparse prefill keeps this dense combine local so AMD-specific SWA changes +# do not touch the shared DeepSeek V4 cache utilities. +_SPARSE_PREFILL_TOPK_ALIGNMENT = 128 + + +@triton.jit +def _combine_topk_swa_indices_kernel( + combined_indices_ptr, + combined_indices_stride, + combined_lens_ptr, + topk_indices_ptr, + topk_indices_stride, + query_start_loc_ptr, + seq_lens_ptr, + gather_lens_ptr, + M, + N, + TOP_K: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + WINDOW_SIZE: tl.constexpr, + TOPK_WIDTH: tl.constexpr, + PADDED_TOP_K: tl.constexpr, +): + batch_idx = tl.program_id(0) + worker_id = tl.program_id(1) + num_workers = tl.num_programs(1) + + base = tl.load(query_start_loc_ptr) + query_start = tl.load(query_start_loc_ptr + batch_idx) - base + query_end = tl.load(query_start_loc_ptr + batch_idx + 1) - base + query_len = query_end - query_start + seq_len = tl.load(seq_lens_ptr + batch_idx) + gather_len = tl.load(gather_lens_ptr + batch_idx) + start_pos = seq_len - query_len + gather_start = seq_len - gather_len + + for token_idx in range(query_start + worker_id, query_end, num_workers): + token_idx_in_query = token_idx - query_start + pos = start_pos + token_idx_in_query + topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K) + swa_len = tl.minimum(pos + 1, WINDOW_SIZE) + + topk_offset = tl.arange(0, PADDED_TOP_K) + topk_mask = topk_offset < topk_len + safe_topk_offset = tl.where(topk_offset < TOPK_WIDTH, topk_offset, 0) + topk_indices = tl.load( + topk_indices_ptr + token_idx * topk_indices_stride + safe_topk_offset, + mask=topk_mask, + other=-1, + ) + valid_topk = (topk_indices >= 0) & (topk_indices < N) + topk_indices = tl.where(valid_topk, topk_indices + M * batch_idx, -1) + tl.store( + combined_indices_ptr + token_idx * combined_indices_stride + topk_offset, + topk_indices, + mask=topk_mask, + ) + + swa_offset = tl.arange(0, WINDOW_SIZE) + tl.store( + combined_indices_ptr + + token_idx * combined_indices_stride + + topk_len + + swa_offset, + M * batch_idx + N + swa_offset + pos - swa_len + 1 - gather_start, + mask=swa_offset < swa_len, + ) + + tl.store(combined_lens_ptr + token_idx, topk_len + swa_len) + + +def combine_topk_swa_indices( + topk_indices: torch.Tensor, + query_start_loc: torch.Tensor, + seq_lens: torch.Tensor, + gather_lens: torch.Tensor, + window_size: int, + compress_ratio: int, + topk: int, + M: int, + N: int, +) -> tuple[torch.Tensor, torch.Tensor]: + """Combine compressed-attention and sliding-window indices with Torch. + + The Triton implementation inherited from DeepSeek V4 launches a + two-dimensional grid with 128 workers per request. On gfx950 it can issue + an out-of-bounds access for V4.1's mixed prefill metadata (including the + synthetic mixed-token warmup). This path is prefill-only and the tensors + are small, so use ordinary Torch indexing until a gfx950-safe fused kernel + is available. + """ + topk_indices = topk_indices.reshape(topk_indices.shape[0], -1).contiguous() + num_tokens = topk_indices.shape[0] + combined_topk = ( + (topk + window_size + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1) + // _SPARSE_PREFILL_TOPK_ALIGNMENT + * _SPARSE_PREFILL_TOPK_ALIGNMENT + ) + combined_indices = torch.full( + (num_tokens, combined_topk), + fill_value=-1, + dtype=torch.int32, + device=topk_indices.device, + ) + combined_lens = torch.empty( + num_tokens, dtype=torch.int32, device=topk_indices.device + ) + + # query_start_loc may have a non-zero base for a narrowed mixed batch. + query_lens = query_start_loc[1:] - query_start_loc[:-1] + req_ids = torch.repeat_interleave( + torch.arange(seq_lens.shape[0], device=seq_lens.device), query_lens + ) + query_starts = query_start_loc[:-1] - query_start_loc[0] + token_offsets = torch.arange(num_tokens, device=seq_lens.device) - ( + torch.repeat_interleave(query_starts, query_lens) + ) + positions = seq_lens[req_ids] - query_lens[req_ids] + token_offsets + + logical_topk_width = min(topk, topk_indices.shape[1]) + topk_lens = torch.minimum( + (positions + 1) // compress_ratio, + torch.full_like(positions, logical_topk_width), + ).clamp_min(0) + topk_offsets = torch.arange(logical_topk_width, device=seq_lens.device) + topk_mask = topk_offsets[None, :] < topk_lens[:, None] + topk_values = topk_indices[:, :logical_topk_width].to(torch.int32) + topk_valid = topk_mask & (topk_values >= 0) & (topk_values < N) + combined_indices[:, :logical_topk_width] = torch.where( + topk_valid, + topk_values + (M * req_ids).to(torch.int32)[:, None], + -1, + ) + + swa_lens = torch.minimum( + positions + 1, torch.full_like(positions, window_size) + ).clamp_min(0) + swa_offsets = torch.arange(window_size, device=seq_lens.device) + swa_mask = swa_offsets[None, :] < swa_lens[:, None] + swa_columns = topk_lens[:, None] + swa_offsets[None, :] + gather_starts = seq_lens - gather_lens + swa_values = ( + M * req_ids[:, None] + + N + + swa_offsets[None, :] + + positions[:, None] + - swa_lens[:, None] + + 1 + - gather_starts[req_ids, None] + ).to(torch.int32) + rows = torch.arange(num_tokens, device=seq_lens.device)[:, None].expand_as( + swa_columns + ) + flat_dst = rows[swa_mask] * combined_topk + swa_columns[swa_mask] + combined_indices.view(-1).index_copy_(0, flat_dst, swa_values[swa_mask]) + combined_lens.copy_((topk_lens + swa_lens).to(torch.int32)) + return combined_indices, combined_lens + + +@triton.jit +def _compute_topk_lens_kernel( + topk_lens_ptr, + topk_indices_ptr, + topk_indices_stride, + topk, + is_valid_token_ptr, + TRITON_BLOCK_SIZE: tl.constexpr, +): + token_idx = tl.program_id(0) + is_valid_token = tl.load(is_valid_token_ptr + token_idx) + + count = tl.zeros((), dtype=tl.int32) + for i in range(0, topk, TRITON_BLOCK_SIZE): + offset = i + tl.arange(0, TRITON_BLOCK_SIZE) + mask = offset < topk + local_idx = tl.load( + topk_indices_ptr + token_idx * topk_indices_stride + offset, + mask=mask, + other=-1, + ) + count += tl.sum((local_idx >= 0).to(tl.int32), axis=0) + + tl.store(topk_lens_ptr + token_idx, tl.where(is_valid_token, count, 0)) + + +@triton.jit +def _pack_global_topk_ragged_kernel( + global_topk_ragged_ptr, + topk_indptr_ptr, + topk_indices_ptr, + topk_indices_stride, + token_to_req_indices_ptr, + block_table_ptr, + block_table_stride, + block_size, + topk, + BLOCK_SIZE: tl.constexpr, +): + token_idx = tl.program_id(0) + block_idx = tl.program_id(1) + offset = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + + out_start = tl.load(topk_indptr_ptr + token_idx) + out_end = tl.load(topk_indptr_ptr + token_idx + 1) + out_len = out_end - out_start + if block_idx * BLOCK_SIZE >= out_len: + return + + req_idx = tl.load(token_to_req_indices_ptr + token_idx) + mask = (offset < out_len) & (offset < topk) + local_idx = tl.load( + topk_indices_ptr + token_idx * topk_indices_stride + offset, + mask=mask, + other=-1, + ) + valid = mask & (local_idx >= 0) + block_indices = local_idx // block_size + block_numbers = tl.load( + block_table_ptr + req_idx * block_table_stride + block_indices, + mask=valid, + other=0, + ) + block_offsets = local_idx % block_size + slot_ids = tl.where(valid, block_numbers * block_size + block_offsets, -1) + tl.store(global_topk_ragged_ptr + out_start + offset, slot_ids, mask=mask) + + +def compute_global_topk_ragged_indices_and_indptr( + topk_indices: torch.Tensor, + token_to_req_indices: torch.Tensor, + block_table: torch.Tensor, + block_size: int, + is_valid_token: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + topk_indices = topk_indices.reshape(topk_indices.shape[0], -1).contiguous() + num_tokens = topk_indices.shape[0] + topk = topk_indices.shape[1] + + topk_lens = torch.empty(num_tokens, dtype=torch.int32, device=topk_indices.device) + _compute_topk_lens_kernel[(num_tokens,)]( + topk_lens, + topk_indices, + topk_indices.stride(0), + topk, + is_valid_token, + TRITON_BLOCK_SIZE=1024, + ) + + topk_indptr = _build_indptr_from_lengths(topk_lens) + global_topk_ragged = torch.empty( + num_tokens * topk, + dtype=torch.int32, + device=topk_indices.device, + ) + if global_topk_ragged.numel() > 0: + block = 128 + _pack_global_topk_ragged_kernel[(num_tokens, triton.cdiv(topk, block))]( + global_topk_ragged, + topk_indptr, + topk_indices, + topk_indices.stride(0), + token_to_req_indices, + block_table, + block_table.stride(0), + block_size, + topk, + BLOCK_SIZE=block, + ) + return global_topk_ragged, topk_indptr, topk_lens + + +def _copy_ragged_to_graph_buffers( + ragged_indices: torch.Tensor, + ragged_indptr: torch.Tensor, + ragged_indices_buffer: torch.Tensor, + ragged_indptr_buffer: torch.Tensor, + num_rows: int, + max_entries_per_row: int, +) -> tuple[torch.Tensor, torch.Tensor]: + """Copy dynamic ragged metadata into persistent CUDA graph buffers. + + FULL decode graphs capture kernel argument addresses. Keep the returned + tensors backed by stable storage, while indptr continues to bound reads. + """ + indptr_out = ragged_indptr_buffer[: num_rows + 1] + indptr_out.copy_(ragged_indptr, non_blocking=True) + + max_entries = max(num_rows * max_entries_per_row, 1) + ragged_out = ragged_indices_buffer[:max_entries] + source_entries = ragged_indices.numel() + if source_entries > 0: + ragged_out[:source_entries].copy_(ragged_indices, non_blocking=True) + if _ON_GFX950: + # Preserve the graph-stable base pointer while exposing source capacity + # to the sync-free split selector; indptr still carries the true NNZ. + ragged_out = ragged_out[: max(source_entries, 1)] + return ragged_out, indptr_out + + +@dataclass +class DeepseekV4ROCMAiterSparseSWAMetadata(DeepseekSparseSWAMetadata): + decode_swa_ragged_indices: torch.Tensor | None = None + decode_swa_ragged_indptr: torch.Tensor | None = None + + +class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBuilder): + # Keep fused multi-step decode disabled until update_draft_decode_metadata() + # also refreshes the ROCm-specific ragged SWA indices and indptrs. + supports_draft_decode_metadata_update = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + max_tokens = self.vllm_config.scheduler_config.max_num_batched_tokens + # The non-causal (DSpark draft) path widens each token's SWA index list + # to ``noncausal_index_width`` (>= window_size), so size the persistent + # ragged buffer to the wider bound to cover both causal and non-causal. + swa_index_width = max(self.window_size, self.noncausal_index_width) + self.decode_swa_ragged_indices_buffer = torch.empty( + max_tokens * swa_index_width, + dtype=torch.int32, + device=self.device, + ) + self.decode_swa_ragged_indptr_buffer = torch.empty( + max_tokens + 1, + dtype=torch.int32, + device=self.device, + ) + + def build( + self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False, + ) -> DeepseekV4ROCMAiterSparseSWAMetadata: + base = super().build( + common_prefix_len=common_prefix_len, + common_attn_metadata=common_attn_metadata, + fast_build=fast_build, + ) + + ragged_indices = None + ragged_indptr = None + if ( + base.num_decode_tokens > 0 + and base.decode_swa_indices is not None + and base.decode_swa_lens is not None + ): + ragged_indices, ragged_indptr = build_ragged_indices_from_dense( + base.decode_swa_indices.reshape( + base.num_decode_tokens, base.decode_swa_width + ), + base.decode_swa_lens, + ) + ragged_indices, ragged_indptr = _copy_ragged_to_graph_buffers( + ragged_indices, + ragged_indptr, + self.decode_swa_ragged_indices_buffer, + self.decode_swa_ragged_indptr_buffer, + base.num_decode_tokens, + base.decode_swa_width, + ) + + return DeepseekV4ROCMAiterSparseSWAMetadata( + **vars(base), + decode_swa_ragged_indices=ragged_indices, + decode_swa_ragged_indptr=ragged_indptr, + ) + + +class DeepseekV4ROCMAiterMLASparseBackend(DeepseekV4SparseMLABackend): + @staticmethod + def get_name() -> str: + return "ROCM_FLASHMLA_SPARSE_DSV4" + + @staticmethod + def get_builder_cls() -> type[DeepseekV4SparseMLAMetadataBuilder]: + return DeepseekV4SparseMLAMetadataBuilder + + +class DeepseekV41ROCMAiterSparseSWABackend(DeepseekSparseSWABackend): + @staticmethod + def get_builder_cls() -> type["DeepseekV4ROCMAiterSparseSWAMetadataBuilder"]: + return DeepseekV4ROCMAiterSparseSWAMetadataBuilder + + +class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention): + """ROCm sparse MLA attention layer for DeepSeek V4.1.""" + + backend_cls = DeepseekV4ROCMAiterMLASparseBackend + swa_backend_cls = DeepseekV41ROCMAiterSparseSWABackend + + def __init__(self, *args, **kwargs): + vllm_config = args[0] if args else kwargs["vllm_config"] + super().__init__(*args, **kwargs) + # CUDA executes WO_A with a quantized grouped-BMM kernel. ROCm's + # correctness path below dequantizes WO_A once and uses torch.einsum, + # so retain the ordinary MXFP8 linear kernel for post-load processing + # instead of asking for the CUDA-only BMM kernel. + self.wo_a.is_bmm = False + self._has_kv_transfer = vllm_config.kv_transfer_config is not None + # Block scale for the preshuffled weight; None = not preshuffled. + self._wqa_wkv_scale: torch.Tensor | None = None + self._wo_b_scale: torch.Tensor | None = None + self._fused_compressor_weight: torch.Tensor | None + self.register_buffer("_fused_compressor_weight", None, persistent=False) + self._fused_compressor_split_sizes: tuple[int, int] | None = None + + @classmethod + def get_padded_num_q_heads(cls, num_heads: int) -> int: + return num_heads + + def prepare_attn_preshuffle(self) -> None: + from vllm._aiter_ops import rocm_aiter_ops + + if not rocm_aiter_ops.is_enabled(): + return + from vllm.model_executor.layers.quantization.utils.fp8_utils import ( + _upcast_e8m0_to_fp32, + ) + from vllm.model_executor.utils import replace_parameter + + def _prep(linear) -> torch.Tensor | None: + w = getattr(linear, "weight", None) + if w is None or w.dim() != 2: + return None + # K % 128 (group-128 quant) and N % 16 (shuffle_weight) must hold. + if w.shape[-1] % 128 != 0 or w.shape[0] % 16 != 0: + return None + ws = getattr(linear, "weight_scale_inv", None) # per-block scale + if ws is None: + return None + if ws.dtype == torch.float8_e8m0fnu: + ws = _upcast_e8m0_to_fp32(ws).contiguous() + # Shuffle the weight in place (single weight, no unshuffled copy). + replace_parameter( + linear, + "weight", + rocm_aiter_ops.shuffle_weight(w.data, layout=(16, 16)), + ) + return ws + + self._wqa_wkv_scale = _prep(self.fused_wqa_wkv) + self._wo_b_scale = _prep(self.wo_b) + + def prepare_compressor_gemm_fusion(self) -> bool: + # V4.1 derives index keys from the source compressor's emitted latent + # and has no nested ``indexer.compressor``. Keep the projections + # separate and use the shared linear/PyTorch correctness path. + return False + + def _bpre_attn_gemm( + self, + weight: torch.Tensor, + scale: torch.Tensor, + x: torch.Tensor, + reduce_tp: bool, + ) -> torch.Tensor: + from vllm._aiter_ops import rocm_aiter_ops + + x_fp8, x_scale = rocm_aiter_ops.group_fp8_quant(x, transpose_scale=True) + out = rocm_aiter_ops.gemm_a8w8_blockscale_bpreshuffle( + x_fp8, weight, x_scale, scale, output_dtype=x.dtype + ) + if reduce_tp and get_tensor_model_parallel_world_size() > 1: + out = tensor_model_parallel_all_reduce(out) + return out + + def _fused_wqa_wkv_gemm(self, hidden_states: torch.Tensor) -> torch.Tensor: + if self._wqa_wkv_scale is not None and hidden_states.dim() == 2: + return self._bpre_attn_gemm( + self.fused_wqa_wkv.weight, self._wqa_wkv_scale, hidden_states, False + ) + return super()._fused_wqa_wkv_gemm(hidden_states) + + def _run_parallel_input_projections( + self, hidden_states: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + return super()._run_parallel_input_projections(hidden_states) + + @functools.cached_property + def _wq_b_uses_aiter_block_scaled(self) -> bool: + """True when both wq_b GEMMs run the aiter block-scaled fp8 kernel. + + Cached: the linear kernels and the aiter env gates are fixed once + the model is built, so this is evaluated at the first forward + only. + + The fused norm+quant path is only valid if the quant and GEMM it + replaces are exactly the aiter ones; otherwise fall back to the + shared path. + """ + from vllm._aiter_ops import rocm_aiter_ops + from vllm.model_executor.kernels.linear.scaled_mm import ( + Fp8BlockScaledMMLinearKernel, + ) + + if not rocm_aiter_ops.is_linear_fp8_enabled(): + return False + + linears = [self.wq_b] + if self.indexer is not None: + linears.append(self.indexer.wq_b) + for linear in linears: + kernel = getattr(getattr(linear, "quant_method", None), "fp8_linear", None) + if not isinstance(kernel, Fp8BlockScaledMMLinearKernel): + return False + return True + + def _split_qkv_and_norm( + self, qr_kv: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]: + """Fuse q/kv RMSNorm + per-1x128 fp8 q quant into one aiter kernel. + + The shared path norms q and kv in one triton kernel and the wq_b + linears then re-read the bf16 qr to quantize it. The aiter kernel + computes both RMSNorms (fp32 accumulate) and the fp8 group quant + in a single pass, writing fp8 qr + group scales directly; both + wq_b GEMMs (attention and indexer) then consume that pair and + skip their own input quant. kv stays bf16: the fused insert + kernel RoPE/quantizes it itself. Falls back to the shared path + when the aiter linear path is not active. + """ + qr, kv = qr_kv.split([self.q_lora_rank, self.head_dim], dim=-1) + if not ( + qr.dim() == 2 + and qr.shape[0] > 0 + and self.q_lora_rank % 128 == 0 + and self._wq_b_uses_aiter_block_scaled + ): + return super()._split_qkv_and_norm(qr_kv) + + from vllm._aiter_ops import rocm_aiter_ops + + return rocm_aiter_ops.fused_qk_rmsnorm_group_quant( + q=qr, + q_weight=self.q_norm.weight.data, + q_epsilon=self.eps, + kv=kv, + kv_weight=self.kv_norm.weight.data, + kv_epsilon=self.eps, + group_size=128, + transpose_scale=False, + ) + + def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + # ROCm BF16 reference wo_a path (inverse RoPE + einsum) + wo_b. + z = rocm_inv_rope_einsum( + self.rotary_emb, + o, + positions, + self.rope_head_dim, + self.n_local_groups, + self.o_lora_rank, + self.wo_a, + ) + zf = z.flatten(1) + if self._wo_b_scale is not None and zf.dim() == 2: + result = self._bpre_attn_gemm(self.wo_b.weight, self._wo_b_scale, zf, True) + else: + result = self.wo_b(zf) + return result + + def forward_mqa( + self, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + output: torch.Tensor, + ) -> None: + assert output.shape == q.shape, ( + f"output buffer shape {output.shape} must match q shape {q.shape}" + ) + assert output.dtype == q.dtype, ( + f"output buffer dtype {output.dtype} must match q dtype {q.dtype}" + ) + + forward_context = get_forward_context() + attn_metadata = forward_context.attn_metadata + + if attn_metadata is None: + # Warmup dummy run: no real metadata. Reserve the same bf16 + # gather workspace _forward_prefill would; the dequantize / topk + # / sparse_fwd kernels are skipped this step. + swa_only = self.compress_ratio == 0 + N = ( + 0 + if swa_only + else (self.max_model_len + self.compress_ratio - 1) + // self.compress_ratio + ) + M = N + self.window_size + self.max_num_batched_tokens + current_workspace_manager().get_simultaneous( + ((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16), + ) + output.zero_() + return + + assert isinstance(attn_metadata, dict) + rocm_metadata = cast( + DeepseekV4FlashMLAMetadata | None, + attn_metadata.get(self.compressed_cache_prefix) + if self.compressed_cache_prefix is not None + else None, + ) + swa_metadata = cast( + DeepseekV4ROCMAiterSparseSWAMetadata | None, + attn_metadata.get(self.swa_cache_layer.prefix), + ) + assert swa_metadata is not None + + swa_only = self.compress_ratio == 0 + self_kv_cache = None if swa_only else self._compressed_kv_cache() + swa_kv_cache = self.swa_cache_layer.kv_cache + + num_decodes = swa_metadata.num_decodes + num_prefills = swa_metadata.num_prefills + num_decode_tokens = swa_metadata.num_decode_tokens + + if num_prefills > 0: + self._forward_prefill( + q=q[num_decode_tokens:], + positions=positions[num_decode_tokens:], + compressed_k_cache=self_kv_cache, + swa_k_cache=swa_kv_cache, + output=output[num_decode_tokens:], + attn_metadata=rocm_metadata, + swa_metadata=swa_metadata, + ) + if num_decodes > 0: + self._forward_decode( + q=q[:num_decode_tokens], + kv_cache=self_kv_cache, + swa_metadata=swa_metadata, + attn_metadata=rocm_metadata, + swa_only=swa_only, + output=output[:num_decode_tokens], + ) + + def _forward_decode( + self, + q: torch.Tensor, + kv_cache: torch.Tensor | None, + swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata, + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_only: bool, + output: torch.Tensor, + ) -> None: + num_decodes = swa_metadata.num_decodes + num_decode_tokens = swa_metadata.num_decode_tokens + + topk_lens = None + topk_ragged_indices = None + topk_ragged_indptr = None + if not swa_only: + # Local indices filled by the index-source layer's indexer. + assert attn_metadata is not None + assert swa_metadata.is_valid_token is not None + assert self.topk_indices_buffer is not None + block_size = attn_metadata.block_size // self.compress_ratio + is_valid = swa_metadata.is_valid_token[:num_decode_tokens] + ( + topk_ragged_indices, + topk_ragged_indptr, + topk_lens, + ) = compute_global_topk_ragged_indices_and_indptr( + self.topk_indices_buffer[:num_decode_tokens], + swa_metadata.token_to_req_indices, + attn_metadata.block_table[:num_decodes], + block_size, + is_valid, + ) + + rocm_sparse_attn_decode( + q=q, + kv_cache=kv_cache, + swa_k_cache=self.swa_cache_layer.kv_cache, + swa_only=swa_only, + topk_indices=None, + topk_lens=topk_lens, + swa_indices=swa_metadata.decode_swa_indices, + swa_lens=swa_metadata.decode_swa_lens, + swa_ragged_indices=swa_metadata.decode_swa_ragged_indices, + swa_ragged_indptr=swa_metadata.decode_swa_ragged_indptr, + topk_ragged_indices=topk_ragged_indices, + topk_ragged_indptr=topk_ragged_indptr, + attn_sink=self.attn_sink, + scale=self.scale, + head_dim=self.head_dim, + nope_head_dim=self.nope_head_dim, + rope_head_dim=self.rope_head_dim, + output=output, + extra_cache_nan_free=_trust_dsv4_extra_cache_nan_free( + self.kv_cache_dtype, + self._has_kv_transfer, + not swa_only and kv_cache is not None, + ), + ) + + def _forward_prefill( + self, + q: torch.Tensor, + positions: torch.Tensor, + compressed_k_cache: torch.Tensor | None, + swa_k_cache: torch.Tensor, + output: torch.Tensor, + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata, + ) -> None: + swa_only = attn_metadata is None + + num_prefills = swa_metadata.num_prefills + num_prefill_tokens = swa_metadata.num_prefill_tokens + num_decodes = swa_metadata.num_decodes + num_decode_tokens = swa_metadata.num_decode_tokens + + seq_lens = swa_metadata.prefill_seq_lens + gather_lens = swa_metadata.prefill_gather_lens + assert seq_lens is not None + assert gather_lens is not None + + query_start_loc_cpu = swa_metadata.query_start_loc_cpu + query_start_loc = swa_metadata.query_start_loc + assert query_start_loc_cpu is not None + assert query_start_loc is not None + prefill_token_base = query_start_loc_cpu[num_decodes] + + # Local indices filled by the index source; SWA-only layers pass + # top_k=0 and never read them. + assert self.topk_indices_buffer is not None + topk_indices = self.topk_indices_buffer[num_decode_tokens:] + topk_indices = topk_indices[:num_prefill_tokens] + if not swa_only: + top_k = topk_indices.shape[-1] + N = (self.max_model_len + self.compress_ratio - 1) // self.compress_ratio + else: + top_k = 0 + N = 0 + + M = N + self.window_size + self.max_num_batched_tokens + num_chunks = (num_prefills + self.PREFILL_CHUNK_SIZE - 1) // ( + self.PREFILL_CHUNK_SIZE + ) + + workspace_manager = current_workspace_manager() + kv = workspace_manager.get_simultaneous( + ((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16), + )[0] + for chunk_idx in range(num_chunks): + chunk_start = chunk_idx * self.PREFILL_CHUNK_SIZE + chunk_end = min(chunk_start + self.PREFILL_CHUNK_SIZE, num_prefills) + chunk_size = chunk_end - chunk_start + if not swa_only: + assert attn_metadata is not None + assert compressed_k_cache is not None + block_table = attn_metadata.block_table[num_decodes:] + # compressed_k_cache is OCP on every platform (Triton encoder). + dequantize_and_gather_k_cache( + kv[:chunk_size], + compressed_k_cache, + seq_lens=seq_lens[chunk_start:chunk_end] // self.compress_ratio, + gather_lens=None, + block_table=block_table[chunk_start:chunk_end], + block_size=attn_metadata.block_size // self.compress_ratio, + offset=0, + use_fnuz=False, + ) + + swa_block_table = swa_metadata.block_table[num_decodes:] + dequantize_and_gather_k_cache( + kv[:chunk_size], + swa_k_cache, + seq_lens=seq_lens[chunk_start:chunk_end], + gather_lens=gather_lens[chunk_start:chunk_end], + block_table=swa_block_table[chunk_start:chunk_end], + block_size=swa_metadata.block_size, + offset=N, + use_fnuz=current_platform.is_fp8_fnuz(), + ) + + query_start = ( + query_start_loc_cpu[num_decodes + chunk_start] - prefill_token_base + ) + query_end = ( + query_start_loc_cpu[num_decodes + chunk_end] - prefill_token_base + ) + + combined_indices, combined_lens = combine_topk_swa_indices( + topk_indices[query_start:query_end], + query_start_loc[ + num_decodes + chunk_start : num_decodes + chunk_end + 1 + ], + seq_lens[chunk_start:chunk_end], + gather_lens[chunk_start:chunk_end], + self.window_size, + self.compress_ratio, + top_k, + M, + N, + ) + rocm_sparse_attn_prefill( + q=q[query_start:query_end], + kv=kv.view(-1, 1, q.shape[-1]), + indices=combined_indices, + topk_length=combined_lens, + scale=self.scale, + head_dim=self.head_dim, + nope_head_dim=self.nope_head_dim, + rope_head_dim=self.rope_head_dim, + attn_sink=self.attn_sink, + output=output[query_start:query_end], + ) diff --git a/vllm/models/deepseek_v4_1/amd/vl_model.py b/vllm/models/deepseek_v4_1/amd/vl_model.py new file mode 100644 index 0000000000..91a13bd725 --- /dev/null +++ b/vllm/models/deepseek_v4_1/amd/vl_model.py @@ -0,0 +1,357 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepSeek-V4.1 vision variant. + +Thin multimodal wrapper around the text-only ``DeepseekV41LLMForCausalLM``: + +- ``vision`` ViT + ``aligner`` produce per-image embeddings for the IMAGE + positions; three learned vectors (``image_start`` / ``image_newline`` / + ``image_end``) fill the delimiter positions. Every image-span position + carries ``image_token_id`` (129264) in ``input_ids``; the per-position + roles come from the processor's ``types`` tensor (see + ``common/mm_preprocess.py``, and ``common/vision.py`` for the tower). +- Merged embeddings enter the text model via ``inputs_embeds``, i.e. before + its hyper-connection stream expansion. Raw ``input_ids`` still flow into + the model so the MoE router can apply ``bias_vl`` to image tokens + (``requires_raw_input_tokens``). +""" + +from collections.abc import Iterable +from typing import Annotated + +import torch +from torch import nn + +from vllm.distributed import get_tensor_model_parallel_world_size +from vllm.model_executor.models.interfaces import ( + MultiModalEmbeddings, + SupportsEagle3, + SupportsMultiModal, + SupportsPP, +) +from vllm.model_executor.models.utils import ( + AutoWeightsLoader, + WeightsMapper, + maybe_prefix, +) +from vllm.model_executor.models.vision import is_vit_use_data_parallel +from vllm.models.deepseek_v4.common.vision import ( + DeepseekV4Aligner, + DeepseekV4ViT, + run_dp_sharded_vision_tower, +) +from vllm.multimodal import MULTIMODAL_REGISTRY +from vllm.utils.tensor_schema import TensorSchema, TensorShape + +from ..common.mm_preprocess import ( + IMAGE, + IMAGE_END, + IMAGE_NEW_LINE, + IMAGE_PAD_ID, + IMAGE_PLACEHOLDER, + IMAGE_SENTINEL_BASE_ID, + IMAGE_START, + DeepseekV4VLDummyInputsBuilder, + DeepseekV4VLMultiModalProcessor, + DeepseekV4VLProcessingInfo, +) +from .model import ( + DeepseekV41LLMForCausalLM, + _linear_scale_param_name, + _make_deepseek_v4_weights_mapper, +) + + +class DeepseekV4VLImagePixelInputs(TensorSchema): + """ViT patch inputs for one batched set of images. + + Dimensions: + - np: Total ViT patches across images (sum of n_vit_h * n_vit_w) + - c: Number of image channels (3) + - p: ViT patch size + - ni: Number of images + - ns: Total image-span positions (sum of n_llm_h * (n_llm_w + 1) + 2) + """ + + patches: Annotated[ + torch.Tensor, TensorShape("np", 3, "p", "p", dynamic_dims={"np"}) + ] + # [n_vit_h, n_vit_w] per image + vit_grid: Annotated[torch.Tensor, TensorShape("ni", 2)] + # [n_llm_h, n_llm_w] per image + llm_grid: Annotated[torch.Tensor, TensorShape("ni", 2)] + types: Annotated[torch.Tensor, TensorShape("ns", dynamic_dims={"ns"})] + + +def _make_deepseek_v4_vl_weights_mapper( + expert_dtype: str, linear_scale_name: str +) -> WeightsMapper: + """Text-checkpoint mapping rules re-rooted under ``language_model.``.""" + base = _make_deepseek_v4_weights_mapper(expert_dtype, linear_scale_name) + orig_to_new_prefix: dict[str, str | None] = { + "layers.": "language_model.model.layers.", + "embed.": "language_model.model.embed.", + "norm.": "language_model.model.norm.", + "hc_head": "language_model.model.hc_head", + "mtp.": "language_model.model.mtp.", + } + return WeightsMapper( + orig_to_new_prefix=orig_to_new_prefix, + orig_to_new_regex=base.orig_to_new_regex, + orig_to_new_suffix={ + "head.weight": "language_model.lm_head.weight", + "embed.weight": "embed_tokens.weight", + ".ffn.gate.bias": ".ffn.gate.e_score_correction_bias", + }, + orig_to_new_substr={ + ".shared_experts.w2": ".shared_experts.down_proj", + # The MTP/DSpark draft heads are not supported for the vision + # variant; drop their weights. + "mtp.": None, + }, + ) + + +@MULTIMODAL_REGISTRY.register_processor( + DeepseekV4VLMultiModalProcessor, + info=DeepseekV4VLProcessingInfo, + dummy_inputs=DeepseekV4VLDummyInputsBuilder, +) +class DeepseekV41ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsEagle3): + """Multimodal entry point for DeepSeek-V4.1 checkpoints with a vision tower. + + ``SupportsEagle3`` (aux hidden-state plumbing for MTP/DSpark drafters) + delegates through ``language_model`` via the protocol defaults. + """ + + supports_encoder_tp_data = True + + # The MoE router needs raw token ids to detect image-span tokens + # (all carrying image_token_id, see common/mm_preprocess.py) and apply + # bias_vl. + requires_raw_input_tokens = True + + @classmethod + def get_placeholder_str(cls, modality: str, i: int) -> str | None: + if modality == "image": + return IMAGE_PLACEHOLDER + raise ValueError(f"Unsupported modality: {modality!r}") + + def __init__(self, *, vllm_config, prefix: str = "") -> None: + super().__init__() + model_config = vllm_config.model_config + config = model_config.hf_config + self.config = config + self.multimodal_config = model_config.multimodal_config + assert self.multimodal_config is not None + + # The tower is always built; _mark_tower_model stubs it out + # (StageMissingLayer, weights skipped) when the image limit is 0. + with self._mark_tower_model(vllm_config, {"image"}): + self.use_data_parallel = is_vit_use_data_parallel(config.vision_n_heads) + self.vision = DeepseekV4ViT(config) + self.aligner = DeepseekV4Aligner(config) + self.image_start = nn.Parameter( + torch.empty(config.hidden_size, dtype=torch.float32) + ) + self.image_end = nn.Parameter( + torch.empty(config.hidden_size, dtype=torch.float32) + ) + self.image_newline = nn.Parameter( + torch.empty(config.hidden_size, dtype=torch.float32) + ) + self.vision.to(dtype=model_config.dtype) + self.aligner.to(dtype=model_config.dtype) + + with self._mark_language_model(vllm_config): + self.language_model = DeepseekV41LLMForCausalLM( + vllm_config=vllm_config, + prefix=maybe_prefix(prefix, "language_model"), + ) + # The outer mapper (see load_weights) fully resolves HF names into + # this wrapper's namespace before AutoWeightsLoader strips the + # "language_model." prefix and delegates to the child's load_weights, + # so the child's own mapper must be a no-op. Its suffix rules are not + # idempotent (e.g. "lm_head.weight".endswith("head.weight") would + # re-fire "head.weight" -> "lm_head.weight"). + self.language_model.hf_to_vllm_mapper = WeightsMapper() + self.make_empty_intermediate_tensors = ( # type: ignore[method-assign] + self.language_model.make_empty_intermediate_tensors + ) + + expert_dtype = getattr(config, "expert_dtype", "fp4") + self.hf_to_vllm_mapper = _make_deepseek_v4_vl_weights_mapper( + expert_dtype, _linear_scale_param_name(vllm_config, expert_dtype) + ) + + def _parse_and_validate_image_input( + self, **kwargs: object + ) -> DeepseekV4VLImagePixelInputs | None: + patches = kwargs.pop("patches", None) + if patches is None: + return None + return DeepseekV4VLImagePixelInputs( + patches=patches, + vit_grid=kwargs.pop("vit_grid"), + llm_grid=kwargs.pop("llm_grid"), + types=kwargs.pop("types"), + resolve_bindings={"p": self.config.vision_patch_size}, + ) + + def _encode_image( + self, + patches: torch.Tensor, + n_vit_h: int, + n_vit_w: int, + ) -> torch.Tensor: + # Aligner rows in reading order, one per IMAGE slot. + return self.aligner(self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w) + + def _build_image_span( + self, image_embeds: torch.Tensor, types: torch.Tensor + ) -> torch.Tensor: + """Full image span: aligner rows at IMAGE slots, the learned + delimiter vectors at IMAGE_START/IMAGE_NEW_LINE/IMAGE_END.""" + types = types.to(image_embeds.device) + span = image_embeds.new_empty(types.numel(), image_embeds.shape[-1]) + dtype = image_embeds.dtype + span[types == IMAGE_START] = self.image_start.to(dtype) + span[types == IMAGE_END] = self.image_end.to(dtype) + span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype) + span[types == IMAGE] = image_embeds + return span + + def _process_image_input( + self, + image_input: DeepseekV4VLImagePixelInputs, + ) -> tuple[torch.Tensor, ...]: + patches = image_input.patches.to(self.aligner.w1.weight.dtype) + vit_grid = image_input.vit_grid.tolist() + + image_embeds_list: list[torch.Tensor] + if self.use_data_parallel and get_tensor_model_parallel_world_size() > 1: + # Data-parallel ViT: shard images across TP ranks and all-gather + # the per-image embeddings (weights are replicated on every rank). + image_embeds_list = run_dp_sharded_vision_tower( + self.vision, self.aligner, patches, vit_grid + ) + else: + image_embeds_list = [] + vit_offset = 0 + for n_vit_h, n_vit_w in vit_grid: + n_vit = n_vit_h * n_vit_w + image_embeds_list.append( + self._encode_image( + patches[vit_offset : vit_offset + n_vit], n_vit_h, n_vit_w + ) + ) + vit_offset += n_vit + + embeds: list[torch.Tensor] = [] + span_offset = 0 + for image_embeds, (n_llm_h, n_llm_w) in zip( + image_embeds_list, image_input.llm_grid.tolist(), strict=True + ): + span_len = n_llm_h * (n_llm_w + 1) + 2 + embeds.append( + self._build_image_span( + image_embeds, + image_input.types[span_offset : span_offset + span_len], + ) + ) + span_offset += span_len + return tuple(embeds) + + def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings: + image_input = self._parse_and_validate_image_input(**kwargs) + if image_input is None: + return [] + return self._process_image_input(image_input) + + def embed_input_ids( + self, + input_ids: torch.Tensor, + multimodal_embeddings: MultiModalEmbeddings | None = None, + *, + is_multimodal: torch.Tensor | None = None, + ) -> torch.Tensor: + from vllm.model_executor.models.utils import _merge_multimodal_embeddings + + # Compressor-alignment pads borrow a reserved id; embed them as the + # plain image token (the checkpoint has no image_pad vector). + # Branch-free: safe inside compiled/captured regions. + input_ids = input_ids.masked_fill( + input_ids == IMAGE_PAD_ID, IMAGE_SENTINEL_BASE_ID + ) + inputs_embeds = self.language_model.embed_input_ids(input_ids) + + if multimodal_embeddings is None or len(multimodal_embeddings) == 0: + return inputs_embeds + + assert is_multimodal is not None + return _merge_multimodal_embeddings( + inputs_embeds=inputs_embeds, + multimodal_embeddings=multimodal_embeddings, + is_multimodal=is_multimodal, + ) + + @staticmethod + def get_model_state_cls(): + from ..nvidia.model_state import DeepseekV41ModelState + + return DeepseekV41ModelState + + @property + def token_lookback_depth(self) -> int: + return self.language_model.token_lookback_depth + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + intermediate_tensors=None, + inputs_embeds: torch.Tensor | None = None, + lookback_token_ids: torch.Tensor | None = None, + **kwargs, + ) -> torch.Tensor: + return self.language_model( + input_ids, + positions, + intermediate_tensors, + inputs_embeds, + lookback_token_ids=lookback_token_ids, + ) + + def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: + return self.language_model.compute_logits(hidden_states) + + def compute_logits_local(self, hidden_states: torch.Tensor) -> torch.Tensor: + return self.language_model.compute_logits_local(hidden_states) + + def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + return self.language_model.get_expert_mapping() + + def get_mtp_target_hidden_states(self) -> torch.Tensor | None: + """Pre-hc_head residual stream buffer for the MTP/DSpark draft model.""" + return self.language_model.get_mtp_target_hidden_states() + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + # Map HF names into this wrapper's namespace up front and sort, so + # the "language_model." group reaches the child loader as one + # contiguous block (AutoWeightsLoader delegates per contiguous group, + # and the child's load_weights finalizes fused expert weights, which + # must not run on a partially loaded model). + mapped = sorted(self.hf_to_vllm_mapper.apply(weights), key=lambda x: x[0]) + loader = AutoWeightsLoader(self) + loaded_params = loader.load_weights(mapped) + # The child's load_weights already ran its post-load finalization. + self._weights_finalized = True + return loaded_params + + def process_weights_after_loading(self) -> None: + # Model-level post-load hook (called by the loader after any load + # format). Under DummyModelLoader the child's load_weights — and + # hence its finalize step — is bypassed, so run it here instead. + if getattr(self, "_weights_finalized", False): + return + self.language_model.process_weights_after_loading() diff --git a/vllm/models/deepseek_v4_1/attention.py b/vllm/models/deepseek_v4_1/attention.py new file mode 100644 index 0000000000..77e98a376e --- /dev/null +++ b/vllm/models/deepseek_v4_1/attention.py @@ -0,0 +1,1225 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +DeepseekV4 MLA Attention Layer +""" + +from abc import ABC, abstractmethod +from collections.abc import Callable +from functools import cached_property +from typing import TYPE_CHECKING, Any, ClassVar, cast + +import regex as re +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import DeepseekV2Config, DeepseekV3Config + +import vllm.envs as envs +from vllm.compilation.breakable_cudagraph import eager_break_during_capture +from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation +from vllm.model_executor.layers.linear import ( + ColumnParallelLinear, + MergedColumnParallelLinear, + ReplicatedLinear, + RowParallelLinear, +) +from vllm.model_executor.layers.sparse_attn_indexer import SparseAttnIndexer +from vllm.models.common.ops import fused_q_kv_rmsnorm +from vllm.models.deepseek_v4_1.common.ops import ( + MXFP4_BLOCK_SIZE, + fused_indexer_q_rope_quant, + indexer_k_norm_rope_store, +) + +if TYPE_CHECKING: + from vllm.v1.attention.backends.mla.sparse_swa import ( + DeepseekSparseSWAMetadata, + ) + +from vllm.config import ( + CacheConfig, + VllmConfig, + get_current_vllm_config, +) +from vllm.distributed import get_tensor_model_parallel_world_size +from vllm.forward_context import get_forward_context +from vllm.logger import init_logger +from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.quantization import QuantizationConfig +from vllm.model_executor.models.utils import extract_layer_index +from vllm.models.deepseek_v4_1.common.rope import build_deepseek_v4_rope +from vllm.models.deepseek_v4_1.compressor import DeepseekCompressor +from vllm.triton_utils import tl, triton +from vllm.utils.multi_stream_utils import ( + execute_in_parallel, + maybe_execute_in_parallel, +) +from vllm.v1.attention.backend import AttentionBackend, AttentionMetadata +from vllm.v1.attention.backends.mla.indexer import ( + DeepseekV4IndexerBackend, + dsa_indexer_uses_fp4, + get_max_prefill_buffer_size, +) +from vllm.v1.attention.backends.mla.sparse_swa import DeepseekV4SWACache +from vllm.v1.kv_cache_interface import ( + KVCacheSpec, + MLAAttentionSpec, + get_kv_quant_mode, +) + +logger = init_logger(__name__) + + +def _replace_layer_index(prefix: str, layer_id: int) -> str: + """Swap the layer index inside a ``...layers....`` prefix.""" + new_prefix, n = re.subn(r"\.layers\.\d+\.", f".layers.{layer_id}.", prefix) + assert n == 1, f"Cannot locate layer index in prefix {prefix}" + return new_prefix + + +def _indexer_k_cache_head_dim(index_head_dim: int, use_fp4_kv: bool) -> int: + """Per-token byte width of the paged indexer K cache row.""" + if use_fp4_kv: + # MXFP4 stores two values per byte plus one UE8M0 byte per 32 values. + # head_dim bytes = 64 packed values + 4 UE8M0 scales = 68. + return index_head_dim // 2 + index_head_dim // MXFP4_BLOCK_SIZE + # NOTE(yifan): FP8 indexer cache uses the same layout as V3.2: + # head_dim bytes = 128 fp8 + 4 fp32 scale = 132. + return index_head_dim + index_head_dim // 128 * 4 + + +@triton.jit +def _fill_short_context_topk_indices( + output, + positions, + TOP_K: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + PADDED_TOP_K: tl.constexpr, +): + # small triton kernel that selects every candidate, -1 otherwise + row = tl.program_id(0) + offsets = tl.arange(0, PADDED_TOP_K) + num_compressed = (tl.load(positions + row) + 1) // COMPRESS_RATIO + tl.store( + output + row * TOP_K + offsets, + tl.where(offsets < num_compressed, offsets, -1), + mask=offsets < TOP_K, + ) + + +def _resolve_dsv4_kv_cache_dtype( + use_fp8_ds_mla_layout: bool, + kv_cache_dtype: str, + cache_config: CacheConfig | None, +) -> tuple[str, torch.dtype]: + """Map ``(layout, --kv-cache-dtype)`` to ``(cache_dtype_str, torch_dtype)``. + + Both layouts are paged; they differ in the per-token block format. The + ``fp8_ds_mla`` format is UE8M0 block-scaled fp8 packed as ``uint8`` (the + canonical ``fp8_ds_mla`` string is written back onto ``cache_config`` so the + page-size specs pick the 576B per-token slot). Plain-row backends store each + token's KV row in its element dtype: bf16 or per-tensor FP8 E4M3. + """ + if use_fp8_ds_mla_layout: + # fp8_ds_mla block format: UE8M0 block-scaled fp8 packed as uint8. + if kv_cache_dtype == "auto": + kv_cache_dtype = "fp8" + if not kv_cache_dtype.startswith("fp8"): + raise ValueError( + "DeepseekV4 fp8_ds_mla layout only supports fp8 " + f"kv-cache, got {kv_cache_dtype}. Please set " + "`--kv-cache-dtype fp8` or select a backend that supports " + "bfloat16 KV cache." + ) + if kv_cache_dtype != "fp8_ds_mla": + if cache_config is not None: + cache_config.cache_dtype = "fp8_ds_mla" + kv_cache_dtype = "fp8_ds_mla" + logger.info_once("Using DeepSeek's fp8_ds_mla KV cache format.") + return kv_cache_dtype, torch.uint8 + + # Plain bf16 / per-tensor fp8 KV row (FlashInfer). + if kv_cache_dtype.startswith("fp8"): + return kv_cache_dtype, torch.float8_e4m3fn + # auto / bfloat16 -> plain bf16 KV row. + return kv_cache_dtype, torch.bfloat16 + + +class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC): + """DeepseekV4 MLA attention layer. + + The platform-specific sparse-MLA forward (``forward_mqa`` / + ``get_padded_num_q_heads`` / ``_o_proj`` / ``backend_cls``) is provided by a + subclass — ``DeepseekV4FlashMLAAttention`` / + ``DeepseekV4FlashInferSM120Attention`` / + ``DeepseekV4FlashInferMLAAttention`` (CUDA) or + ``DeepseekV41ROCMAiterMLAAttention`` (ROCm) — selected by the platform-specific + deepseek_v4_1 model module. The base is never instantiated directly. + """ + + # Provided by the platform subclass. + backend_cls: ClassVar[type[AttentionBackend]] + # Backend for the SWA cache layer; None uses the default SWA backend. + swa_backend_cls: ClassVar[type[AttentionBackend] | None] = None + # KV-cache per-token block format (both layouts are paged). True (default) + # = fp8_ds_mla (UE8M0 block-scaled fp8 packed as uint8); False = plain + # bf16 / per-tensor fp8 KV row. Backends can override the instance hook when + # a single attention class dispatches across arch-specific layouts. + use_fp8_ds_mla_layout: ClassVar[bool] = True + # Prefill is processed in fixed-size chunks; this bounds the bf16 kv-gather + # workspace allocated in _forward_prefill and is also read by the dummy-run + # path to pre-reserve that workspace. + PREFILL_CHUNK_SIZE: ClassVar[int] = 4 + + @classmethod + @abstractmethod + def get_padded_num_q_heads(cls, num_heads: int) -> int: + """Q head count the q/output buffers are allocated at. + + The layer allocates the q/output buffers at + ``[N, get_padded_num_q_heads(n_local_heads), head_dim]``. Must satisfy + ``result >= num_heads``. Backends with no padding constraint return + ``num_heads``. + """ + raise NotImplementedError + + @abstractmethod + def forward_mqa( + self, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + output: torch.Tensor, + ) -> None: + """Platform-specific sparse MLA forward; writes attention into ``output``.""" + raise NotImplementedError + + @abstractmethod + def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + """Inverse-RoPE + wo_a + wo_b output projection (platform-specific).""" + raise NotImplementedError + + def _uses_fp8_ds_mla_layout(self) -> bool: + """Return whether this instance stores fp8 KV in fp8_ds_mla layout.""" + return self.use_fp8_ds_mla_layout + + def __init__( + self, + vllm_config: VllmConfig, + prefix: str, + topk_indices_buffer: torch.Tensor | None = None, + aux_stream_list: list[torch.cuda.Stream] | None = None, + candidate_block_buffer: torch.Tensor | None = None, + ) -> None: + super().__init__() + config = vllm_config.model_config.hf_config + quant_config = vllm_config.quant_config + cache_config = vllm_config.cache_config + tp_size = get_tensor_model_parallel_world_size() + layer_id = extract_layer_index(prefix) + self.layer_id = layer_id + + self.prefix = prefix # Alias for compatibility with compressor + self.hidden_size = config.hidden_size + self.n_heads = config.num_attention_heads + assert self.n_heads % tp_size == 0 + self.n_local_heads = self.n_heads // tp_size + self.q_lora_rank = config.q_lora_rank + self.o_lora_rank = config.o_lora_rank + self.head_dim = config.head_dim + self.rope_head_dim = config.qk_rope_head_dim + self.nope_head_dim = self.head_dim - self.rope_head_dim + self.n_groups = config.o_groups + self.n_local_groups = self.n_groups // tp_size + self.window_size = config.sliding_window + # Vision variant: image spans are visible bidirectionally, widening + # prefill SWA index rows by up to max_image_tokens columns. + self.max_image_tokens = ( + getattr(config, "vision_max_n_token", 0) + if getattr(config, "vision_n_layers", 0) > 0 + else 0 + ) + # ---- v4.1 sparse-attention topology ---- + # compress_ratios has one entry per layer (MTP layers included): + # 0 = pure sliding window, 1 = full-length compressed cache, + # 2 = ratio-2 compressed. Compressors and compressed-KV caches live + # only on ``kv_source_layer_ids``; indexers only on + # ``index_source_layer_ids``. Consumers reuse the most recently + # published source below them. + compress_ratios = getattr(config, "compress_ratios", None) + if compress_ratios is not None and layer_id < len(compress_ratios): + self.compress_ratio = int(compress_ratios[layer_id]) + else: + # MTP layers past the configured list are pure sliding-window. + self.compress_ratio = 0 + if self.compress_ratio not in (0, 1, 2): + raise ValueError( + f"DeepSeek V4.1 layer {layer_id} has compress_ratio=" + f"{self.compress_ratio}; only 0 (sliding window), 1 and 2 are " + "supported." + ) + self.kv_source_layers = tuple( + getattr(config, "kv_source_layer_ids", None) or () + ) + self.index_source_layers = tuple( + getattr(config, "index_source_layer_ids", None) or () + ) + self.candidate_source_layer = getattr(config, "candidate_source_layer_id", -1) + self.candidate_topk_blocks = getattr(config, "candidate_topk_blocks", 0) + self.candidate_block_size = getattr(config, "candidate_block_size", 0) + + is_backbone = layer_id < config.num_hidden_layers + self.is_kv_source = is_backbone and layer_id in self.kv_source_layers + self.is_index_source = is_backbone and layer_id in self.index_source_layers + if self.compress_ratio > 0: + if not self.kv_source_layers or not self.index_source_layers: + raise ValueError( + "DeepSeek V4.1 requires kv_source_layer_ids / " + "index_source_layer_ids in the config for compressed " + f"layers (layer {layer_id} has " + f"compress_ratio={self.compress_ratio})." + ) + self.kv_source_layer_id = max( + s for s in self.kv_source_layers if s <= layer_id + ) + self.index_source_layer_id = max( + s for s in self.index_source_layers if s <= layer_id + ) + else: + self.kv_source_layer_id = None + self.index_source_layer_id = None + self.eps = config.rms_norm_eps + self.scale = self.head_dim**-0.5 + + # Padded Q head count is dictated by the platform subclass. + self.padded_heads = self.get_padded_num_q_heads(self.n_local_heads) + # Sink padded to the same head count, initialized to -inf (no sink + # effect). Weight loading fills the first n_local_heads slots. + self.attn_sink = nn.Parameter( + torch.full((self.padded_heads,), -float("inf"), dtype=torch.float32), + requires_grad=False, + ) + + self.fused_wqa_wkv = MergedColumnParallelLinear( + self.hidden_size, + [self.q_lora_rank, self.head_dim], + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.fused_wqa_wkv", + disable_tp=True, # fused ReplicatedLinear + ) + self.q_norm = RMSNorm(self.q_lora_rank, self.eps) + self.wq_b = ColumnParallelLinear( + self.q_lora_rank, + self.n_heads * self.head_dim, + bias=False, + quant_config=quant_config, + return_bias=False, + prefix=f"{prefix}.wq_b", + ) + + self.kv_norm = RMSNorm(self.head_dim, self.eps) + self.wo_a = ColumnParallelLinear( + self.n_heads * self.head_dim // self.n_groups, + self.n_groups * self.o_lora_rank, + bias=False, + quant_config=quant_config, + return_bias=False, + prefix=f"{prefix}.wo_a", + ) + self.wo_a.is_bmm = True + self.wo_a.bmm_batch_size = self.n_local_groups + self._o_proj_block_size = ( + 32 if getattr(self.wo_a, "weight_block_size", None) == [1, 32] else 128 + ) + self.wo_b = RowParallelLinear( + self.n_groups * self.o_lora_rank, + self.hidden_size, + bias=False, + quant_config=quant_config, + return_bias=False, + prefix=f"{prefix}.wo_b", + ) + + # Initialize rotary embedding before the indexer/compressor consume it. + self.rotary_emb = build_deepseek_v4_rope( + config, + head_dim=self.head_dim, + rope_head_dim=self.rope_head_dim, + max_position_embeddings=config.max_position_embeddings, + compress_ratio=self.compress_ratio, + ) + self.indexer_rotary_emb = self.rotary_emb + self.topk_indices_buffer = topk_indices_buffer + self.candidate_block_buffer = candidate_block_buffer + + # Register with compilation context for metadata lookup. Done before + # indexer/compressor creation so consumers can resolve their source + # layers through it. + compilation_config = vllm_config.compilation_config + if prefix and prefix in compilation_config.static_forward_context: + raise ValueError(f"Duplicate layer name: {prefix}") + if prefix: + compilation_config.static_forward_context[prefix] = self + self.kv_cache = torch.tensor([]) + self._static_forward_context = compilation_config.static_forward_context + + self.indexer = None + if self.is_index_source: + index_k_cache: DeepseekV4IndexerCache | None + # Index K cache: owned only by kv-source layers (their indexer has + # wk/k_norm); non-owning index sources share the K cache of the + # latest kv source below them (its indexer produces the keys). + if self.is_kv_source: + index_k_cache = DeepseekV4IndexerCache( + head_dim=_indexer_k_cache_head_dim( + config.index_head_dim, dsa_indexer_uses_fp4(vllm_config) + ), + dtype=torch.uint8, + prefix=f"{prefix}.indexer.k_cache", + cache_config=cache_config, + compress_ratio=self.compress_ratio, + ) + else: + assert self.kv_source_layer_id is not None + k_cache_prefix = ( + f"{_replace_layer_index(prefix, self.kv_source_layer_id)}" + ".indexer.k_cache" + ) + index_k_cache = self._static_forward_context.get(k_cache_prefix) + if index_k_cache is None: + raise NotImplementedError( + f"Indexer K cache source {k_cache_prefix} not found on " + "this rank; PP splits inside a v4.1 kv-sharing group " + "are not supported." + ) + is_candidate_source = layer_id == self.candidate_source_layer + uses_candidates = 0 <= self.candidate_source_layer < layer_id + self.indexer = DeepseekV4Indexer( + vllm_config, + config=config, + hidden_size=self.hidden_size, + q_lora_rank=self.q_lora_rank, + quant_config=quant_config, + cache_config=cache_config, + topk_indices_buffer=topk_indices_buffer, + compress_ratio=self.compress_ratio, + prefix=f"{prefix}.indexer", + owns_k=self.is_kv_source, + k_cache=index_k_cache, + main_head_dim=self.head_dim, + candidate_block_buffer=( + candidate_block_buffer + if (is_candidate_source or uses_candidates) + else None + ), + candidate_block_size=self.candidate_block_size, + candidate_write=is_candidate_source, + ) + + self._prepare_and_attn_fn = self._prepare_and_attn + if not vllm_config.use_v2_model_runner: + # MRV1's piecewise capture only tolerates the wide eager region: with + # the narrow one the attention input preparation stays in the captured + # graph and MRV1 produces garbage (#51430). + self._prepare_and_attn_fn = self._prepare_and_attn_eager + + # Will be None on ROCm for now. + self.aux_stream_list = aux_stream_list + # [0]: GEMM start / post-GEMM event0. [1..3]: GEMM done events; + # [1] doubles as post-GEMM event1. Reuse is safe: GEMM fully joins + # before post-GEMM starts. + self.ln_events = [torch.cuda.Event() for _ in range(4)] + + assert cache_config is not None, "DeepseekV4 attention requires cache_config" + # ---- Attention / KV-cache setup ---- + self.max_num_batched_tokens = ( + vllm_config.scheduler_config.max_num_batched_tokens + ) + self.max_model_len = vllm_config.model_config.max_model_len + + # Resolve the kv-cache dtype from this backend's block format. The same + # resolution drives the SWA cache tensor dtype below. + self.kv_cache_dtype, self.kv_cache_torch_dtype = _resolve_dsv4_kv_cache_dtype( + self._uses_fp8_ds_mla_layout(), cache_config.cache_dtype, cache_config + ) + + self.swa_cache_layer = DeepseekV4SWACache( + head_dim=self.head_dim, + window_size=self.window_size, + dtype=self.kv_cache_torch_dtype, + prefix=f"{prefix}.swa_cache", + cache_config=cache_config, + backend_cls=self.swa_backend_cls, + block_size=32, + ) + + # The attention layer itself was already registered with the + # compilation context above (before indexer/compressor creation). + + # Compressors live only on kv-source layers; consumers read the + # source's compressed cache through the forward context. + self.compressor = None + if self.is_kv_source: + self.compressor = DeepseekCompressor( + vllm_config=vllm_config, + compress_ratio=self.compress_ratio, + hidden_size=self.hidden_size, + head_dim=self.head_dim, + rotate=True, + prefix=f"{prefix}.compressor", + k_cache_prefix=self.prefix, + ) + # Prefix of the attention layer owning this layer's compressed KV + # cache (self for kv sources). + if self.compress_ratio > 0: + assert self.kv_source_layer_id is not None + self.compressed_cache_prefix: str | None = _replace_layer_index( + prefix, self.kv_source_layer_id + ) + if ( + not self.is_kv_source + and self.compressed_cache_prefix not in self._static_forward_context + ): + raise NotImplementedError( + f"Compressed-KV source {self.compressed_cache_prefix} not " + "found on this rank; PP splits inside a v4.1 kv-sharing " + "group are not supported." + ) + else: + self.compressed_cache_prefix = None + + if vllm_config.kernel_config.enable_jit_warmup: + from vllm.v1.attention.backends.mla.sparse_swa import ( + _COMPUTE_PREFILL_METADATA_KERNEL, + _COMPUTE_SWA_INDICES_AND_LENS_KERNEL, + ) + + _COMPUTE_PREFILL_METADATA_KERNEL.register_warmup() + _COMPUTE_SWA_INDICES_AND_LENS_KERNEL.register_warmup( + window_size=self.window_size, + block_size=self.swa_cache_layer.block_size, + max_image_tokens=self.max_image_tokens, + ) + + if self.compress_ratio > 1: + from vllm.v1.attention.backends.mla.compressor_utils import ( + _COMPRESSED_SLOT_MAPPING_KERNEL, + ) + + _COMPRESSED_SLOT_MAPPING_KERNEL.register_warmup() + + if self.indexer is not None: + from vllm.v1.attention.backends.mla.indexer import ( + _BUILD_PREFILL_CHUNK_METADATA_KERNEL, + _PREPARE_UNIFORM_DECODE_KERNEL, + ) + + _PREPARE_UNIFORM_DECODE_KERNEL.register_warmup() + _BUILD_PREFILL_CHUNK_METADATA_KERNEL.register_warmup() + + spec_config = vllm_config.speculative_config + if spec_config is not None and spec_config.use_dspark(): + from vllm.v1.attention.backends.mla.sparse_swa import ( + _COMPUTE_DSPARK_NONCAUSAL_SWA_INDICES_KERNEL, + ) + + _COMPUTE_DSPARK_NONCAUSAL_SWA_INDICES_KERNEL.register_warmup( + window_size=self.window_size, + num_speculative_tokens=spec_config.num_speculative_tokens, + block_size=self.swa_cache_layer.block_size, + ) + + if self.backend_cls.get_name() in ( + "FLASHMLA_SPARSE_DSV41", + "ROCM_FLASHMLA_SPARSE_DSV4", + ): + from vllm.models.deepseek_v4_1.common.ops.cache_utils import ( + _COMBINE_TOPK_SWA_INDICES_KERNEL, + ) + + _COMBINE_TOPK_SWA_INDICES_KERNEL.register_warmup() + + def forward( + self, + positions: torch.Tensor, + hidden_states: torch.Tensor, + llama_4_scaling: torch.Tensor | None = None, + ) -> torch.Tensor: + # Pre-allocate attention output with FlashMLA-padded head count. + # The op writes into `o_padded`; we slice to n_local_heads after. + num_tokens = hidden_states.shape[0] + o_padded = torch.empty( + (num_tokens, self.padded_heads, self.head_dim), + dtype=hidden_states.dtype, + device=hidden_states.device, + ) + + # Keep the attention input preparation in the captured graph. Only the + # sparse indexer and MLA attention run in the eager break below. + qr_kv, kv_score, indexer_weights = self._run_parallel_input_projections( + hidden_states + ) + qr, qr_scale, kv = self._split_qkv_and_norm(qr_kv) + + self._prepare_and_attn_fn( + hidden_states, + qr, + kv, + qr_scale, + kv_score, + indexer_weights, + positions, + o_padded, + ) + o = o_padded[:, : self.n_local_heads, :] + + # Inverse-RoPE + wo_a + wo_b output projection (platform-specific). + return self._o_proj(o, positions) + + @cached_property + def _can_fuse_query_quant(self) -> bool: + from vllm.models.deepseek_v4_1.common.ops.query_quant import ( + can_fuse_query_quant, + ) + + linears = [self.wq_b] + if self.indexer is not None: + linears.append(self.indexer.wq_b) + return can_fuse_query_quant(linears) + + def _split_qkv_and_norm( + self, qr_kv: torch.Tensor + ) -> tuple[torch.Tensor | QuantizedActivation, torch.Tensor | None, torch.Tensor]: + """Split the fused q-lora / kv projection and RMSNorm both halves. + + Compatible MXFP8 projections share the quantized Q and scales; + other projection backends consume the normalized Q directly. + """ + qr, kv = qr_kv.split([self.q_lora_rank, self.head_dim], dim=-1) + if self.q_lora_rank % 32 == 0 and self._can_fuse_query_quant: + from vllm.models.deepseek_v4_1.common.ops.query_quant import ( + fused_q_kv_rmsnorm_quant, + ) + + qr_quant, kv = fused_q_kv_rmsnorm_quant( + qr, + kv, + self.q_norm.weight.data, + self.kv_norm.weight.data, + self.eps, + ) + return qr_quant, None, kv + qr, kv = fused_q_kv_rmsnorm( + qr, + kv, + self.q_norm.weight.data, + self.kv_norm.weight.data, + self.eps, + ) + return qr, None, kv + + @eager_break_during_capture + def _prepare_and_attn_eager( + self, + hidden_states: torch.Tensor, + qr: torch.Tensor | QuantizedActivation, + kv: torch.Tensor, + qr_scale: torch.Tensor | None, + kv_score: torch.Tensor, + indexer_weights: torch.Tensor, + positions: torch.Tensor, + o_padded: torch.Tensor, + ) -> None: + """Wide eager region: the whole of ``_prepare_and_attn`` runs eagerly. + + The nested ``_sparse_indexer_and_attn`` break runs inline, since + ``add_eager`` clears ``_capturing`` before invoking this. + """ + self._prepare_and_attn( + hidden_states, + qr, + kv, + qr_scale, + kv_score, + indexer_weights, + positions, + o_padded, + ) + + def _prepare_and_attn( + self, + hidden_states: torch.Tensor, + qr: torch.Tensor | QuantizedActivation, + kv: torch.Tensor, + qr_scale: torch.Tensor | None, + kv_score: torch.Tensor, + indexer_weights: torch.Tensor, + positions: torch.Tensor, + o_padded: torch.Tensor, + ) -> None: + """Attention input preparation followed by the sparse indexer and MLA. + + Only the latter runs in the eager break. + + Q/SWA preparation overlaps state saving and compression. Once the + latent is ready, main-cache insertion overlaps indexer preparation; + both cache writes finish before sparse attention reads either cache. + """ + attn_metadata = get_forward_context().attn_metadata + indexer = self.indexer + compressor = self.compressor + aux_streams = self.aux_stream_list + + def project_query_and_cache_kv() -> torch.Tensor: + q = self._wq_b_proj(qr, qr_scale).view( + -1, self.n_local_heads, self.head_dim + ) + return self._fused_qnorm_rope_kv_insert(q, kv, positions, attn_metadata) + + index_q: torch.Tensor | None = None + index_q_scale: torch.Tensor | None = None + index_weights_out: torch.Tensor | None = None + latent: torch.Tensor | None = None + aux_stream = aux_streams[0] if aux_streams is not None else None + + if compressor is not None: + # Q projection / KV insertion on the default stream overlaps the + # compressor on aux stream 0 (sequential on ROCm). + q, latent = maybe_execute_in_parallel( + project_query_and_cache_kv, + lambda: compressor(kv_score, positions), + self.ln_events[0], + self.ln_events[1], + aux_stream, + ) + else: + q = project_query_and_cache_kv() + + def prepare_indexer(): + if indexer is None: + return None, None, None + return indexer( + qr, + latent, + indexer_weights, + positions, + self.indexer_rotary_emb, + qr_scale, + ) + + if compressor is not None: + indexer_result, _ = maybe_execute_in_parallel( + prepare_indexer, + lambda: compressor.insert_cache(latent, positions, self.rotary_emb), + self.ln_events[0], + self.ln_events[1], + aux_stream, + ) + else: + indexer_result = prepare_indexer() + index_q, index_q_scale, index_weights_out = indexer_result + + self._sparse_indexer_and_attn( + hidden_states, + index_q, + index_q_scale, + index_weights_out, + q, + kv, + positions, + o_padded, + ) + + def _fused_wqa_wkv_gemm(self, hidden_states: torch.Tensor) -> torch.Tensor: + # Override point: the ROCm layer preshuffles this weight in place, so + # it cannot go through fused_wqa_wkv directly. + # MergedColumnParallelLinear returns (output, bias); bias is None. + qr_kv, _ = self.fused_wqa_wkv(hidden_states) + return qr_kv + + def _wq_b_proj( + self, + qr: torch.Tensor | QuantizedActivation, + qr_scale: torch.Tensor | None = None, + ) -> torch.Tensor: + """Project normalized Q, bypassing quantization when already fused.""" + assert qr_scale is None, "ROCm-only path" + return self.wq_b(qr) + + def _run_parallel_input_projections( + self, hidden_states: torch.Tensor + ) -> tuple[ + torch.Tensor, + torch.Tensor | None, + torch.Tensor | None, + ]: + aux_streams = self.aux_stream_list + if aux_streams is not None: + aux_streams = aux_streams[:2] + + # fused_wqa_wkv (heaviest) on default; the two lighter input GEMMs on + # aux streams 0/1 when their owning module exists. ln_events[0] is the + # fan-out start event; ln_events[1..2] are per-aux done events. The + # v4.1 indexer derives K from the kv-source compressor's latent, so + # unlike v4.0 there is no indexer K GEMM over hidden_states here. + aux_fns: list[Callable[[], Any] | None] = [None, None] + + if self.compressor is not None: + # Local ref so the closure keeps a non-None type for mypy. + compressor = self.compressor + + def compressor_kv_score() -> torch.Tensor: + return torch.mm( + hidden_states, + compressor.fused_wkv_wgate.weight.T, + out_dtype=torch.float32, + ) + + aux_fns[0] = compressor_kv_score + + if self.indexer is not None: + indexer = self.indexer + + def indexer_weights_proj() -> torch.Tensor: + # ReplicatedLinear returns (output, bias); bias is None. + weights, _ = indexer.weights_proj(hidden_states) + return weights + + aux_fns[1] = indexer_weights_proj + + qr_kv, (kv_score, indexer_weights) = execute_in_parallel( + lambda: self._fused_wqa_wkv_gemm(hidden_states), + aux_fns, + self.ln_events[0], + self.ln_events[1:3], + aux_streams, + enable=hidden_states.shape[0] + <= envs.VLLM_MULTI_STREAM_GEMM_TOKEN_THRESHOLD, + ) + + return qr_kv, kv_score, indexer_weights + + @eager_break_during_capture + def _sparse_indexer_and_attn( + self, + hidden_states: torch.Tensor, + index_q: torch.Tensor | None, + index_q_scale: torch.Tensor | None, + index_weights: torch.Tensor | None, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + out: torch.Tensor, + ) -> None: + if self.indexer is not None and index_q is not None: + assert index_weights is not None + q_quant = (index_q, index_q_scale) if index_q_scale is not None else index_q + self.indexer.indexer_op( + hidden_states, + q_quant, + None, + index_weights, + ) + + # MLA attention writes into the pre-allocated `out` buffer + # ([num_tokens, padded_heads, head_dim]). + self.forward_mqa(q, kv, positions, out) + + def _fused_qnorm_rope_kv_insert( + self, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + attn_metadata: ( + dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None + ), + ) -> torch.Tensor: + if not isinstance(attn_metadata, dict): + # Profile run: kernel doesn't fire; produce a padded tensor so + # downstream FlashMLA gets the right shape. + if self.n_local_heads < self.padded_heads: + return F.pad( + q, + (0, 0, 0, self.padded_heads - self.n_local_heads), + value=0.0, + ) + return q + + swa_metadata = cast( + "DeepseekSparseSWAMetadata | None", + attn_metadata.get(self.swa_cache_layer.prefix), + ) + assert swa_metadata is not None + + swa_kv_cache = self.swa_cache_layer.kv_cache + # The fused insert ops require int64 position_ids; the runner's positions + # buffer is already int64, so no cast is needed. + assert positions.dtype == torch.int64 + cos_sin_cache = self.rotary_emb.cos_sin_cache + cache_dtype = swa_kv_cache.dtype + + # kv is unchanged; attention reads kv solely via swa_kv_cache. + if cache_dtype == torch.uint8: + # fp8_ds_mla UE8M0 paged path. Horizontally fused: + # Q side: GPT-J RoPE, zero-filling the padding head slots; the + # kernel allocates and returns the padded q tensor. + # KV side: GPT-J RoPE + UE8M0 FP8 quant + paged cache insert. + swa_kv_cache_2d = swa_kv_cache.view(swa_kv_cache.shape[0], -1) + return torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert( + q, + kv, + swa_kv_cache_2d, + swa_metadata.slot_mapping, + positions, + cos_sin_cache, + self.padded_heads, + self.eps, + swa_metadata.block_size, + False, + ) + + # Plain-row path: the [num_blocks, block_size, 512] cache stores the KV + # row in its element dtype (no Q padding). bf16 rewrites q in place; + # per-tensor fp8 writes a separately-allocated fp8 q and quantizes the + # KV row. + block_size = swa_metadata.block_size + assert swa_kv_cache.shape[1:] == (block_size, self.head_dim) + swa_kv_cache_3d = swa_kv_cache + if cache_dtype == torch.bfloat16: + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert( + q, + kv, + swa_kv_cache_3d, + swa_metadata.slot_mapping, + positions, + cos_sin_cache, + self.eps, + block_size, + False, + ) + return q + + # per-tensor fp8 (torch.float8_e4m3fn) + q_fp8 = torch.empty_like(q, dtype=torch.float8_e4m3fn) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_fp8_insert( + q, + kv, + q_fp8, + swa_kv_cache_3d, + swa_metadata.slot_mapping, + positions, + cos_sin_cache, + self._flashinfer_fp8_kv_scale, + self._flashinfer_fp8_q_scale_inv, + self.eps, + block_size, + False, + ) + return q_fp8 + + def bind_kv_cache(self, kv_cache: torch.Tensor) -> None: + # [B, H=1, N, C] -> [B, N, C] + self.kv_cache = kv_cache.squeeze(1) + + def get_attn_backend(self) -> type[AttentionBackend]: + return self.backend_cls + + def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec | None: + # Only kv-source layers own a compressed-KV cache; consumers read the + # source's cache through the forward context, and cr==0 layers are + # pure SWA. The SWA cache is allocated separately as + # DeepseekV4SWACache. + if not self.is_kv_source: + return None + # fp8_ds_mla is a UE8M0 block-scaled uint8 layout and needs 576B + # alignment; plain bf16 / per-tensor fp8 rows use natural element-size + # pages. + uses_fp8_ds_mla_layout = self.kv_cache_dtype == "fp8_ds_mla" + return MLAAttentionSpec( + block_size=vllm_config.cache_config.block_size, + num_kv_heads=1, + head_size=self.head_dim, + dtype=torch.uint8 if uses_fp8_ds_mla_layout else self.kv_cache_torch_dtype, + tokens_per_state=self.compress_ratio, + cache_dtype_str=self.kv_cache_dtype, + alignment=576 if uses_fp8_ds_mla_layout else 512, + model_version="deepseek_v4", + kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype), + # DeepseekV4: 448B NoPE + 128B RoPE + 8B fp8 scale = 584B per token; + # head_size stays semantic (512). + state_content_bytes=584 if uses_fp8_ds_mla_layout else None, + ) + + def _compressed_kv_cache(self) -> torch.Tensor: + """The compressed-KV cache tensor of this layer's kv source (own + cache for kv-source layers).""" + if self.is_kv_source: + return self.kv_cache + assert self.compressed_cache_prefix is not None + source = self._static_forward_context[self.compressed_cache_prefix] + return source.kv_cache + + +class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase): + def __init__( + self, + head_dim: int, + dtype: torch.dtype, + prefix: str, + cache_config: CacheConfig, + compress_ratio: int = 1, + ): + super().__init__() + self.kv_cache = torch.tensor([]) + self.head_dim = head_dim + self.prefix = prefix + self.cache_config = cache_config + self.dtype = dtype + self.compress_ratio = compress_ratio + compilation_config = get_current_vllm_config().compilation_config + if prefix in compilation_config.static_forward_context: + raise ValueError(f"Duplicate layer name: {prefix}") + compilation_config.static_forward_context[prefix] = self + + def bind_kv_cache(self, kv_cache: torch.Tensor) -> None: + # [B, H=1, N, C] -> [B, N, C] + self.kv_cache = kv_cache.squeeze(1) + + def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: + # head_dim already carries the fp8 scale padding + # tokens_per_state=1 for V3.2, >1 for DeepseekV4; same cache layout. + uses_fp8_ds_mla_layout = vllm_config.cache_config.cache_dtype == "fp8_ds_mla" + return MLAAttentionSpec( + block_size=self.cache_config.block_size, + num_kv_heads=1, + head_size=self.head_dim, + dtype=self.dtype, + tokens_per_state=self.compress_ratio, + # 576B for FlashMLA packing; 512B for FlashInfer sparse (#44577). + alignment=576 if uses_fp8_ds_mla_layout else 512, + ) + + def forward(self): ... + + def get_attn_backend(self) -> type[AttentionBackend]: + return DeepseekV4IndexerBackend + + +class DeepseekV4Indexer(nn.Module): + """DeepSeek V4.1 sparse-attention indexer. + + Exists only on ``index_source_layer_ids``; consumers reuse the topk + indices it publishes into the shared ``topk_indices_buffer``. Unlike v4.0 + the index key is derived from the kv-source layer's compressor latent + (``k = k_norm(wk(latent))``, ``owns_k``) instead of an indexer-local + compressor over hidden states, so there is no hidden-state K GEMM here. + Non-owning index sources share the kv source's paged K cache. + + Two-level candidate filtering: the indexer at ``candidate_source_layer_id`` + additionally publishes the top ``candidate_topk_blocks`` blocks of + ``candidate_block_size`` compressed positions (``candidate_write``); + later indexers mask their scores to those blocks before their own top-k. + """ + + def __init__( + self, + vllm_config: VllmConfig, + config: DeepseekV2Config | DeepseekV3Config, + hidden_size: int, + q_lora_rank: int, + quant_config: QuantizationConfig | None, + cache_config: CacheConfig | None, + topk_indices_buffer: torch.Tensor | None, + compress_ratio: int, + prefix: str, + *, + owns_k: bool, + k_cache: DeepseekV4IndexerCache, + main_head_dim: int, + candidate_block_buffer: torch.Tensor | None = None, + candidate_block_size: int = 0, + candidate_write: bool = False, + ): + super().__init__() + self.vllm_config = vllm_config + self.config = config + self.quant_config = quant_config + self.topk_tokens = config.index_topk + self.n_head = config.index_n_heads # 32 + self.head_dim = config.index_head_dim # 128 + self.rope_dim = config.qk_rope_head_dim # 64 + self.q_lora_rank = q_lora_rank # 1280 + self.compress_ratio = compress_ratio + self.owns_k = owns_k + self.use_fp4_kv = dsa_indexer_uses_fp4(vllm_config) + logger.info_once( + "Using %s indexer cache for Lightning Indexer.", + "MXFP4" if self.use_fp4_kv else "FP8", + ) + + # no tensor parallel, just replicated + self.wq_b = ReplicatedLinear( + self.q_lora_rank, + self.head_dim * self.n_head, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.wq_b", + ) + self.weights_proj = ReplicatedLinear( + hidden_size, + self.n_head, + bias=False, + quant_config=None, + prefix=f"{prefix}.weights_proj", + ) + self.softmax_scale = self.head_dim**-0.5 + + self.scale_fmt = "ue8m0" + self.quant_block_size = 128 # TODO: get from config + self.topk_indices_buffer = topk_indices_buffer + + self.max_model_len = ( + vllm_config.model_config.max_model_len // self.compress_ratio + ) + self.prefix = prefix + + self.max_total_seq_len = ( + get_max_prefill_buffer_size(vllm_config) // self.compress_ratio + ) + + assert cache_config is not None, "Deepseek V4 indexer requires cache_config" + if owns_k: + # wk maps the main compressor's (pre-RoPE) latent to index keys. + # The checkpoint stores it in bf16 with no quantization scales. + self.wk = ReplicatedLinear( + main_head_dim, + self.head_dim, + bias=False, + quant_config=None, + prefix=f"{prefix}.wk", + ) + self.k_norm = RMSNorm(self.head_dim, config.rms_norm_eps) + self.k_cache = k_cache + + self.indexer_op = SparseAttnIndexer( + self.k_cache, + self.quant_block_size, + self.scale_fmt, + self.topk_tokens, + self.head_dim, + self.max_model_len, + self.max_total_seq_len, + self.topk_indices_buffer, + skip_k_cache_insert=True, + use_fp4_cache=self.use_fp4_kv, + compress_ratio=self.compress_ratio, + candidate_blocks=candidate_block_buffer, + candidate_block_size=candidate_block_size, + candidate_write=candidate_write, + ) + + def _produce_k( + self, + latent: torch.Tensor | None, + positions: torch.Tensor, + rotary_emb: nn.Module, + ) -> None: + """Turn the compressor's pre-RoPE latent into paged index keys. + + ``k_norm(wk(latent))`` at group-boundary tokens, RoPE'd at the group + position and MXFP4/FP8-quantized into the indexer K cache. + """ + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict) or latent is None: + # Profile run: the indexer K cache is not bound yet and the + # compressor skipped its latent output. + return + assert self.owns_k + indexer_metadata = cast(Any, attn_metadata[self.k_cache.prefix]) + # ReplicatedLinear returns (output, bias); bias is None. Rows at + # non-boundary tokens hold garbage latent and are skipped by the + # store kernel. + k_pre, _ = self.wk(latent) + indexer_k_norm_rope_store( + k_pre, + positions, + rotary_emb.cos_sin_cache, + self.k_norm.weight, + self.k_norm.variance_epsilon, + self.k_cache.kv_cache, + indexer_metadata.slot_mapping, + self.compress_ratio, + self.use_fp4_kv, + ) + + def forward( + self, + qr: torch.Tensor | QuantizedActivation, + latent: torch.Tensor | None, + indexer_weights: torch.Tensor, + positions: torch.Tensor, + rotary_emb: nn.Module, + qr_scale: torch.Tensor | None = None, + ) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]: + attn_metadata = get_forward_context().attn_metadata + if isinstance(attn_metadata, dict): + indexer_metadata = cast(Any, attn_metadata[self.k_cache.prefix]) + if ( + indexer_metadata.max_seq_len // self.compress_ratio <= self.topk_tokens + and not torch.cuda.is_current_stream_capturing() + ): + # candidates num smaller than topk, every candidate is selected + # but we still need to build k cache + if self.owns_k: + self._produce_k(latent, positions, rotary_emb) + assert self.topk_indices_buffer is not None + num_tokens = ( + indexer_metadata.num_decode_tokens + + indexer_metadata.num_prefill_tokens + ) + if num_tokens > 0: + _fill_short_context_topk_indices[(num_tokens,)]( + self.topk_indices_buffer, + positions, + TOP_K=self.topk_tokens, + COMPRESS_RATIO=self.compress_ratio, + PADDED_TOP_K=triton.next_power_of_2(self.topk_tokens), + num_warps=8, + ) + return None, None, None + + if self.owns_k: + # K write must land before indexer_op reads the cache + # (skip_k_cache_insert=True). + self._produce_k(latent, positions, rotary_emb) + + q = self._wq_b_proj(qr, qr_scale) + q = q.view(-1, self.n_head, self.head_dim) + q_quant, weights = fused_indexer_q_rope_quant( + positions, + q, + rotary_emb.cos_sin_cache, + indexer_weights, + self.softmax_scale, + self.n_head**-0.5, + use_fp4=self.use_fp4_kv, + ) + if isinstance(q_quant, tuple): + q, q_scale = q_quant + else: + q, q_scale = q_quant, None + return q, q_scale, weights + + def _wq_b_proj( + self, + qr: torch.Tensor | QuantizedActivation, + qr_scale: torch.Tensor | None = None, + ) -> torch.Tensor: + """Project normalized Q with the main attention's shared quantization.""" + assert qr_scale is None, "ROCm-only path" + # ReplicatedLinear returns (output, bias); bias is None. + q, _ = self.wq_b(qr) + return q diff --git a/vllm/models/deepseek_v4_1/common/__init__.py b/vllm/models/deepseek_v4_1/common/__init__.py new file mode 100644 index 0000000000..208f01a7cb --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/deepseek_v4_1/common/engram.py b/vllm/models/deepseek_v4_1/common/engram.py new file mode 100644 index 0000000000..f30c3a5606 --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/engram.py @@ -0,0 +1,1033 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Engram: n-gram hash lookups gated into the hyper-connection stream. + +Port of the reference ``inference/engram.py`` + ``Engram`` / +``ParallelEngramEmbedding`` from ``inference/model.py`` (DeepSeek V4.1 +checkpoint layout). Engram modules live on the backbone layers listed in +``engram_layer_ids`` only. + +Two pieces of cross-forward state are needed because vLLM streams tokens +chunk-by-chunk while an n-gram at position ``p`` needs the token ids at +``p-1..p-3``: + +- ``token_map``: token id -> compressed vocab id, built once from the + model's tokenizer at init (deterministic; asserted against + ``engram_compressed_vocab_size``). +- ``hash_cache``: one int32 slot per KV slot of the first local layer's + sliding-window cache, holding the compressed id (or DEAD) of the token + last written to that slot. Slots are stable per (request, position) — + the block table pins a position to a physical slot, prefix-cache hits + reuse both the physical blocks and the identical token ids, and + spec-decode rollbacks rewrite the same slots — so lookbacks read back + exactly what the owning request wrote. Lookback depth (3) is far inside + the sliding window (128), so window eviction never frees a block a + live lookback still needs. + + Slots are not part of the KV cache, so KV loaded from another instance + (P/D, offload connectors) leaves them unwritten. The runner therefore + passes ``lookback_token_ids``, the ids just before each request's chunk + start, which take precedence over the slots. The V2 runner reads them + from its device-resident token history and needs no slot cache; the V1 + runner's CPU token table holds placeholders for generated tokens under + async scheduling, so it passes prompt positions only and keeps the slot + cache for the rest. +""" + +import weakref + +import numpy as np +import torch +from torch import nn + +from vllm.config import VllmConfig, get_current_vllm_config +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, + tensor_model_parallel_all_gather, +) +from vllm.logger import init_logger +from vllm.model_executor.layers.linear import ReplicatedLinear +from vllm.model_executor.layers.quantization import QuantizationConfig +from vllm.model_executor.utils import set_weight_attrs +from vllm.triton_utils import tl, triton +from vllm.utils.platform_utils import is_uva_available +from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor + +logger = init_logger(__name__) + +# Cache value for tokens that take no part in an n-gram (image spans). +DEAD_ID = -1 + + +def _is_prime(n: int) -> bool: + """Deterministic Miller-Rabin for n < 2**32 (avoids a sympy import).""" + if n < 2: + return False + for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): + if n % p == 0: + return n == p + d = n - 1 + r = 0 + while d % 2 == 0: + d //= 2 + r += 1 + for a in (2, 7, 61): + x = pow(a, d, n) + if x in (1, n - 1): + continue + for _ in range(r - 1): + x = x * x % n + if x == n - 1: + break + else: + return False + return True + + +def find_next_prime(start: int, seen_primes: set[int]) -> int: + """The smallest prime above `start` that has not been handed out yet.""" + candidate = start + 1 + while not _is_prime(candidate) or candidate in seen_primes: + candidate += 1 + return candidate + + +def build_compressed_token_map(tokenizer) -> tuple[list[int], int]: + """Map every token id onto a smaller id space where tokens that normalize + alike collapse together. + + N-grams are hashed over these compressed ids, so " The", "the" and "THE" + all hash the same way. The compressed size matters beyond bounds checking: + every hash multiplier is derived from it. + """ + from tokenizers import Regex, normalizers + + # A private-use char, so a token that is exactly one space survives + # Strip() instead of collapsing to the empty string and merging with + # unrelated tokens. + sentinel = "\ue000" + normalizer = normalizers.Sequence( + [ + normalizers.NFKC(), + normalizers.NFD(), + normalizers.StripAccents(), + normalizers.Lowercase(), + normalizers.Replace(Regex(r"[ \t\r\n]+"), " "), + normalizers.Replace(Regex(r"^ $"), sentinel), + normalizers.Strip(), + normalizers.Replace(sentinel, " "), + ] + ) + + # The raw Rust tokenizer, matching what training decodes with + # (no clean_up_tokenization_spaces). + backend = tokenizer.backend_tokenizer + key_to_new: dict[str, int] = {} + lookup = [0] * len(tokenizer) + for token_id in range(len(tokenizer)): + text = backend.decode([token_id], skip_special_tokens=False) + if "\ufffd" in text: + # A partial UTF-8 byte token: nothing to normalize, so key it + # by its raw form. + key = backend.id_to_token(token_id) + else: + normalized = normalizer.normalize_str(text) + key = normalized if normalized else text + + new_id = key_to_new.get(key) + if new_id is None: + new_id = len(key_to_new) + key_to_new[key] = new_id + lookup[token_id] = new_id + + return lookup, len(key_to_new) + + +def compute_hash_multipliers( + layer_ids: tuple[int, ...], max_ngram_size: int, compressed_vocab_size: int +) -> torch.Tensor: + """One multiplier per (layer, lookback), from a per-layer RNG so layers + hash differently. Kept odd and bounded so `token_id * multiplier` cannot + overflow int64. + """ + max_long = np.iinfo(np.int64).max + multiplier_bound = max(1, (max_long // compressed_vocab_size) // 2) + rows = [] + for layer_id in layer_ids: + generator = np.random.default_rng(10007 * layer_id) + values = generator.integers( + low=0, + high=multiplier_bound, + size=(max_ngram_size,), + dtype=np.int64, + ) + rows.append(torch.tensor(values * 2 + 1)) + return torch.stack(rows) + + +class EngramLayout: + """Bucket layout of the n-gram hash tables. + + A position is hashed as `max_ngram_size - 1` n-grams (2-gram .. max), each + split over `n_heads` heads. Every (n-gram size, head) pair owns its own + prime-sized bucket range in the layer's table; the primes are drawn in + order and never reused, which keeps the ranges disjoint. + """ + + def __init__(self, config) -> None: + self.layer_ids: tuple[int, ...] = tuple(config.engram_layer_ids) + self.num_embeddings: tuple[int, ...] = tuple(config.engram_num_embeddings) + self.max_ngram_size: int = config.engram_max_ngram_size + self.n_heads: int = config.engram_n_heads + self.head_dim: int = config.engram_head_dim + self.compressed_vocab_size: int = config.engram_compressed_vocab_size + self.pad_token_id: int = config.engram_pad_token_id + assert len(self.layer_ids) == len(self.num_embeddings) + + primes = [] + seen: set[int] = set() + for _ in self.layer_ids: + per_ngram = [] + for _ in range(self.max_ngram_size - 1): + sizes, current = [], config.engram_vocab_size - 1 + for _ in range(self.n_heads): + current = find_next_prime(current, seen) + seen.add(current) + sizes.append(current) + per_ngram.append(tuple(sizes)) + primes.append(tuple(per_ngram)) + self.primes: tuple[tuple[tuple[int, ...], ...], ...] = tuple(primes) + self.n_hash_cols = (self.max_ngram_size - 1) * self.n_heads + flat = [[p for per_ngram in layer for p in per_ngram] for layer in primes] + offsets = [np.cumsum([0, *sizes[:-1]]) for sizes in flat] + self.offsets = torch.tensor(np.array(offsets)) # [n_layers, n_hash_cols] + + @classmethod + def from_config(cls, config) -> "EngramLayout | None": + if not getattr(config, "engram_layer_ids", None): + return None + return cls(config) + + +@triton.jit(do_not_specialize=["num_tokens"]) +def _write_hash_cache_kernel( + input_ids, + token_map, + dead_mask, + slot_mapping, + cache, + num_tokens, + input_stride, + mask_stride, + slot_stride, + BLOCK_SIZE: tl.constexpr, + dead_id, +): + token_idx = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + slot = tl.load( + slot_mapping + token_idx * slot_stride, token_idx < num_tokens, other=-1 + ).to(tl.int64) + valid = (token_idx < num_tokens) & (slot >= 0) + token = tl.load(input_ids + token_idx * input_stride, valid, other=0) + value = tl.load(token_map + token, valid, other=0) + dead = tl.load(dead_mask + token_idx * mask_stride, valid, other=False) + value = tl.where(dead, dead_id, value) + tl.store(cache + slot, value, valid) + + +@triton.jit( + do_not_specialize=[ + "num_tokens", + "num_slots", + "num_query_rows", + "num_table_rows", + "max_blocks", + ] +) +def _hash_ids_kernel( + input_ids, + token_map, + dead_mask, + positions, + block_table, + query_start_loc, + multipliers, + primes, + offsets, + cache, + lookback_token_ids, + lookback_dead_mask, + output, + num_tokens, + num_slots, + pad_id, + input_stride, + mask_stride, + position_stride, + table_stride, + table_col_stride, + query_stride, + num_query_rows, + num_table_rows, + max_blocks, + cache_block_size, + MAX_NGRAM: tl.constexpr, + num_heads, + BLOCK_T: tl.constexpr, + BLOCK_H: tl.constexpr, + dead_id, + lookback_depth, + lookback_row_stride, + lookback_col_stride, + lookback_mask_row_stride, + lookback_mask_col_stride, +): + token = tl.program_id(0) * BLOCK_T + tl.arange(0, BLOCK_T) + layer = tl.program_id(1) + num_layers = tl.num_programs(1) + valid = token < num_tokens + # Upper bound in query_start_loc[1:], including repeated padding boundaries. + lo = tl.full((BLOCK_T,), 0, tl.int32) + hi = tl.full((BLOCK_T,), num_query_rows, tl.int32) + while tl.sum((lo < hi).to(tl.int32), 0) > 0: + mid = (lo + hi) // 2 + end = tl.load( + query_start_loc + (mid + 1) * query_stride, + lo < hi, + other=0, + ) + right = token >= end + active = lo < hi + lo = tl.where(active & right, mid + 1, lo) + hi = tl.where(active & ~right, mid, hi) + req = tl.minimum(lo, num_query_rows - 1).to(tl.int64) + chunk_idx = tl.load(query_start_loc + req * query_stride) + chunk_idx = tl.minimum(chunk_idx, num_tokens - 1).to(tl.int64) + chunk_start = tl.load(positions + chunk_idx * position_stride) + position = tl.load(positions + token * position_stride, valid, other=0).to(tl.int64) + head = tl.arange(0, BLOCK_H) + blocked = tl.full((BLOCK_T,), False, tl.int1) + rolling = tl.full((BLOCK_T,), 0, tl.int64) + for shift in tl.static_range(MAX_NGRAM): + lookback = position - shift + in_batch = lookback >= chunk_start + batch_idx = tl.maximum(token - shift, 0) + batch_token = tl.load( + input_ids + batch_idx * input_stride, valid & in_batch, other=0 + ) + batch_source = tl.load(token_map + batch_token, valid & in_batch, other=0) + batch_dead = tl.load( + dead_mask + batch_idx * mask_stride, valid & in_batch, other=False + ) + batch_source = tl.where(batch_dead, dead_id, batch_source) + + col = chunk_start - 1 - lookback + in_window = valid & ~in_batch & (col >= 0) & (col < lookback_depth) + col = tl.minimum(tl.maximum(col, 0), lookback_depth - 1) + window_token = tl.load( + lookback_token_ids + req * lookback_row_stride + col * lookback_col_stride, + in_window, + other=-1, + ) + known = in_window & (window_token >= 0) + window_source = tl.load(token_map + window_token, known, other=0) + window_dead = tl.load( + lookback_dead_mask + + req * lookback_mask_row_stride + + col * lookback_mask_col_stride, + known, + other=False, + ) + window_source = tl.where(window_dead, dead_id, window_source) + + if cache is not None: + clamped = tl.minimum( + tl.maximum(lookback, 0), max_blocks * cache_block_size - 1 + ) + block_row = tl.minimum(req, num_table_rows - 1) + needs_cache = valid & ~in_batch & ~known + block = tl.load( + block_table + + block_row * table_stride + + (clamped // cache_block_size) * table_col_stride, + needs_cache, + other=0, + ).to(tl.int64) + slot = tl.minimum( + tl.maximum(block * cache_block_size + clamped % cache_block_size, 0), + num_slots - 1, + ) + fallback = tl.load(cache + slot, needs_cache, other=0) + else: + fallback = tl.full((BLOCK_T,), pad_id, tl.int32) + source = tl.where( + in_batch, batch_source, tl.where(known, window_source, fallback) + ).to(tl.int64) + blocked |= (lookback < 0) | (source == dead_id) + value = tl.where(blocked, pad_id, source) + multiplier = tl.load(multipliers + layer * MAX_NGRAM + shift) + rolling ^= value * multiplier + if shift > 0: + col = (shift - 1) * num_heads + head + param_offset = layer * (MAX_NGRAM - 1) * num_heads + col + prime = tl.load(primes + param_offset, head < num_heads, other=1) + offset = tl.load(offsets + param_offset, head < num_heads, other=0) + hashed = rolling[:, None] % prime[None, :] + offset[None, :] + out_offset = (token.to(tl.int64) * num_layers + layer)[:, None] * ( + (MAX_NGRAM - 1) * num_heads + ) + col[None, :] + tl.store(output + out_offset, hashed, valid[:, None] & (head < num_heads)) + + +class NgramHashState(nn.Module): + """Maps each position to the hash ids of the n-grams ending there. + + Stateless on the V2 runner, which supplies every lookback token id. On + the V1 runner it also keeps `hash_cache`, the slot-keyed rolling store + of compressed ids (see module docstring), for generated tokens. + """ + + def __init__( + self, + vllm_config: VllmConfig, + layout: EngramLayout, + swa_cache_module: nn.Module, + ) -> None: + super().__init__() + self.layout = layout + self.swa_cache_module = swa_cache_module + self.block_size: int = swa_cache_module.block_size + self.lookback_depth: int = layout.max_ngram_size - 1 + self.use_slot_cache: bool = not vllm_config.use_v2_model_runner + self._cache: torch.Tensor | None = None + self._kv_cache_ref: weakref.ReferenceType[torch.Tensor] | None = None + + model_config = vllm_config.model_config + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained( + model_config.tokenizer, + trust_remote_code=model_config.trust_remote_code, + revision=model_config.revision, + ) + token_map, vocab_size = build_compressed_token_map(tokenizer) + if vocab_size != layout.compressed_vocab_size: + raise ValueError( + f"Compressed vocab size mismatch: built {vocab_size} from the " + f"tokenizer, config expects {layout.compressed_vocab_size}; " + "every hash multiplier derives from it, so the engram tables " + "would be silently rehashed." + ) + self.pad_id = token_map[layout.pad_token_id] + multipliers = compute_hash_multipliers( + layout.layer_ids, layout.max_ngram_size, vocab_size + ) + self.register_buffer( + "token_map", torch.tensor(token_map, dtype=torch.int32), persistent=False + ) + self.register_buffer("primes", torch.tensor(layout.primes), persistent=False) + self.register_buffer("offsets", layout.offsets, persistent=False) + self.register_buffer("multipliers", multipliers, persistent=False) + logger.info( + "Built engram token map (%d -> %d ids) for layers %s", + len(token_map), + vocab_size, + layout.layer_ids, + ) + + def ensure_cache(self) -> bool: + """Lazily size the slot-keyed cache from the bound SWA KV cache. + + Returns False while the KV cache is unbound (profile run); the caller + skips engram hashing then. Without the slot cache only that check + remains. + """ + kv_cache = self.swa_cache_module.kv_cache + if kv_cache.numel() == 0: + self._cache = None + self._kv_cache_ref = None + return False + if not self.use_slot_cache: + return True + if self._kv_cache_ref is not None and self._kv_cache_ref() is kv_cache: + return True + # Graph memory profiling binds a temporary, smaller KV cache first. + # Rebinding must discard its hash history without retaining KV storage. + self._cache = torch.zeros( + kv_cache.shape[0] * self.block_size, + dtype=torch.int32, + device=kv_cache.device, + ) + self._kv_cache_ref = weakref.ref(kv_cache) + return True + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + query_start_loc: torch.Tensor, + dead_mask: torch.Tensor, + lookback_token_ids: torch.Tensor, + lookback_dead_mask: torch.Tensor, + slot_mapping: torch.Tensor | None, + block_table: torch.Tensor | None, + ) -> torch.Tensor: + """Compute [tokens, layers, hash columns] int32 n-gram hashes. + + History comes from the current chunk, then the runner's lookback + window, then the optional V1 slot cache. V2 needs only one launch. + """ + cache = self._cache if self.use_slot_cache else None + num_tokens = input_ids.shape[0] + num_layers, max_ngram = self.multipliers.shape + num_heads = self.primes.shape[-1] + output = input_ids.new_empty( + (num_tokens, num_layers, (max_ngram - 1) * num_heads), dtype=torch.int32 + ) + if num_tokens == 0: + return output + if self.use_slot_cache: + assert cache is not None and slot_mapping is not None + assert block_table is not None + # Finish writes before other thread blocks read fallback history. + _write_hash_cache_kernel[(triton.cdiv(num_tokens, 256),)]( + input_ids, + self.token_map, + dead_mask, + slot_mapping, + cache, + num_tokens, + input_ids.stride(0), + dead_mask.stride(0), + slot_mapping.stride(0), + 256, + DEAD_ID, + ) + _hash_ids_kernel[(triton.cdiv(num_tokens, 32), num_layers)]( + input_ids, + self.token_map, + dead_mask, + positions, + block_table, + query_start_loc, + self.multipliers, + self.primes, + self.offsets, + cache, + lookback_token_ids, + lookback_dead_mask, + output, + num_tokens, + cache.shape[0] if cache is not None else 0, + self.pad_id, + input_stride=input_ids.stride(0), + mask_stride=dead_mask.stride(0), + position_stride=positions.stride(0), + table_stride=block_table.stride(0) if block_table is not None else 0, + table_col_stride=block_table.stride(1) if block_table is not None else 0, + query_stride=query_start_loc.stride(0), + num_query_rows=query_start_loc.numel() - 1, + num_table_rows=block_table.shape[0] if block_table is not None else 0, + max_blocks=block_table.shape[1] if block_table is not None else 0, + cache_block_size=self.block_size, + MAX_NGRAM=max_ngram, + num_heads=num_heads, + BLOCK_T=32, + BLOCK_H=triton.next_power_of_2(num_heads), + dead_id=DEAD_ID, + lookback_depth=lookback_token_ids.shape[1], + lookback_row_stride=lookback_token_ids.stride(0), + lookback_col_stride=lookback_token_ids.stride(1), + lookback_mask_row_stride=lookback_dead_mask.stride(0), + lookback_mask_col_stride=lookback_dead_mask.stride(1), + num_warps=4, + ) + return output + + +def _engram_head_shard_weight_loader( + param: torch.nn.Parameter, loaded_weight: torch.Tensor +) -> None: + """Load this rank's complete head buckets. ue8m0 scales arrive as + float8_e8m0fnu; keep the raw bytes (the param stores uint8).""" + part_rows = param.shape[0] + if loaded_weight.dtype == torch.float8_e8m0fnu: + loaded_weight = loaded_weight.view(torch.uint8) + shard = loaded_weight.narrow(0, param.engram_vocab_start, part_rows) + assert shard.shape == param.shape, ( + f"engram shard {tuple(shard.shape)} does not fit param {tuple(param.shape)}" + ) + param.data.copy_(shard) + + +@triton.jit +def _engram_lookup_kernel( + weight, + scales, + ids, + out, + vocab_start, + vocab_end, + num_rows, + ids_stride_t, + ids_stride_h, + HEAD_START: tl.constexpr, + LOCAL_HEADS: tl.constexpr, + TOTAL_HEADS: tl.constexpr, + DIM: tl.constexpr, + QUANT_BLOCK: tl.constexpr, + BLOCK_R: tl.constexpr, + GRID: tl.constexpr, +): + """Gather fp8 rows, apply their ue8m0 block scales, write bf16. + + Only this rank's heads are read; padded heads write zeros for all-gather. + `weight`/`scales` may address pinned host memory through UVA. + """ + cols = tl.arange(0, DIM) + scale_cols = cols // QUANT_BLOCK + for base in tl.range(tl.program_id(0) * BLOCK_R, num_rows, GRID * BLOCK_R): + rows = base + tl.arange(0, BLOCK_R) + valid = rows < num_rows + head = HEAD_START + rows % LOCAL_HEADS + token = (rows // LOCAL_HEADS).to(tl.int64) + index = tl.load( + ids + token * ids_stride_t + head * ids_stride_h, + mask=valid & (head < TOTAL_HEADS), + other=-1, + ).to(tl.int64) + owned = valid & (head < TOTAL_HEADS) + owned &= (index >= vocab_start) & (index < vocab_end) + local = tl.where(owned, index - vocab_start, 0) + values = tl.load( + weight + local[:, None] * DIM + cols[None, :], + mask=owned[:, None], + other=0.0, + ) + scale = tl.load( + scales + local[:, None] * (DIM // QUANT_BLOCK) + scale_cols[None, :], + mask=owned[:, None], + other=0, + ) + # ue8m0 is a power of two, so its byte *is* the fp32 exponent field. + scale = (scale.to(tl.int32) << 23).to(tl.float32, bitcast=True) + tl.store( + out + rows[:, None] * DIM + cols[None, :], + (values.to(tl.float32) * scale).to(tl.bfloat16), + mask=valid[:, None], + ) + + +class ParallelEngramEmbedding(nn.Module): + """The n-gram hash table, sharded by complete hash heads over TP ranks. + Rows stay fp8 and are dequantized with ue8m0 per-32 scales on lookup. + + With `cpu_offload` the shard lives in pinned host memory and is read over + UVA instead of HBM; the TP sharding is unchanged either way. + """ + + def __init__( + self, + num_embeddings: int, + dim: int, + head_sizes: tuple[int, ...], + block_size: int = 32, + cpu_offload: bool = False, + ): + super().__init__() + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + assert head_sizes and all(size > 0 for size in head_sizes) + assert sum(head_sizes) <= num_embeddings + if cpu_offload and not is_uva_available(): + raise RuntimeError("Engram CPU offload requires UVA support") + self.num_embeddings = num_embeddings + self.dim = dim + self.block_size = block_size + self.n_hash_cols = len(head_sizes) + self.part_n_hash_cols = triton.cdiv(self.n_hash_cols, tp_size) + self.head_start = tp_rank * self.part_n_hash_cols + head_end = self.head_start + self.part_n_hash_cols + self.vocab_start_idx = sum(head_sizes[: self.head_start]) + self.vocab_end_idx = sum(head_sizes[:head_end]) + self.part_num_embeddings = self.vocab_end_idx - self.vocab_start_idx + self.tp_size = tp_size + self.cpu_offload = cpu_offload + self._views: tuple[torch.Tensor, torch.Tensor] | None = None + self._view_src: tuple[int, int] | None = None + self._num_sms = torch.cuda.get_device_properties( + torch.accelerator.current_device_index() + ).multi_processor_count + + # Explicit device: model init runs under a `torch.device("cuda")` + # context, which would otherwise put the shard in HBM. + kwargs = {"device": "cpu", "pin_memory": True} if cpu_offload else {} + self.weight = nn.Parameter( + torch.empty( + self.part_num_embeddings, dim, dtype=torch.float8_e4m3fn, **kwargs + ), + requires_grad=False, + ) + self.weight_scale_inv = nn.Parameter( + torch.empty( + self.part_num_embeddings, + dim // block_size, + dtype=torch.uint8, + **kwargs, + ), + requires_grad=False, + ) + for param in (self.weight, self.weight_scale_inv): + set_weight_attrs( + param, + { + "weight_loader": _engram_head_shard_weight_loader, + "engram_vocab_start": self.vocab_start_idx, + }, + ) + if cpu_offload: + logger.info( + "Engram table offloaded to pinned host memory: %d rows x %d, " + "%.2f GiB per rank", + self.part_num_embeddings, + dim, + self.part_num_embeddings * (dim + dim // block_size) / 1024**3, + ) + + def _storage(self) -> tuple[torch.Tensor, torch.Tensor]: + """Parameters when resident, else cached UVA views of the pinned shard. + + Rebuilt if anything swaps `.data`, so a stale device pointer cannot + survive silently. + """ + if not self.cpu_offload: + return self.weight.data, self.weight_scale_inv.data + src = (self.weight.data_ptr(), self.weight_scale_inv.data_ptr()) + if self._view_src != src: + self._views = ( + get_accelerator_view_from_cpu_tensor(self.weight.data), + get_accelerator_view_from_cpu_tensor(self.weight_scale_inv.data), + ) + self._view_src = src + assert self._views is not None + return self._views + + def lookup( + self, indices: torch.Tensor, out: torch.Tensor, background: bool = False + ) -> None: + """Look up local heads of [T, heads] into [T, local_heads, dim] bf16. + + `background` limits the grid to leave SMs for concurrent work. + """ + rows = indices.shape[0] * self.part_n_hash_cols + if not rows: + return + weight, scales = self._storage() + # The table dwarfs TLB reach, so a persistent grid near the SM count + # beats one program per row; halve it to leave SMs for the main stream. + tiles = triton.cdiv(rows, 16) + grid = min(tiles, self._num_sms // 2 if background else self._num_sms) + _engram_lookup_kernel[(grid,)]( + weight, + scales, + indices, + out, + self.vocab_start_idx, + self.vocab_end_idx, + rows, + indices.stride(0), + indices.stride(1), + HEAD_START=self.head_start, + LOCAL_HEADS=self.part_n_hash_cols, + TOTAL_HEADS=self.n_hash_cols, + DIM=self.dim, + QUANT_BLOCK=self.block_size, + BLOCK_R=16, + GRID=grid, + ) + + def forward(self, indices: torch.Tensor) -> torch.Tensor: + """indices: [num_tokens, n_hash_cols] -> [num_tokens, n_hash_cols, dim] + bf16, gathered from all TP shards.""" + out = torch.empty( + (indices.shape[0], self.part_n_hash_cols, self.dim), + dtype=torch.bfloat16, + device=indices.device, + ) + self.lookup(indices, out) + if self.tp_size > 1: + out = tensor_model_parallel_all_gather(out, dim=1) + out = out[:, : self.n_hash_cols] + return out + + +@triton.jit(do_not_specialize=["num_kv_tokens"]) +def _fused_engram_post_wkv_kernel( + hidden_states, + kv, + q_weight, + k_weight, + token_mask, + output, + num_kv_tokens, + hidden_stride_t, + hidden_stride_h, + hidden_stride_d, + kv_stride_t, + kv_stride_d, + q_stride_h, + q_stride_d, + k_stride_h, + k_stride_d, + mask_stride, + output_stride_t, + output_stride_h, + output_stride_d, + eps, + clamp_value, + DIM: tl.constexpr, + HC_MULT: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + HAS_MASK: tl.constexpr, +): + program_idx = tl.program_id(0) + token_idx = program_idx // HC_MULT + hc_idx = program_idx % HC_MULT + token_idx = token_idx.to(tl.int64) + source_idx = token_idx + source_valid = source_idx < num_kv_tokens + + dim_offsets = tl.arange(0, BLOCK_SIZE) + dim_valid = dim_offsets < DIM + hidden = tl.load( + hidden_states + + token_idx * hidden_stride_t + + hc_idx * hidden_stride_h + + dim_offsets * hidden_stride_d, + mask=dim_valid, + other=0.0, + ).to(tl.float32) + key = tl.load( + kv + source_idx * kv_stride_t + (hc_idx * DIM + dim_offsets) * kv_stride_d, + mask=source_valid & dim_valid, + other=0.0, + ).to(tl.float32) + q = tl.load( + q_weight + hc_idx * q_stride_h + dim_offsets * q_stride_d, + mask=dim_valid, + other=0.0, + ).to(tl.float32) + k = tl.load( + k_weight + hc_idx * k_stride_h + dim_offsets * k_stride_d, + mask=dim_valid, + other=0.0, + ).to(tl.float32) + + hidden_rms = tl.rsqrt(tl.sum(hidden * hidden, axis=0) / DIM + eps) + key_rms = tl.rsqrt(tl.sum(key * key, axis=0) / DIM + eps) + dot = tl.sum(hidden * q * k * key, axis=0) + dot *= hidden_rms * key_rms * tl.rsqrt(DIM * 1.0) + gate_input = tl.sqrt(tl.maximum(tl.abs(dot), clamp_value)) + gate_input = tl.where(dot < 0.0, -gate_input, gate_input) + gate = tl.sigmoid(gate_input) + if HAS_MASK: + active = tl.load( + token_mask + source_idx * mask_stride, + mask=source_valid, + other=0, + ) + gate = tl.where(active, gate, 0.0) + + value = tl.load( + kv + source_idx * kv_stride_t + (HC_MULT * DIM + dim_offsets) * kv_stride_d, + mask=source_valid & dim_valid, + other=0.0, + ).to(tl.float32) + tl.store( + output + + token_idx * output_stride_t + + hc_idx * output_stride_h + + dim_offsets * output_stride_d, + hidden + gate * value, + mask=dim_valid, + ) + + +@triton.jit(do_not_specialize=["num_tokens", "token_start", "num_elements"]) +def _engram_sp_rows_kernel( + gathered, + output, + num_tokens, + token_start, + num_elements, + LOCAL_WIDTH: tl.constexpr, + WIDTH: tl.constexpr, + BLOCK_SIZE: tl.constexpr, +): + offsets = tl.program_id(0).to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + tokens = token_start + offsets // WIDTH + cols = offsets % WIDTH + source = (cols // LOCAL_WIDTH * num_tokens + tokens) * LOCAL_WIDTH + source += cols % LOCAL_WIDTH + values = tl.load( + gathered + source, (offsets < num_elements) & (tokens < num_tokens), other=0 + ) + tl.store(output + offsets, values, offsets < num_elements) + + +class Engram(nn.Module): + """Writes an n-gram lookup into the residual stream, gated by how well it + matches that stream. + + The hash ids fetch `n_hash_cols` rows; `wkv` turns them into one key per + hc copy plus a shared value. The gate is a normalized dot product of the + stream against the key, signed-sqrt'ed before the sigmoid (matching the + training kernel). + """ + + def __init__( + self, + config, + quant_config: QuantizationConfig | None, + layout: EngramLayout, + layer_hash_index: int, + use_sequence_parallel: bool, + prefix: str, + ) -> None: + super().__init__() + self.layer_hash_index = layer_hash_index + self.dim = config.hidden_size + self.hc_mult = config.hc_mult + self.eps = config.rms_norm_eps + self.clamp_value = 1e-6 + self.use_sequence_parallel = use_sequence_parallel + + # Named ``embed_tokens`` so the checkpoint's ``engram.embed.weight`` + # survives the mapper's ``embed.weight`` -> ``embed_tokens.weight`` + # suffix rule. + engram_config = get_current_vllm_config().engram_config + self.embed_tokens = ParallelEngramEmbedding( + layout.num_embeddings[layer_hash_index], + layout.head_dim, + tuple(size for order in layout.primes[layer_hash_index] for size in order), + cpu_offload=engram_config.cpu_offload if engram_config else True, + ) + n_hash_cols = (layout.max_ngram_size - 1) * layout.n_heads + self.wkv = ReplicatedLinear( + n_hash_cols * layout.head_dim, + self.dim * (self.hc_mult + 1), + bias=False, + quant_config=quant_config, + return_bias=False, + prefix=f"{prefix}.wkv", + ) + self.q_weight = nn.Parameter( + torch.empty(self.hc_mult, self.dim, dtype=torch.bfloat16), + requires_grad=False, + ) + self.k_weight = nn.Parameter( + torch.empty(self.hc_mult, self.dim, dtype=torch.bfloat16), + requires_grad=False, + ) + + max_tokens = get_current_vllm_config().scheduler_config.max_num_batched_tokens + # Keep lookup results alive across breakable graph segments. + self.staged_rows = torch.empty( + max_tokens, + self.embed_tokens.part_n_hash_cols, + layout.head_dim, + dtype=torch.bfloat16, + ) + + def prepare_embeddings(self, hash_ids: torch.Tensor) -> None: + """Gather this layer's rows on the main stream before decoder layers.""" + self.embed_tokens.lookup(hash_ids, self.staged_rows[: hash_ids.shape[0]]) + + def embed(self, hash_ids: torch.Tensor) -> torch.Tensor: + """Gather heads, returning only local tokens when SP is enabled.""" + rows = self.staged_rows[: hash_ids.shape[0]] + if self.embed_tokens.tp_size == 1: + return rows + if self.use_sequence_parallel: + tp_size = self.embed_tokens.tp_size + num_tokens, local_heads, dim = rows.shape + gathered = tensor_model_parallel_all_gather(rows, dim=0) + chunk = (num_tokens + tp_size - 1) // tp_size + rows = rows.new_empty((chunk, self.embed_tokens.n_hash_cols, dim)) + _engram_sp_rows_kernel[(triton.cdiv(rows.numel(), 1024),)]( + gathered, + rows, + num_tokens, + get_tensor_model_parallel_rank() * chunk, + rows.numel(), + local_heads * dim, + self.embed_tokens.n_hash_cols * dim, + BLOCK_SIZE=1024, + ) + return rows + rows = tensor_model_parallel_all_gather(rows, dim=1) + return rows[:, : self.embed_tokens.n_hash_cols] + + def forward( + self, + hidden_states: torch.Tensor, + hash_ids: torch.Tensor, + token_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + """hidden_states: [T, hc_mult, dim]; hash_ids: [T, n_hash_cols] (all + tokens, pre sequence-parallel shard); token_mask: [T], False shuts + the gate so those positions pass through untouched.""" + kv = self.wkv(self.embed(hash_ids).flatten(-2)) + num_kv_tokens = hash_ids.shape[0] + assert token_mask is None or token_mask.shape == (num_kv_tokens,) + if self.use_sequence_parallel: + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + shard_size = (num_kv_tokens + tp_size - 1) // tp_size + assert hidden_states.shape[0] == shard_size + start = min(tp_rank * shard_size, num_kv_tokens) + num_kv_tokens = min(shard_size, num_kv_tokens - start) + if token_mask is not None: + token_mask = token_mask[start : start + num_kv_tokens] + + num_tokens, hc_mult, dim = hidden_states.shape + assert hc_mult == self.hc_mult and dim == self.dim + assert kv.ndim == 2 and kv.shape[1] == (hc_mult + 1) * dim + output = torch.empty_like(hidden_states) + if num_tokens == 0: + return output + + block_size = triton.next_power_of_2(dim) + num_warps = 8 if block_size >= 2048 else 4 + mask = token_mask if token_mask is not None else hidden_states + _fused_engram_post_wkv_kernel[(num_tokens * hc_mult,)]( + hidden_states, + kv, + self.q_weight, + self.k_weight, + mask, + output, + num_kv_tokens, + hidden_states.stride(0), + hidden_states.stride(1), + hidden_states.stride(2), + kv.stride(0), + kv.stride(1), + self.q_weight.stride(0), + self.q_weight.stride(1), + self.k_weight.stride(0), + self.k_weight.stride(1), + token_mask.stride(0) if token_mask is not None else 0, + output.stride(0), + output.stride(1), + output.stride(2), + self.eps, + self.clamp_value, + DIM=dim, + HC_MULT=hc_mult, + BLOCK_SIZE=block_size, + HAS_MASK=token_mask is not None, + num_warps=num_warps, + ) + return output diff --git a/vllm/models/deepseek_v4_1/common/ops/__init__.py b/vllm/models/deepseek_v4_1/common/ops/__init__.py new file mode 100644 index 0000000000..73c4d1b4da --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/ops/__init__.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepSeek V4.1 fused ops. + +Single bridging point for the kernels V4.1 shares verbatim with V4: the +re-exports below are the only place this package reaches into +``vllm.models.deepseek_v4``, so submodules import them from ``.`` instead of +naming the V4 path themselves. Keep these imports above the ``.``-relative +ones — ``indexer_k_store`` reads them off this partially-initialized module. +""" + +from vllm.models.deepseek_v4.common.ops.fused_indexer_q import ( + MXFP4_BLOCK_SIZE, + fused_indexer_q_rope_quant, +) +from vllm.models.deepseek_v4.common.ops.fused_indexer_q import ( + _fp32x2_to_fp4x2 as _fp32x2_to_fp4x2, # re-export for .indexer_k_store +) +from vllm.models.deepseek_v4.common.ops.fused_inv_rope_fp8_quant import ( + fused_inv_rope_fp8_quant, +) + +from .cache_utils import ( + build_flashinfer_mixed_sparse_indices, + combine_topk_swa_indices, + compute_global_topk_indices_and_lens, + dequantize_and_gather_k_cache, + quantize_and_insert_k_cache, +) +from .indexer_k_store import indexer_k_norm_rope_store + +__all__ = [ + "MXFP4_BLOCK_SIZE", + "build_flashinfer_mixed_sparse_indices", + "combine_topk_swa_indices", + "compute_global_topk_indices_and_lens", + "dequantize_and_gather_k_cache", + "fused_indexer_q_rope_quant", + "fused_inv_rope_fp8_quant", + "indexer_k_norm_rope_store", + "quantize_and_insert_k_cache", +] diff --git a/vllm/models/deepseek_v4_1/common/ops/cache_utils.py b/vllm/models/deepseek_v4_1/common/ops/cache_utils.py new file mode 100644 index 0000000000..e2da6f5e2b --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/ops/cache_utils.py @@ -0,0 +1,1254 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +Triton kernels for DeepseekV4 paged K-cache management and sparse-attention index +preparation. + +- quantize_and_insert_k_cache: quantize bf16 K to UE8M0 FP8 and insert into + the paged cache. +- dequantize_and_gather_k_cache: gather and dequantize FP8 K from the paged + cache for sparse/SWA prefill. +- compute_global_topk_indices_and_lens: map local topk indices to global KV + cache slots and count valid entries. +- combine_topk_swa_indices: concatenate topk compressed indices with SWA + window indices for sparse prefill. +""" + +from dataclasses import dataclass +from typing import Any + +import torch + +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + get_fp8_min_max, +) +from vllm.model_executor.warmup.jit_warmup import ( + VllmJitKernel, + _WarmupInputRows, + zip_inputs, +) +from vllm.model_executor.warmup.jit_warmup_triton_helper import ( + TritonPointerInputVariant, + TritonWarmupTensor, +) +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton +from vllm.utils.import_utils import has_cutedsl +from vllm.utils.math_utils import next_power_of_2 + + +@triton.jit +def quantize_and_insert_k_kernel( + # Input tensors + k_ptr, # [num_tokens, 512] bf16 + slot_mapping_ptr, # [num_tokens] int64 + # Output tensor + k_cache_ptr, # [num_blocks, block_bytes] as uint8 (flattened view) + # Dimensions + num_tokens, + input_dim: tl.constexpr, # 512 + fp8_dim: tl.constexpr, # 448 + bf16_dim: tl.constexpr, # 64 + scale_dim: tl.constexpr, # 8 + quant_block: tl.constexpr, # 64 (quantization block size) + cache_block_size: tl.constexpr, # 64 (paged cache block size) + token_data_size: tl.constexpr, # 576 bytes per token data + block_stride: tl.constexpr, # total bytes per block (padded) + fp8_max: tl.constexpr, + n_quant_blocks: tl.constexpr, # 8 (7 real + 1 padding) + use_fnuz: tl.constexpr = False, +): + """ + Quantize K tensor and insert into paged K cache. + + K Cache block layout (block_size=64 tokens): + - [0, 64*576): Token data, each token has 448 fp8 + 128 bf16 + - [64*576, 64*576 + 64*8): Scales, each token has 8 uint8 scales + - [64*576 + 64*8, block_stride): Padding + + One program per token. + + ``use_fnuz=True`` selects FNUZ (``tl.float8e4b8``); default OCP + (``tl.float8e4nv``) matches every production caller. + """ + pid = tl.program_id(0) + + if pid >= num_tokens: + return + + # Get slot mapping + slot_idx = tl.load(slot_mapping_ptr + pid) + if slot_idx == -1: + return + + block_idx = slot_idx // cache_block_size + pos_in_block = slot_idx % cache_block_size + + # Input pointer for this token + input_row_ptr = k_ptr + pid * input_dim + + # int64: block_idx * block_stride can exceed 2^31 with many KV-cache blocks + # (e.g. >= 57K at block_stride ~37K). Matches gather path below. + cache_block_ptr = k_cache_ptr + block_idx.to(tl.int64) * block_stride + + # Token data pointer: token data is stored contiguously at start of block + # Each token's data is at offset pos_in_block * token_data_size + token_data_ptr = cache_block_ptr + pos_in_block * token_data_size + + # Scale pointer: scales are stored after ALL token data in the block + # Scale for this token is at offset (64 * 576) + pos_in_block * 8 + token_scale_ptr = ( + cache_block_ptr + cache_block_size * token_data_size + pos_in_block * scale_dim + ) + + # Token data layout: [0:448] fp8, [448:576] bf16 + token_fp8_ptr = token_data_ptr + token_bf16_ptr = token_data_ptr + fp8_dim + + # ========== Quantize and store FP8 portion (first 448 elements) ========== + # Using UE8M0 quantization strategy (scale is power of 2, stored as uint8 exponent) + for qblock_idx in tl.static_range(n_quant_blocks): + qblock_start = qblock_idx * quant_block + + if qblock_start < fp8_dim: + offsets = qblock_start + tl.arange(0, quant_block) + mask = offsets < fp8_dim + + # Load bf16 input + x = tl.load(input_row_ptr + offsets, mask=mask, other=0.0) + + # Compute absmax scale (same as CUDA kernel) + abs_x = tl.abs(x) + block_max = tl.max(abs_x, axis=0) + block_max = tl.maximum(block_max, 1e-4) # Match CUDA: fmaxf(amax, 1e-4) + + # UE8M0: Round scale UP to next power of 2 + # scale = 2^ceil(log2(block_max / fp8_max)) + raw_scale = block_max / fp8_max + log_scale = tl.log2(raw_scale) + exponent = tl.ceil(log_scale) # Round UP to next integer exponent + scale = tl.exp2(exponent) # scale = 2^exponent (power of 2) + + # Quantize to fp8: fp8_value = bf16_value / scale + x_scaled = x / scale + x_clamped = tl.clamp(x_scaled, -fp8_max, fp8_max) + + # Convert to fp8 (FNUZ on gfx942, OCP elsewhere), then bitcast to uint8. + if use_fnuz: + x_fp8 = x_clamped.to(tl.float8e4b8) + else: + x_fp8 = x_clamped.to(tl.float8e4nv) + x_uint8 = x_fp8.to(tl.uint8, bitcast=True) + + # Store as uint8 (1 byte each) + tl.store(token_fp8_ptr + offsets, x_uint8, mask=mask) + + # UE8M0 scale encoding: stored_value = exponent + 127 (bias) + # During dequant: scale = 2^(stored_value - 127) + encoded_scale = exponent + 127.0 + encoded_scale = tl.maximum(tl.minimum(encoded_scale, 255.0), 0.0) + tl.store(token_scale_ptr + qblock_idx, encoded_scale.to(tl.uint8)) + + # Padding scale at index 7 + tl.store(token_scale_ptr + 7, tl.zeros((), dtype=tl.uint8)) + + # ========== Store BF16 portion (last 64 elements, no quantization) ========== + bf16_input_offset = fp8_dim + + # Process bf16 in chunks of 16 + bf16_out_ptr = token_bf16_ptr.to(tl.pointer_type(tl.bfloat16)) + for i in tl.static_range(bf16_dim // 16): + chunk_offsets = i * 16 + tl.arange(0, 16) + bf16_vals = tl.load(input_row_ptr + bf16_input_offset + chunk_offsets) + tl.store(bf16_out_ptr + chunk_offsets, bf16_vals) + + +def quantize_and_insert_k_cache( + k: torch.Tensor, # [num_tokens, 512] bf16 + k_cache: torch.Tensor, # [num_blocks, block_bytes] uint8 + slot_mapping: torch.Tensor, # [num_tokens] int64 + block_size: int = 64, + is_ue8m0: bool = True, + use_fnuz: bool = False, +): + """ + Quantize K tensor and insert into paged K cache. + + K Cache block layout (block_size=64 tokens): + - First 64 * 576 = 36864 bytes: Token data + - Each token: 448 bytes (fp8) + 128 bytes (bf16) + - Next 64 * 8 = 512 bytes: Scales + - Each token: 8 bytes (uint8 scales, 7 real + 1 padding) + - Padded to multiple of 576 + + ``use_fnuz=True`` selects FNUZ E4M3 cache encoding and is only valid on + platforms whose FP8 format is FNUZ. ``use_fnuz=False`` selects OCP E4M3, + which is used by OCP-encoded caches even on gfx942. + """ + assert k.dim() == 2 and k.shape[1] == 512, ( + f"K must be [num_tokens, 512], got {k.shape}" + ) + assert k.dtype == torch.bfloat16, f"K must be bf16, got {k.dtype}" + assert is_ue8m0, "Only support ue8m0 quantization." + + # NOTE: When using DP, slot_mapping.shape[0] can be less than k.shape[0] due to + # padding. Always use slot_mapping.shape[0] as the token count. + num_tokens = slot_mapping.shape[0] + block_stride = k_cache.stride(0) # bytes per block + + TOKEN_FP8_DIM = 448 + TOKEN_BF16_DIM = 64 + TOKEN_SCALE_DIM = 8 + QUANT_BLOCK_SIZE = 64 + if use_fnuz: + if not current_platform.is_fp8_fnuz(): + raise ValueError("use_fnuz=True requires a platform using FNUZ FP8") + _, FP8_MAX = get_fp8_min_max() + else: + FP8_MAX = torch.finfo(torch.float8_e4m3fn).max + TOKEN_DATA_SIZE = TOKEN_FP8_DIM + TOKEN_BF16_DIM * 2 + + grid = (num_tokens,) + + quantize_and_insert_k_kernel[grid]( + k, + slot_mapping, + k_cache, + num_tokens, + input_dim=512, + fp8_dim=TOKEN_FP8_DIM, + bf16_dim=TOKEN_BF16_DIM, + scale_dim=TOKEN_SCALE_DIM, + quant_block=QUANT_BLOCK_SIZE, + cache_block_size=block_size, + token_data_size=TOKEN_DATA_SIZE, + block_stride=block_stride, + fp8_max=FP8_MAX, + n_quant_blocks=8, + use_fnuz=use_fnuz, + ) + + +@triton.jit +def _dequantize_and_gather_k_kernel( + out_ptr, + out_stride0, + out_stride1, + k_cache_ptr, + seq_lens_ptr, + block_table_ptr, + offset, + gather_lens_ptr, + # Constants + max_blocks_per_seq: tl.constexpr, + fp8_dim: tl.constexpr, # 448 + bf16_dim: tl.constexpr, # 64 + scale_dim: tl.constexpr, # 8 + quant_block: tl.constexpr, # 64 (quantization block size) + cache_block_size: tl.constexpr, # 64 or 128 (paged cache block size) + token_data_size: tl.constexpr, # 576 bytes per token data + block_stride: tl.constexpr, # total bytes per block (padded) int32 + output_dim: tl.constexpr, # 512 + fp8_max: tl.constexpr, + n_quant_blocks: tl.constexpr, # 7 real blocks + use_fnuz: tl.constexpr = False, +): + batch_idx = tl.program_id(0) + worker_id = tl.program_id(1) + num_workers = tl.num_programs(1) + + seq_len = tl.load(seq_lens_ptr + batch_idx) + if gather_lens_ptr is not None: # noqa: SIM108 + gather_len = tl.load(gather_lens_ptr + batch_idx) + else: + # Gather all tokens + gather_len = seq_len + start_pos = seq_len - gather_len + + for i in range(worker_id, gather_len, num_workers): + # Calculate the actual token index in the sequence + pos = start_pos + i + + # Calculate which block and position within block + block_in_seq = pos // cache_block_size + pos_in_block = pos % cache_block_size + + # Get physical block index from block table + block_table_row_ptr = block_table_ptr + batch_idx * max_blocks_per_seq + physical_block_idx = tl.load(block_table_row_ptr + block_in_seq) # int32 + + # int64: physical_block_idx * block_stride can exceed 2^31 with many + # KV-cache blocks (e.g. >= 57K at block_stride ~37K). + cache_block_ptr = k_cache_ptr + physical_block_idx.to(tl.int64) * block_stride + + # Token data pointer + token_data_ptr = cache_block_ptr + pos_in_block * token_data_size + + # Scale pointer: after all token data + token_scale_ptr = ( + cache_block_ptr + + cache_block_size * token_data_size + + pos_in_block * scale_dim + ) + + # Token data layout: [0:448] fp8, [448:576] bf16 + token_fp8_ptr = token_data_ptr + token_bf16_ptr = token_data_ptr + fp8_dim + + # Output pointer for this token (flattened) + output_row_ptr = out_ptr + batch_idx * out_stride0 + (offset + i) * out_stride1 + + # ========== Dequantize FP8 portion using UE8M0 ========== + for qblock_idx in tl.static_range(n_quant_blocks): + qblock_start = qblock_idx * quant_block + + if qblock_start < fp8_dim: + offsets = qblock_start + tl.arange(0, quant_block) + mask = offsets < fp8_dim + + # Load quantized fp8 values (stored as uint8) + x_uint8 = tl.load(token_fp8_ptr + offsets, mask=mask, other=0) + + # Bitcast uint8 back to fp8 (FNUZ on gfx942, OCP elsewhere). + if use_fnuz: + x_fp8 = x_uint8.to(tl.float8e4b8, bitcast=True) + else: + x_fp8 = x_uint8.to(tl.float8e4nv, bitcast=True) + + # Convert fp8 to float32 for computation + x_float = x_fp8.to(tl.float32) + + # Load and decode UE8M0 scale + # UE8M0: scale = 2^(stored_value - 127) + encoded_scale = tl.load(token_scale_ptr + qblock_idx) + exponent = encoded_scale.to(tl.float32) - 127.0 + scale = tl.exp2(exponent) + + # Dequantize: bf16_value = fp8_value * scale + x_dequant = x_float * scale + + # Store as bf16 + tl.store(output_row_ptr + offsets, x_dequant.to(tl.bfloat16), mask=mask) + + # ========== Copy BF16 portion directly ========== + bf16_output_offset = fp8_dim # After 448 elements in output + + # Read bf16 from cache + bf16_cache_ptr = token_bf16_ptr.to(tl.pointer_type(tl.bfloat16)) + + # Process in chunks of 16 + for j in tl.static_range(bf16_dim // 16): + chunk_offsets = j * 16 + tl.arange(0, 16) + bf16_vals = tl.load(bf16_cache_ptr + chunk_offsets) + tl.store(output_row_ptr + bf16_output_offset + chunk_offsets, bf16_vals) + + +def dequantize_and_gather_k_cache_triton( + # [num_reqs, max_num_tokens, head_size] + out: torch.Tensor, + # [num_blocks, block_size, head_bytes] + k_cache: torch.Tensor, + # [num_reqs] + seq_lens: torch.Tensor, + # [num_reqs] + gather_lens: torch.Tensor | None, + # [num_reqs, max_blocks_per_seq] + block_table: torch.Tensor, + block_size: int, + offset: int, + use_fnuz: bool = False, +) -> None: + TOKEN_FP8_DIM = 448 + TOKEN_BF16_DIM = 64 + TOKEN_SCALE_DIM = 8 + QUANT_BLOCK_SIZE = 64 + FP8_MAX = 448.0 + TOKEN_DATA_SIZE = TOKEN_FP8_DIM + TOKEN_BF16_DIM * 2 + + num_reqs = seq_lens.shape[0] + NUM_WORKERS = 128 + _dequantize_and_gather_k_kernel[(num_reqs, NUM_WORKERS)]( + out, + out.stride(0), + out.stride(1), + k_cache, + seq_lens, + block_table, + offset, + gather_lens, + max_blocks_per_seq=block_table.shape[-1], + fp8_dim=TOKEN_FP8_DIM, + bf16_dim=TOKEN_BF16_DIM, + scale_dim=TOKEN_SCALE_DIM, + quant_block=QUANT_BLOCK_SIZE, + cache_block_size=block_size, + token_data_size=TOKEN_DATA_SIZE, + block_stride=k_cache.stride(0), + output_dim=512, + fp8_max=FP8_MAX, + n_quant_blocks=7, + use_fnuz=use_fnuz, + ) + + +def dequantize_and_gather_k_cache( + # [num_reqs, max_num_tokens, head_size] + out: torch.Tensor, + # [num_blocks, block_size, head_bytes] + k_cache: torch.Tensor, + # [num_reqs] + seq_lens: torch.Tensor, + # [num_reqs] + gather_lens: torch.Tensor | None, + # [num_reqs, max_blocks_per_seq] + block_table: torch.Tensor, + block_size: int, + offset: int, + use_fnuz: bool = False, +) -> None: + """Dequantize and gather a paged DSv4 K cache. + + ``use_fnuz`` MUST match the encoder of the specific cache being read: + ``False`` for ``compressed_k_cache`` (Triton encoder is OCP everywhere), + ``current_platform.is_fp8_fnuz()`` for ``swa_k_cache`` (C++ encoder + writes FNUZ on gfx942 and OCP on gfx950). + """ + if has_cutedsl(): + # lazily import, otherwise some tests fail due to CUDA driver init failure. + from vllm.models.deepseek_v4.nvidia.ops.dequant_gather_k_cutedsl import ( + dequantize_and_gather_k_cache_cutedsl, + ) + + dequantize_and_gather_k_cache_cutedsl( + out, k_cache, seq_lens, gather_lens, block_table, block_size, offset + ) + return + + dequantize_and_gather_k_cache_triton( + out, + k_cache, + seq_lens, + gather_lens, + block_table, + block_size, + offset, + use_fnuz=use_fnuz, + ) + + +def compute_global_topk_indices_and_lens( + topk_indices: torch.Tensor, + token_to_req_indices: torch.Tensor, + block_table: torch.Tensor, + block_size: int, + is_valid_token: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Map local topk indices to global KV cache slots and count valid entries. + + Fuses three operations into a single kernel: + 1. Block-table lookup (local index → global slot id) + 2. Valid-entry counting (topk_lens per token) + 3. Masking padding tokens to length 0 + """ + num_tokens = topk_indices.shape[0] + global_topk_indices = torch.empty_like(topk_indices) + topk_lens = torch.empty(num_tokens, dtype=torch.int32, device=topk_indices.device) + _compute_global_topk_indices_and_lens_kernel[(num_tokens,)]( + global_topk_indices, + global_topk_indices.stride(0), + topk_lens, + topk_indices, + topk_indices.stride(0), + topk_indices.shape[-1], + token_to_req_indices, + block_table, + block_table.stride(0), + block_size, + is_valid_token, + TRITON_BLOCK_SIZE=1024, + ) + return global_topk_indices, topk_lens + + +@triton.jit +def _compute_global_topk_indices_and_lens_kernel( + global_topk_indices_ptr, + global_topk_indices_stride: tl.constexpr, + topk_lens_ptr, + topk_indices_ptr, + topk_indices_stride: tl.constexpr, + topk: tl.constexpr, + token_to_req_indices_ptr, + block_table_ptr, + block_table_stride: tl.constexpr, + block_size: tl.constexpr, + is_valid_token_ptr, + TRITON_BLOCK_SIZE: tl.constexpr, +): + token_idx = tl.program_id(0) + is_valid_token = tl.load(is_valid_token_ptr + token_idx) + req_idx = tl.load(token_to_req_indices_ptr + token_idx) + + count = tl.zeros((), dtype=tl.int32) + for i in range(0, topk, TRITON_BLOCK_SIZE): + offset = i + tl.arange(0, TRITON_BLOCK_SIZE) + mask = offset < topk + + local_idx = tl.load( + topk_indices_ptr + token_idx * topk_indices_stride + offset, + mask=mask, + other=-1, + ) + is_valid = local_idx >= 0 + + block_indices = local_idx // block_size + block_numbers = tl.load( + block_table_ptr + req_idx * block_table_stride + block_indices, + mask=mask & is_valid, + ) + block_offsets = local_idx % block_size + + slot_ids = block_numbers * block_size + block_offsets + slot_ids = tl.where(is_valid, slot_ids, -1) + tl.store( + global_topk_indices_ptr + token_idx * global_topk_indices_stride + offset, + slot_ids, + mask=mask, + ) + count += tl.sum(is_valid.to(tl.int32), axis=0) + + # Zero out length for padding tokens. + tl.store(topk_lens_ptr + token_idx, tl.where(is_valid_token, count, 0)) + + +# FlashMLA sparse prefill asserts `params.topk % B_TOPK == 0` (see +# flashmla/csrc/sm100/prefill/sparse/fwd/head{64,128}/phase1.cuh). B_TOPK is +# 64 for the h_q=64 kernel and 128 for h_q=128; pad to 128 to satisfy both. +# The extra slots stay as -1 sentinels and `combined_lens` caps the valid +# range via `topk_length`, so padding is a no-op at kernel level. +_SPARSE_PREFILL_TOPK_ALIGNMENT = 128 + + +def combine_topk_swa_indices( + topk_indices: torch.Tensor, + query_start_loc: torch.Tensor, + seq_lens: torch.Tensor, + gather_lens: torch.Tensor, + window_size: int, + compress_ratio: int, + topk: int, + M: int, + N: int, + out: tuple[torch.Tensor, torch.Tensor] | None = None, + left_visible: torch.Tensor | None = None, + right_visible: torch.Tensor | None = None, + max_image_tokens: int = 0, +) -> tuple[torch.Tensor, torch.Tensor]: + num_tokens = topk_indices.shape[0] + # max_image_tokens widens the SWA column region for in-image + # bidirectional visibility; the width is fixed per model so the + # caller-provided workspace stays valid on image-free batches. + combined_topk = ( + (topk + window_size + max_image_tokens + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1) + // _SPARSE_PREFILL_TOPK_ALIGNMENT + * _SPARSE_PREFILL_TOPK_ALIGNMENT + ) + if out is None: + combined_indices = torch.full( + (num_tokens, combined_topk), + fill_value=-1, + dtype=torch.int32, + device=topk_indices.device, + ) + combined_lens = torch.empty( + num_tokens, dtype=torch.int32, device=topk_indices.device + ) + else: + combined_indices, combined_lens = out + + _COMBINE_TOPK_SWA_INDICES_KERNEL( + combined_indices, + combined_lens, + topk_indices, + query_start_loc, + seq_lens, + gather_lens, + M, + N, + TOP_K=topk, + COMPRESS_RATIO=compress_ratio, + WINDOW_SIZE=window_size, + left_visible=left_visible, + right_visible=right_visible, + max_image_tokens=max_image_tokens, + ) + return combined_indices, combined_lens + + +_COMBINE_TOPK_SWA_NUM_WORKERS = 256 + + +# Representative pointer alignment variants for Triton pointer specialization. +_COMBINE_TOPK_SWA_POINTER_INPUTS = zip_inputs( + dict( + topk_indices=True, + query_start_loc=True, + seq_lens=True, + gather_lens=True, + ), + dict( + topk_indices=True, + query_start_loc=False, + seq_lens=False, + gather_lens=True, + ), + dict( + topk_indices=False, + query_start_loc=False, + seq_lens=False, + gather_lens=False, + ), +) + + +def _hf_config_int(vllm_config: Any, name: str, default: int) -> int: + model_config = getattr(vllm_config, "model_config", None) + hf_config = getattr(model_config, "hf_config", None) + return int(getattr(hf_config, name, default) or default) + + +def _combine_topk_swa_warmup_inputs(vllm_config: Any) -> _WarmupInputRows: + """One warmup row per v4.1 layer type (compress ratio) in the model. + + Every layer slices the shared ``index_topk``-wide indices buffer, so the + padded width is the same for all rows; SWA-only layers (ratio 0) pass + ``TOP_K=0``. + """ + model_config = getattr(vllm_config, "model_config", None) + hf_config = getattr(model_config, "hf_config", None) + compress_ratios = getattr(hf_config, "compress_ratios", None) or [0] + topk = _hf_config_int(vllm_config, "index_topk", 0) + return zip_inputs( + *( + dict(compress_ratio=ratio, topk=topk if ratio > 0 else 0, topk_width=topk) + for ratio in sorted({int(ratio) for ratio in compress_ratios}) + ) + ) + + +def _scheduler_config_int(vllm_config: Any, name: str, default: int) -> int: + scheduler_config = getattr(vllm_config, "scheduler_config", None) + return int(getattr(scheduler_config, name, default) or default) + + +class CombineTopkSwaIndicesKernel( + VllmJitKernel["CombineTopkSwaIndicesKernel.CompileKey"] +): + @dataclass(frozen=True) + class CompileKey: + TOP_K: int + COMPRESS_RATIO: int + WINDOW_SIZE: int + IMAGE_WIDTH: int + PADDED_TOP_K: int + input_variant: TritonPointerInputVariant + + @staticmethod + @triton.jit( + do_not_specialize=[ + "combined_indices_stride", + "topk_indices_stride", + "M", + "N", + ] + ) + def kernel( + combined_indices_ptr, + combined_indices_stride, + combined_lens_ptr, + topk_indices_ptr, + topk_indices_stride, + query_start_loc_ptr, + seq_lens_ptr, + gather_lens_ptr, + left_visible_ptr, + right_visible_ptr, + M, + N, + TOP_K: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + WINDOW_SIZE: tl.constexpr, + IMAGE_WIDTH: tl.constexpr, + PADDED_TOP_K: tl.constexpr, + ): + batch_idx = tl.program_id(0) + worker_id = tl.program_id(1) + num_workers = tl.num_programs(1) + + # query_start_loc is a global tensor; rebase to chunk-local offsets + # by subtracting the chunk's starting value. + base = tl.load(query_start_loc_ptr) + query_start = tl.load(query_start_loc_ptr + batch_idx) - base + query_end = tl.load(query_start_loc_ptr + batch_idx + 1) - base + query_len = query_end - query_start + seq_len = tl.load(seq_lens_ptr + batch_idx) + gather_len = tl.load(gather_lens_ptr + batch_idx) + start_pos = seq_len - query_len + # The SWA portion of the gathered buffer starts from position + # (seq_len - gather_len), not position 0. We need this offset + # to correctly index into the gathered buffer. + gather_start = seq_len - gather_len + + for token_idx in range(query_start + worker_id, query_end, num_workers): + # topk_len is fully determined by the query token's absolute position: + # the indexer emits min((pos + 1) // compress_ratio, topk_tokens) + # valid entries. Caller passes TOP_K=0 for SWA-only layers to zero + # this out. + token_idx_in_query = token_idx - query_start + pos = start_pos + token_idx_in_query + if COMPRESS_RATIO > 0: + topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K) + else: + # SWA-only layers pass TOP_K=0; skip the division entirely + # (integer div by constexpr 0 is UB and yields garbage, which + # turns the store index below negative). + topk_len = 0 + if IMAGE_WIDTH > 0: + # In-image bidirectional visibility: the window starts up to + # max(left - (window - 1), 0) positions earlier and extends + # `right` positions past the query token (both 0 outside + # image spans, reducing to the plain causal window). + left = tl.load(left_visible_ptr + token_idx) + right = tl.load(right_visible_ptr + token_idx) + else: + left = 0 + right = 0 + left_add = tl.maximum(left - (WINDOW_SIZE - 1), 0) + swa_start = tl.maximum(pos - (WINDOW_SIZE - 1) - left_add, 0) + swa_len = pos + right - swa_start + 1 + + offset = tl.arange(0, PADDED_TOP_K) + mask = offset < topk_len + topk_indices = tl.load( + topk_indices_ptr + token_idx * topk_indices_stride + offset, + mask=mask, + ) + tl.store( + combined_indices_ptr + token_idx * combined_indices_stride + offset, + topk_indices + M * batch_idx, + mask=mask, + ) + # Index into gathered buffer: N + (position - gather_start) + # For positions [swa_start, pos + right], the buffer indices are: + # [N + swa_start - gather_start, N + pos + right - gather_start] + for i in range(0, WINDOW_SIZE + IMAGE_WIDTH, WINDOW_SIZE): + swa_offset = i + tl.arange(0, WINDOW_SIZE) + tl.store( + combined_indices_ptr + + token_idx * combined_indices_stride + + topk_len + + swa_offset, + M * batch_idx + N + swa_start + swa_offset - gather_start, + mask=swa_offset < swa_len, + ) + + combined_len = topk_len + swa_len + tl.store(combined_lens_ptr + token_idx, combined_len) + + def dispatch( # type: ignore[override] + self, + *, + topk_width: int, + topk_indices: bool, + query_start_loc: bool, + seq_lens: bool, + gather_lens: bool, + topk: int, + compress_ratio: int, + WINDOW_SIZE: int, + image_width: int = 0, + ) -> CompileKey: + padded_topk = next_power_of_2(topk_width) + input_variant = TritonPointerInputVariant.from_alignment( + topk_indices=topk_indices, + query_start_loc=query_start_loc, + seq_lens=seq_lens, + gather_lens=gather_lens, + ) + return self.CompileKey( + TOP_K=topk, + COMPRESS_RATIO=compress_ratio, + WINDOW_SIZE=WINDOW_SIZE, + IMAGE_WIDTH=image_width, + PADDED_TOP_K=padded_topk, + input_variant=input_variant, + ) + + def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]: + if _scheduler_config_int(vllm_config, "max_num_batched_tokens", 0) <= 0: + return [] + + window_size = _hf_config_int(vllm_config, "sliding_window", 128) + image_width = ( + _hf_config_int(vllm_config, "vision_max_n_token", 0) + if _hf_config_int(vllm_config, "vision_n_layers", 0) > 0 + else 0 + ) + # Warm both the plain-window variant (batches without image spans) + # and the in-image bidirectional variant. + image_widths = [0, image_width] if image_width > 0 else [0] + return self._trace_dispatch(self.dispatch)( + _combine_topk_swa_warmup_inputs(vllm_config), + _COMBINE_TOPK_SWA_POINTER_INPUTS, + WINDOW_SIZE=window_size, + image_width=image_widths, + ) + + def compile(self, compile_key: CompileKey) -> None: + warmup = getattr(self.kernel, "warmup", None) + assert warmup is not None + int32_ptr = TritonWarmupTensor(torch.int32) + input_variant = compile_key.input_variant + warmup( + int32_ptr, + 1, # do not specialize combined_indices_stride + int32_ptr, + input_variant.pointer("topk_indices", torch.int32), + 1, # do not specialize topk_indices_stride + input_variant.pointer("query_start_loc", torch.int32), + input_variant.pointer("seq_lens", torch.int32), + input_variant.pointer("gather_lens", torch.int32), + int32_ptr, + int32_ptr, + 1, # do not specialize M + 1, # do not specialize N + TOP_K=compile_key.TOP_K, + COMPRESS_RATIO=compile_key.COMPRESS_RATIO, + WINDOW_SIZE=compile_key.WINDOW_SIZE, + IMAGE_WIDTH=compile_key.IMAGE_WIDTH, + PADDED_TOP_K=compile_key.PADDED_TOP_K, + grid=(1, _COMBINE_TOPK_SWA_NUM_WORKERS), + ) + + def __call__( + self, + combined_indices: torch.Tensor, + combined_lens: torch.Tensor, + topk_indices: torch.Tensor, + query_start_loc: torch.Tensor, + seq_lens: torch.Tensor, + gather_lens: torch.Tensor, + M: int, + N: int, + *, + TOP_K: int, + COMPRESS_RATIO: int, + WINDOW_SIZE: int, + left_visible: torch.Tensor | None = None, + right_visible: torch.Tensor | None = None, + max_image_tokens: int = 0, + ) -> None: + num_reqs = seq_lens.shape[0] + has_image = left_visible is not None + image_width = max_image_tokens if has_image else 0 + self.kernel[(num_reqs, _COMBINE_TOPK_SWA_NUM_WORKERS)]( + combined_indices, + combined_indices.stride(0), + combined_lens, + topk_indices, + topk_indices.stride(0), + query_start_loc, + seq_lens, + gather_lens, + left_visible if has_image else topk_indices, + right_visible if has_image else topk_indices, + M, + N, + TOP_K=TOP_K, + COMPRESS_RATIO=COMPRESS_RATIO, + WINDOW_SIZE=WINDOW_SIZE, + IMAGE_WIDTH=image_width, + PADDED_TOP_K=next_power_of_2(topk_indices.shape[-1]), + ) + + +_COMBINE_TOPK_SWA_INDICES_KERNEL = CombineTopkSwaIndicesKernel() + + +def build_flashinfer_mixed_sparse_indices( + decode_swa_indices: torch.Tensor, + decode_compressed_indices: torch.Tensor | None, + decode_compressed_topk_lens: torch.Tensor | None, + prefill_topk_indices: torch.Tensor, + query_start_loc: torch.Tensor, + seq_lens: torch.Tensor, + token_to_req_indices: torch.Tensor, + swa_block_table: torch.Tensor, + swa_block_size: int, + compressed_block_table: torch.Tensor | None, + compressed_block_size: int, + window_size: int, + compress_ratio: int, + topk: int, + decode_compressed_indices_are_local: bool = False, + decode_is_valid_token: torch.Tensor | None = None, + swa_block_span: int | None = None, + compressed_block_span: int | None = None, + prefill_left_visible: torch.Tensor | None = None, + prefill_right_visible: torch.Tensor | None = None, + max_image_tokens: int = 0, +) -> tuple[torch.Tensor, torch.Tensor]: + """Build the FlashInfer DSV4 sparse-index matrix for decode-first batches. + + Produces ``sparse_indices`` of shape ``[num_tokens, swa_total_width + + padded_topk]`` (the first ``swa_total_width`` columns are SWA slot ids, the + rest are compressed/top-k slot ids) and ``sparse_topk_lens`` (active length + per token). Decode tokens read precomputed SWA/compressed indices; prefill + tokens derive their SWA window from the position and translate local + compressed indices to global slots via the block tables. + + When ``prefill_left_visible``/``prefill_right_visible`` are given (vision + variant), the SWA column region widens by ``max_image_tokens`` and prefill + tokens inside an image span get a bidirectionally widened window; decode + rows are padded with -1 across the extra columns. + """ + assert decode_swa_indices.dtype == torch.int32 + assert decode_swa_indices.dim() == 2 + swa_index_width = decode_swa_indices.shape[-1] + assert swa_index_width >= window_size + has_image = prefill_left_visible is not None + image_width = max_image_tokens if has_image else 0 + swa_total_width = swa_index_width + image_width + if has_image: + assert prefill_right_visible is not None + if decode_compressed_topk_lens is not None: + assert decode_compressed_topk_lens.dtype == torch.int32 + assert prefill_topk_indices.dtype == torch.int32 + assert prefill_topk_indices.dim() == 2 + assert query_start_loc.dtype == torch.int32 + assert seq_lens.dtype == torch.int32 + assert token_to_req_indices.dtype == torch.int32 + assert swa_block_table.dtype == torch.int32 + + num_decode_tokens = decode_swa_indices.shape[0] + num_prefill_tokens = prefill_topk_indices.shape[0] + num_tokens = num_decode_tokens + num_prefill_tokens + assert token_to_req_indices.shape[0] >= num_tokens + if decode_compressed_topk_lens is not None: + assert decode_compressed_topk_lens.shape[0] >= num_decode_tokens + + decode_compressed_topk = 0 + if decode_compressed_indices is None: + decode_compressed_indices = prefill_topk_indices + else: + assert decode_compressed_indices.dtype == torch.int32 + assert decode_compressed_indices.dim() == 2 + assert decode_compressed_indices.shape[0] == num_decode_tokens + decode_compressed_topk = decode_compressed_indices.shape[-1] + if decode_compressed_topk > 0 and decode_compressed_indices_are_local: + assert decode_is_valid_token is not None + assert decode_is_valid_token.dtype == torch.bool + assert decode_is_valid_token.shape[0] >= num_decode_tokens + else: + decode_is_valid_token = token_to_req_indices + + if compressed_block_table is None: + compressed_block_table = swa_block_table + assert compressed_block_table.dtype == torch.int32 + has_decode_compressed_lens = decode_compressed_topk_lens is not None + if decode_compressed_topk_lens is None: + decode_compressed_topk_lens = token_to_req_indices + + # The FlashInfer TRTLLM-gen sparse-MLA kernels require every per-token topk + # index row to start on a 16-byte boundary: the kernel loads the compressed + # indices with 128-bit (16-byte) vectorized loads, so a misaligned row would + # fault or read across rows. 16 bytes = 4 int32 indices, so round the topk + # width (and hence the row stride, since the SWA columns are fixed-width) up + # to a multiple of 4. The extra columns are filled with -1 (invalid) and bounded + # by ``sparse_topk_lens``, so padding never changes the attention result. + padded_topk = max(topk, decode_compressed_topk) + padded_topk = (padded_topk + 3) // 4 * 4 + sparse_indices = torch.empty( + (num_tokens, swa_total_width + padded_topk), + dtype=torch.int32, + device=decode_swa_indices.device, + ) + sparse_topk_lens = torch.empty( + num_tokens, dtype=torch.int32, device=decode_swa_indices.device + ) + if num_tokens == 0: + return sparse_indices, sparse_topk_lens + + window_block_size = triton.next_power_of_2(max(swa_index_width, 1)) + topk_block_size = triton.next_power_of_2(max(padded_topk, 1)) + max_block_size = max(window_block_size, topk_block_size) + num_warps = 4 if max_block_size >= 256 else 1 + + # block_span = page_stride / token_stride; == block_size (no-op) for unpacked KV. + swa_span = swa_block_size if swa_block_span is None else swa_block_span + compressed_span = ( + compressed_block_size + if compressed_block_span is None + else compressed_block_span + ) + _build_flashinfer_mixed_sparse_indices_kernel[(num_tokens,)]( + sparse_indices, + sparse_indices.stride(0), + sparse_topk_lens, + decode_swa_indices, + decode_swa_indices.stride(0), + decode_compressed_indices, + decode_compressed_indices.stride(0), + decode_compressed_topk_lens, + decode_is_valid_token, + prefill_topk_indices, + prefill_topk_indices.stride(0), + prefill_left_visible if has_image else token_to_req_indices, + prefill_right_visible if has_image else token_to_req_indices, + query_start_loc, + seq_lens, + token_to_req_indices, + swa_block_table, + swa_block_table.stride(0), + swa_block_size, + swa_span, + compressed_block_table, + compressed_block_table.stride(0), + compressed_block_size, + compressed_span, + NUM_DECODE_TOKENS=num_decode_tokens, + WINDOW_SIZE=window_size, + SWA_INDEX_WIDTH=swa_index_width, + IMAGE_WIDTH=image_width, + COMPRESS_RATIO=compress_ratio, + TOP_K=topk, + PADDED_TOP_K=padded_topk, + PREFILL_TOPK_STRIDE=prefill_topk_indices.shape[-1], + DECODE_COMPRESSED_TOPK=decode_compressed_topk, + DECODE_COMPRESSED_INDICES_ARE_LOCAL=decode_compressed_indices_are_local, + HAS_DECODE_COMPRESSED_LENS=has_decode_compressed_lens, + WINDOW_BLOCK_SIZE=window_block_size, + TOPK_BLOCK_SIZE=topk_block_size, + num_warps=num_warps, + ) + return sparse_indices, sparse_topk_lens + + +@triton.jit +def _remap_flashinfer_index(values, block_size, block_span): + # FlashInfer's DSv4 kernel indexes sparse KV by physical token stride, so + # packed pages (#44577) need block*block_size+off -> block*block_span+off. + # TODO: remove once flashinfer-ai/flashinfer#3856 is fixed. + is_valid = values >= 0 + safe_values = tl.where(is_valid, values, 0) + values = (safe_values // block_size) * block_span + values += safe_values % block_size + return tl.where(is_valid, values, -1) + + +@triton.jit( + do_not_specialize=[ + "sparse_indices_stride", + "decode_swa_stride", + "decode_compressed_stride", + "prefill_topk_stride", + "swa_block_table_stride", + "swa_block_size", + "swa_block_span", + "compressed_block_table_stride", + "compressed_block_size", + "compressed_block_span", + "NUM_DECODE_TOKENS", + "PREFILL_TOPK_STRIDE", + ] +) +def _build_flashinfer_mixed_sparse_indices_kernel( + sparse_indices_ptr, + sparse_indices_stride, + sparse_topk_lens_ptr, + decode_swa_indices_ptr, + decode_swa_stride, + decode_compressed_indices_ptr, + decode_compressed_stride, + decode_compressed_topk_lens_ptr, + decode_is_valid_token_ptr, + prefill_topk_indices_ptr, + prefill_topk_stride, + left_visible_ptr, + right_visible_ptr, + query_start_loc_ptr, + seq_lens_ptr, + token_to_req_indices_ptr, + swa_block_table_ptr, + swa_block_table_stride, + swa_block_size, + swa_block_span, + compressed_block_table_ptr, + compressed_block_table_stride, + compressed_block_size, + compressed_block_span, + NUM_DECODE_TOKENS, + WINDOW_SIZE: tl.constexpr, + SWA_INDEX_WIDTH: tl.constexpr, + IMAGE_WIDTH: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + TOP_K: tl.constexpr, + PADDED_TOP_K: tl.constexpr, + PREFILL_TOPK_STRIDE, + DECODE_COMPRESSED_TOPK: tl.constexpr, + DECODE_COMPRESSED_INDICES_ARE_LOCAL: tl.constexpr, + HAS_DECODE_COMPRESSED_LENS: tl.constexpr, + WINDOW_BLOCK_SIZE: tl.constexpr, + TOPK_BLOCK_SIZE: tl.constexpr, +): + token_idx = tl.program_id(0) + # Total SWA column count; > SWA_INDEX_WIDTH only for in-image + # bidirectional visibility (vision variant), where the extra columns are + # -1-padded for decode rows. + SWA_TOTAL_WIDTH: tl.constexpr = SWA_INDEX_WIDTH + IMAGE_WIDTH + + if token_idx < NUM_DECODE_TOKENS: + for i in range(0, SWA_TOTAL_WIDTH, WINDOW_BLOCK_SIZE): + offset = i + tl.arange(0, WINDOW_BLOCK_SIZE) + mask = offset < SWA_TOTAL_WIDTH + values = tl.load( + decode_swa_indices_ptr + token_idx * decode_swa_stride + offset, + mask=offset < SWA_INDEX_WIDTH, + other=-1, + ) + values = _remap_flashinfer_index(values, swa_block_size, swa_block_span) + tl.store( + sparse_indices_ptr + token_idx * sparse_indices_stride + offset, + values, + mask=mask, + ) + + compressed_len = tl.zeros((), dtype=tl.int32) + for i in range(0, PADDED_TOP_K, TOPK_BLOCK_SIZE): + offset = i + tl.arange(0, TOPK_BLOCK_SIZE) + mask = offset < PADDED_TOP_K + values = tl.load( + decode_compressed_indices_ptr + + token_idx * decode_compressed_stride + + offset, + mask=offset < DECODE_COMPRESSED_TOPK, + other=-1, + ) + if DECODE_COMPRESSED_INDICES_ARE_LOCAL: + token_valid = tl.load(decode_is_valid_token_ptr + token_idx) + is_valid = values >= 0 + req_idx = tl.load(token_to_req_indices_ptr + token_idx) + block_indices = values // compressed_block_size + block_numbers = tl.load( + compressed_block_table_ptr + + req_idx * compressed_block_table_stride + + block_indices, + mask=mask & is_valid, + other=-1, + ) + block_offsets = values % compressed_block_size + values = block_numbers * compressed_block_size + block_offsets + values = tl.where(is_valid, values, -1) + compressed_len += tl.sum((is_valid & token_valid).to(tl.int32), axis=0) + values = _remap_flashinfer_index( + values, compressed_block_size, compressed_block_span + ) + tl.store( + sparse_indices_ptr + + token_idx * sparse_indices_stride + + SWA_TOTAL_WIDTH + + offset, + values, + mask=mask, + ) + + if DECODE_COMPRESSED_TOPK == 0: + compressed_len = tl.zeros((), dtype=tl.int32) + elif not DECODE_COMPRESSED_INDICES_ARE_LOCAL: + if HAS_DECODE_COMPRESSED_LENS: + compressed_len = tl.load(decode_compressed_topk_lens_ptr + token_idx) + else: + compressed_len = tl.full((), DECODE_COMPRESSED_TOPK, dtype=tl.int32) + + tl.store(sparse_topk_lens_ptr + token_idx, SWA_TOTAL_WIDTH + compressed_len) + return + + prefill_idx = token_idx - NUM_DECODE_TOKENS + req_idx = tl.load(token_to_req_indices_ptr + token_idx) + query_start = tl.load(query_start_loc_ptr + req_idx) + query_end = tl.load(query_start_loc_ptr + req_idx + 1) + query_len = query_end - query_start + seq_len = tl.load(seq_lens_ptr + req_idx) + start_pos = seq_len - query_len + token_idx_in_query = token_idx - query_start + pos = start_pos + token_idx_in_query + if IMAGE_WIDTH > 0: + # In-image bidirectional visibility: window starts up to + # max(left - (window - 1), 0) earlier and extends `right` past pos. + left = tl.load(left_visible_ptr + token_idx) + right = tl.load(right_visible_ptr + token_idx) + else: + left = 0 + right = 0 + left_add = tl.maximum(left - (WINDOW_SIZE - 1), 0) + swa_start_pos = tl.maximum(pos - (WINDOW_SIZE - 1) - left_add, 0) + swa_len = pos + right - swa_start_pos + 1 + if COMPRESS_RATIO > 0: + topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K) + else: + # SWA-only layers (ratio 0): no indexer topk; div by constexpr 0 is UB. + topk_len = 0 + + for i in range(0, SWA_TOTAL_WIDTH, WINDOW_BLOCK_SIZE): + offset = i + tl.arange(0, WINDOW_BLOCK_SIZE) + mask = offset < SWA_TOTAL_WIDTH + pos_offset = swa_start_pos + offset + block_indices = pos_offset // swa_block_size + block_numbers = tl.load( + swa_block_table_ptr + req_idx * swa_block_table_stride + block_indices, + mask=mask & (offset < swa_len), + other=-1, + ) + block_offsets = pos_offset % swa_block_size + slot_ids = block_numbers * swa_block_size + block_offsets + slot_ids = tl.where(offset < swa_len, slot_ids, -1) + slot_ids = _remap_flashinfer_index(slot_ids, swa_block_size, swa_block_span) + tl.store( + sparse_indices_ptr + token_idx * sparse_indices_stride + offset, + slot_ids, + mask=mask, + ) + + for i in range(0, PADDED_TOP_K, TOPK_BLOCK_SIZE): + offset = i + tl.arange(0, TOPK_BLOCK_SIZE) + mask = offset < PADDED_TOP_K + local_idx = tl.load( + prefill_topk_indices_ptr + prefill_idx * prefill_topk_stride + offset, + mask=(offset < PREFILL_TOPK_STRIDE) & (offset < topk_len), + other=-1, + ) + is_valid = local_idx >= 0 + block_indices = local_idx // compressed_block_size + block_numbers = tl.load( + compressed_block_table_ptr + + req_idx * compressed_block_table_stride + + block_indices, + mask=mask & is_valid, + other=-1, + ) + block_offsets = local_idx % compressed_block_size + slot_ids = block_numbers * compressed_block_size + block_offsets + slot_ids = tl.where((offset < topk_len) & is_valid, slot_ids, -1) + slot_ids = _remap_flashinfer_index( + slot_ids, compressed_block_size, compressed_block_span + ) + tl.store( + sparse_indices_ptr + + token_idx * sparse_indices_stride + + SWA_TOTAL_WIDTH + + offset, + slot_ids, + mask=mask, + ) + + tl.store(sparse_topk_lens_ptr + token_idx, SWA_TOTAL_WIDTH + topk_len) diff --git a/vllm/models/deepseek_v4_1/common/ops/fused_compress_quant_cache.py b/vllm/models/deepseek_v4_1/common/ops/fused_compress_quant_cache.py new file mode 100644 index 0000000000..5950c4b6ba --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/ops/fused_compress_quant_cache.py @@ -0,0 +1,383 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""V4.1 state saving/compression and independently schedulable cache insertion.""" + +import torch + +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton + +if current_platform.is_rocm(): + from vllm.platforms.rocm import _ON_GFX950 +else: + _ON_GFX950 = False + +# The ring and raw rows a ratio-2 request program pools are not adjacent, so +# reading them as one tile means joining two pointers. ROCm's Triton fails to +# legalize `tt.join` on pointers, so there the two rows are loaded separately. +_JOIN_ROW_PTRS = not current_platform.is_rocm() + + +def fused_save_compress_norm( + kv_score: torch.Tensor, + positions: torch.Tensor, + state_cache: torch.Tensor | None, + slot_mapping: torch.Tensor, + query_start_loc: torch.Tensor | None, + token_to_req_indices: torch.Tensor | None, + rms_norm_weight: torch.Tensor, + rms_norm_eps: float, + compress_ratio: int, + latent_out: torch.Tensor, +) -> None: + """Pool each closed group into a normalized BF16 latent; save FP32 states. + + The latent feeds the main-cache insert and the indexer K path, which the + attention layer schedules on separate streams. + + Ratio 2 keeps one ring block per request holding the open group's rows: + position ``p`` lives in row ``p % capacity`` and ``slot_mapping`` encodes + ``block * capacity + p % capacity``. The grid has one program per request + followed by one per pair of packed tokens. A request program handles the + group that the chunk's first token closes with its predecessor's ring row, + then stores the chunk's last ``capacity`` rows to the ring; because the + same program does both, ring reads and writes never race. A pair program + handles the group that ends inside its pair, reading both rows from the + raw input. Ratio 1 has no ring and one program per token; ``slot_mapping`` + then only marks valid tokens. + + Args: + kv_score: FP32 [tokens, 512] for CR1, [tokens, 1024] for CR2. + positions: Absolute positions of the packed request tokens. + state_cache: Ring FP32 [blocks, capacity, 1024] KV/score states (CR2). + slot_mapping: Ring slots (CR2) or main-cache slots (CR1). + query_start_loc: [num_reqs + 1] token offsets of each request's chunk. + token_to_req_indices: Request indices for the packed token rows. + rms_norm_weight: BF16 [512] normalization weight. + rms_norm_eps: RMSNorm epsilon. + compress_ratio: Group size, either 1 or 2. + latent_out: BF16 [tokens, 512], written only at valid group boundaries. + """ + assert compress_ratio in (1, 2) + assert kv_score.dtype == torch.float32 + assert kv_score.shape[1] == 512 * compress_ratio and kv_score.stride(1) == 1 + assert latent_out.shape == (kv_score.shape[0], 512) + assert latent_out.is_contiguous() and latent_out.dtype == torch.bfloat16 + assert positions.is_contiguous() and slot_mapping.is_contiguous() + # Rows stay 64-byte aligned, as the kernel's tl.multiple_of hint promises. + assert kv_score.stride(0) % 16 == 0 + if compress_ratio == 2: + assert state_cache is not None and query_start_loc is not None + assert token_to_req_indices is not None + assert query_start_loc.is_contiguous() + assert token_to_req_indices.is_contiguous() + assert state_cache.dtype == torch.float32 + assert state_cache.shape[2] == 1024 and state_cache.stride(2) == 1 + assert state_cache.stride(1) % 16 == 0 + state_stride, state_row_stride, state_block = ( + state_cache.stride(0), + state_cache.stride(1), + state_cache.shape[1], + ) + num_reqs = query_start_loc.numel() - 1 + else: + state_cache = query_start_loc = token_to_req_indices = None + state_stride = state_row_stride = state_block = 1 + num_reqs = 0 + num_tokens = slot_mapping.numel() + assert num_tokens <= min(kv_score.shape[0], positions.numel()) + if num_tokens == 0: + return + grid = num_reqs + triton.cdiv(num_tokens, compress_ratio) + _fused_save_compress_norm_kernel[(grid,)]( + kv_score, + positions, + state_cache, + slot_mapping, + query_start_loc, + token_to_req_indices, + rms_norm_weight, + latent_out, + num_tokens, + num_reqs, + RAW_STRIDE=kv_score.stride(0), + STATE_STRIDE=state_stride, + STATE_ROW_STRIDE=state_row_stride, + STATE_BLOCK=state_block, + COMPRESS_RATIO=compress_ratio, + EPS=rms_norm_eps, + JOIN_ROW_PTRS=_JOIN_ROW_PTRS, + num_warps=4, + **({"launch_pdl": False} if current_platform.is_cuda() else {}), + ) + + +@triton.jit(do_not_specialize=["num_tokens", "num_reqs"]) +def _fused_save_compress_norm_kernel( + raw, + positions, + state, + state_slots, + query_start_loc, + req_ids, + norm_weight, + latent, + num_tokens, + num_reqs, + RAW_STRIDE: tl.constexpr, + STATE_STRIDE: tl.constexpr, + STATE_ROW_STRIDE: tl.constexpr, + STATE_BLOCK: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + EPS: tl.constexpr, + JOIN_ROW_PTRS: tl.constexpr, +): + pid = tl.program_id(0) + d = tl.arange(0, 512) + + if COMPRESS_RATIO == 2: # noqa: SIM102 (constexpr branch, then runtime) + if pid < num_reqs: + # Request program: the group closed by the chunk's first token, + # then the ring tail store. + start = tl.load(query_start_loc + pid) + end = tl.load(query_start_loc + pid + 1) + if start >= end: + return + state_slot = tl.load(state_slots + start) + if state_slot < 0: + return + position = tl.load(positions + start) + if (position + 1) % 2 == 0: + ring = state + (state_slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE + prev = ring + ((position - 1) % STATE_BLOCK) * STATE_ROW_STRIDE + current = raw + start.to(tl.int64) * RAW_STRIDE + if JOIN_ROW_PTRS: + # Joining pointers hides row alignment from Triton; restate it. + rows = tl.multiple_of(tl.join(prev, current)[:, None], (16, 16)) + kv = tl.load(rows + d[None, :]) + score = tl.load(rows + 512 + d[None, :]) + # Every lane has read the ring before the tail store below + # writes it. + tl.debug_barrier() + pooled = tl.sum(kv * tl.softmax(score, 0), 0) + else: + kv_prev = tl.load(prev + d) + score_prev = tl.load(prev + 512 + d) + kv_current = tl.load(current + d) + score_current = tl.load(current + 512 + d) + # Every lane has read the ring before the tail store below + # writes it. + tl.debug_barrier() + peak = tl.maximum(score_prev, score_current) + weight_prev = tl.exp(score_prev - peak) + weight_current = tl.exp(score_current - peak) + pooled = (kv_prev * weight_prev + kv_current * weight_current) / ( + weight_prev + weight_current + ) + _store_latent(pooled, start, norm_weight, latent, EPS) + num_rows = tl.minimum(end - start, STATE_BLOCK) + for k in tl.range(0, num_rows): + token = end - num_rows + k + slot = tl.load(state_slots + token) + if slot >= 0: + row = ( + state + + (slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE + + (slot % STATE_BLOCK) * STATE_ROW_STRIDE + ) + src = raw + token.to(tl.int64) * RAW_STRIDE + tl.store(row + d, tl.load(src + d)) + tl.store(row + 512 + d, tl.load(src + 512 + d)) + return + + # Group program: one token (ratio 1) or the token of the pair that ends + # a group (ratio 2). A chunk's first token belongs to its request program. + t = (pid - num_reqs) * COMPRESS_RATIO + if COMPRESS_RATIO == 2: + t += (tl.load(positions + t) + 1) % 2 + state_slot = tl.load(state_slots + t, t < num_tokens, other=-1) + if state_slot < 0: + return + if COMPRESS_RATIO == 1: + pooled = tl.load(raw + t.to(tl.int64) * RAW_STRIDE + d) + else: + if t == tl.load(query_start_loc + tl.load(req_ids + t)): + return + rows = raw + (t.to(tl.int64) - 1 + tl.arange(0, 2)[:, None]) * RAW_STRIDE + kv = tl.load(rows + d[None, :]) + score = tl.load(rows + 512 + d[None, :]) + pooled = tl.sum(kv * tl.softmax(score, 0), 0) + _store_latent(pooled, t, norm_weight, latent, EPS) + + +@triton.jit +def _store_latent(pooled, t, norm_weight, latent, EPS: tl.constexpr): + d = tl.arange(0, 512) + weight = tl.load(norm_weight + d).to(tl.float32) + variance = tl.sum(pooled * pooled, 0) / 512 + normed = pooled * tl.rsqrt(variance + EPS) * weight + tl.store(latent + t.to(tl.int64) * 512 + d, normed.to(tl.bfloat16)) + + +def rope_quant_insert( + latent: torch.Tensor, + positions: torch.Tensor, + cos_sin_cache: torch.Tensor, + kv_cache: torch.Tensor, + slot_mapping: torch.Tensor, + compress_ratio: int, + fp8_scale: torch.Tensor | None = None, +) -> None: + """Apply GPT-J RoPE and publish a latent to the compressed KV cache. + + The BF16 latent supplies both NoPE quantization and RoPE input. It is read + only for valid slots at group boundaries. The cache dtype selects the + layout: ``uint8`` is the fp8_ds_mla paged layout (576 value bytes and eight + segregated UE8M0 scale bytes per token, including one zero padding scale); + ``bfloat16`` and ``float8_e4m3fn`` are the plain [448 NoPE | 64 RoPE] rows + read by FlashInfer, the latter scaled by the per-tensor ``fp8_scale``. + """ + assert compress_ratio in (1, 2) + assert latent.shape[1] == 512 and latent.dtype == torch.bfloat16 + assert latent.is_contiguous() + num_tokens = slot_mapping.numel() + assert num_tokens <= min(latent.shape[0], positions.numel()) + if num_tokens == 0: + return + launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {} + if kv_cache.dtype == torch.uint8: + assert kv_cache.shape[-1] == 584 + _rope_quant_insert_kernel[(num_tokens,)]( + latent, + positions, + cos_sin_cache, + kv_cache, + slot_mapping, + COS_STRIDE=cos_sin_cache.stride(0), + CACHE_STRIDE=kv_cache.stride(0), + CACHE_BLOCK=kv_cache.shape[1], + COMPRESS_RATIO=compress_ratio, + SANITIZE_CACHE_NANS=_ON_GFX950, + num_warps=4, + **launch_kwargs, + ) + return + + assert kv_cache.dtype in (torch.bfloat16, torch.float8_e4m3fn) + assert kv_cache.shape[-1] == 512 and kv_cache.stride(-1) == 1 + store_fp8 = kv_cache.dtype == torch.float8_e4m3fn + if store_fp8: + assert fp8_scale is not None and fp8_scale.numel() == 1 + assert fp8_scale.dtype == torch.float32 + _rope_plain_insert_kernel[(num_tokens,)]( + latent, + positions, + cos_sin_cache, + kv_cache, + slot_mapping, + fp8_scale if store_fp8 else None, + COS_STRIDE=cos_sin_cache.stride(0), + CACHE_STRIDE=kv_cache.stride(0), + ROW_STRIDE=kv_cache.stride(1), + CACHE_BLOCK=kv_cache.shape[1], + COMPRESS_RATIO=compress_ratio, + STORE_FP8=store_fp8, + num_warps=4, + **launch_kwargs, + ) + + +@triton.jit +def _rope_quant_insert_kernel( + latent, + positions, + cos_sin, + cache, + cache_slots, + COS_STRIDE: tl.constexpr, + CACHE_STRIDE: tl.constexpr, + CACHE_BLOCK: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + SANITIZE_CACHE_NANS: tl.constexpr, +): + t = tl.program_id(0) + slot = tl.load(cache_slots + t) + if slot < 0: + return + position = tl.load(positions + t) + if (position + 1) % COMPRESS_RATIO != 0: + return + d = tl.arange(0, 512) + normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32) + page = cache + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE + values = page + (slot % CACHE_BLOCK) * 576 + scales = page + CACHE_BLOCK * 576 + (slot % CACHE_BLOCK) * 8 + + quant = tl.reshape(normed, (8, 64)) + amax = tl.maximum(tl.max(tl.abs(quant), 1), 1e-4) + exponent = tl.ceil(tl.log2(amax * (1.0 / 448.0))) + scaled = quant * tl.reshape(tl.exp2(-exponent), (8, 1)) + fp8 = tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv) + packed = tl.reshape(fp8.to(tl.uint8, bitcast=True), (512,)) + tl.store(values + d, packed, d < 448) + s = tl.arange(0, 8) + max_encoded: tl.constexpr = 254.0 if SANITIZE_CACHE_NANS else 255.0 + encoded = tl.minimum(tl.maximum(exponent + 127.0, 0.0), max_encoded) + tl.store(scales + s, encoded.to(tl.uint8), s < 7) + tl.store(scales + 7, tl.full((), 0, tl.uint8)) + + even, odd = tl.split(tl.reshape(normed, (256, 2))) + pair = tl.arange(0, 256) - 224 + cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE + c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32) + s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32) + rotated = tl.interleave(even * c - odd * s, odd * c + even * s) + if SANITIZE_CACHE_NANS: + rotated = tl.where(rotated == rotated, rotated, 0.0) + rope_dst = (values + 448).to(tl.pointer_type(tl.bfloat16)) + tl.store(rope_dst + d - 448, rotated.to(tl.bfloat16), d >= 448) + + +@triton.jit +def _rope_plain_insert_kernel( + latent, + positions, + cos_sin, + cache, + cache_slots, + fp8_scale, + COS_STRIDE: tl.constexpr, + CACHE_STRIDE: tl.constexpr, + ROW_STRIDE: tl.constexpr, + CACHE_BLOCK: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + STORE_FP8: tl.constexpr, +): + t = tl.program_id(0) + slot = tl.load(cache_slots + t) + if slot < 0: + return + position = tl.load(positions + t) + if (position + 1) % COMPRESS_RATIO != 0: + return + d = tl.arange(0, 512) + normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32) + + # NoPE pairs load (cos, sin) = (1, 0), so the rotation is the identity there. + even, odd = tl.split(tl.reshape(normed, (256, 2))) + pair = tl.arange(0, 256) - 224 + cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE + c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32) + s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32) + row = tl.interleave(even * c - odd * s, odd * c + even * s).to(tl.bfloat16) + + dst = ( + cache + + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE + + (slot % CACHE_BLOCK) * ROW_STRIDE + ) + if STORE_FP8: + scaled = row.to(tl.float32) * (1.0 / tl.load(fp8_scale)) + tl.store(dst + d, tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv)) + else: + tl.store(dst + d, row) diff --git a/vllm/models/deepseek_v4_1/common/ops/indexer_k_store.py b/vllm/models/deepseek_v4_1/common/ops/indexer_k_store.py new file mode 100644 index 0000000000..c4bd98b9e9 --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/ops/indexer_k_store.py @@ -0,0 +1,253 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Indexer K production for DeepSeek V4.1 kv-source layers. + +In v4.1 the index key is derived from the *main* compressor's latent: +``k = k_norm(wk(latent))`` (reference model.py Indexer.forward), then RoPE'd +at the group's first-token position and MXFP4/FP8-quantized into the paged +indexer K cache. The ``wk(latent)`` GEMM runs in torch; this kernel fuses the +remaining k_norm → RoPE → quant → paged store, one program per token. + +Unlike the legacy (v4.0) indexer path there is no per-token pooling from a +compressor state cache: the latent already stands for a whole group, so only +group-boundary tokens ``(position + 1) % compress_ratio == 0`` produce a key. +""" + +import torch + +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton + +from . import MXFP4_BLOCK_SIZE, _fp32x2_to_fp4x2 + +# ROCm tiled ("SHUFFLE") indexer K value layout, mirroring +# indexer_k_quant_and_cache_triton's defaults: 16 positions x 16 bytes. +_BLOCK_TILE_SIZE = 16 +_HEAD_TILE_SIZE = 16 + + +def indexer_k_norm_rope_store( + k_pre: torch.Tensor, + positions: torch.Tensor, + cos_sin_cache: torch.Tensor, + rms_norm_weight: torch.Tensor, + rms_norm_eps: float, + k_cache: torch.Tensor, + kv_slot_mapping: torch.Tensor, + compress_ratio: int, + use_fp4_cache: bool, +) -> None: + """k_norm → RoPE → quant → paged store for indexer keys. + + Args: + k_pre: [num_tokens, 128] bf16, the ``wk(latent)`` projection. Only + group-boundary rows are read. + positions: [num_tokens] int64 token positions. + cos_sin_cache: [max_pos, rope_head_dim] GPT-J layout (cos half, then + sin half), from the layer's compress-RoPE instance. + rms_norm_weight: [128] k_norm weight. + k_cache: uint8 paged indexer cache [num_blocks, block_size, row_bytes]. + kv_slot_mapping: [num_tokens] slots in the indexer cache (-1 = skip). + compress_ratio: group size; keys are emitted at group boundaries. + use_fp4_cache: MXFP4 (2 nibbles/byte + ue8m0 per 32) when True, else + per-token FP8 with a single fp32 scale. + """ + num_tokens = kv_slot_mapping.numel() + assert k_pre.ndim == 2 and k_pre.shape[1] == 128 + assert k_pre.dtype == torch.bfloat16 and k_pre.stride(1) == 1 + assert num_tokens <= k_pre.shape[0] and num_tokens <= positions.numel() + assert compress_ratio in (1, 2) + if num_tokens == 0: + return + + head_dim = k_pre.shape[1] + if use_fp4_cache: + token_stride = head_dim // 2 + scale_dim = head_dim // MXFP4_BLOCK_SIZE + else: + token_stride = head_dim + scale_dim = 4 # single float32 scale + + # ROCm reads this cache back with the 16x16-tiled ("SHUFFLE") value + # layout: cp_gather_indexer_k_quant_cache_triton on prefill and aiter's + # deepgemm_fp8_paged_mqa_logits(Preshuffle=True) on decode both select it + # from ``block_size > 1``, matching the v4.0 writer + # (indexer_k_quant_and_cache_triton). Writing row-major here would hand + # both readers permuted key bytes. + block_size = k_cache.shape[1] + shuffle = current_platform.is_rocm() and block_size > 1 + if shuffle: + if use_fp4_cache: + raise NotImplementedError( + "MXFP4 indexer K cache has no tiled ROCm layout; " + "the ROCm readers only implement the FP8 one." + ) + if block_size % _BLOCK_TILE_SIZE != 0 or head_dim % _HEAD_TILE_SIZE != 0: + raise ValueError( + f"ROCm tiled indexer K cache needs block_size " + f"({block_size}) % {_BLOCK_TILE_SIZE} == 0 and head_dim " + f"({head_dim}) % {_HEAD_TILE_SIZE} == 0." + ) + + launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {} + _indexer_k_norm_rope_quant_store_kernel[(num_tokens,)]( + k_pre, + k_pre.stride(0), + positions, + rms_norm_weight, + rms_norm_eps, + cos_sin_cache, + cos_sin_cache.stride(0), + k_cache, + kv_slot_mapping, + k_cache.shape[1], + HEAD_SIZE=head_dim, + ROPE_HEAD_DIM=64, + COMPRESS_RATIO=compress_ratio, + TOKEN_STRIDE=token_stride, + SCALE_DIM=scale_dim, + KV_BLOCK_STRIDE=k_cache.stride(0), + FP8_MAX=448.0, + USE_FP4=use_fp4_cache, + SHUFFLE=shuffle, + BLOCK_TILE_SIZE=_BLOCK_TILE_SIZE, + HEAD_TILE_SIZE=_HEAD_TILE_SIZE, + num_warps=1, + **launch_kwargs, + ) + + +@triton.jit +def _indexer_k_norm_rope_quant_store_kernel( + k_pre_ptr, + k_pre_stride, + positions_ptr, + rms_norm_weight_ptr, + rms_norm_eps, + cos_sin_cache_ptr, + cos_sin_stride, + k_cache_ptr, + kv_slot_mapping_ptr, + kv_cache_block_size, + HEAD_SIZE: tl.constexpr, + ROPE_HEAD_DIM: tl.constexpr, + COMPRESS_RATIO: tl.constexpr, + TOKEN_STRIDE: tl.constexpr, + SCALE_DIM: tl.constexpr, + KV_BLOCK_STRIDE: tl.constexpr, + FP8_MAX: tl.constexpr, + USE_FP4: tl.constexpr, + SHUFFLE: tl.constexpr, + BLOCK_TILE_SIZE: tl.constexpr, + HEAD_TILE_SIZE: tl.constexpr, +): + token_idx = tl.program_id(0) + + kv_slot_idx = tl.load(kv_slot_mapping_ptr + token_idx) + if kv_slot_idx < 0: + return + position = tl.load(positions_ptr + token_idx) + # Only the last token of a group publishes that group's index key. + if (position + 1) % COMPRESS_RATIO != 0: + return + + block = tl.arange(0, HEAD_SIZE) + + # ── k_norm (fp32 throughout, bf16 roundtrip like the reference) ──── + k = tl.load(k_pre_ptr + token_idx * k_pre_stride + block).to(tl.float32) + rms_w = tl.load(rms_norm_weight_ptr + block).to(tl.float32) + variance = tl.sum(k * k, axis=0) / HEAD_SIZE + k = (k * tl.rsqrt(variance + rms_norm_eps) * rms_w).to(tl.bfloat16) + k = k.to(tl.float32) + + # ── Register-based GPT-J forward RoPE in fp32 ───────────────────── + # A latent stands for the first token of its group, so group j takes + # position j * compress_ratio. + NUM_PAIRS: tl.constexpr = HEAD_SIZE // 2 + NOPE_HEAD_DIM: tl.constexpr = HEAD_SIZE - ROPE_HEAD_DIM + NOPE_PAIRS: tl.constexpr = NOPE_HEAD_DIM // 2 + HALF_ROPE: tl.constexpr = ROPE_HEAD_DIM // 2 + + even, odd = tl.split(tl.reshape(k, (NUM_PAIRS, 2))) # each [NUM_PAIRS] + pair_idx = tl.arange(0, NUM_PAIRS) + rope_pair_local = pair_idx - NOPE_PAIRS + is_rope_pair = rope_pair_local >= 0 + cs_idx = tl.maximum(rope_pair_local, 0) + + compressed_pos = (position // COMPRESS_RATIO) * COMPRESS_RATIO + cache_base = cos_sin_cache_ptr + compressed_pos * cos_sin_stride + cos_v = tl.load(cache_base + cs_idx, mask=is_rope_pair, other=1.0) + sin_v = tl.load(cache_base + HALF_ROPE + cs_idx, mask=is_rope_pair, other=0.0) + + new_even = even * cos_v - odd * sin_v + new_odd = odd * cos_v + even * sin_v + + # bf16 roundtrip for parity with the reference / Q-side kernel numerics. + new_even = new_even.to(tl.bfloat16).to(tl.float32) + new_odd = new_odd.to(tl.bfloat16).to(tl.float32) + + # ── Paged cache pointers (segregated: values first, then scales) ── + kv_block_idx = kv_slot_idx // kv_cache_block_size + kv_pos_in_block = kv_slot_idx % kv_cache_block_size + cache_block_ptr = k_cache_ptr + kv_block_idx.to(tl.int64) * KV_BLOCK_STRIDE + if SHUFFLE: + # [block_size // BT, HEAD_SIZE // HT, BT, HT] value tiles. + val_ptr = ( + cache_block_ptr + + (kv_pos_in_block // BLOCK_TILE_SIZE) * BLOCK_TILE_SIZE * TOKEN_STRIDE + + (kv_pos_in_block % BLOCK_TILE_SIZE) * HEAD_TILE_SIZE + ) + else: + val_ptr = cache_block_ptr + kv_pos_in_block * TOKEN_STRIDE + scale_ptr = ( + cache_block_ptr + + kv_cache_block_size * TOKEN_STRIDE + + kv_pos_in_block * SCALE_DIM + ) + + if USE_FP4: + # MXFP4: each 32-element block = 16 consecutive even/odd pairs, so + # tiling the halves into (N_BLOCKS, 16) lands one block per row. + N_QUANT_BLOCKS: tl.constexpr = HEAD_SIZE // 32 + HALF_BLOCK: tl.constexpr = 16 + even_2d = tl.reshape(new_even, (N_QUANT_BLOCKS, HALF_BLOCK)) + odd_2d = tl.reshape(new_odd, (N_QUANT_BLOCKS, HALF_BLOCK)) + + amax = tl.maximum( + tl.max(tl.abs(even_2d), axis=1), + tl.max(tl.abs(odd_2d), axis=1), + ) + amax = tl.maximum(amax, 6.0 * (2**-126)) + # ue8m0 block scale: 2^ceil(log2(amax / 6.0)), stored (exp + 127). + log2_ratio = tl.ceil(tl.log2(amax * (1.0 / 6.0))) + log2_ratio = tl.minimum(tl.maximum(log2_ratio, -127.0), 127.0) + inv_scale = tl.exp2(-log2_ratio) + ue8m0 = (log2_ratio + 127.0).to(tl.uint8) # [N_QUANT_BLOCKS] + + inv_scale_col = tl.reshape(inv_scale, (N_QUANT_BLOCKS, 1)) + packed = _fp32x2_to_fp4x2( + even_2d * inv_scale_col, odd_2d * inv_scale_col + ) # (N_BLOCKS, HALF_BLOCK) uint8 + packed_flat = tl.reshape(packed, (TOKEN_STRIDE,)) + + tl.store(val_ptr + tl.arange(0, TOKEN_STRIDE), packed_flat) + tl.store(scale_ptr + tl.arange(0, SCALE_DIM), ue8m0) + else: + # Per-token FP8 (single 128-wide block) with one float32 scale. + result = tl.interleave(new_even, new_odd) # [HEAD_SIZE] fp32 + result_bf16 = result.to(tl.bfloat16).to(tl.float32) + INV_FP8_MAX: tl.constexpr = 1.0 / FP8_MAX + absmax = tl.maximum(tl.max(tl.abs(result_bf16), axis=0), 1e-4) + exponent = tl.ceil(tl.log2(absmax * INV_FP8_MAX)) + inv_scale = tl.exp2(-exponent) + x_clamped = tl.clamp(result_bf16 * inv_scale, -FP8_MAX, FP8_MAX) + x_uint8 = x_clamped.to(tl.float8e4nv).to(tl.uint8, bitcast=True) + if SHUFFLE: + tiled = ( + block // HEAD_TILE_SIZE * BLOCK_TILE_SIZE * HEAD_TILE_SIZE + + block % HEAD_TILE_SIZE + ) + tl.store(val_ptr + tiled, x_uint8) + else: + tl.store(val_ptr + block, x_uint8) + tl.store(scale_ptr.to(tl.pointer_type(tl.float32)), tl.exp2(exponent)) diff --git a/vllm/models/deepseek_v4_1/common/ops/query_quant.py b/vllm/models/deepseek_v4_1/common/ops/query_quant.py new file mode 100644 index 0000000000..4894a615bc --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/ops/query_quant.py @@ -0,0 +1,142 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import torch + +from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation +from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton + + +@triton.jit +def _norm_row(x, weight, row, stride, eps, SIZE: tl.constexpr, BLOCK: tl.constexpr): + cols = tl.arange(0, BLOCK) + w = tl.load(weight + cols, cols < SIZE, 0).to(tl.float32) + values = tl.load(x + row * stride + cols, cols < SIZE, 0).to(tl.float32) + rrms = tl.rsqrt(tl.sum(values * values, 0) / SIZE + eps) + return values * rrms * w + + +@triton.jit(do_not_specialize=["num_tokens"]) +def _q_kv_norm_quant_kernel( + q, + kv, + qw, + kvw, + qo, + kvo, + scales, + num_tokens, + q_stride, + kv_stride, + eps, + Q_SIZE: tl.constexpr, + KV_SIZE: tl.constexpr, + BLOCK: tl.constexpr, + LAUNCH_PDL: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + cols = tl.arange(0, BLOCK) + if LAUNCH_PDL: + tl.extra.cuda.gdc_wait() + tl.extra.cuda.gdc_launch_dependents() + if tl.program_id(1) == 0: + groups = tl.arange(0, BLOCK // 32) + if row < num_tokens: + y = _norm_row(q, qw, row, q_stride, eps, Q_SIZE, BLOCK) + # Preserve the materialized normalization output's rounding boundary. + y = y.to(q.dtype.element_ty).to(tl.float32) + grouped = tl.reshape(y, (BLOCK // 32, 32)) + amax = tl.max(tl.abs(grouped), 1) + normalized = amax * (1.0 / 448.0) + bits = normalized.to(tl.uint32, bitcast=True) + exponent = (bits >> 23) & 255 + mantissa = bits & 0x7FFFFF + bump = (mantissa != 0) & ~((exponent == 0) & (mantissa <= 0x400000)) + sf = tl.minimum(exponent + bump, 254) + sf = tl.where(normalized <= 0, 0, sf) + # Match FlashInfer's UE8M0 conversion, including zero/subnormal scales. + inv_bits = tl.where(sf == 0, 0, (254 - sf) << 23) + inv_scale = inv_bits.to(tl.float32, bitcast=True) + quantized = tl.reshape(grouped * inv_scale[:, None], (BLOCK,)) + tl.store(qo + row * Q_SIZE + cols, quantized, cols < Q_SIZE) + else: + sf = tl.full((BLOCK // 32,), 0, tl.uint32) + padded_groups: tl.constexpr = triton.cdiv(Q_SIZE // 32, 4) * 4 + sf = tl.where(groups < Q_SIZE // 32, sf, 0) + # F8_128x4: [row/128, group/4, row%32, row%128/32, group%4]. + offsets = ( + row // 128 * (128 * padded_groups) + + groups // 4 * 512 + + row % 32 * 16 + + row % 128 // 32 * 4 + + groups % 4 + ) + tl.store(scales + offsets, sf, groups < padded_groups) + elif row < num_tokens: + y = _norm_row(kv, kvw, row, kv_stride, eps, KV_SIZE, BLOCK) + tl.store(kvo + row * KV_SIZE + cols, y, cols < KV_SIZE) + + +def fused_q_kv_rmsnorm_quant( + qr: torch.Tensor, + kv: torch.Tensor, + q_weight: torch.Tensor, + kv_weight: torch.Tensor, + eps: float, +) -> tuple[QuantizedActivation, torch.Tensor]: + """Normalize Q/KV and quantize Q with FlashInfer's swizzled MXFP8 scales.""" + assert qr.ndim == kv.ndim == 2 and qr.shape[0] == kv.shape[0] + assert qr.stride(-1) == kv.stride(-1) == 1 + assert q_weight.is_contiguous() and kv_weight.is_contiguous() + assert qr.shape[1] % 32 == 0 + tokens, q_size = qr.shape + kv_size = kv.shape[1] + qo = torch.empty(qr.shape, dtype=torch.float8_e4m3fn, device=qr.device) + kvo = torch.empty(kv.shape, dtype=kv.dtype, device=kv.device) + padded_tokens = triton.cdiv(tokens, 128) * 128 + padded_groups = triton.cdiv(q_size // 32, 4) * 4 + scales = torch.empty( + padded_tokens * padded_groups, dtype=torch.uint8, device=qr.device + ) + if tokens: + block = triton.next_power_of_2(max(q_size, kv_size)) + _q_kv_norm_quant_kernel[(padded_tokens, 2)]( + qr, + kv, + q_weight, + kv_weight, + qo, + kvo, + scales, + tokens, + qr.stride(0), + kv.stride(0), + eps, + q_size, + kv_size, + block, + current_platform.is_arch_support_pdl(), + num_warps=8 if block >= 2048 else 4, + ) + return QuantizedActivation(qo, scales, qr.dtype, qr.shape, kMxfp8Dynamic), kvo + + +def can_fuse_query_quant(linears: list[torch.nn.Module]) -> bool: + """Require both local projections to use the same MXFP8 activation ABI.""" + if not current_platform.is_cuda(): + return False + from vllm.model_executor.kernels.linear.mxfp8.flashinfer import ( + FlashInferCutedslMxfp8LinearKernel, + FlashInferCutlassMxfp8LinearKernel, + ) + + # QuantKey does not encode scale layout; restrict this producer to the + # consumers that accept F8_128x4 swizzled scales. + return all( + getattr(linear, "input_quant_key", None) == kMxfp8Dynamic + and type(getattr(getattr(linear, "quant_method", None), "kernel", None)) + in (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel) + for linear in linears + ) diff --git a/vllm/models/deepseek_v4_1/common/rope.py b/vllm/models/deepseek_v4_1/common/rope.py new file mode 100644 index 0000000000..51ff879269 --- /dev/null +++ b/vllm/models/deepseek_v4_1/common/rope.py @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepseekV4 rotary embedding initialization.""" + +from vllm.model_executor.layers.rotary_embedding import get_rope +from vllm.model_executor.layers.rotary_embedding.base import RotaryEmbedding + + +def build_deepseek_v4_rope( + config, + *, + head_dim: int, + rope_head_dim: int, + max_position_embeddings: int, + compress_ratio: int, +) -> RotaryEmbedding: + rope_parameters = config.rope_parameters + # Newer checkpoints nest per-layer-type rope dicts ({"main", "compress"}); + # older ones ship a single flat dict shared by all layer types. + if isinstance(rope_parameters.get("main"), dict) and isinstance( + rope_parameters.get("compress"), dict + ): + key = "compress" if compress_ratio > 0 else "main" + rope_parameters = dict(rope_parameters[key]) + else: + rope_parameters = dict(rope_parameters) + + rope_parameters["rope_theta"] = ( + config.compress_rope_theta if compress_ratio > 0 else config.rope_theta + ) + if compress_ratio > 0 and rope_parameters["rope_type"] != "default": + # YaRN applies to all compressed-KV layers (compress_ratio > 0); only + # pure sliding-window layers (compress_ratio == 0) use plain RoPE. + rope_parameters["rope_type"] = ( + "deepseek_yarn" + if rope_parameters.get("apply_yarn_scaling", True) + else "deepseek_llama_scaling" + ) + else: + # Sliding-window layers use plain RoPE (theta=rope_theta, no YaRN). + rope_parameters["rope_type"] = "deepseek_yarn" + rope_parameters["factor"] = 1.0 + rope_parameters["original_max_position_embeddings"] = max_position_embeddings + rope_parameters["mscale"] = 0 # Disable mscale + rope_parameters["mscale_all_dim"] = 0 # Disable mscale + rope_parameters["is_deepseek_v4"] = True + rope_parameters["rope_dim"] = rope_head_dim + return get_rope( + head_dim, + max_position=max_position_embeddings, + rope_parameters=rope_parameters, + is_neox_style=False, + ) diff --git a/vllm/models/deepseek_v4_1/compressor.py b/vllm/models/deepseek_v4_1/compressor.py new file mode 100644 index 0000000000..d09d97d04c --- /dev/null +++ b/vllm/models/deepseek_v4_1/compressor.py @@ -0,0 +1,323 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from dataclasses import dataclass +from typing import Any, ClassVar, cast + +import torch +from torch import nn + +from vllm.config import VllmConfig, get_current_vllm_config +from vllm.forward_context import get_forward_context +from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.linear import MergedColumnParallelLinear +from vllm.models.deepseek_v4_1.common.ops.fused_compress_quant_cache import ( + fused_save_compress_norm, + rope_quant_insert, +) +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton +from vllm.v1.attention.backend import ( + AttentionBackend, + AttentionCGSupport, + AttentionMetadataBuilder, + CommonAttentionMetadata, + MultipleOf, +) +from vllm.v1.kv_cache_interface import CircularBufferSpec, KVCacheSpec + + +class CompressorBackend(AttentionBackend): + def __init__(self): + super().__init__() + + @staticmethod + def get_name() -> str: + return "CompressorBackend" + + @staticmethod + def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: + return [MultipleOf(1)] + + @classmethod + def get_supported_head_sizes(cls) -> list[int]: + return [512, 1024] + + @staticmethod + def get_builder_cls() -> type["CompressorMetadataBuilder"]: + return CompressorMetadataBuilder + + +@dataclass +class CompressorMetadata: + # [num_tokens] ring slot of every token: block * capacity + pos % capacity. + slot_mapping: torch.Tensor + query_start_loc: torch.Tensor # [num_reqs + 1] + token_to_req_indices: torch.Tensor # [num_tokens] + + +@triton.jit +def _ring_slot_mapping_kernel( + slot_mapping_ptr, + block_table_ptr, + block_table_stride, + token_to_req_ptr, + positions_ptr, + num_actual_tokens, + num_tokens, + CAPACITY: tl.constexpr, + BLOCK: tl.constexpr, +): + offsets = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + valid = offsets < num_actual_tokens + req = tl.load(token_to_req_ptr + offsets, mask=valid, other=0).to(tl.int64) + block = tl.load(block_table_ptr + req * block_table_stride, mask=valid, other=0) + pos = tl.load(positions_ptr + offsets, mask=valid, other=0) + slot = block.to(tl.int64) * CAPACITY + pos % CAPACITY + tl.store( + slot_mapping_ptr + offsets, tl.where(valid, slot, -1), mask=offsets < num_tokens + ) + + +class CompressorMetadataBuilder(AttentionMetadataBuilder): + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + assert isinstance(self.kv_cache_spec, CircularBufferSpec) + self.capacity = self.kv_cache_spec.block_size + max_num_batched_tokens = ( + self.vllm_config.scheduler_config.max_num_batched_tokens + ) + self.token_to_req_indices = torch.zeros( + max_num_batched_tokens, dtype=torch.int32, device=self.device + ) + self.slot_mapping_buffer = torch.empty( + max_num_batched_tokens, dtype=torch.int64, device=self.device + ) + + def build( + self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False, + ) -> CompressorMetadata: + num_tokens = common_attn_metadata.slot_mapping.numel() + positions = common_attn_metadata.positions + assert positions is not None + token_to_req_indices = common_attn_metadata.token_to_req_indices( + self.token_to_req_indices + ) + slot_mapping = self.slot_mapping_buffer[:num_tokens] + block_table = common_attn_metadata.block_table_tensor + _ring_slot_mapping_kernel[(triton.cdiv(num_tokens, 256),)]( + slot_mapping, + block_table, + block_table.stride(0), + token_to_req_indices, + positions, + common_attn_metadata.num_actual_tokens, + num_tokens, + CAPACITY=self.capacity, + BLOCK=256, + ) + return CompressorMetadata( + slot_mapping=slot_mapping, + query_start_loc=common_attn_metadata.query_start_loc, + token_to_req_indices=token_to_req_indices, + ) + + +class CompressorStateCache(torch.nn.Module, AttentionLayerBase): + """Per-request ring of the open group's [kv, score] rows (ratio > 1).""" + + def __init__(self, state_dim: int, dtype: torch.dtype, prefix: str): + super().__init__() + self.state_dim = state_dim + self.dtype = dtype + self.prefix = prefix + self.kv_cache = torch.tensor([]) + compilation_config = get_current_vllm_config().compilation_config + if prefix in compilation_config.static_forward_context: + raise ValueError(f"Duplicate layer name: {prefix}") + compilation_config.static_forward_context[prefix] = self + + assert self.dtype == torch.float32 + # Drafts + bonus token + the previous row, as a power of two >= 8. + rows_per_step = get_current_vllm_config().num_speculative_tokens + 2 + self.block_size = max(8, 1 << (rows_per_step - 1).bit_length()) + + def bind_kv_cache(self, kv_cache: torch.Tensor) -> None: + # [B, H=1, N, C] -> [B, N, C] + self.kv_cache = kv_cache.squeeze(1) + + def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: + del vllm_config + return CircularBufferSpec( + block_size=self.block_size, + num_kv_heads=1, + head_size=self.state_dim, + head_size_v=0, + dtype=self.dtype, + ) + + def forward(self): ... + + def get_attn_backend(self) -> type[AttentionBackend]: + return CompressorBackend + + +class DeepseekCompressor(nn.Module): + """DeepSeek V4.1 KV/score compressor. + + Pools ``compress_ratio`` consecutive tokens into one KV latent with a + learned softmax gate (ratio 1 has no gate and no pooling). Owns the + linear, norm and state cache. State saving, compression and RMSNorm share + one Triton kernel. The emitted latent feeds independent main-cache and + indexer K kernels, which the attention layer can schedule concurrently. + """ + + def __init__( + self, + vllm_config: VllmConfig, + compress_ratio: int, + hidden_size: int, + head_dim: int, + rotate: bool = False, + prefix: str = "", + k_cache_prefix="", + ): + super().__init__() + if compress_ratio not in (1, 2): + raise NotImplementedError( + "DeepSeek V4.1 compressor supports compress_ratio 1 (full-length " + f"compressed cache) and 2; got {compress_ratio}. The ratio-4/128 " + "CuTe-DSL kernels are v4.0-specific and not wired here." + ) + self.compress_ratio = compress_ratio + self.hidden_size = hidden_size + self.head_dim = head_dim + self.rotate = rotate + self.prefix = prefix + self.k_cache_prefix = k_cache_prefix + # Ratio 1 pools single tokens, so the checkpoint carries no gate. + self.has_gate = compress_ratio > 1 + + config = vllm_config.model_config.hf_config + self.rope_head_dim = config.qk_rope_head_dim + self.nope_head_dim = self.head_dim - self.rope_head_dim + assert self.head_dim == 512 and self.rope_head_dim == 64 + self.rms_norm_eps = config.rms_norm_eps + self.device = current_platform.device_type + self.max_num_reqs = vllm_config.scheduler_config.max_num_seqs + self.max_model_len = vllm_config.model_config.max_model_len + + wkv_wgate_sizes = ( + [self.head_dim, self.head_dim] if self.has_gate else [self.head_dim] + ) + self.fused_wkv_wgate = MergedColumnParallelLinear( + self.hidden_size, + wkv_wgate_sizes, + bias=False, + return_bias=False, + quant_config=None, + disable_tp=True, + prefix=f"{prefix}.fused_wkv_wgate", + ) + self.norm = RMSNorm(self.head_dim, self.rms_norm_eps) + + self.state_cache = ( + CompressorStateCache( + state_dim=2 * self.head_dim, # kv_state + score_state + dtype=torch.float32, + prefix=f"{prefix}.state_cache", + ) + if compress_ratio > 1 + else None + ) + + # Save reference to static_forward_context for forward-time KV cache lookup. + # get_current_vllm_config() is only available during __init__, not forward. + self._static_forward_context = ( + vllm_config.compilation_config.static_forward_context + ) + + def forward( + self, + # [num_tokens, (2 if has_gate else 1) * self.head_dim] + kv_score: torch.Tensor, + # [num_tokens] + positions: torch.Tensor, + ) -> torch.Tensor | None: + """Save states and return the BF16 latent for cache insertion and indexing. + + Only valid group-boundary rows are written. + """ + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict): + return None + + if self.state_cache is None: + state_cache = query_start_loc = token_to_req_indices = None + slot_mapping = cast(Any, attn_metadata[self.k_cache_prefix]).slot_mapping + else: + state_metadata = cast( + CompressorMetadata, attn_metadata[self.state_cache.prefix] + ) + state_cache = self.state_cache.kv_cache + slot_mapping = state_metadata.slot_mapping + query_start_loc = state_metadata.query_start_loc + token_to_req_indices = state_metadata.token_to_req_indices + + latent = torch.empty( + kv_score.shape[0], + self.head_dim, + dtype=torch.bfloat16, + device=kv_score.device, + ) + fused_save_compress_norm( + kv_score, + positions, + state_cache, + slot_mapping, + query_start_loc, + token_to_req_indices, + self.norm.weight, + self.rms_norm_eps, + self.compress_ratio, + latent, + ) + return latent + + def insert_cache( + self, + latent: torch.Tensor | None, + positions: torch.Tensor, + rotary_emb, + ) -> None: + """Publish compressed main-cache rows after the latent becomes ready.""" + if latent is None: + return + attn_metadata = get_forward_context().attn_metadata + assert isinstance(attn_metadata, dict) + k_cache_metadata = cast(Any, attn_metadata[self.k_cache_prefix]) + k_cache_layer = self._static_forward_context[self.k_cache_prefix] + kv_cache = k_cache_layer.kv_cache + # Plain-row per-tensor fp8 caches (FlashInfer) carry the layer's scale; + # fp8_ds_mla and bf16 rows need none. + fp8_scale = ( + getattr(k_cache_layer, "_flashinfer_fp8_kv_scale", None) + if kv_cache.dtype == torch.float8_e4m3fn + else None + ) + + rope_quant_insert( + latent, + positions, + rotary_emb.cos_sin_cache, + kv_cache, + k_cache_metadata.slot_mapping, + self.compress_ratio, + fp8_scale=fp8_scale, + ) diff --git a/vllm/models/deepseek_v4_1/nvidia/__init__.py b/vllm/models/deepseek_v4_1/nvidia/__init__.py new file mode 100644 index 0000000000..208f01a7cb --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/deepseek_v4_1/nvidia/dspark.py b/vllm/models/deepseek_v4_1/nvidia/dspark.py new file mode 100644 index 0000000000..46fe2558ab --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/dspark.py @@ -0,0 +1,558 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DSpark draft model for DeepSeek-V4.1 (semi-autoregressive speculative decoding). + +See: qwen3_dspark.py for base architecture. This one is specialized to the +DSV4.1 DSpark, which reuses the target model's architecture similarly to MTP. +Its weights ship in the target checkpoint under the ``mtp.{0,1,2}.*`` prefix. + +To implement non-causal attention, we leverage the sparse attention implementation to +include the future query tokens in the top-k indices for each query token. +""" + +from collections.abc import Iterable + +import regex as re +import torch +import torch.nn as nn + +import vllm.envs as envs +from vllm.config import VllmConfig, get_current_vllm_config +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, +) +from vllm.forward_context import get_forward_context, is_forward_context_available +from vllm.logger import init_logger +from vllm.model_executor.kernels.mhc.tilelang import ( + mhc_post_tilelang, +) +from vllm.model_executor.kernels.mhc.triton import hc_collapse_triton +from vllm.model_executor.layers.fused_moe import ( + fused_moe_make_expert_params_mapping, +) +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.linear import ReplicatedLinear +from vllm.model_executor.layers.logits_processor import LogitsProcessor +from vllm.model_executor.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, +) +from vllm.model_executor.model_loader.weight_utils import default_weight_loader +from vllm.model_executor.models.qwen3_dspark import ( + DSparkConfidenceHead, + DSparkMarkovHead, +) +from vllm.model_executor.models.utils import maybe_prefix +from vllm.models.common.ops.sequence_parallel import ( + sp_all_gather, + sp_padding_mask, + sp_shard, +) + +from .model import ( + DeepseekV4DecoderLayer, + DeepseekV4Model, + _linear_scale_param_name, + _use_sequence_parallel, + make_deepseek_v4_expert_params_mapping, +) + +logger = init_logger(__name__) + +# MoE expert scale suffix differs by expert dtype (mirrors deepseek_v4 loaders): +# fp4 experts register ``.weight_scale``; block-fp8 experts ``.weight_scale_inv``. +_EXPERT_SCALE_RE = re.compile(r"\.experts\.\d+\.w[123]\.scale$") + + +class DSparkDeepseekV4Model(nn.Module): + def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: + super().__init__() + assert vllm_config.speculative_config is not None + config = vllm_config.speculative_config.draft_model_config.hf_config + self.config = config + self.hidden_size = config.hidden_size + self.hc_mult = config.hc_mult + self.hc_eps = config.hc_eps + self.rms_norm_eps = config.rms_norm_eps + self.num_hidden_layers = config.num_hidden_layers + self.target_layer_ids = tuple(config.dspark_target_layer_ids) + self.use_sequence_parallel = _use_sequence_parallel(vllm_config) + + self.num_dspark_layers = ( + getattr(config, "n_mtp_layers", None) + or getattr(config, "num_nextn_predict_layers", None) + or 3 + ) + + # Shared with the target (aliased by the speculator's loading utility). + self.embed_tokens = VocabParallelEmbedding( + config.vocab_size, + config.hidden_size, + prefix=maybe_prefix(prefix, "embed_tokens"), + ) + + self.main_proj = ReplicatedLinear( + config.hidden_size * len(self.target_layer_ids), + config.hidden_size, + bias=False, + return_bias=False, + quant_config=vllm_config.quant_config, + prefix=maybe_prefix(prefix, "main_proj"), + ) + self.main_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.topk_indices_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + config.index_topk, + dtype=torch.int32, + ) + + current_vllm_config = get_current_vllm_config() + self.layers = nn.ModuleList( + [ + DeepseekV4DecoderLayer( + current_vllm_config, + prefix=maybe_prefix(prefix, f"layers.{self.num_hidden_layers + i}"), + topk_indices_buffer=self.topk_indices_buffer, + ) + for i in range(self.num_dspark_layers) + ] + ) + + # Heads: final norm, and the Markov + confidence heads. + # Loaded from the "final" MTP layer weights (mtp.*) in the target + # checkpoint. v4.1 has no learned hc_head: the hc copies are + # collapsed with a pre-mix derived from the last layer's hc_ffn + # projection at the end of forward(). + self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + draft_vocab_size = ( + getattr(config, "draft_vocab_size", None) or config.vocab_size + ) + self.markov_head = DSparkMarkovHead( + config.vocab_size, + draft_vocab_size, + config.dspark_markov_rank, + prefix=maybe_prefix(prefix, "markov_head"), + ) + self.confidence_head: DSparkConfidenceHead | None = None + if getattr(config, "enable_confidence_head", True): + self.confidence_head = DSparkConfidenceHead( + config.hidden_size + config.dspark_markov_rank, + prefix=maybe_prefix(prefix, "confidence_head"), + ) + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.embed_tokens(input_ids) + + def combine_hidden_states(self, aux_hidden_states: torch.Tensor) -> torch.Tensor: + """main_x = main_norm(main_proj(concat of target aux hidden states)). + + ``aux_hidden_states`` is [T, hidden_size * len(target_layer_ids)]. + """ + return self.main_norm(self.main_proj(aux_hidden_states)) + + @torch.inference_mode() + def precompute_and_store_context_kv( + self, + main_x: torch.Tensor, + context_positions: torch.Tensor, + context_slot_mappings: list[torch.Tensor | None] | None = None, + ) -> None: + """Insert the sliding-window context KV for every draft layer. + + Mirrors the reference DSparkAttention: each layer derives its context KV + from the SAME projected target hidden ``main_x``, via that layer's own + ``wkv`` + ``kv_norm`` + RoPE + quant, then writes it at the + layer's context slots. + + ``context_slot_mappings`` is a per-layer list (each entry is the context + slot mapping for that layer's kv-cache group, since the hybrid manager may + place draft layers in different groups). ``None`` (or a ``None`` entry) + runs the projection to reserve workspace but writes nothing (profiling). + """ + for i, layer in enumerate(self.layers): + slot_mapping = ( + None if context_slot_mappings is None else context_slot_mappings[i] + ) + attn = layer.attn + # Optimized DSV4 MLA path: wkv part of the fused wq_a|wkv projection + # (q_lora part discarded), then RoPE/quant/insert via the fused op. + qr_kv, _ = attn.fused_wqa_wkv(main_x) + kv = qr_kv[..., attn.q_lora_rank :] + kv = attn.kv_norm(kv) + if slot_mapping is None: + continue + _insert_context_kv(attn, kv, context_positions, slot_mapping) + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None = None, + ) -> torch.Tensor: + if inputs_embeds is None: + inputs_embeds = self.embed_input_ids(input_ids) + full_num_tokens = positions.shape[0] + if self.use_sequence_parallel: + if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available(): + forward_context = get_forward_context() + forward_context.is_padding = sp_padding_mask( + forward_context.is_padding, inputs_embeds + ) + inputs_embeds = sp_shard(inputs_embeds) + input_ids = sp_shard(input_ids) + # Expand to hc_mult copies for hyper-connections ([T, H] -> [T, hc, H]). + hidden_states = inputs_embeds.unsqueeze(-2).repeat(1, self.hc_mult, 1) + + residual = post_mix = res_mix = pre_mix = None + for layer in self.layers: + hidden_states, residual, post_mix, res_mix, pre_mix = layer( + hidden_states, + positions, + input_ids, + pre_mix, + post_mix, + res_mix, + residual, + ) + hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix) + if self.use_sequence_parallel: + hidden_states = sp_all_gather(hidden_states)[:full_num_tokens] + pre_mix = sp_all_gather(pre_mix)[:full_num_tokens] + # Collapse the hc copies with the pre-mix from the last layer's FFN + # mixes — the mix the reference forward_head applies (hc_pre with the + # last block's ffn pre-mix). Return the PRE-norm head hidden; + # compute_logits applies self.norm. + assert pre_mix is not None + hidden_states = hc_collapse_triton(hidden_states, pre_mix) + return hidden_states + + +def _insert_context_kv( + attn: nn.Module, + kv: torch.Tensor, + positions: torch.Tensor, + slot_mapping: torch.Tensor, +) -> None: + """RoPE + quant + paged-cache insert of (already kv_norm'd) context KV. + + Reuses the DSV4 fused insert ops (which also process a query; we pass a dummy + query and discard it, since context tokens have no query). Mirrors + ``DeepseekV4Attention._fused_qnorm_rope_kv_insert``. + """ + swa_cache = attn.swa_cache_layer.kv_cache + block_size = attn.swa_cache_layer.block_size + cos_sin_cache = attn.rotary_emb.cos_sin_cache + cache_dtype = swa_cache.dtype + n_ctx = kv.shape[0] + dummy_q = torch.zeros( + (n_ctx, attn.n_local_heads, attn.head_dim), + dtype=kv.dtype, + device=kv.device, + ) + if cache_dtype == torch.uint8: + # fp8_ds_mla UE8M0 paged layout + swa_2d = swa_cache.view(swa_cache.shape[0], -1) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert( + dummy_q, + kv, + swa_2d, + slot_mapping, + positions, + cos_sin_cache, + attn.padded_heads, + attn.eps, + block_size, + ) + elif cache_dtype == torch.bfloat16: + swa_3d = swa_cache.view(-1, block_size, attn.head_dim) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert( + dummy_q, + kv, + swa_3d, + slot_mapping, + positions, + cos_sin_cache, + attn.eps, + block_size, + ) + else: # per-tensor fp8 (torch.float8_e4m3fn) + # TODO(ben): double-check if this is being dispatched correctly for FI backend + swa_3d = swa_cache.view(-1, block_size, attn.head_dim) + dummy_q_fp8 = torch.zeros_like(dummy_q, dtype=torch.float8_e4m3fn) + torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_fp8_insert( + dummy_q, + kv, + dummy_q_fp8, + swa_3d, + slot_mapping, + positions, + cos_sin_cache, + attn._flashinfer_fp8_kv_scale, + attn._flashinfer_fp8_q_scale_inv, + attn.eps, + block_size, + ) + + +class DSparkDeepseekV4ForCausalLM(nn.Module): + # Draft weights ship in the target checkpoint (mtp.*) without embed/head, so + # load_dspark_model always aliases the target's. + has_own_embed_tokens = False + has_own_lm_head = False + # Full-vocab draft: draft ids are target ids, no remapping needed. + draft_id_to_target_id = None + + def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: + super().__init__() + assert vllm_config.speculative_config is not None + self.draft_model_config = vllm_config.speculative_config.draft_model_config + self.config = self.draft_model_config.hf_config + self.quant_config = vllm_config.quant_config + self.linear_scale_name = _linear_scale_param_name( + vllm_config, getattr(self.config, "expert_dtype", "fp4") + ) + self.pad_shared_expert = getattr( + self.quant_config, "weight_block_size", None + ) is not None and not _use_sequence_parallel(vllm_config) + self.model = DSparkDeepseekV4Model( + vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") + ) + # Shared with the target (aliased by the speculator's load utility). + self.lm_head = ParallelLMHead( + self.config.vocab_size, + self.config.hidden_size, + prefix=maybe_prefix(prefix, "lm_head"), + ) + self.logits_processor = LogitsProcessor(self.config.vocab_size) + + # --- Hooks used by the speculator ------------------------------------- + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.model.embed_input_ids(input_ids) + + def combine_hidden_states(self, aux_hidden_states: torch.Tensor) -> torch.Tensor: + return self.model.combine_hidden_states(aux_hidden_states) + + def get_draft_kv_cache_layer_names(self) -> list[str]: + # DSV4 MLA path: each draft layer's sliding-window cache is a separate + # layer, named by its prefix. + return [layer.attn.swa_cache_layer.prefix for layer in self.model.layers] + + def precompute_and_store_context_kv( + self, + context_states: torch.Tensor, + context_positions: torch.Tensor, + context_slot_mappings: list[torch.Tensor | None] | None = None, + ) -> None: + self.model.precompute_and_store_context_kv( + context_states, context_positions, context_slot_mappings + ) + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None = None, + ) -> torch.Tensor: + # Returns the pre-norm collapsed head hidden ([T, hidden_size]). + return self.model(input_ids, positions, inputs_embeds) + + def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + """Base logits U_k = lm_head(norm(head_hidden)).""" + return self.logits_processor(self.lm_head, self.model.norm(hidden_states)) + + def compute_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + # Full-vocab draft: base logits, no d2t scatter. + return self.compute_logits(hidden_states) + + def map_draft_to_target(self, draft_ids: torch.Tensor) -> torch.Tensor: + return draft_ids # full-vocab: draft ids are target ids + + def markov_embed(self, token_ids: torch.Tensor) -> torch.Tensor: + return self.model.markov_head.embed(token_ids) + + def markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor: + return self.model.markov_head.bias(markov_embed, self.logits_processor) + + def compute_confidence( + self, head_hidden: torch.Tensor, markov_embed: torch.Tensor + ) -> torch.Tensor: + """Per-position acceptance probability for each drafted token.""" + assert self.model.confidence_head is not None + return torch.sigmoid(self.model.confidence_head(head_hidden, markov_embed)) + + # --- Weight loading ---------------------------------------------------- + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + """Load the ``mtp.{0,1,2}.*`` draft weights from the target checkpoint. + + Non-mtp weights (embed/head/main layers) belong to the target model and + are skipped here. ``embed_tokens``/``lm_head`` are aliased from the target. + """ + first_layer = self.model.layers[0] + use_mega_moe = first_layer.ffn.use_mega_moe + # Draft MoE layers use the dspark_* expert counts, not the + # backbone's (see DeepseekV4MoE and the reference + # ModelArgs.get_moe_config). + n_draft_experts = ( + getattr(self.config, "dspark_n_routed_experts", 0) + or self.config.n_routed_experts + ) + if use_mega_moe: + expert_mapping = make_deepseek_v4_expert_params_mapping(n_draft_experts) + else: + expert_mapping = fused_moe_make_expert_params_mapping( + self, + ckpt_gate_proj_name="w1", + ckpt_down_proj_name="w2", + ckpt_up_proj_name="w3", + num_experts=n_draft_experts, + ) + expert_scale_suffix = ( + ".weight_scale" + if getattr(self.config, "expert_dtype", "fp4") == "fp4" + else ".weight_scale_inv" + ) + + # (param_name, ckpt_shard_name, shard_id) for non-expert stacked params. + stacked_params_mapping = [ + ("gate_up_proj", "w1", 0), + ("gate_up_proj", "w3", 1), + ("attn.fused_wqa_wkv", "attn.wq_a", 0), + ("attn.fused_wqa_wkv", "attn.wkv", 1), + ] + + params_dict = dict(self.named_parameters()) + loaded_params: set[str] = set() + loaded_confidence_head = False + + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + n_local_head = self.config.num_attention_heads // tp_size + head_start = n_local_head * tp_rank + head_end = n_local_head * (tp_rank + 1) + + for name, loaded_weight in weights: + mapped = self._remap_dspark_name(name) + if mapped is None: + continue + name = mapped + if "confidence_head." in name: + loaded_confidence_head = True + + # ``.scale`` -> per-method scale suffix. + if name.endswith(".scale"): + suffix = ( + expert_scale_suffix + if _EXPERT_SCALE_RE.search(name) + else f".{self.linear_scale_name}" + ) + name = name.removesuffix(".scale") + suffix + if ".shared_experts.w2" in name: + name = name.replace(".shared_experts.w2", ".shared_experts.down_proj") + if self.pad_shared_expert and ".shared_experts." in name: + loaded_weight = DeepseekV4Model._pad_shared_expert_weight( + self.quant_config, name, loaded_weight + ) + + # E8M0 expert scales: keep raw exponent bytes. + if ".experts." in name: + if ( + "weight_scale" in name + and loaded_weight.dtype == torch.float8_e8m0fnu + ): + loaded_weight = loaded_weight.view(torch.uint8) + for param_name, weight_name, expert_id, shard_id in expert_mapping: + if weight_name not in name: + continue + name_mapped = name.replace(weight_name, param_name) + param = params_dict[name_mapped] + success = param.weight_loader( + param, + loaded_weight, + name_mapped, + shard_id=shard_id, + expert_id=expert_id, + return_success=True, + ) + if success: + loaded_params.add(name_mapped) + break + continue + + # Stacked rules only apply to decoder-layer weights. Head-stack params + # (main_proj/norm/markov_head/confidence_head) load directly — + # otherwise e.g. "markov_w1" would collide with the "w1" shard rule. + is_layer_param = name.startswith("model.layers.") + for param_name, weight_name, stacked_shard_id in stacked_params_mapping: + if not is_layer_param or weight_name not in name: + continue + name = name.replace(weight_name, param_name) + param = params_dict[name] + param.weight_loader(param, loaded_weight, stacked_shard_id) + loaded_params.add(name) + break + else: + if "attn_sink" in name: + narrow = loaded_weight[head_start:head_end] + params_dict[name][: narrow.shape[0]].copy_(narrow) + loaded_params.add(name) + continue + if name.endswith(".ffn.gate.bias"): + name = name.replace( + ".ffn.gate.bias", ".ffn.gate.e_score_correction_bias" + ) + param = params_dict[name] + weight_loader = getattr(param, "weight_loader", default_weight_loader) + weight_loader(param, loaded_weight) + loaded_params.add(name) + + if self.model.confidence_head is not None and not loaded_confidence_head: + self.model.confidence_head = None + self.process_weights_after_loading() + logger.info_once("DSpark draft model loaded: %d params", len(loaded_params)) + return loaded_params + + def _finalize_moe(self) -> None: + for layer in self.model.layers: + layer.ffn.finalize_mega_moe_weights() + + def process_weights_after_loading(self) -> None: + self._finalize_moe() + + def _remap_dspark_name(self, name: str) -> str | None: + """Map a checkpoint ``mtp.{i}.*`` name to this model's parameter path. + + Returns None for non-mtp weights (owned by the target model). + """ + m = re.match(r"mtp\.(\d+)\.(.*)", name) + if m is None: + return None + stage = int(m.group(1)) + rest = m.group(2) + if rest.startswith("confidence_head.") and self.model.confidence_head is None: + return None + # The checkpoint calls the Markov head's factors ``embed``/``head``; + # DSparkMarkovHead registers them as ``markov_w1``/``markov_w2``. + if rest.startswith("markov_head.embed."): + return "model.markov_head.markov_w1." + rest.removeprefix( + "markov_head.embed." + ) + if rest.startswith("markov_head.head."): + return "model.markov_head.markov_w2." + rest.removeprefix( + "markov_head.head." + ) + # Head-stack params live at model level (mtp.last), context combiner at + # model level (mtp.0); everything else is a per-layer decoder block. + head_prefixes = ( + "norm.", + "markov_head.", + "confidence_head.", + ) + if rest.startswith(("main_proj.", "main_norm.")) or rest.startswith( + head_prefixes + ): + return f"model.{rest}" + return f"model.layers.{stage}.{rest}" diff --git a/vllm/models/deepseek_v4_1/nvidia/flashinfer_sparse.py b/vllm/models/deepseek_v4_1/nvidia/flashinfer_sparse.py new file mode 100644 index 0000000000..802ddede9c --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/flashinfer_sparse.py @@ -0,0 +1,908 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepSeek V4 FlashInfer sparse MLA backend.""" + +from typing import TYPE_CHECKING, ClassVar, cast + +import torch + +from vllm.config import VllmConfig +from vllm.config.cache import CacheDType +from vllm.forward_context import get_forward_context +from vllm.models.deepseek_v4.nvidia.ops.o_proj import ( + compute_fp8_einsum_recipe, + deep_gemm_fp8_o_proj, +) +from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention +from vllm.models.deepseek_v4_1.common.ops import ( + build_flashinfer_mixed_sparse_indices, + compute_global_topk_indices_and_lens, +) +from vllm.models.deepseek_v4_1.sparse_mla import ( + DeepseekV4FlashMLAMetadata, + DeepseekV4SparseMLABackend, + DeepseekV4SparseMLAMetadataBuilder, + DeepseekV41SparseSWAMetadataBuilder, +) +from vllm.platforms.interface import DeviceCapability +from vllm.utils.flashinfer import flashinfer_trtllm_batch_decode_sparse_mla_dsv4 +from vllm.v1.attention.backend import AttentionCGSupport, MultipleOf +from vllm.v1.attention.backends.mla.compressor_utils import ( + get_dspark_swa_index_width, +) +from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWABackend + +if TYPE_CHECKING: + from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata + +_FLASHINFER_DSV4_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024 +_flashinfer_dsv4_workspace_by_device: dict[torch.device, torch.Tensor] = {} + + +def _get_flashinfer_dsv4_workspace(device: torch.device) -> torch.Tensor: + workspace = _flashinfer_dsv4_workspace_by_device.get(device) + if workspace is None: + workspace = torch.zeros( + _FLASHINFER_DSV4_WORKSPACE_BUFFER_SIZE, + dtype=torch.uint8, + device=device, + ) + _flashinfer_dsv4_workspace_by_device[device] = workspace + return workspace + + +def _packed_block_span(pool: torch.Tensor) -> int: + """Per-block stride of ``pool`` in tokens (``stride(0)//stride(-2)``): == + block_size for unpacked KV, larger when packed (#44577). Raises if not + token-aligned.""" + block_stride = pool.stride(0) + token_stride = pool.stride(-2) + if block_stride % token_stride != 0: + raise NotImplementedError( + "FLASHINFER_MLA_SPARSE_DSV4 packed KV requires the per-block stride " + f"({block_stride}) to be a multiple of the per-token stride " + f"({token_stride}); this layout is not supported yet." + ) + return block_stride // token_stride + + +# Sparse MLA h_q counts accepted natively (flashinfer>=0.6.14, #3545). +_SPARSE_MLA_SUPPORTED_Q_HEADS = (8, 16, 32, 64, 128) + + +def _pad_to_supported_q_heads(num_heads: int) -> int: + for supported in _SPARSE_MLA_SUPPORTED_Q_HEADS: + if num_heads <= supported: + return supported + raise ValueError( + f"DeepseekV4 FlashInfer MLA Sparse does not support {num_heads} heads " + "(sparse MLA kernel requires h_q in {8, 16, 32, 64, 128})." + ) + + +def _required_sm120_sparse_topk(vllm_config: VllmConfig, window_size: int) -> int: + """Return the SM120 DSV4 SWA specialization needed by this model.""" + if not vllm_config.attention_config.use_non_causal: + return window_size + speculative_config = vllm_config.speculative_config + if speculative_config is None: + return window_size + return get_dspark_swa_index_width( + window_size, + speculative_config.num_speculative_tokens, + ) + + +class DeepseekV4FlashInferMLASparseBackend(DeepseekV4SparseMLABackend): + """FlashInfer backend using the DSv4 sparse metadata/cache layout. + + Inherits the base and backend reuses its``DeepseekV4SparseMLAMetadataBuilder`` + """ + + supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16] + supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ + "auto", + "bfloat16", + "fp8", + "fp8_e4m3", + "fp8_ds_mla", + ] + + @staticmethod + def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: + return [128] + + @staticmethod + def get_name() -> str: + return "FLASHINFER_MLA_SPARSE_DSV41" + + @classmethod + def get_supported_head_sizes(cls) -> list[int]: + return [512] + + @classmethod + def supports_sink(cls) -> bool: + return True + + @classmethod + def is_sparse(cls) -> bool: + return True + + @classmethod + def supports_compute_capability(cls, capability: DeviceCapability) -> bool: + return capability.major in [10, 12] + + @classmethod + def supports_combination( + cls, + head_size: int, + dtype: torch.dtype, + kv_cache_dtype: CacheDType | None, + block_size: int | None, + use_mla: bool, + has_sink: bool, + use_sparse: bool, + use_mm_prefix: bool, + device_capability: DeviceCapability, + ) -> str | None: + if device_capability.major == 10: + if kv_cache_dtype == "fp8_ds_mla": + return ( + "FLASHINFER_MLA_SPARSE_DSV4 SM10x uses the plain " + "per-tensor FP8 KV layout, not fp8_ds_mla" + ) + if kv_cache_dtype not in (None, "auto", "bfloat16", "fp8", "fp8_e4m3"): + return "kv_cache_dtype not supported" + return None + if device_capability.major == 12: + if kv_cache_dtype not in ("fp8", "fp8_e4m3", "fp8_ds_mla"): + return "kv_cache_dtype not supported" + from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120 + + if not has_flashinfer_sparse_mla_sm120(): + return ( + "FLASHINFER_MLA_SPARSE_DSV4 SM120 requires FlashInfer's " + "sparse MLA decode API" + ) + return None + return "FLASHINFER_MLA_SPARSE_DSV4 requires SM10x or SM12x" + + @staticmethod + def get_builder_cls() -> type["DeepseekV4FlashInferSparseMLAMetadataBuilder"]: + return DeepseekV4FlashInferSparseMLAMetadataBuilder + + +class DeepseekV4FlashInferSparseMLAMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder): + """Varlen-capable metadata builder for the FlashInfer sparse MLA backend.""" + + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS + + +class DeepseekSparseSWAFlashInferMetadataBuilder(DeepseekV41SparseSWAMetadataBuilder): + """SWA metadata for the FlashInfer sparse decode path (varlen decode).""" + + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS + + +class DeepseekSparseSWAFlashInferBackend(DeepseekSparseSWABackend): + @staticmethod + def get_builder_cls() -> type[DeepseekSparseSWAFlashInferMetadataBuilder]: + return DeepseekSparseSWAFlashInferMetadataBuilder + + +class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention): + """FlashInfer TRTLLM-gen sparse MLA attention layer for SM100 DeepSeek V4.""" + + backend_cls = DeepseekV4FlashInferMLASparseBackend + swa_backend_cls = DeepseekSparseSWAFlashInferBackend + use_fp8_ds_mla_layout: ClassVar[bool] = False + + @classmethod + def get_padded_num_q_heads(cls, num_heads: int) -> int: + return _pad_to_supported_q_heads(num_heads) + + def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + return deep_gemm_fp8_o_proj( + o, + positions, + self.rotary_emb.cos_sin_cache, + self.wo_a, + self.wo_b, + n_groups=self.n_local_groups, + heads_per_group=self.n_local_heads // self.n_local_groups, + nope_dim=self.nope_head_dim, + rope_dim=self.rope_head_dim, + o_lora_rank=self.o_lora_rank, + einsum_recipe=self._einsum_recipe, + tma_aligned_scales=self._tma_aligned_scales, + ) + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe( + self._o_proj_block_size + ) + # Per-tensor FP8 scale buffers + precomputed scalar BMM scales. Only the + # per-tensor FP8 cache path consumes these; bf16 reads ``self.scale``. + if self.kv_cache_torch_dtype != torch.float8_e4m3fn: + return + fp8_q_scale = 1.0 + fp8_kv_scale = 1.0 + self.register_buffer( + "_flashinfer_fp8_q_scale", + torch.tensor([fp8_q_scale], dtype=torch.float32), + persistent=False, + ) + self.register_buffer( + "_flashinfer_fp8_q_scale_inv", + torch.tensor([1.0 / fp8_q_scale], dtype=torch.float32), + persistent=False, + ) + self.register_buffer( + "_flashinfer_fp8_kv_scale", + torch.tensor([fp8_kv_scale], dtype=torch.float32), + persistent=False, + ) + # TRTLLM-gen takes scalar scale args on a distinct C++ path vs + # one-element tensors, so these are Python floats. + self._flashinfer_fp8_bmm1_scale = self.scale * fp8_q_scale * fp8_kv_scale + self._flashinfer_fp8_bmm2_scale = fp8_kv_scale + + def forward_mqa( + self, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + output: torch.Tensor, + ) -> None: + # The TRTLLM-gen kernel requires h_q in {64, 128}, so the output buffer + # is allocated at the padded head count while q arrives at the local + # head count; _forward pads q to match before the launcher. + assert output.shape[0] == q.shape[0] and output.shape[-1] == q.shape[-1], ( + f"output buffer shape {output.shape} incompatible with q shape {q.shape}" + ) + assert output.shape[1] >= q.shape[1], ( + f"output heads {output.shape[1]} must be >= q heads {q.shape[1]}" + ) + # Per-tensor FP8 q produces a bf16 attention output. + expected_output_dtype = ( + torch.bfloat16 if q.dtype == torch.float8_e4m3fn else q.dtype + ) + assert output.dtype == expected_output_dtype, ( + f"output dtype {output.dtype} must match expected {expected_output_dtype} " + f"for q dtype {q.dtype}" + ) + + forward_context = get_forward_context() + attn_metadata = forward_context.attn_metadata + if attn_metadata is None: + # Warmup dummy run: FlashInfer reads the cache directly and lazily + # allocates its workspace, so nothing to reserve here. + output.zero_() + return + + assert isinstance(attn_metadata, dict) + # Compressed-cache metadata lives on the kv-source layer's prefix; + # consumers share that cache and its block table. + flashmla_metadata = cast( + DeepseekV4FlashMLAMetadata | None, + attn_metadata.get(self.compressed_cache_prefix) + if self.compressed_cache_prefix is not None + else None, + ) + swa_metadata = cast( + "DeepseekSparseSWAMetadata | None", + attn_metadata.get(self.swa_cache_layer.prefix), + ) + assert swa_metadata is not None + + swa_only = self.compress_ratio == 0 + # SWA-only layers have no compressed KV cache; consumers read the kv + # source's cache. + self_kv_cache = None if swa_only else self._compressed_kv_cache() + swa_kv_cache = self.swa_cache_layer.kv_cache + + self._forward( + q=q, + kv_cache=self_kv_cache, + swa_k_cache=swa_kv_cache, + swa_metadata=swa_metadata, + attn_metadata=flashmla_metadata, + swa_only=swa_only, + output=output, + ) + + def _build_sparse_index_metadata( + self, + kv_cache: torch.Tensor | None, + swa_k_cache: torch.Tensor, + swa_metadata: "DeepseekSparseSWAMetadata", + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_only: bool, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Build the combined sparse-index tensors for the mixed batch. + + Returns ``(compressed_kv_cache, seq_lens, sparse_indices, + sparse_topk_lens)``. + """ + num_decodes = swa_metadata.num_decodes + num_prefills = swa_metadata.num_prefills + num_decode_tokens = swa_metadata.num_decode_tokens + num_prefill_tokens = swa_metadata.num_prefill_tokens + num_reqs = num_decodes + num_prefills + num_tokens = num_decode_tokens + num_prefill_tokens + + assert swa_metadata.seq_lens is not None + assert swa_metadata.query_start_loc is not None + assert swa_metadata.token_to_req_indices is not None + assert swa_metadata.decode_swa_indices is not None + assert swa_metadata.block_table is not None + + decode_swa_indices = swa_metadata.decode_swa_indices.reshape( + num_decode_tokens, swa_metadata.decode_swa_width + ) + decode_compressed_topk_lens = None + decode_compressed_indices_are_local = False + decode_is_valid_token = None + + if swa_only: + assert self.topk_indices_buffer is not None + compressed_kv_cache = swa_k_cache + decode_compressed_indices = None + prefill_topk_indices = self.topk_indices_buffer[ + num_decode_tokens:num_tokens, :0 + ] + compressed_block_table = None + compressed_block_size = swa_metadata.block_size + top_k = 0 + else: + assert kv_cache is not None + assert attn_metadata is not None + assert self.topk_indices_buffer is not None + assert swa_metadata.is_valid_token is not None + compressed_kv_cache = kv_cache + compressed_block_table = attn_metadata.block_table[:num_reqs] + compressed_block_size = attn_metadata.block_size // self.compress_ratio + + # Local indices filled by the index-source layer's indexer. + if num_prefill_tokens > 0: + prefill_topk_indices = self.topk_indices_buffer[ + num_decode_tokens:num_tokens + ] + top_k = prefill_topk_indices.shape[-1] + else: + prefill_topk_indices = self.topk_indices_buffer[:0, :0] + top_k = 0 + + decode_compressed_indices_are_local = True + decode_is_valid_token = swa_metadata.is_valid_token[:num_decode_tokens] + if num_decode_tokens > 0: + decode_compressed_indices = self.topk_indices_buffer[:num_decode_tokens] + else: + # Keep the logical width aligned with the mixed-batch case so + # pure-prefill steps reuse the same Triton specialization. + decode_compressed_indices = prefill_topk_indices[:0] + + query_start_loc = swa_metadata.query_start_loc[: num_reqs + 1] + seq_lens = swa_metadata.seq_lens[:num_reqs] + assert seq_lens.dtype == torch.int32 + # SWA-only layers all build the same mixed sparse indices, so the first + # one caches them for the step; indexer layers depend on their own topk + # indices and stay uncached. + cached_sparse = ( + swa_metadata.flashinfer_sparse_index_cache.get("swa_only") + if swa_only + else None + ) + if cached_sparse is None: + swa_block_span = _packed_block_span(swa_k_cache) + compressed_block_span = _packed_block_span(compressed_kv_cache) + sparse_indices, sparse_topk_lens = build_flashinfer_mixed_sparse_indices( + decode_swa_indices, + decode_compressed_indices, + decode_compressed_topk_lens, + prefill_topk_indices[:num_prefill_tokens], + query_start_loc, + seq_lens, + swa_metadata.token_to_req_indices[:num_tokens], + swa_metadata.block_table[:num_reqs], + swa_metadata.block_size, + compressed_block_table, + compressed_block_size, + self.window_size, + self.compress_ratio, + top_k, + decode_compressed_indices_are_local=decode_compressed_indices_are_local, + decode_is_valid_token=decode_is_valid_token, + swa_block_span=swa_block_span, + compressed_block_span=compressed_block_span, + prefill_left_visible=swa_metadata.prefill_left_visible, + prefill_right_visible=swa_metadata.prefill_right_visible, + # getattr for tests that bypass __init__ via object.__new__. + max_image_tokens=getattr(self, "max_image_tokens", 0), + ) + if swa_only: + swa_metadata.flashinfer_sparse_index_cache["swa_only"] = ( + sparse_indices, + sparse_topk_lens, + ) + else: + sparse_indices, sparse_topk_lens = cached_sparse + return compressed_kv_cache, seq_lens, sparse_indices, sparse_topk_lens + + def _forward( + self, + q: torch.Tensor, + kv_cache: torch.Tensor | None, + swa_k_cache: torch.Tensor, + swa_metadata: "DeepseekSparseSWAMetadata", + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_only: bool, + output: torch.Tensor, + ) -> None: + assert self.kv_cache_torch_dtype in (torch.bfloat16, torch.float8_e4m3fn) + num_decodes = swa_metadata.num_decodes + num_prefills = swa_metadata.num_prefills + num_decode_tokens = swa_metadata.num_decode_tokens + num_prefill_tokens = swa_metadata.num_prefill_tokens + num_reqs = num_decodes + num_prefills + num_tokens = num_decode_tokens + num_prefill_tokens + if num_tokens == 0: + return + + ( + compressed_kv_cache, + seq_lens, + sparse_indices, + sparse_topk_lens, + ) = self._build_sparse_index_metadata( + kv_cache=kv_cache, + swa_k_cache=swa_k_cache, + swa_metadata=swa_metadata, + attn_metadata=attn_metadata, + swa_only=swa_only, + ) + + # CUDA graph execution can pad q/output past the scheduled token count; + # restrict to the real tokens (the launcher validates sparse indices). + query = q[:num_tokens] + output = output[:num_tokens] + bmm1_scale: float | torch.Tensor = self.scale + bmm2_scale: float | torch.Tensor = 1.0 + if self.kv_cache_torch_dtype == torch.float8_e4m3fn: + assert query.dtype == torch.float8_e4m3fn + bmm1_scale = self._flashinfer_fp8_bmm1_scale + bmm2_scale = self._flashinfer_fp8_bmm2_scale + else: + assert query.dtype == torch.bfloat16 + query = query.contiguous() + + # The TRTLLM-gen sparse-MLA kernel requires h_q in {64, 128}; zero-pad + # the query heads to the allocated output head count. Padded heads attend + # to the shared KV and are sliced off downstream (output is padded too). + padded_heads = output.shape[1] + if query.shape[1] < padded_heads: + padded_query = query.new_zeros( + (query.shape[0], padded_heads, query.shape[2]) + ) + padded_query[:, : query.shape[1], :] = query + query = padded_query + + workspace = _get_flashinfer_dsv4_workspace(q.device) + query_start_loc = swa_metadata.query_start_loc + query_start_loc_cpu = swa_metadata.query_start_loc_cpu + assert query_start_loc is not None and query_start_loc_cpu is not None + + # Keep the TRTLLM-gen decode/prefill split: the launcher is tuned for + # uniform-q batches, and this avoids flattening mixed batches into one call. + if num_decode_tokens > 0: + decode_cu = query_start_loc[: num_decodes + 1] + flashinfer_trtllm_batch_decode_sparse_mla_dsv4( + query=query[:num_decode_tokens], + swa_kv_cache=swa_k_cache, + workspace_buffer=workspace, + sparse_indices=sparse_indices[:num_decode_tokens], + compressed_kv_cache=compressed_kv_cache, + sparse_topk_lens=sparse_topk_lens[:num_decode_tokens], + seq_lens=seq_lens[:num_decodes], + out=output[:num_decode_tokens], + bmm1_scale=bmm1_scale, + bmm2_scale=bmm2_scale, + sinks=self.attn_sink, + cum_seq_lens_q=decode_cu, + max_q_len=swa_metadata.max_decode_query_len, + ) + + if num_prefill_tokens > 0: + # The prefill query view re-anchors at offset 0, so rebase the + # cumulative query offsets to start at 0. + prefill_cu = ( + query_start_loc[num_decodes : num_reqs + 1] + - query_start_loc[num_decodes] + ) + prefill_cu_cpu = query_start_loc_cpu[num_decodes : num_reqs + 1] + prefill_lens_cpu = prefill_cu_cpu[1:] - prefill_cu_cpu[:-1] + flashinfer_trtllm_batch_decode_sparse_mla_dsv4( + query=query[num_decode_tokens:num_tokens], + swa_kv_cache=swa_k_cache, + workspace_buffer=workspace, + sparse_indices=sparse_indices[num_decode_tokens:num_tokens], + compressed_kv_cache=compressed_kv_cache, + sparse_topk_lens=sparse_topk_lens[num_decode_tokens:num_tokens], + seq_lens=seq_lens[num_decodes:num_reqs], + out=output[num_decode_tokens:num_tokens], + bmm1_scale=bmm1_scale, + bmm2_scale=bmm2_scale, + sinks=self.attn_sink, + cum_seq_lens_q=prefill_cu, + max_q_len=int(prefill_lens_cpu.max().item()), + ) + + +class DeepseekV4FlashInferSM120Attention(DeepseekV4Attention): + """DeepSeek V4 sparse MLA attention through FlashInfer's SM120 kernels.""" + + backend_cls = DeepseekV4FlashInferMLASparseBackend + swa_backend_cls = DeepseekSparseSWAFlashInferBackend + use_fp8_ds_mla_layout: ClassVar[bool] = True + + @staticmethod + def _get_workspace(device: torch.device) -> torch.Tensor: + return _get_flashinfer_dsv4_workspace(device) + + @staticmethod + def _as_sparse_cache(kv_cache: torch.Tensor) -> torch.Tensor: + if kv_cache.dtype == torch.float8_e4m3fn: + kv_cache = kv_cache.view(torch.uint8) + if kv_cache.dim() == 4: + return kv_cache + return kv_cache.unsqueeze(-2) + + @classmethod + def get_padded_num_q_heads(cls, num_heads: int) -> int: + return _pad_to_supported_q_heads(num_heads) + + def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + return deep_gemm_fp8_o_proj( + o, + positions, + self.rotary_emb.cos_sin_cache, + self.wo_a, + self.wo_b, + n_groups=self.n_local_groups, + heads_per_group=self.n_local_heads // self.n_local_groups, + nope_dim=self.nope_head_dim, + rope_dim=self.rope_head_dim, + o_lora_rank=self.o_lora_rank, + einsum_recipe=self._einsum_recipe, + tma_aligned_scales=self._tma_aligned_scales, + ) + + def __init__(self, vllm_config: VllmConfig, *args, **kwargs) -> None: + super().__init__(vllm_config, *args, **kwargs) + from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120_config + + required_topk = _required_sm120_sparse_topk(vllm_config, self.window_size) + if not has_flashinfer_sparse_mla_sm120_config(self.padded_heads, required_topk): + raise RuntimeError( + "FLASHINFER_MLA_SPARSE_DSV4 on SM120 requires a FlashInfer " + "DSV4 sparse MLA decode specialization for " + f"(num_q_heads={self.padded_heads}, top_k={required_topk}). " + "Install a FlashInfer build containing " + "flashinfer-ai/flashinfer#4380." + ) + self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe( + self._o_proj_block_size + ) + # Per-tensor FP8 cache path scales. + if self.kv_cache_torch_dtype != torch.float8_e4m3fn: + return + fp8_q_scale = 1.0 + fp8_kv_scale = 1.0 + self.register_buffer( + "_flashinfer_fp8_q_scale", + torch.tensor([fp8_q_scale], dtype=torch.float32), + persistent=False, + ) + self.register_buffer( + "_flashinfer_fp8_q_scale_inv", + torch.tensor([1.0 / fp8_q_scale], dtype=torch.float32), + persistent=False, + ) + self.register_buffer( + "_flashinfer_fp8_kv_scale", + torch.tensor([fp8_kv_scale], dtype=torch.float32), + persistent=False, + ) + # FlashInfer expects scalar scale arguments for this path. + self._flashinfer_fp8_bmm1_scale = self.scale * fp8_q_scale * fp8_kv_scale + self._flashinfer_fp8_bmm2_scale = fp8_kv_scale + + def _reserve_empty_forward_workspace(self) -> None: + self._get_workspace( + torch.device("cuda", torch.accelerator.current_device_index()) + ) + + def _forward_sparse_impl( + self, + q: torch.Tensor, + output: torch.Tensor, + flashmla_metadata: DeepseekV4FlashMLAMetadata | None, + swa_metadata: "DeepseekSparseSWAMetadata", + self_kv_cache: torch.Tensor | None, + swa_kv_cache: torch.Tensor, + swa_only: bool, + ) -> None: + num_decode_tokens = swa_metadata.num_decode_tokens + if swa_metadata.num_prefills > 0: + self._forward_prefill( + q=q[num_decode_tokens:], + compressed_k_cache=self_kv_cache, + swa_k_cache=swa_kv_cache, + output=output[num_decode_tokens:], + attn_metadata=flashmla_metadata, + swa_metadata=swa_metadata, + ) + if swa_metadata.num_decodes > 0: + self._forward_decode( + q=q[:num_decode_tokens], + kv_cache=self_kv_cache, + swa_metadata=swa_metadata, + attn_metadata=flashmla_metadata, + swa_only=swa_only, + output=output[:num_decode_tokens], + ) + + def forward_mqa( + self, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + output: torch.Tensor, + ) -> None: + # Output may be padded to backend-supported head counts. + assert output.shape[0] == q.shape[0] and output.shape[-1] == q.shape[-1], ( + f"output buffer shape {output.shape} incompatible with q shape {q.shape}" + ) + assert output.shape[1] >= q.shape[1], ( + f"output heads {output.shape[1]} must be >= q heads {q.shape[1]}" + ) + # Per-tensor FP8 q produces a bf16 attention output. + expected_output_dtype = ( + torch.bfloat16 if q.dtype == torch.float8_e4m3fn else q.dtype + ) + assert output.dtype == expected_output_dtype, ( + f"output dtype {output.dtype} must match expected {expected_output_dtype} " + f"for q dtype {q.dtype}" + ) + + forward_context = get_forward_context() + attn_metadata = forward_context.attn_metadata + if attn_metadata is None: + self._reserve_empty_forward_workspace() + output.zero_() + return + + assert isinstance(attn_metadata, dict) + # Compressed-cache metadata lives on the kv-source layer's prefix; + # consumers share that cache and its block table. + flashmla_metadata = cast( + DeepseekV4FlashMLAMetadata | None, + attn_metadata.get(self.compressed_cache_prefix) + if self.compressed_cache_prefix is not None + else None, + ) + swa_metadata = cast( + "DeepseekSparseSWAMetadata | None", + attn_metadata.get(self.swa_cache_layer.prefix), + ) + assert swa_metadata is not None + + swa_only = self.compress_ratio == 0 + # SWA-only layers have no compressed KV cache; consumers read the kv + # source's cache. + self_kv_cache = None if swa_only else self._compressed_kv_cache() + swa_kv_cache = self.swa_cache_layer.kv_cache + + self._forward_sparse_impl( + q=q, + output=output, + flashmla_metadata=flashmla_metadata, + swa_metadata=swa_metadata, + self_kv_cache=self_kv_cache, + swa_kv_cache=swa_kv_cache, + swa_only=swa_only, + ) + + def _prepare_query(self, q: torch.Tensor, output: torch.Tensor) -> torch.Tensor: + if self.kv_cache_torch_dtype == torch.float8_e4m3fn: + assert q.dtype == torch.float8_e4m3fn + q = q.to(torch.bfloat16) + else: + assert q.dtype == torch.bfloat16 + padded_heads = output.shape[1] + if q.shape[1] < padded_heads: + padded_query = q.new_zeros((q.shape[0], padded_heads, q.shape[2])) + padded_query[:, : q.shape[1], :] = q + q = padded_query + return q.contiguous() + + def _forward_decode( + self, + q: torch.Tensor, + kv_cache: torch.Tensor | None, + swa_metadata: "DeepseekSparseSWAMetadata", + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_only: bool, + output: torch.Tensor, + ) -> None: + num_decodes = swa_metadata.num_decodes + num_decode_tokens = swa_metadata.num_decode_tokens + + extra_sparse_indices = None + extra_sparse_lengths = None + if not swa_only: + if attn_metadata is None: + raise RuntimeError( + "Sparse MLA metadata is required for compressed layers." + ) + if swa_metadata.is_valid_token is None: + raise RuntimeError( + "SWA validity metadata is required for compressed layers." + ) + if self.topk_indices_buffer is None: + raise RuntimeError( + "Compressed-layer decode requires top-k indices from the indexer." + ) + # Local indices filled by the index-source layer's indexer. + is_valid = swa_metadata.is_valid_token[:num_decode_tokens] + block_size = attn_metadata.block_size // self.compress_ratio + global_indices, extra_sparse_lengths = compute_global_topk_indices_and_lens( + self.topk_indices_buffer[:num_decode_tokens], + swa_metadata.token_to_req_indices, + attn_metadata.block_table[:num_decodes], + block_size, + is_valid, + ) + extra_sparse_indices = global_indices.view(num_decode_tokens, 1, -1) + + swa_indices = swa_metadata.decode_swa_indices + swa_lens = swa_metadata.decode_swa_lens + assert swa_indices is not None + assert swa_lens is not None + q = self._prepare_query(q, output) + swa_cache = self._as_sparse_cache(self.swa_cache_layer.kv_cache) + extra_cache = self._as_sparse_cache(kv_cache) if kv_cache is not None else None + if extra_cache is not None and extra_sparse_indices is None: + raise RuntimeError( + "Compressed sparse MLA decode requires compressed sparse indices." + ) + flashinfer_trtllm_batch_decode_sparse_mla_dsv4( + query=q, + swa_kv_cache=swa_cache, + workspace_buffer=self._get_workspace(q.device), + sparse_indices=swa_indices, + compressed_kv_cache=extra_cache, + out=output, + bmm1_scale=self.scale, + sinks=self.attn_sink, + kv_layout="NHD", + swa_topk_lens=swa_lens, + extra_sparse_indices=extra_sparse_indices, + extra_sparse_topk_lens=extra_sparse_lengths, + ) + + def _forward_prefill( + self, + q: torch.Tensor, + compressed_k_cache: torch.Tensor | None, + swa_k_cache: torch.Tensor, + output: torch.Tensor, + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_metadata: "DeepseekSparseSWAMetadata", + ) -> None: + swa_only = self.compress_ratio == 0 + + num_prefills = swa_metadata.num_prefills + num_decodes = swa_metadata.num_decodes + num_decode_tokens = swa_metadata.num_decode_tokens + num_prefill_tokens = swa_metadata.num_prefill_tokens + + query_start_loc_cpu = swa_metadata.query_start_loc_cpu + assert query_start_loc_cpu is not None + prefill_token_base = query_start_loc_cpu[num_decodes] + + extra_sparse_indices: torch.Tensor | None = None + extra_sparse_lengths: torch.Tensor | None = None + if not swa_only: + if self.topk_indices_buffer is None: + raise RuntimeError( + "Compressed-layer prefill requires top-k indices from the indexer." + ) + if attn_metadata is None: + raise RuntimeError("Compressed-layer prefill metadata is missing.") + if swa_metadata.token_to_req_indices is None: + raise RuntimeError( + "Compressed-layer prefill request mapping is missing." + ) + if swa_metadata.is_valid_token is None: + raise RuntimeError( + "Compressed-layer prefill validity metadata is missing." + ) + # Local indices filled by the index-source layer's indexer. + local_topk_indices = self.topk_indices_buffer[ + num_decode_tokens : num_decode_tokens + num_prefill_tokens + ] + prefill_token_slice = slice( + num_decode_tokens, num_decode_tokens + num_prefill_tokens + ) + block_size = attn_metadata.block_size // self.compress_ratio + extra_sparse_indices, extra_sparse_lengths = ( + compute_global_topk_indices_and_lens( + local_topk_indices, + swa_metadata.token_to_req_indices[prefill_token_slice], + attn_metadata.block_table, + block_size, + swa_metadata.is_valid_token[prefill_token_slice], + ) + ) + + assert swa_metadata.prefill_swa_indices is not None + assert swa_metadata.prefill_swa_lens is not None + + q = self._prepare_query(q, output) + swa_kv_paged = self._as_sparse_cache(swa_k_cache) + if swa_only: + extra_kv_paged = None + else: + if compressed_k_cache is None: + raise RuntimeError( + "Compressed sparse MLA layers require their compressed KV cache." + ) + extra_kv_paged = self._as_sparse_cache(compressed_k_cache) + + num_chunks = ( + num_prefills + self.PREFILL_CHUNK_SIZE - 1 + ) // self.PREFILL_CHUNK_SIZE + for chunk_idx in range(num_chunks): + chunk_start = chunk_idx * self.PREFILL_CHUNK_SIZE + chunk_end = min(chunk_start + self.PREFILL_CHUNK_SIZE, num_prefills) + query_start = ( + query_start_loc_cpu[num_decodes + chunk_start] - prefill_token_base + ) + query_end = ( + query_start_loc_cpu[num_decodes + chunk_end] - prefill_token_base + ) + + extra_sparse_indices_chunk = ( + extra_sparse_indices[query_start:query_end] + if extra_sparse_indices is not None + else None + ) + extra_sparse_lengths_chunk = ( + extra_sparse_lengths[query_start:query_end] + if extra_sparse_lengths is not None + else None + ) + + q_chunk = q[query_start:query_end] + swa_indices_chunk = swa_metadata.prefill_swa_indices[query_start:query_end] + swa_lens_chunk = swa_metadata.prefill_swa_lens[query_start:query_end] + if extra_kv_paged is not None and extra_sparse_indices_chunk is None: + raise RuntimeError( + "Compressed sparse MLA prefill requires compressed sparse indices." + ) + flashinfer_trtllm_batch_decode_sparse_mla_dsv4( + query=q_chunk, + swa_kv_cache=swa_kv_paged, + workspace_buffer=self._get_workspace(q.device), + sparse_indices=swa_indices_chunk, + compressed_kv_cache=extra_kv_paged, + out=output[query_start:query_end], + bmm1_scale=self.scale, + sinks=self.attn_sink, + kv_layout="NHD", + swa_topk_lens=swa_lens_chunk, + extra_sparse_indices=extra_sparse_indices_chunk, + extra_sparse_topk_lens=extra_sparse_lengths_chunk, + ) diff --git a/vllm/models/deepseek_v4_1/nvidia/flashmla.py b/vllm/models/deepseek_v4_1/nvidia/flashmla.py new file mode 100644 index 0000000000..86d8fb2031 --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/flashmla.py @@ -0,0 +1,387 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from typing import TYPE_CHECKING, ClassVar, cast + +import torch + +from vllm.forward_context import get_forward_context +from vllm.models.deepseek_v4.nvidia.ops.o_proj import ( + compute_fp8_einsum_recipe, + deep_gemm_fp8_o_proj, +) +from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention +from vllm.models.deepseek_v4_1.common.ops import ( + combine_topk_swa_indices, + compute_global_topk_indices_and_lens, + dequantize_and_gather_k_cache, +) +from vllm.models.deepseek_v4_1.sparse_mla import ( + DeepseekV4FlashMLABackend, + DeepseekV4FlashMLAMetadata, + DeepseekV41SparseSWAMetadataBuilder, +) +from vllm.utils.math_utils import round_up +from vllm.v1.attention.backend import AttentionCGSupport +from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWABackend +from vllm.v1.attention.ops.flashmla import ( + flash_mla_sparse_fwd, + flash_mla_with_kvcache, +) +from vllm.v1.worker.workspace import current_workspace_manager + +if TYPE_CHECKING: + from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata + + +class DeepseekSparseSWAFlashMLAMetadataBuilder(DeepseekV41SparseSWAMetadataBuilder): + """SWA metadata for the FlashMLA decode path, which allows varlen decode.""" + + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS + + +class DeepseekSparseSWAFlashMLABackend(DeepseekSparseSWABackend): + @staticmethod + def get_builder_cls() -> type[DeepseekSparseSWAFlashMLAMetadataBuilder]: + return DeepseekSparseSWAFlashMLAMetadataBuilder + + +class DeepseekV4FlashMLAAttention(DeepseekV4Attention): + """FlashMLA sparse MLA attention layer for DeepSeek V4.1 (CUDA).""" + + backend_cls = DeepseekV4FlashMLABackend + swa_backend_cls = DeepseekSparseSWAFlashMLABackend + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe( + self._o_proj_block_size + ) + + def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + return deep_gemm_fp8_o_proj( + o, + positions, + self.rotary_emb.cos_sin_cache, + self.wo_a, + self.wo_b, + n_groups=self.n_local_groups, + heads_per_group=self.n_local_heads // self.n_local_groups, + nope_dim=self.nope_head_dim, + rope_dim=self.rope_head_dim, + o_lora_rank=self.o_lora_rank, + einsum_recipe=self._einsum_recipe, + tma_aligned_scales=self._tma_aligned_scales, + ) + + @classmethod + def get_padded_num_q_heads(cls, num_heads: int) -> int: + # FP8 decode kernel only supports h_q = 64 or 128. + if num_heads > 128: + raise ValueError( + f"DeepseekV4 FlashMLA does not support {num_heads} heads " + "(FP8 decode kernel requires h_q in {64, 128})." + ) + return 64 if num_heads <= 64 else 128 + + def forward_mqa( + self, + q: torch.Tensor, + kv: torch.Tensor, + positions: torch.Tensor, + output: torch.Tensor, + ) -> None: + assert output.shape == q.shape, ( + f"output buffer shape {output.shape} must match q shape {q.shape}" + ) + assert output.dtype == q.dtype, ( + f"output buffer dtype {output.dtype} must match q dtype {q.dtype}" + ) + + # Get SWA and indexer metadata from forward context + forward_context = get_forward_context() + attn_metadata = forward_context.attn_metadata + + if attn_metadata is None: + # Warmup dummy run: no real metadata. Reserve the same bf16 + # gather workspace _forward_prefill would; the dequantize / topk + # / sparse_fwd kernels are skipped this step. + swa_only = self.compress_ratio == 0 + N = ( + 0 + if swa_only + else (self.max_model_len + self.compress_ratio - 1) + // self.compress_ratio + ) + M = N + self.window_size + self.max_num_batched_tokens + if swa_only: + top_k = 0 + else: + assert self.topk_indices_buffer is not None + top_k = self.topk_indices_buffer.shape[-1] + combined_topk = round_up( + top_k + self.window_size + self.max_image_tokens, 128 + ) + current_workspace_manager().get_simultaneous( + ((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16), + ((self.max_num_batched_tokens, combined_topk), torch.int32), + ((self.max_num_batched_tokens,), torch.int32), + ) + output.zero_() + return + + assert isinstance(attn_metadata, dict) + # Compressed-cache metadata lives on the kv-source layer's prefix; + # consumers share that cache and its block table. + flashmla_metadata = cast( + DeepseekV4FlashMLAMetadata | None, + attn_metadata.get(self.compressed_cache_prefix) + if self.compressed_cache_prefix is not None + else None, + ) + swa_metadata = cast( + "DeepseekSparseSWAMetadata | None", + attn_metadata.get(self.swa_cache_layer.prefix), + ) + assert swa_metadata is not None + + swa_only = self.compress_ratio == 0 + # SWA-only layers (compress_ratio == 0) don't have their own KV cache + # allocation; consumers read the kv source's cache, which is bound on + # the source layer. + self_kv_cache = None if swa_only else self._compressed_kv_cache() + swa_kv_cache = self.swa_cache_layer.kv_cache + + # Split prefill and decode + num_decodes = swa_metadata.num_decodes + num_prefills = swa_metadata.num_prefills + num_decode_tokens = swa_metadata.num_decode_tokens + + if num_prefills > 0: + self._forward_prefill( + q=q[num_decode_tokens:], + positions=positions[num_decode_tokens:], + compressed_k_cache=self_kv_cache, + swa_k_cache=swa_kv_cache, + output=output[num_decode_tokens:], + attn_metadata=flashmla_metadata, + swa_metadata=swa_metadata, + ) + if num_decodes > 0: + self._forward_decode( + q=q[:num_decode_tokens], + kv_cache=self_kv_cache, + swa_metadata=swa_metadata, + attn_metadata=flashmla_metadata, + swa_only=swa_only, + output=output[:num_decode_tokens], + ) + + def _forward_decode( + self, + q: torch.Tensor, + kv_cache: torch.Tensor | None, # None for SWA-only layers + swa_metadata: "DeepseekSparseSWAMetadata", + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_only: bool, + output: torch.Tensor, + ) -> None: + num_decodes = swa_metadata.num_decodes + num_decode_tokens = swa_metadata.num_decode_tokens + + topk_indices = None + topk_lens = None + if not swa_only: + # Local indices filled by the index-source layer's indexer. + assert attn_metadata is not None + assert swa_metadata.is_valid_token is not None + assert self.topk_indices_buffer is not None + block_size = attn_metadata.block_size // self.compress_ratio + is_valid = swa_metadata.is_valid_token[:num_decode_tokens] + global_indices, topk_lens = compute_global_topk_indices_and_lens( + self.topk_indices_buffer[:num_decode_tokens], + swa_metadata.token_to_req_indices, + attn_metadata.block_table[:num_decodes], + block_size, + is_valid, + ) + topk_indices = global_indices.view(num_decode_tokens, 1, -1) + + swa_indices = swa_metadata.decode_swa_indices + swa_lens = swa_metadata.decode_swa_lens + + # We treat queries in the same seq as different queries + # and later we only attend by generated indices. + # q arrives pre-padded to self.padded_heads by the outer wrapper. + q = q.unsqueeze(1) + + # Prepare SWA cache (num_blocks, swa_block_size, 1, head_bytes) + # Use unsqueeze to preserve strides (handles padded blocks correctly) + swa_cache = self.swa_cache_layer.kv_cache.unsqueeze(-2) + # Reshape KV cache to (num_blocks, block_size, 1, head_bytes) + if kv_cache is not None: + kv_cache = kv_cache.unsqueeze(-2) + + # One FlashMLASchedMeta per layer type, shared across all same-type + # layers within this decode step. The first forward call per type + # triggers the in-kernel planner (allocating tile_scheduler_metadata + # and num_splits via PyTorch's graph-aware allocator so CUDA graph + # capture reuses the same addresses on replay); subsequent same-type + # layers see have_initialized=True and skip the planner. + tile_metadata = { + 0: swa_metadata.tile_sched_swaonly, + 1: swa_metadata.tile_sched_c1a, + 2: swa_metadata.tile_sched_c2a, + }[self.compress_ratio] + assert tile_metadata is not None, ( + "swa_metadata missing tile_sched entry for " + f"compress_ratio={self.compress_ratio}; " + "DeepseekSparseSWAMetadataBuilder.build_tile_scheduler did not " + "allocate one for this layer type." + ) + + out, _ = flash_mla_with_kvcache( + q=q, + k_cache=swa_cache, + block_table=None, + head_dim_v=512, + tile_scheduler_metadata=tile_metadata, + cache_seqlens=None, + is_fp8_kvcache=True, + indices=swa_indices, + topk_length=swa_lens, + softmax_scale=self.scale, + attn_sink=self.attn_sink, + extra_k_cache=kv_cache if not swa_only else None, + extra_indices_in_kvcache=topk_indices, + extra_topk_length=topk_lens, + out=output.unsqueeze(1), + ) + + def _forward_prefill( + self, + q: torch.Tensor, + positions: torch.Tensor, + compressed_k_cache: torch.Tensor | None, # None for SWA-only layers + swa_k_cache: torch.Tensor, + output: torch.Tensor, + attn_metadata: DeepseekV4FlashMLAMetadata | None, + swa_metadata: "DeepseekSparseSWAMetadata", + ) -> None: + swa_only = self.compress_ratio == 0 + + num_prefill_tokens = swa_metadata.num_prefill_tokens + num_decodes = swa_metadata.num_decodes + num_decode_tokens = swa_metadata.num_decode_tokens + + # Use pre-computed prefill metadata. + seq_lens = swa_metadata.prefill_seq_lens + gather_lens = swa_metadata.prefill_gather_lens + assert seq_lens is not None + assert gather_lens is not None + + # Derive prefill-local token offsets from the full query_start_loc_cpu. + query_start_loc_cpu = swa_metadata.query_start_loc_cpu + query_start_loc = swa_metadata.query_start_loc + assert query_start_loc_cpu is not None + assert query_start_loc is not None + prefill_token_base = query_start_loc_cpu[num_decodes] + + # Local indices filled by the index source; SWA-only layers pass + # top_k=0 and never read them. + assert self.topk_indices_buffer is not None + topk_indices = self.topk_indices_buffer[num_decode_tokens:] + topk_indices = topk_indices[:num_prefill_tokens] + top_k = 0 if swa_only else topk_indices.shape[-1] + chunk_plan = swa_metadata.get_prefill_chunk_plan( + compress_ratio=self.compress_ratio, + prefill_chunk_size=self.PREFILL_CHUNK_SIZE, + # v4.1: every cr>0 layer (including cr==1) gathers a full-length + # compressed region; only cr==0 layers are SWA-only. + has_compressed=not swa_only, + ) + assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0" + workspace_manager = current_workspace_manager() + combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128) + for chunk_start, chunk_end, chunk_N, chunk_M in chunk_plan: + chunk_size = chunk_end - chunk_start + workspace = workspace_manager.get_simultaneous( + ((chunk_size, chunk_M, q.shape[-1]), torch.bfloat16), + ((self.max_num_batched_tokens, combined_topk), torch.int32), + ((self.max_num_batched_tokens,), torch.int32), + ) + kv, combined_indices_out, combined_lens_out = workspace + if not swa_only: + # Gather compressed KV + assert attn_metadata is not None + block_table = attn_metadata.block_table[num_decodes:] + dequantize_and_gather_k_cache( + kv[:chunk_size], + compressed_k_cache, + seq_lens=seq_lens[chunk_start:chunk_end] // self.compress_ratio, + gather_lens=None, + block_table=block_table[chunk_start:chunk_end], + block_size=attn_metadata.block_size // self.compress_ratio, + offset=0, + ) + + # Gather SWA KV + swa_block_table = swa_metadata.block_table[num_decodes:] + dequantize_and_gather_k_cache( + kv[:chunk_size], + swa_k_cache, + seq_lens=seq_lens[chunk_start:chunk_end], + gather_lens=gather_lens[chunk_start:chunk_end], + block_table=swa_block_table[chunk_start:chunk_end], + block_size=swa_metadata.block_size, + offset=chunk_N, + ) + + # Combine the topk indices and SWA indices for gathered KV cache + query_start = ( + query_start_loc_cpu[num_decodes + chunk_start] - prefill_token_base + ) + query_end = ( + query_start_loc_cpu[num_decodes + chunk_end] - prefill_token_base + ) + combined_indices_out = combined_indices_out[: query_end - query_start] + combined_lens_out = combined_lens_out[: query_end - query_start] + + combined_indices, combined_lens = combine_topk_swa_indices( + topk_indices[query_start:query_end], + query_start_loc[ + num_decodes + chunk_start : num_decodes + chunk_end + 1 + ], + seq_lens[chunk_start:chunk_end], + gather_lens[chunk_start:chunk_end], + self.window_size, + self.compress_ratio, + top_k, + chunk_M, + chunk_N, + out=(combined_indices_out, combined_lens_out), + left_visible=( + swa_metadata.prefill_left_visible[ + num_decode_tokens + query_start : num_decode_tokens + query_end + ] + if swa_metadata.prefill_left_visible is not None + else None + ), + right_visible=( + swa_metadata.prefill_right_visible[ + num_decode_tokens + query_start : num_decode_tokens + query_end + ] + if swa_metadata.prefill_right_visible is not None + else None + ), + max_image_tokens=self.max_image_tokens, + ) + flash_mla_sparse_fwd( + q=q[query_start:query_end], + kv=kv.view(-1, 1, q.shape[-1]), + indices=combined_indices.unsqueeze(1), + sm_scale=self.scale, + attn_sink=self.attn_sink, + topk_length=combined_lens, + out=output[query_start:query_end], + ) diff --git a/vllm/models/deepseek_v4_1/nvidia/model.py b/vllm/models/deepseek_v4_1/nvidia/model.py new file mode 100644 index 0000000000..6d803736ec --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/model.py @@ -0,0 +1,1111 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import typing +from collections.abc import Callable, Iterable +from itertools import islice + +import regex as re +import torch +import torch.nn as nn + +import vllm.envs as envs +from vllm.config import VllmConfig +from vllm.config.kernel import MEGA_MOE_BACKENDS +from vllm.distributed import ( + get_pp_group, + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, +) +from vllm.forward_context import get_forward_context, is_forward_context_available +from vllm.logger import init_logger +from vllm.model_executor.kernels.mhc.tilelang import ( + mhc_post_tilelang, + mhc_pre_delayed_tilelang, +) +from vllm.model_executor.kernels.mhc.triton import hc_collapse_triton +from vllm.model_executor.layers.fused_moe import ( + fused_moe_make_expert_params_mapping, +) +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.logits_processor import LogitsProcessor +from vllm.model_executor.layers.quantization import QuantizationConfig +from vllm.model_executor.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, +) +from vllm.model_executor.model_loader.weight_utils import default_weight_loader +from vllm.model_executor.models.interfaces import ( + EagleModelMixin, + MixtureOfExperts, + SupportsEagle3, + SupportsLoRA, + SupportsPP, +) +from vllm.model_executor.models.utils import ( + AutoWeightsLoader, + PPMissingLayer, + WeightsMapper, + extract_layer_index, + is_pp_missing_parameter, + make_layers, + maybe_prefix, +) +from vllm.models.common.ops.sequence_parallel import ( + sp_all_gather, + sp_padding_mask, + sp_reduce_scatter, + sp_shard, +) +from vllm.models.deepseek_v4.nvidia.model import ( + DeepseekV4MoE as DeepseekV4MoEBase, +) +from vllm.models.deepseek_v4.nvidia.model import ( + make_deepseek_v4_expert_params_mapping, +) +from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention +from vllm.models.deepseek_v4_1.nvidia.flashinfer_sparse import ( + DeepseekV4FlashInferMLAAttention, + DeepseekV4FlashInferSM120Attention, +) +from vllm.models.deepseek_v4_1.nvidia.flashmla import DeepseekV4FlashMLAAttention +from vllm.platforms import current_platform +from vllm.sequence import IntermediateTensors +from vllm.utils.math_utils import cdiv +from vllm.v1.attention.backends.registry import AttentionBackendEnum +from vllm.v1.worker.ubatching import dbo_current_ubatch_id + +from ..common.engram import Engram, EngramLayout, NgramHashState +from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask + +if typing.TYPE_CHECKING: + from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata + +logger = init_logger(__name__) + + +class DeepseekV4MoE(DeepseekV4MoEBase): + def __init__( + self, + vllm_config: VllmConfig, + prefix: str = "", + use_sequence_parallel: bool = False, + ): + config = vllm_config.model_config.hf_config + n_routed_experts = config.n_routed_experts + n_activated_experts = config.num_experts_per_tok + if extract_layer_index(prefix) >= config.num_hidden_layers: + n_routed_experts = ( + getattr(config, "dspark_n_routed_experts", 0) or n_routed_experts + ) + n_activated_experts = ( + getattr(config, "dspark_num_experts_per_tok", 0) or n_activated_experts + ) + super().__init__( + vllm_config, + prefix=prefix, + use_sequence_parallel=use_sequence_parallel, + n_routed_experts=n_routed_experts, + n_activated_experts=n_activated_experts, + num_hash_layers=0, + image_sentinel_lo=IMAGE_SENTINEL_BASE_ID, + ) + + +def _select_dsv4_attn_cls(vllm_config: VllmConfig) -> type[DeepseekV4Attention]: + """Pick the CUDA sparse-MLA attention class for the configured backend. + + The generic CUDA backend selector does not instantiate DSv4 layers directly, + so map generic sparse-MLA choices to the DSv4-specialized attention class. + Without an explicit backend, SM12 defaults to FlashInfer while the other + CUDA arches keep the FlashMLA path. + """ + backend = vllm_config.attention_config.backend + device_capability = current_platform.get_device_capability() + if backend in ( + AttentionBackendEnum.FLASHINFER_MLA_SPARSE, + AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM120, + ): + raise ValueError( + f"{backend.name} is not a DeepSeek V4.1 attention backend. " + "Use FLASHINFER_MLA_SPARSE_DSV41 for DeepSeek V4.1 FlashInfer " + "sparse MLA." + ) + if backend in ( + AttentionBackendEnum.FLASHINFER_MLA_SPARSE_DSV4, + AttentionBackendEnum.FLASHINFER_MLA_SPARSE_DSV41, + ): + if device_capability is not None and device_capability.major == 12: + return DeepseekV4FlashInferSM120Attention + return DeepseekV4FlashInferMLAAttention + if backend in ( + AttentionBackendEnum.FLASHMLA_SPARSE, + AttentionBackendEnum.FLASHMLA_SPARSE_DSV4, + AttentionBackendEnum.FLASHMLA_SPARSE_DSV41, + ): + return DeepseekV4FlashMLAAttention + + if device_capability is not None and device_capability.major == 12: + return DeepseekV4FlashInferSM120Attention + return DeepseekV4FlashMLAAttention + + +def _use_sequence_parallel(vllm_config: VllmConfig) -> bool: + parallel_config = vllm_config.parallel_config + use_mega_moe = vllm_config.kernel_config.moe_backend in MEGA_MOE_BACKENDS + return ( + parallel_config.pipeline_parallel_size == 1 + and parallel_config.enable_expert_parallel + and parallel_config.tensor_parallel_size > 1 + and (use_mega_moe or parallel_config.data_parallel_size > 1) + ) + + +class DeepseekV4DecoderLayer(nn.Module): + def __init__( + self, + vllm_config, + prefix, + topk_indices_buffer: torch.Tensor | None = None, + aux_stream_list: list[torch.cuda.Stream] | None = None, + candidate_block_buffer: torch.Tensor | None = None, + engram_layout: EngramLayout | None = None, + ): + super().__init__() + + config = vllm_config.model_config.hf_config + self.hidden_size = config.hidden_size + self.use_sequence_parallel = _use_sequence_parallel(vllm_config) + + self.engram: Engram | None = None + if engram_layout is not None: + layer_id = extract_layer_index(prefix) + if layer_id in engram_layout.layer_ids: + self.engram = Engram( + config, + vllm_config.quant_config, + engram_layout, + engram_layout.layer_ids.index(layer_id), + use_sequence_parallel=self.use_sequence_parallel, + prefix=f"{prefix}.engram", + ) + + self.rms_norm_eps = config.rms_norm_eps + self.attn = _select_dsv4_attn_cls(vllm_config)( + vllm_config, + prefix=f"{prefix}.attn", + topk_indices_buffer=topk_indices_buffer, + aux_stream_list=aux_stream_list, + candidate_block_buffer=candidate_block_buffer, + ) + if self.use_sequence_parallel: + self.attn.wo_b.reduce_results = False + self.ffn = DeepseekV4MoE( + vllm_config, + prefix=f"{prefix}.ffn", + use_sequence_parallel=self.use_sequence_parallel, + ) + + self.attn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps) + self.ffn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps) + self.hc_mult = config.hc_mult + self.hc_sinkhorn_iters = config.hc_sinkhorn_iters + self.hc_eps = config.hc_eps + self.hc_post_alpha = 2.0 + if vllm_config.kernel_config.enable_jit_warmup and current_platform.is_cuda(): + from vllm.model_executor.kernels.mhc.warmup import MHC_PRE_NORM_KERNEL + + max_tokens = vllm_config.scheduler_config.max_num_batched_tokens + if self.use_sequence_parallel: + tp_size = vllm_config.parallel_config.tensor_parallel_size + max_tokens = (max_tokens + tp_size - 1) // tp_size + for input_size, use_pre_mix in ( + (self.hidden_size, False), + (self.hc_mult * self.hidden_size, False), + (self.hc_mult * self.hidden_size, True), + ): + MHC_PRE_NORM_KERNEL.register_warmup( + max_tokens=max_tokens, + hidden_size=self.hidden_size, + rms_eps=self.rms_norm_eps, + hc_pre_eps=self.hc_eps, + hc_sinkhorn_eps=self.hc_eps, + hc_post_mult_value=self.hc_post_alpha, + sinkhorn_repeat=self.hc_sinkhorn_iters, + norm_eps=self.rms_norm_eps, + hc_mult=self.hc_mult, + use_pre_mix_in=use_pre_mix, + rms_numel=input_size, + ) + mix_hc = (2 + self.hc_mult) * self.hc_mult + hc_dim = self.hc_mult * self.hidden_size + self.hc_attn_fn = nn.Parameter( + torch.empty( + (mix_hc, hc_dim), + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_attn_fn_broadcast: torch.Tensor | None = None + self.hc_ffn_fn = nn.Parameter( + torch.empty( + (mix_hc, hc_dim), + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_attn_base = nn.Parameter( + torch.empty( + mix_hc, + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_ffn_base = nn.Parameter( + torch.empty( + mix_hc, + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_attn_scale = nn.Parameter( + torch.empty( + 3, + dtype=torch.float32, + ), + requires_grad=False, + ) + self.hc_ffn_scale = nn.Parameter( + torch.empty( + 3, + dtype=torch.float32, + ), + requires_grad=False, + ) + + def forward( + self, + x: torch.Tensor, + positions: torch.Tensor, + input_ids: torch.Tensor | None, + pre_mix: torch.Tensor | None = None, + post_mix: torch.Tensor | None = None, + res_mix: torch.Tensor | None = None, + residual: torch.Tensor | None = None, + engram_hashes: torch.Tensor | None = None, + engram_mask: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + # The reference collapses each sublayer's input with the *previous* + # sublayer's pre-mix: attention uses the pre-mix carried in (identity + # for the first layer), the FFN uses this layer's attention pre-mix. + if residual is None: + if x.dim() == 2: + # First layer: the stream is the embedding broadcast to hc + # copies and the identity pre-mix selects copy 0. + assert self.hc_attn_fn_broadcast is not None + residual = x.unsqueeze(1).expand(-1, self.hc_mult, -1).contiguous() + post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang( + residual, + self.hc_attn_fn_broadcast, + self.hc_attn_scale, + self.hc_attn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + x=x, + norm_weight=self.attn_norm.weight, + norm_eps=self.attn_norm.variance_epsilon, + ) + else: + residual = x + post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang( + residual, + self.hc_attn_fn, + self.hc_attn_scale, + self.hc_attn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + pre_mix=pre_mix, + norm_weight=self.attn_norm.weight, + norm_eps=self.attn_norm.variance_epsilon, + ) + else: + residual = mhc_post_tilelang(x, residual, post_mix, res_mix) + if self.engram is not None and engram_hashes is not None: + # Engram injection happens between the previous sublayer's + # post and this block's pre, on the full hc stream, so the + # mix coefficients see the injected stream. + residual = self.engram( + residual, + engram_hashes[:, self.engram.layer_hash_index], + engram_mask, + ) + post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang( + residual, + self.hc_attn_fn, + self.hc_attn_scale, + self.hc_attn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + pre_mix=pre_mix, + norm_weight=self.attn_norm.weight, + norm_eps=self.attn_norm.variance_epsilon, + ) + + if self.use_sequence_parallel: + x = sp_all_gather(x)[: positions.shape[0]] + + x = self.attn(positions, x, None) + if self.use_sequence_parallel: + x = sp_reduce_scatter(x) + + residual = mhc_post_tilelang(x, residual, post_mix, res_mix) + post_mix, res_mix, x, ffn_pre = mhc_pre_delayed_tilelang( + residual, + self.hc_ffn_fn, + self.hc_ffn_scale, + self.hc_ffn_base, + self.rms_norm_eps, + self.hc_eps, + self.hc_eps, + self.hc_post_alpha, + self.hc_sinkhorn_iters, + pre_mix=attn_pre, + norm_weight=self.ffn_norm.weight, + norm_eps=self.ffn_norm.variance_epsilon, + ) + x = self.ffn(x, input_ids) + return x, residual, post_mix, res_mix, ffn_pre + + +class DeepseekV4Model(nn.Module, EagleModelMixin): + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): + super().__init__() + + config = vllm_config.model_config.hf_config + quant_config = vllm_config.quant_config + self.config = config + self.quant_config = quant_config + self.parallel_config = vllm_config.parallel_config + self.use_mega_moe = vllm_config.kernel_config.moe_backend in MEGA_MOE_BACKENDS + self.use_sequence_parallel = _use_sequence_parallel(vllm_config) + if self.use_mega_moe and not vllm_config.parallel_config.enable_expert_parallel: + raise NotImplementedError( + "DeepSeek V4 MegaMoE currently requires expert parallel. " + "Enable it with --enable-expert-parallel, or pick a different " + "moe backend." + ) + self.vocab_size = config.vocab_size + self.hc_eps = config.hc_eps + self.hc_mult = config.hc_mult + self.hc_dim = self.hc_mult * config.hidden_size + self.rms_norm_eps = config.rms_norm_eps + + # Three aux streams: one per non-default input GEMM in + # DeepseekV4Attention._run_parallel_input_projections + # (compressor kv_score, indexer.weights_proj). fused_wqa_wkv stays on + # the default stream. + aux_stream_list = [torch.cuda.Stream() for _ in range(3)] + + # Reserved topk indices buffer for all Indexer layers to reuse. + self.topk_indices_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + config.index_topk, + dtype=torch.int32, + ) + + # Two-level candidate filtering: the indexer at + # candidate_source_layer_id publishes the top candidate blocks of + # compressed positions here; later ratio-1 indexers (24/28/32/36) + # mask their scores with it. + candidate_source_layer = getattr(config, "candidate_source_layer_id", -1) + candidate_topk_blocks = getattr(config, "candidate_topk_blocks", 0) + if candidate_source_layer >= 0 and candidate_topk_blocks > 0: + self.candidate_block_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + candidate_topk_blocks, + dtype=torch.int32, + ) + else: + self.candidate_block_buffer = None + + if get_pp_group().is_first_rank: + self.embed_tokens = VocabParallelEmbedding( + config.vocab_size, + config.hidden_size, + quant_config=quant_config, + prefix=f"{prefix}.embed_tokens", + ) + else: + self.embed_tokens = PPMissingLayer() + + self.engram_layout = EngramLayout.from_config(config) + + self.start_layer, self.end_layer, self.layers = make_layers( + config.num_hidden_layers, + lambda prefix: DeepseekV4DecoderLayer( + vllm_config, + prefix=prefix, + topk_indices_buffer=self.topk_indices_buffer, + aux_stream_list=aux_stream_list, + candidate_block_buffer=self.candidate_block_buffer, + engram_layout=self.engram_layout, + ), + prefix=f"{prefix}.layers", + ) + + # The n-gram hash needs a slot-keyed rolling store of compressed ids + # (chunked prefill / decode lookback); key it off the first local + # layer's sliding-window KV cache. Only PP ranks owning an engram + # layer need it. + self.engram_hash: NgramHashState | None = None + self.engram_swa_prefix: str | None = None + if self.engram_layout is not None: + local_engram = any( + isinstance(layer, DeepseekV4DecoderLayer) and layer.engram is not None + for layer in islice(self.layers, self.start_layer, self.end_layer) + ) + if local_engram: + first_layer = next( + iter(islice(self.layers, self.start_layer, self.end_layer)) + ) + swa_cache_module = first_layer.attn.swa_cache_layer + self.engram_hash = NgramHashState( + vllm_config, self.engram_layout, swa_cache_module + ) + self.engram_swa_prefix = swa_cache_module.prefix + + if get_pp_group().is_last_rank: + self.norm = RMSNorm(config.hidden_size, self.rms_norm_eps) + else: + self.norm = PPMissingLayer() + + spec_config = vllm_config.speculative_config + needs_mtp_hidden_states = spec_config is not None and ( + spec_config.use_eagle() or spec_config.uses_draft_model() + ) + if get_pp_group().is_last_rank and needs_mtp_hidden_states: + self._mtp_hidden_buffer = torch.empty( + vllm_config.scheduler_config.max_num_batched_tokens, + self.hc_dim, + dtype=vllm_config.model_config.dtype, + ) + else: + self._mtp_hidden_buffer = None + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.embed_tokens(input_ids) + + def make_empty_intermediate_tensors( + self, + batch_size: int, + dtype: torch.dtype, + device: torch.device, + ) -> IntermediateTensors: + # PP intermediate tensors carry the multi-stream hidden_states + # of shape (num_tokens, hc_mult, hidden_size) — V4 expands the + # token embedding to hc_mult streams before the first decoder + # layer and keeps that shape until the final hc collapse — plus the + # (num_tokens, hc_mult) pre-mix the next rank's first layer needs + # for its attention collapse. + return IntermediateTensors( + { + "hidden_states": torch.zeros( + (batch_size, self.hc_mult, self.config.hidden_size), + dtype=dtype, + device=device, + ), + "pre_mix": torch.zeros( + (batch_size, self.hc_mult), + dtype=torch.float32, + device=device, + ), + } + ) + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + intermediate_tensors: IntermediateTensors | None, + inputs_embeds: torch.Tensor | None = None, + lookback_token_ids: torch.Tensor | None = None, + ) -> torch.Tensor | IntermediateTensors: + if get_pp_group().is_first_rank: + if inputs_embeds is not None: + hidden_states = inputs_embeds + else: + hidden_states = self.embed_input_ids(input_ids) + else: + assert intermediate_tensors is not None + hidden_states = intermediate_tensors["hidden_states"] + + if self.use_mega_moe: + input_ids = input_ids.to(torch.int64) + + # Engram n-gram hashes for the whole (flattened) batch, computed once + # on the full token stream — before any sequence-parallel sharding — + # and consumed by the engram layers (1 and 14) below. Skipped on + # profile runs (KV cache unbound). + engram_hashes: torch.Tensor | None = None + engram_mask: torch.Tensor | None = None + if ( + self.engram_hash is not None + and input_ids is not None + and is_forward_context_available() + ): + attn_metadata = get_forward_context().attn_metadata + if isinstance(attn_metadata, list): + attn_metadata = attn_metadata[dbo_current_ubatch_id()] + if isinstance(attn_metadata, dict) and self.engram_hash.ensure_cache(): + assert self.engram_swa_prefix is not None + swa_metadata = typing.cast( + "DeepseekSparseSWAMetadata", attn_metadata[self.engram_swa_prefix] + ) + # Image-span tokens are dead: they break n-grams (hash op + # takes True=dead) and their gate is zeroed (Engram.forward + # takes True=keep). + image_mask = image_sentinel_mask(input_ids) + engram_mask = ~image_mask + if lookback_token_ids is None: + if not self.engram_hash.use_slot_cache: + raise NotImplementedError( + "engram needs `lookback_token_ids` from the model " + "runner (the DBO/ubatch wrapper drops model kwargs)" + ) + num_reqs = swa_metadata.num_decodes + swa_metadata.num_prefills + lookback_token_ids = input_ids.new_full( + (num_reqs, self.engram_hash.lookback_depth), -1 + ) + engram_hashes = self.engram_hash( + input_ids, + positions, + swa_metadata.query_start_loc, + image_mask, + lookback_token_ids, + image_sentinel_mask(lookback_token_ids), + swa_metadata.slot_mapping, + swa_metadata.block_table, + ) + # Gather all Engram rows before entering the decoder layers. + for layer in islice(self.layers, self.start_layer, self.end_layer): + engram = getattr(layer, "engram", None) + if engram is not None: + engram.prepare_embeddings( + engram_hashes[:, engram.layer_hash_index] + ) + + full_num_tokens = positions.shape[0] + if self.use_sequence_parallel: + if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available(): + forward_context = get_forward_context() + forward_context.is_padding = sp_padding_mask( + forward_context.is_padding, hidden_states + ) + hidden_states = sp_shard(hidden_states) + input_ids = sp_shard(input_ids) + + residual, post_mix, res_mix = None, None, None + pre_mix: torch.Tensor | None = None + if not get_pp_group().is_first_rank: + assert intermediate_tensors is not None + pre_mix = intermediate_tensors["pre_mix"] + aux_hidden_states: list[torch.Tensor] = [] + final_aux_recon: torch.Tensor | None = None # avoid duplicate mhc_post call + for idx, layer in enumerate( + islice(self.layers, self.start_layer, self.end_layer), + start=self.start_layer, + ): + hidden_states, residual, post_mix, res_mix, pre_mix = layer( + hidden_states, + positions, + input_ids, + pre_mix, + post_mix, + res_mix, + residual, + engram_hashes, + engram_mask, + ) + if idx + 1 in self.aux_hidden_state_layers: + # Reconstruct the aux hidden state for draft models + aux_recon = mhc_post_tilelang( + hidden_states, residual, post_mix, res_mix + ) + aux_hidden_state = aux_recon.mean(dim=1) + if self.use_sequence_parallel: + aux_hidden_state = sp_all_gather(aux_hidden_state)[:full_num_tokens] + aux_hidden_states.append(aux_hidden_state) + final_aux_recon = aux_recon + if layer is not None: + # Reuse if the last layer was captured as an aux hidden state + if self.end_layer in self.aux_hidden_state_layers: + hidden_states = final_aux_recon + else: + hidden_states = mhc_post_tilelang( + hidden_states, residual, post_mix, res_mix + ) + + if not get_pp_group().is_last_rank: + return IntermediateTensors( + {"hidden_states": hidden_states, "pre_mix": pre_mix} + ) + + # MTP needs full HC states; otherwise collapse and normalize locally + # before gathering to reduce communication. + if self._mtp_hidden_buffer is not None: + if self.use_sequence_parallel: + hidden_states = sp_all_gather(hidden_states)[:full_num_tokens] + pre_mix = sp_all_gather(pre_mix)[:full_num_tokens] + num_tokens = hidden_states.shape[0] + self._mtp_hidden_buffer[:num_tokens].copy_(hidden_states.flatten(1)) + + # Collapse the hc copies with the pre-mix from the last layer's FFN + # mixes — the mix the reference applies via + # ``last_layer.hc_pre(h, pre_mix)`` (v4.1 has no learned hc_head). + assert pre_mix is not None + hidden_states = hc_collapse_triton(hidden_states, pre_mix) + hidden_states = self.norm(hidden_states) + if self.use_sequence_parallel and self._mtp_hidden_buffer is None: + # Without MTP, gather only the collapsed and normalized hidden states. + hidden_states = sp_all_gather(hidden_states)[:full_num_tokens] + if len(aux_hidden_states) > 0: + return hidden_states, aux_hidden_states + return hidden_states + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + stacked_params_mapping = [ + # (param_name, shard_name, shard_id) + ("gate_up_proj", "w1", 0), + ("gate_up_proj", "w3", 1), + ("attn.fused_wqa_wkv", "attn.wq_a", 0), + ("attn.fused_wqa_wkv", "attn.wkv", 1), + ("compressor.fused_wkv_wgate", "compressor.wkv", 0), + ("compressor.fused_wkv_wgate", "compressor.wgate", 1), + ] + params_dict = dict(self.named_parameters()) + loaded_params: set[str] = set() + + # TP for attention + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() + n_head = self.config.num_attention_heads + n_local_head = n_head // tp_size + head_rank_start = n_local_head * tp_rank + head_rank_end = n_local_head * (tp_rank + 1) + + # Pre-compute expert mapping ONCE. + expert_mapping = self.get_expert_mapping() + + # Block-FP8 shared experts: pad the intermediate up to the TP-uniform + # block count so the standard loaders below slice it evenly (trailing + # ranks land on the zero pad). SP / unquantized ones need no padding. + pad_shared_expert = ( + getattr(self.quant_config, "weight_block_size", None) is not None + and not self.use_sequence_parallel + ) + + for name, loaded_weight in weights: + if name.startswith(("vision.", "aligner.", "image_")): + # Vision weights are loaded by the outer multimodal wrapper. + logger.warning_once("Skipping non-text weight: %s", name) + continue + if pad_shared_expert and ".shared_experts." in name: + loaded_weight = self._pad_shared_expert_weight( + self.quant_config, name, loaded_weight + ) + for param_name, weight_name, shard_id in stacked_params_mapping: + # Skip non-stacked layers and experts (experts handled below). + if ".experts." in name: + continue + if weight_name not in name: + continue + name = name.replace(weight_name, param_name) + + if is_pp_missing_parameter(name, self): + break + if name not in params_dict: + head, _, leaf = name.rpartition(".") + suffixed = f"{head}.base_layer.{leaf}" + if suffixed in params_dict: + name = suffixed + param = params_dict[name] + weight_loader = param.weight_loader + weight_loader(param, loaded_weight, shard_id) + loaded_params.add(name) + break + else: + if ".experts." in name: + # E8M0 scales are stored as float8_e8m0fnu in + # checkpoints but the MoE param is uint8. copy_() + # would do a numeric conversion (e.g. 2^-7 → 0), + # destroying the raw exponent bytes. + if ( + "weight_scale" in name + and loaded_weight.dtype == torch.float8_e8m0fnu + ): + loaded_weight = loaded_weight.view(torch.uint8) + for mapping in expert_mapping: + param_name, weight_name, expert_id, expert_shard_id = mapping + if weight_name not in name: + continue + name_mapped = name.replace(weight_name, param_name) + if is_pp_missing_parameter(name_mapped, self): + continue + param = params_dict[name_mapped] + # We should ask the weight loader to return success or not + # here since otherwise we may skip experts with other + # available replicas. + weight_loader = typing.cast( + Callable[..., bool], param.weight_loader + ) + success = weight_loader( + param, + loaded_weight, + name_mapped, + shard_id=expert_shard_id, + expert_id=expert_id, + return_success=True, + ) + if success: + name = name_mapped + break + loaded_params.add(name_mapped) + continue + elif "attn_sink" in name: + if is_pp_missing_parameter(name, self): + continue + narrow_weight = loaded_weight[head_rank_start:head_rank_end] + n = narrow_weight.shape[0] + params_dict[name][:n].copy_(narrow_weight) + loaded_params.add(name) + continue + else: + if is_pp_missing_parameter(name, self): + continue + # Non-LoRA params on a LoRA-wrapped module live at + # ``.base_layer.``; the checkpoint is plain. + if name not in params_dict: + head, _, leaf = name.rpartition(".") + suffixed = f"{head}.base_layer.{leaf}" + if suffixed in params_dict: + name = suffixed + param = params_dict[name] + weight_loader = getattr( + param, "weight_loader", default_weight_loader + ) + weight_loader(param, loaded_weight) + loaded_params.add(name) + continue + + return loaded_params + + @staticmethod + def _pad_shared_expert_weight( + quant_config: QuantizationConfig | None, + name: str, + loaded_weight: torch.Tensor, + ) -> torch.Tensor: + """Zero-pad a block-FP8 shared-expert weight/scale on its intermediate + axis so the standard TP loaders split it into even, block-aligned shards + (trailing ranks get the zero pad). gate (w1)/up (w3) [I, H] pad dim 0; + down (w2 -> down_proj) [H, I] pads dim 1. + """ + block_size = getattr(quant_config, "weight_block_size", None) + assert block_size is not None + # Round the intermediate axis up to a whole number of TP shards. The axis + # is in elements for weights (step = block) and in blocks for scales. + step = ( + 1 if name.endswith(("weight_scale_inv", "weight_scale")) else block_size[0] + ) + dim = 1 if ".down_proj." in name else 0 + mult = get_tensor_model_parallel_world_size() * step + pad = cdiv(loaded_weight.shape[dim], mult) * mult - loaded_weight.shape[dim] + if pad == 0: + return loaded_weight + pad_shape = list(loaded_weight.shape) + pad_shape[dim] = pad + return torch.cat([loaded_weight, loaded_weight.new_zeros(pad_shape)], dim=dim) + + def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + first_layer = next(iter(islice(self.layers, self.start_layer, self.end_layer))) + if first_layer.ffn.use_mega_moe: + return make_deepseek_v4_expert_params_mapping(self.config.n_routed_experts) + # Params for weights, fp8 weight scales, fp8 activation scales + # (param_name, weight_name, expert_id, shard_id) + return fused_moe_make_expert_params_mapping( + self, + ckpt_gate_proj_name="w1", + ckpt_down_proj_name="w2", + ckpt_up_proj_name="w3", + num_experts=self.config.n_routed_experts, + ) + + def finalize_mega_moe_weights(self) -> None: + for layer in islice(self.layers, self.start_layer, self.end_layer): + layer.ffn.finalize_mega_moe_weights() + + def finalize_mhc_broadcast_weights(self) -> None: + if not get_pp_group().is_first_rank or self.start_layer >= self.end_layer: + return + layer = self.layers[self.start_layer] + if isinstance(layer, DeepseekV4DecoderLayer): + broadcast = ( + layer.hc_attn_fn.detach() + .view(-1, layer.hc_mult, layer.hidden_size) + .sum(dim=1) + ) + if layer.hc_attn_fn_broadcast is None: + layer.hc_attn_fn_broadcast = broadcast + else: + layer.hc_attn_fn_broadcast.copy_(broadcast) + + +def _linear_scale_param_name(vllm_config: VllmConfig, expert_dtype: str) -> str: + """Parameter name the linear quant method registers for weight scales. + + Native MXFP8 checkpoints ([32, 32] blocks with MXFP4 experts) route linear + layers through ModelOptLinearMethod, which registers ``weight_scale``; + block-FP8 linear layers register ``weight_scale_inv``. + """ + use_mxfp8 = ( + getattr(vllm_config.quant_config, "weight_block_size", None) == [32, 32] + and expert_dtype == "fp4" + ) + return "weight_scale" if use_mxfp8 else "weight_scale_inv" + + +def _make_deepseek_v4_weights_mapper( + expert_dtype: str, linear_scale_name: str = "weight_scale_inv" +) -> WeightsMapper: + if expert_dtype == "fp4": + # MXFP4 experts use Mxfp4MoEMethod, which registers scales as + # ``w{1,2,3}_weight_scale`` (no _inv suffix). Linear scales use the + # parameter name registered by their quantization method. + scale_regex = { + # ``.base_layer.``-namespace variant (LoRA-wrapped experts). + re.compile( + r"(\.experts\.\d+\.w[123]\.base_layer)\.scale$" + ): r"\1.weight_scale", + re.compile(r"(\.experts\.\d+\.w[123])\.scale$"): r"\1.weight_scale", + # The ``embed.weight`` -> ``embed_tokens.weight`` suffix rule + # renames the engram fp8 table but not its scale; route the + # scale explicitly to the same module. + re.compile(r"(engram\.embed)\.scale$"): r"\1_tokens.weight_scale_inv", + re.compile(r"\.scale$"): f".{linear_scale_name}", + } + else: + # FP8 experts use Fp8MoEMethod (block_quant=True), which registers + # scales as ``w{13,2}_weight_scale_inv``. Map all ``.scale`` keys + # there. + scale_regex = { + # ``.base_layer.``-namespace variant of the above. + re.compile( + r"(\.experts\.\d+\.w[123]\.base_layer)\.scale$" + ): r"\1.weight_scale_inv", + # Same engram reroute as the fp4 branch above. + re.compile(r"(engram\.embed)\.scale$"): r"\1_tokens.weight_scale_inv", + re.compile(r"\.scale$"): f".{linear_scale_name}", + } + return WeightsMapper( + orig_to_new_prefix={ + "layers.": "model.layers.", + "embed.": "model.embed.", + "norm.": "model.norm.", + "mtp.": "model.mtp.", + }, + orig_to_new_regex=scale_regex, + orig_to_new_suffix={ + "head.weight": "lm_head.weight", + "embed.weight": "embed_tokens.weight", + ".ffn.gate.bias": ".ffn.gate.e_score_correction_bias", + }, + orig_to_new_substr={ + ".shared_experts.w2": ".shared_experts.down_proj", + "mtp.": None, + # The v4.1 checkpoint declares the VL arch even for text-only + # use; the text backbone drops the vision-tower weights. + "vision.": None, + "aligner.": None, + "image_": None, + }, + ) + + +class DeepseekV4MixtureOfExperts(MixtureOfExperts): + moe_mlp_layers: list["DeepseekV4MoE"] + + def extract_moe_parameters(self, example_moe: "DeepseekV4MoE | None") -> None: + if example_moe is None: + self.num_moe_layers = 0 + self.num_expert_groups = 0 + self.num_logical_experts = 0 + self.num_physical_experts = 0 + self.num_local_physical_experts = 0 + self.num_routed_experts = 0 + self.num_shared_experts = 0 + self.num_redundant_experts = 0 + return + self.num_logical_experts = example_moe.n_logical_experts + self.num_physical_experts = example_moe.n_physical_experts + self.num_local_physical_experts = example_moe.n_local_physical_experts + self.num_routed_experts = example_moe.n_routed_experts + self.num_shared_experts = example_moe.n_shared_experts + self.num_redundant_experts = example_moe.n_redundant_experts + + def update_physical_experts_metadata( + self, + num_physical_experts: int, + num_local_physical_experts: int, + ) -> None: + assert self.num_local_physical_experts == num_local_physical_experts + self.num_physical_experts = num_physical_experts + self.num_local_physical_experts = num_local_physical_experts + self.num_redundant_experts = num_physical_experts - self.num_logical_experts + for moe in self.moe_mlp_layers: + moe.n_local_physical_experts = num_local_physical_experts + moe.n_physical_experts = num_physical_experts + moe.n_redundant_experts = self.num_redundant_experts + moe.experts.update_expert_map() + + +class DeepseekV41LLMForCausalLM( + nn.Module, + SupportsPP, + SupportsEagle3, + SupportsLoRA, + DeepseekV4MixtureOfExperts, +): + model_cls = DeepseekV4Model + + # Default mapper assumes the original FP4-expert checkpoint layout. + # Overridden per-instance in __init__ when expert_dtype != "fp4". + hf_to_vllm_mapper = _make_deepseek_v4_weights_mapper("fp4") + + packed_modules_mapping = { + "gate_up_proj": ["w1", "w3"], + "fused_wqa_wkv": ["wq_a", "wkv"], + "fused_wkv_wgate": ["wkv", "wgate"], + } + + # The MTP draft head is not LoRA-adapted. + lora_skip_prefixes = ["mtp."] + + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): + super().__init__() + + config = vllm_config.model_config.hf_config + self.config = config + expert_dtype = getattr(config, "expert_dtype", "fp4") + self.hf_to_vllm_mapper = _make_deepseek_v4_weights_mapper( + expert_dtype, _linear_scale_param_name(vllm_config, expert_dtype) + ) + + self.model = self.model_cls( + vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") + ) + if get_pp_group().is_last_rank: + self.lm_head = ParallelLMHead( + config.vocab_size, + config.hidden_size, + prefix=maybe_prefix(prefix, "lm_head"), + ) + else: + self.lm_head = PPMissingLayer() + self.logits_processor = LogitsProcessor(config.vocab_size) + self.make_empty_intermediate_tensors = ( # type: ignore[method-assign] + self.model.make_empty_intermediate_tensors + ) + + self.set_moe_parameters() + + def set_moe_parameters(self) -> None: + self.num_expert_groups = getattr(self.config, "n_group", 1) + self.num_moe_layers = self.config.num_hidden_layers + self.moe_layers: list[nn.Module] = [] + self.moe_mlp_layers: list[DeepseekV4MoE] = [] + example_moe: DeepseekV4MoE | None = None + for layer in self.model.layers: + if isinstance(layer, PPMissingLayer): + continue + if not isinstance(layer, DeepseekV4DecoderLayer): + continue + if isinstance(layer.ffn, DeepseekV4MoE): + example_moe = layer.ffn + self.moe_mlp_layers.append(layer.ffn) + self.moe_layers.append(layer.ffn.experts) + + self.num_moe_layers = len(self.moe_layers) + self.extract_moe_parameters(example_moe) + + def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + return self.model.embed_input_ids(input_ids) + + def compute_logits( + self, + hidden_states: torch.Tensor, + ) -> torch.Tensor | None: + logits = self.logits_processor(self.lm_head, hidden_states) + return logits + + def compute_logits_local( + self, + hidden_states: torch.Tensor, + ) -> torch.Tensor: + return self.logits_processor(self.lm_head, hidden_states, skip_gather=True) + + @staticmethod + def get_model_state_cls(): + from .model_state import DeepseekV41ModelState + + return DeepseekV41ModelState + + @property + def token_lookback_depth(self) -> int: + """Tokens before a chunk start the engram hash needs; the model runner + passes them as `lookback_token_ids`.""" + engram_hash = self.model.engram_hash + return engram_hash.lookback_depth if engram_hash is not None else 0 + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + intermediate_tensors: IntermediateTensors | None = None, + inputs_embeds: torch.Tensor | None = None, + lookback_token_ids: torch.Tensor | None = None, + ) -> torch.Tensor | IntermediateTensors: + hidden_states = self.model( + input_ids, + positions, + intermediate_tensors, + inputs_embeds, + lookback_token_ids=lookback_token_ids, + ) + return hidden_states + + def get_mtp_target_hidden_states(self) -> torch.Tensor | None: + """Pre-collapse residual stream buffer (max_num_batched_tokens, + hc_mult * hidden_size) for the MTP draft model. Populated by + forward(); valid after each target step.""" + return getattr(self.model, "_mtp_hidden_buffer", None) + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + loader = AutoWeightsLoader(self) + loaded_params = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) + self.process_weights_after_loading() + return loaded_params + + def process_weights_after_loading(self) -> None: + self.model.finalize_mega_moe_weights() + self.model.finalize_mhc_broadcast_weights() + + def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + return self.model.get_expert_mapping() diff --git a/vllm/models/deepseek_v4_1/nvidia/model_state.py b/vllm/models/deepseek_v4_1/nvidia/model_state.py new file mode 100644 index 0000000000..1ba0f41603 --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/model_state.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from typing import Any + +import torch +import torch.nn as nn + +from vllm.config import VllmConfig +from vllm.triton_utils import tl, triton +from vllm.v1.worker.gpu.input_batch import InputBatch +from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache +from vllm.v1.worker.gpu.model_states.default import DefaultModelState +from vllm.v1.worker.gpu.states import RequestState + + +@triton.jit +def _gather_lookback_kernel( + lookback_ptr, + idx_mapping_ptr, + num_computed_tokens_ptr, + all_token_ids_ptr, + all_token_ids_stride, + num_reqs, + DEPTH: tl.constexpr, + BLOCK_DEPTH: tl.constexpr, +): + # One program per lookback row; rows past the batch are filled with -1. + batch_idx = tl.program_id(0) + in_batch = batch_idx < num_reqs + req_state_idx = tl.load(idx_mapping_ptr + batch_idx, mask=in_batch, other=0) + num_computed = tl.load(num_computed_tokens_ptr + req_state_idx) + + offs = tl.arange(0, BLOCK_DEPTH) + pos = num_computed - 1 - offs + valid = in_batch & (offs < DEPTH) & (pos >= 0) + ids = tl.load( + all_token_ids_ptr + req_state_idx * all_token_ids_stride + pos, + mask=valid, + other=-1, + ) + tl.store(lookback_ptr + batch_idx * DEPTH + offs, ids, mask=offs < DEPTH) + + +class DeepseekV41ModelState(DefaultModelState): + """DefaultModelState plus the engram lookback window. + + The engram n-gram hash needs the ids of the ``depth`` tokens preceding + each request's chunk start (see ``common/engram.py``). The runner keeps + the full token history on device, so the window is gathered there every + step: exact for prompt and generated tokens alike, whatever instance + produced their KV. + """ + + def __init__( + self, + vllm_config: VllmConfig, + model: nn.Module, + encoder_cache: EncoderCache | None, + device: torch.device, + ): + super().__init__(vllm_config, model, encoder_cache, device) + depth = model.token_lookback_depth + self.lookback_token_ids: torch.Tensor | None = None + if depth > 0: + # Persistent so a captured graph can read it on replay. + self.lookback_token_ids = torch.full( + (self.max_num_reqs, depth), -1, dtype=torch.int32, device=device + ) + + def prepare_inputs( + self, input_batch: InputBatch, req_states: RequestState + ) -> dict[str, torch.Tensor | None]: + model_inputs = super().prepare_inputs(input_batch, req_states) + window = self.lookback_token_ids + if window is None: + return model_inputs + all_token_ids = req_states.all_token_ids.gpu + depth = window.shape[1] + _gather_lookback_kernel[(window.shape[0],)]( + window, + input_batch.idx_mapping, + req_states.num_computed_tokens.gpu, + all_token_ids, + all_token_ids.stride(0), + input_batch.idx_mapping.shape[0], + DEPTH=depth, + BLOCK_DEPTH=triton.next_power_of_2(depth), + ) + model_inputs["lookback_token_ids"] = window + return model_inputs + + def prepare_dummy_inputs(self, num_reqs: int, num_tokens: int) -> dict[str, Any]: + model_inputs = super().prepare_dummy_inputs(num_reqs, num_tokens) + if self.lookback_token_ids is not None: + # The captured graph reads this buffer; replays refill it in place. + self.lookback_token_ids.fill_(-1) + model_inputs["lookback_token_ids"] = self.lookback_token_ids + return model_inputs diff --git a/vllm/models/deepseek_v4_1/nvidia/vl_model.py b/vllm/models/deepseek_v4_1/nvidia/vl_model.py new file mode 100644 index 0000000000..111936b431 --- /dev/null +++ b/vllm/models/deepseek_v4_1/nvidia/vl_model.py @@ -0,0 +1,357 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepSeek-V4.1 vision variant. + +Thin multimodal wrapper around the text-only ``DeepseekV41LLMForCausalLM``: + +- ``vision`` ViT + ``aligner`` produce per-image embeddings for the IMAGE + positions; three learned vectors (``image_start`` / ``image_newline`` / + ``image_end``) fill the delimiter positions. Every image-span position + carries ``image_token_id`` (129264) in ``input_ids``; the per-position + roles come from the processor's ``types`` tensor (see + ``common/mm_preprocess.py``, and ``common/vision.py`` for the tower). +- Merged embeddings enter the text model via ``inputs_embeds``, i.e. before + its hyper-connection stream expansion. Raw ``input_ids`` still flow into + the model so the MoE router can apply ``bias_vl`` to image tokens + (``requires_raw_input_tokens``). +""" + +from collections.abc import Iterable +from typing import Annotated + +import torch +from torch import nn + +from vllm.distributed import get_tensor_model_parallel_world_size +from vllm.model_executor.models.interfaces import ( + MultiModalEmbeddings, + SupportsEagle3, + SupportsMultiModal, + SupportsPP, +) +from vllm.model_executor.models.utils import ( + AutoWeightsLoader, + WeightsMapper, + maybe_prefix, +) +from vllm.model_executor.models.vision import is_vit_use_data_parallel +from vllm.models.deepseek_v4.common.vision import ( + DeepseekV4Aligner, + DeepseekV4ViT, + run_dp_sharded_vision_tower, +) +from vllm.multimodal import MULTIMODAL_REGISTRY +from vllm.utils.tensor_schema import TensorSchema, TensorShape + +from ..common.mm_preprocess import ( + IMAGE, + IMAGE_END, + IMAGE_NEW_LINE, + IMAGE_PAD_ID, + IMAGE_PLACEHOLDER, + IMAGE_SENTINEL_BASE_ID, + IMAGE_START, + DeepseekV4VLDummyInputsBuilder, + DeepseekV4VLMultiModalProcessor, + DeepseekV4VLProcessingInfo, +) +from .model import ( + DeepseekV41LLMForCausalLM, + _linear_scale_param_name, + _make_deepseek_v4_weights_mapper, +) + + +class DeepseekV4VLImagePixelInputs(TensorSchema): + """ViT patch inputs for one batched set of images. + + Dimensions: + - np: Total ViT patches across images (sum of n_vit_h * n_vit_w) + - c: Number of image channels (3) + - p: ViT patch size + - ni: Number of images + - ns: Total image-span positions (sum of n_llm_h * (n_llm_w + 1) + 2) + """ + + patches: Annotated[ + torch.Tensor, TensorShape("np", 3, "p", "p", dynamic_dims={"np"}) + ] + # [n_vit_h, n_vit_w] per image + vit_grid: Annotated[torch.Tensor, TensorShape("ni", 2)] + # [n_llm_h, n_llm_w] per image + llm_grid: Annotated[torch.Tensor, TensorShape("ni", 2)] + types: Annotated[torch.Tensor, TensorShape("ns", dynamic_dims={"ns"})] + + +def _make_deepseek_v4_vl_weights_mapper( + expert_dtype: str, linear_scale_name: str +) -> WeightsMapper: + """Text-checkpoint mapping rules re-rooted under ``language_model.``.""" + base = _make_deepseek_v4_weights_mapper(expert_dtype, linear_scale_name) + orig_to_new_prefix: dict[str, str | None] = { + "layers.": "language_model.model.layers.", + "embed.": "language_model.model.embed.", + "norm.": "language_model.model.norm.", + "hc_head": "language_model.model.hc_head", + "mtp.": "language_model.model.mtp.", + } + return WeightsMapper( + orig_to_new_prefix=orig_to_new_prefix, + orig_to_new_regex=base.orig_to_new_regex, + orig_to_new_suffix={ + "head.weight": "language_model.lm_head.weight", + "embed.weight": "embed_tokens.weight", + ".ffn.gate.bias": ".ffn.gate.e_score_correction_bias", + }, + orig_to_new_substr={ + ".shared_experts.w2": ".shared_experts.down_proj", + # The MTP/DSpark draft heads are not supported for the vision + # variant; drop their weights. + "mtp.": None, + }, + ) + + +@MULTIMODAL_REGISTRY.register_processor( + DeepseekV4VLMultiModalProcessor, + info=DeepseekV4VLProcessingInfo, + dummy_inputs=DeepseekV4VLDummyInputsBuilder, +) +class DeepseekV41ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsEagle3): + """Multimodal entry point for DeepSeek-V4.1 checkpoints with a vision tower. + + ``SupportsEagle3`` (aux hidden-state plumbing for MTP/DSpark drafters) + delegates through ``language_model`` via the protocol defaults. + """ + + supports_encoder_tp_data = True + + # The MoE router needs raw token ids to detect image-span tokens + # (all carrying image_token_id, see common/mm_preprocess.py) and apply + # bias_vl. + requires_raw_input_tokens = True + + @classmethod + def get_placeholder_str(cls, modality: str, i: int) -> str | None: + if modality == "image": + return IMAGE_PLACEHOLDER + raise ValueError(f"Unsupported modality: {modality!r}") + + def __init__(self, *, vllm_config, prefix: str = "") -> None: + super().__init__() + model_config = vllm_config.model_config + config = model_config.hf_config + self.config = config + self.multimodal_config = model_config.multimodal_config + assert self.multimodal_config is not None + + # The tower is always built; _mark_tower_model stubs it out + # (StageMissingLayer, weights skipped) when the image limit is 0. + with self._mark_tower_model(vllm_config, {"image"}): + self.use_data_parallel = is_vit_use_data_parallel(config.vision_n_heads) + self.vision = DeepseekV4ViT(config) + self.aligner = DeepseekV4Aligner(config) + self.image_start = nn.Parameter( + torch.empty(config.hidden_size, dtype=torch.float32) + ) + self.image_end = nn.Parameter( + torch.empty(config.hidden_size, dtype=torch.float32) + ) + self.image_newline = nn.Parameter( + torch.empty(config.hidden_size, dtype=torch.float32) + ) + self.vision.to(dtype=model_config.dtype) + self.aligner.to(dtype=model_config.dtype) + + with self._mark_language_model(vllm_config): + self.language_model = DeepseekV41LLMForCausalLM( + vllm_config=vllm_config, + prefix=maybe_prefix(prefix, "language_model"), + ) + # The outer mapper (see load_weights) fully resolves HF names into + # this wrapper's namespace before AutoWeightsLoader strips the + # "language_model." prefix and delegates to the child's load_weights, + # so the child's own mapper must be a no-op. Its suffix rules are not + # idempotent (e.g. "lm_head.weight".endswith("head.weight") would + # re-fire "head.weight" -> "lm_head.weight"). + self.language_model.hf_to_vllm_mapper = WeightsMapper() + self.make_empty_intermediate_tensors = ( # type: ignore[method-assign] + self.language_model.make_empty_intermediate_tensors + ) + + expert_dtype = getattr(config, "expert_dtype", "fp4") + self.hf_to_vllm_mapper = _make_deepseek_v4_vl_weights_mapper( + expert_dtype, _linear_scale_param_name(vllm_config, expert_dtype) + ) + + def _parse_and_validate_image_input( + self, **kwargs: object + ) -> DeepseekV4VLImagePixelInputs | None: + patches = kwargs.pop("patches", None) + if patches is None: + return None + return DeepseekV4VLImagePixelInputs( + patches=patches, + vit_grid=kwargs.pop("vit_grid"), + llm_grid=kwargs.pop("llm_grid"), + types=kwargs.pop("types"), + resolve_bindings={"p": self.config.vision_patch_size}, + ) + + def _encode_image( + self, + patches: torch.Tensor, + n_vit_h: int, + n_vit_w: int, + ) -> torch.Tensor: + # Aligner rows in reading order, one per IMAGE slot. + return self.aligner(self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w) + + def _build_image_span( + self, image_embeds: torch.Tensor, types: torch.Tensor + ) -> torch.Tensor: + """Full image span: aligner rows at IMAGE slots, the learned + delimiter vectors at IMAGE_START/IMAGE_NEW_LINE/IMAGE_END.""" + types = types.to(image_embeds.device) + span = image_embeds.new_empty(types.numel(), image_embeds.shape[-1]) + dtype = image_embeds.dtype + span[types == IMAGE_START] = self.image_start.to(dtype) + span[types == IMAGE_END] = self.image_end.to(dtype) + span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype) + span[types == IMAGE] = image_embeds + return span + + def _process_image_input( + self, + image_input: DeepseekV4VLImagePixelInputs, + ) -> tuple[torch.Tensor, ...]: + patches = image_input.patches.to(self.aligner.w1.weight.dtype) + vit_grid = image_input.vit_grid.tolist() + + image_embeds_list: list[torch.Tensor] + if self.use_data_parallel and get_tensor_model_parallel_world_size() > 1: + # Data-parallel ViT: shard images across TP ranks and all-gather + # the per-image embeddings (weights are replicated on every rank). + image_embeds_list = run_dp_sharded_vision_tower( + self.vision, self.aligner, patches, vit_grid + ) + else: + image_embeds_list = [] + vit_offset = 0 + for n_vit_h, n_vit_w in vit_grid: + n_vit = n_vit_h * n_vit_w + image_embeds_list.append( + self._encode_image( + patches[vit_offset : vit_offset + n_vit], n_vit_h, n_vit_w + ) + ) + vit_offset += n_vit + + embeds: list[torch.Tensor] = [] + span_offset = 0 + for image_embeds, (n_llm_h, n_llm_w) in zip( + image_embeds_list, image_input.llm_grid.tolist(), strict=True + ): + span_len = n_llm_h * (n_llm_w + 1) + 2 + embeds.append( + self._build_image_span( + image_embeds, + image_input.types[span_offset : span_offset + span_len], + ) + ) + span_offset += span_len + return tuple(embeds) + + def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings: + image_input = self._parse_and_validate_image_input(**kwargs) + if image_input is None: + return [] + return self._process_image_input(image_input) + + def embed_input_ids( + self, + input_ids: torch.Tensor, + multimodal_embeddings: MultiModalEmbeddings | None = None, + *, + is_multimodal: torch.Tensor | None = None, + ) -> torch.Tensor: + from vllm.model_executor.models.utils import _merge_multimodal_embeddings + + # Compressor-alignment pads borrow a reserved id; embed them as the + # plain image token (the checkpoint has no image_pad vector). + # Branch-free: safe inside compiled/captured regions. + input_ids = input_ids.masked_fill( + input_ids == IMAGE_PAD_ID, IMAGE_SENTINEL_BASE_ID + ) + inputs_embeds = self.language_model.embed_input_ids(input_ids) + + if multimodal_embeddings is None or len(multimodal_embeddings) == 0: + return inputs_embeds + + assert is_multimodal is not None + return _merge_multimodal_embeddings( + inputs_embeds=inputs_embeds, + multimodal_embeddings=multimodal_embeddings, + is_multimodal=is_multimodal, + ) + + @staticmethod + def get_model_state_cls(): + from .model_state import DeepseekV41ModelState + + return DeepseekV41ModelState + + @property + def token_lookback_depth(self) -> int: + return self.language_model.token_lookback_depth + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + intermediate_tensors=None, + inputs_embeds: torch.Tensor | None = None, + lookback_token_ids: torch.Tensor | None = None, + **kwargs, + ) -> torch.Tensor: + return self.language_model( + input_ids, + positions, + intermediate_tensors, + inputs_embeds, + lookback_token_ids=lookback_token_ids, + ) + + def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: + return self.language_model.compute_logits(hidden_states) + + def compute_logits_local(self, hidden_states: torch.Tensor) -> torch.Tensor: + return self.language_model.compute_logits_local(hidden_states) + + def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + return self.language_model.get_expert_mapping() + + def get_mtp_target_hidden_states(self) -> torch.Tensor | None: + """Pre-hc_head residual stream buffer for the MTP/DSpark draft model.""" + return self.language_model.get_mtp_target_hidden_states() + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + # Map HF names into this wrapper's namespace up front and sort, so + # the "language_model." group reaches the child loader as one + # contiguous block (AutoWeightsLoader delegates per contiguous group, + # and the child's load_weights finalizes fused expert weights, which + # must not run on a partially loaded model). + mapped = sorted(self.hf_to_vllm_mapper.apply(weights), key=lambda x: x[0]) + loader = AutoWeightsLoader(self) + loaded_params = loader.load_weights(mapped) + # The child's load_weights already ran its post-load finalization. + self._weights_finalized = True + return loaded_params + + def process_weights_after_loading(self) -> None: + # Model-level post-load hook (called by the loader after any load + # format). Under DummyModelLoader the child's load_weights — and + # hence its finalize step — is bypassed, so run it here instead. + if getattr(self, "_weights_finalized", False): + return + self.language_model.process_weights_after_loading() diff --git a/vllm/models/deepseek_v4_1/quant_config.py b/vllm/models/deepseek_v4_1/quant_config.py new file mode 100644 index 0000000000..c8361b2da5 --- /dev/null +++ b/vllm/models/deepseek_v4_1/quant_config.py @@ -0,0 +1,229 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Quantization config for DeepSeek V4.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +from vllm.config import get_current_vllm_config +from vllm.config.quantization import QuantSpec +from vllm.model_executor.layers.fused_moe import ( + RoutedExperts, + UnquantizedFusedMoEMethod, +) +from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod +from vllm.model_executor.layers.quantization import QuantizationMethods +from vllm.model_executor.layers.quantization.fp8 import Fp8Config +from vllm.model_executor.layers.quantization.mxfp4 import Mxfp4MoEMethod +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + is_layer_skipped, + kMxfp8Dynamic, + kMxfp8Static, +) + +_DEEPSEEK_V4_EXPERT_DTYPES = ("fp4", "fp8") + +if TYPE_CHECKING: + from vllm.model_executor.layers.quantization.modelopt import ( + ModelOptNvFp4Config, + ) + + +class DeepseekV4FP8Config(Fp8Config): + """FP8 config for DeepSeek V4 with expert-dtype-aware MoE dispatch. + + DeepSeek V4 checkpoints always use FP8 block quantization for + linear/attention layers. The MoE expert weights vary by checkpoint: + - ``expert_dtype="fp4"`` (e.g. DeepSeek-V4-Flash): MXFP4 experts + with ue8m0 (e8m0fnu) FP8 linear scales. + - ``expert_dtype="fp8"`` (e.g. DeepSeek-V4-Flash-Base): FP8 block + experts with float32 FP8 linear scales. + + The dispatch and the linear scale dtype are both keyed off + ``expert_dtype`` from the model's hf_config; missing values default + to ``"fp4"`` so existing FP4 checkpoints stay unchanged. + + NOTE: ``expert_dtype`` is resolved lazily because this config is + constructed during VllmConfig setup, before ``set_current_vllm_config`` + is active. Reading hf_config eagerly in ``__init__`` would always see + the default ``"fp4"`` and silently misroute Flash-Base checkpoints. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._resolved_expert_dtype: str | None = None + self._resolved_moe_quant_algo: str | None = None + self._nvfp4_config: ModelOptNvFp4Config | None = None + # ``is_scale_e8m0`` is a property that resolves on first read, + # by which time the current vllm_config has been set. + + @property + def expert_dtype(self) -> str: + if self._resolved_expert_dtype is None: + try: + hf_config = get_current_vllm_config().model_config.hf_config + except Exception: + # vllm_config not yet set; defer the decision until a + # later call lands inside set_current_vllm_config. + return "fp4" + expert_dtype = getattr(hf_config, "expert_dtype", "fp4") + if expert_dtype not in _DEEPSEEK_V4_EXPERT_DTYPES: + raise ValueError( + f"Unsupported DeepSeek V4 expert_dtype={expert_dtype!r}; " + f"expected one of {_DEEPSEEK_V4_EXPERT_DTYPES}." + ) + self._resolved_expert_dtype = expert_dtype + from vllm.logger import init_logger + + init_logger(__name__).info_once( + "DeepSeek V4 expert_dtype resolved to %r", expert_dtype + ) + return self._resolved_expert_dtype + + @property + def is_scale_e8m0(self) -> bool: + # FP4 checkpoints store FP8 linear scales as e8m0fnu; FP8 expert + # checkpoints (Flash-Base) store them as float32. + return self.expert_dtype == "fp4" + + def _resolve_moe_overrides(self) -> None: + if self._resolved_moe_quant_algo is not None: + return + try: + hf_config = get_current_vllm_config().model_config.hf_config + except Exception: + return + quant_cfg = getattr(hf_config, "quantization_config", None) or {} + algo = (quant_cfg.get("moe_quant_algo") or "").upper() or None + self._resolved_moe_quant_algo = algo or "" + + @property + def moe_quant_algo(self) -> str: + self._resolve_moe_overrides() + return self._resolved_moe_quant_algo or "" + + def _get_nvfp4_config(self) -> ModelOptNvFp4Config: + if self._nvfp4_config is None: + from vllm.model_executor.layers.quantization.modelopt import ( + ModelOptNvFp4Config, + ) + + self._nvfp4_config = ModelOptNvFp4Config( + is_checkpoint_nvfp4_serialized=True, + kv_cache_quant_algo=None, + exclude_modules=[], + group_size=16, + ) + return self._nvfp4_config + + @classmethod + def get_name(cls) -> QuantizationMethods: + return "deepseek_v4_fp8" + + @staticmethod + def _is_quark_mxfp4_ocp(hf_quant_cfg: dict) -> bool: + """True for AMD-Quark exports whose global scheme is MXFP4.""" + weight = (hf_quant_cfg.get("global_quant_config") or {}).get("weight") + # A non-dict weight (e.g. a list of multiple specs) means not an OCP + # MXFP4 scheme (e.g. NVFP4 with 2-level scale). + if not isinstance(weight, dict): + return False + return ( + weight.get("dtype") == "fp4" + and weight.get("qscheme") == "per_group" + and weight.get("group_size") == 32 + ) + + @classmethod + def override_quantization_method( + cls, hf_quant_cfg, user_quant, hf_config=None + ) -> QuantizationMethods | None: + if not ( + isinstance(hf_quant_cfg, dict) + and ( + hf_quant_cfg.get("quant_method") in ("fp8", "deepseek_v4_fp8") + or ( + hf_quant_cfg.get("quant_method") == "quark" + and cls._is_quark_mxfp4_ocp(hf_quant_cfg) + ) + ) + ): + return None + model_type = getattr(hf_config, "model_type", None) + if ( + model_type + in ( + "deepseek_v4", + "deepseek_v4_text", + "deepseek_v41", + "deepseek_v41_text", + ) + or user_quant == "deepseek_v4_fp8" + ): + return "deepseek_v4_fp8" + return None + + @classmethod + def from_config(cls, config: dict) -> DeepseekV4FP8Config: + # Reroute AMD-Quark fused shared expert MXFP4 checkpoints onto the fp8 + # path: the runtime layout matches the DeepSeek-native fp8 checkpoint, + # so translate the schema into format Fp8Config.from_config expects. + if config.get("quant_method") == "quark": + quark_exclude = config.get("exclude") or [] + config = { + "quant_method": "fp8", + "activation_scheme": "dynamic", + "fmt": "e4m3", + "scale_fmt": "ue8m0", + "weight_block_size": [128, 128], + "ignored_layers": [ + name for name in quark_exclude if isinstance(name, str) + ], + } + return cast("DeepseekV4FP8Config", super().from_config(config)) + + def get_quant_method(self, layer, prefix): + if ( + isinstance(layer, LinearBase) + and self.weight_block_size == [32, 32] + and self.is_scale_e8m0 + ): + if is_layer_skipped( + prefix=prefix, + ignored_layers=self.ignored_layers, + fused_mapping=self.packed_modules_mapping, + match_mode=self.ignored_layers_match_mode, + ): + return UnquantizedLinearMethod() + from vllm.model_executor.layers.quantization.modelopt import ( + CkptCtx, + ModelOptLinearMethod, + ) + + rows, cols = self.weight_block_size + return ModelOptLinearMethod( + QuantSpec(weight=kMxfp8Static, activation=kMxfp8Dynamic), + CkptCtx(scale_block_size=(rows, cols)), + ) + if isinstance(layer, RoutedExperts): + if is_layer_skipped( + prefix=prefix, + ignored_layers=self.ignored_layers, + fused_mapping=self.packed_modules_mapping, + ): + return UnquantizedFusedMoEMethod(layer.moe_config) + if self.expert_dtype == "fp4": + if self.moe_quant_algo == "NVFP4": + from vllm.model_executor.layers.quantization.modelopt import ( + ModelOptNvFp4FusedMoE, + ) + + return ModelOptNvFp4FusedMoE( + quant_config=self._get_nvfp4_config(), + moe_config=layer.moe_config, + ) + return Mxfp4MoEMethod(layer.moe_config) + # expert_dtype == "fp8": fall through to Fp8Config which + # returns Fp8MoEMethod with block-wise float32 scales. + return super().get_quant_method(layer, prefix) diff --git a/vllm/models/deepseek_v4_1/sparse_mla.py b/vllm/models/deepseek_v4_1/sparse_mla.py new file mode 100644 index 0000000000..6a0f09f952 --- /dev/null +++ b/vllm/models/deepseek_v4_1/sparse_mla.py @@ -0,0 +1,231 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DeepSeek-V4.1 FlashMLA sparse backend, metadata, and metadata builders.""" + +from dataclasses import dataclass +from typing import Any, ClassVar + +import torch + +from vllm.config import VllmConfig +from vllm.config.cache import CacheDType +from vllm.platforms import current_platform +from vllm.platforms.interface import DeviceCapability +from vllm.v1.attention.backend import ( + AttentionBackend, + AttentionCGSupport, + AttentionMetadata, + AttentionMetadataBuilder, + CommonAttentionMetadata, + MultipleOf, +) +from vllm.v1.attention.backends.mla.compressor_utils import get_compressed_slot_mapping +from vllm.v1.attention.backends.mla.sparse_swa import ( + _LAYER_TYPE_C1A, + _LAYER_TYPE_C2A, + _LAYER_TYPE_SWAONLY, + DeepseekSparseSWAMetadataBuilder, +) +from vllm.v1.kv_cache_interface import AttentionSpec + +# v4.1 per-layer compress ratios: 0 = pure sliding window, 1 = full-length +# compressed cache, 2 = ratio-2 compressed cache. Ratio-1 and ratio-2 layers +# both attend over indexer topk indices into a shared compressed cache but +# differ in compressed page block size (block_size // ratio), so each needs its +# own FlashMLA tile-scheduler plan. +_V41_LAYER_TYPES: dict[int, str] = { + 0: _LAYER_TYPE_SWAONLY, + 1: _LAYER_TYPE_C1A, + 2: _LAYER_TYPE_C2A, +} + + +def deepseek_v41_layer_type(compress_ratio: int) -> str: + layer_type = _V41_LAYER_TYPES.get(compress_ratio) + if layer_type is None: + raise ValueError( + f"Unsupported DeepSeek V4.1 compress_ratio={compress_ratio}; " + "expected 0, 1, or 2." + ) + return layer_type + + +class DeepseekV41SparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuilder): + """SWA metadata builder base for v4.1. + + The shared builder classifies decode layer types by the v4.0 ratios + (1 = SWA-only, 4, 128). v4.1 uses 0 / 1 / 2, so recompute the set of + tile-scheduler plans from the v4.1 topology. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + compress_ratios = getattr( + self.vllm_config.model_config.hf_config, "compress_ratios", None + ) or [0] + self._layer_types = { + deepseek_v41_layer_type(int(ratio)) for ratio in compress_ratios + } + + +class DeepseekV4SparseMLABackend(AttentionBackend): + """DeepSeek-V4.1 sparse-MLA backend base. + + Subclasses ``AttentionBackend`` directly (not the V3.2 + ``FlashMLASparseBackend``): DeepSeek-V4.1 runs its own attention layer + (``DeepseekV4Attention``), so it does not reuse the V3.2 builder or impl, and + only needs to declare its own metadata builder, KV-cache layout, and the + sparse-MLA capability flags. + """ + + supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16] + supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ + "auto", + "fp8_ds_mla", + "fp8", # alias for fp8_ds_mla + ] + + @staticmethod + def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: + return [64 if current_platform.is_device_capability_family(90) else 128] + + @staticmethod + def get_builder_cls() -> type["DeepseekV4SparseMLAMetadataBuilder"]: + return DeepseekV4SparseMLAMetadataBuilder + + @staticmethod + def get_impl_cls() -> type[Any]: + # DeepSeek-V4.1 runs its attention through ``DeepseekV4Attention.forward``, + # not the generic ``Attention``/``MLAAttention`` layer, so the backend's + # impl class is never instantiated. + raise NotImplementedError( + "DeepseekV4SparseMLABackend has no separate impl class; DeepSeek-V4.1 " + "attention runs through DeepseekV4Attention." + ) + + @classmethod + def get_supported_head_sizes(cls) -> list[int]: + # DeepSeek V4 layout: 448 NoPE + 64 RoPE = 512. + return [512] + + @classmethod + def is_mla(cls) -> bool: + return True + + @classmethod + def is_sparse(cls) -> bool: + return True + + @classmethod + def supports_sink(cls) -> bool: + return True + + @classmethod + def supports_compute_capability(cls, capability: DeviceCapability) -> bool: + return capability.major in [9, 10] + + +@dataclass +class DeepseekV4FlashMLAMetadata(AttentionMetadata): + num_reqs: int + max_query_len: int + max_seq_len: int + + num_actual_tokens: int # Number of tokens excluding padding. + query_start_loc: torch.Tensor + slot_mapping: torch.Tensor + + block_table: torch.Tensor + req_id_per_token: torch.Tensor + block_size: int + topk_tokens: int + + +class DeepseekV4SparseMLAMetadataBuilder( + AttentionMetadataBuilder[DeepseekV4FlashMLAMetadata] +): + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH + + def __init__( + self, + kv_cache_spec: AttentionSpec, + layer_names: list[str], + vllm_config: VllmConfig, + device: torch.device, + ) -> None: + super().__init__(kv_cache_spec, layer_names, vllm_config, device) + self.model_config = vllm_config.model_config + # Classify single-token queries (plus num_speculative_tokens via + # supports_spec_as_decode=True) as decodes; longer queries go to prefill. + self._init_reorder_batch_threshold(1, supports_spec_as_decode=True) + self.topk_tokens = self.model_config.hf_config.index_topk + + max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens + self.req_id_per_token_buffer = torch.empty( + (max_num_batched_tokens,), dtype=torch.int32, device=device + ) + + assert isinstance(self.kv_cache_spec.tokens_per_state, int) + self.compress_ratio = self.kv_cache_spec.tokens_per_state + # Only kv-source layers own a compressed cache, and v4.1 compresses at + # ratio 1 or 2. + if self.compress_ratio not in (1, 2): + raise ValueError( + "DeepSeek V4.1 compressed-KV caches use compress_ratio 1 or 2; " + f"got {self.compress_ratio}." + ) + + # Pre-allocate compressed slot mapping buffer for CUDA graph address + # stability when compress_ratio > 1. + if self.compress_ratio > 1: + self.compressed_slot_mapping_buffer = torch.empty( + max_num_batched_tokens, dtype=torch.int64, device=device + ) + + def build( + self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False, + ) -> DeepseekV4FlashMLAMetadata: + cm = common_attn_metadata + req_id_per_token = cm.token_to_req_indices(self.req_id_per_token_buffer) + + slot_mapping = cm.slot_mapping + if self.compress_ratio > 1: + slot_mapping = get_compressed_slot_mapping( + cm.num_actual_tokens, + cm.query_start_loc, + cm.seq_lens, + cm.block_table_tensor.clamp_(min=0), + int(self.kv_cache_spec.num_states), + self.compress_ratio, + out=self.compressed_slot_mapping_buffer, + ) + + return DeepseekV4FlashMLAMetadata( + num_reqs=cm.num_reqs, + max_query_len=cm.max_query_len, + max_seq_len=cm.max_seq_len, + num_actual_tokens=cm.num_actual_tokens, + query_start_loc=cm.query_start_loc, + slot_mapping=slot_mapping, + block_table=cm.block_table_tensor, + req_id_per_token=req_id_per_token, + block_size=self.kv_cache_spec.block_size, + topk_tokens=self.topk_tokens, + ) + + +class DeepseekV4FlashMLAMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder): + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS + + +class DeepseekV4FlashMLABackend(DeepseekV4SparseMLABackend): + @staticmethod + def get_name() -> str: + return "FLASHMLA_SPARSE_DSV41" + + @staticmethod + def get_builder_cls() -> type[DeepseekV4FlashMLAMetadataBuilder]: + return DeepseekV4FlashMLAMetadataBuilder diff --git a/vllm/v1/attention/backends/mla/sparse_swa.py b/vllm/v1/attention/backends/mla/sparse_swa.py index 0e4c360e42..02e6336a38 100644 --- a/vllm/v1/attention/backends/mla/sparse_swa.py +++ b/vllm/v1/attention/backends/mla/sparse_swa.py @@ -46,18 +46,26 @@ from vllm.v1.kv_cache_interface import ( _LAYER_TYPE_SWAONLY = "swaonly" _LAYER_TYPE_C4A = "c4a" _LAYER_TYPE_C128A = "c128a" +# v4.1 ratio-1 / ratio-2 indexer layers: same indexer-path shape as C4A, but +# their compressed page block is block_size // ratio, so each gets its own plan. +# v4.1 builders classify layer types themselves (ratio 0 is SWA-only there); see +# deepseek_v4_1/sparse_mla.py. +_LAYER_TYPE_C1A = "c1a" +_LAYER_TYPE_C2A = "c2a" def _layer_type_for(compress_ratio: int) -> str: if compress_ratio <= 1: return _LAYER_TYPE_SWAONLY + if compress_ratio == 2: + return _LAYER_TYPE_C2A if compress_ratio == 4: return _LAYER_TYPE_C4A if compress_ratio == 128: return _LAYER_TYPE_C128A raise ValueError( f"Unsupported DeepseekV4 compress_ratio={compress_ratio}; " - "expected 1, 4, or 128." + "expected 1, 2, 4, or 128." ) @@ -70,6 +78,7 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase): prefix: str, cache_config: CacheConfig, backend_cls: "type[AttentionBackend] | None" = None, + block_size: int = 64, ): super().__init__() self.backend_cls = backend_cls or DeepseekSparseSWABackend @@ -84,12 +93,9 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase): raise ValueError(f"Duplicate layer name: {prefix}") compilation_config.static_forward_context[prefix] = self - # Block size is constrained by tensor sharing between SWA and C4A KV blocks. - # Since both block types share the same physical tensor, they must use the - # same page size. The C4A KV block shape [256//4, head_dim] = [64, head_dim] - # determines the SWA block size of 64 tokens per block. - # TODO(yifan): make SWA block size automatically determined and configurable. - self.block_size = 64 + # Any multiple of 32; the sparse decode kernels take the page size at + # runtime. + self.block_size = block_size # uint8: fp8_ds_mla UE8M0 paged layout. bfloat16 / float8_e4m3fn: # contiguous full-cache layout. assert self.dtype in (torch.uint8, torch.bfloat16, torch.float8_e4m3fn) @@ -130,7 +136,7 @@ class DeepseekSparseSWABackend(AttentionBackend): @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: - return [MultipleOf(64)] + return [MultipleOf(32)] @classmethod def get_preferred_block_size(cls, default_block_size: int) -> int: @@ -213,12 +219,17 @@ class DeepseekSparseSWAMetadata: tile_sched_swaonly: "FlashMLASchedMeta | None" = None tile_sched_c4a: "FlashMLASchedMeta | None" = None tile_sched_c128a: "FlashMLASchedMeta | None" = None + tile_sched_c1a: "FlashMLASchedMeta | None" = None + tile_sched_c2a: "FlashMLASchedMeta | None" = None flashinfer_sparse_index_cache: dict[str, tuple[torch.Tensor, torch.Tensor]] = field( default_factory=dict ) def get_prefill_chunk_plan( - self, compress_ratio: int, prefill_chunk_size: int + self, + compress_ratio: int, + prefill_chunk_size: int, + has_compressed: bool | None = None, ) -> list[tuple[int, int, int, int]]: if self.num_prefills == 0: return [] @@ -226,17 +237,20 @@ class DeepseekSparseSWAMetadata: assert self.prefill_seq_lens_cpu is not None assert self.prefill_query_lens_cpu is not None + # Whether the layer gathers a compressed-KV region into the prefill + # workspace. v4.0 callers keep the legacy default (ratio <= 1 means + # SWA-only); v4.1 passes has_compressed explicitly because its + # compress_ratio==1 layers DO have a full-length compressed cache. + if has_compressed is None: + has_compressed = compress_ratio > 1 + # query_len <= max_num_batched_tokens and # gather_len = query_len + min(prefix_len, window_size - 1), so the # worst-case gathered width is bounded by # max_num_batched_tokens + window_size - 1. The compressed prefix pool # is bounded by ceil(max_model_len / compress_ratio). max_workspace_area = prefill_chunk_size * ( - ( - 0 - if compress_ratio <= 1 - else cdiv(self.prefill_max_model_len, compress_ratio) - ) + (cdiv(self.prefill_max_model_len, compress_ratio) if has_compressed else 0) + self.prefill_window_size + self.prefill_max_num_batched_tokens ) @@ -245,13 +259,13 @@ class DeepseekSparseSWAMetadata: prefix_lens_cpu, min=0, max=self.prefill_window_size - 1 ) compressed_lens_cpu = ( - torch.zeros_like(self.prefill_seq_lens_cpu) - if compress_ratio <= 1 - else torch.div( + torch.div( self.prefill_seq_lens_cpu, compress_ratio, rounding_mode="floor", ) + if has_compressed + else torch.zeros_like(self.prefill_seq_lens_cpu) ) chunk_plan: list[tuple[int, int, int, int]] = [] @@ -715,6 +729,8 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder): tile_sched_swaonly=tile_sched[_LAYER_TYPE_SWAONLY], tile_sched_c4a=tile_sched[_LAYER_TYPE_C4A], tile_sched_c128a=tile_sched[_LAYER_TYPE_C128A], + tile_sched_c1a=tile_sched[_LAYER_TYPE_C1A], + tile_sched_c2a=tile_sched[_LAYER_TYPE_C2A], **deepseek_v4_fields, # type: ignore[arg-type] ) @@ -795,6 +811,8 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder): metadata.tile_sched_swaonly = tile_sched[_LAYER_TYPE_SWAONLY] metadata.tile_sched_c4a = tile_sched[_LAYER_TYPE_C4A] metadata.tile_sched_c128a = tile_sched[_LAYER_TYPE_C128A] + metadata.tile_sched_c1a = tile_sched[_LAYER_TYPE_C1A] + metadata.tile_sched_c2a = tile_sched[_LAYER_TYPE_C2A] metadata.flashinfer_sparse_index_cache.clear() def build_tile_scheduler( @@ -815,6 +833,8 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder): _LAYER_TYPE_SWAONLY: None, _LAYER_TYPE_C4A: None, _LAYER_TYPE_C128A: None, + _LAYER_TYPE_C1A: None, + _LAYER_TYPE_C2A: None, } if ( num_decode_tokens == 0 diff --git a/vllm/v1/attention/backends/registry.py b/vllm/v1/attention/backends/registry.py index 0c9b39c988..c1c6330576 100644 --- a/vllm/v1/attention/backends/registry.py +++ b/vllm/v1/attention/backends/registry.py @@ -98,6 +98,16 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta): ROCM_FLASHMLA_SPARSE_DSV4 = ( "vllm.models.deepseek_v4.amd.rocm.DeepseekV4ROCMAiterMLASparseBackend" ) + # DeepSeek V4.1 sparse MLA backends (model-driven; selected via the V4.1 + # layer). Separate names from DSV4 so a V4.1 model never resolves the + # V4.0 backend classes through this enum. + FLASHMLA_SPARSE_DSV41 = ( + "vllm.models.deepseek_v4_1.sparse_mla.DeepseekV4FlashMLABackend" + ) + FLASHINFER_MLA_SPARSE_DSV41 = ( + "vllm.models.deepseek_v4_1.nvidia.flashinfer_sparse." + "DeepseekV4FlashInferMLASparseBackend" + ) B12X = "vllm.v1.attention.backends.b12x.B12xPagedAttentionBackend" FLASH_ATTN_MLA = "vllm.v1.attention.backends.mla.flashattn_mla.FlashAttnMLABackend" FLASH_ATTN_MLA_SPARSE = (