[ROCm]Migrating Deepseek V3.2 to vllm/models/deepseek_v32/ (#47207)

Signed-off-by: sroberts-amd <sroberts@amd.com>
Signed-off-by: Stacy Roberts <sroberts@amd.com>
Co-authored-by: Elvir Crncevic <elvircrn@gmail.com>
Co-authored-by: Andreas Karatzas <akaratza@amd.com>
This commit is contained in:
sroberts-amd
2026-07-30 08:37:43 -05:00
committed by GitHub
co-authored by Elvir Crncevic Andreas Karatzas
parent 38a267cdd5
commit e2efe79695
12 changed files with 1031 additions and 70 deletions
@@ -27,7 +27,7 @@ rtol/atol=1e-2 (the tolerance the sibling deepseek_v4 fused-kernel test uses).
import pytest
import torch
from vllm.models.deepseek_v32.nvidia import kernels as K
from vllm.models.deepseek_v32.common import kernels as K
from vllm.platforms import current_platform
FP8 = torch.float8_e4m3fn
+9 -5
View File
@@ -10,11 +10,15 @@ attend. The same model code serves any DSA checkpoint, including GLM-5.2
from vllm.platforms import current_platform
if current_platform.is_rocm() or current_platform.is_xpu():
raise NotImplementedError("deepseek_v32 currently supports NVIDIA SM100 only.")
from .nvidia.model import DeepseekV32ForCausalLM
from .nvidia.mtp import DeepseekV32MTP
if current_platform.is_rocm():
from .amd.model import DeepseekV32ForCausalLM
from .amd.mtp import DeepseekV32MTP
elif current_platform.is_xpu():
raise NotImplementedError("deepseek_v32 does not yet support XPU.")
else:
# Covers Blackwell (sm100) and all other CUDA devices.
from .nvidia.model import DeepseekV32ForCausalLM
from .nvidia.mtp import DeepseekV32MTP
__all__ = [
"DeepseekV32ForCausalLM",
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
+327
View File
@@ -0,0 +1,327 @@
# 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 torch
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
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.vocab_parallel_embedding import (
VocabParallelEmbedding,
)
from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader,
maybe_remap_kv_scale_name,
)
from vllm.model_executor.models.deepseek_v2 import (
DeepseekV2ForCausalLM,
DeepseekV2MLP,
DeepseekV2MoE,
_try_load_fp8_indexer_wk,
get_spec_layer_idx_from_weight_name,
)
from vllm.model_executor.models.utils import (
PPMissingLayer,
get_pp_missing_layer_names,
is_pp_missing_parameter,
make_empty_intermediate_tensors_factory,
make_layers,
)
from vllm.models.deepseek_v32.common.fused_ops import fused_allreduce_rms_norm
from vllm.sequence import IntermediateTensors
from .rocm import DeepseekV32MLAAttention
class DeepseekV32DecoderLayer(torch.nn.Module):
def __init__(
self,
vllm_config: VllmConfig,
prefix: str,
config=None,
topk_indices_buffer: torch.Tensor | None = None,
) -> None:
super().__init__()
if config is None:
config = vllm_config.model_config.hf_config
quant_config = vllm_config.quant_config
parallel_config = vllm_config.parallel_config
self.hidden_size = config.hidden_size
moe_layer_freq = getattr(config, "moe_layer_freq", 1)
layer_idx = int(prefix.split(sep=".")[-1])
self.layer_idx = layer_idx
self.use_mha = False
self.self_attn = DeepseekV32MLAAttention(
vllm_config=vllm_config,
config=config,
prefix=f"{prefix}.self_attn",
topk_indices_buffer=topk_indices_buffer,
)
if (
config.n_routed_experts is not None
and layer_idx >= config.first_k_dense_replace
and layer_idx % moe_layer_freq == 0
):
self.mlp = DeepseekV2MoE(
config=config,
parallel_config=parallel_config,
quant_config=quant_config,
prefix=f"{prefix}.mlp",
)
self.mlp.experts.moe_config.skip_final_all_reduce = True
else:
self.mlp = DeepseekV2MLP(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
prefix=f"{prefix}.mlp",
reduce_results=False,
)
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = RMSNorm(
config.hidden_size, eps=config.rms_norm_eps
)
self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0)
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
residual: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
if residual is None:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
else:
hidden_states, residual = fused_allreduce_rms_norm(
hidden_states, residual, self.input_layernorm
)
hidden_states = self.self_attn(positions=positions, hidden_states=hidden_states)
hidden_states, residual = fused_allreduce_rms_norm(
hidden_states, residual, self.post_attention_layernorm
)
hidden_states = self.mlp(hidden_states)
return hidden_states, residual
class DeepseekV32Model(torch.nn.Module):
fall_back_to_pt_during_load = False
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
from vllm.platforms import current_platform
self.device = current_platform.device_type
self.vocab_size = config.vocab_size
self.is_v32 = True
topk_indices_buffer = torch.empty(
vllm_config.scheduler_config.max_num_batched_tokens,
config.index_topk,
dtype=torch.int32,
device=self.device,
)
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.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
lambda prefix: DeepseekV32DecoderLayer(
vllm_config=vllm_config,
prefix=prefix,
topk_indices_buffer=topk_indices_buffer,
),
prefix=f"{prefix}.layers",
)
if get_pp_group().is_last_rank:
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
else:
self.norm = PPMissingLayer()
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
["hidden_states", "residual"], config.hidden_size
)
self.aux_hidden_state_layers = tuple[int, ...]()
self.num_redundant_experts = (
vllm_config.parallel_config.eplb_config.num_redundant_experts
)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
def forward(
self,
input_ids: torch.Tensor | None,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: 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:
assert input_ids is not None
hidden_states = self.embed_input_ids(input_ids)
residual = None
else:
assert intermediate_tensors is not None
hidden_states = intermediate_tensors["hidden_states"]
residual = intermediate_tensors["residual"]
aux_hidden_states = []
for idx, layer in enumerate(
islice(self.layers, self.start_layer, self.end_layer),
start=self.start_layer,
):
if idx in self.aux_hidden_state_layers:
aux_hidden_states.append(hidden_states + residual)
hidden_states, residual = layer(positions, hidden_states, residual)
if not get_pp_group().is_last_rank:
return IntermediateTensors(
{"hidden_states": hidden_states, "residual": residual}
)
hidden_states, _ = fused_allreduce_rms_norm(hidden_states, residual, self.norm)
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 = [
("gate_up_proj", "gate_proj", 0),
("gate_up_proj", "up_proj", 1),
("fused_qkv_a_proj", "q_a_proj", 0),
("fused_qkv_a_proj", "kv_a_proj_with_mqa", 1),
("wk_weights_proj", "wk", 0),
("wk_weights_proj", "weights_proj", 1),
]
expert_params_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=self.config.n_routed_experts,
num_redundant_experts=self.num_redundant_experts,
)
pp_missing_layer_names = get_pp_missing_layer_names(self)
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
_pending_wk_fp8: dict = {}
for name, loaded_weight in weights:
if "rotary_emb.inv_freq" in name:
continue
if get_spec_layer_idx_from_weight_name(self.config, name) is not None:
continue
if _try_load_fp8_indexer_wk(
name,
loaded_weight,
_pending_wk_fp8,
params_dict,
loaded_params,
pp_missing_layer_names,
):
continue
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in name:
continue
if ("mlp.experts." in name) and name not in params_dict:
continue
name_mapped = name.replace(weight_name, param_name)
if (
param_name == "fused_qkv_a_proj"
) and name_mapped not in params_dict:
continue
name = name_mapped
if name.endswith(".bias") and name not in params_dict:
continue
if is_pp_missing_parameter(name, self):
continue
param = params_dict[name]
param.weight_loader(param, loaded_weight, shard_id)
break
else:
is_expert_weight = False
for mapping in expert_params_mapping:
param_name, weight_name, expert_id, shard_id = mapping # type: ignore[assignment]
if weight_name not in name:
continue
is_expert_weight = True
name_mapped = name.replace(weight_name, param_name)
if is_pp_missing_parameter(name_mapped, self):
continue
param = params_dict[name_mapped]
weight_loader = typing.cast(
Callable[..., bool], param.weight_loader
)
success = weight_loader(
param,
loaded_weight,
name_mapped,
shard_id=shard_id,
expert_id=expert_id,
return_success=True,
)
if success:
name = name_mapped
break
else:
if is_expert_weight:
continue
if name.endswith(".bias") and name not in params_dict:
continue
name = maybe_remap_kv_scale_name(name, params_dict) # type: ignore[assignment]
if name is None:
continue
if is_pp_missing_parameter(name, self):
continue
param = params_dict[name]
loader = getattr(param, "weight_loader", default_weight_loader)
loader(param, loaded_weight)
loaded_params.add(name)
return loaded_params
class DeepseekV32ForCausalLM(DeepseekV2ForCausalLM):
model_cls = DeepseekV32Model
def set_moe_parameters(self):
self.num_expert_groups = getattr(self.config, "n_group", 1)
self.moe_layers = []
self.moe_mlp_layers = []
example_moe = None
for layer in self.model.layers:
if isinstance(layer, PPMissingLayer):
continue
if isinstance(layer.mlp, DeepseekV2MoE):
example_moe = layer.mlp
self.moe_mlp_layers.append(layer.mlp)
self.moe_layers.append(layer.mlp.experts)
self.extract_moe_parameters(example_moe)
+392
View File
@@ -0,0 +1,392 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import typing
from collections.abc import Callable, Iterable
import torch
import torch.nn as nn
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import VllmConfig
from vllm.distributed import tensor_model_parallel_all_reduce
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.vocab_parallel_embedding import (
VocabParallelEmbedding,
)
from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader,
maybe_remap_kv_scale_name,
)
from vllm.model_executor.models.deepseek_mtp import SharedHead
from vllm.model_executor.models.deepseek_v2 import (
DeepseekV2MixtureOfExperts,
DeepseekV2MoE,
_try_load_fp8_indexer_wk,
get_spec_layer_idx_from_weight_name,
)
from vllm.model_executor.models.utils import (
get_pp_missing_layer_names,
maybe_prefix,
)
from vllm.models.deepseek_v32.common.kernels import fused_eh_norm
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from .model import DeepseekV32DecoderLayer
class DeepseekV32MultiTokenPredictorLayer(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
quant_config = vllm_config.quant_config
self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
topk_indices_buffer = torch.empty(
vllm_config.scheduler_config.max_num_batched_tokens,
config.index_topk,
dtype=torch.int32,
device=current_platform.device_type,
)
self.shared_head = SharedHead(
config=config, prefix=prefix, quant_config=quant_config
)
self.mtp_block = DeepseekV32DecoderLayer(
vllm_config,
prefix,
config=config,
topk_indices_buffer=topk_indices_buffer,
)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
previous_hidden_states: torch.Tensor,
inputs_embeds: torch.Tensor | None = None,
spec_step_index: int = 0,
) -> torch.Tensor:
assert inputs_embeds is not None
eh_input = fused_eh_norm(
positions,
inputs_embeds,
previous_hidden_states,
self.enorm.weight,
self.hnorm.weight,
self.enorm.variance_epsilon,
)
hidden_states = self.eh_proj(eh_input)
hidden_states, residual = self.mtp_block(
positions=positions, hidden_states=hidden_states, residual=None
)
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
hidden_states = residual + hidden_states
hidden_states = self.shared_head.norm(hidden_states)
return hidden_states, hidden_states
class DeepseekV32MultiTokenPredictor(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
self.mtp_start_layer_idx = config.num_hidden_layers
self.num_mtp_layers = config.num_nextn_predict_layers
self.layers = torch.nn.ModuleDict(
{
str(idx): DeepseekV32MultiTokenPredictorLayer(
vllm_config, f"{prefix}.layers.{idx}"
)
for idx in range(
self.mtp_start_layer_idx,
self.mtp_start_layer_idx + self.num_mtp_layers,
)
}
)
self.embed_tokens = VocabParallelEmbedding(
config.vocab_size,
config.hidden_size,
prefix=maybe_prefix(prefix, "embed_tokens"),
)
self.logits_processor = LogitsProcessor(config.vocab_size)
def set_skip_topk(self, skip: bool):
for layer in self.layers.values():
self_attn = getattr(layer.mtp_block, "self_attn", None)
if self_attn is not None and hasattr(self_attn, "skip_topk"):
self_attn.skip_topk = skip
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
previous_hidden_states: torch.Tensor,
inputs_embeds: torch.Tensor | None = None,
spec_step_idx: int = 0,
) -> torch.Tensor:
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
current_step_idx = spec_step_idx % self.num_mtp_layers
return self.layers[str(self.mtp_start_layer_idx + current_step_idx)](
input_ids,
positions,
previous_hidden_states,
inputs_embeds,
current_step_idx,
)
def compute_logits(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
current_step_idx = spec_step_idx % self.num_mtp_layers
mtp_layer = self.layers[str(self.mtp_start_layer_idx + current_step_idx)]
return self.logits_processor(mtp_layer.shared_head.head, hidden_states)
class DeepseekV32MTP(nn.Module, DeepseekV2MixtureOfExperts):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
self.config = vllm_config.model_config.hf_config
self.quant_config = vllm_config.quant_config
self.model = DeepseekV32MultiTokenPredictor(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
self.set_moe_parameters()
def set_moe_parameters(self):
self.num_moe_layers = self.config.num_nextn_predict_layers
self.num_expert_groups = self.config.n_group
self.moe_layers = []
self.moe_mlp_layers = []
example_moe = None
for layer in self.model.layers.values():
mlp = layer.mtp_block.mlp
if isinstance(mlp, DeepseekV2MoE):
example_moe = mlp
self.moe_mlp_layers.append(mlp)
self.moe_layers.append(mlp.experts)
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 forward(
self,
input_ids: torch.Tensor | None,
positions: torch.Tensor,
hidden_states: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
spec_step_idx: int = 0,
) -> torch.Tensor:
return self.model(
input_ids, positions, hidden_states, inputs_embeds, spec_step_idx
)
def compute_logits(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor | None:
return self.model.compute_logits(hidden_states, spec_step_idx)
def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
spec_layer_weight_names = [
"embed_tokens",
"enorm",
"hnorm",
"eh_proj",
"shared_head",
]
shared_weight_names = ["embed_tokens"]
spec_layer_weight = False
shared_weight = False
for weight_name in spec_layer_weight_names:
if weight_name in name:
spec_layer_weight = True
if weight_name in shared_weight_names:
shared_weight = True
break
if not spec_layer_weight:
name = name.replace(
f"model.layers.{spec_layer}.", f"model.layers.{spec_layer}.mtp_block."
)
elif shared_weight:
name = name.replace(f"model.layers.{spec_layer}.", "model.")
return name
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
rocm_aiter_moe_shared_expert_enabled = (
rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()
)
stacked_params_mapping = [
("gate_up_proj", "gate_proj", 0),
("gate_up_proj", "up_proj", 1),
("fused_qkv_a_proj", "q_a_proj", 0),
("fused_qkv_a_proj", "kv_a_proj_with_mqa", 1),
("wk_weights_proj", "wk", 0),
("wk_weights_proj", "weights_proj", 1),
]
expert_params_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=self.config.n_routed_experts
+ (
self.config.n_shared_experts
if rocm_aiter_moe_shared_expert_enabled
else 0
),
)
pp_missing_layer_names = get_pp_missing_layer_names(self)
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
_pending_wk_fp8: dict = {}
for name, loaded_weight in weights:
if "rotary_emb.inv_freq" in name:
continue
spec_layer = get_spec_layer_idx_from_weight_name(self.config, name)
if spec_layer is None:
continue
is_fusion_moe_shared_experts_layer = (
rocm_aiter_moe_shared_expert_enabled and ("mlp.shared_experts" in name)
)
name = self._rewrite_spec_layer_name(spec_layer, name)
if _try_load_fp8_indexer_wk(
name,
loaded_weight,
_pending_wk_fp8,
params_dict,
loaded_params,
pp_missing_layer_names,
):
continue
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in name:
continue
if ("mlp.experts." in name) and name not in params_dict:
continue
if is_fusion_moe_shared_experts_layer:
continue
name_mapped = name.replace(weight_name, param_name)
if (
param_name == "fused_qkv_a_proj"
) and name_mapped not in params_dict:
continue
else:
name = name_mapped
if name.endswith(".bias") and name not in params_dict:
continue
param = params_dict[name]
weight_loader = param.weight_loader
weight_loader(param, loaded_weight, shard_id)
break
else:
num_chunks = 1
if is_fusion_moe_shared_experts_layer:
num_chunks = getattr(self.config, "n_shared_experts", 1) or 1
split_dim = (
1
if ("down_proj.weight" in name and loaded_weight.ndim > 1)
else 0
)
total = loaded_weight.shape[split_dim]
assert total % num_chunks == 0
chunk_size = total // num_chunks
for j in range(num_chunks):
chunk_name = name
weight_to_load = loaded_weight
if is_fusion_moe_shared_experts_layer:
chunk_slice = slice(j * chunk_size, (j + 1) * chunk_size)
if loaded_weight.ndim == 1:
weight_to_load = loaded_weight[chunk_slice]
elif split_dim == 0:
weight_to_load = loaded_weight[chunk_slice, :]
else:
weight_to_load = loaded_weight[:, chunk_slice]
chunk_name = name.replace(
"mlp.shared_experts",
f"mlp.experts.{self.config.n_routed_experts + j}",
)
is_expert_weight = False
for mapping in expert_params_mapping:
param_name, weight_name, expert_id, shard_id = mapping # type: ignore[assignment]
if weight_name not in chunk_name:
continue
is_expert_weight = True
name_mapped = chunk_name.replace(weight_name, param_name)
param = params_dict[name_mapped]
weight_loader = typing.cast(
Callable[..., bool], param.weight_loader
)
success = weight_loader(
param,
weight_to_load,
name_mapped,
shard_id=shard_id,
expert_id=expert_id,
return_success=True,
)
if success:
if not is_fusion_moe_shared_experts_layer:
name = name_mapped
else:
loaded_params.add(name_mapped)
break
else:
if is_expert_weight:
continue
if name.endswith(".bias") and name not in params_dict:
continue
name = maybe_remap_kv_scale_name(name, params_dict) # type: ignore[assignment]
if name is None:
continue
if (
spec_layer != self.model.mtp_start_layer_idx
and ".layers" not in name
):
continue
param = params_dict[name]
weight_loader = getattr(
param, "weight_loader", default_weight_loader
)
weight_loader(param, loaded_weight)
if not is_fusion_moe_shared_experts_layer:
loaded_params.add(name)
loaded_layers: set[int] = set()
for param_name in loaded_params:
spec_layer = get_spec_layer_idx_from_weight_name(self.config, param_name)
if spec_layer is not None:
loaded_layers.add(spec_layer)
for layer_idx in range(
self.model.mtp_start_layer_idx,
self.model.mtp_start_layer_idx + self.model.num_mtp_layers,
):
if layer_idx not in loaded_layers:
raise ValueError(
f"MTP speculative decoding layer {layer_idx} weights "
f"missing from checkpoint."
)
return loaded_params
+263
View File
@@ -0,0 +1,263 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.forward_context import get_forward_context
from vllm.model_executor.layers.sparse_attn_indexer import SparseAttnIndexer
from vllm.model_executor.models.deepseek_v2 import DeepseekV32IndexerCache
from vllm.models.deepseek_v32.attention import DeepseekV32Attention, DeepseekV32Indexer
from vllm.models.deepseek_v32.common.kernels import fused_norm_rope, fused_q
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backends.mla.indexer import DeepseekV32IndexerBackend
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
ROCMAiterMLASparseBackend,
)
class DeepseekV32MLASparseBackend(ROCMAiterMLASparseBackend):
@staticmethod
def get_supported_kernel_block_sizes() -> list:
return [16, 32]
class DeepseekV32ROCmIndexerBackend(DeepseekV32IndexerBackend):
@staticmethod
def get_supported_kernel_block_sizes() -> list:
return [16, 32]
class DeepseekV32ROCmIndexerCache(DeepseekV32IndexerCache):
def get_attn_backend(self):
return DeepseekV32ROCmIndexerBackend
class DeepseekV32ROCmIndexer(DeepseekV32Indexer):
indexer_cache_cls = DeepseekV32ROCmIndexerCache
class DeepseekV32MLAAttention(DeepseekV32Attention):
require_fp8_kv_cache: bool = False
indexer_cls = DeepseekV32ROCmIndexer
def __init__(self, vllm_config, config, prefix, topk_indices_buffer=None):
super().__init__(
vllm_config,
config,
prefix,
topk_indices_buffer,
attn_backend=DeepseekV32MLASparseBackend,
)
self.indexer_op: SparseAttnIndexer | None = None
if self.indexer is not None:
self.indexer_op = SparseAttnIndexer(
self.indexer.k_cache,
self.indexer.quant_block_size,
self.indexer.scale_fmt,
self.indexer.topk_tokens,
self.indexer.head_dim,
self.indexer.max_model_len,
self.indexer.max_total_seq_len,
topk_indices_buffer,
skip_k_cache_insert=True,
)
self._fp8_kv = is_quantized_kv_cache(self.kv_cache_dtype)
self._fp8_kv_needs_view = self._fp8_kv and self.kv_cache_dtype != "fp8_ds_mla"
def _compute_ql_nope(self, q_c: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
q = self.q_b_proj(q_c)[0].view(-1, self.num_local_heads, self.qk_head_dim)
q_nope, q_pe = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
q_nope = q_nope.transpose(0, 1) # (N, tokens, P)
if self.is_aiter_triton_fp4_bmm_enabled:
from aiter.ops.triton.batched_gemm_a16wfp4 import batched_gemm_a16wfp4
ql_nope = batched_gemm_a16wfp4(
q_nope, self.W_K, self.W_K_scale, transpose_bm=True, prequant=True
)
elif self.is_aiter_triton_fp8_bmm_enabled:
from vllm._aiter_ops import rocm_aiter_ops
ql_nope = rocm_aiter_ops.triton_fp8_bmm(
q_nope, self.W_K, self.W_K_scale, group_size=128, transpose_bm=True
)
else:
ql_nope = torch.bmm(q_nope, self.W_UK_T).transpose(0, 1)
return ql_nope, q_pe
def _run_indexer(
self,
q_c: torch.Tensor,
index_q_fp8: torch.Tensor | None,
index_weights_out: torch.Tensor | None,
) -> None:
"""Run the ROCm sparse indexer (forward_hip) if this layer has an indexer."""
if self.indexer_op is not None:
self.indexer_op.forward_hip(q_c, index_q_fp8, None, index_weights_out)
def _build_q_for_attn(
self,
ql_nope: torch.Tensor,
mqa_q: torch.Tensor,
num_actual: int,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if self._fp8_kv:
# fp8 KV: mqa_q is the full [ql_nope; q_pe] packed as fp8.
return mqa_q[:num_actual]
return (ql_nope[:num_actual], mqa_q[:num_actual])
def _compute_uv_out(
self,
attn_out: torch.Tensor,
output: torch.Tensor,
num_actual: int,
) -> None:
x = attn_out.view(
num_actual, self.num_local_heads, self.kv_lora_rank
).transpose(0, 1) # (N, tokens, L)
out_view = output[:num_actual].view(
num_actual, self.num_local_heads, self.v_head_dim
)
if self.is_aiter_triton_fp4_bmm_enabled:
from aiter.ops.triton.batched_gemm_a16wfp4 import batched_gemm_a16wfp4
batched_gemm_a16wfp4(
x, self.W_V, self.W_V_scale, out_view, transpose_bm=True, prequant=True
)
elif self.is_aiter_triton_fp8_bmm_enabled:
from vllm._aiter_ops import rocm_aiter_ops
rocm_aiter_ops.triton_fp8_bmm(
x,
self.W_V,
self.W_V_scale,
group_size=128,
transpose_bm=True,
YQ=out_view,
)
else:
torch.bmm(x, self.W_UV, out=out_view.transpose(0, 1))
@eager_break_during_capture
def _fused_attention(
self,
positions: torch.Tensor,
q_c: torch.Tensor,
kv_c: torch.Tensor,
k_pe: torch.Tensor,
index_k: torch.Tensor | None,
index_weights: torch.Tensor | None,
output: torch.Tensor,
) -> None:
forward_context = get_forward_context()
attn_metadata_raw = forward_context.attn_metadata
if isinstance(attn_metadata_raw, dict):
attn_metadata = attn_metadata_raw.get(self.layer_name)
elif isinstance(attn_metadata_raw, list):
attn_metadata = attn_metadata_raw[0].get(self.layer_name)
else:
attn_metadata = attn_metadata_raw
slot_mapping = forward_context.slot_mapping
assert isinstance(slot_mapping, dict)
mla_slot = slot_mapping.get(self.layer_name)
if self.indexer is not None:
has_indexer = True
indexer_k_norm_w = self.indexer.k_norm.weight
indexer_k_norm_bias = self.indexer.k_norm.bias
indexer_k_norm_eps = self.indexer.k_norm.eps
indexer_k_rope_cos_sin_cache = self.indexer_rope_emb.cos_sin_cache
indexer_k_cache = self.indexer.k_cache.kv_cache
indexer_softmax_scale = self.indexer.softmax_scale
indexer_n_head_scale = self.indexer.n_head**-0.5
else:
has_indexer = False
indexer_k_norm_w = None
indexer_k_norm_bias = None
indexer_k_norm_eps = 1e-6
indexer_k_rope_cos_sin_cache = None
indexer_k_cache = None
indexer_softmax_scale = 0.0
indexer_n_head_scale = 0.0
if attn_metadata is None:
mla_kv_cache = None
mla_k_scale = None
indexer_k_cache = None
mla_slot = None
else:
mla_kv_cache = self.kv_cache
mla_k_scale = self._k_scale
q_c = fused_norm_rope(
positions,
q_c,
self.q_a_layernorm.weight,
self.q_a_layernorm.variance_epsilon,
kv_c,
self.kv_a_layernorm.weight,
self.kv_a_layernorm.variance_epsilon,
k_pe,
self.rotary_emb.cos_sin_cache,
index_k,
indexer_k_norm_w,
indexer_k_norm_bias,
indexer_k_norm_eps,
indexer_k_rope_cos_sin_cache,
self.topk_indices_buffer,
slot_mapping=mla_slot,
indexer_k_cache=indexer_k_cache,
mla_kv_cache=mla_kv_cache,
mla_kv_cache_dtype=self.kv_cache_dtype,
mla_k_scale=mla_k_scale,
has_indexer=has_indexer,
index_rope_interleave=self._index_rope_interleave,
)
ql_nope, q_pe = self._compute_ql_nope(q_c)
if self.indexer is not None:
index_q = self.indexer.wq_b(q_c)[0]
index_q = index_q.view(-1, self.indexer.n_head, self.indexer.head_dim)
else:
index_q = None
index_q_fp8, index_weights_out, mqa_q = fused_q(
positions,
q_pe,
self.rotary_emb.cos_sin_cache,
index_q,
self.indexer_rope_emb.cos_sin_cache if has_indexer else None,
ql_nope,
self._q_scale,
index_weights,
indexer_softmax_scale,
indexer_n_head_scale,
has_indexer=has_indexer,
index_rope_interleave=self._index_rope_interleave,
quantize_mqa=self._fp8_kv,
)
self._run_indexer(q_c, index_q_fp8, index_weights_out)
if attn_metadata is None:
output.zero_()
return
num_actual = attn_metadata.num_actual_tokens # type: ignore[attr-defined]
kv_cache = self.kv_cache
if self._fp8_kv_needs_view:
kv_cache = kv_cache.view(torch.float8_e4m3fn)
q_for_attn = self._build_q_for_attn(ql_nope, mqa_q, num_actual)
attn_out, _ = self.impl.forward_mqa( # type: ignore[attr-defined]
q_for_attn, kv_cache, attn_metadata, self
)
self._compute_uv_out(attn_out, output, num_actual)
@@ -31,12 +31,13 @@ from vllm.model_executor.models.deepseek_v2 import (
yarn_get_mscale,
)
from vllm.model_executor.models.utils import extract_layer_index
from vllm.models.deepseek_v32.common.kernels import fused_norm_rope, fused_q
from vllm.utils.torch_utils import is_quantized_kv_cache
from .kernels import fused_norm_rope, fused_q
class DeepseekV32Indexer(nn.Module):
indexer_cache_cls = DeepseekV32IndexerCache
def __init__(
self,
vllm_config: VllmConfig,
@@ -55,7 +56,6 @@ class DeepseekV32Indexer(nn.Module):
self.rope_dim = config.qk_rope_head_dim
self.q_lora_rank = q_lora_rank
# No tensor parallel, just replicated.
self.wq_b = ReplicatedLinear(
self.q_lora_rank,
self.head_dim * self.n_head,
@@ -63,8 +63,7 @@ class DeepseekV32Indexer(nn.Module):
quant_config=quant_config,
prefix=f"{prefix}.wq_b",
)
# Fused wk + weights_proj: single GEMM producing [head_dim + n_head].
# FP8 wk weights are upcasted to BF16 during loading to keep this fused.
self.wk_weights_proj = MergedColumnParallelLinear(
hidden_size,
[self.head_dim, self.n_head],
@@ -80,9 +79,8 @@ class DeepseekV32Indexer(nn.Module):
self.quant_block_size = 128
self.topk_indices_buffer = topk_indices_buffer
# fp8 naive cache: value in fp8 + fp32 scale per quant_block_size element.
assert cache_config is not None, "DeepSeek V3.2 indexer requires cache_config"
self.k_cache = DeepseekV32IndexerCache(
self.k_cache = type(self).indexer_cache_cls(
head_dim=self.head_dim + self.head_dim // self.quant_block_size * 4,
dtype=torch.uint8,
prefix=f"{prefix}.k_cache",
@@ -120,7 +118,7 @@ class DeepseekV32Indexer(nn.Module):
q_pe, q_nope = torch.split(
q, [self.rope_dim, self.head_dim - self.rope_dim], dim=-1
)
# Fused wk + weights_proj: one GEMM, then split.
kw, _ = self.wk_weights_proj(hidden_states)
k = kw[:, : self.head_dim]
weights = kw[:, self.head_dim :]
@@ -131,14 +129,13 @@ class DeepseekV32Indexer(nn.Module):
)
q_pe, k_pe = rotary_emb(positions, q_pe, k_pe.unsqueeze(1))
# RoPE (NeoX) can introduce extra leading dims; reshape back to flat.
q_pe = q_pe.reshape(-1, self.n_head, self.rope_dim)
k_pe = k_pe.reshape(-1, 1, self.rope_dim)
q = torch.cat([q_pe, q_nope], dim=-1)
k = torch.cat([k_pe.squeeze(-2), k_nope], dim=-1)
# Only quant q here; k quant is fused with cache insertion.
q = q.view(-1, self.head_dim)
q_fp8, q_scale = per_token_group_quant_fp8(
q,
@@ -158,9 +155,10 @@ class DeepseekV32Indexer(nn.Module):
class DeepseekV32Attention(MLAAttention):
# Narrow the base's broadly-typed `indexer` to the concrete type so the
# `if self.indexer is not None` guards below type-check its attributes.
indexer: "DeepseekV32Indexer | None"
indexer_cls: "type[DeepseekV32Indexer]" = DeepseekV32Indexer
require_fp8_kv_cache: bool = True
def __init__(
self,
@@ -168,6 +166,7 @@ class DeepseekV32Attention(MLAAttention):
config: DeepseekV2Config | DeepseekV3Config,
prefix: str,
topk_indices_buffer: torch.Tensor | None = None,
attn_backend: "type | None" = None,
) -> None:
quant_config = vllm_config.quant_config
cache_config = vllm_config.cache_config
@@ -200,11 +199,6 @@ class DeepseekV32Attention(MLAAttention):
mscale = yarn_get_mscale(scaling_factor, float(mscale_all_dim))
scaling = scaling * mscale * mscale
# DSA "shared indexer" pattern: only some layers carry an indexer; the
# rest reuse the top-k written by the previous indexer layer into the
# shared topk_indices_buffer. DeepSeek-V3.2 builds it on every layer
# (index_topk_freq defaults to 1); GLM-5.2 uses index_topk_freq=4 so
# only layers [0,1,2,6,10,...] (+ MTP) carry one.
layer_id = extract_layer_index(prefix)
index_topk_freq = getattr(config, "index_topk_freq", 1)
index_topk_pattern = getattr(config, "index_topk_pattern", None)
@@ -217,12 +211,10 @@ class DeepseekV32Attention(MLAAttention):
skip_topk = index_topk_pattern[layer_id] == "S"
else:
skip_topk = False
# MTP/nextn layers always build a full indexer (they toggle at runtime).
num_hidden_layers = getattr(config, "num_hidden_layers", None)
is_mtp_layer = num_hidden_layers is not None and layer_id >= num_hidden_layers
# Build kv_b_proj + indexer first; they are passed to MLAAttention.__init__
# (which runs nn.Module.__init__ and registers them).
kv_b_proj = ColumnParallelLinear(
kv_lora_rank,
num_heads * (qk_nope_head_dim + v_head_dim),
@@ -232,7 +224,7 @@ class DeepseekV32Attention(MLAAttention):
)
indexer = None
if not skip_topk or is_mtp_layer:
indexer = DeepseekV32Indexer(
indexer = type(self).indexer_cls(
vllm_config,
config,
hidden_size,
@@ -243,8 +235,6 @@ class DeepseekV32Attention(MLAAttention):
prefix=f"{prefix}.indexer",
)
# Set up the MLA engine (impl, KV cache, scales, backend, registration,
# and process_weights_after_loading) via the MLAAttention base.
super().__init__(
num_heads=num_local_heads,
scale=scaling,
@@ -260,41 +250,32 @@ class DeepseekV32Attention(MLAAttention):
use_sparse=True,
indexer=indexer,
topk_indices_buffer=topk_indices_buffer,
attn_backend=attn_backend,
)
self.num_local_heads = num_local_heads
self.qk_head_dim = qk_head_dim
self.indexer = indexer
self.topk_indices_buffer = topk_indices_buffer
# Runtime toggle for index_share_for_mtp_iteration: MTP draft step 0
# computes the top-k, steps 1+ set this True to reuse it.
self.skip_topk = False
# Fused fp8 paths: Triton fused norm/rope/cache + fused-q. Two layouts,
# picked by the sparse MLA backend's query support:
# * supports_quant_query_input (FlashInfer sparse, SM100): per-tensor
# fp8 cache + a single packed fp8 MQA query.
# * not supported (FlashMLA sparse, SM90/SM100): fp8_ds_mla cache
# (per-128 block-scaled fp8 NoPE + unquantized bf16 RoPE) + a bf16
# (ql_nope, q_pe) query tuple. FA3 cannot mix a bf16 query with an
# fp8 KV cache, so FlashMLA (which dequantizes internally) is used.
# FlashMLA sparse runs on both Hopper and Blackwell, so this is the
# only DSA path on SM90 and an opt-in alternative on SM100.
assert is_quantized_kv_cache(self.kv_cache_dtype), (
"deepseek_v32 (nvidia) requires an fp8 KV cache served by a sparse "
"MLA backend. Launch with --kv-cache-dtype fp8 (FlashInfer sparse) "
"or --kv-cache-dtype fp8_ds_mla (FlashMLA sparse)."
)
self._fp8_query = self.impl.supports_quant_query_input
if not self._fp8_query:
assert self.kv_cache_dtype == "fp8_ds_mla", (
"deepseek_v32 (nvidia) on a bf16-query sparse MLA backend "
"(FlashMLA sparse) requires the fp8_ds_mla KV cache layout. "
"Launch with --kv-cache-dtype fp8_ds_mla."
if self.require_fp8_kv_cache:
assert is_quantized_kv_cache(self.kv_cache_dtype), (
"deepseek_v32 (nvidia) requires an fp8 KV cache served by a sparse "
"MLA backend. Launch with --kv-cache-dtype fp8 (FlashInfer sparse) "
"or --kv-cache-dtype fp8_ds_mla (FlashMLA sparse)."
)
# The paged KV cache is stored as uint8 and viewed as fp8 for the decode
# (per-tensor fp8). The fp8_ds_mla layout is consumed as raw bytes.
self._fp8_kv_needs_view = self.kv_cache_dtype != "fp8_ds_mla"
# GLM-5.2 uses interleaved indexer RoPE; DeepSeek-V3.2 uses NeoX.
self._fp8_query = self.impl.supports_quant_query_input
if not self._fp8_query:
assert self.kv_cache_dtype == "fp8_ds_mla", (
"deepseek_v32 (nvidia) on a bf16-query sparse MLA backend "
"(FlashMLA sparse) requires the fp8_ds_mla KV cache layout. "
"Launch with --kv-cache-dtype fp8_ds_mla."
)
self._fp8_kv_needs_view = self.kv_cache_dtype != "fp8_ds_mla"
self._index_rope_interleave = getattr(config, "indexer_rope_interleave", False)
# Remaining MLA projections (registered on this module).
@@ -313,9 +294,7 @@ class DeepseekV32Attention(MLAAttention):
prefix=f"{prefix}.q_b_proj",
)
self.kv_a_layernorm = RMSNorm(kv_lora_rank, eps=config.rms_norm_eps)
# reduce_results=False: the attention all-reduce is fused with the
# following post_attention_layernorm in the decoder layer via
# fused_allreduce_rms_norm.
self.o_proj = RowParallelLinear(
num_heads * v_head_dim,
hidden_size,
@@ -380,11 +359,6 @@ class DeepseekV32Attention(MLAAttention):
index_weights: torch.Tensor | None,
output: torch.Tensor,
) -> None:
# One eager break for the whole attention. In FULL cudagraph mode (pure
# decode) this decorator is a no-op, so everything here is captured; in
# PIECEWISE (prefill) it runs eagerly. The cache writes, sparse indexer,
# and forward_mqa all depend on per-step metadata and must not be split
# out (PIECEWISE capture would otherwise miss them).
forward_context = get_forward_context()
attn_metadata_raw = forward_context.attn_metadata
if isinstance(attn_metadata_raw, dict):
@@ -516,8 +490,6 @@ class DeepseekV32Attention(MLAAttention):
:num_actual
]
else:
# FlashMLA sparse: bf16 (ql_nope, q_pe) tuple. mqa_q is the RoPE'd
# q_pe; ql_nope is consumed directly.
mqa_q_arg = (ql_nope[:num_actual], mqa_q[:num_actual])
attn_out, _ = self.impl.forward_mqa( # type: ignore[attr-defined]
mqa_q_arg, kv_cache, attn_metadata, self
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
+2 -3
View File
@@ -38,11 +38,10 @@ from vllm.model_executor.models.utils import (
make_layers,
sequence_parallel_chunk,
)
from vllm.models.deepseek_v32.attention import DeepseekV32Attention
from vllm.models.deepseek_v32.common.fused_ops import fused_allreduce_rms_norm
from vllm.sequence import IntermediateTensors
from .attention import DeepseekV32Attention
from .fused_ops import fused_allreduce_rms_norm
def _all_gather_sp_states(
hidden_states: torch.Tensor,
+1 -1
View File
@@ -38,10 +38,10 @@ from vllm.model_executor.models.utils import (
get_pp_missing_layer_names,
maybe_prefix,
)
from vllm.models.deepseek_v32.common.kernels import fused_eh_norm
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from .kernels import fused_eh_norm
from .model import DeepseekV32DecoderLayer