Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
@@ -153,9 +153,9 @@ class DeepseekV32Attention(MLAAttention):
|
||||
# DSA checkpoints may use plain ("default") or yarn-scaled RoPE.
|
||||
if config.rope_parameters["rope_type"] != "default":
|
||||
config.rope_parameters["rope_type"] = (
|
||||
"deepseek_yarn"
|
||||
if config.rope_parameters.get("apply_yarn_scaling", True)
|
||||
else "deepseek_llama_scaling"
|
||||
"deepseek_llama_scaling"
|
||||
if config.rope_parameters.get("attention_factor") == 1.0
|
||||
else "deepseek_yarn"
|
||||
)
|
||||
if config.rope_parameters["rope_type"] == "deepseek_yarn":
|
||||
mscale_all_dim = config.rope_parameters.get("mscale_all_dim", False)
|
||||
|
||||
@@ -315,7 +315,7 @@ def _fused_norm_rope_kernel(
|
||||
if MLA_CACHE_DS_MLA:
|
||||
# fp8_ds_mla layout (DeepSeek-V3.2, KV_DIM == 512): per-128-element
|
||||
# tile of the NoPE is dynamically quantized to fp8 with its own
|
||||
# float32 scale; the RoPE tail is stored unquantized in bf16.
|
||||
# power-of-two scale stored as float32; the RoPE tail is bf16.
|
||||
# bytes [0, KV_DIM) : KV_DIM fp8 NoPE values
|
||||
# bytes [KV_DIM, KV_DIM + 16) : MLA_NUM_TILES float32 scales
|
||||
# bytes [KV_DIM + 16, ...) : 2 * KPE_HALF_ROT_DIM bf16 RoPE
|
||||
@@ -327,9 +327,8 @@ def _fused_norm_rope_kernel(
|
||||
)
|
||||
kv_2d = tl.reshape(kv_c, (MLA_NUM_TILES, MLA_TILE_DIM))
|
||||
tile_amax = tl.max(tl.abs(kv_2d), axis=1, keep_dims=True)
|
||||
# scale = amax / 448 (fp8 e4m3 max), matching the reference
|
||||
# concat_and_cache_ds_mla kernel; floored to FLT_MIN.
|
||||
tile_scale = tl.maximum(tile_amax * (1.0 / 448.0), 1.1754944e-38)
|
||||
tile_scale = tl.maximum(tile_amax * (1.0 / 448.0), 1e-4)
|
||||
tile_scale = tl.math.exp2(tl.math.ceil(tl.math.log2(tile_scale)))
|
||||
kv_c_fp8 = tl.reshape((kv_2d / tile_scale).to(tl.float8e4nv), (KV_DIM,))
|
||||
tl.store(mla_cache_ptr + byte_base + kv_block, kv_c_fp8)
|
||||
tile_off = tl.arange(0, MLA_NUM_TILES)
|
||||
|
||||
@@ -495,11 +495,13 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuild
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
replay_start: torch.Tensor | None = None,
|
||||
) -> DeepseekV4ROCMAiterSparseSWAMetadata:
|
||||
base = super().build(
|
||||
common_prefix_len=common_prefix_len,
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
fast_build=fast_build,
|
||||
replay_start=replay_start,
|
||||
)
|
||||
|
||||
ragged_indices = None
|
||||
@@ -558,14 +560,17 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
self._fused_compressor_split_sizes: tuple[int, int] | None = None
|
||||
|
||||
if self.indexer is None:
|
||||
# Only enable multi-stream overlap for CSA layer now.
|
||||
self.aux_stream_list = None
|
||||
# Dense layers have no compressor work to overlap; HCA layers
|
||||
# (compressor, no indexer) keep the streams for the dual-stream
|
||||
# fork below.
|
||||
if self.compressor is None:
|
||||
self.aux_stream_list = None
|
||||
else:
|
||||
# Disable indexer inner overlap.
|
||||
self.indexer.aux_stream = None
|
||||
|
||||
def _enable_csa_multi_stream(self) -> bool:
|
||||
"""All CSA multi-stream gates: env var, streams, and capture region.
|
||||
def _enable_multi_stream_overlap(self) -> bool:
|
||||
"""ROCm multi-stream gates: streams and capture region.
|
||||
|
||||
Dict metadata marks piecewise cudagraph, whose eager breaks rebuild
|
||||
the attention inputs on the owning stream. Forking side streams
|
||||
@@ -573,7 +578,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
this overlap on ROCm (event waits can hang), so multi-stream only
|
||||
runs where the fork/join becomes static graph edges: inside capture,
|
||||
or with non-dict metadata (full cudagraph or the profile run), which
|
||||
has no eager breaks.
|
||||
has no eager breaks. Covers both the HCA and CSA forks.
|
||||
"""
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
return self.aux_stream_list is not None and (
|
||||
@@ -624,7 +629,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
device=hidden_states.device,
|
||||
)
|
||||
|
||||
if self._enable_csa_multi_stream():
|
||||
if self._enable_multi_stream_overlap():
|
||||
# The ROCm override consumes these sentinels inside the capture
|
||||
# boundary, moving the stream fan-out ahead of the projections.
|
||||
self._prepare_and_attn_fn(
|
||||
@@ -658,7 +663,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
positions: torch.Tensor,
|
||||
o_padded: torch.Tensor,
|
||||
) -> None:
|
||||
"""Run the ROCm CSA fork/join inside the graph capture boundary."""
|
||||
"""Run the ROCm fork/join (HCA or CSA) inside the capture boundary."""
|
||||
aux_streams = self.aux_stream_list
|
||||
# The sequential pipeline disables aux_stream_list before calling
|
||||
# back with real projection inputs; aux_streams is None ends that
|
||||
@@ -684,13 +689,13 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
|
||||
# Re-check: forward's gate ran inside a captured segment that
|
||||
# _prepare_and_attn_eager (MRV1) then broke, making this region eager.
|
||||
if not self._enable_csa_multi_stream():
|
||||
if not self._enable_multi_stream_overlap():
|
||||
self._run_sequential_pipeline(hidden_states, positions, o_padded)
|
||||
return
|
||||
|
||||
indexer = self.indexer
|
||||
compressor = self.compressor
|
||||
assert indexer is not None and compressor is not None
|
||||
assert compressor is not None
|
||||
|
||||
def default_chain():
|
||||
qr_kv = self._fused_wqa_wkv_gemm(hidden_states)
|
||||
@@ -710,6 +715,24 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
)
|
||||
compressor(score, positions, self.rotary_emb)
|
||||
|
||||
if indexer is None:
|
||||
# HCA dual-stream: the main compressor runs on aux stream 0 while
|
||||
# the default stream produces q and inserts KV into the SWA cache.
|
||||
# Both branches only read hidden_states, so the join merely has to
|
||||
# precede the sparse attention that consumes the compressed KV.
|
||||
(q, _qr_out, _qr_scale_out, kv_out), _ = execute_in_parallel(
|
||||
default_chain,
|
||||
[main_compressor_chain],
|
||||
self.ln_events[0],
|
||||
[self.ln_events[1]],
|
||||
aux_streams[:1],
|
||||
enable=True,
|
||||
)
|
||||
self._sparse_indexer_and_attn(
|
||||
hidden_states, None, None, None, q, kv_out, positions, o_padded
|
||||
)
|
||||
return
|
||||
|
||||
def indexer_compressor_chain() -> None:
|
||||
score = torch.mm(
|
||||
hidden_states,
|
||||
@@ -718,6 +741,11 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
)
|
||||
indexer.compressor(score, positions, self.indexer_rotary_emb)
|
||||
|
||||
# CSA three-stream: the main and indexer compressors run on aux
|
||||
# streams 0 and 1 while the default stream produces q and inserts KV
|
||||
# into the SWA cache. Every branch only reads hidden_states plus its
|
||||
# own state, so the join merely has to precede the indexer op and the
|
||||
# sparse attention, which consume the compressed KV caches.
|
||||
(q, qr_out, qr_scale_out, kv_out), _ = execute_in_parallel(
|
||||
default_chain,
|
||||
[main_compressor_chain, indexer_compressor_chain],
|
||||
|
||||
@@ -22,7 +22,7 @@ reference's out-of-vocab scheme.
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, cast
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -30,7 +30,7 @@ from PIL import Image, ImageOps
|
||||
from transformers import BatchFeature
|
||||
from typing_extensions import assert_never
|
||||
|
||||
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
|
||||
from vllm.config.multimodal import MultiModalDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
|
||||
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
|
||||
@@ -375,7 +375,7 @@ class DeepseekV4VLDummyInputsBuilder(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> MultiModalDataDict:
|
||||
size = self.info.get_image_size_with_most_features()
|
||||
return {
|
||||
@@ -383,7 +383,7 @@ class DeepseekV4VLDummyInputsBuilder(
|
||||
width=size.width,
|
||||
height=size.height,
|
||||
num_images=mm_counts.get("image", 0),
|
||||
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
|
||||
overrides=mm_options.get("image"),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -31,9 +31,9 @@ def build_deepseek_v4_rope(
|
||||
if compress_ratio > 1 and rope_parameters["rope_type"] != "default":
|
||||
# YaRN applies only to compressor (CSA/HCA) layers.
|
||||
rope_parameters["rope_type"] = (
|
||||
"deepseek_yarn"
|
||||
if rope_parameters.get("apply_yarn_scaling", True)
|
||||
else "deepseek_llama_scaling"
|
||||
"deepseek_llama_scaling"
|
||||
if rope_parameters.get("attention_factor") == 1.0
|
||||
else "deepseek_yarn"
|
||||
)
|
||||
else:
|
||||
# Sliding-window layers use plain RoPE (theta=rope_theta, no YaRN).
|
||||
|
||||
@@ -17,6 +17,7 @@ import torch.nn as nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
from vllm.config.kernel import MEGA_MOE_BACKENDS
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
@@ -31,7 +32,10 @@ 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.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
ReplicatedLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
@@ -48,12 +52,14 @@ from vllm.models.common.ops.sequence_parallel import (
|
||||
sp_padding_mask,
|
||||
sp_shard,
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
|
||||
|
||||
from .model import (
|
||||
DeepseekV4DecoderLayer,
|
||||
DeepseekV4Model,
|
||||
_use_sequence_parallel,
|
||||
make_deepseek_v4_expert_params_mapping,
|
||||
prepare_mega_gate_routing_metadata,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -61,6 +67,24 @@ 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$")
|
||||
_CONTEXT_WKV_RE = re.compile(r"^mtp\.(\d+)\.attn\.wkv\.(.+)$")
|
||||
|
||||
|
||||
def _duplicate_context_wkv_weights(
|
||||
weights: Iterable[tuple[str, torch.Tensor]], num_layers: int
|
||||
) -> Iterable[tuple[str, torch.Tensor]]:
|
||||
"""Load every draft layer's WKV into the cross-layer projection."""
|
||||
for name, weight in weights:
|
||||
yield name, weight
|
||||
match = _CONTEXT_WKV_RE.fullmatch(name)
|
||||
if match is None:
|
||||
continue
|
||||
layer_idx = int(match.group(1))
|
||||
if layer_idx >= num_layers:
|
||||
continue
|
||||
stacked_weight = weight.detach()
|
||||
stacked_weight.shard_id = layer_idx
|
||||
yield f"context_wkv_proj.{match.group(2)}", stacked_weight
|
||||
|
||||
|
||||
class DSparkDeepseekV4Model(nn.Module):
|
||||
@@ -75,6 +99,7 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
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_mega_moe = vllm_config.kernel_config.moe_backend in MEGA_MOE_BACKENDS
|
||||
self.use_sequence_parallel = _use_sequence_parallel(vllm_config)
|
||||
|
||||
self.num_dspark_layers = getattr(config, "n_mtp_layers", None) or 3
|
||||
@@ -113,6 +138,15 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
for i in range(self.num_dspark_layers)
|
||||
]
|
||||
)
|
||||
self.context_wkv_proj = MergedColumnParallelLinear(
|
||||
config.hidden_size,
|
||||
[config.head_dim] * self.num_dspark_layers,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=vllm_config.quant_config,
|
||||
prefix=maybe_prefix(prefix, "context_wkv_proj"),
|
||||
disable_tp=True,
|
||||
)
|
||||
|
||||
# Heads: final norm + hc_head, and the Markov + confidence heads
|
||||
# Loaded from the "final" MTP layer weights (mtp.*) in the target checkpoint
|
||||
@@ -173,15 +207,16 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
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):
|
||||
all_kv = self.context_wkv_proj(main_x).view(
|
||||
main_x.shape[0], self.num_dspark_layers, self.config.head_dim
|
||||
)
|
||||
for i, (layer, kv) in enumerate(
|
||||
zip(self.layers, all_kv.unbind(1), strict=True)
|
||||
):
|
||||
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
|
||||
@@ -204,6 +239,15 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
)
|
||||
inputs_embeds = sp_shard(inputs_embeds)
|
||||
input_ids = sp_shard(input_ids)
|
||||
mega_gate_metadata = None
|
||||
if self.use_mega_moe:
|
||||
mega_gate_metadata = prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
# 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)
|
||||
|
||||
@@ -216,6 +260,7 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix)
|
||||
if self.use_sequence_parallel:
|
||||
@@ -429,6 +474,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
head_start = n_local_head * tp_rank
|
||||
head_end = n_local_head * (tp_rank + 1)
|
||||
|
||||
weights = _duplicate_context_wkv_weights(weights, len(self.model.layers))
|
||||
for name, loaded_weight in weights:
|
||||
mapped = self._remap_dspark_name(name)
|
||||
if mapped is None:
|
||||
@@ -452,6 +498,12 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
self.quant_config, name, loaded_weight
|
||||
)
|
||||
|
||||
if name.startswith("model.context_wkv_proj."):
|
||||
param = params_dict[name]
|
||||
param.weight_loader(param, loaded_weight, loaded_weight.shard_id)
|
||||
loaded_params.add(name)
|
||||
continue
|
||||
|
||||
# E8M0 expert scales: keep raw exponent bytes.
|
||||
if ".experts." in name:
|
||||
if (
|
||||
@@ -522,6 +574,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
|
||||
Returns None for non-mtp weights (owned by the target model).
|
||||
"""
|
||||
if name.startswith("context_wkv_proj."):
|
||||
return f"model.{name}"
|
||||
m = re.match(r"mtp\.(\d+)\.(.*)", name)
|
||||
if m is None:
|
||||
return None
|
||||
|
||||
@@ -98,6 +98,37 @@ from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class MegaGateRoutingMetadata(typing.NamedTuple):
|
||||
safe_hash_input_ids: torch.Tensor | None
|
||||
image_token_mask: torch.Tensor | None
|
||||
hash_token_mask: torch.Tensor | None
|
||||
|
||||
|
||||
def prepare_mega_gate_routing_metadata(
|
||||
input_ids: torch.Tensor,
|
||||
*,
|
||||
has_hash_routing: bool,
|
||||
image_sentinel_base_id: int | None,
|
||||
) -> MegaGateRoutingMetadata:
|
||||
if image_sentinel_base_id is None:
|
||||
return MegaGateRoutingMetadata(
|
||||
input_ids if has_hash_routing else None,
|
||||
None,
|
||||
torch.ones_like(input_ids, dtype=torch.bool) if has_hash_routing else None,
|
||||
)
|
||||
|
||||
image_token_mask = (input_ids >= image_sentinel_base_id) & (
|
||||
input_ids < image_sentinel_base_id + 5
|
||||
)
|
||||
if not has_hash_routing:
|
||||
return MegaGateRoutingMetadata(None, image_token_mask, None)
|
||||
return MegaGateRoutingMetadata(
|
||||
torch.where(image_token_mask, 0, input_ids),
|
||||
image_token_mask,
|
||||
~image_token_mask,
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4MLP(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -803,6 +834,10 @@ class DeepseekV4MoE(nn.Module):
|
||||
raise NotImplementedError(
|
||||
"DeepSeek V4 MegaMoE currently supports sqrtsoftplus routing only."
|
||||
)
|
||||
if self.use_mega_moe and not self.renormalize:
|
||||
raise NotImplementedError(
|
||||
"DeepSeek V4 MegaMoE requires normalized top-k probabilities."
|
||||
)
|
||||
if self.use_mega_moe and getattr(config, "expert_dtype", "fp4") != "fp4":
|
||||
raise NotImplementedError(
|
||||
"DeepSeek V4 MegaMoE only supports fp4 experts; got expert_dtype="
|
||||
@@ -958,20 +993,18 @@ class DeepseekV4MoE(nn.Module):
|
||||
prefix: str,
|
||||
) -> None:
|
||||
parallel_config = vllm_config.parallel_config
|
||||
self.tp_rank = get_tensor_model_parallel_rank()
|
||||
ep_group = get_ep_group()
|
||||
ep_size = ep_group.world_size
|
||||
ep_rank = ep_group.rank_in_group
|
||||
|
||||
eplb_config = parallel_config.eplb_config
|
||||
self.n_redundant_experts = eplb_config.num_redundant_experts
|
||||
self.n_shared_experts = config.n_shared_experts or 0
|
||||
self.n_logical_experts = self.n_routed_experts
|
||||
self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts
|
||||
assert self.n_physical_experts % self.tp_size == 0, (
|
||||
f"n_physical_experts={self.n_physical_experts} must be divisible by "
|
||||
f"tp_size={self.tp_size}. Adjust num_redundant_experts."
|
||||
)
|
||||
self.n_local_physical_experts = self.n_physical_experts // self.tp_size
|
||||
self.n_local_physical_experts = self.n_physical_experts // ep_size
|
||||
self.n_local_experts = self.n_local_physical_experts
|
||||
self.experts_start_idx = self.tp_rank * self.n_local_experts
|
||||
self.experts_start_idx = ep_rank * self.n_local_experts
|
||||
self.experts_end_idx = self.experts_start_idx + self.n_local_experts
|
||||
self.physical_expert_start = self.experts_start_idx
|
||||
self.physical_expert_end = self.experts_end_idx
|
||||
@@ -1000,7 +1033,10 @@ class DeepseekV4MoE(nn.Module):
|
||||
)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, input_ids: torch.Tensor | None = None
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
mega_gate_metadata: MegaGateRoutingMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.gate.tid2eid is not None and input_ids is None:
|
||||
raise ValueError("DeepSeek V4 hash MoE routing requires input_ids.")
|
||||
@@ -1013,23 +1049,61 @@ class DeepseekV4MoE(nn.Module):
|
||||
return self._forward_fused_moe(hidden_states, input_ids)
|
||||
|
||||
org_shape = hidden_states.shape
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
topk_weights, topk_ids = fused_topk_bias(
|
||||
hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
scoring_func=self.scoring_func,
|
||||
e_score_correction_bias=self.gate.e_score_correction_bias.data
|
||||
if self.gate.e_score_correction_bias is not None
|
||||
else None,
|
||||
topk=self.n_activated_experts,
|
||||
renormalize=self.renormalize,
|
||||
indices_type=self.hash_indices_dtype,
|
||||
input_tokens=input_ids,
|
||||
hash_indices_table=self.gate.tid2eid,
|
||||
routed_scaling_factor=self.routed_scaling_factor,
|
||||
bias_vl=bias_vl.data if bias_vl is not None else None,
|
||||
image_sentinel_lo=self.image_sentinel_lo if bias_vl is not None else 0,
|
||||
)
|
||||
# Small local padded batches favor GateLinear; 128-expert gates cross earlier.
|
||||
gate_threshold = 1 if self.gate.weight.shape[0] == 128 else 16
|
||||
if hidden_states.shape[0] <= gate_threshold:
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
topk_weights, topk_ids = fused_topk_bias(
|
||||
hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
scoring_func=self.scoring_func,
|
||||
e_score_correction_bias=self.gate.e_score_correction_bias.data
|
||||
if self.gate.e_score_correction_bias is not None
|
||||
else None,
|
||||
topk=self.n_activated_experts,
|
||||
renormalize=self.renormalize,
|
||||
indices_type=self.hash_indices_dtype,
|
||||
input_tokens=input_ids,
|
||||
hash_indices_table=self.gate.tid2eid,
|
||||
routed_scaling_factor=self.routed_scaling_factor,
|
||||
bias_vl=bias_vl.data if bias_vl is not None else None,
|
||||
image_sentinel_lo=self.image_sentinel_lo if bias_vl is not None else 0,
|
||||
)
|
||||
else:
|
||||
from vllm.utils.deep_gemm import bf16_mega_gate
|
||||
|
||||
if mega_gate_metadata is None:
|
||||
raise RuntimeError(
|
||||
"MegaMoE routing metadata must be prepared once by the model."
|
||||
)
|
||||
|
||||
unmapped_topk_idx = None
|
||||
fix_routing_mask = None
|
||||
if self.gate.tid2eid is not None:
|
||||
if mega_gate_metadata.safe_hash_input_ids is None:
|
||||
raise RuntimeError("Hash routing requires prepared input IDs.")
|
||||
if mega_gate_metadata.hash_token_mask is None:
|
||||
raise RuntimeError("Hash routing requires a prepared routing mask.")
|
||||
unmapped_topk_idx = self.gate.tid2eid[
|
||||
mega_gate_metadata.safe_hash_input_ids
|
||||
]
|
||||
fix_routing_mask = mega_gate_metadata.hash_token_mask
|
||||
|
||||
topk_weights, topk_ids = bf16_mega_gate(
|
||||
hidden_states,
|
||||
self.gate.weight,
|
||||
self.n_activated_experts,
|
||||
scoring_func=self.scoring_func,
|
||||
routed_scaling_factor=self.routed_scaling_factor,
|
||||
ep_rank=self.ep_rank,
|
||||
bias=self.gate.e_score_correction_bias.data
|
||||
if self.gate.e_score_correction_bias is not None
|
||||
else None,
|
||||
image_bias=bias_vl.data if bias_vl is not None else None,
|
||||
image_token_mask=mega_gate_metadata.image_token_mask,
|
||||
fix_routing_mask=fix_routing_mask,
|
||||
unmapped_topk_idx=unmapped_topk_idx,
|
||||
)
|
||||
activation_clamp = (
|
||||
float(self.swiglu_limit) if self.swiglu_limit is not None else None
|
||||
)
|
||||
@@ -1248,6 +1322,7 @@ class DeepseekV4DecoderLayer(nn.Module):
|
||||
post_mix: torch.Tensor | None = None,
|
||||
res_mix: torch.Tensor | None = None,
|
||||
residual: torch.Tensor | None = None,
|
||||
mega_gate_metadata: MegaGateRoutingMetadata | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
attn_norm_weight = self.attn_norm.weight.data
|
||||
attn_norm_eps = self.attn_norm.variance_epsilon
|
||||
@@ -1332,7 +1407,7 @@ class DeepseekV4DecoderLayer(nn.Module):
|
||||
norm_eps=ffn_norm_eps,
|
||||
)
|
||||
|
||||
x = self.ffn(x, input_ids)
|
||||
x = self.ffn(x, input_ids, mega_gate_metadata)
|
||||
return x, residual, post_mix, res_mix
|
||||
|
||||
|
||||
@@ -1394,6 +1469,9 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
),
|
||||
prefix=f"{prefix}.layers",
|
||||
)
|
||||
self.has_local_hash_moe = self.start_layer < min(
|
||||
self.end_layer, config.num_hash_layers
|
||||
)
|
||||
|
||||
if get_pp_group().is_last_rank:
|
||||
self.norm = RMSNorm(config.hidden_size, self.rms_norm_eps)
|
||||
@@ -1496,6 +1574,16 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
hidden_states = sp_shard(hidden_states)
|
||||
input_ids = sp_shard(input_ids)
|
||||
|
||||
mega_gate_metadata = None
|
||||
if self.use_mega_moe:
|
||||
mega_gate_metadata = prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=self.has_local_hash_moe,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
|
||||
residual, post_mix, res_mix = None, None, None
|
||||
remote_aux = self.collect_remote_aux_hidden_states(intermediate_tensors)
|
||||
aux_hidden_states: list[torch.Tensor] = []
|
||||
@@ -1511,6 +1599,7 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
if idx + 1 in self.aux_hidden_state_layers:
|
||||
# Reconstruct the aux hidden state for draft models
|
||||
|
||||
@@ -20,6 +20,7 @@ import torch.nn as nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.kernel import MEGA_MOE_BACKENDS
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
@@ -51,6 +52,7 @@ from vllm.models.common.ops.sequence_parallel import (
|
||||
sp_padding_mask,
|
||||
sp_shard,
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
|
||||
from vllm.models.deepseek_v4.common.ops.fused_mtp_input_rmsnorm import (
|
||||
_FUSED_MTP_INPUT_RMSNORM_KERNEL,
|
||||
_MTP_SHARED_HEAD_RMSNORM_KERNEL,
|
||||
@@ -62,6 +64,7 @@ from .model import (
|
||||
DeepseekV4Model,
|
||||
_use_sequence_parallel,
|
||||
make_deepseek_v4_expert_params_mapping,
|
||||
prepare_mega_gate_routing_metadata,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -92,6 +95,7 @@ class DeepSeekV4MultiTokenPredictorLayer(nn.Module):
|
||||
self.config = config
|
||||
quant_config = vllm_config.quant_config
|
||||
self.rms_norm_eps = config.rms_norm_eps
|
||||
self.use_mega_moe = vllm_config.kernel_config.moe_backend in MEGA_MOE_BACKENDS
|
||||
|
||||
self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
@@ -181,8 +185,23 @@ class DeepSeekV4MultiTokenPredictorLayer(nn.Module):
|
||||
hidden_states = self.h_proj(previous_hidden_states) + self.e_proj(
|
||||
inputs_embeds
|
||||
).unsqueeze(-2)
|
||||
mega_gate_metadata = None
|
||||
if self.use_mega_moe:
|
||||
routing_input_ids = input_ids
|
||||
if self.mtp_block.use_sequence_parallel:
|
||||
routing_input_ids = sp_shard(routing_input_ids)
|
||||
mega_gate_metadata = prepare_mega_gate_routing_metadata(
|
||||
routing_input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
hidden_states, residual, post_mix, res_mix = self.mtp_block(
|
||||
positions=positions, x=hidden_states, input_ids=input_ids
|
||||
positions=positions,
|
||||
x=hidden_states,
|
||||
input_ids=input_ids,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix)
|
||||
if self.mtp_block.use_sequence_parallel:
|
||||
|
||||
@@ -12,7 +12,7 @@ import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
@triton.jit(do_not_specialize=["num_tokens"])
|
||||
def _prepare_megamoe_inputs_kernel(
|
||||
hidden_states,
|
||||
x_fp8,
|
||||
@@ -40,27 +40,32 @@ def _prepare_megamoe_inputs_kernel(
|
||||
topk_idx_stride_k: tl.constexpr,
|
||||
topk_weights_out_stride_m: tl.constexpr,
|
||||
topk_weights_out_stride_k: tl.constexpr,
|
||||
num_tokens,
|
||||
hidden_size: tl.constexpr,
|
||||
top_k: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
GROUP_K: tl.constexpr,
|
||||
BLOCK_TOPK: tl.constexpr,
|
||||
SHARED_BLOCK_M: tl.constexpr,
|
||||
) -> None:
|
||||
token_id = tl.program_id(0)
|
||||
token_id = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
token_mask = token_id < num_tokens
|
||||
k_block_id = tl.program_id(1)
|
||||
|
||||
k_offsets = k_block_id * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
k_mask = k_offsets < hidden_size
|
||||
k_mask = token_mask[:, None] & (k_offsets[None, :] < hidden_size)
|
||||
hidden = tl.load(
|
||||
hidden_states + token_id * hidden_stride_m + k_offsets * hidden_stride_k,
|
||||
hidden_states
|
||||
+ token_id[:, None] * hidden_stride_m
|
||||
+ k_offsets[None, :] * hidden_stride_k,
|
||||
mask=k_mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
|
||||
num_groups: tl.constexpr = BLOCK_K // GROUP_K
|
||||
hidden_groups = tl.reshape(tl.abs(hidden), [num_groups, GROUP_K])
|
||||
amax = tl.max(hidden_groups, axis=1)
|
||||
hidden_groups = tl.reshape(tl.abs(hidden), [BLOCK_M, num_groups, GROUP_K])
|
||||
amax = tl.max(hidden_groups, axis=2)
|
||||
amax = tl.maximum(amax, 1.0e-4)
|
||||
|
||||
scale = amax / 448.0
|
||||
@@ -71,21 +76,24 @@ def _prepare_megamoe_inputs_kernel(
|
||||
scale_exp = tl.minimum(tl.maximum(scale_exp, 1), 254)
|
||||
rounded_scale = (scale_exp << 23).to(tl.float32, bitcast=True)
|
||||
|
||||
hidden_groups = tl.reshape(hidden, [num_groups, GROUP_K])
|
||||
scaled = hidden_groups * (1.0 / rounded_scale)[:, None]
|
||||
scaled = tl.reshape(scaled, [BLOCK_K])
|
||||
hidden_groups = tl.reshape(hidden, [BLOCK_M, num_groups, GROUP_K])
|
||||
scaled = hidden_groups * (1.0 / rounded_scale)[:, :, None]
|
||||
scaled = tl.reshape(scaled, [BLOCK_M, BLOCK_K])
|
||||
fp8 = scaled.to(tl.float8e4nv)
|
||||
tl.store(
|
||||
x_fp8 + token_id * x_stride_m + k_offsets * x_stride_k,
|
||||
x_fp8 + token_id[:, None] * x_stride_m + k_offsets[None, :] * x_stride_k,
|
||||
fp8,
|
||||
mask=k_mask,
|
||||
)
|
||||
|
||||
scale_offsets = tl.arange(0, num_groups)
|
||||
packed_scale = tl.sum(scale_exp << (scale_offsets * 8), axis=0).to(tl.int32)
|
||||
packed_scale = tl.sum(scale_exp << (scale_offsets[None, :] * 8), axis=1).to(
|
||||
tl.int32
|
||||
)
|
||||
tl.store(
|
||||
x_sf + token_id * x_sf_stride_m + k_block_id * x_sf_stride_k,
|
||||
packed_scale,
|
||||
mask=token_mask,
|
||||
)
|
||||
|
||||
# DeepGEMM's SM100 shared-expert TMA loads require the activation scales
|
||||
@@ -105,41 +113,48 @@ def _prepare_megamoe_inputs_kernel(
|
||||
+ shared_row * shared_x_sf_stride_m
|
||||
+ k_block_id * shared_x_sf_stride_k,
|
||||
packed_scale,
|
||||
mask=token_mask,
|
||||
)
|
||||
|
||||
if k_block_id == 0:
|
||||
topk_offsets = tl.arange(0, BLOCK_TOPK)
|
||||
topk_mask = topk_offsets < top_k
|
||||
token_is_padding = False
|
||||
topk_mask = token_mask[:, None] & (topk_offsets[None, :] < top_k)
|
||||
token_is_padding = tl.full((BLOCK_M,), False, tl.int1)
|
||||
if is_padding is not None:
|
||||
token_is_padding = tl.load(is_padding + token_id * is_padding_stride_m)
|
||||
token_is_padding = tl.load(
|
||||
is_padding + token_id * is_padding_stride_m,
|
||||
mask=token_mask,
|
||||
other=True,
|
||||
)
|
||||
|
||||
ids = tl.load(
|
||||
topk_ids + token_id * topk_ids_stride_m + topk_offsets * topk_ids_stride_k,
|
||||
topk_ids
|
||||
+ token_id[:, None] * topk_ids_stride_m
|
||||
+ topk_offsets[None, :] * topk_ids_stride_k,
|
||||
mask=topk_mask,
|
||||
other=0,
|
||||
).to(tl.int64)
|
||||
ids = tl.where(token_is_padding, -1, ids)
|
||||
ids = tl.where(token_is_padding[:, None], -1, ids)
|
||||
tl.store(
|
||||
topk_idx_out
|
||||
+ token_id * topk_idx_stride_m
|
||||
+ topk_offsets * topk_idx_stride_k,
|
||||
+ token_id[:, None] * topk_idx_stride_m
|
||||
+ topk_offsets[None, :] * topk_idx_stride_k,
|
||||
ids,
|
||||
mask=topk_mask,
|
||||
)
|
||||
|
||||
weights = tl.load(
|
||||
topk_weights
|
||||
+ token_id * topk_weights_stride_m
|
||||
+ topk_offsets * topk_weights_stride_k,
|
||||
+ token_id[:, None] * topk_weights_stride_m
|
||||
+ topk_offsets[None, :] * topk_weights_stride_k,
|
||||
mask=topk_mask,
|
||||
other=0.0,
|
||||
)
|
||||
weights = tl.where(token_is_padding, 0.0, weights)
|
||||
weights = tl.where(token_is_padding[:, None], 0.0, weights)
|
||||
tl.store(
|
||||
topk_weights_out
|
||||
+ token_id * topk_weights_out_stride_m
|
||||
+ topk_offsets * topk_weights_out_stride_k,
|
||||
+ token_id[:, None] * topk_weights_out_stride_m
|
||||
+ topk_offsets[None, :] * topk_weights_out_stride_k,
|
||||
weights,
|
||||
mask=topk_mask,
|
||||
)
|
||||
@@ -195,7 +210,9 @@ def prepare_megamoe_inputs(
|
||||
)
|
||||
|
||||
block_k = 128
|
||||
grid = (num_tokens, triton.cdiv(hidden_size, block_k))
|
||||
# On GB200, eight-row tiles win from 64 tokens; keep smaller batches untiled.
|
||||
block_m = 8 if num_tokens >= 64 else 1
|
||||
grid = (triton.cdiv(num_tokens, block_m), triton.cdiv(hidden_size, block_k))
|
||||
block_topk = triton.next_power_of_2(top_k)
|
||||
padding_stride_m = is_padding.stride(0) if is_padding is not None else 0
|
||||
_prepare_megamoe_inputs_kernel[grid](
|
||||
@@ -225,8 +242,10 @@ def prepare_megamoe_inputs(
|
||||
topk_idx_out.stride(1),
|
||||
topk_weights_out.stride(0),
|
||||
topk_weights_out.stride(1),
|
||||
num_tokens,
|
||||
hidden_size,
|
||||
top_k,
|
||||
BLOCK_M=block_m,
|
||||
BLOCK_K=block_k,
|
||||
GROUP_K=32,
|
||||
BLOCK_TOPK=block_topk,
|
||||
|
||||
@@ -195,6 +195,7 @@ class DeepseekV4SparseMLAMetadataBuilder(
|
||||
if self.compress_ratio > 1:
|
||||
slot_mapping = get_compressed_slot_mapping(
|
||||
cm.num_actual_tokens,
|
||||
cm.slot_mapping,
|
||||
cm.query_start_loc,
|
||||
cm.seq_lens,
|
||||
cm.block_table_tensor.clamp_(min=0),
|
||||
|
||||
@@ -425,11 +425,13 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBu
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
replay_start: torch.Tensor | None = None,
|
||||
) -> DeepseekV4ROCMAiterSparseSWAMetadata:
|
||||
base = super().build(
|
||||
common_prefix_len=common_prefix_len,
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
fast_build=fast_build,
|
||||
replay_start=replay_start,
|
||||
)
|
||||
|
||||
ragged_indices = None
|
||||
|
||||
@@ -512,6 +512,25 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
|
||||
"decodes only on SM100."
|
||||
)
|
||||
|
||||
swa_bounded_replay = cache_config.swa_bounded_replay
|
||||
if swa_bounded_replay and not vllm_config.use_v2_model_runner:
|
||||
logger.warning_once(
|
||||
"SWA bounded replay needs model runner V2 (only it skips the "
|
||||
"paged-KV writes of replayed tokens); the sliding-window cache "
|
||||
"takes part in prefix caching instead."
|
||||
)
|
||||
swa_bounded_replay = False
|
||||
if (
|
||||
swa_bounded_replay
|
||||
and vllm_config.parallel_config.prefill_context_parallel_size > 1
|
||||
):
|
||||
logger.warning_once(
|
||||
"SWA bounded replay is off under prefill context parallelism "
|
||||
"(the replayed tokens' slot padding knows the rank-local batch "
|
||||
"only); the sliding-window cache takes part in prefix caching "
|
||||
"instead."
|
||||
)
|
||||
swa_bounded_replay = False
|
||||
self.swa_cache_layer = DeepseekV4SWACache(
|
||||
head_dim=self.head_dim,
|
||||
window_size=self.window_size,
|
||||
@@ -522,6 +541,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
|
||||
block_size=32,
|
||||
packed_bytes_per_token=self.swa_bytes_per_token,
|
||||
packed_page_alignment=self.kv_page_alignment,
|
||||
bounded_replay=swa_bounded_replay,
|
||||
)
|
||||
|
||||
# The attention layer itself was already registered with the
|
||||
|
||||
@@ -19,14 +19,14 @@ boundaries freely).
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, cast
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image, ImageOps
|
||||
from transformers import BatchFeature
|
||||
|
||||
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
|
||||
from vllm.config.multimodal import MultiModalDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
|
||||
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
|
||||
@@ -296,7 +296,7 @@ class DeepseekV4VLDummyInputsBuilder(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> MultiModalDataDict:
|
||||
size = self.info.get_image_size_with_most_features()
|
||||
return {
|
||||
@@ -304,7 +304,7 @@ class DeepseekV4VLDummyInputsBuilder(
|
||||
width=size.width,
|
||||
height=size.height,
|
||||
num_images=mm_counts.get("image", 0),
|
||||
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
|
||||
overrides=mm_options.get("image"),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -584,7 +584,11 @@ def dequantize_and_gather_k_cache_triton(
|
||||
num_reqs = seq_lens.shape[0]
|
||||
NUM_WORKERS = 128
|
||||
if k_cache.shape[-1] == V41_NVFP4_BYTES_PER_TOKEN:
|
||||
_dequantize_and_gather_k_nvfp4_kernel[(num_reqs, NUM_WORKERS)](
|
||||
# Keep short gathers unchanged; cap total workers for multi-request chunks.
|
||||
num_workers = min(
|
||||
max(128, 2048 // max(1, num_reqs)), max(128, out.shape[1] - offset)
|
||||
)
|
||||
_dequantize_and_gather_k_nvfp4_kernel[(num_reqs, num_workers)](
|
||||
out,
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
@@ -978,6 +982,10 @@ class CombineTopkSwaIndicesKernel(
|
||||
# turns the store index below negative).
|
||||
topk_len = 0
|
||||
swa_start = tl.maximum(pos - (WINDOW_SIZE - 1), 0)
|
||||
# gather_len already excludes context below the request's replay
|
||||
# start (SWA bounded replay), so the window cannot start before
|
||||
# the gathered buffer does.
|
||||
swa_start = tl.maximum(swa_start, gather_start)
|
||||
swa_len = pos - swa_start + 1
|
||||
|
||||
offset = tl.arange(0, PADDED_TOP_K)
|
||||
@@ -1124,6 +1132,8 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
decode_is_valid_token: torch.Tensor | None = None,
|
||||
swa_block_span: int | None = None,
|
||||
compressed_block_span: int | None = None,
|
||||
*,
|
||||
replay_start: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Build the FlashInfer DSV4 sparse-index matrix for decode-first batches.
|
||||
|
||||
@@ -1133,6 +1143,9 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
per token). Decode tokens read precomputed SWA/compressed indices; prefill
|
||||
tokens derive their SWA window from the position and translate local
|
||||
compressed indices to global slots via the block tables.
|
||||
|
||||
``replay_start`` ([num_reqs], SWA bounded replay) lower-bounds every
|
||||
prefill token's window: positions below it hold no window KV.
|
||||
"""
|
||||
assert decode_swa_indices.dtype == torch.int32
|
||||
assert decode_swa_indices.dim() == 2
|
||||
@@ -1223,6 +1236,7 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
token_to_req_indices,
|
||||
replay_start,
|
||||
swa_block_table,
|
||||
swa_block_table.stride(0),
|
||||
swa_block_size,
|
||||
@@ -1291,6 +1305,7 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
token_to_req_indices_ptr,
|
||||
replay_start_ptr,
|
||||
swa_block_table_ptr,
|
||||
swa_block_table_stride,
|
||||
swa_block_size,
|
||||
@@ -1390,6 +1405,8 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
token_idx_in_query = token_idx - query_start
|
||||
pos = start_pos + token_idx_in_query
|
||||
swa_start_pos = tl.maximum(pos - (WINDOW_SIZE - 1), 0)
|
||||
# SWA bounded replay: no window KV exists below the request's replay start.
|
||||
swa_start_pos = tl.maximum(swa_start_pos, tl.load(replay_start_ptr + req_idx))
|
||||
swa_len = pos - swa_start_pos + 1
|
||||
if COMPRESS_RATIO > 0:
|
||||
topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K)
|
||||
|
||||
@@ -32,9 +32,9 @@ def build_deepseek_v4_rope(
|
||||
# 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"
|
||||
"deepseek_llama_scaling"
|
||||
if rope_parameters.get("attention_factor") == 1.0
|
||||
else "deepseek_yarn"
|
||||
)
|
||||
else:
|
||||
# Sliding-window layers use plain RoPE (theta=rope_theta, no YaRN).
|
||||
|
||||
@@ -18,6 +18,7 @@ import torch.nn as nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
from vllm.config.kernel import MEGA_MOE_BACKENDS
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
@@ -50,12 +51,14 @@ from vllm.models.common.ops.sequence_parallel import (
|
||||
sp_shard,
|
||||
)
|
||||
|
||||
from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
|
||||
from .model import (
|
||||
DeepseekV4DecoderLayer,
|
||||
DeepseekV4Model,
|
||||
_linear_scale_param_name,
|
||||
_use_sequence_parallel,
|
||||
make_deepseek_v4_expert_params_mapping,
|
||||
prepare_mega_gate_routing_metadata,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -77,6 +80,7 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
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_mega_moe = vllm_config.kernel_config.moe_backend in MEGA_MOE_BACKENDS
|
||||
self.use_sequence_parallel = _use_sequence_parallel(vllm_config)
|
||||
|
||||
self.num_dspark_layers = (
|
||||
@@ -202,6 +206,15 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
)
|
||||
inputs_embeds = sp_shard(inputs_embeds)
|
||||
input_ids = sp_shard(input_ids)
|
||||
mega_gate_metadata = None
|
||||
if self.use_mega_moe:
|
||||
mega_gate_metadata = prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
# 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)
|
||||
|
||||
@@ -215,6 +228,7 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix)
|
||||
# Collapse the hc copies with the pre-mix from the last layer's FFN
|
||||
|
||||
@@ -422,7 +422,7 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
|
||||
if not swa_only:
|
||||
assert flashmla_metadata is not None
|
||||
dequantize_and_gather_k_cache(
|
||||
kv_ws[:chunk_size],
|
||||
kv_ws[:chunk_size, :chunk_n],
|
||||
self._compressed_kv_cache(),
|
||||
seq_lens=seq_lens[chunk_start:chunk_end] // self.compress_ratio,
|
||||
gather_lens=None,
|
||||
|
||||
@@ -26,7 +26,11 @@ from vllm.models.deepseek_v41.sparse_mla import (
|
||||
)
|
||||
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.backend import (
|
||||
AttentionCGSupport,
|
||||
CommonAttentionMetadata,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.compressor_utils import (
|
||||
get_dspark_swa_index_width,
|
||||
)
|
||||
@@ -183,6 +187,42 @@ class DeepseekSparseSWAFlashInferMetadataBuilder(DeepseekV41SparseSWAMetadataBui
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# Graphs retain these addresses while each build refreshes their contents.
|
||||
self._decode_topk_lens = torch.empty(
|
||||
self._max_tokens, dtype=torch.int32, device=self.device
|
||||
)
|
||||
self._decode_seq_lens = torch.empty_like(self._decode_topk_lens)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
replay_start: torch.Tensor | None = None,
|
||||
) -> "DeepseekSparseSWAMetadata":
|
||||
metadata = super().build(
|
||||
common_prefix_len, common_attn_metadata, fast_build, replay_start
|
||||
)
|
||||
num_tokens = metadata.num_decode_tokens
|
||||
if not common_attn_metadata.causal and num_tokens > 0:
|
||||
assert metadata.decode_swa_lens is not None
|
||||
assert metadata.seq_lens is not None
|
||||
assert metadata.token_to_req_indices is not None
|
||||
topk_lens = self._decode_topk_lens[:num_tokens]
|
||||
seq_lens = self._decode_seq_lens[:num_tokens]
|
||||
torch.clamp(metadata.decode_swa_lens, min=self.window_size, out=topk_lens)
|
||||
torch.index_select(
|
||||
metadata.seq_lens,
|
||||
0,
|
||||
metadata.token_to_req_indices[:num_tokens],
|
||||
out=seq_lens,
|
||||
)
|
||||
metadata.flashinfer_decode_topk_lens = topk_lens
|
||||
metadata.flashinfer_decode_seq_lens = seq_lens
|
||||
return metadata
|
||||
|
||||
|
||||
class DeepseekSparseSWAFlashInferBackend(DeepseekSparseSWABackend):
|
||||
@staticmethod
|
||||
@@ -338,6 +378,7 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
|
||||
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
|
||||
assert swa_metadata.replay_start is not None
|
||||
|
||||
decode_swa_indices = swa_metadata.decode_swa_indices.reshape(
|
||||
num_decode_tokens, swa_metadata.decode_swa_width
|
||||
@@ -417,6 +458,7 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
|
||||
decode_is_valid_token=decode_is_valid_token,
|
||||
swa_block_span=swa_block_span,
|
||||
compressed_block_span=compressed_block_span,
|
||||
replay_start=swa_metadata.replay_start[:num_reqs],
|
||||
)
|
||||
if swa_only:
|
||||
swa_metadata.flashinfer_sparse_index_cache["swa_only"] = (
|
||||
@@ -493,21 +535,40 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
|
||||
# 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_query = query[:num_decode_tokens]
|
||||
decode_output = output[:num_decode_tokens]
|
||||
decode_cu = query_start_loc[: num_decodes + 1]
|
||||
decode_seq_lens = seq_lens[:num_decodes]
|
||||
decode_topk_lens = sparse_topk_lens[:num_decode_tokens]
|
||||
max_decode_query_len = swa_metadata.max_decode_query_len
|
||||
if swa_metadata.decode_swa_width > self.window_size:
|
||||
# DSpark's non-causal window extends past the fixed 128 SWA
|
||||
# columns into the aliased compressed pool. Exclude padding,
|
||||
# and expose the full block to each query instead of letting
|
||||
# TRTLLM derive a causal SWA length from its query position.
|
||||
assert swa_only
|
||||
assert swa_metadata.flashinfer_decode_topk_lens is not None
|
||||
assert swa_metadata.flashinfer_decode_seq_lens is not None
|
||||
decode_topk_lens = swa_metadata.flashinfer_decode_topk_lens
|
||||
decode_seq_lens = swa_metadata.flashinfer_decode_seq_lens
|
||||
decode_query = decode_query.unsqueeze(1)
|
||||
decode_output = decode_output.unsqueeze(1)
|
||||
decode_cu = None
|
||||
max_decode_query_len = 1
|
||||
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
|
||||
query=query[:num_decode_tokens],
|
||||
query=decode_query,
|
||||
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],
|
||||
sparse_topk_lens=decode_topk_lens,
|
||||
seq_lens=decode_seq_lens,
|
||||
out=decode_output,
|
||||
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,
|
||||
max_q_len=max_decode_query_len,
|
||||
)
|
||||
|
||||
if num_prefill_tokens > 0:
|
||||
|
||||
@@ -61,7 +61,9 @@ from vllm.models.deepseek_v4.nvidia.model import (
|
||||
DeepseekV4MoE as DeepseekV4MoEBase,
|
||||
)
|
||||
from vllm.models.deepseek_v4.nvidia.model import (
|
||||
MegaGateRoutingMetadata,
|
||||
make_deepseek_v4_expert_params_mapping,
|
||||
prepare_mega_gate_routing_metadata,
|
||||
)
|
||||
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
|
||||
from vllm.models.deepseek_v41.nvidia.flash_mla_mega_attn import (
|
||||
@@ -339,6 +341,7 @@ class DeepseekV4DecoderLayer(nn.Module):
|
||||
engram_mask: torch.Tensor | None = None,
|
||||
*,
|
||||
capture_previous_aux: bool = False,
|
||||
mega_gate_metadata: MegaGateRoutingMetadata | None = None,
|
||||
) -> tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
@@ -462,7 +465,7 @@ class DeepseekV4DecoderLayer(nn.Module):
|
||||
norm_weight=self.ffn_norm.weight,
|
||||
norm_eps=self.ffn_norm.variance_epsilon,
|
||||
)
|
||||
x = self.ffn(x, input_ids)
|
||||
x = self.ffn(x, input_ids, mega_gate_metadata)
|
||||
return x, residual, post_mix, res_mix, ffn_pre, previous_aux
|
||||
|
||||
|
||||
@@ -705,6 +708,16 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
hidden_states = sp_shard(hidden_states)
|
||||
input_ids = sp_shard(input_ids)
|
||||
|
||||
mega_gate_metadata = None
|
||||
if self.use_mega_moe:
|
||||
mega_gate_metadata = prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
|
||||
residual, post_mix, res_mix = None, None, None
|
||||
pre_mix: torch.Tensor | None = None
|
||||
if not get_pp_group().is_first_rank:
|
||||
@@ -728,6 +741,7 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
engram_hashes,
|
||||
engram_mask,
|
||||
capture_previous_aux=idx in self.aux_hidden_state_layers,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
if previous_aux is not None:
|
||||
# idx is the one-based id of the layer whose post this is.
|
||||
|
||||
@@ -2,15 +2,23 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config import CUDAGraphMode, VllmConfig
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadataBuilder
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.core.sched.output import NewRequestData
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.worker.gpu.buffer_utils import UvaBufferPool
|
||||
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.model_states.interface import ModelSpecificAttnMetadata
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -41,14 +49,69 @@ def _gather_lookback_kernel(
|
||||
tl.store(lookback_ptr + batch_idx * DEPTH + offs, ids, mask=offs < DEPTH)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _pad_replayed_slots_kernel(
|
||||
slot_mappings_ptr, # [num_groups, num_tokens_padded]
|
||||
group_stride,
|
||||
cacheable_groups_ptr, # [NUM_GROUPS] indices of the prefix-cacheable groups
|
||||
query_start_loc_ptr, # [num_reqs + 1]
|
||||
positions_ptr, # [num_tokens]
|
||||
replay_start_ptr, # [num_reqs]
|
||||
window,
|
||||
pad_slot_id,
|
||||
NUM_GROUPS: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
req = tl.program_id(0)
|
||||
start = tl.load(replay_start_ptr + req)
|
||||
if start == 0:
|
||||
return
|
||||
begin = tl.load(query_start_loc_ptr + req)
|
||||
end = tl.load(query_start_loc_ptr + req + 1)
|
||||
for tok in range(begin, end, BLOCK):
|
||||
offs = tok + tl.arange(0, BLOCK)
|
||||
pos = tl.load(positions_ptr + offs, mask=offs < end, other=0)
|
||||
replayed = (offs < end) & (pos >= start) & (pos < start + window)
|
||||
for i in tl.static_range(NUM_GROUPS):
|
||||
group = tl.load(cacheable_groups_ptr + i)
|
||||
tl.store(
|
||||
slot_mappings_ptr + group * group_stride + offs,
|
||||
pad_slot_id,
|
||||
mask=replayed,
|
||||
)
|
||||
|
||||
|
||||
class ReplayAttnMetadata(ModelSpecificAttnMetadata):
|
||||
"""Hands the batch's replay starts to the sliding-window builders."""
|
||||
|
||||
def __init__(self, replay_start: torch.Tensor) -> None:
|
||||
self.replay_start = replay_start
|
||||
|
||||
def get_extra_attn_kwargs(
|
||||
self, attn_metadata_builder: Any, num_reqs: int
|
||||
) -> dict[str, Any]:
|
||||
if isinstance(attn_metadata_builder, DeepseekSparseSWAMetadataBuilder):
|
||||
return {"replay_start": self.replay_start[:num_reqs]}
|
||||
return {}
|
||||
|
||||
|
||||
class DeepseekV41ModelState(DefaultModelState):
|
||||
"""DefaultModelState plus the engram lookback window.
|
||||
"""DefaultModelState plus the engram lookback window and SWA bounded replay.
|
||||
|
||||
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.
|
||||
|
||||
SWA bounded replay (``CacheConfig.swa_bounded_replay``) keeps the
|
||||
sliding-window KV out of prefix caching and rebuilds it after a prefix hit
|
||||
by recomputing the hit's last window; the scheduler tells each request the
|
||||
position from which it holds window KV (``NewRequestData.replay_start``).
|
||||
``prepare_attn`` gathers those per batch, pads the replayed tokens' slots
|
||||
in the prefix-cacheable groups so the cached KV stays as is, and hands the
|
||||
starts to the sliding-window metadata builders, whose kernels read no
|
||||
window KV below them.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -67,6 +130,20 @@ class DeepseekV41ModelState(DefaultModelState):
|
||||
(self.max_num_reqs, depth), -1, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
# Per request state index; batches gather from it (see prepare_attn).
|
||||
self._replay_start_np = np.zeros(self.max_num_reqs, dtype=np.int32)
|
||||
self._replay_start = torch.zeros(
|
||||
self.max_num_reqs, dtype=torch.int32, device=device
|
||||
)
|
||||
self._replay_start_staging = UvaBufferPool(self.max_num_reqs, torch.int32)
|
||||
# The replay window and the indices of the prefix-cacheable groups, from
|
||||
# the KV cache config on first use; None until then.
|
||||
self._replay: tuple[int, torch.Tensor] | None = None
|
||||
|
||||
def add_request(self, req_index: int, new_req_data: NewRequestData) -> None:
|
||||
super().add_request(req_index, new_req_data)
|
||||
self._replay_start_np[req_index] = new_req_data.replay_start
|
||||
|
||||
def prepare_inputs(
|
||||
self, input_batch: InputBatch, req_states: RequestState
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
@@ -96,3 +173,67 @@ class DeepseekV41ModelState(DefaultModelState):
|
||||
self.lookback_token_ids.fill_(-1)
|
||||
model_inputs["lookback_token_ids"] = self.lookback_token_ids
|
||||
return model_inputs
|
||||
|
||||
def prepare_attn(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
cudagraph_mode: CUDAGraphMode,
|
||||
block_tables: tuple[torch.Tensor, ...],
|
||||
slot_mappings: torch.Tensor,
|
||||
attn_groups: list[list[AttentionGroup]],
|
||||
kv_cache_config: KVCacheConfig,
|
||||
for_capture: bool = False,
|
||||
ubatch_idx: int = 0,
|
||||
model_specific_attn_metadata: ModelSpecificAttnMetadata | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if self._replay is None:
|
||||
specs = [group.kv_cache_spec for group in kv_cache_config.kv_cache_groups]
|
||||
self._replay = (
|
||||
max(spec.prefix_replay_tokens for spec in specs),
|
||||
torch.tensor(
|
||||
[i for i, spec in enumerate(specs) if spec.prefix_cacheable],
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
),
|
||||
)
|
||||
window, cacheable_groups = self._replay
|
||||
if window:
|
||||
num_reqs = input_batch.num_reqs
|
||||
# Decode rows sit above the hit, so only prefills carry a replay
|
||||
# start; dummy batches (captures, profiling) carry none.
|
||||
replay_start_np = np.where(
|
||||
input_batch.is_prefilling_np[:num_reqs],
|
||||
self._replay_start_np[input_batch.idx_mapping_np[:num_reqs]],
|
||||
0,
|
||||
).astype(np.int32)
|
||||
replay_start = self._replay_start_staging.copy_to_gpu(
|
||||
replay_start_np, out=self._replay_start[:num_reqs]
|
||||
)
|
||||
if replay_start_np.any():
|
||||
# The replayed tokens rebuild window KV only: their slots in the
|
||||
# prefix-cacheable groups are padded so the cached KV stays as is.
|
||||
_pad_replayed_slots_kernel[(num_reqs,)](
|
||||
slot_mappings,
|
||||
slot_mappings.stride(0),
|
||||
cacheable_groups,
|
||||
input_batch.query_start_loc,
|
||||
input_batch.positions,
|
||||
replay_start,
|
||||
window,
|
||||
PAD_SLOT_ID,
|
||||
NUM_GROUPS=cacheable_groups.numel(),
|
||||
BLOCK=1024,
|
||||
)
|
||||
assert model_specific_attn_metadata is None
|
||||
model_specific_attn_metadata = ReplayAttnMetadata(replay_start)
|
||||
return super().prepare_attn(
|
||||
input_batch,
|
||||
cudagraph_mode,
|
||||
block_tables,
|
||||
slot_mappings,
|
||||
attn_groups,
|
||||
kv_cache_config,
|
||||
for_capture=for_capture,
|
||||
ubatch_idx=ubatch_idx,
|
||||
model_specific_attn_metadata=model_specific_attn_metadata,
|
||||
)
|
||||
|
||||
@@ -195,6 +195,7 @@ class DeepseekV4SparseMLAMetadataBuilder(
|
||||
if self.compress_ratio > 1:
|
||||
slot_mapping = get_compressed_slot_mapping(
|
||||
cm.num_actual_tokens,
|
||||
cm.slot_mapping,
|
||||
cm.query_start_loc,
|
||||
cm.seq_lens,
|
||||
cm.block_table_tensor.clamp_(min=0),
|
||||
|
||||
@@ -13,10 +13,7 @@ from PIL import Image
|
||||
from transformers import BatchFeature
|
||||
|
||||
from vllm.config.multimodal import (
|
||||
AudioDummyOptions,
|
||||
BaseDummyOptions,
|
||||
ImageDummyOptions,
|
||||
VideoDummyOptions,
|
||||
MultiModalDummyOptions,
|
||||
)
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
|
||||
@@ -584,7 +581,7 @@ class Dots3NoteDummyInputsBuilder(BaseDummyInputsBuilder[Dots3NoteProcessingInfo
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> MultiModalDataDict:
|
||||
data: dict[str, Any] = {}
|
||||
num_images = mm_counts.get("image", 0)
|
||||
@@ -594,7 +591,7 @@ class Dots3NoteDummyInputsBuilder(BaseDummyInputsBuilder[Dots3NoteProcessingInfo
|
||||
width=width,
|
||||
height=height,
|
||||
num_images=num_images,
|
||||
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
|
||||
overrides=mm_options.get("image"),
|
||||
)
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
if num_audios:
|
||||
@@ -611,7 +608,7 @@ class Dots3NoteDummyInputsBuilder(BaseDummyInputsBuilder[Dots3NoteProcessingInfo
|
||||
data["audio"] = self._get_dummy_audios(
|
||||
length=min(chunk_samples, max(1, seq_len) * stride),
|
||||
num_audios=num_audios,
|
||||
overrides=cast(AudioDummyOptions | None, mm_options.get("audio")),
|
||||
overrides=mm_options.get("audio"),
|
||||
)
|
||||
num_videos = mm_counts.get("video", 0)
|
||||
if num_videos:
|
||||
@@ -625,7 +622,7 @@ class Dots3NoteDummyInputsBuilder(BaseDummyInputsBuilder[Dots3NoteProcessingInfo
|
||||
height=height,
|
||||
num_frames=num_frames,
|
||||
num_videos=num_videos,
|
||||
overrides=cast(VideoDummyOptions | None, mm_options.get("video")),
|
||||
overrides=mm_options.get("video"),
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ def sparse_attn_indexer_kpool(
|
||||
scale_fmt: str | None,
|
||||
topk_tokens: int,
|
||||
head_dim: int,
|
||||
max_model_len: int,
|
||||
max_pool_len: int,
|
||||
total_seq_lens: int,
|
||||
topk_indices_buffer: torch.Tensor,
|
||||
skip_k_cache_insert: bool,
|
||||
@@ -136,7 +136,7 @@ def sparse_attn_indexer_kpool(
|
||||
)
|
||||
|
||||
# Reserve profiler-visible memory for the worst-case decode logits,
|
||||
# whose shape is [B * next_n, max_model_len]. This profiling branch
|
||||
# whose shape is [B * next_n, max_pool_len]. This profiling branch
|
||||
# returns before invoking the logits kernel itself.
|
||||
cfg = get_current_vllm_config_or_none()
|
||||
worst_decode_tokens = 0
|
||||
@@ -152,7 +152,7 @@ def sparse_attn_indexer_kpool(
|
||||
sched.max_num_batched_tokens,
|
||||
)
|
||||
# float32 logits -> 4 bytes/element; uint8 sentinel so elems == bytes.
|
||||
decode_logits_elems = worst_decode_tokens * max_model_len * 4
|
||||
decode_logits_elems = worst_decode_tokens * max_pool_len * 4
|
||||
prefill_cap_elems = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
|
||||
max_logits_elems = max(decode_logits_elems, prefill_cap_elems)
|
||||
_ = torch.empty(
|
||||
@@ -566,7 +566,7 @@ def sparse_attn_indexer_kpool(
|
||||
seq_lens,
|
||||
decode_metadata.block_table,
|
||||
decode_metadata.schedule_metadata,
|
||||
max_model_len=max_model_len,
|
||||
max_model_len=max_pool_len,
|
||||
)
|
||||
num_rows = logits.shape[0]
|
||||
# kpool: logits are pool-granular -> select topk_tokens//kpool pools,
|
||||
@@ -645,7 +645,7 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
scale_fmt: str,
|
||||
topk_tokens: int,
|
||||
head_dim: int,
|
||||
max_model_len: int,
|
||||
max_pool_len: int,
|
||||
max_total_seq_len: int,
|
||||
topk_indices_buffer: torch.Tensor,
|
||||
skip_k_cache_insert: bool = False,
|
||||
@@ -659,13 +659,13 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
self.scale_fmt = scale_fmt
|
||||
self.topk_tokens = topk_tokens
|
||||
self.head_dim = head_dim
|
||||
self.max_model_len = max_model_len
|
||||
self.max_pool_len = max_pool_len
|
||||
self.max_total_seq_len = max_total_seq_len
|
||||
self.topk_indices_buffer = topk_indices_buffer
|
||||
self.skip_k_cache_insert = skip_k_cache_insert
|
||||
self.use_fp4_cache = use_fp4_cache
|
||||
|
||||
def forward_native(
|
||||
def forward_hip(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
@@ -698,7 +698,7 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
self.scale_fmt,
|
||||
self.topk_tokens,
|
||||
self.head_dim,
|
||||
self.max_model_len,
|
||||
self.max_pool_len,
|
||||
self.max_total_seq_len,
|
||||
self.topk_indices_buffer,
|
||||
skip_k_cache_insert=self.skip_k_cache_insert,
|
||||
@@ -715,7 +715,7 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
self.scale_fmt,
|
||||
self.topk_tokens,
|
||||
self.head_dim,
|
||||
self.max_model_len,
|
||||
self.max_pool_len,
|
||||
self.max_total_seq_len,
|
||||
self.topk_indices_buffer,
|
||||
self.skip_k_cache_insert,
|
||||
@@ -727,3 +727,26 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
self.tail_cache.kv_cache if self.tail_cache is not None else None,
|
||||
self.tail_cache.prefix if self.tail_cache is not None else None,
|
||||
)
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
k: torch.Tensor,
|
||||
weights: torch.Tensor,
|
||||
*,
|
||||
gate_score: torch.Tensor | None = None,
|
||||
compress_ape: torch.Tensor | None = None,
|
||||
index_kpool: int = 1,
|
||||
positions: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_hip(
|
||||
hidden_states,
|
||||
q_quant,
|
||||
k,
|
||||
weights,
|
||||
gate_score=gate_score,
|
||||
compress_ape=compress_ape,
|
||||
index_kpool=index_kpool,
|
||||
positions=positions,
|
||||
)
|
||||
|
||||
@@ -296,7 +296,7 @@ class Indexer(nn.Module):
|
||||
cache_config=cache_config,
|
||||
index_kpool=self.index_kpool,
|
||||
)
|
||||
self.max_model_len = vllm_config.model_config.max_model_len
|
||||
self.max_pool_len = vllm_config.model_config.max_model_len // self.index_kpool
|
||||
self.prefix = prefix
|
||||
from vllm.v1.attention.backends.mla.indexer import get_max_prefill_buffer_size
|
||||
|
||||
@@ -307,7 +307,7 @@ class Indexer(nn.Module):
|
||||
self.scale_fmt,
|
||||
self.topk_tokens,
|
||||
self.head_dim,
|
||||
self.max_model_len,
|
||||
self.max_pool_len,
|
||||
self.max_total_seq_len,
|
||||
self.topk_indices_buffer,
|
||||
tail_cache=self.tail_cache,
|
||||
@@ -496,9 +496,9 @@ class Glm5NextMLAAttention(nn.Module):
|
||||
assert config.rope_parameters is not None
|
||||
if config.rope_parameters["rope_type"] != "default":
|
||||
config.rope_parameters["rope_type"] = (
|
||||
"deepseek_yarn"
|
||||
if config.rope_parameters.get("apply_yarn_scaling", True)
|
||||
else "deepseek_llama_scaling"
|
||||
"deepseek_llama_scaling"
|
||||
if config.rope_parameters.get("attention_factor") == 1.0
|
||||
else "deepseek_yarn"
|
||||
)
|
||||
|
||||
self.rotary_emb: RotaryEmbedding | None = get_rope(
|
||||
|
||||
@@ -38,6 +38,22 @@ if current_platform.is_cuda_alike():
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _use_cooperative_topk(
|
||||
logits: torch.Tensor,
|
||||
select_k: int,
|
||||
num_rows: int,
|
||||
) -> bool:
|
||||
return (
|
||||
current_platform.is_cuda()
|
||||
and select_k in (512, 1024, 2048)
|
||||
and num_rows <= 64
|
||||
and logits.stride(0) % 4 == 0
|
||||
and current_platform.has_device_capability(90)
|
||||
and not current_platform.is_device_capability_family(120)
|
||||
)
|
||||
|
||||
|
||||
# kpool write helper: form pools from the current token batch and compress them
|
||||
# into the index K cache via the fused Triton kernel.
|
||||
|
||||
@@ -101,7 +117,7 @@ def sparse_attn_indexer_kpool(
|
||||
scale_fmt: str | None,
|
||||
topk_tokens: int,
|
||||
head_dim: int,
|
||||
max_model_len: int,
|
||||
max_pool_len: int,
|
||||
total_seq_lens: int,
|
||||
topk_indices_buffer: torch.Tensor,
|
||||
skip_k_cache_insert: bool,
|
||||
@@ -137,7 +153,7 @@ def sparse_attn_indexer_kpool(
|
||||
)
|
||||
|
||||
# Reserve profiler-visible memory for the worst-case decode logits,
|
||||
# whose shape is [B * next_n, max_model_len]. This profiling branch
|
||||
# whose shape is [B * next_n, max_pool_len]. This profiling branch
|
||||
# returns before invoking the logits kernel itself.
|
||||
cfg = get_current_vllm_config_or_none()
|
||||
worst_decode_tokens = 0
|
||||
@@ -153,7 +169,7 @@ def sparse_attn_indexer_kpool(
|
||||
sched.max_num_batched_tokens,
|
||||
)
|
||||
# float32 logits -> 4 bytes/element; uint8 sentinel so elems == bytes.
|
||||
decode_logits_elems = worst_decode_tokens * max_model_len * 4
|
||||
decode_logits_elems = worst_decode_tokens * max_pool_len * 4
|
||||
prefill_cap_elems = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
|
||||
max_logits_elems = max(decode_logits_elems, prefill_cap_elems)
|
||||
_ = torch.empty(
|
||||
@@ -553,7 +569,7 @@ def sparse_attn_indexer_kpool(
|
||||
seq_lens,
|
||||
decode_metadata.block_table,
|
||||
decode_metadata.schedule_metadata,
|
||||
max_model_len=max_model_len,
|
||||
max_model_len=max_pool_len,
|
||||
clean_logits=False,
|
||||
)
|
||||
num_rows = logits.shape[0]
|
||||
@@ -573,7 +589,12 @@ def sparse_attn_indexer_kpool(
|
||||
(topk_workspace,) = workspace_manager.get_simultaneous(
|
||||
((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
|
||||
)
|
||||
torch.ops._C.persistent_topk(
|
||||
topk_op = (
|
||||
torch.ops._C.cooperative_topk
|
||||
if _use_cooperative_topk(logits, select_k, num_rows)
|
||||
else torch.ops._C.persistent_topk
|
||||
)
|
||||
topk_op(
|
||||
logits,
|
||||
seq_lens,
|
||||
topk_dst,
|
||||
@@ -647,7 +668,7 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
scale_fmt: str,
|
||||
topk_tokens: int,
|
||||
head_dim: int,
|
||||
max_model_len: int,
|
||||
max_pool_len: int,
|
||||
max_total_seq_len: int,
|
||||
topk_indices_buffer: torch.Tensor,
|
||||
skip_k_cache_insert: bool = False,
|
||||
@@ -661,7 +682,7 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
self.scale_fmt = scale_fmt
|
||||
self.topk_tokens = topk_tokens
|
||||
self.head_dim = head_dim
|
||||
self.max_model_len = max_model_len
|
||||
self.max_pool_len = max_pool_len
|
||||
self.max_total_seq_len = max_total_seq_len
|
||||
self.topk_indices_buffer = topk_indices_buffer
|
||||
self.skip_k_cache_insert = skip_k_cache_insert
|
||||
@@ -734,7 +755,7 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
self.scale_fmt,
|
||||
self.topk_tokens,
|
||||
self.head_dim,
|
||||
self.max_model_len,
|
||||
self.max_pool_len,
|
||||
self.max_total_seq_len,
|
||||
self.topk_indices_buffer,
|
||||
self.skip_k_cache_insert,
|
||||
|
||||
@@ -34,6 +34,7 @@ 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.model_executor.models.deepseek_v2 import Indexer
|
||||
@@ -220,6 +221,7 @@ class HYV4FlashMLASparseImpl(FlashMLASparseImpl):
|
||||
topk_indices: torch.Tensor,
|
||||
topk_length: torch.Tensor | None = None,
|
||||
actual_num_heads: int | None = None,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
num_tokens = q.shape[0]
|
||||
kv_c_and_k_pe_cache = kv_c_and_k_pe_cache.view(
|
||||
@@ -250,7 +252,14 @@ class HYV4FlashMLASparseImpl(FlashMLASparseImpl):
|
||||
# Zero (not new_empty) the padded lanes: topk_indices is shared by
|
||||
# all heads, so the kernel reduces across the head group and NaNs
|
||||
# from uninitialized memory would leak into the real heads.
|
||||
q_padded = q.new_zeros((q.shape[0], padded_num_heads, q.shape[2]))
|
||||
if out is None:
|
||||
q_padded = q.new_zeros((q.shape[0], padded_num_heads, q.shape[2]))
|
||||
else:
|
||||
*_, q_padded, _, _ = current_workspace_manager().get_simultaneous(
|
||||
*self.workspace_specs
|
||||
)
|
||||
q_padded = q_padded[:num_tokens]
|
||||
q_padded[:, actual_num_heads:].zero_()
|
||||
q_padded[:, :actual_num_heads, :] = q
|
||||
q = q_padded
|
||||
|
||||
@@ -262,6 +271,7 @@ class HYV4FlashMLASparseImpl(FlashMLASparseImpl):
|
||||
self.softmax_scale,
|
||||
attn_sink=attn_sink,
|
||||
topk_length=topk_length,
|
||||
out=out,
|
||||
)
|
||||
|
||||
output = output[:, :actual_num_heads, :]
|
||||
|
||||
@@ -13,9 +13,7 @@ import torch
|
||||
from transformers.feature_extraction_utils import BatchFeature
|
||||
|
||||
from vllm.config.multimodal import (
|
||||
AudioDummyOptions,
|
||||
BaseDummyOptions,
|
||||
ImageDummyOptions,
|
||||
MultiModalDummyOptions,
|
||||
)
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import (
|
||||
@@ -145,7 +143,7 @@ class InklingDummyInputsBuilder(BaseDummyInputsBuilder[InklingProcessingInfo]):
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> MultiModalDataDict:
|
||||
config = self.info.get_hf_config()
|
||||
num_images = mm_counts.get("image", 0)
|
||||
@@ -156,12 +154,11 @@ class InklingDummyInputsBuilder(BaseDummyInputsBuilder[InklingProcessingInfo]):
|
||||
patch_size = getattr(config.vision_config, "patch_size", 40)
|
||||
# A square image ~4 patches wide so the dummy emits several patches.
|
||||
side = patch_size * 4
|
||||
image_overrides = mm_options.get("image")
|
||||
mm_data["image"] = self._get_dummy_images(
|
||||
width=side,
|
||||
height=side,
|
||||
num_images=num_images,
|
||||
overrides=cast(ImageDummyOptions | None, image_overrides),
|
||||
overrides=mm_options.get("image"),
|
||||
)
|
||||
if num_audios:
|
||||
# Size the dummy at the maximum allowed audio so memory/encoder
|
||||
@@ -169,11 +166,10 @@ class InklingDummyInputsBuilder(BaseDummyInputsBuilder[InklingProcessingInfo]):
|
||||
params = self.info.get_hf_processor().audio_feature_extractor.params
|
||||
hop = int(round(params.audio_token_duration_s * params.sample_rate))
|
||||
audio_len = MAX_AUDIO_TOKENS * hop
|
||||
audio_overrides = mm_options.get("audio")
|
||||
mm_data["audio"] = self._get_dummy_audios(
|
||||
length=audio_len,
|
||||
num_audios=num_audios,
|
||||
overrides=cast(AudioDummyOptions | None, audio_overrides),
|
||||
overrides=mm_options.get("audio"),
|
||||
)
|
||||
return mm_data
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from typing import Any, cast
|
||||
import torch
|
||||
from transformers import BatchFeature
|
||||
|
||||
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
|
||||
from vllm.config.multimodal import ImageDummyOptions, MultiModalDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal.inputs import (
|
||||
@@ -204,7 +204,7 @@ class KimiK3DummyInputsBuilder(BaseDummyInputsBuilder[KimiK3ProcessingInfo]):
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions] | None = None,
|
||||
mm_options: MultiModalDummyOptions | None = None,
|
||||
) -> MultiModalDataDict:
|
||||
media_proc_cfg = self.info.image_processor.media_proc_cfg
|
||||
max_size = self.info.get_max_image_size(
|
||||
@@ -214,7 +214,6 @@ class KimiK3DummyInputsBuilder(BaseDummyInputsBuilder[KimiK3ProcessingInfo]):
|
||||
media_proc_cfg["patch_limit_on_one_side"],
|
||||
media_proc_cfg["fixed_output_tokens"],
|
||||
)
|
||||
num_images = mm_counts.get("image", 0)
|
||||
image_overrides = cast(
|
||||
ImageDummyOptions | None,
|
||||
mm_options.get("image") if mm_options else None,
|
||||
@@ -223,7 +222,7 @@ class KimiK3DummyInputsBuilder(BaseDummyInputsBuilder[KimiK3ProcessingInfo]):
|
||||
"image": self._get_dummy_images(
|
||||
width=max_size.width,
|
||||
height=max_size.height,
|
||||
num_images=num_images,
|
||||
num_images=mm_counts.get("image", 0),
|
||||
overrides=image_overrides,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -165,9 +165,9 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
|
||||
rope_parameters = dict(config.rope_parameters)
|
||||
if rope_parameters["rope_type"] != "default":
|
||||
rope_parameters["rope_type"] = (
|
||||
"deepseek_yarn"
|
||||
if rope_parameters.get("apply_yarn_scaling", True)
|
||||
else "deepseek_llama_scaling"
|
||||
"deepseek_llama_scaling"
|
||||
if rope_parameters.get("attention_factor") == 1.0
|
||||
else "deepseek_yarn"
|
||||
)
|
||||
self.rotary_emb = get_rope(
|
||||
qk_rope_head_dim,
|
||||
|
||||
@@ -677,7 +677,7 @@ class KimiMoE(nn.Module):
|
||||
hidden_size,
|
||||
self.moe_hidden_size,
|
||||
bias=False,
|
||||
quant_config=None,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.routed_expert_down_proj",
|
||||
)
|
||||
self.routed_expert_norm = (
|
||||
@@ -694,7 +694,7 @@ class KimiMoE(nn.Module):
|
||||
self.moe_hidden_size,
|
||||
hidden_size,
|
||||
bias=False,
|
||||
quant_config=None,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.routed_expert_up_proj",
|
||||
)
|
||||
|
||||
@@ -761,6 +761,7 @@ class KimiMoE(nn.Module):
|
||||
routed_input_transform=None,
|
||||
routed_output_transform=self.routed_output_transform,
|
||||
is_sequence_parallel=use_sequence_parallel,
|
||||
skip_padding=True,
|
||||
runner_cls=LatentMoERunner if self.use_latent_moe else None,
|
||||
)
|
||||
if self.padded_moe_intermediate_size != moe_intermediate_size:
|
||||
|
||||
@@ -76,9 +76,9 @@ def fused_mla_key_concat_ds_mla_insert(
|
||||
"""Concat full K (bf16) and insert the latent in the fp8_ds_mla layout.
|
||||
|
||||
The cache uses DeepSeek's 656-byte block-scaled layout (NoPE in 4 tiles of
|
||||
128 with per-tile dynamic fp8 scales, RoPE as bf16) -- self-scaling, so no
|
||||
scale argument. Returns the bf16 full key; optionally rotates ``q`` and
|
||||
writes ``kv_cache`` in place.
|
||||
128 with per-tile power-of-two scales stored as float32, RoPE as bf16) --
|
||||
self-scaling, so no scale argument. Returns the bf16 full key; optionally
|
||||
rotates ``q`` and writes ``kv_cache`` in place.
|
||||
"""
|
||||
k_pe = k_pe.reshape(k_pe.shape[0], -1)
|
||||
tp, num_heads, qk_nope_head_dim = k_nope.shape
|
||||
|
||||
@@ -579,6 +579,32 @@ class MiniMaxM3Attention(nn.Module):
|
||||
return output
|
||||
|
||||
|
||||
# Widest row pitch aiter's reshape_and_cache can carry in its `int` stride args.
|
||||
_MAX_KV_INSERT_ROW_STRIDE = 2**31 - 1
|
||||
|
||||
|
||||
def _kv_insert_operand(t: torch.Tensor) -> torch.Tensor:
|
||||
"""K or V operand for ``aiter.reshape_and_cache``, without a needless copy.
|
||||
|
||||
The AITER sparse-PA insert takes K and V as column slices of the fused
|
||||
``[q | k | v | index_q | index_k]`` projection, so they are row-strided
|
||||
views and never contiguous. ``reshape_and_cache`` does not need them to be:
|
||||
it passes ``key.stride(0)`` to the kernel as the row pitch and reads
|
||||
``key[token_idx * key_stride + i]`` for ``i`` over ``num_heads *
|
||||
head_size``, so the only requirement is that the trailing
|
||||
``(num_heads, head_size)`` block be contiguous within a row, which such a
|
||||
slice always satisfies. Any other layout falls back to a copy.
|
||||
"""
|
||||
if (
|
||||
t.dim() == 3
|
||||
and t.stride(2) == 1
|
||||
and t.stride(1) == t.shape[2]
|
||||
and t.stride(0) <= _MAX_KV_INSERT_ROW_STRIDE
|
||||
):
|
||||
return t
|
||||
return t.contiguous()
|
||||
|
||||
|
||||
class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
|
||||
"""Block-sparse attention layer with the lightning-indexer branch.
|
||||
|
||||
@@ -902,8 +928,8 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
|
||||
else "auto"
|
||||
)
|
||||
reshape_and_cache(
|
||||
k.contiguous(),
|
||||
v.contiguous(),
|
||||
_kv_insert_operand(k),
|
||||
_kv_insert_operand(v),
|
||||
key_cache,
|
||||
value_cache,
|
||||
slot_mapping,
|
||||
|
||||
@@ -11,9 +11,7 @@ from transformers import BatchFeature
|
||||
from transformers.video_utils import VideoMetadata
|
||||
|
||||
from vllm.config.multimodal import (
|
||||
BaseDummyOptions,
|
||||
ImageDummyOptions,
|
||||
VideoDummyOptions,
|
||||
MultiModalDummyOptions,
|
||||
)
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import (
|
||||
@@ -283,7 +281,7 @@ class MiniMaxM3VLDummyInputsBuilder(BaseDummyInputsBuilder[MiniMaxM3VLProcessing
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> MultiModalDataDict:
|
||||
size = self.info.get_image_size_with_most_features()
|
||||
video_size = self.info.get_video_size_with_most_features()
|
||||
@@ -293,14 +291,14 @@ class MiniMaxM3VLDummyInputsBuilder(BaseDummyInputsBuilder[MiniMaxM3VLProcessing
|
||||
width=size.width,
|
||||
height=size.height,
|
||||
num_images=mm_counts.get("image", 0),
|
||||
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
|
||||
overrides=mm_options.get("image"),
|
||||
),
|
||||
"video": self._get_dummy_videos(
|
||||
width=video_size.width,
|
||||
height=video_size.height,
|
||||
num_frames=num_frames,
|
||||
num_videos=mm_counts.get("video", 0),
|
||||
overrides=cast(VideoDummyOptions | None, mm_options.get("video")),
|
||||
overrides=mm_options.get("video"),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,12 @@ def _is_sm120() -> bool:
|
||||
return current_platform.get_device_capability() == (12, 0)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _is_sm90() -> bool:
|
||||
"""True on sm_90 (H100/H200/H20): selects the sm_90 tuning table."""
|
||||
return current_platform.get_device_capability() == (9, 0)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_rows", "num_requests"])
|
||||
def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
q_ptr,
|
||||
@@ -476,7 +482,8 @@ def _select_sm120_config(
|
||||
"""(block_n, target_splits, num_warps) retuned on sm_120 (RTX PRO 6000
|
||||
Blackwell), split by cache dtype: bf16 and fp8 favour different configs on
|
||||
sm_120, most visibly on the large-prefill region. Each entry is the fastest
|
||||
config that stays correct on its own path; the main win is more warps."""
|
||||
config that stays correct on its own path; the main win is more warps.
|
||||
"""
|
||||
if is_fp8:
|
||||
if base_programs > 2048:
|
||||
return (32, 2, 1) if use_prefill_config else (64, 1, 2)
|
||||
@@ -509,6 +516,33 @@ def _select_sm120_config(
|
||||
return 32, 4, 1
|
||||
|
||||
|
||||
def _select_sm90_config(
|
||||
base_programs: int, use_prefill_config: bool, is_fp8: bool
|
||||
) -> tuple[int, int, int]:
|
||||
"""(block_n, target_splits, num_warps) tuned on sm_90 (H20)."""
|
||||
if base_programs > 2048:
|
||||
return (32, 1, 1) if use_prefill_config else (64, 1, 2)
|
||||
if is_fp8:
|
||||
if base_programs <= 24:
|
||||
return 64, 64, 2
|
||||
if base_programs <= 32:
|
||||
return 32, 16, 1
|
||||
if base_programs <= 64:
|
||||
return 32, 8, 1
|
||||
if base_programs <= 128:
|
||||
return 32, 4, 1
|
||||
if base_programs <= 256:
|
||||
return 32, 8, 1
|
||||
return 32, 4, 1
|
||||
if base_programs <= 32:
|
||||
return 64, 64, 2
|
||||
if base_programs <= 64:
|
||||
return 32, 16, 1
|
||||
if base_programs <= 256:
|
||||
return 32, 8, 1
|
||||
return 32, 4, 1
|
||||
|
||||
|
||||
def _select_config(
|
||||
num_rows: int,
|
||||
num_kv_heads: int,
|
||||
@@ -521,13 +555,18 @@ def _select_config(
|
||||
Keyed on base_programs = num_rows * num_kv_heads. The bp > 2048 region splits
|
||||
on use_prefill_config (capture-stable: at FULL-graph capture max_query_len is
|
||||
the uniform decode/verify length). This default table was tuned on GB300;
|
||||
sm_120 (RTX PRO 6000 Blackwell) dispatches to _select_sm120_config instead.
|
||||
sm_120 (RTX PRO 6000 Blackwell) dispatches to _select_sm120_config instead,
|
||||
and sm_90 (Hopper) to _select_sm90_config.
|
||||
"""
|
||||
base_programs = num_rows * num_kv_heads
|
||||
if _is_sm120():
|
||||
BLOCK_N, target_splits, num_warps = _select_sm120_config(
|
||||
base_programs, use_prefill_config, is_fp8
|
||||
)
|
||||
elif _is_sm90():
|
||||
BLOCK_N, target_splits, num_warps = _select_sm90_config(
|
||||
base_programs, use_prefill_config, is_fp8
|
||||
)
|
||||
elif base_programs > 2048:
|
||||
BLOCK_N, target_splits, num_warps = (
|
||||
(32, 1, 1) if use_prefill_config else (64, 1, 2)
|
||||
|
||||
Reference in New Issue
Block a user