[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,20 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepSeek V4.1 hardware-isolated model entry point."""
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from .quant_config import DeepseekV4FP8Config
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from .amd.dspark import DSparkDeepseekV4ForCausalLM
|
||||
from .amd.vl_model import DeepseekV41ForCausalLM
|
||||
else:
|
||||
from .nvidia.dspark import DSparkDeepseekV4ForCausalLM
|
||||
from .nvidia.vl_model import DeepseekV41ForCausalLM
|
||||
|
||||
__all__ = [
|
||||
"DSparkDeepseekV4ForCausalLM",
|
||||
"DeepseekV4FP8Config",
|
||||
"DeepseekV41ForCausalLM",
|
||||
]
|
||||
@@ -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()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,363 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Multimodal preprocessing for the DeepSeek-V4.1 vision variant.
|
||||
|
||||
The image transform and image-span construction are ported from the
|
||||
official repository's ``image_processor.py`` so that token counts bit-match
|
||||
the reference. Each ``<|deepseek_image|>`` placeholder in the prompt expands
|
||||
to ``[IMAGE_START] + ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h +
|
||||
[IMAGE_END]``; every span position carries ``image_token_id`` (129264) in
|
||||
``input_ids`` and the roles ride along in a per-image ``types`` tensor
|
||||
(the reference's out-of-band ``token_types``). IMAGE slots receive aligner
|
||||
rows in reading order; the delimiters take the learned ``image_start`` /
|
||||
``image_newline`` / ``image_end`` vectors.
|
||||
|
||||
The token stream matches the reference exactly: no compressor-alignment
|
||||
pad is inserted (the reference pools image tokens across compressor-group
|
||||
boundaries freely).
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image, ImageOps
|
||||
from transformers import BatchFeature
|
||||
|
||||
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
|
||||
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
|
||||
from vllm.multimodal.processing import (
|
||||
BaseDummyInputsBuilder,
|
||||
BaseMultiModalProcessor,
|
||||
BaseProcessingInfo,
|
||||
PromptReplacement,
|
||||
PromptUpdate,
|
||||
PromptUpdateDetails,
|
||||
)
|
||||
from vllm.transformers_utils.configs.deepseek_v41 import DeepseekV41Config
|
||||
|
||||
IMAGE_START, IMAGE, IMAGE_NEW_LINE, IMAGE_END = range(4)
|
||||
|
||||
IMAGE_PLACEHOLDER = "<|deepseek_image|>"
|
||||
|
||||
# The checkpoint tokenizer's id for IMAGE_PLACEHOLDER (the config's
|
||||
# ``image_token_id``). Every image-span position carries this id, exactly
|
||||
# like the reference; the MoE router detects image tokens as the range
|
||||
# [IMAGE_SENTINEL_BASE_ID, IMAGE_SENTINEL_BASE_ID + 5).
|
||||
IMAGE_SENTINEL_BASE_ID = 129264
|
||||
|
||||
|
||||
def image_sentinel_mask(token_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Boolean mask for image-span positions."""
|
||||
return token_ids == IMAGE_SENTINEL_BASE_ID
|
||||
|
||||
|
||||
def validate_image_sentinel_ids(tokenizer) -> None:
|
||||
"""Check the image token id against the tokenizer."""
|
||||
image_id = tokenizer.convert_tokens_to_ids(IMAGE_PLACEHOLDER)
|
||||
if image_id != IMAGE_SENTINEL_BASE_ID:
|
||||
raise ValueError(
|
||||
f"Image placeholder {IMAGE_PLACEHOLDER!r} has id {image_id}, "
|
||||
f"expected {IMAGE_SENTINEL_BASE_ID} (the config's "
|
||||
"image_token_id); the DeepSeek-V4.1 vision path keys image "
|
||||
"routing and engram masking off this id."
|
||||
)
|
||||
|
||||
|
||||
def llm_grid(best_height, best_width, patch_size, downsample_ratio):
|
||||
"""Token grid the aligner produces from a patch grid of this pixel size."""
|
||||
return (
|
||||
math.ceil((best_height // patch_size) / downsample_ratio),
|
||||
math.ceil((best_width // patch_size) / downsample_ratio),
|
||||
)
|
||||
|
||||
|
||||
def num_image_tokens(n_llm_h: int, n_llm_w: int) -> int:
|
||||
return n_llm_h * (n_llm_w + 1) + 2
|
||||
|
||||
|
||||
def solve_resize_ratio(height, width, patch_size, downsample_ratio, max_n_token):
|
||||
"""Largest aspect-preserving pixel size whose token grid still fits in
|
||||
max_n_token. Returns (best_height, best_width)."""
|
||||
r = height / width
|
||||
max_w_float = math.sqrt((max_n_token - 2) / r + 0.25) - 0.5
|
||||
max_h_float = max_w_float * r
|
||||
cell = patch_size * downsample_ratio
|
||||
if max_w_float < 1.0: # very tall: collapse to a single column
|
||||
return (max_n_token - 2) // 2 * cell, cell
|
||||
if max_h_float < 1.0: # very wide: collapse to a single row
|
||||
return cell, (max_n_token - 3) * cell
|
||||
beta = min(
|
||||
math.floor(max_w_float) * cell / width,
|
||||
math.floor(max_h_float) * cell / height,
|
||||
)
|
||||
return (
|
||||
math.floor(height * beta / patch_size) * patch_size,
|
||||
math.floor(width * beta / patch_size) * patch_size,
|
||||
)
|
||||
|
||||
|
||||
def safe_resize(
|
||||
height, width, best_height, best_width, patch_size, downsample_ratio, max_n_token
|
||||
):
|
||||
"""Shrink the pixel size until the image costs at most max_n_token LLM
|
||||
tokens."""
|
||||
n_llm_h, n_llm_w = llm_grid(best_height, best_width, patch_size, downsample_ratio)
|
||||
if num_image_tokens(n_llm_h, n_llm_w) > max_n_token:
|
||||
best_height, best_width = solve_resize_ratio(
|
||||
height, width, patch_size, downsample_ratio, max_n_token
|
||||
)
|
||||
n_llm_h, n_llm_w = llm_grid(
|
||||
best_height, best_width, patch_size, downsample_ratio
|
||||
)
|
||||
assert num_image_tokens(n_llm_h, n_llm_w) <= max_n_token
|
||||
return n_llm_h, n_llm_w, best_height, best_width
|
||||
|
||||
|
||||
def load_image(
|
||||
image: Image.Image,
|
||||
*,
|
||||
patch_size: int,
|
||||
downsample_ratio: int,
|
||||
max_n_token: int,
|
||||
min_pixels: int,
|
||||
max_wh_ratio: float | None,
|
||||
):
|
||||
"""Transform one PIL image into ViT patches.
|
||||
|
||||
Same math as the reference ``load_image``, except the image is already
|
||||
decoded (vLLM supplies PIL images instead of a record dict).
|
||||
"""
|
||||
p = patch_size
|
||||
image = image.convert("RGB")
|
||||
width, height = image.size
|
||||
if max_wh_ratio is not None and width > height * max_wh_ratio:
|
||||
width = height * max_wh_ratio
|
||||
if 0 < width * height < min_pixels:
|
||||
ratio = (min_pixels / (width * height)) ** 0.5
|
||||
width = int(width * ratio)
|
||||
height = int(height * ratio)
|
||||
best_width = math.ceil(width / p) * p
|
||||
best_height = math.ceil(height / p) * p
|
||||
n_llm_h, n_llm_w, best_height, best_width = safe_resize(
|
||||
height, width, best_height, best_width, p, downsample_ratio, max_n_token
|
||||
)
|
||||
n_vit_h, n_vit_w = best_height // p, best_width // p
|
||||
if max_wh_ratio is not None and image.width >= max_wh_ratio * image.height:
|
||||
image = image.resize((best_width, best_height))
|
||||
else:
|
||||
image = ImageOps.pad(image, (best_width, best_height), color=(127, 127, 127))
|
||||
x = torch.from_numpy(np.asarray(image, dtype=np.float32)).permute(2, 0, 1) / 255
|
||||
x = ((x - 0.5) / 0.5).to(torch.bfloat16)
|
||||
patches = (
|
||||
x.reshape(3, n_vit_h, p, n_vit_w, p)
|
||||
.permute(1, 3, 0, 2, 4)
|
||||
.reshape(n_vit_h * n_vit_w, 3, p, p)
|
||||
)
|
||||
return patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w
|
||||
|
||||
|
||||
def image_token_types(n_llm_h: int, n_llm_w: int) -> torch.Tensor:
|
||||
"""Reading-order span layout: one IMAGE_NEW_LINE per row."""
|
||||
types = [IMAGE_START]
|
||||
types += ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h
|
||||
types.append(IMAGE_END)
|
||||
return torch.tensor(types, dtype=torch.int64)
|
||||
|
||||
|
||||
class DeepseekV4VLImageProcessor:
|
||||
"""Per-image transform (the PIL-input equivalent of the reference
|
||||
``load_image``)."""
|
||||
|
||||
def __init__(self, config: DeepseekV41Config) -> None:
|
||||
super().__init__()
|
||||
self.patch_size = config.vision_patch_size
|
||||
self.downsample_ratio = config.vision_downsample_ratio
|
||||
self.max_n_token = config.vision_max_n_token
|
||||
self.min_pixels = config.vision_min_pixels
|
||||
self.max_wh_ratio = config.vision_max_wh_ratio
|
||||
|
||||
def __call__(self, image: Image.Image):
|
||||
return load_image(
|
||||
image,
|
||||
patch_size=self.patch_size,
|
||||
downsample_ratio=self.downsample_ratio,
|
||||
max_n_token=self.max_n_token,
|
||||
min_pixels=self.min_pixels,
|
||||
max_wh_ratio=self.max_wh_ratio,
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4VLProcessor:
|
||||
"""Minimal stand-in for the HF processor of DeepSeek-V4.1 vision models.
|
||||
|
||||
The official repository ships image preprocessing as plain functions in
|
||||
``image_processor.py`` (no ``auto_map`` processor), so this class wraps
|
||||
their ports directly and the model loads without ``--trust-remote-code``.
|
||||
|
||||
``__call__`` returns a ``BatchFeature`` with one entry per image
|
||||
(flattened across images):
|
||||
|
||||
- ``patches``: ``(sum(n_vit_h * n_vit_w), 3, p, p)`` bf16 ViT patches.
|
||||
- ``vit_grid``: ``(num_images, 2)`` int64 ``[n_vit_h, n_vit_w]``.
|
||||
- ``llm_grid``: ``(num_images, 2)`` int64 ``[n_llm_h, n_llm_w]``.
|
||||
- ``types``: concatenated per-image pad-free span roles
|
||||
(IMAGE_START/IMAGE/IMAGE_NEW_LINE/IMAGE_END); every span position
|
||||
carries ``image_token_id`` in the prompt's token ids.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV41Config) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.image_processor = DeepseekV4VLImageProcessor(config)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
text: str | None = None,
|
||||
images: Sequence[Image.Image] | None = None,
|
||||
return_tensors: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> BatchFeature:
|
||||
patches_list = []
|
||||
vit_grid = []
|
||||
llm_grid_list = []
|
||||
types_list = []
|
||||
for image in images or []:
|
||||
patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w = self.image_processor(image)
|
||||
patches_list.append(patches)
|
||||
vit_grid.append((n_vit_h, n_vit_w))
|
||||
llm_grid_list.append((n_llm_h, n_llm_w))
|
||||
types_list.append(image_token_types(n_llm_h, n_llm_w))
|
||||
|
||||
if not patches_list:
|
||||
return BatchFeature({})
|
||||
|
||||
return BatchFeature(
|
||||
{
|
||||
"patches": torch.cat(patches_list),
|
||||
"vit_grid": torch.tensor(vit_grid, dtype=torch.int64),
|
||||
"llm_grid": torch.tensor(llm_grid_list, dtype=torch.int64),
|
||||
"types": torch.cat(types_list),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4VLProcessingInfo(BaseProcessingInfo):
|
||||
def get_hf_config(self) -> DeepseekV41Config:
|
||||
return self.ctx.get_hf_config(DeepseekV41Config)
|
||||
|
||||
def get_hf_processor(self, **kwargs: object) -> DeepseekV4VLProcessor:
|
||||
if kwargs:
|
||||
raise ValueError(f"Unexpected processor kwargs: {sorted(kwargs)}")
|
||||
return DeepseekV4VLProcessor(self.get_hf_config())
|
||||
|
||||
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
|
||||
return {"image": None}
|
||||
|
||||
def get_mm_max_tokens_per_item(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
) -> Mapping[str, int]:
|
||||
return {"image": self.get_hf_config().vision_max_n_token}
|
||||
|
||||
def get_image_placeholder_token_id(self) -> int:
|
||||
token_id = self.get_tokenizer().convert_tokens_to_ids(IMAGE_PLACEHOLDER)
|
||||
if token_id is None:
|
||||
raise ValueError(f"Token not found in tokenizer: {IMAGE_PLACEHOLDER}")
|
||||
return token_id
|
||||
|
||||
def get_image_size_with_most_features(self) -> ImageSize:
|
||||
hf_config = self.get_hf_config()
|
||||
patch_size = hf_config.vision_patch_size
|
||||
downsample_ratio = hf_config.vision_downsample_ratio
|
||||
# A square maximizes the ViT patch count (area) within the token
|
||||
# budget; solve the budget-derived size directly to keep the dummy
|
||||
# image small.
|
||||
budget = hf_config.vision_max_n_token
|
||||
side = budget * patch_size * downsample_ratio
|
||||
best_h, best_w = solve_resize_ratio(
|
||||
side, side, patch_size, downsample_ratio, budget
|
||||
)
|
||||
return ImageSize(width=best_w, height=best_h)
|
||||
|
||||
|
||||
class DeepseekV4VLDummyInputsBuilder(
|
||||
BaseDummyInputsBuilder[DeepseekV4VLProcessingInfo]
|
||||
):
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return IMAGE_PLACEHOLDER * mm_counts.get("image", 0)
|
||||
|
||||
def get_dummy_mm_data(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
) -> MultiModalDataDict:
|
||||
size = self.info.get_image_size_with_most_features()
|
||||
return {
|
||||
"image": self._get_dummy_images(
|
||||
width=size.width,
|
||||
height=size.height,
|
||||
num_images=mm_counts.get("image", 0),
|
||||
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class DeepseekV4VLMultiModalProcessor(
|
||||
BaseMultiModalProcessor[DeepseekV4VLProcessingInfo]
|
||||
):
|
||||
def _get_mm_fields_config(
|
||||
self,
|
||||
hf_inputs: BatchFeature,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
) -> Mapping[str, MultiModalFieldConfig]:
|
||||
vit_grid = hf_inputs.get("vit_grid")
|
||||
llm_grid = hf_inputs.get("llm_grid")
|
||||
|
||||
if vit_grid is None or llm_grid is None:
|
||||
empty = torch.empty(0, dtype=torch.long)
|
||||
patch_sizes = types_sizes = empty
|
||||
else:
|
||||
patch_sizes = vit_grid.prod(-1)
|
||||
n_llm_h, n_llm_w = llm_grid[:, 0], llm_grid[:, 1]
|
||||
types_sizes = n_llm_h * (n_llm_w + 1) + 2
|
||||
|
||||
return {
|
||||
"patches": MultiModalFieldConfig.flat_from_sizes("image", patch_sizes),
|
||||
"vit_grid": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
|
||||
"llm_grid": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
|
||||
"types": MultiModalFieldConfig.flat_from_sizes(
|
||||
"image", types_sizes, keep_on_cpu=True
|
||||
),
|
||||
}
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
out_mm_kwargs: MultiModalKwargsItems,
|
||||
) -> Sequence[PromptUpdate]:
|
||||
image_token_id = self.info.get_image_placeholder_token_id()
|
||||
validate_image_sentinel_ids(self.info.get_tokenizer())
|
||||
|
||||
def get_image_replacement(item_idx: int) -> PromptUpdateDetails:
|
||||
types: torch.Tensor = out_mm_kwargs["image"][item_idx]["types"].data
|
||||
# Every span position carries image_token_id; the roles live in
|
||||
# ``types``. All of them are embed positions (delimiters get the
|
||||
# learned vectors from embed_multimodal, not the embed table).
|
||||
full = [image_token_id] * types.numel()
|
||||
return PromptUpdateDetails.select_token_id(full, image_token_id)
|
||||
|
||||
return [
|
||||
PromptReplacement(
|
||||
modality="image",
|
||||
target=[image_token_id],
|
||||
replacement=get_image_replacement,
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepSeek V4.1 fused ops.
|
||||
|
||||
Single bridging point for the kernels V4.1 shares verbatim with V4: the
|
||||
re-exports below are the only place this package reaches into
|
||||
``vllm.models.deepseek_v4``, so submodules import them from ``.`` instead of
|
||||
naming the V4 path themselves. Keep these imports above the ``.``-relative
|
||||
ones — ``indexer_k_store`` reads them off this partially-initialized module.
|
||||
"""
|
||||
|
||||
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import (
|
||||
MXFP4_BLOCK_SIZE,
|
||||
fused_indexer_q_rope_quant,
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import (
|
||||
_fp32x2_to_fp4x2 as _fp32x2_to_fp4x2, # re-export for .indexer_k_store
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.ops.fused_inv_rope_fp8_quant import (
|
||||
fused_inv_rope_fp8_quant,
|
||||
)
|
||||
|
||||
from .cache_utils import (
|
||||
build_flashinfer_mixed_sparse_indices,
|
||||
combine_topk_swa_indices,
|
||||
compute_global_topk_indices_and_lens,
|
||||
dequantize_and_gather_k_cache,
|
||||
quantize_and_insert_k_cache,
|
||||
)
|
||||
from .indexer_k_store import indexer_k_norm_rope_store
|
||||
|
||||
__all__ = [
|
||||
"MXFP4_BLOCK_SIZE",
|
||||
"build_flashinfer_mixed_sparse_indices",
|
||||
"combine_topk_swa_indices",
|
||||
"compute_global_topk_indices_and_lens",
|
||||
"dequantize_and_gather_k_cache",
|
||||
"fused_indexer_q_rope_quant",
|
||||
"fused_inv_rope_fp8_quant",
|
||||
"indexer_k_norm_rope_store",
|
||||
"quantize_and_insert_k_cache",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,383 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""V4.1 state saving/compression and independently schedulable cache insertion."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from vllm.platforms.rocm import _ON_GFX950
|
||||
else:
|
||||
_ON_GFX950 = False
|
||||
|
||||
# The ring and raw rows a ratio-2 request program pools are not adjacent, so
|
||||
# reading them as one tile means joining two pointers. ROCm's Triton fails to
|
||||
# legalize `tt.join` on pointers, so there the two rows are loaded separately.
|
||||
_JOIN_ROW_PTRS = not current_platform.is_rocm()
|
||||
|
||||
|
||||
def fused_save_compress_norm(
|
||||
kv_score: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
state_cache: torch.Tensor | None,
|
||||
slot_mapping: torch.Tensor,
|
||||
query_start_loc: torch.Tensor | None,
|
||||
token_to_req_indices: torch.Tensor | None,
|
||||
rms_norm_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
compress_ratio: int,
|
||||
latent_out: torch.Tensor,
|
||||
) -> None:
|
||||
"""Pool each closed group into a normalized BF16 latent; save FP32 states.
|
||||
|
||||
The latent feeds the main-cache insert and the indexer K path, which the
|
||||
attention layer schedules on separate streams.
|
||||
|
||||
Ratio 2 keeps one ring block per request holding the open group's rows:
|
||||
position ``p`` lives in row ``p % capacity`` and ``slot_mapping`` encodes
|
||||
``block * capacity + p % capacity``. The grid has one program per request
|
||||
followed by one per pair of packed tokens. A request program handles the
|
||||
group that the chunk's first token closes with its predecessor's ring row,
|
||||
then stores the chunk's last ``capacity`` rows to the ring; because the
|
||||
same program does both, ring reads and writes never race. A pair program
|
||||
handles the group that ends inside its pair, reading both rows from the
|
||||
raw input. Ratio 1 has no ring and one program per token; ``slot_mapping``
|
||||
then only marks valid tokens.
|
||||
|
||||
Args:
|
||||
kv_score: FP32 [tokens, 512] for CR1, [tokens, 1024] for CR2.
|
||||
positions: Absolute positions of the packed request tokens.
|
||||
state_cache: Ring FP32 [blocks, capacity, 1024] KV/score states (CR2).
|
||||
slot_mapping: Ring slots (CR2) or main-cache slots (CR1).
|
||||
query_start_loc: [num_reqs + 1] token offsets of each request's chunk.
|
||||
token_to_req_indices: Request indices for the packed token rows.
|
||||
rms_norm_weight: BF16 [512] normalization weight.
|
||||
rms_norm_eps: RMSNorm epsilon.
|
||||
compress_ratio: Group size, either 1 or 2.
|
||||
latent_out: BF16 [tokens, 512], written only at valid group boundaries.
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert kv_score.dtype == torch.float32
|
||||
assert kv_score.shape[1] == 512 * compress_ratio and kv_score.stride(1) == 1
|
||||
assert latent_out.shape == (kv_score.shape[0], 512)
|
||||
assert latent_out.is_contiguous() and latent_out.dtype == torch.bfloat16
|
||||
assert positions.is_contiguous() and slot_mapping.is_contiguous()
|
||||
# Rows stay 64-byte aligned, as the kernel's tl.multiple_of hint promises.
|
||||
assert kv_score.stride(0) % 16 == 0
|
||||
if compress_ratio == 2:
|
||||
assert state_cache is not None and query_start_loc is not None
|
||||
assert token_to_req_indices is not None
|
||||
assert query_start_loc.is_contiguous()
|
||||
assert token_to_req_indices.is_contiguous()
|
||||
assert state_cache.dtype == torch.float32
|
||||
assert state_cache.shape[2] == 1024 and state_cache.stride(2) == 1
|
||||
assert state_cache.stride(1) % 16 == 0
|
||||
state_stride, state_row_stride, state_block = (
|
||||
state_cache.stride(0),
|
||||
state_cache.stride(1),
|
||||
state_cache.shape[1],
|
||||
)
|
||||
num_reqs = query_start_loc.numel() - 1
|
||||
else:
|
||||
state_cache = query_start_loc = token_to_req_indices = None
|
||||
state_stride = state_row_stride = state_block = 1
|
||||
num_reqs = 0
|
||||
num_tokens = slot_mapping.numel()
|
||||
assert num_tokens <= min(kv_score.shape[0], positions.numel())
|
||||
if num_tokens == 0:
|
||||
return
|
||||
grid = num_reqs + triton.cdiv(num_tokens, compress_ratio)
|
||||
_fused_save_compress_norm_kernel[(grid,)](
|
||||
kv_score,
|
||||
positions,
|
||||
state_cache,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
token_to_req_indices,
|
||||
rms_norm_weight,
|
||||
latent_out,
|
||||
num_tokens,
|
||||
num_reqs,
|
||||
RAW_STRIDE=kv_score.stride(0),
|
||||
STATE_STRIDE=state_stride,
|
||||
STATE_ROW_STRIDE=state_row_stride,
|
||||
STATE_BLOCK=state_block,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
EPS=rms_norm_eps,
|
||||
JOIN_ROW_PTRS=_JOIN_ROW_PTRS,
|
||||
num_warps=4,
|
||||
**({"launch_pdl": False} if current_platform.is_cuda() else {}),
|
||||
)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_tokens", "num_reqs"])
|
||||
def _fused_save_compress_norm_kernel(
|
||||
raw,
|
||||
positions,
|
||||
state,
|
||||
state_slots,
|
||||
query_start_loc,
|
||||
req_ids,
|
||||
norm_weight,
|
||||
latent,
|
||||
num_tokens,
|
||||
num_reqs,
|
||||
RAW_STRIDE: tl.constexpr,
|
||||
STATE_STRIDE: tl.constexpr,
|
||||
STATE_ROW_STRIDE: tl.constexpr,
|
||||
STATE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
JOIN_ROW_PTRS: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
d = tl.arange(0, 512)
|
||||
|
||||
if COMPRESS_RATIO == 2: # noqa: SIM102 (constexpr branch, then runtime)
|
||||
if pid < num_reqs:
|
||||
# Request program: the group closed by the chunk's first token,
|
||||
# then the ring tail store.
|
||||
start = tl.load(query_start_loc + pid)
|
||||
end = tl.load(query_start_loc + pid + 1)
|
||||
if start >= end:
|
||||
return
|
||||
state_slot = tl.load(state_slots + start)
|
||||
if state_slot < 0:
|
||||
return
|
||||
position = tl.load(positions + start)
|
||||
if (position + 1) % 2 == 0:
|
||||
ring = state + (state_slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE
|
||||
prev = ring + ((position - 1) % STATE_BLOCK) * STATE_ROW_STRIDE
|
||||
current = raw + start.to(tl.int64) * RAW_STRIDE
|
||||
if JOIN_ROW_PTRS:
|
||||
# Joining pointers hides row alignment from Triton; restate it.
|
||||
rows = tl.multiple_of(tl.join(prev, current)[:, None], (16, 16))
|
||||
kv = tl.load(rows + d[None, :])
|
||||
score = tl.load(rows + 512 + d[None, :])
|
||||
# Every lane has read the ring before the tail store below
|
||||
# writes it.
|
||||
tl.debug_barrier()
|
||||
pooled = tl.sum(kv * tl.softmax(score, 0), 0)
|
||||
else:
|
||||
kv_prev = tl.load(prev + d)
|
||||
score_prev = tl.load(prev + 512 + d)
|
||||
kv_current = tl.load(current + d)
|
||||
score_current = tl.load(current + 512 + d)
|
||||
# Every lane has read the ring before the tail store below
|
||||
# writes it.
|
||||
tl.debug_barrier()
|
||||
peak = tl.maximum(score_prev, score_current)
|
||||
weight_prev = tl.exp(score_prev - peak)
|
||||
weight_current = tl.exp(score_current - peak)
|
||||
pooled = (kv_prev * weight_prev + kv_current * weight_current) / (
|
||||
weight_prev + weight_current
|
||||
)
|
||||
_store_latent(pooled, start, norm_weight, latent, EPS)
|
||||
num_rows = tl.minimum(end - start, STATE_BLOCK)
|
||||
for k in tl.range(0, num_rows):
|
||||
token = end - num_rows + k
|
||||
slot = tl.load(state_slots + token)
|
||||
if slot >= 0:
|
||||
row = (
|
||||
state
|
||||
+ (slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE
|
||||
+ (slot % STATE_BLOCK) * STATE_ROW_STRIDE
|
||||
)
|
||||
src = raw + token.to(tl.int64) * RAW_STRIDE
|
||||
tl.store(row + d, tl.load(src + d))
|
||||
tl.store(row + 512 + d, tl.load(src + 512 + d))
|
||||
return
|
||||
|
||||
# Group program: one token (ratio 1) or the token of the pair that ends
|
||||
# a group (ratio 2). A chunk's first token belongs to its request program.
|
||||
t = (pid - num_reqs) * COMPRESS_RATIO
|
||||
if COMPRESS_RATIO == 2:
|
||||
t += (tl.load(positions + t) + 1) % 2
|
||||
state_slot = tl.load(state_slots + t, t < num_tokens, other=-1)
|
||||
if state_slot < 0:
|
||||
return
|
||||
if COMPRESS_RATIO == 1:
|
||||
pooled = tl.load(raw + t.to(tl.int64) * RAW_STRIDE + d)
|
||||
else:
|
||||
if t == tl.load(query_start_loc + tl.load(req_ids + t)):
|
||||
return
|
||||
rows = raw + (t.to(tl.int64) - 1 + tl.arange(0, 2)[:, None]) * RAW_STRIDE
|
||||
kv = tl.load(rows + d[None, :])
|
||||
score = tl.load(rows + 512 + d[None, :])
|
||||
pooled = tl.sum(kv * tl.softmax(score, 0), 0)
|
||||
_store_latent(pooled, t, norm_weight, latent, EPS)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _store_latent(pooled, t, norm_weight, latent, EPS: tl.constexpr):
|
||||
d = tl.arange(0, 512)
|
||||
weight = tl.load(norm_weight + d).to(tl.float32)
|
||||
variance = tl.sum(pooled * pooled, 0) / 512
|
||||
normed = pooled * tl.rsqrt(variance + EPS) * weight
|
||||
tl.store(latent + t.to(tl.int64) * 512 + d, normed.to(tl.bfloat16))
|
||||
|
||||
|
||||
def rope_quant_insert(
|
||||
latent: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
compress_ratio: int,
|
||||
fp8_scale: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Apply GPT-J RoPE and publish a latent to the compressed KV cache.
|
||||
|
||||
The BF16 latent supplies both NoPE quantization and RoPE input. It is read
|
||||
only for valid slots at group boundaries. The cache dtype selects the
|
||||
layout: ``uint8`` is the fp8_ds_mla paged layout (576 value bytes and eight
|
||||
segregated UE8M0 scale bytes per token, including one zero padding scale);
|
||||
``bfloat16`` and ``float8_e4m3fn`` are the plain [448 NoPE | 64 RoPE] rows
|
||||
read by FlashInfer, the latter scaled by the per-tensor ``fp8_scale``.
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert latent.shape[1] == 512 and latent.dtype == torch.bfloat16
|
||||
assert latent.is_contiguous()
|
||||
num_tokens = slot_mapping.numel()
|
||||
assert num_tokens <= min(latent.shape[0], positions.numel())
|
||||
if num_tokens == 0:
|
||||
return
|
||||
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
|
||||
if kv_cache.dtype == torch.uint8:
|
||||
assert kv_cache.shape[-1] == 584
|
||||
_rope_quant_insert_kernel[(num_tokens,)](
|
||||
latent,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
COS_STRIDE=cos_sin_cache.stride(0),
|
||||
CACHE_STRIDE=kv_cache.stride(0),
|
||||
CACHE_BLOCK=kv_cache.shape[1],
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
SANITIZE_CACHE_NANS=_ON_GFX950,
|
||||
num_warps=4,
|
||||
**launch_kwargs,
|
||||
)
|
||||
return
|
||||
|
||||
assert kv_cache.dtype in (torch.bfloat16, torch.float8_e4m3fn)
|
||||
assert kv_cache.shape[-1] == 512 and kv_cache.stride(-1) == 1
|
||||
store_fp8 = kv_cache.dtype == torch.float8_e4m3fn
|
||||
if store_fp8:
|
||||
assert fp8_scale is not None and fp8_scale.numel() == 1
|
||||
assert fp8_scale.dtype == torch.float32
|
||||
_rope_plain_insert_kernel[(num_tokens,)](
|
||||
latent,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
fp8_scale if store_fp8 else None,
|
||||
COS_STRIDE=cos_sin_cache.stride(0),
|
||||
CACHE_STRIDE=kv_cache.stride(0),
|
||||
ROW_STRIDE=kv_cache.stride(1),
|
||||
CACHE_BLOCK=kv_cache.shape[1],
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
STORE_FP8=store_fp8,
|
||||
num_warps=4,
|
||||
**launch_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rope_quant_insert_kernel(
|
||||
latent,
|
||||
positions,
|
||||
cos_sin,
|
||||
cache,
|
||||
cache_slots,
|
||||
COS_STRIDE: tl.constexpr,
|
||||
CACHE_STRIDE: tl.constexpr,
|
||||
CACHE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
SANITIZE_CACHE_NANS: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0)
|
||||
slot = tl.load(cache_slots + t)
|
||||
if slot < 0:
|
||||
return
|
||||
position = tl.load(positions + t)
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
d = tl.arange(0, 512)
|
||||
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
|
||||
page = cache + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
|
||||
values = page + (slot % CACHE_BLOCK) * 576
|
||||
scales = page + CACHE_BLOCK * 576 + (slot % CACHE_BLOCK) * 8
|
||||
|
||||
quant = tl.reshape(normed, (8, 64))
|
||||
amax = tl.maximum(tl.max(tl.abs(quant), 1), 1e-4)
|
||||
exponent = tl.ceil(tl.log2(amax * (1.0 / 448.0)))
|
||||
scaled = quant * tl.reshape(tl.exp2(-exponent), (8, 1))
|
||||
fp8 = tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv)
|
||||
packed = tl.reshape(fp8.to(tl.uint8, bitcast=True), (512,))
|
||||
tl.store(values + d, packed, d < 448)
|
||||
s = tl.arange(0, 8)
|
||||
max_encoded: tl.constexpr = 254.0 if SANITIZE_CACHE_NANS else 255.0
|
||||
encoded = tl.minimum(tl.maximum(exponent + 127.0, 0.0), max_encoded)
|
||||
tl.store(scales + s, encoded.to(tl.uint8), s < 7)
|
||||
tl.store(scales + 7, tl.full((), 0, tl.uint8))
|
||||
|
||||
even, odd = tl.split(tl.reshape(normed, (256, 2)))
|
||||
pair = tl.arange(0, 256) - 224
|
||||
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
|
||||
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
|
||||
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
|
||||
rotated = tl.interleave(even * c - odd * s, odd * c + even * s)
|
||||
if SANITIZE_CACHE_NANS:
|
||||
rotated = tl.where(rotated == rotated, rotated, 0.0)
|
||||
rope_dst = (values + 448).to(tl.pointer_type(tl.bfloat16))
|
||||
tl.store(rope_dst + d - 448, rotated.to(tl.bfloat16), d >= 448)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rope_plain_insert_kernel(
|
||||
latent,
|
||||
positions,
|
||||
cos_sin,
|
||||
cache,
|
||||
cache_slots,
|
||||
fp8_scale,
|
||||
COS_STRIDE: tl.constexpr,
|
||||
CACHE_STRIDE: tl.constexpr,
|
||||
ROW_STRIDE: tl.constexpr,
|
||||
CACHE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
STORE_FP8: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0)
|
||||
slot = tl.load(cache_slots + t)
|
||||
if slot < 0:
|
||||
return
|
||||
position = tl.load(positions + t)
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
d = tl.arange(0, 512)
|
||||
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
|
||||
|
||||
# NoPE pairs load (cos, sin) = (1, 0), so the rotation is the identity there.
|
||||
even, odd = tl.split(tl.reshape(normed, (256, 2)))
|
||||
pair = tl.arange(0, 256) - 224
|
||||
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
|
||||
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
|
||||
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
|
||||
row = tl.interleave(even * c - odd * s, odd * c + even * s).to(tl.bfloat16)
|
||||
|
||||
dst = (
|
||||
cache
|
||||
+ (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
|
||||
+ (slot % CACHE_BLOCK) * ROW_STRIDE
|
||||
)
|
||||
if STORE_FP8:
|
||||
scaled = row.to(tl.float32) * (1.0 / tl.load(fp8_scale))
|
||||
tl.store(dst + d, tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv))
|
||||
else:
|
||||
tl.store(dst + d, row)
|
||||
@@ -0,0 +1,253 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Indexer K production for DeepSeek V4.1 kv-source layers.
|
||||
|
||||
In v4.1 the index key is derived from the *main* compressor's latent:
|
||||
``k = k_norm(wk(latent))`` (reference model.py Indexer.forward), then RoPE'd
|
||||
at the group's first-token position and MXFP4/FP8-quantized into the paged
|
||||
indexer K cache. The ``wk(latent)`` GEMM runs in torch; this kernel fuses the
|
||||
remaining k_norm → RoPE → quant → paged store, one program per token.
|
||||
|
||||
Unlike the legacy (v4.0) indexer path there is no per-token pooling from a
|
||||
compressor state cache: the latent already stands for a whole group, so only
|
||||
group-boundary tokens ``(position + 1) % compress_ratio == 0`` produce a key.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from . import MXFP4_BLOCK_SIZE, _fp32x2_to_fp4x2
|
||||
|
||||
# ROCm tiled ("SHUFFLE") indexer K value layout, mirroring
|
||||
# indexer_k_quant_and_cache_triton's defaults: 16 positions x 16 bytes.
|
||||
_BLOCK_TILE_SIZE = 16
|
||||
_HEAD_TILE_SIZE = 16
|
||||
|
||||
|
||||
def indexer_k_norm_rope_store(
|
||||
k_pre: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
rms_norm_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
k_cache: torch.Tensor,
|
||||
kv_slot_mapping: torch.Tensor,
|
||||
compress_ratio: int,
|
||||
use_fp4_cache: bool,
|
||||
) -> None:
|
||||
"""k_norm → RoPE → quant → paged store for indexer keys.
|
||||
|
||||
Args:
|
||||
k_pre: [num_tokens, 128] bf16, the ``wk(latent)`` projection. Only
|
||||
group-boundary rows are read.
|
||||
positions: [num_tokens] int64 token positions.
|
||||
cos_sin_cache: [max_pos, rope_head_dim] GPT-J layout (cos half, then
|
||||
sin half), from the layer's compress-RoPE instance.
|
||||
rms_norm_weight: [128] k_norm weight.
|
||||
k_cache: uint8 paged indexer cache [num_blocks, block_size, row_bytes].
|
||||
kv_slot_mapping: [num_tokens] slots in the indexer cache (-1 = skip).
|
||||
compress_ratio: group size; keys are emitted at group boundaries.
|
||||
use_fp4_cache: MXFP4 (2 nibbles/byte + ue8m0 per 32) when True, else
|
||||
per-token FP8 with a single fp32 scale.
|
||||
"""
|
||||
num_tokens = kv_slot_mapping.numel()
|
||||
assert k_pre.ndim == 2 and k_pre.shape[1] == 128
|
||||
assert k_pre.dtype == torch.bfloat16 and k_pre.stride(1) == 1
|
||||
assert num_tokens <= k_pre.shape[0] and num_tokens <= positions.numel()
|
||||
assert compress_ratio in (1, 2)
|
||||
if num_tokens == 0:
|
||||
return
|
||||
|
||||
head_dim = k_pre.shape[1]
|
||||
if use_fp4_cache:
|
||||
token_stride = head_dim // 2
|
||||
scale_dim = head_dim // MXFP4_BLOCK_SIZE
|
||||
else:
|
||||
token_stride = head_dim
|
||||
scale_dim = 4 # single float32 scale
|
||||
|
||||
# ROCm reads this cache back with the 16x16-tiled ("SHUFFLE") value
|
||||
# layout: cp_gather_indexer_k_quant_cache_triton on prefill and aiter's
|
||||
# deepgemm_fp8_paged_mqa_logits(Preshuffle=True) on decode both select it
|
||||
# from ``block_size > 1``, matching the v4.0 writer
|
||||
# (indexer_k_quant_and_cache_triton). Writing row-major here would hand
|
||||
# both readers permuted key bytes.
|
||||
block_size = k_cache.shape[1]
|
||||
shuffle = current_platform.is_rocm() and block_size > 1
|
||||
if shuffle:
|
||||
if use_fp4_cache:
|
||||
raise NotImplementedError(
|
||||
"MXFP4 indexer K cache has no tiled ROCm layout; "
|
||||
"the ROCm readers only implement the FP8 one."
|
||||
)
|
||||
if block_size % _BLOCK_TILE_SIZE != 0 or head_dim % _HEAD_TILE_SIZE != 0:
|
||||
raise ValueError(
|
||||
f"ROCm tiled indexer K cache needs block_size "
|
||||
f"({block_size}) % {_BLOCK_TILE_SIZE} == 0 and head_dim "
|
||||
f"({head_dim}) % {_HEAD_TILE_SIZE} == 0."
|
||||
)
|
||||
|
||||
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
|
||||
_indexer_k_norm_rope_quant_store_kernel[(num_tokens,)](
|
||||
k_pre,
|
||||
k_pre.stride(0),
|
||||
positions,
|
||||
rms_norm_weight,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache,
|
||||
cos_sin_cache.stride(0),
|
||||
k_cache,
|
||||
kv_slot_mapping,
|
||||
k_cache.shape[1],
|
||||
HEAD_SIZE=head_dim,
|
||||
ROPE_HEAD_DIM=64,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
TOKEN_STRIDE=token_stride,
|
||||
SCALE_DIM=scale_dim,
|
||||
KV_BLOCK_STRIDE=k_cache.stride(0),
|
||||
FP8_MAX=448.0,
|
||||
USE_FP4=use_fp4_cache,
|
||||
SHUFFLE=shuffle,
|
||||
BLOCK_TILE_SIZE=_BLOCK_TILE_SIZE,
|
||||
HEAD_TILE_SIZE=_HEAD_TILE_SIZE,
|
||||
num_warps=1,
|
||||
**launch_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexer_k_norm_rope_quant_store_kernel(
|
||||
k_pre_ptr,
|
||||
k_pre_stride,
|
||||
positions_ptr,
|
||||
rms_norm_weight_ptr,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache_ptr,
|
||||
cos_sin_stride,
|
||||
k_cache_ptr,
|
||||
kv_slot_mapping_ptr,
|
||||
kv_cache_block_size,
|
||||
HEAD_SIZE: tl.constexpr,
|
||||
ROPE_HEAD_DIM: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
TOKEN_STRIDE: tl.constexpr,
|
||||
SCALE_DIM: tl.constexpr,
|
||||
KV_BLOCK_STRIDE: tl.constexpr,
|
||||
FP8_MAX: tl.constexpr,
|
||||
USE_FP4: tl.constexpr,
|
||||
SHUFFLE: tl.constexpr,
|
||||
BLOCK_TILE_SIZE: tl.constexpr,
|
||||
HEAD_TILE_SIZE: tl.constexpr,
|
||||
):
|
||||
token_idx = tl.program_id(0)
|
||||
|
||||
kv_slot_idx = tl.load(kv_slot_mapping_ptr + token_idx)
|
||||
if kv_slot_idx < 0:
|
||||
return
|
||||
position = tl.load(positions_ptr + token_idx)
|
||||
# Only the last token of a group publishes that group's index key.
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
|
||||
block = tl.arange(0, HEAD_SIZE)
|
||||
|
||||
# ── k_norm (fp32 throughout, bf16 roundtrip like the reference) ────
|
||||
k = tl.load(k_pre_ptr + token_idx * k_pre_stride + block).to(tl.float32)
|
||||
rms_w = tl.load(rms_norm_weight_ptr + block).to(tl.float32)
|
||||
variance = tl.sum(k * k, axis=0) / HEAD_SIZE
|
||||
k = (k * tl.rsqrt(variance + rms_norm_eps) * rms_w).to(tl.bfloat16)
|
||||
k = k.to(tl.float32)
|
||||
|
||||
# ── Register-based GPT-J forward RoPE in fp32 ─────────────────────
|
||||
# A latent stands for the first token of its group, so group j takes
|
||||
# position j * compress_ratio.
|
||||
NUM_PAIRS: tl.constexpr = HEAD_SIZE // 2
|
||||
NOPE_HEAD_DIM: tl.constexpr = HEAD_SIZE - ROPE_HEAD_DIM
|
||||
NOPE_PAIRS: tl.constexpr = NOPE_HEAD_DIM // 2
|
||||
HALF_ROPE: tl.constexpr = ROPE_HEAD_DIM // 2
|
||||
|
||||
even, odd = tl.split(tl.reshape(k, (NUM_PAIRS, 2))) # each [NUM_PAIRS]
|
||||
pair_idx = tl.arange(0, NUM_PAIRS)
|
||||
rope_pair_local = pair_idx - NOPE_PAIRS
|
||||
is_rope_pair = rope_pair_local >= 0
|
||||
cs_idx = tl.maximum(rope_pair_local, 0)
|
||||
|
||||
compressed_pos = (position // COMPRESS_RATIO) * COMPRESS_RATIO
|
||||
cache_base = cos_sin_cache_ptr + compressed_pos * cos_sin_stride
|
||||
cos_v = tl.load(cache_base + cs_idx, mask=is_rope_pair, other=1.0)
|
||||
sin_v = tl.load(cache_base + HALF_ROPE + cs_idx, mask=is_rope_pair, other=0.0)
|
||||
|
||||
new_even = even * cos_v - odd * sin_v
|
||||
new_odd = odd * cos_v + even * sin_v
|
||||
|
||||
# bf16 roundtrip for parity with the reference / Q-side kernel numerics.
|
||||
new_even = new_even.to(tl.bfloat16).to(tl.float32)
|
||||
new_odd = new_odd.to(tl.bfloat16).to(tl.float32)
|
||||
|
||||
# ── Paged cache pointers (segregated: values first, then scales) ──
|
||||
kv_block_idx = kv_slot_idx // kv_cache_block_size
|
||||
kv_pos_in_block = kv_slot_idx % kv_cache_block_size
|
||||
cache_block_ptr = k_cache_ptr + kv_block_idx.to(tl.int64) * KV_BLOCK_STRIDE
|
||||
if SHUFFLE:
|
||||
# [block_size // BT, HEAD_SIZE // HT, BT, HT] value tiles.
|
||||
val_ptr = (
|
||||
cache_block_ptr
|
||||
+ (kv_pos_in_block // BLOCK_TILE_SIZE) * BLOCK_TILE_SIZE * TOKEN_STRIDE
|
||||
+ (kv_pos_in_block % BLOCK_TILE_SIZE) * HEAD_TILE_SIZE
|
||||
)
|
||||
else:
|
||||
val_ptr = cache_block_ptr + kv_pos_in_block * TOKEN_STRIDE
|
||||
scale_ptr = (
|
||||
cache_block_ptr
|
||||
+ kv_cache_block_size * TOKEN_STRIDE
|
||||
+ kv_pos_in_block * SCALE_DIM
|
||||
)
|
||||
|
||||
if USE_FP4:
|
||||
# MXFP4: each 32-element block = 16 consecutive even/odd pairs, so
|
||||
# tiling the halves into (N_BLOCKS, 16) lands one block per row.
|
||||
N_QUANT_BLOCKS: tl.constexpr = HEAD_SIZE // 32
|
||||
HALF_BLOCK: tl.constexpr = 16
|
||||
even_2d = tl.reshape(new_even, (N_QUANT_BLOCKS, HALF_BLOCK))
|
||||
odd_2d = tl.reshape(new_odd, (N_QUANT_BLOCKS, HALF_BLOCK))
|
||||
|
||||
amax = tl.maximum(
|
||||
tl.max(tl.abs(even_2d), axis=1),
|
||||
tl.max(tl.abs(odd_2d), axis=1),
|
||||
)
|
||||
amax = tl.maximum(amax, 6.0 * (2**-126))
|
||||
# ue8m0 block scale: 2^ceil(log2(amax / 6.0)), stored (exp + 127).
|
||||
log2_ratio = tl.ceil(tl.log2(amax * (1.0 / 6.0)))
|
||||
log2_ratio = tl.minimum(tl.maximum(log2_ratio, -127.0), 127.0)
|
||||
inv_scale = tl.exp2(-log2_ratio)
|
||||
ue8m0 = (log2_ratio + 127.0).to(tl.uint8) # [N_QUANT_BLOCKS]
|
||||
|
||||
inv_scale_col = tl.reshape(inv_scale, (N_QUANT_BLOCKS, 1))
|
||||
packed = _fp32x2_to_fp4x2(
|
||||
even_2d * inv_scale_col, odd_2d * inv_scale_col
|
||||
) # (N_BLOCKS, HALF_BLOCK) uint8
|
||||
packed_flat = tl.reshape(packed, (TOKEN_STRIDE,))
|
||||
|
||||
tl.store(val_ptr + tl.arange(0, TOKEN_STRIDE), packed_flat)
|
||||
tl.store(scale_ptr + tl.arange(0, SCALE_DIM), ue8m0)
|
||||
else:
|
||||
# Per-token FP8 (single 128-wide block) with one float32 scale.
|
||||
result = tl.interleave(new_even, new_odd) # [HEAD_SIZE] fp32
|
||||
result_bf16 = result.to(tl.bfloat16).to(tl.float32)
|
||||
INV_FP8_MAX: tl.constexpr = 1.0 / FP8_MAX
|
||||
absmax = tl.maximum(tl.max(tl.abs(result_bf16), axis=0), 1e-4)
|
||||
exponent = tl.ceil(tl.log2(absmax * INV_FP8_MAX))
|
||||
inv_scale = tl.exp2(-exponent)
|
||||
x_clamped = tl.clamp(result_bf16 * inv_scale, -FP8_MAX, FP8_MAX)
|
||||
x_uint8 = x_clamped.to(tl.float8e4nv).to(tl.uint8, bitcast=True)
|
||||
if SHUFFLE:
|
||||
tiled = (
|
||||
block // HEAD_TILE_SIZE * BLOCK_TILE_SIZE * HEAD_TILE_SIZE
|
||||
+ block % HEAD_TILE_SIZE
|
||||
)
|
||||
tl.store(val_ptr + tiled, x_uint8)
|
||||
else:
|
||||
tl.store(val_ptr + block, x_uint8)
|
||||
tl.store(scale_ptr.to(tl.pointer_type(tl.float32)), tl.exp2(exponent))
|
||||
@@ -0,0 +1,142 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _norm_row(x, weight, row, stride, eps, SIZE: tl.constexpr, BLOCK: tl.constexpr):
|
||||
cols = tl.arange(0, BLOCK)
|
||||
w = tl.load(weight + cols, cols < SIZE, 0).to(tl.float32)
|
||||
values = tl.load(x + row * stride + cols, cols < SIZE, 0).to(tl.float32)
|
||||
rrms = tl.rsqrt(tl.sum(values * values, 0) / SIZE + eps)
|
||||
return values * rrms * w
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_tokens"])
|
||||
def _q_kv_norm_quant_kernel(
|
||||
q,
|
||||
kv,
|
||||
qw,
|
||||
kvw,
|
||||
qo,
|
||||
kvo,
|
||||
scales,
|
||||
num_tokens,
|
||||
q_stride,
|
||||
kv_stride,
|
||||
eps,
|
||||
Q_SIZE: tl.constexpr,
|
||||
KV_SIZE: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
LAUNCH_PDL: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
cols = tl.arange(0, BLOCK)
|
||||
if LAUNCH_PDL:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
if tl.program_id(1) == 0:
|
||||
groups = tl.arange(0, BLOCK // 32)
|
||||
if row < num_tokens:
|
||||
y = _norm_row(q, qw, row, q_stride, eps, Q_SIZE, BLOCK)
|
||||
# Preserve the materialized normalization output's rounding boundary.
|
||||
y = y.to(q.dtype.element_ty).to(tl.float32)
|
||||
grouped = tl.reshape(y, (BLOCK // 32, 32))
|
||||
amax = tl.max(tl.abs(grouped), 1)
|
||||
normalized = amax * (1.0 / 448.0)
|
||||
bits = normalized.to(tl.uint32, bitcast=True)
|
||||
exponent = (bits >> 23) & 255
|
||||
mantissa = bits & 0x7FFFFF
|
||||
bump = (mantissa != 0) & ~((exponent == 0) & (mantissa <= 0x400000))
|
||||
sf = tl.minimum(exponent + bump, 254)
|
||||
sf = tl.where(normalized <= 0, 0, sf)
|
||||
# Match FlashInfer's UE8M0 conversion, including zero/subnormal scales.
|
||||
inv_bits = tl.where(sf == 0, 0, (254 - sf) << 23)
|
||||
inv_scale = inv_bits.to(tl.float32, bitcast=True)
|
||||
quantized = tl.reshape(grouped * inv_scale[:, None], (BLOCK,))
|
||||
tl.store(qo + row * Q_SIZE + cols, quantized, cols < Q_SIZE)
|
||||
else:
|
||||
sf = tl.full((BLOCK // 32,), 0, tl.uint32)
|
||||
padded_groups: tl.constexpr = triton.cdiv(Q_SIZE // 32, 4) * 4
|
||||
sf = tl.where(groups < Q_SIZE // 32, sf, 0)
|
||||
# F8_128x4: [row/128, group/4, row%32, row%128/32, group%4].
|
||||
offsets = (
|
||||
row // 128 * (128 * padded_groups)
|
||||
+ groups // 4 * 512
|
||||
+ row % 32 * 16
|
||||
+ row % 128 // 32 * 4
|
||||
+ groups % 4
|
||||
)
|
||||
tl.store(scales + offsets, sf, groups < padded_groups)
|
||||
elif row < num_tokens:
|
||||
y = _norm_row(kv, kvw, row, kv_stride, eps, KV_SIZE, BLOCK)
|
||||
tl.store(kvo + row * KV_SIZE + cols, y, cols < KV_SIZE)
|
||||
|
||||
|
||||
def fused_q_kv_rmsnorm_quant(
|
||||
qr: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
kv_weight: torch.Tensor,
|
||||
eps: float,
|
||||
) -> tuple[QuantizedActivation, torch.Tensor]:
|
||||
"""Normalize Q/KV and quantize Q with FlashInfer's swizzled MXFP8 scales."""
|
||||
assert qr.ndim == kv.ndim == 2 and qr.shape[0] == kv.shape[0]
|
||||
assert qr.stride(-1) == kv.stride(-1) == 1
|
||||
assert q_weight.is_contiguous() and kv_weight.is_contiguous()
|
||||
assert qr.shape[1] % 32 == 0
|
||||
tokens, q_size = qr.shape
|
||||
kv_size = kv.shape[1]
|
||||
qo = torch.empty(qr.shape, dtype=torch.float8_e4m3fn, device=qr.device)
|
||||
kvo = torch.empty(kv.shape, dtype=kv.dtype, device=kv.device)
|
||||
padded_tokens = triton.cdiv(tokens, 128) * 128
|
||||
padded_groups = triton.cdiv(q_size // 32, 4) * 4
|
||||
scales = torch.empty(
|
||||
padded_tokens * padded_groups, dtype=torch.uint8, device=qr.device
|
||||
)
|
||||
if tokens:
|
||||
block = triton.next_power_of_2(max(q_size, kv_size))
|
||||
_q_kv_norm_quant_kernel[(padded_tokens, 2)](
|
||||
qr,
|
||||
kv,
|
||||
q_weight,
|
||||
kv_weight,
|
||||
qo,
|
||||
kvo,
|
||||
scales,
|
||||
tokens,
|
||||
qr.stride(0),
|
||||
kv.stride(0),
|
||||
eps,
|
||||
q_size,
|
||||
kv_size,
|
||||
block,
|
||||
current_platform.is_arch_support_pdl(),
|
||||
num_warps=8 if block >= 2048 else 4,
|
||||
)
|
||||
return QuantizedActivation(qo, scales, qr.dtype, qr.shape, kMxfp8Dynamic), kvo
|
||||
|
||||
|
||||
def can_fuse_query_quant(linears: list[torch.nn.Module]) -> bool:
|
||||
"""Require both local projections to use the same MXFP8 activation ABI."""
|
||||
if not current_platform.is_cuda():
|
||||
return False
|
||||
from vllm.model_executor.kernels.linear.mxfp8.flashinfer import (
|
||||
FlashInferCutedslMxfp8LinearKernel,
|
||||
FlashInferCutlassMxfp8LinearKernel,
|
||||
)
|
||||
|
||||
# QuantKey does not encode scale layout; restrict this producer to the
|
||||
# consumers that accept F8_128x4 swizzled scales.
|
||||
return all(
|
||||
getattr(linear, "input_quant_key", None) == kMxfp8Dynamic
|
||||
and type(getattr(getattr(linear, "quant_method", None), "kernel", None))
|
||||
in (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel)
|
||||
for linear in linears
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepseekV4 rotary embedding initialization."""
|
||||
|
||||
from vllm.model_executor.layers.rotary_embedding import get_rope
|
||||
from vllm.model_executor.layers.rotary_embedding.base import RotaryEmbedding
|
||||
|
||||
|
||||
def build_deepseek_v4_rope(
|
||||
config,
|
||||
*,
|
||||
head_dim: int,
|
||||
rope_head_dim: int,
|
||||
max_position_embeddings: int,
|
||||
compress_ratio: int,
|
||||
) -> RotaryEmbedding:
|
||||
rope_parameters = config.rope_parameters
|
||||
# Newer checkpoints nest per-layer-type rope dicts ({"main", "compress"});
|
||||
# older ones ship a single flat dict shared by all layer types.
|
||||
if isinstance(rope_parameters.get("main"), dict) and isinstance(
|
||||
rope_parameters.get("compress"), dict
|
||||
):
|
||||
key = "compress" if compress_ratio > 0 else "main"
|
||||
rope_parameters = dict(rope_parameters[key])
|
||||
else:
|
||||
rope_parameters = dict(rope_parameters)
|
||||
|
||||
rope_parameters["rope_theta"] = (
|
||||
config.compress_rope_theta if compress_ratio > 0 else config.rope_theta
|
||||
)
|
||||
if compress_ratio > 0 and rope_parameters["rope_type"] != "default":
|
||||
# YaRN applies to all compressed-KV layers (compress_ratio > 0); only
|
||||
# pure sliding-window layers (compress_ratio == 0) use plain RoPE.
|
||||
rope_parameters["rope_type"] = (
|
||||
"deepseek_yarn"
|
||||
if rope_parameters.get("apply_yarn_scaling", True)
|
||||
else "deepseek_llama_scaling"
|
||||
)
|
||||
else:
|
||||
# Sliding-window layers use plain RoPE (theta=rope_theta, no YaRN).
|
||||
rope_parameters["rope_type"] = "deepseek_yarn"
|
||||
rope_parameters["factor"] = 1.0
|
||||
rope_parameters["original_max_position_embeddings"] = max_position_embeddings
|
||||
rope_parameters["mscale"] = 0 # Disable mscale
|
||||
rope_parameters["mscale_all_dim"] = 0 # Disable mscale
|
||||
rope_parameters["is_deepseek_v4"] = True
|
||||
rope_parameters["rope_dim"] = rope_head_dim
|
||||
return get_rope(
|
||||
head_dim,
|
||||
max_position=max_position_embeddings,
|
||||
rope_parameters=rope_parameters,
|
||||
is_neox_style=False,
|
||||
)
|
||||
@@ -0,0 +1,323 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
|
||||
from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
|
||||
fused_save_compress_norm,
|
||||
rope_quant_insert,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionMetadataBuilder,
|
||||
CommonAttentionMetadata,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import CircularBufferSpec, KVCacheSpec
|
||||
|
||||
|
||||
class CompressorBackend(AttentionBackend):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "CompressorBackend"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [MultipleOf(1)]
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
return [512, 1024]
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["CompressorMetadataBuilder"]:
|
||||
return CompressorMetadataBuilder
|
||||
|
||||
|
||||
@dataclass
|
||||
class CompressorMetadata:
|
||||
# [num_tokens] ring slot of every token: block * capacity + pos % capacity.
|
||||
slot_mapping: torch.Tensor
|
||||
query_start_loc: torch.Tensor # [num_reqs + 1]
|
||||
token_to_req_indices: torch.Tensor # [num_tokens]
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _ring_slot_mapping_kernel(
|
||||
slot_mapping_ptr,
|
||||
block_table_ptr,
|
||||
block_table_stride,
|
||||
token_to_req_ptr,
|
||||
positions_ptr,
|
||||
num_actual_tokens,
|
||||
num_tokens,
|
||||
CAPACITY: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
offsets = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
|
||||
valid = offsets < num_actual_tokens
|
||||
req = tl.load(token_to_req_ptr + offsets, mask=valid, other=0).to(tl.int64)
|
||||
block = tl.load(block_table_ptr + req * block_table_stride, mask=valid, other=0)
|
||||
pos = tl.load(positions_ptr + offsets, mask=valid, other=0)
|
||||
slot = block.to(tl.int64) * CAPACITY + pos % CAPACITY
|
||||
tl.store(
|
||||
slot_mapping_ptr + offsets, tl.where(valid, slot, -1), mask=offsets < num_tokens
|
||||
)
|
||||
|
||||
|
||||
class CompressorMetadataBuilder(AttentionMetadataBuilder):
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
assert isinstance(self.kv_cache_spec, CircularBufferSpec)
|
||||
self.capacity = self.kv_cache_spec.block_size
|
||||
max_num_batched_tokens = (
|
||||
self.vllm_config.scheduler_config.max_num_batched_tokens
|
||||
)
|
||||
self.token_to_req_indices = torch.zeros(
|
||||
max_num_batched_tokens, dtype=torch.int32, device=self.device
|
||||
)
|
||||
self.slot_mapping_buffer = torch.empty(
|
||||
max_num_batched_tokens, dtype=torch.int64, device=self.device
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> CompressorMetadata:
|
||||
num_tokens = common_attn_metadata.slot_mapping.numel()
|
||||
positions = common_attn_metadata.positions
|
||||
assert positions is not None
|
||||
token_to_req_indices = common_attn_metadata.token_to_req_indices(
|
||||
self.token_to_req_indices
|
||||
)
|
||||
slot_mapping = self.slot_mapping_buffer[:num_tokens]
|
||||
block_table = common_attn_metadata.block_table_tensor
|
||||
_ring_slot_mapping_kernel[(triton.cdiv(num_tokens, 256),)](
|
||||
slot_mapping,
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
token_to_req_indices,
|
||||
positions,
|
||||
common_attn_metadata.num_actual_tokens,
|
||||
num_tokens,
|
||||
CAPACITY=self.capacity,
|
||||
BLOCK=256,
|
||||
)
|
||||
return CompressorMetadata(
|
||||
slot_mapping=slot_mapping,
|
||||
query_start_loc=common_attn_metadata.query_start_loc,
|
||||
token_to_req_indices=token_to_req_indices,
|
||||
)
|
||||
|
||||
|
||||
class CompressorStateCache(torch.nn.Module, AttentionLayerBase):
|
||||
"""Per-request ring of the open group's [kv, score] rows (ratio > 1)."""
|
||||
|
||||
def __init__(self, state_dim: int, dtype: torch.dtype, prefix: str):
|
||||
super().__init__()
|
||||
self.state_dim = state_dim
|
||||
self.dtype = dtype
|
||||
self.prefix = prefix
|
||||
self.kv_cache = torch.tensor([])
|
||||
compilation_config = get_current_vllm_config().compilation_config
|
||||
if prefix in compilation_config.static_forward_context:
|
||||
raise ValueError(f"Duplicate layer name: {prefix}")
|
||||
compilation_config.static_forward_context[prefix] = self
|
||||
|
||||
assert self.dtype == torch.float32
|
||||
# Drafts + bonus token + the previous row, as a power of two >= 8.
|
||||
rows_per_step = get_current_vllm_config().num_speculative_tokens + 2
|
||||
self.block_size = max(8, 1 << (rows_per_step - 1).bit_length())
|
||||
|
||||
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
|
||||
# [B, H=1, N, C] -> [B, N, C]
|
||||
self.kv_cache = kv_cache.squeeze(1)
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
del vllm_config
|
||||
return CircularBufferSpec(
|
||||
block_size=self.block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=self.state_dim,
|
||||
head_size_v=0,
|
||||
dtype=self.dtype,
|
||||
)
|
||||
|
||||
def forward(self): ...
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return CompressorBackend
|
||||
|
||||
|
||||
class DeepseekCompressor(nn.Module):
|
||||
"""DeepSeek V4.1 KV/score compressor.
|
||||
|
||||
Pools ``compress_ratio`` consecutive tokens into one KV latent with a
|
||||
learned softmax gate (ratio 1 has no gate and no pooling). Owns the
|
||||
linear, norm and state cache. State saving, compression and RMSNorm share
|
||||
one Triton kernel. The emitted latent feeds independent main-cache and
|
||||
indexer K kernels, which the attention layer can schedule concurrently.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
compress_ratio: int,
|
||||
hidden_size: int,
|
||||
head_dim: int,
|
||||
rotate: bool = False,
|
||||
prefix: str = "",
|
||||
k_cache_prefix="",
|
||||
):
|
||||
super().__init__()
|
||||
if compress_ratio not in (1, 2):
|
||||
raise NotImplementedError(
|
||||
"DeepSeek V4.1 compressor supports compress_ratio 1 (full-length "
|
||||
f"compressed cache) and 2; got {compress_ratio}. The ratio-4/128 "
|
||||
"CuTe-DSL kernels are v4.0-specific and not wired here."
|
||||
)
|
||||
self.compress_ratio = compress_ratio
|
||||
self.hidden_size = hidden_size
|
||||
self.head_dim = head_dim
|
||||
self.rotate = rotate
|
||||
self.prefix = prefix
|
||||
self.k_cache_prefix = k_cache_prefix
|
||||
# Ratio 1 pools single tokens, so the checkpoint carries no gate.
|
||||
self.has_gate = compress_ratio > 1
|
||||
|
||||
config = vllm_config.model_config.hf_config
|
||||
self.rope_head_dim = config.qk_rope_head_dim
|
||||
self.nope_head_dim = self.head_dim - self.rope_head_dim
|
||||
assert self.head_dim == 512 and self.rope_head_dim == 64
|
||||
self.rms_norm_eps = config.rms_norm_eps
|
||||
self.device = current_platform.device_type
|
||||
self.max_num_reqs = vllm_config.scheduler_config.max_num_seqs
|
||||
self.max_model_len = vllm_config.model_config.max_model_len
|
||||
|
||||
wkv_wgate_sizes = (
|
||||
[self.head_dim, self.head_dim] if self.has_gate else [self.head_dim]
|
||||
)
|
||||
self.fused_wkv_wgate = MergedColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
wkv_wgate_sizes,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=None,
|
||||
disable_tp=True,
|
||||
prefix=f"{prefix}.fused_wkv_wgate",
|
||||
)
|
||||
self.norm = RMSNorm(self.head_dim, self.rms_norm_eps)
|
||||
|
||||
self.state_cache = (
|
||||
CompressorStateCache(
|
||||
state_dim=2 * self.head_dim, # kv_state + score_state
|
||||
dtype=torch.float32,
|
||||
prefix=f"{prefix}.state_cache",
|
||||
)
|
||||
if compress_ratio > 1
|
||||
else None
|
||||
)
|
||||
|
||||
# Save reference to static_forward_context for forward-time KV cache lookup.
|
||||
# get_current_vllm_config() is only available during __init__, not forward.
|
||||
self._static_forward_context = (
|
||||
vllm_config.compilation_config.static_forward_context
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
# [num_tokens, (2 if has_gate else 1) * self.head_dim]
|
||||
kv_score: torch.Tensor,
|
||||
# [num_tokens]
|
||||
positions: torch.Tensor,
|
||||
) -> torch.Tensor | None:
|
||||
"""Save states and return the BF16 latent for cache insertion and indexing.
|
||||
|
||||
Only valid group-boundary rows are written.
|
||||
"""
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
if not isinstance(attn_metadata, dict):
|
||||
return None
|
||||
|
||||
if self.state_cache is None:
|
||||
state_cache = query_start_loc = token_to_req_indices = None
|
||||
slot_mapping = cast(Any, attn_metadata[self.k_cache_prefix]).slot_mapping
|
||||
else:
|
||||
state_metadata = cast(
|
||||
CompressorMetadata, attn_metadata[self.state_cache.prefix]
|
||||
)
|
||||
state_cache = self.state_cache.kv_cache
|
||||
slot_mapping = state_metadata.slot_mapping
|
||||
query_start_loc = state_metadata.query_start_loc
|
||||
token_to_req_indices = state_metadata.token_to_req_indices
|
||||
|
||||
latent = torch.empty(
|
||||
kv_score.shape[0],
|
||||
self.head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
device=kv_score.device,
|
||||
)
|
||||
fused_save_compress_norm(
|
||||
kv_score,
|
||||
positions,
|
||||
state_cache,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
token_to_req_indices,
|
||||
self.norm.weight,
|
||||
self.rms_norm_eps,
|
||||
self.compress_ratio,
|
||||
latent,
|
||||
)
|
||||
return latent
|
||||
|
||||
def insert_cache(
|
||||
self,
|
||||
latent: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
rotary_emb,
|
||||
) -> None:
|
||||
"""Publish compressed main-cache rows after the latent becomes ready."""
|
||||
if latent is None:
|
||||
return
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
assert isinstance(attn_metadata, dict)
|
||||
k_cache_metadata = cast(Any, attn_metadata[self.k_cache_prefix])
|
||||
k_cache_layer = self._static_forward_context[self.k_cache_prefix]
|
||||
kv_cache = k_cache_layer.kv_cache
|
||||
# Plain-row per-tensor fp8 caches (FlashInfer) carry the layer's scale;
|
||||
# fp8_ds_mla and bf16 rows need none.
|
||||
fp8_scale = (
|
||||
getattr(k_cache_layer, "_flashinfer_fp8_kv_scale", None)
|
||||
if kv_cache.dtype == torch.float8_e4m3fn
|
||||
else None
|
||||
)
|
||||
|
||||
rope_quant_insert(
|
||||
latent,
|
||||
positions,
|
||||
rotary_emb.cos_sin_cache,
|
||||
kv_cache,
|
||||
k_cache_metadata.slot_mapping,
|
||||
self.compress_ratio,
|
||||
fp8_scale=fp8_scale,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,558 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DSpark draft model for DeepSeek-V4.1 (semi-autoregressive speculative decoding).
|
||||
|
||||
See: qwen3_dspark.py for base architecture. This one is specialized to the
|
||||
DSV4.1 DSpark, which reuses the target model's architecture similarly to MTP.
|
||||
Its weights ship in the target checkpoint under the ``mtp.{0,1,2}.*`` prefix.
|
||||
|
||||
To implement non-causal attention, we leverage the sparse attention implementation to
|
||||
include the future query tokens in the top-k indices for each query token.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
from vllm.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.kernels.mhc.tilelang import (
|
||||
mhc_post_tilelang,
|
||||
)
|
||||
from vllm.model_executor.kernels.mhc.triton import hc_collapse_triton
|
||||
from vllm.model_executor.layers.fused_moe import (
|
||||
fused_moe_make_expert_params_mapping,
|
||||
)
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.qwen3_dspark import (
|
||||
DSparkConfidenceHead,
|
||||
DSparkMarkovHead,
|
||||
)
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
from vllm.models.common.ops.sequence_parallel import (
|
||||
sp_all_gather,
|
||||
sp_padding_mask,
|
||||
sp_shard,
|
||||
)
|
||||
|
||||
from .model import (
|
||||
DeepseekV4DecoderLayer,
|
||||
DeepseekV4Model,
|
||||
_linear_scale_param_name,
|
||||
_use_sequence_parallel,
|
||||
make_deepseek_v4_expert_params_mapping,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# MoE expert scale suffix differs by expert dtype (mirrors deepseek_v4 loaders):
|
||||
# fp4 experts register ``.weight_scale``; block-fp8 experts ``.weight_scale_inv``.
|
||||
_EXPERT_SCALE_RE = re.compile(r"\.experts\.\d+\.w[123]\.scale$")
|
||||
|
||||
|
||||
class DSparkDeepseekV4Model(nn.Module):
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
assert vllm_config.speculative_config is not None
|
||||
config = vllm_config.speculative_config.draft_model_config.hf_config
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.hc_mult = config.hc_mult
|
||||
self.hc_eps = config.hc_eps
|
||||
self.rms_norm_eps = config.rms_norm_eps
|
||||
self.num_hidden_layers = config.num_hidden_layers
|
||||
self.target_layer_ids = tuple(config.dspark_target_layer_ids)
|
||||
self.use_sequence_parallel = _use_sequence_parallel(vllm_config)
|
||||
|
||||
self.num_dspark_layers = (
|
||||
getattr(config, "n_mtp_layers", None)
|
||||
or getattr(config, "num_nextn_predict_layers", None)
|
||||
or 3
|
||||
)
|
||||
|
||||
# Shared with the target (aliased by the speculator's loading utility).
|
||||
self.embed_tokens = VocabParallelEmbedding(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
prefix=maybe_prefix(prefix, "embed_tokens"),
|
||||
)
|
||||
|
||||
self.main_proj = ReplicatedLinear(
|
||||
config.hidden_size * len(self.target_layer_ids),
|
||||
config.hidden_size,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=vllm_config.quant_config,
|
||||
prefix=maybe_prefix(prefix, "main_proj"),
|
||||
)
|
||||
self.main_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
self.topk_indices_buffer = torch.empty(
|
||||
vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
config.index_topk,
|
||||
dtype=torch.int32,
|
||||
)
|
||||
|
||||
current_vllm_config = get_current_vllm_config()
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
DeepseekV4DecoderLayer(
|
||||
current_vllm_config,
|
||||
prefix=maybe_prefix(prefix, f"layers.{self.num_hidden_layers + i}"),
|
||||
topk_indices_buffer=self.topk_indices_buffer,
|
||||
)
|
||||
for i in range(self.num_dspark_layers)
|
||||
]
|
||||
)
|
||||
|
||||
# Heads: final norm, and the Markov + confidence heads.
|
||||
# Loaded from the "final" MTP layer weights (mtp.*) in the target
|
||||
# checkpoint. v4.1 has no learned hc_head: the hc copies are
|
||||
# collapsed with a pre-mix derived from the last layer's hc_ffn
|
||||
# projection at the end of forward().
|
||||
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
draft_vocab_size = (
|
||||
getattr(config, "draft_vocab_size", None) or config.vocab_size
|
||||
)
|
||||
self.markov_head = DSparkMarkovHead(
|
||||
config.vocab_size,
|
||||
draft_vocab_size,
|
||||
config.dspark_markov_rank,
|
||||
prefix=maybe_prefix(prefix, "markov_head"),
|
||||
)
|
||||
self.confidence_head: DSparkConfidenceHead | None = None
|
||||
if getattr(config, "enable_confidence_head", True):
|
||||
self.confidence_head = DSparkConfidenceHead(
|
||||
config.hidden_size + config.dspark_markov_rank,
|
||||
prefix=maybe_prefix(prefix, "confidence_head"),
|
||||
)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def combine_hidden_states(self, aux_hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
"""main_x = main_norm(main_proj(concat of target aux hidden states)).
|
||||
|
||||
``aux_hidden_states`` is [T, hidden_size * len(target_layer_ids)].
|
||||
"""
|
||||
return self.main_norm(self.main_proj(aux_hidden_states))
|
||||
|
||||
@torch.inference_mode()
|
||||
def precompute_and_store_context_kv(
|
||||
self,
|
||||
main_x: torch.Tensor,
|
||||
context_positions: torch.Tensor,
|
||||
context_slot_mappings: list[torch.Tensor | None] | None = None,
|
||||
) -> None:
|
||||
"""Insert the sliding-window context KV for every draft layer.
|
||||
|
||||
Mirrors the reference DSparkAttention: each layer derives its context KV
|
||||
from the SAME projected target hidden ``main_x``, via that layer's own
|
||||
``wkv`` + ``kv_norm`` + RoPE + quant, then writes it at the
|
||||
layer's context slots.
|
||||
|
||||
``context_slot_mappings`` is a per-layer list (each entry is the context
|
||||
slot mapping for that layer's kv-cache group, since the hybrid manager may
|
||||
place draft layers in different groups). ``None`` (or a ``None`` entry)
|
||||
runs the projection to reserve workspace but writes nothing (profiling).
|
||||
"""
|
||||
for i, layer in enumerate(self.layers):
|
||||
slot_mapping = (
|
||||
None if context_slot_mappings is None else context_slot_mappings[i]
|
||||
)
|
||||
attn = layer.attn
|
||||
# Optimized DSV4 MLA path: wkv part of the fused wq_a|wkv projection
|
||||
# (q_lora part discarded), then RoPE/quant/insert via the fused op.
|
||||
qr_kv, _ = attn.fused_wqa_wkv(main_x)
|
||||
kv = qr_kv[..., attn.q_lora_rank :]
|
||||
kv = attn.kv_norm(kv)
|
||||
if slot_mapping is None:
|
||||
continue
|
||||
_insert_context_kv(attn, kv, context_positions, slot_mapping)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_input_ids(input_ids)
|
||||
full_num_tokens = positions.shape[0]
|
||||
if self.use_sequence_parallel:
|
||||
if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available():
|
||||
forward_context = get_forward_context()
|
||||
forward_context.is_padding = sp_padding_mask(
|
||||
forward_context.is_padding, inputs_embeds
|
||||
)
|
||||
inputs_embeds = sp_shard(inputs_embeds)
|
||||
input_ids = sp_shard(input_ids)
|
||||
# Expand to hc_mult copies for hyper-connections ([T, H] -> [T, hc, H]).
|
||||
hidden_states = inputs_embeds.unsqueeze(-2).repeat(1, self.hc_mult, 1)
|
||||
|
||||
residual = post_mix = res_mix = pre_mix = None
|
||||
for layer in self.layers:
|
||||
hidden_states, residual, post_mix, res_mix, pre_mix = layer(
|
||||
hidden_states,
|
||||
positions,
|
||||
input_ids,
|
||||
pre_mix,
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
)
|
||||
hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix)
|
||||
if self.use_sequence_parallel:
|
||||
hidden_states = sp_all_gather(hidden_states)[:full_num_tokens]
|
||||
pre_mix = sp_all_gather(pre_mix)[:full_num_tokens]
|
||||
# Collapse the hc copies with the pre-mix from the last layer's FFN
|
||||
# mixes — the mix the reference forward_head applies (hc_pre with the
|
||||
# last block's ffn pre-mix). Return the PRE-norm head hidden;
|
||||
# compute_logits applies self.norm.
|
||||
assert pre_mix is not None
|
||||
hidden_states = hc_collapse_triton(hidden_states, pre_mix)
|
||||
return hidden_states
|
||||
|
||||
|
||||
def _insert_context_kv(
|
||||
attn: nn.Module,
|
||||
kv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
) -> None:
|
||||
"""RoPE + quant + paged-cache insert of (already kv_norm'd) context KV.
|
||||
|
||||
Reuses the DSV4 fused insert ops (which also process a query; we pass a dummy
|
||||
query and discard it, since context tokens have no query). Mirrors
|
||||
``DeepseekV4Attention._fused_qnorm_rope_kv_insert``.
|
||||
"""
|
||||
swa_cache = attn.swa_cache_layer.kv_cache
|
||||
block_size = attn.swa_cache_layer.block_size
|
||||
cos_sin_cache = attn.rotary_emb.cos_sin_cache
|
||||
cache_dtype = swa_cache.dtype
|
||||
n_ctx = kv.shape[0]
|
||||
dummy_q = torch.zeros(
|
||||
(n_ctx, attn.n_local_heads, attn.head_dim),
|
||||
dtype=kv.dtype,
|
||||
device=kv.device,
|
||||
)
|
||||
if cache_dtype == torch.uint8:
|
||||
# fp8_ds_mla UE8M0 paged layout
|
||||
swa_2d = swa_cache.view(swa_cache.shape[0], -1)
|
||||
torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
|
||||
dummy_q,
|
||||
kv,
|
||||
swa_2d,
|
||||
slot_mapping,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
attn.padded_heads,
|
||||
attn.eps,
|
||||
block_size,
|
||||
)
|
||||
elif cache_dtype == torch.bfloat16:
|
||||
swa_3d = swa_cache.view(-1, block_size, attn.head_dim)
|
||||
torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert(
|
||||
dummy_q,
|
||||
kv,
|
||||
swa_3d,
|
||||
slot_mapping,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
attn.eps,
|
||||
block_size,
|
||||
)
|
||||
else: # per-tensor fp8 (torch.float8_e4m3fn)
|
||||
# TODO(ben): double-check if this is being dispatched correctly for FI backend
|
||||
swa_3d = swa_cache.view(-1, block_size, attn.head_dim)
|
||||
dummy_q_fp8 = torch.zeros_like(dummy_q, dtype=torch.float8_e4m3fn)
|
||||
torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_fp8_insert(
|
||||
dummy_q,
|
||||
kv,
|
||||
dummy_q_fp8,
|
||||
swa_3d,
|
||||
slot_mapping,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
attn._flashinfer_fp8_kv_scale,
|
||||
attn._flashinfer_fp8_q_scale_inv,
|
||||
attn.eps,
|
||||
block_size,
|
||||
)
|
||||
|
||||
|
||||
class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
# Draft weights ship in the target checkpoint (mtp.*) without embed/head, so
|
||||
# load_dspark_model always aliases the target's.
|
||||
has_own_embed_tokens = False
|
||||
has_own_lm_head = False
|
||||
# Full-vocab draft: draft ids are target ids, no remapping needed.
|
||||
draft_id_to_target_id = None
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
assert vllm_config.speculative_config is not None
|
||||
self.draft_model_config = vllm_config.speculative_config.draft_model_config
|
||||
self.config = self.draft_model_config.hf_config
|
||||
self.quant_config = vllm_config.quant_config
|
||||
self.linear_scale_name = _linear_scale_param_name(
|
||||
vllm_config, getattr(self.config, "expert_dtype", "fp4")
|
||||
)
|
||||
self.pad_shared_expert = getattr(
|
||||
self.quant_config, "weight_block_size", None
|
||||
) is not None and not _use_sequence_parallel(vllm_config)
|
||||
self.model = DSparkDeepseekV4Model(
|
||||
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
|
||||
)
|
||||
# Shared with the target (aliased by the speculator's load utility).
|
||||
self.lm_head = ParallelLMHead(
|
||||
self.config.vocab_size,
|
||||
self.config.hidden_size,
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
self.logits_processor = LogitsProcessor(self.config.vocab_size)
|
||||
|
||||
# --- Hooks used by the speculator -------------------------------------
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.embed_input_ids(input_ids)
|
||||
|
||||
def combine_hidden_states(self, aux_hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.combine_hidden_states(aux_hidden_states)
|
||||
|
||||
def get_draft_kv_cache_layer_names(self) -> list[str]:
|
||||
# DSV4 MLA path: each draft layer's sliding-window cache is a separate
|
||||
# layer, named by its prefix.
|
||||
return [layer.attn.swa_cache_layer.prefix for layer in self.model.layers]
|
||||
|
||||
def precompute_and_store_context_kv(
|
||||
self,
|
||||
context_states: torch.Tensor,
|
||||
context_positions: torch.Tensor,
|
||||
context_slot_mappings: list[torch.Tensor | None] | None = None,
|
||||
) -> None:
|
||||
self.model.precompute_and_store_context_kv(
|
||||
context_states, context_positions, context_slot_mappings
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Returns the pre-norm collapsed head hidden ([T, hidden_size]).
|
||||
return self.model(input_ids, positions, inputs_embeds)
|
||||
|
||||
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
"""Base logits U_k = lm_head(norm(head_hidden))."""
|
||||
return self.logits_processor(self.lm_head, self.model.norm(hidden_states))
|
||||
|
||||
def compute_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
# Full-vocab draft: base logits, no d2t scatter.
|
||||
return self.compute_logits(hidden_states)
|
||||
|
||||
def map_draft_to_target(self, draft_ids: torch.Tensor) -> torch.Tensor:
|
||||
return draft_ids # full-vocab: draft ids are target ids
|
||||
|
||||
def markov_embed(self, token_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.markov_head.embed(token_ids)
|
||||
|
||||
def markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.markov_head.bias(markov_embed, self.logits_processor)
|
||||
|
||||
def compute_confidence(
|
||||
self, head_hidden: torch.Tensor, markov_embed: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Per-position acceptance probability for each drafted token."""
|
||||
assert self.model.confidence_head is not None
|
||||
return torch.sigmoid(self.model.confidence_head(head_hidden, markov_embed))
|
||||
|
||||
# --- Weight loading ----------------------------------------------------
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load the ``mtp.{0,1,2}.*`` draft weights from the target checkpoint.
|
||||
|
||||
Non-mtp weights (embed/head/main layers) belong to the target model and
|
||||
are skipped here. ``embed_tokens``/``lm_head`` are aliased from the target.
|
||||
"""
|
||||
first_layer = self.model.layers[0]
|
||||
use_mega_moe = first_layer.ffn.use_mega_moe
|
||||
# Draft MoE layers use the dspark_* expert counts, not the
|
||||
# backbone's (see DeepseekV4MoE and the reference
|
||||
# ModelArgs.get_moe_config).
|
||||
n_draft_experts = (
|
||||
getattr(self.config, "dspark_n_routed_experts", 0)
|
||||
or self.config.n_routed_experts
|
||||
)
|
||||
if use_mega_moe:
|
||||
expert_mapping = make_deepseek_v4_expert_params_mapping(n_draft_experts)
|
||||
else:
|
||||
expert_mapping = fused_moe_make_expert_params_mapping(
|
||||
self,
|
||||
ckpt_gate_proj_name="w1",
|
||||
ckpt_down_proj_name="w2",
|
||||
ckpt_up_proj_name="w3",
|
||||
num_experts=n_draft_experts,
|
||||
)
|
||||
expert_scale_suffix = (
|
||||
".weight_scale"
|
||||
if getattr(self.config, "expert_dtype", "fp4") == "fp4"
|
||||
else ".weight_scale_inv"
|
||||
)
|
||||
|
||||
# (param_name, ckpt_shard_name, shard_id) for non-expert stacked params.
|
||||
stacked_params_mapping = [
|
||||
("gate_up_proj", "w1", 0),
|
||||
("gate_up_proj", "w3", 1),
|
||||
("attn.fused_wqa_wkv", "attn.wq_a", 0),
|
||||
("attn.fused_wqa_wkv", "attn.wkv", 1),
|
||||
]
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
loaded_confidence_head = False
|
||||
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
tp_rank = get_tensor_model_parallel_rank()
|
||||
n_local_head = self.config.num_attention_heads // tp_size
|
||||
head_start = n_local_head * tp_rank
|
||||
head_end = n_local_head * (tp_rank + 1)
|
||||
|
||||
for name, loaded_weight in weights:
|
||||
mapped = self._remap_dspark_name(name)
|
||||
if mapped is None:
|
||||
continue
|
||||
name = mapped
|
||||
if "confidence_head." in name:
|
||||
loaded_confidence_head = True
|
||||
|
||||
# ``.scale`` -> per-method scale suffix.
|
||||
if name.endswith(".scale"):
|
||||
suffix = (
|
||||
expert_scale_suffix
|
||||
if _EXPERT_SCALE_RE.search(name)
|
||||
else f".{self.linear_scale_name}"
|
||||
)
|
||||
name = name.removesuffix(".scale") + suffix
|
||||
if ".shared_experts.w2" in name:
|
||||
name = name.replace(".shared_experts.w2", ".shared_experts.down_proj")
|
||||
if self.pad_shared_expert and ".shared_experts." in name:
|
||||
loaded_weight = DeepseekV4Model._pad_shared_expert_weight(
|
||||
self.quant_config, name, loaded_weight
|
||||
)
|
||||
|
||||
# E8M0 expert scales: keep raw exponent bytes.
|
||||
if ".experts." in name:
|
||||
if (
|
||||
"weight_scale" in name
|
||||
and loaded_weight.dtype == torch.float8_e8m0fnu
|
||||
):
|
||||
loaded_weight = loaded_weight.view(torch.uint8)
|
||||
for param_name, weight_name, expert_id, shard_id in expert_mapping:
|
||||
if weight_name not in name:
|
||||
continue
|
||||
name_mapped = name.replace(weight_name, param_name)
|
||||
param = params_dict[name_mapped]
|
||||
success = param.weight_loader(
|
||||
param,
|
||||
loaded_weight,
|
||||
name_mapped,
|
||||
shard_id=shard_id,
|
||||
expert_id=expert_id,
|
||||
return_success=True,
|
||||
)
|
||||
if success:
|
||||
loaded_params.add(name_mapped)
|
||||
break
|
||||
continue
|
||||
|
||||
# Stacked rules only apply to decoder-layer weights. Head-stack params
|
||||
# (main_proj/norm/markov_head/confidence_head) load directly —
|
||||
# otherwise e.g. "markov_w1" would collide with the "w1" shard rule.
|
||||
is_layer_param = name.startswith("model.layers.")
|
||||
for param_name, weight_name, stacked_shard_id in stacked_params_mapping:
|
||||
if not is_layer_param or weight_name not in name:
|
||||
continue
|
||||
name = name.replace(weight_name, param_name)
|
||||
param = params_dict[name]
|
||||
param.weight_loader(param, loaded_weight, stacked_shard_id)
|
||||
loaded_params.add(name)
|
||||
break
|
||||
else:
|
||||
if "attn_sink" in name:
|
||||
narrow = loaded_weight[head_start:head_end]
|
||||
params_dict[name][: narrow.shape[0]].copy_(narrow)
|
||||
loaded_params.add(name)
|
||||
continue
|
||||
if name.endswith(".ffn.gate.bias"):
|
||||
name = name.replace(
|
||||
".ffn.gate.bias", ".ffn.gate.e_score_correction_bias"
|
||||
)
|
||||
param = params_dict[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, loaded_weight)
|
||||
loaded_params.add(name)
|
||||
|
||||
if self.model.confidence_head is not None and not loaded_confidence_head:
|
||||
self.model.confidence_head = None
|
||||
self.process_weights_after_loading()
|
||||
logger.info_once("DSpark draft model loaded: %d params", len(loaded_params))
|
||||
return loaded_params
|
||||
|
||||
def _finalize_moe(self) -> None:
|
||||
for layer in self.model.layers:
|
||||
layer.ffn.finalize_mega_moe_weights()
|
||||
|
||||
def process_weights_after_loading(self) -> None:
|
||||
self._finalize_moe()
|
||||
|
||||
def _remap_dspark_name(self, name: str) -> str | None:
|
||||
"""Map a checkpoint ``mtp.{i}.*`` name to this model's parameter path.
|
||||
|
||||
Returns None for non-mtp weights (owned by the target model).
|
||||
"""
|
||||
m = re.match(r"mtp\.(\d+)\.(.*)", name)
|
||||
if m is None:
|
||||
return None
|
||||
stage = int(m.group(1))
|
||||
rest = m.group(2)
|
||||
if rest.startswith("confidence_head.") and self.model.confidence_head is None:
|
||||
return None
|
||||
# The checkpoint calls the Markov head's factors ``embed``/``head``;
|
||||
# DSparkMarkovHead registers them as ``markov_w1``/``markov_w2``.
|
||||
if rest.startswith("markov_head.embed."):
|
||||
return "model.markov_head.markov_w1." + rest.removeprefix(
|
||||
"markov_head.embed."
|
||||
)
|
||||
if rest.startswith("markov_head.head."):
|
||||
return "model.markov_head.markov_w2." + rest.removeprefix(
|
||||
"markov_head.head."
|
||||
)
|
||||
# Head-stack params live at model level (mtp.last), context combiner at
|
||||
# model level (mtp.0); everything else is a per-layer decoder block.
|
||||
head_prefixes = (
|
||||
"norm.",
|
||||
"markov_head.",
|
||||
"confidence_head.",
|
||||
)
|
||||
if rest.startswith(("main_proj.", "main_norm.")) or rest.startswith(
|
||||
head_prefixes
|
||||
):
|
||||
return f"model.{rest}"
|
||||
return f"model.layers.{stage}.{rest}"
|
||||
@@ -0,0 +1,403 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA Engram DP sharding, shared host storage, and asynchronous prefetch."""
|
||||
|
||||
import mmap
|
||||
import tempfile
|
||||
import weakref
|
||||
from contextlib import ExitStack
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.distributed import (
|
||||
get_dp_group,
|
||||
get_engram_dp_group,
|
||||
get_engram_dp_size,
|
||||
get_tensor_model_parallel_rank,
|
||||
tensor_model_parallel_all_gather,
|
||||
)
|
||||
from vllm.distributed.parallel_state import GroupCoordinator
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.utils import set_weight_attrs
|
||||
from vllm.models.deepseek_v41.common.engram import (
|
||||
DEAD_ID,
|
||||
EngramLayout,
|
||||
_engram_head_shard_weight_loader,
|
||||
_engram_select_rows,
|
||||
)
|
||||
from vllm.models.deepseek_v41.common.engram import (
|
||||
Engram as BaseEngram,
|
||||
)
|
||||
from vllm.models.deepseek_v41.common.engram import (
|
||||
ParallelEngramEmbedding as BaseParallelEngramEmbedding,
|
||||
)
|
||||
from vllm.utils.platform_utils import is_uva_available
|
||||
from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def engram_head_shard_rank() -> int:
|
||||
"""This rank's slot among the hash-head shards of one engram table.
|
||||
|
||||
TP-major, so the shards a DP gather brings in are contiguous heads and
|
||||
the following TP gather completes the head order.
|
||||
"""
|
||||
dp_group = get_engram_dp_group()
|
||||
dp_size = dp_group.world_size if dp_group is not None else 1
|
||||
dp_rank = dp_group.rank_in_group if dp_group is not None else 0
|
||||
return get_tensor_model_parallel_rank() * dp_size + dp_rank
|
||||
|
||||
|
||||
def engram_gathered_num_tokens() -> int:
|
||||
"""Per-replica token slot for the node-local Engram DP group."""
|
||||
dp_metadata = get_forward_context().dp_metadata
|
||||
if dp_metadata is None:
|
||||
raise RuntimeError("a DP-shared engram table needs DP token metadata")
|
||||
group = get_engram_dp_group()
|
||||
assert group is not None
|
||||
# Engram groups are contiguous slices of the full DP group.
|
||||
start = get_dp_group().rank_in_group - group.rank_in_group
|
||||
return int(
|
||||
dp_metadata.num_tokens_across_dp_cpu[start : start + group.world_size].max()
|
||||
)
|
||||
|
||||
|
||||
def gather_engram_hashes(
|
||||
hash_ids: torch.Tensor, *, dp_shared_memory: bool = False
|
||||
) -> torch.Tensor:
|
||||
"""Collect the n-gram ids of every DP replica sharing one table.
|
||||
|
||||
Replicas are padded to a common token slot, so the gathered shape is
|
||||
static under CUDA graph capture (where DP already pads alike).
|
||||
"""
|
||||
dp_group = get_engram_dp_group()
|
||||
if dp_group is None or dp_shared_memory:
|
||||
return hash_ids
|
||||
slot = engram_gathered_num_tokens()
|
||||
if hash_ids.shape[0] > slot:
|
||||
raise ValueError("Engram token count exceeds the DP token slot")
|
||||
if hash_ids.shape[0] < slot:
|
||||
pad = hash_ids.new_full(
|
||||
(slot - hash_ids.shape[0], *hash_ids.shape[1:]), DEAD_ID
|
||||
)
|
||||
hash_ids = torch.cat((hash_ids, pad))
|
||||
return dp_group.all_gather(hash_ids, dim=0)
|
||||
|
||||
|
||||
class DPSharedEngramStorage:
|
||||
"""Registered host weights shared by a node-local DP group with one writer."""
|
||||
|
||||
def __init__(
|
||||
self, num_rows: int, dim: int, block_size: int, group: GroupCoordinator
|
||||
) -> None:
|
||||
self.group = group
|
||||
weight_bytes = num_rows * dim
|
||||
storage = self._allocate(weight_bytes + weight_bytes // block_size)
|
||||
self.weight = storage[:weight_bytes].view(torch.float8_e4m3fn).view(-1, dim)
|
||||
self.weight_scale_inv = storage[weight_bytes:].view(-1, dim // block_size)
|
||||
self._views: tuple[torch.Tensor, torch.Tensor] | None = None
|
||||
|
||||
def _allocate(self, num_bytes: int) -> torch.Tensor:
|
||||
"""Map and register one physical allocation across a node-local DP group."""
|
||||
from vllm.distributed.device_communicators.shm_broadcast import (
|
||||
check_shm_free_space,
|
||||
)
|
||||
|
||||
group = self.group
|
||||
with ExitStack() as stack:
|
||||
path, error = None, None
|
||||
if group.rank_in_group == 0:
|
||||
try:
|
||||
check_shm_free_space(num_bytes)
|
||||
backing_file = stack.enter_context(
|
||||
tempfile.NamedTemporaryFile(
|
||||
prefix="vllm_engram_", dir="/dev/shm"
|
||||
)
|
||||
)
|
||||
backing_file.truncate(num_bytes)
|
||||
path = backing_file.name
|
||||
except Exception as exc:
|
||||
error = f"{type(exc).__name__}: {exc}"
|
||||
path, error = group.broadcast_object((path, error))
|
||||
if error is not None:
|
||||
raise RuntimeError(
|
||||
"Engram shared-memory creation failed on EDP rank 0: " + error
|
||||
)
|
||||
|
||||
mapping = owner = tensor = finalizer = None
|
||||
stage = "open"
|
||||
try:
|
||||
try:
|
||||
with open(path, "r+b") as file:
|
||||
stage = "mmap"
|
||||
mapping = mmap.mmap(
|
||||
file.fileno(), num_bytes, flags=mmap.MAP_SHARED
|
||||
)
|
||||
stage = "cudaHostRegister"
|
||||
owner = np.frombuffer(mapping, dtype=np.uint8)
|
||||
pointer = owner.ctypes.data
|
||||
tensor = torch.from_numpy(owner)
|
||||
result = torch.cuda.cudart().cudaHostRegister(pointer, num_bytes, 0)
|
||||
if result.value != 0:
|
||||
raise RuntimeError(f"cudaHostRegister failed: {result}")
|
||||
finalizer = weakref.finalize(
|
||||
owner, self._unregister, mapping, pointer
|
||||
)
|
||||
finalizer.atexit = False # type: ignore[misc]
|
||||
# The UVA helper otherwise allocates a private pinned copy.
|
||||
if not tensor.is_pinned():
|
||||
raise RuntimeError(
|
||||
"CUDA did not recognize the shared Engram registration"
|
||||
)
|
||||
except Exception as exc:
|
||||
error = f"{stage}: {type(exc).__name__}: {exc}"
|
||||
|
||||
errors: list[str | None] = [None] * group.world_size
|
||||
# Also fences peer mappings before the leader unlinks the file.
|
||||
torch.distributed.all_gather_object(
|
||||
errors, error, group=group.cpu_group
|
||||
)
|
||||
failures = "; ".join(
|
||||
f"EDP rank {rank}: {error}"
|
||||
for rank, error in enumerate(errors)
|
||||
if error is not None
|
||||
)
|
||||
if failures:
|
||||
raise RuntimeError(
|
||||
"Engram shared-memory initialization failed: " + failures
|
||||
)
|
||||
assert tensor is not None
|
||||
return tensor
|
||||
except Exception:
|
||||
if finalizer is not None:
|
||||
finalizer()
|
||||
tensor = owner = None
|
||||
if mapping is not None:
|
||||
mapping.close()
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _unregister(mapping: mmap.mmap, pointer: int) -> None:
|
||||
# Torch storage retains the numpy owner, including through cached UVA views.
|
||||
# Keep its mmap alive until CUDA has released the registration.
|
||||
result = torch.cuda.cudart().cudaHostUnregister(pointer)
|
||||
if result.value != 0:
|
||||
logger.warning("Engram cudaHostUnregister failed: %s", result)
|
||||
|
||||
def load_weight(
|
||||
self, param: torch.nn.Parameter, loaded_weight: torch.Tensor
|
||||
) -> None:
|
||||
if self.group.rank_in_group == 0:
|
||||
_engram_head_shard_weight_loader(param, loaded_weight)
|
||||
# Read order may differ across ranks. Equal load counts ensure all shared
|
||||
# weights are ready after the last weight-loader call returns.
|
||||
torch.distributed.barrier(group=self.group.cpu_group)
|
||||
|
||||
def get_views(
|
||||
self, weight: torch.Tensor, scales: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if (weight.data_ptr(), scales.data_ptr()) != (
|
||||
self.weight.data_ptr(),
|
||||
self.weight_scale_inv.data_ptr(),
|
||||
):
|
||||
raise RuntimeError("Shared Engram parameter storage must not be replaced")
|
||||
if self._views is None:
|
||||
self._views = (
|
||||
get_accelerator_view_from_cpu_tensor(self.weight),
|
||||
get_accelerator_view_from_cpu_tensor(self.weight_scale_inv),
|
||||
)
|
||||
return self._views
|
||||
|
||||
|
||||
class ParallelEngramEmbedding(BaseParallelEngramEmbedding):
|
||||
"""Extend TP lookup with DP head sharding or shared, CPU-offloaded TP slices."""
|
||||
|
||||
_shared_memory: DPSharedEngramStorage | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_embeddings: int,
|
||||
dim: int,
|
||||
head_sizes: tuple[int, ...],
|
||||
block_size: int = 32,
|
||||
cpu_offload: bool = False,
|
||||
dp_shared_memory: bool = False,
|
||||
) -> None:
|
||||
self.cpu_offload = cpu_offload
|
||||
self.dp_shared_memory = dp_shared_memory
|
||||
self.dp_size = get_engram_dp_size()
|
||||
if dp_shared_memory:
|
||||
if not cpu_offload:
|
||||
raise ValueError("dp_shared_memory requires cpu_offload=True")
|
||||
if self.dp_size <= 1:
|
||||
raise ValueError(
|
||||
"dp_shared_memory requires a node-local Engram DP "
|
||||
f"group with size > 1; effective Engram DP size is {self.dp_size}. "
|
||||
"Check that the node layout and rank placement allow complete "
|
||||
"DP replicas to be co-located."
|
||||
)
|
||||
self.dp_size = 1
|
||||
if cpu_offload and not is_uva_available():
|
||||
raise RuntimeError("Engram CPU offload requires UVA support")
|
||||
self._views: tuple[torch.Tensor, torch.Tensor] | None = None
|
||||
self._view_src: tuple[int, int] | None = None
|
||||
super().__init__(num_embeddings, dim, head_sizes, block_size)
|
||||
if cpu_offload:
|
||||
# Constant dummy values avoid randomizing huge CPU lookup tables.
|
||||
set_weight_attrs(self.weight, {"dummy_weight_value": 1.0})
|
||||
# The ue8m0 encoding of scale 1.0 is exponent byte 127.
|
||||
set_weight_attrs(self.weight_scale_inv, {"dummy_weight_value": 127})
|
||||
logger.info(
|
||||
"Engram table offloaded to pinned host memory: %d rows x %d, "
|
||||
"%.2f GiB %s",
|
||||
self.part_num_embeddings,
|
||||
dim,
|
||||
self.part_num_embeddings * (dim + dim // block_size) / 1024**3,
|
||||
"shared across DP replicas" if dp_shared_memory else "per rank",
|
||||
)
|
||||
|
||||
def _get_shard_info(self) -> tuple[int, int]:
|
||||
if self.dp_size == 1:
|
||||
return super()._get_shard_info()
|
||||
return self.tp_size * self.dp_size, engram_head_shard_rank()
|
||||
|
||||
def _allocate_weights(self) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if self.dp_shared_memory:
|
||||
group = get_engram_dp_group()
|
||||
assert group is not None
|
||||
storage = DPSharedEngramStorage(
|
||||
self.part_num_embeddings, self.dim, self.block_size, group
|
||||
)
|
||||
self._shared_memory = storage
|
||||
self._weight_loader = storage.load_weight
|
||||
return storage.weight, storage.weight_scale_inv
|
||||
if not self.cpu_offload:
|
||||
return super()._allocate_weights()
|
||||
# Model initialization may be inside a CUDA device context.
|
||||
return (
|
||||
torch.empty(
|
||||
self.part_num_embeddings,
|
||||
self.dim,
|
||||
dtype=torch.float8_e4m3fn,
|
||||
device="cpu",
|
||||
pin_memory=True,
|
||||
),
|
||||
torch.empty(
|
||||
self.part_num_embeddings,
|
||||
self.dim // self.block_size,
|
||||
dtype=torch.uint8,
|
||||
device="cpu",
|
||||
pin_memory=True,
|
||||
),
|
||||
)
|
||||
|
||||
def _storage(self) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if self._shared_memory is not None:
|
||||
return self._shared_memory.get_views(self.weight, self.weight_scale_inv)
|
||||
if not self.cpu_offload:
|
||||
return super()._storage()
|
||||
src = (self.weight.data_ptr(), self.weight_scale_inv.data_ptr())
|
||||
if self._view_src != src:
|
||||
self._views = (
|
||||
get_accelerator_view_from_cpu_tensor(self.weight.data),
|
||||
get_accelerator_view_from_cpu_tensor(self.weight_scale_inv.data),
|
||||
)
|
||||
self._view_src = src
|
||||
assert self._views is not None
|
||||
return self._views
|
||||
|
||||
def forward(self, indices: torch.Tensor) -> torch.Tensor:
|
||||
if self.dp_size == 1:
|
||||
return super().forward(indices)
|
||||
num_tokens = indices.shape[0]
|
||||
indices = gather_engram_hashes(indices)
|
||||
out = torch.empty(
|
||||
(indices.shape[0], self.part_n_hash_cols, self.dim),
|
||||
dtype=torch.bfloat16,
|
||||
device=indices.device,
|
||||
)
|
||||
self.lookup(indices, out)
|
||||
out = _gather_engram_rows(out, num_tokens)
|
||||
if self.tp_size > 1:
|
||||
out = tensor_model_parallel_all_gather(out, dim=1)
|
||||
return out[:, : self.n_hash_cols]
|
||||
|
||||
|
||||
def _gather_engram_rows(staged: torch.Tensor, num_tokens: int) -> torch.Tensor:
|
||||
"""Exchange DP tokens for heads, retaining only this replica's tokens."""
|
||||
dp_group = get_engram_dp_group()
|
||||
assert dp_group is not None
|
||||
slot, remainder = divmod(staged.shape[0], dp_group.world_size)
|
||||
assert remainder == 0 and 0 <= num_tokens <= slot
|
||||
gathered = dp_group.all_gather(staged, dim=0)
|
||||
local_heads, dim = staged.shape[1:]
|
||||
rows = staged.new_empty((num_tokens, dp_group.world_size * local_heads, dim))
|
||||
_engram_select_rows(
|
||||
gathered,
|
||||
rows,
|
||||
staged.shape[0],
|
||||
dp_group.rank_in_group * slot,
|
||||
local_heads * dim,
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
class Engram(BaseEngram):
|
||||
"""NVIDIA Engram with asynchronous offload and node-local DP lookup."""
|
||||
|
||||
_prefetch_stream: torch.cuda.Stream | None = None
|
||||
|
||||
def _create_embedding(
|
||||
self, layout: EngramLayout, layer_hash_index: int
|
||||
) -> ParallelEngramEmbedding:
|
||||
engram_config = get_current_vllm_config().engram_config
|
||||
assert engram_config is not None
|
||||
return ParallelEngramEmbedding(
|
||||
layout.num_embeddings[layer_hash_index],
|
||||
layout.head_dim,
|
||||
tuple(size for order in layout.primes[layer_hash_index] for size in order),
|
||||
cpu_offload=engram_config.cpu_offload,
|
||||
dp_shared_memory=engram_config.dp_shared_memory,
|
||||
)
|
||||
|
||||
def _init_staging(self, max_tokens: int, head_dim: int) -> None:
|
||||
super()._init_staging(max_tokens * self.embed_tokens.dp_size, head_dim)
|
||||
if self.embed_tokens.cpu_offload:
|
||||
self._prefetch_stream = torch.cuda.Stream(device=self.staged_rows.device)
|
||||
|
||||
def prepare_embeddings(self, hash_ids: torch.Tensor) -> None:
|
||||
"""Prefetch local shared rows or the DP group's gathered hash IDs."""
|
||||
if self._prefetch_stream is None:
|
||||
return super().prepare_embeddings(hash_ids)
|
||||
rows = self.staged_rows[: hash_ids.shape[0]]
|
||||
assert rows.shape[0] == hash_ids.shape[0], "engram staging buffer too small"
|
||||
self._start_prefetch(hash_ids, rows, self._prefetch_stream)
|
||||
|
||||
@eager_break_during_capture
|
||||
def _start_prefetch(
|
||||
self, hash_ids: torch.Tensor, rows: torch.Tensor, stream: torch.cuda.Stream
|
||||
) -> None:
|
||||
# Eager boundaries let the lookup span piecewise graph segments.
|
||||
stream.wait_stream(torch.cuda.current_stream())
|
||||
# Keep temporary hash storage alive until lookup finishes reading it.
|
||||
hash_ids.record_stream(stream)
|
||||
with torch.cuda.stream(stream):
|
||||
self.embed_tokens.lookup(hash_ids, rows, background=True)
|
||||
|
||||
@eager_break_during_capture
|
||||
def _finish_prefetch(self, stream: torch.cuda.Stream) -> None:
|
||||
torch.cuda.current_stream().wait_stream(stream)
|
||||
|
||||
def _ready_rows(self, num_tokens: int) -> torch.Tensor:
|
||||
if self._prefetch_stream is not None:
|
||||
self._finish_prefetch(self._prefetch_stream)
|
||||
if self.embed_tokens.dp_size > 1:
|
||||
slot = engram_gathered_num_tokens()
|
||||
staged = self.staged_rows[: slot * self.embed_tokens.dp_size]
|
||||
return _gather_engram_rows(staged, num_tokens)
|
||||
return super()._ready_rows(num_tokens)
|
||||
@@ -0,0 +1,908 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepSeek V4 FlashInfer sparse MLA backend."""
|
||||
|
||||
from typing import TYPE_CHECKING, ClassVar, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
|
||||
compute_fp8_einsum_recipe,
|
||||
deep_gemm_fp8_o_proj,
|
||||
)
|
||||
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
|
||||
from vllm.models.deepseek_v41.common.ops import (
|
||||
build_flashinfer_mixed_sparse_indices,
|
||||
compute_global_topk_indices_and_lens,
|
||||
)
|
||||
from vllm.models.deepseek_v41.sparse_mla import (
|
||||
DeepseekV4FlashMLAMetadata,
|
||||
DeepseekV4SparseMLABackend,
|
||||
DeepseekV4SparseMLAMetadataBuilder,
|
||||
DeepseekV41SparseSWAMetadataBuilder,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.utils.flashinfer import flashinfer_trtllm_batch_decode_sparse_mla_dsv4
|
||||
from vllm.v1.attention.backend import AttentionCGSupport, MultipleOf
|
||||
from vllm.v1.attention.backends.mla.compressor_utils import (
|
||||
get_dspark_swa_index_width,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWABackend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
|
||||
|
||||
_FLASHINFER_DSV4_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024
|
||||
_flashinfer_dsv4_workspace_by_device: dict[torch.device, torch.Tensor] = {}
|
||||
|
||||
|
||||
def _get_flashinfer_dsv4_workspace(device: torch.device) -> torch.Tensor:
|
||||
workspace = _flashinfer_dsv4_workspace_by_device.get(device)
|
||||
if workspace is None:
|
||||
workspace = torch.zeros(
|
||||
_FLASHINFER_DSV4_WORKSPACE_BUFFER_SIZE,
|
||||
dtype=torch.uint8,
|
||||
device=device,
|
||||
)
|
||||
_flashinfer_dsv4_workspace_by_device[device] = workspace
|
||||
return workspace
|
||||
|
||||
|
||||
def _packed_block_span(pool: torch.Tensor) -> int:
|
||||
"""Per-block stride of ``pool`` in tokens (``stride(0)//stride(-2)``): ==
|
||||
block_size for unpacked KV, larger when packed (#44577). Raises if not
|
||||
token-aligned."""
|
||||
block_stride = pool.stride(0)
|
||||
token_stride = pool.stride(-2)
|
||||
if block_stride % token_stride != 0:
|
||||
raise NotImplementedError(
|
||||
"FLASHINFER_MLA_SPARSE_DSV4 packed KV requires the per-block stride "
|
||||
f"({block_stride}) to be a multiple of the per-token stride "
|
||||
f"({token_stride}); this layout is not supported yet."
|
||||
)
|
||||
return block_stride // token_stride
|
||||
|
||||
|
||||
# Sparse MLA h_q counts accepted natively (flashinfer>=0.6.14, #3545).
|
||||
_SPARSE_MLA_SUPPORTED_Q_HEADS = (8, 16, 32, 64, 128)
|
||||
|
||||
|
||||
def _pad_to_supported_q_heads(num_heads: int) -> int:
|
||||
for supported in _SPARSE_MLA_SUPPORTED_Q_HEADS:
|
||||
if num_heads <= supported:
|
||||
return supported
|
||||
raise ValueError(
|
||||
f"DeepseekV4 FlashInfer MLA Sparse does not support {num_heads} heads "
|
||||
"(sparse MLA kernel requires h_q in {8, 16, 32, 64, 128})."
|
||||
)
|
||||
|
||||
|
||||
def _required_sm120_sparse_topk(vllm_config: VllmConfig, window_size: int) -> int:
|
||||
"""Return the SM120 DSV4 SWA specialization needed by this model."""
|
||||
if not vllm_config.attention_config.use_non_causal:
|
||||
return window_size
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if speculative_config is None:
|
||||
return window_size
|
||||
return get_dspark_swa_index_width(
|
||||
window_size,
|
||||
speculative_config.num_speculative_tokens,
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4FlashInferMLASparseBackend(DeepseekV4SparseMLABackend):
|
||||
"""FlashInfer backend using the DSv4 sparse metadata/cache layout.
|
||||
|
||||
Inherits the base and backend reuses its``DeepseekV4SparseMLAMetadataBuilder``
|
||||
"""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
"fp8_ds_mla",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [128]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_MLA_SPARSE_DSV41"
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
return [512]
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
|
||||
return capability.major in [10, 12]
|
||||
|
||||
@classmethod
|
||||
def supports_combination(
|
||||
cls,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
kv_cache_dtype: CacheDType | None,
|
||||
block_size: int | None,
|
||||
use_mla: bool,
|
||||
has_sink: bool,
|
||||
use_sparse: bool,
|
||||
use_mm_prefix: bool,
|
||||
device_capability: DeviceCapability,
|
||||
) -> str | None:
|
||||
if device_capability.major == 10:
|
||||
if kv_cache_dtype == "fp8_ds_mla":
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE_DSV4 SM10x uses the plain "
|
||||
"per-tensor FP8 KV layout, not fp8_ds_mla"
|
||||
)
|
||||
if kv_cache_dtype not in (None, "auto", "bfloat16", "fp8", "fp8_e4m3"):
|
||||
return "kv_cache_dtype not supported"
|
||||
return None
|
||||
if device_capability.major == 12:
|
||||
if kv_cache_dtype not in ("fp8", "fp8_e4m3", "fp8_ds_mla"):
|
||||
return "kv_cache_dtype not supported"
|
||||
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120
|
||||
|
||||
if not has_flashinfer_sparse_mla_sm120():
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE_DSV4 SM120 requires FlashInfer's "
|
||||
"sparse MLA decode API"
|
||||
)
|
||||
return None
|
||||
return "FLASHINFER_MLA_SPARSE_DSV4 requires SM10x or SM12x"
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["DeepseekV4FlashInferSparseMLAMetadataBuilder"]:
|
||||
return DeepseekV4FlashInferSparseMLAMetadataBuilder
|
||||
|
||||
|
||||
class DeepseekV4FlashInferSparseMLAMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder):
|
||||
"""Varlen-capable metadata builder for the FlashInfer sparse MLA backend."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
|
||||
|
||||
class DeepseekSparseSWAFlashInferMetadataBuilder(DeepseekV41SparseSWAMetadataBuilder):
|
||||
"""SWA metadata for the FlashInfer sparse decode path (varlen decode)."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
|
||||
|
||||
class DeepseekSparseSWAFlashInferBackend(DeepseekSparseSWABackend):
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[DeepseekSparseSWAFlashInferMetadataBuilder]:
|
||||
return DeepseekSparseSWAFlashInferMetadataBuilder
|
||||
|
||||
|
||||
class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
|
||||
"""FlashInfer TRTLLM-gen sparse MLA attention layer for SM100 DeepSeek V4."""
|
||||
|
||||
backend_cls = DeepseekV4FlashInferMLASparseBackend
|
||||
swa_backend_cls = DeepseekSparseSWAFlashInferBackend
|
||||
use_fp8_ds_mla_layout: ClassVar[bool] = False
|
||||
|
||||
@classmethod
|
||||
def get_padded_num_q_heads(cls, num_heads: int) -> int:
|
||||
return _pad_to_supported_q_heads(num_heads)
|
||||
|
||||
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
|
||||
return deep_gemm_fp8_o_proj(
|
||||
o,
|
||||
positions,
|
||||
self.rotary_emb.cos_sin_cache,
|
||||
self.wo_a,
|
||||
self.wo_b,
|
||||
n_groups=self.n_local_groups,
|
||||
heads_per_group=self.n_local_heads // self.n_local_groups,
|
||||
nope_dim=self.nope_head_dim,
|
||||
rope_dim=self.rope_head_dim,
|
||||
o_lora_rank=self.o_lora_rank,
|
||||
einsum_recipe=self._einsum_recipe,
|
||||
tma_aligned_scales=self._tma_aligned_scales,
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe(
|
||||
self._o_proj_block_size
|
||||
)
|
||||
# Per-tensor FP8 scale buffers + precomputed scalar BMM scales. Only the
|
||||
# per-tensor FP8 cache path consumes these; bf16 reads ``self.scale``.
|
||||
if self.kv_cache_torch_dtype != torch.float8_e4m3fn:
|
||||
return
|
||||
fp8_q_scale = 1.0
|
||||
fp8_kv_scale = 1.0
|
||||
self.register_buffer(
|
||||
"_flashinfer_fp8_q_scale",
|
||||
torch.tensor([fp8_q_scale], dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
self.register_buffer(
|
||||
"_flashinfer_fp8_q_scale_inv",
|
||||
torch.tensor([1.0 / fp8_q_scale], dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
self.register_buffer(
|
||||
"_flashinfer_fp8_kv_scale",
|
||||
torch.tensor([fp8_kv_scale], dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
# TRTLLM-gen takes scalar scale args on a distinct C++ path vs
|
||||
# one-element tensors, so these are Python floats.
|
||||
self._flashinfer_fp8_bmm1_scale = self.scale * fp8_q_scale * fp8_kv_scale
|
||||
self._flashinfer_fp8_bmm2_scale = fp8_kv_scale
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
# The TRTLLM-gen kernel requires h_q in {64, 128}, so the output buffer
|
||||
# is allocated at the padded head count while q arrives at the local
|
||||
# head count; _forward pads q to match before the launcher.
|
||||
assert output.shape[0] == q.shape[0] and output.shape[-1] == q.shape[-1], (
|
||||
f"output buffer shape {output.shape} incompatible with q shape {q.shape}"
|
||||
)
|
||||
assert output.shape[1] >= q.shape[1], (
|
||||
f"output heads {output.shape[1]} must be >= q heads {q.shape[1]}"
|
||||
)
|
||||
# Per-tensor FP8 q produces a bf16 attention output.
|
||||
expected_output_dtype = (
|
||||
torch.bfloat16 if q.dtype == torch.float8_e4m3fn else q.dtype
|
||||
)
|
||||
assert output.dtype == expected_output_dtype, (
|
||||
f"output dtype {output.dtype} must match expected {expected_output_dtype} "
|
||||
f"for q dtype {q.dtype}"
|
||||
)
|
||||
|
||||
forward_context = get_forward_context()
|
||||
attn_metadata = forward_context.attn_metadata
|
||||
if attn_metadata is None:
|
||||
# Warmup dummy run: FlashInfer reads the cache directly and lazily
|
||||
# allocates its workspace, so nothing to reserve here.
|
||||
output.zero_()
|
||||
return
|
||||
|
||||
assert isinstance(attn_metadata, dict)
|
||||
# Compressed-cache metadata lives on the kv-source layer's prefix;
|
||||
# consumers share that cache and its block table.
|
||||
flashmla_metadata = cast(
|
||||
DeepseekV4FlashMLAMetadata | None,
|
||||
attn_metadata.get(self.compressed_cache_prefix)
|
||||
if self.compressed_cache_prefix is not None
|
||||
else None,
|
||||
)
|
||||
swa_metadata = cast(
|
||||
"DeepseekSparseSWAMetadata | None",
|
||||
attn_metadata.get(self.swa_cache_layer.prefix),
|
||||
)
|
||||
assert swa_metadata is not None
|
||||
|
||||
swa_only = self.compress_ratio == 0
|
||||
# SWA-only layers have no compressed KV cache; consumers read the kv
|
||||
# source's cache.
|
||||
self_kv_cache = None if swa_only else self._compressed_kv_cache()
|
||||
swa_kv_cache = self.swa_cache_layer.kv_cache
|
||||
|
||||
self._forward(
|
||||
q=q,
|
||||
kv_cache=self_kv_cache,
|
||||
swa_k_cache=swa_kv_cache,
|
||||
swa_metadata=swa_metadata,
|
||||
attn_metadata=flashmla_metadata,
|
||||
swa_only=swa_only,
|
||||
output=output,
|
||||
)
|
||||
|
||||
def _build_sparse_index_metadata(
|
||||
self,
|
||||
kv_cache: torch.Tensor | None,
|
||||
swa_k_cache: torch.Tensor,
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_only: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Build the combined sparse-index tensors for the mixed batch.
|
||||
|
||||
Returns ``(compressed_kv_cache, seq_lens, sparse_indices,
|
||||
sparse_topk_lens)``.
|
||||
"""
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_prefills = swa_metadata.num_prefills
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
num_prefill_tokens = swa_metadata.num_prefill_tokens
|
||||
num_reqs = num_decodes + num_prefills
|
||||
num_tokens = num_decode_tokens + num_prefill_tokens
|
||||
|
||||
assert swa_metadata.seq_lens is not None
|
||||
assert swa_metadata.query_start_loc is not None
|
||||
assert swa_metadata.token_to_req_indices is not None
|
||||
assert swa_metadata.decode_swa_indices is not None
|
||||
assert swa_metadata.block_table is not None
|
||||
|
||||
decode_swa_indices = swa_metadata.decode_swa_indices.reshape(
|
||||
num_decode_tokens, swa_metadata.decode_swa_width
|
||||
)
|
||||
decode_compressed_topk_lens = None
|
||||
decode_compressed_indices_are_local = False
|
||||
decode_is_valid_token = None
|
||||
|
||||
if swa_only:
|
||||
assert self.topk_indices_buffer is not None
|
||||
compressed_kv_cache = swa_k_cache
|
||||
decode_compressed_indices = None
|
||||
prefill_topk_indices = self.topk_indices_buffer[
|
||||
num_decode_tokens:num_tokens, :0
|
||||
]
|
||||
compressed_block_table = None
|
||||
compressed_block_size = swa_metadata.block_size
|
||||
top_k = 0
|
||||
else:
|
||||
assert kv_cache is not None
|
||||
assert attn_metadata is not None
|
||||
assert self.topk_indices_buffer is not None
|
||||
assert swa_metadata.is_valid_token is not None
|
||||
compressed_kv_cache = kv_cache
|
||||
compressed_block_table = attn_metadata.block_table[:num_reqs]
|
||||
compressed_block_size = attn_metadata.block_size // self.compress_ratio
|
||||
|
||||
# Local indices filled by the index-source layer's indexer.
|
||||
if num_prefill_tokens > 0:
|
||||
prefill_topk_indices = self.topk_indices_buffer[
|
||||
num_decode_tokens:num_tokens
|
||||
]
|
||||
top_k = prefill_topk_indices.shape[-1]
|
||||
else:
|
||||
prefill_topk_indices = self.topk_indices_buffer[:0, :0]
|
||||
top_k = 0
|
||||
|
||||
decode_compressed_indices_are_local = True
|
||||
decode_is_valid_token = swa_metadata.is_valid_token[:num_decode_tokens]
|
||||
if num_decode_tokens > 0:
|
||||
decode_compressed_indices = self.topk_indices_buffer[:num_decode_tokens]
|
||||
else:
|
||||
# Keep the logical width aligned with the mixed-batch case so
|
||||
# pure-prefill steps reuse the same Triton specialization.
|
||||
decode_compressed_indices = prefill_topk_indices[:0]
|
||||
|
||||
query_start_loc = swa_metadata.query_start_loc[: num_reqs + 1]
|
||||
seq_lens = swa_metadata.seq_lens[:num_reqs]
|
||||
assert seq_lens.dtype == torch.int32
|
||||
# SWA-only layers all build the same mixed sparse indices, so the first
|
||||
# one caches them for the step; indexer layers depend on their own topk
|
||||
# indices and stay uncached.
|
||||
cached_sparse = (
|
||||
swa_metadata.flashinfer_sparse_index_cache.get("swa_only")
|
||||
if swa_only
|
||||
else None
|
||||
)
|
||||
if cached_sparse is None:
|
||||
swa_block_span = _packed_block_span(swa_k_cache)
|
||||
compressed_block_span = _packed_block_span(compressed_kv_cache)
|
||||
sparse_indices, sparse_topk_lens = build_flashinfer_mixed_sparse_indices(
|
||||
decode_swa_indices,
|
||||
decode_compressed_indices,
|
||||
decode_compressed_topk_lens,
|
||||
prefill_topk_indices[:num_prefill_tokens],
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
swa_metadata.token_to_req_indices[:num_tokens],
|
||||
swa_metadata.block_table[:num_reqs],
|
||||
swa_metadata.block_size,
|
||||
compressed_block_table,
|
||||
compressed_block_size,
|
||||
self.window_size,
|
||||
self.compress_ratio,
|
||||
top_k,
|
||||
decode_compressed_indices_are_local=decode_compressed_indices_are_local,
|
||||
decode_is_valid_token=decode_is_valid_token,
|
||||
swa_block_span=swa_block_span,
|
||||
compressed_block_span=compressed_block_span,
|
||||
prefill_left_visible=swa_metadata.prefill_left_visible,
|
||||
prefill_right_visible=swa_metadata.prefill_right_visible,
|
||||
# getattr for tests that bypass __init__ via object.__new__.
|
||||
max_image_tokens=getattr(self, "max_image_tokens", 0),
|
||||
)
|
||||
if swa_only:
|
||||
swa_metadata.flashinfer_sparse_index_cache["swa_only"] = (
|
||||
sparse_indices,
|
||||
sparse_topk_lens,
|
||||
)
|
||||
else:
|
||||
sparse_indices, sparse_topk_lens = cached_sparse
|
||||
return compressed_kv_cache, seq_lens, sparse_indices, sparse_topk_lens
|
||||
|
||||
def _forward(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
kv_cache: torch.Tensor | None,
|
||||
swa_k_cache: torch.Tensor,
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_only: bool,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
assert self.kv_cache_torch_dtype in (torch.bfloat16, torch.float8_e4m3fn)
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_prefills = swa_metadata.num_prefills
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
num_prefill_tokens = swa_metadata.num_prefill_tokens
|
||||
num_reqs = num_decodes + num_prefills
|
||||
num_tokens = num_decode_tokens + num_prefill_tokens
|
||||
if num_tokens == 0:
|
||||
return
|
||||
|
||||
(
|
||||
compressed_kv_cache,
|
||||
seq_lens,
|
||||
sparse_indices,
|
||||
sparse_topk_lens,
|
||||
) = self._build_sparse_index_metadata(
|
||||
kv_cache=kv_cache,
|
||||
swa_k_cache=swa_k_cache,
|
||||
swa_metadata=swa_metadata,
|
||||
attn_metadata=attn_metadata,
|
||||
swa_only=swa_only,
|
||||
)
|
||||
|
||||
# CUDA graph execution can pad q/output past the scheduled token count;
|
||||
# restrict to the real tokens (the launcher validates sparse indices).
|
||||
query = q[:num_tokens]
|
||||
output = output[:num_tokens]
|
||||
bmm1_scale: float | torch.Tensor = self.scale
|
||||
bmm2_scale: float | torch.Tensor = 1.0
|
||||
if self.kv_cache_torch_dtype == torch.float8_e4m3fn:
|
||||
assert query.dtype == torch.float8_e4m3fn
|
||||
bmm1_scale = self._flashinfer_fp8_bmm1_scale
|
||||
bmm2_scale = self._flashinfer_fp8_bmm2_scale
|
||||
else:
|
||||
assert query.dtype == torch.bfloat16
|
||||
query = query.contiguous()
|
||||
|
||||
# The TRTLLM-gen sparse-MLA kernel requires h_q in {64, 128}; zero-pad
|
||||
# the query heads to the allocated output head count. Padded heads attend
|
||||
# to the shared KV and are sliced off downstream (output is padded too).
|
||||
padded_heads = output.shape[1]
|
||||
if query.shape[1] < padded_heads:
|
||||
padded_query = query.new_zeros(
|
||||
(query.shape[0], padded_heads, query.shape[2])
|
||||
)
|
||||
padded_query[:, : query.shape[1], :] = query
|
||||
query = padded_query
|
||||
|
||||
workspace = _get_flashinfer_dsv4_workspace(q.device)
|
||||
query_start_loc = swa_metadata.query_start_loc
|
||||
query_start_loc_cpu = swa_metadata.query_start_loc_cpu
|
||||
assert query_start_loc is not None and query_start_loc_cpu is not None
|
||||
|
||||
# Keep the TRTLLM-gen decode/prefill split: the launcher is tuned for
|
||||
# uniform-q batches, and this avoids flattening mixed batches into one call.
|
||||
if num_decode_tokens > 0:
|
||||
decode_cu = query_start_loc[: num_decodes + 1]
|
||||
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
|
||||
query=query[:num_decode_tokens],
|
||||
swa_kv_cache=swa_k_cache,
|
||||
workspace_buffer=workspace,
|
||||
sparse_indices=sparse_indices[:num_decode_tokens],
|
||||
compressed_kv_cache=compressed_kv_cache,
|
||||
sparse_topk_lens=sparse_topk_lens[:num_decode_tokens],
|
||||
seq_lens=seq_lens[:num_decodes],
|
||||
out=output[:num_decode_tokens],
|
||||
bmm1_scale=bmm1_scale,
|
||||
bmm2_scale=bmm2_scale,
|
||||
sinks=self.attn_sink,
|
||||
cum_seq_lens_q=decode_cu,
|
||||
max_q_len=swa_metadata.max_decode_query_len,
|
||||
)
|
||||
|
||||
if num_prefill_tokens > 0:
|
||||
# The prefill query view re-anchors at offset 0, so rebase the
|
||||
# cumulative query offsets to start at 0.
|
||||
prefill_cu = (
|
||||
query_start_loc[num_decodes : num_reqs + 1]
|
||||
- query_start_loc[num_decodes]
|
||||
)
|
||||
prefill_cu_cpu = query_start_loc_cpu[num_decodes : num_reqs + 1]
|
||||
prefill_lens_cpu = prefill_cu_cpu[1:] - prefill_cu_cpu[:-1]
|
||||
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
|
||||
query=query[num_decode_tokens:num_tokens],
|
||||
swa_kv_cache=swa_k_cache,
|
||||
workspace_buffer=workspace,
|
||||
sparse_indices=sparse_indices[num_decode_tokens:num_tokens],
|
||||
compressed_kv_cache=compressed_kv_cache,
|
||||
sparse_topk_lens=sparse_topk_lens[num_decode_tokens:num_tokens],
|
||||
seq_lens=seq_lens[num_decodes:num_reqs],
|
||||
out=output[num_decode_tokens:num_tokens],
|
||||
bmm1_scale=bmm1_scale,
|
||||
bmm2_scale=bmm2_scale,
|
||||
sinks=self.attn_sink,
|
||||
cum_seq_lens_q=prefill_cu,
|
||||
max_q_len=int(prefill_lens_cpu.max().item()),
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4FlashInferSM120Attention(DeepseekV4Attention):
|
||||
"""DeepSeek V4 sparse MLA attention through FlashInfer's SM120 kernels."""
|
||||
|
||||
backend_cls = DeepseekV4FlashInferMLASparseBackend
|
||||
swa_backend_cls = DeepseekSparseSWAFlashInferBackend
|
||||
use_fp8_ds_mla_layout: ClassVar[bool] = True
|
||||
|
||||
@staticmethod
|
||||
def _get_workspace(device: torch.device) -> torch.Tensor:
|
||||
return _get_flashinfer_dsv4_workspace(device)
|
||||
|
||||
@staticmethod
|
||||
def _as_sparse_cache(kv_cache: torch.Tensor) -> torch.Tensor:
|
||||
if kv_cache.dtype == torch.float8_e4m3fn:
|
||||
kv_cache = kv_cache.view(torch.uint8)
|
||||
if kv_cache.dim() == 4:
|
||||
return kv_cache
|
||||
return kv_cache.unsqueeze(-2)
|
||||
|
||||
@classmethod
|
||||
def get_padded_num_q_heads(cls, num_heads: int) -> int:
|
||||
return _pad_to_supported_q_heads(num_heads)
|
||||
|
||||
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
|
||||
return deep_gemm_fp8_o_proj(
|
||||
o,
|
||||
positions,
|
||||
self.rotary_emb.cos_sin_cache,
|
||||
self.wo_a,
|
||||
self.wo_b,
|
||||
n_groups=self.n_local_groups,
|
||||
heads_per_group=self.n_local_heads // self.n_local_groups,
|
||||
nope_dim=self.nope_head_dim,
|
||||
rope_dim=self.rope_head_dim,
|
||||
o_lora_rank=self.o_lora_rank,
|
||||
einsum_recipe=self._einsum_recipe,
|
||||
tma_aligned_scales=self._tma_aligned_scales,
|
||||
)
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, *args, **kwargs) -> None:
|
||||
super().__init__(vllm_config, *args, **kwargs)
|
||||
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120_config
|
||||
|
||||
required_topk = _required_sm120_sparse_topk(vllm_config, self.window_size)
|
||||
if not has_flashinfer_sparse_mla_sm120_config(self.padded_heads, required_topk):
|
||||
raise RuntimeError(
|
||||
"FLASHINFER_MLA_SPARSE_DSV4 on SM120 requires a FlashInfer "
|
||||
"DSV4 sparse MLA decode specialization for "
|
||||
f"(num_q_heads={self.padded_heads}, top_k={required_topk}). "
|
||||
"Install a FlashInfer build containing "
|
||||
"flashinfer-ai/flashinfer#4380."
|
||||
)
|
||||
self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe(
|
||||
self._o_proj_block_size
|
||||
)
|
||||
# Per-tensor FP8 cache path scales.
|
||||
if self.kv_cache_torch_dtype != torch.float8_e4m3fn:
|
||||
return
|
||||
fp8_q_scale = 1.0
|
||||
fp8_kv_scale = 1.0
|
||||
self.register_buffer(
|
||||
"_flashinfer_fp8_q_scale",
|
||||
torch.tensor([fp8_q_scale], dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
self.register_buffer(
|
||||
"_flashinfer_fp8_q_scale_inv",
|
||||
torch.tensor([1.0 / fp8_q_scale], dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
self.register_buffer(
|
||||
"_flashinfer_fp8_kv_scale",
|
||||
torch.tensor([fp8_kv_scale], dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
# FlashInfer expects scalar scale arguments for this path.
|
||||
self._flashinfer_fp8_bmm1_scale = self.scale * fp8_q_scale * fp8_kv_scale
|
||||
self._flashinfer_fp8_bmm2_scale = fp8_kv_scale
|
||||
|
||||
def _reserve_empty_forward_workspace(self) -> None:
|
||||
self._get_workspace(
|
||||
torch.device("cuda", torch.accelerator.current_device_index())
|
||||
)
|
||||
|
||||
def _forward_sparse_impl(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
flashmla_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
self_kv_cache: torch.Tensor | None,
|
||||
swa_kv_cache: torch.Tensor,
|
||||
swa_only: bool,
|
||||
) -> None:
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
if swa_metadata.num_prefills > 0:
|
||||
self._forward_prefill(
|
||||
q=q[num_decode_tokens:],
|
||||
compressed_k_cache=self_kv_cache,
|
||||
swa_k_cache=swa_kv_cache,
|
||||
output=output[num_decode_tokens:],
|
||||
attn_metadata=flashmla_metadata,
|
||||
swa_metadata=swa_metadata,
|
||||
)
|
||||
if swa_metadata.num_decodes > 0:
|
||||
self._forward_decode(
|
||||
q=q[:num_decode_tokens],
|
||||
kv_cache=self_kv_cache,
|
||||
swa_metadata=swa_metadata,
|
||||
attn_metadata=flashmla_metadata,
|
||||
swa_only=swa_only,
|
||||
output=output[:num_decode_tokens],
|
||||
)
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
# Output may be padded to backend-supported head counts.
|
||||
assert output.shape[0] == q.shape[0] and output.shape[-1] == q.shape[-1], (
|
||||
f"output buffer shape {output.shape} incompatible with q shape {q.shape}"
|
||||
)
|
||||
assert output.shape[1] >= q.shape[1], (
|
||||
f"output heads {output.shape[1]} must be >= q heads {q.shape[1]}"
|
||||
)
|
||||
# Per-tensor FP8 q produces a bf16 attention output.
|
||||
expected_output_dtype = (
|
||||
torch.bfloat16 if q.dtype == torch.float8_e4m3fn else q.dtype
|
||||
)
|
||||
assert output.dtype == expected_output_dtype, (
|
||||
f"output dtype {output.dtype} must match expected {expected_output_dtype} "
|
||||
f"for q dtype {q.dtype}"
|
||||
)
|
||||
|
||||
forward_context = get_forward_context()
|
||||
attn_metadata = forward_context.attn_metadata
|
||||
if attn_metadata is None:
|
||||
self._reserve_empty_forward_workspace()
|
||||
output.zero_()
|
||||
return
|
||||
|
||||
assert isinstance(attn_metadata, dict)
|
||||
# Compressed-cache metadata lives on the kv-source layer's prefix;
|
||||
# consumers share that cache and its block table.
|
||||
flashmla_metadata = cast(
|
||||
DeepseekV4FlashMLAMetadata | None,
|
||||
attn_metadata.get(self.compressed_cache_prefix)
|
||||
if self.compressed_cache_prefix is not None
|
||||
else None,
|
||||
)
|
||||
swa_metadata = cast(
|
||||
"DeepseekSparseSWAMetadata | None",
|
||||
attn_metadata.get(self.swa_cache_layer.prefix),
|
||||
)
|
||||
assert swa_metadata is not None
|
||||
|
||||
swa_only = self.compress_ratio == 0
|
||||
# SWA-only layers have no compressed KV cache; consumers read the kv
|
||||
# source's cache.
|
||||
self_kv_cache = None if swa_only else self._compressed_kv_cache()
|
||||
swa_kv_cache = self.swa_cache_layer.kv_cache
|
||||
|
||||
self._forward_sparse_impl(
|
||||
q=q,
|
||||
output=output,
|
||||
flashmla_metadata=flashmla_metadata,
|
||||
swa_metadata=swa_metadata,
|
||||
self_kv_cache=self_kv_cache,
|
||||
swa_kv_cache=swa_kv_cache,
|
||||
swa_only=swa_only,
|
||||
)
|
||||
|
||||
def _prepare_query(self, q: torch.Tensor, output: torch.Tensor) -> torch.Tensor:
|
||||
if self.kv_cache_torch_dtype == torch.float8_e4m3fn:
|
||||
assert q.dtype == torch.float8_e4m3fn
|
||||
q = q.to(torch.bfloat16)
|
||||
else:
|
||||
assert q.dtype == torch.bfloat16
|
||||
padded_heads = output.shape[1]
|
||||
if q.shape[1] < padded_heads:
|
||||
padded_query = q.new_zeros((q.shape[0], padded_heads, q.shape[2]))
|
||||
padded_query[:, : q.shape[1], :] = q
|
||||
q = padded_query
|
||||
return q.contiguous()
|
||||
|
||||
def _forward_decode(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
kv_cache: torch.Tensor | None,
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_only: bool,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
|
||||
extra_sparse_indices = None
|
||||
extra_sparse_lengths = None
|
||||
if not swa_only:
|
||||
if attn_metadata is None:
|
||||
raise RuntimeError(
|
||||
"Sparse MLA metadata is required for compressed layers."
|
||||
)
|
||||
if swa_metadata.is_valid_token is None:
|
||||
raise RuntimeError(
|
||||
"SWA validity metadata is required for compressed layers."
|
||||
)
|
||||
if self.topk_indices_buffer is None:
|
||||
raise RuntimeError(
|
||||
"Compressed-layer decode requires top-k indices from the indexer."
|
||||
)
|
||||
# Local indices filled by the index-source layer's indexer.
|
||||
is_valid = swa_metadata.is_valid_token[:num_decode_tokens]
|
||||
block_size = attn_metadata.block_size // self.compress_ratio
|
||||
global_indices, extra_sparse_lengths = compute_global_topk_indices_and_lens(
|
||||
self.topk_indices_buffer[:num_decode_tokens],
|
||||
swa_metadata.token_to_req_indices,
|
||||
attn_metadata.block_table[:num_decodes],
|
||||
block_size,
|
||||
is_valid,
|
||||
)
|
||||
extra_sparse_indices = global_indices.view(num_decode_tokens, 1, -1)
|
||||
|
||||
swa_indices = swa_metadata.decode_swa_indices
|
||||
swa_lens = swa_metadata.decode_swa_lens
|
||||
assert swa_indices is not None
|
||||
assert swa_lens is not None
|
||||
q = self._prepare_query(q, output)
|
||||
swa_cache = self._as_sparse_cache(self.swa_cache_layer.kv_cache)
|
||||
extra_cache = self._as_sparse_cache(kv_cache) if kv_cache is not None else None
|
||||
if extra_cache is not None and extra_sparse_indices is None:
|
||||
raise RuntimeError(
|
||||
"Compressed sparse MLA decode requires compressed sparse indices."
|
||||
)
|
||||
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
|
||||
query=q,
|
||||
swa_kv_cache=swa_cache,
|
||||
workspace_buffer=self._get_workspace(q.device),
|
||||
sparse_indices=swa_indices,
|
||||
compressed_kv_cache=extra_cache,
|
||||
out=output,
|
||||
bmm1_scale=self.scale,
|
||||
sinks=self.attn_sink,
|
||||
kv_layout="NHD",
|
||||
swa_topk_lens=swa_lens,
|
||||
extra_sparse_indices=extra_sparse_indices,
|
||||
extra_sparse_topk_lens=extra_sparse_lengths,
|
||||
)
|
||||
|
||||
def _forward_prefill(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
compressed_k_cache: torch.Tensor | None,
|
||||
swa_k_cache: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
) -> None:
|
||||
swa_only = self.compress_ratio == 0
|
||||
|
||||
num_prefills = swa_metadata.num_prefills
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
num_prefill_tokens = swa_metadata.num_prefill_tokens
|
||||
|
||||
query_start_loc_cpu = swa_metadata.query_start_loc_cpu
|
||||
assert query_start_loc_cpu is not None
|
||||
prefill_token_base = query_start_loc_cpu[num_decodes]
|
||||
|
||||
extra_sparse_indices: torch.Tensor | None = None
|
||||
extra_sparse_lengths: torch.Tensor | None = None
|
||||
if not swa_only:
|
||||
if self.topk_indices_buffer is None:
|
||||
raise RuntimeError(
|
||||
"Compressed-layer prefill requires top-k indices from the indexer."
|
||||
)
|
||||
if attn_metadata is None:
|
||||
raise RuntimeError("Compressed-layer prefill metadata is missing.")
|
||||
if swa_metadata.token_to_req_indices is None:
|
||||
raise RuntimeError(
|
||||
"Compressed-layer prefill request mapping is missing."
|
||||
)
|
||||
if swa_metadata.is_valid_token is None:
|
||||
raise RuntimeError(
|
||||
"Compressed-layer prefill validity metadata is missing."
|
||||
)
|
||||
# Local indices filled by the index-source layer's indexer.
|
||||
local_topk_indices = self.topk_indices_buffer[
|
||||
num_decode_tokens : num_decode_tokens + num_prefill_tokens
|
||||
]
|
||||
prefill_token_slice = slice(
|
||||
num_decode_tokens, num_decode_tokens + num_prefill_tokens
|
||||
)
|
||||
block_size = attn_metadata.block_size // self.compress_ratio
|
||||
extra_sparse_indices, extra_sparse_lengths = (
|
||||
compute_global_topk_indices_and_lens(
|
||||
local_topk_indices,
|
||||
swa_metadata.token_to_req_indices[prefill_token_slice],
|
||||
attn_metadata.block_table,
|
||||
block_size,
|
||||
swa_metadata.is_valid_token[prefill_token_slice],
|
||||
)
|
||||
)
|
||||
|
||||
assert swa_metadata.prefill_swa_indices is not None
|
||||
assert swa_metadata.prefill_swa_lens is not None
|
||||
|
||||
q = self._prepare_query(q, output)
|
||||
swa_kv_paged = self._as_sparse_cache(swa_k_cache)
|
||||
if swa_only:
|
||||
extra_kv_paged = None
|
||||
else:
|
||||
if compressed_k_cache is None:
|
||||
raise RuntimeError(
|
||||
"Compressed sparse MLA layers require their compressed KV cache."
|
||||
)
|
||||
extra_kv_paged = self._as_sparse_cache(compressed_k_cache)
|
||||
|
||||
num_chunks = (
|
||||
num_prefills + self.PREFILL_CHUNK_SIZE - 1
|
||||
) // self.PREFILL_CHUNK_SIZE
|
||||
for chunk_idx in range(num_chunks):
|
||||
chunk_start = chunk_idx * self.PREFILL_CHUNK_SIZE
|
||||
chunk_end = min(chunk_start + self.PREFILL_CHUNK_SIZE, num_prefills)
|
||||
query_start = (
|
||||
query_start_loc_cpu[num_decodes + chunk_start] - prefill_token_base
|
||||
)
|
||||
query_end = (
|
||||
query_start_loc_cpu[num_decodes + chunk_end] - prefill_token_base
|
||||
)
|
||||
|
||||
extra_sparse_indices_chunk = (
|
||||
extra_sparse_indices[query_start:query_end]
|
||||
if extra_sparse_indices is not None
|
||||
else None
|
||||
)
|
||||
extra_sparse_lengths_chunk = (
|
||||
extra_sparse_lengths[query_start:query_end]
|
||||
if extra_sparse_lengths is not None
|
||||
else None
|
||||
)
|
||||
|
||||
q_chunk = q[query_start:query_end]
|
||||
swa_indices_chunk = swa_metadata.prefill_swa_indices[query_start:query_end]
|
||||
swa_lens_chunk = swa_metadata.prefill_swa_lens[query_start:query_end]
|
||||
if extra_kv_paged is not None and extra_sparse_indices_chunk is None:
|
||||
raise RuntimeError(
|
||||
"Compressed sparse MLA prefill requires compressed sparse indices."
|
||||
)
|
||||
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
|
||||
query=q_chunk,
|
||||
swa_kv_cache=swa_kv_paged,
|
||||
workspace_buffer=self._get_workspace(q.device),
|
||||
sparse_indices=swa_indices_chunk,
|
||||
compressed_kv_cache=extra_kv_paged,
|
||||
out=output[query_start:query_end],
|
||||
bmm1_scale=self.scale,
|
||||
sinks=self.attn_sink,
|
||||
kv_layout="NHD",
|
||||
swa_topk_lens=swa_lens_chunk,
|
||||
extra_sparse_indices=extra_sparse_indices_chunk,
|
||||
extra_sparse_topk_lens=extra_sparse_lengths_chunk,
|
||||
)
|
||||
@@ -0,0 +1,387 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import TYPE_CHECKING, ClassVar, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
|
||||
compute_fp8_einsum_recipe,
|
||||
deep_gemm_fp8_o_proj,
|
||||
)
|
||||
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
|
||||
from vllm.models.deepseek_v41.common.ops import (
|
||||
combine_topk_swa_indices,
|
||||
compute_global_topk_indices_and_lens,
|
||||
dequantize_and_gather_k_cache,
|
||||
)
|
||||
from vllm.models.deepseek_v41.sparse_mla import (
|
||||
DeepseekV4FlashMLABackend,
|
||||
DeepseekV4FlashMLAMetadata,
|
||||
DeepseekV41SparseSWAMetadataBuilder,
|
||||
)
|
||||
from vllm.utils.math_utils import round_up
|
||||
from vllm.v1.attention.backend import AttentionCGSupport
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWABackend
|
||||
from vllm.v1.attention.ops.flashmla import (
|
||||
flash_mla_sparse_fwd,
|
||||
flash_mla_with_kvcache,
|
||||
)
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
|
||||
|
||||
|
||||
class DeepseekSparseSWAFlashMLAMetadataBuilder(DeepseekV41SparseSWAMetadataBuilder):
|
||||
"""SWA metadata for the FlashMLA decode path, which allows varlen decode."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
|
||||
|
||||
class DeepseekSparseSWAFlashMLABackend(DeepseekSparseSWABackend):
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[DeepseekSparseSWAFlashMLAMetadataBuilder]:
|
||||
return DeepseekSparseSWAFlashMLAMetadataBuilder
|
||||
|
||||
|
||||
class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
|
||||
"""FlashMLA sparse MLA attention layer for DeepSeek V4.1 (CUDA)."""
|
||||
|
||||
backend_cls = DeepseekV4FlashMLABackend
|
||||
swa_backend_cls = DeepseekSparseSWAFlashMLABackend
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe(
|
||||
self._o_proj_block_size
|
||||
)
|
||||
|
||||
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
|
||||
return deep_gemm_fp8_o_proj(
|
||||
o,
|
||||
positions,
|
||||
self.rotary_emb.cos_sin_cache,
|
||||
self.wo_a,
|
||||
self.wo_b,
|
||||
n_groups=self.n_local_groups,
|
||||
heads_per_group=self.n_local_heads // self.n_local_groups,
|
||||
nope_dim=self.nope_head_dim,
|
||||
rope_dim=self.rope_head_dim,
|
||||
o_lora_rank=self.o_lora_rank,
|
||||
einsum_recipe=self._einsum_recipe,
|
||||
tma_aligned_scales=self._tma_aligned_scales,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_padded_num_q_heads(cls, num_heads: int) -> int:
|
||||
# FP8 decode kernel only supports h_q = 64 or 128.
|
||||
if num_heads > 128:
|
||||
raise ValueError(
|
||||
f"DeepseekV4 FlashMLA does not support {num_heads} heads "
|
||||
"(FP8 decode kernel requires h_q in {64, 128})."
|
||||
)
|
||||
return 64 if num_heads <= 64 else 128
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
assert output.shape == q.shape, (
|
||||
f"output buffer shape {output.shape} must match q shape {q.shape}"
|
||||
)
|
||||
assert output.dtype == q.dtype, (
|
||||
f"output buffer dtype {output.dtype} must match q dtype {q.dtype}"
|
||||
)
|
||||
|
||||
# Get SWA and indexer metadata from forward context
|
||||
forward_context = get_forward_context()
|
||||
attn_metadata = forward_context.attn_metadata
|
||||
|
||||
if attn_metadata is None:
|
||||
# Warmup dummy run: no real metadata. Reserve the same bf16
|
||||
# gather workspace _forward_prefill would; the dequantize / topk
|
||||
# / sparse_fwd kernels are skipped this step.
|
||||
swa_only = self.compress_ratio == 0
|
||||
N = (
|
||||
0
|
||||
if swa_only
|
||||
else (self.max_model_len + self.compress_ratio - 1)
|
||||
// self.compress_ratio
|
||||
)
|
||||
M = N + self.window_size + self.max_num_batched_tokens
|
||||
if swa_only:
|
||||
top_k = 0
|
||||
else:
|
||||
assert self.topk_indices_buffer is not None
|
||||
top_k = self.topk_indices_buffer.shape[-1]
|
||||
combined_topk = round_up(
|
||||
top_k + self.window_size + self.max_image_tokens, 128
|
||||
)
|
||||
current_workspace_manager().get_simultaneous(
|
||||
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
|
||||
((self.max_num_batched_tokens, combined_topk), torch.int32),
|
||||
((self.max_num_batched_tokens,), torch.int32),
|
||||
)
|
||||
output.zero_()
|
||||
return
|
||||
|
||||
assert isinstance(attn_metadata, dict)
|
||||
# Compressed-cache metadata lives on the kv-source layer's prefix;
|
||||
# consumers share that cache and its block table.
|
||||
flashmla_metadata = cast(
|
||||
DeepseekV4FlashMLAMetadata | None,
|
||||
attn_metadata.get(self.compressed_cache_prefix)
|
||||
if self.compressed_cache_prefix is not None
|
||||
else None,
|
||||
)
|
||||
swa_metadata = cast(
|
||||
"DeepseekSparseSWAMetadata | None",
|
||||
attn_metadata.get(self.swa_cache_layer.prefix),
|
||||
)
|
||||
assert swa_metadata is not None
|
||||
|
||||
swa_only = self.compress_ratio == 0
|
||||
# SWA-only layers (compress_ratio == 0) don't have their own KV cache
|
||||
# allocation; consumers read the kv source's cache, which is bound on
|
||||
# the source layer.
|
||||
self_kv_cache = None if swa_only else self._compressed_kv_cache()
|
||||
swa_kv_cache = self.swa_cache_layer.kv_cache
|
||||
|
||||
# Split prefill and decode
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_prefills = swa_metadata.num_prefills
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
|
||||
if num_prefills > 0:
|
||||
self._forward_prefill(
|
||||
q=q[num_decode_tokens:],
|
||||
positions=positions[num_decode_tokens:],
|
||||
compressed_k_cache=self_kv_cache,
|
||||
swa_k_cache=swa_kv_cache,
|
||||
output=output[num_decode_tokens:],
|
||||
attn_metadata=flashmla_metadata,
|
||||
swa_metadata=swa_metadata,
|
||||
)
|
||||
if num_decodes > 0:
|
||||
self._forward_decode(
|
||||
q=q[:num_decode_tokens],
|
||||
kv_cache=self_kv_cache,
|
||||
swa_metadata=swa_metadata,
|
||||
attn_metadata=flashmla_metadata,
|
||||
swa_only=swa_only,
|
||||
output=output[:num_decode_tokens],
|
||||
)
|
||||
|
||||
def _forward_decode(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
kv_cache: torch.Tensor | None, # None for SWA-only layers
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_only: bool,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
|
||||
topk_indices = None
|
||||
topk_lens = None
|
||||
if not swa_only:
|
||||
# Local indices filled by the index-source layer's indexer.
|
||||
assert attn_metadata is not None
|
||||
assert swa_metadata.is_valid_token is not None
|
||||
assert self.topk_indices_buffer is not None
|
||||
block_size = attn_metadata.block_size // self.compress_ratio
|
||||
is_valid = swa_metadata.is_valid_token[:num_decode_tokens]
|
||||
global_indices, topk_lens = compute_global_topk_indices_and_lens(
|
||||
self.topk_indices_buffer[:num_decode_tokens],
|
||||
swa_metadata.token_to_req_indices,
|
||||
attn_metadata.block_table[:num_decodes],
|
||||
block_size,
|
||||
is_valid,
|
||||
)
|
||||
topk_indices = global_indices.view(num_decode_tokens, 1, -1)
|
||||
|
||||
swa_indices = swa_metadata.decode_swa_indices
|
||||
swa_lens = swa_metadata.decode_swa_lens
|
||||
|
||||
# We treat queries in the same seq as different queries
|
||||
# and later we only attend by generated indices.
|
||||
# q arrives pre-padded to self.padded_heads by the outer wrapper.
|
||||
q = q.unsqueeze(1)
|
||||
|
||||
# Prepare SWA cache (num_blocks, swa_block_size, 1, head_bytes)
|
||||
# Use unsqueeze to preserve strides (handles padded blocks correctly)
|
||||
swa_cache = self.swa_cache_layer.kv_cache.unsqueeze(-2)
|
||||
# Reshape KV cache to (num_blocks, block_size, 1, head_bytes)
|
||||
if kv_cache is not None:
|
||||
kv_cache = kv_cache.unsqueeze(-2)
|
||||
|
||||
# One FlashMLASchedMeta per layer type, shared across all same-type
|
||||
# layers within this decode step. The first forward call per type
|
||||
# triggers the in-kernel planner (allocating tile_scheduler_metadata
|
||||
# and num_splits via PyTorch's graph-aware allocator so CUDA graph
|
||||
# capture reuses the same addresses on replay); subsequent same-type
|
||||
# layers see have_initialized=True and skip the planner.
|
||||
tile_metadata = {
|
||||
0: swa_metadata.tile_sched_swaonly,
|
||||
1: swa_metadata.tile_sched_c1a,
|
||||
2: swa_metadata.tile_sched_c2a,
|
||||
}[self.compress_ratio]
|
||||
assert tile_metadata is not None, (
|
||||
"swa_metadata missing tile_sched entry for "
|
||||
f"compress_ratio={self.compress_ratio}; "
|
||||
"DeepseekSparseSWAMetadataBuilder.build_tile_scheduler did not "
|
||||
"allocate one for this layer type."
|
||||
)
|
||||
|
||||
out, _ = flash_mla_with_kvcache(
|
||||
q=q,
|
||||
k_cache=swa_cache,
|
||||
block_table=None,
|
||||
head_dim_v=512,
|
||||
tile_scheduler_metadata=tile_metadata,
|
||||
cache_seqlens=None,
|
||||
is_fp8_kvcache=True,
|
||||
indices=swa_indices,
|
||||
topk_length=swa_lens,
|
||||
softmax_scale=self.scale,
|
||||
attn_sink=self.attn_sink,
|
||||
extra_k_cache=kv_cache if not swa_only else None,
|
||||
extra_indices_in_kvcache=topk_indices,
|
||||
extra_topk_length=topk_lens,
|
||||
out=output.unsqueeze(1),
|
||||
)
|
||||
|
||||
def _forward_prefill(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
compressed_k_cache: torch.Tensor | None, # None for SWA-only layers
|
||||
swa_k_cache: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
swa_metadata: "DeepseekSparseSWAMetadata",
|
||||
) -> None:
|
||||
swa_only = self.compress_ratio == 0
|
||||
|
||||
num_prefill_tokens = swa_metadata.num_prefill_tokens
|
||||
num_decodes = swa_metadata.num_decodes
|
||||
num_decode_tokens = swa_metadata.num_decode_tokens
|
||||
|
||||
# Use pre-computed prefill metadata.
|
||||
seq_lens = swa_metadata.prefill_seq_lens
|
||||
gather_lens = swa_metadata.prefill_gather_lens
|
||||
assert seq_lens is not None
|
||||
assert gather_lens is not None
|
||||
|
||||
# Derive prefill-local token offsets from the full query_start_loc_cpu.
|
||||
query_start_loc_cpu = swa_metadata.query_start_loc_cpu
|
||||
query_start_loc = swa_metadata.query_start_loc
|
||||
assert query_start_loc_cpu is not None
|
||||
assert query_start_loc is not None
|
||||
prefill_token_base = query_start_loc_cpu[num_decodes]
|
||||
|
||||
# Local indices filled by the index source; SWA-only layers pass
|
||||
# top_k=0 and never read them.
|
||||
assert self.topk_indices_buffer is not None
|
||||
topk_indices = self.topk_indices_buffer[num_decode_tokens:]
|
||||
topk_indices = topk_indices[:num_prefill_tokens]
|
||||
top_k = 0 if swa_only else topk_indices.shape[-1]
|
||||
chunk_plan = swa_metadata.get_prefill_chunk_plan(
|
||||
compress_ratio=self.compress_ratio,
|
||||
prefill_chunk_size=self.PREFILL_CHUNK_SIZE,
|
||||
# v4.1: every cr>0 layer (including cr==1) gathers a full-length
|
||||
# compressed region; only cr==0 layers are SWA-only.
|
||||
has_compressed=not swa_only,
|
||||
)
|
||||
assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0"
|
||||
workspace_manager = current_workspace_manager()
|
||||
combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128)
|
||||
for chunk_start, chunk_end, chunk_N, chunk_M in chunk_plan:
|
||||
chunk_size = chunk_end - chunk_start
|
||||
workspace = workspace_manager.get_simultaneous(
|
||||
((chunk_size, chunk_M, q.shape[-1]), torch.bfloat16),
|
||||
((self.max_num_batched_tokens, combined_topk), torch.int32),
|
||||
((self.max_num_batched_tokens,), torch.int32),
|
||||
)
|
||||
kv, combined_indices_out, combined_lens_out = workspace
|
||||
if not swa_only:
|
||||
# Gather compressed KV
|
||||
assert attn_metadata is not None
|
||||
block_table = attn_metadata.block_table[num_decodes:]
|
||||
dequantize_and_gather_k_cache(
|
||||
kv[:chunk_size],
|
||||
compressed_k_cache,
|
||||
seq_lens=seq_lens[chunk_start:chunk_end] // self.compress_ratio,
|
||||
gather_lens=None,
|
||||
block_table=block_table[chunk_start:chunk_end],
|
||||
block_size=attn_metadata.block_size // self.compress_ratio,
|
||||
offset=0,
|
||||
)
|
||||
|
||||
# Gather SWA KV
|
||||
swa_block_table = swa_metadata.block_table[num_decodes:]
|
||||
dequantize_and_gather_k_cache(
|
||||
kv[:chunk_size],
|
||||
swa_k_cache,
|
||||
seq_lens=seq_lens[chunk_start:chunk_end],
|
||||
gather_lens=gather_lens[chunk_start:chunk_end],
|
||||
block_table=swa_block_table[chunk_start:chunk_end],
|
||||
block_size=swa_metadata.block_size,
|
||||
offset=chunk_N,
|
||||
)
|
||||
|
||||
# Combine the topk indices and SWA indices for gathered KV cache
|
||||
query_start = (
|
||||
query_start_loc_cpu[num_decodes + chunk_start] - prefill_token_base
|
||||
)
|
||||
query_end = (
|
||||
query_start_loc_cpu[num_decodes + chunk_end] - prefill_token_base
|
||||
)
|
||||
combined_indices_out = combined_indices_out[: query_end - query_start]
|
||||
combined_lens_out = combined_lens_out[: query_end - query_start]
|
||||
|
||||
combined_indices, combined_lens = combine_topk_swa_indices(
|
||||
topk_indices[query_start:query_end],
|
||||
query_start_loc[
|
||||
num_decodes + chunk_start : num_decodes + chunk_end + 1
|
||||
],
|
||||
seq_lens[chunk_start:chunk_end],
|
||||
gather_lens[chunk_start:chunk_end],
|
||||
self.window_size,
|
||||
self.compress_ratio,
|
||||
top_k,
|
||||
chunk_M,
|
||||
chunk_N,
|
||||
out=(combined_indices_out, combined_lens_out),
|
||||
left_visible=(
|
||||
swa_metadata.prefill_left_visible[
|
||||
num_decode_tokens + query_start : num_decode_tokens + query_end
|
||||
]
|
||||
if swa_metadata.prefill_left_visible is not None
|
||||
else None
|
||||
),
|
||||
right_visible=(
|
||||
swa_metadata.prefill_right_visible[
|
||||
num_decode_tokens + query_start : num_decode_tokens + query_end
|
||||
]
|
||||
if swa_metadata.prefill_right_visible is not None
|
||||
else None
|
||||
),
|
||||
max_image_tokens=self.max_image_tokens,
|
||||
)
|
||||
flash_mla_sparse_fwd(
|
||||
q=q[query_start:query_end],
|
||||
kv=kv.view(-1, 1, q.shape[-1]),
|
||||
indices=combined_indices.unsqueeze(1),
|
||||
sm_scale=self.scale,
|
||||
attn_sink=self.attn_sink,
|
||||
topk_length=combined_lens,
|
||||
out=output[query_start:query_end],
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,98 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _gather_lookback_kernel(
|
||||
lookback_ptr,
|
||||
idx_mapping_ptr,
|
||||
num_computed_tokens_ptr,
|
||||
all_token_ids_ptr,
|
||||
all_token_ids_stride,
|
||||
num_reqs,
|
||||
DEPTH: tl.constexpr,
|
||||
BLOCK_DEPTH: tl.constexpr,
|
||||
):
|
||||
# One program per lookback row; rows past the batch are filled with -1.
|
||||
batch_idx = tl.program_id(0)
|
||||
in_batch = batch_idx < num_reqs
|
||||
req_state_idx = tl.load(idx_mapping_ptr + batch_idx, mask=in_batch, other=0)
|
||||
num_computed = tl.load(num_computed_tokens_ptr + req_state_idx)
|
||||
|
||||
offs = tl.arange(0, BLOCK_DEPTH)
|
||||
pos = num_computed - 1 - offs
|
||||
valid = in_batch & (offs < DEPTH) & (pos >= 0)
|
||||
ids = tl.load(
|
||||
all_token_ids_ptr + req_state_idx * all_token_ids_stride + pos,
|
||||
mask=valid,
|
||||
other=-1,
|
||||
)
|
||||
tl.store(lookback_ptr + batch_idx * DEPTH + offs, ids, mask=offs < DEPTH)
|
||||
|
||||
|
||||
class DeepseekV41ModelState(DefaultModelState):
|
||||
"""DefaultModelState plus the engram lookback window.
|
||||
|
||||
The engram n-gram hash needs the ids of the ``depth`` tokens preceding
|
||||
each request's chunk start (see ``common/engram.py``). The runner keeps
|
||||
the full token history on device, so the window is gathered there every
|
||||
step: exact for prompt and generated tokens alike, whatever instance
|
||||
produced their KV.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
model: nn.Module,
|
||||
encoder_cache: EncoderCache | None,
|
||||
device: torch.device,
|
||||
):
|
||||
super().__init__(vllm_config, model, encoder_cache, device)
|
||||
depth = model.token_lookback_depth
|
||||
self.lookback_token_ids: torch.Tensor | None = None
|
||||
if depth > 0:
|
||||
# Persistent so a captured graph can read it on replay.
|
||||
self.lookback_token_ids = torch.full(
|
||||
(self.max_num_reqs, depth), -1, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
def prepare_inputs(
|
||||
self, input_batch: InputBatch, req_states: RequestState
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
model_inputs = super().prepare_inputs(input_batch, req_states)
|
||||
window = self.lookback_token_ids
|
||||
if window is None:
|
||||
return model_inputs
|
||||
all_token_ids = req_states.all_token_ids.gpu
|
||||
depth = window.shape[1]
|
||||
_gather_lookback_kernel[(window.shape[0],)](
|
||||
window,
|
||||
input_batch.idx_mapping,
|
||||
req_states.num_computed_tokens.gpu,
|
||||
all_token_ids,
|
||||
all_token_ids.stride(0),
|
||||
input_batch.idx_mapping.shape[0],
|
||||
DEPTH=depth,
|
||||
BLOCK_DEPTH=triton.next_power_of_2(depth),
|
||||
)
|
||||
model_inputs["lookback_token_ids"] = window
|
||||
return model_inputs
|
||||
|
||||
def prepare_dummy_inputs(self, num_reqs: int, num_tokens: int) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_dummy_inputs(num_reqs, num_tokens)
|
||||
if self.lookback_token_ids is not None:
|
||||
# The captured graph reads this buffer; replays refill it in place.
|
||||
self.lookback_token_ids.fill_(-1)
|
||||
model_inputs["lookback_token_ids"] = self.lookback_token_ids
|
||||
return model_inputs
|
||||
@@ -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 .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()
|
||||
@@ -0,0 +1,229 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Quantization config for DeepSeek V4."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.config.quantization import QuantSpec
|
||||
from vllm.model_executor.layers.fused_moe import (
|
||||
RoutedExperts,
|
||||
UnquantizedFusedMoEMethod,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
|
||||
from vllm.model_executor.layers.quantization import QuantizationMethods
|
||||
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
|
||||
from vllm.model_executor.layers.quantization.mxfp4 import Mxfp4MoEMethod
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
is_layer_skipped,
|
||||
kMxfp8Dynamic,
|
||||
kMxfp8Static,
|
||||
)
|
||||
|
||||
_DEEPSEEK_V4_EXPERT_DTYPES = ("fp4", "fp8")
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptNvFp4Config,
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4FP8Config(Fp8Config):
|
||||
"""FP8 config for DeepSeek V4 with expert-dtype-aware MoE dispatch.
|
||||
|
||||
DeepSeek V4 checkpoints always use FP8 block quantization for
|
||||
linear/attention layers. The MoE expert weights vary by checkpoint:
|
||||
- ``expert_dtype="fp4"`` (e.g. DeepSeek-V4-Flash): MXFP4 experts
|
||||
with ue8m0 (e8m0fnu) FP8 linear scales.
|
||||
- ``expert_dtype="fp8"`` (e.g. DeepSeek-V4-Flash-Base): FP8 block
|
||||
experts with float32 FP8 linear scales.
|
||||
|
||||
The dispatch and the linear scale dtype are both keyed off
|
||||
``expert_dtype`` from the model's hf_config; missing values default
|
||||
to ``"fp4"`` so existing FP4 checkpoints stay unchanged.
|
||||
|
||||
NOTE: ``expert_dtype`` is resolved lazily because this config is
|
||||
constructed during VllmConfig setup, before ``set_current_vllm_config``
|
||||
is active. Reading hf_config eagerly in ``__init__`` would always see
|
||||
the default ``"fp4"`` and silently misroute Flash-Base checkpoints.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._resolved_expert_dtype: str | None = None
|
||||
self._resolved_moe_quant_algo: str | None = None
|
||||
self._nvfp4_config: ModelOptNvFp4Config | None = None
|
||||
# ``is_scale_e8m0`` is a property that resolves on first read,
|
||||
# by which time the current vllm_config has been set.
|
||||
|
||||
@property
|
||||
def expert_dtype(self) -> str:
|
||||
if self._resolved_expert_dtype is None:
|
||||
try:
|
||||
hf_config = get_current_vllm_config().model_config.hf_config
|
||||
except Exception:
|
||||
# vllm_config not yet set; defer the decision until a
|
||||
# later call lands inside set_current_vllm_config.
|
||||
return "fp4"
|
||||
expert_dtype = getattr(hf_config, "expert_dtype", "fp4")
|
||||
if expert_dtype not in _DEEPSEEK_V4_EXPERT_DTYPES:
|
||||
raise ValueError(
|
||||
f"Unsupported DeepSeek V4 expert_dtype={expert_dtype!r}; "
|
||||
f"expected one of {_DEEPSEEK_V4_EXPERT_DTYPES}."
|
||||
)
|
||||
self._resolved_expert_dtype = expert_dtype
|
||||
from vllm.logger import init_logger
|
||||
|
||||
init_logger(__name__).info_once(
|
||||
"DeepSeek V4 expert_dtype resolved to %r", expert_dtype
|
||||
)
|
||||
return self._resolved_expert_dtype
|
||||
|
||||
@property
|
||||
def is_scale_e8m0(self) -> bool:
|
||||
# FP4 checkpoints store FP8 linear scales as e8m0fnu; FP8 expert
|
||||
# checkpoints (Flash-Base) store them as float32.
|
||||
return self.expert_dtype == "fp4"
|
||||
|
||||
def _resolve_moe_overrides(self) -> None:
|
||||
if self._resolved_moe_quant_algo is not None:
|
||||
return
|
||||
try:
|
||||
hf_config = get_current_vllm_config().model_config.hf_config
|
||||
except Exception:
|
||||
return
|
||||
quant_cfg = getattr(hf_config, "quantization_config", None) or {}
|
||||
algo = (quant_cfg.get("moe_quant_algo") or "").upper() or None
|
||||
self._resolved_moe_quant_algo = algo or ""
|
||||
|
||||
@property
|
||||
def moe_quant_algo(self) -> str:
|
||||
self._resolve_moe_overrides()
|
||||
return self._resolved_moe_quant_algo or ""
|
||||
|
||||
def _get_nvfp4_config(self) -> ModelOptNvFp4Config:
|
||||
if self._nvfp4_config is None:
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptNvFp4Config,
|
||||
)
|
||||
|
||||
self._nvfp4_config = ModelOptNvFp4Config(
|
||||
is_checkpoint_nvfp4_serialized=True,
|
||||
kv_cache_quant_algo=None,
|
||||
exclude_modules=[],
|
||||
group_size=16,
|
||||
)
|
||||
return self._nvfp4_config
|
||||
|
||||
@classmethod
|
||||
def get_name(cls) -> QuantizationMethods:
|
||||
return "deepseek_v4_fp8"
|
||||
|
||||
@staticmethod
|
||||
def _is_quark_mxfp4_ocp(hf_quant_cfg: dict) -> bool:
|
||||
"""True for AMD-Quark exports whose global scheme is MXFP4."""
|
||||
weight = (hf_quant_cfg.get("global_quant_config") or {}).get("weight")
|
||||
# A non-dict weight (e.g. a list of multiple specs) means not an OCP
|
||||
# MXFP4 scheme (e.g. NVFP4 with 2-level scale).
|
||||
if not isinstance(weight, dict):
|
||||
return False
|
||||
return (
|
||||
weight.get("dtype") == "fp4"
|
||||
and weight.get("qscheme") == "per_group"
|
||||
and weight.get("group_size") == 32
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def override_quantization_method(
|
||||
cls, hf_quant_cfg, user_quant, hf_config=None
|
||||
) -> QuantizationMethods | None:
|
||||
if not (
|
||||
isinstance(hf_quant_cfg, dict)
|
||||
and (
|
||||
hf_quant_cfg.get("quant_method") in ("fp8", "deepseek_v4_fp8")
|
||||
or (
|
||||
hf_quant_cfg.get("quant_method") == "quark"
|
||||
and cls._is_quark_mxfp4_ocp(hf_quant_cfg)
|
||||
)
|
||||
)
|
||||
):
|
||||
return None
|
||||
model_type = getattr(hf_config, "model_type", None)
|
||||
if (
|
||||
model_type
|
||||
in (
|
||||
"deepseek_v4",
|
||||
"deepseek_v4_text",
|
||||
"deepseek_v41",
|
||||
"deepseek_v41_text",
|
||||
)
|
||||
or user_quant == "deepseek_v4_fp8"
|
||||
):
|
||||
return "deepseek_v4_fp8"
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config: dict) -> DeepseekV4FP8Config:
|
||||
# Reroute AMD-Quark fused shared expert MXFP4 checkpoints onto the fp8
|
||||
# path: the runtime layout matches the DeepSeek-native fp8 checkpoint,
|
||||
# so translate the schema into format Fp8Config.from_config expects.
|
||||
if config.get("quant_method") == "quark":
|
||||
quark_exclude = config.get("exclude") or []
|
||||
config = {
|
||||
"quant_method": "fp8",
|
||||
"activation_scheme": "dynamic",
|
||||
"fmt": "e4m3",
|
||||
"scale_fmt": "ue8m0",
|
||||
"weight_block_size": [128, 128],
|
||||
"ignored_layers": [
|
||||
name for name in quark_exclude if isinstance(name, str)
|
||||
],
|
||||
}
|
||||
return cast("DeepseekV4FP8Config", super().from_config(config))
|
||||
|
||||
def get_quant_method(self, layer, prefix):
|
||||
if (
|
||||
isinstance(layer, LinearBase)
|
||||
and self.weight_block_size == [32, 32]
|
||||
and self.is_scale_e8m0
|
||||
):
|
||||
if is_layer_skipped(
|
||||
prefix=prefix,
|
||||
ignored_layers=self.ignored_layers,
|
||||
fused_mapping=self.packed_modules_mapping,
|
||||
match_mode=self.ignored_layers_match_mode,
|
||||
):
|
||||
return UnquantizedLinearMethod()
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
CkptCtx,
|
||||
ModelOptLinearMethod,
|
||||
)
|
||||
|
||||
rows, cols = self.weight_block_size
|
||||
return ModelOptLinearMethod(
|
||||
QuantSpec(weight=kMxfp8Static, activation=kMxfp8Dynamic),
|
||||
CkptCtx(scale_block_size=(rows, cols)),
|
||||
)
|
||||
if isinstance(layer, RoutedExperts):
|
||||
if is_layer_skipped(
|
||||
prefix=prefix,
|
||||
ignored_layers=self.ignored_layers,
|
||||
fused_mapping=self.packed_modules_mapping,
|
||||
):
|
||||
return UnquantizedFusedMoEMethod(layer.moe_config)
|
||||
if self.expert_dtype == "fp4":
|
||||
if self.moe_quant_algo == "NVFP4":
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptNvFp4FusedMoE,
|
||||
)
|
||||
|
||||
return ModelOptNvFp4FusedMoE(
|
||||
quant_config=self._get_nvfp4_config(),
|
||||
moe_config=layer.moe_config,
|
||||
)
|
||||
return Mxfp4MoEMethod(layer.moe_config)
|
||||
# expert_dtype == "fp8": fall through to Fp8Config which
|
||||
# returns Fp8MoEMethod with block-wise float32 scales.
|
||||
return super().get_quant_method(layer, prefix)
|
||||
@@ -0,0 +1,231 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepSeek-V4.1 FlashMLA sparse backend, metadata, and metadata builders."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionMetadata,
|
||||
AttentionMetadataBuilder,
|
||||
CommonAttentionMetadata,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.compressor_utils import get_compressed_slot_mapping
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import (
|
||||
_LAYER_TYPE_C1A,
|
||||
_LAYER_TYPE_C2A,
|
||||
_LAYER_TYPE_SWAONLY,
|
||||
DeepseekSparseSWAMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
|
||||
# v4.1 per-layer compress ratios: 0 = pure sliding window, 1 = full-length
|
||||
# compressed cache, 2 = ratio-2 compressed cache. Ratio-1 and ratio-2 layers
|
||||
# both attend over indexer topk indices into a shared compressed cache but
|
||||
# differ in compressed page block size (block_size // ratio), so each needs its
|
||||
# own FlashMLA tile-scheduler plan.
|
||||
_V41_LAYER_TYPES: dict[int, str] = {
|
||||
0: _LAYER_TYPE_SWAONLY,
|
||||
1: _LAYER_TYPE_C1A,
|
||||
2: _LAYER_TYPE_C2A,
|
||||
}
|
||||
|
||||
|
||||
def deepseek_v41_layer_type(compress_ratio: int) -> str:
|
||||
layer_type = _V41_LAYER_TYPES.get(compress_ratio)
|
||||
if layer_type is None:
|
||||
raise ValueError(
|
||||
f"Unsupported DeepSeek V4.1 compress_ratio={compress_ratio}; "
|
||||
"expected 0, 1, or 2."
|
||||
)
|
||||
return layer_type
|
||||
|
||||
|
||||
class DeepseekV41SparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuilder):
|
||||
"""SWA metadata builder base for v4.1.
|
||||
|
||||
The shared builder classifies decode layer types by the v4.0 ratios
|
||||
(1 = SWA-only, 4, 128). v4.1 uses 0 / 1 / 2, so recompute the set of
|
||||
tile-scheduler plans from the v4.1 topology.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
compress_ratios = getattr(
|
||||
self.vllm_config.model_config.hf_config, "compress_ratios", None
|
||||
) or [0]
|
||||
self._layer_types = {
|
||||
deepseek_v41_layer_type(int(ratio)) for ratio in compress_ratios
|
||||
}
|
||||
|
||||
|
||||
class DeepseekV4SparseMLABackend(AttentionBackend):
|
||||
"""DeepSeek-V4.1 sparse-MLA backend base.
|
||||
|
||||
Subclasses ``AttentionBackend`` directly (not the V3.2
|
||||
``FlashMLASparseBackend``): DeepSeek-V4.1 runs its own attention layer
|
||||
(``DeepseekV4Attention``), so it does not reuse the V3.2 builder or impl, and
|
||||
only needs to declare its own metadata builder, KV-cache layout, and the
|
||||
sparse-MLA capability flags.
|
||||
"""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"fp8_ds_mla",
|
||||
"fp8", # alias for fp8_ds_mla
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [64 if current_platform.is_device_capability_family(90) else 128]
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["DeepseekV4SparseMLAMetadataBuilder"]:
|
||||
return DeepseekV4SparseMLAMetadataBuilder
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[Any]:
|
||||
# DeepSeek-V4.1 runs its attention through ``DeepseekV4Attention.forward``,
|
||||
# not the generic ``Attention``/``MLAAttention`` layer, so the backend's
|
||||
# impl class is never instantiated.
|
||||
raise NotImplementedError(
|
||||
"DeepseekV4SparseMLABackend has no separate impl class; DeepSeek-V4.1 "
|
||||
"attention runs through DeepseekV4Attention."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
# DeepSeek V4 layout: 448 NoPE + 64 RoPE = 512.
|
||||
return [512]
|
||||
|
||||
@classmethod
|
||||
def is_mla(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
|
||||
return capability.major in [9, 10]
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeepseekV4FlashMLAMetadata(AttentionMetadata):
|
||||
num_reqs: int
|
||||
max_query_len: int
|
||||
max_seq_len: int
|
||||
|
||||
num_actual_tokens: int # Number of tokens excluding padding.
|
||||
query_start_loc: torch.Tensor
|
||||
slot_mapping: torch.Tensor
|
||||
|
||||
block_table: torch.Tensor
|
||||
req_id_per_token: torch.Tensor
|
||||
block_size: int
|
||||
topk_tokens: int
|
||||
|
||||
|
||||
class DeepseekV4SparseMLAMetadataBuilder(
|
||||
AttentionMetadataBuilder[DeepseekV4FlashMLAMetadata]
|
||||
):
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: AttentionSpec,
|
||||
layer_names: list[str],
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
self.model_config = vllm_config.model_config
|
||||
# Classify single-token queries (plus num_speculative_tokens via
|
||||
# supports_spec_as_decode=True) as decodes; longer queries go to prefill.
|
||||
self._init_reorder_batch_threshold(1, supports_spec_as_decode=True)
|
||||
self.topk_tokens = self.model_config.hf_config.index_topk
|
||||
|
||||
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.req_id_per_token_buffer = torch.empty(
|
||||
(max_num_batched_tokens,), dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
assert isinstance(self.kv_cache_spec.tokens_per_state, int)
|
||||
self.compress_ratio = self.kv_cache_spec.tokens_per_state
|
||||
# Only kv-source layers own a compressed cache, and v4.1 compresses at
|
||||
# ratio 1 or 2.
|
||||
if self.compress_ratio not in (1, 2):
|
||||
raise ValueError(
|
||||
"DeepSeek V4.1 compressed-KV caches use compress_ratio 1 or 2; "
|
||||
f"got {self.compress_ratio}."
|
||||
)
|
||||
|
||||
# Pre-allocate compressed slot mapping buffer for CUDA graph address
|
||||
# stability when compress_ratio > 1.
|
||||
if self.compress_ratio > 1:
|
||||
self.compressed_slot_mapping_buffer = torch.empty(
|
||||
max_num_batched_tokens, dtype=torch.int64, device=device
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> DeepseekV4FlashMLAMetadata:
|
||||
cm = common_attn_metadata
|
||||
req_id_per_token = cm.token_to_req_indices(self.req_id_per_token_buffer)
|
||||
|
||||
slot_mapping = cm.slot_mapping
|
||||
if self.compress_ratio > 1:
|
||||
slot_mapping = get_compressed_slot_mapping(
|
||||
cm.num_actual_tokens,
|
||||
cm.query_start_loc,
|
||||
cm.seq_lens,
|
||||
cm.block_table_tensor.clamp_(min=0),
|
||||
int(self.kv_cache_spec.num_states),
|
||||
self.compress_ratio,
|
||||
out=self.compressed_slot_mapping_buffer,
|
||||
)
|
||||
|
||||
return DeepseekV4FlashMLAMetadata(
|
||||
num_reqs=cm.num_reqs,
|
||||
max_query_len=cm.max_query_len,
|
||||
max_seq_len=cm.max_seq_len,
|
||||
num_actual_tokens=cm.num_actual_tokens,
|
||||
query_start_loc=cm.query_start_loc,
|
||||
slot_mapping=slot_mapping,
|
||||
block_table=cm.block_table_tensor,
|
||||
req_id_per_token=req_id_per_token,
|
||||
block_size=self.kv_cache_spec.block_size,
|
||||
topk_tokens=self.topk_tokens,
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4FlashMLAMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder):
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
|
||||
|
||||
class DeepseekV4FlashMLABackend(DeepseekV4SparseMLABackend):
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHMLA_SPARSE_DSV41"
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[DeepseekV4FlashMLAMetadataBuilder]:
|
||||
return DeepseekV4FlashMLAMetadataBuilder
|
||||
Reference in New Issue
Block a user