[Refactor] Normalize DeepSeek V4.1 model package naming (#56741)
Signed-off-by: Bugen Zhao <i@bugenzhao.com>
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -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}"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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_v41.attention import DeepseekV4Attention
|
||||
from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
|
||||
from vllm.models.deepseek_v41.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],
|
||||
)
|
||||
@@ -0,0 +1,349 @@
|
||||
# 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_PLACEHOLDER,
|
||||
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
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user