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:
lesj0610
2026-09-16 13:41:12 +09:00
517 changed files with 21831 additions and 6611 deletions
+3 -1
View File
@@ -237,7 +237,9 @@ class DeepseekV32Attention(MLAAttention):
fp8_attention = is_quantized_kv_cache(self.kv_cache_dtype)
self._fp8_query = fp8_attention and self.impl.supports_quant_query_input
self._fp8_kv_needs_view = fp8_attention and self.kv_cache_dtype != "fp8_ds_mla"
self._fp8_kv_needs_view = fp8_attention and not self.kv_cache_dtype.endswith(
"_ds_mla"
)
self._index_rope_interleave = getattr(config, "indexer_rope_interleave", False)
+61 -7
View File
@@ -150,6 +150,7 @@ def _fused_norm_rope_kernel(
mla_cache_ds_scale_ptr,
mla_cache_ds_rope_ptr,
MLA_CACHE_DS_MLA: tl.constexpr,
MLA_CACHE_NVFP4: tl.constexpr,
MLA_NUM_TILES: tl.constexpr,
MLA_TILE_DIM: tl.constexpr,
# Top k indices
@@ -261,6 +262,56 @@ def _fused_norm_rope_kernel(
mla_block_idx = slot_idx // mla_block_size
mla_block_off = slot_idx % mla_block_size
if MLA_CACHE_NVFP4:
# nvfp4_ds_mla layout (352 B/token, KV_DIM == 512):
# [0, 256) 512 e2m1 NoPE, packed 2/byte (low nibble = even)
# [256, 320) 64 e4m3 RoPE, unscaled
# [320, 352) 32 e4m3 NoPE scales, byte-permuted
# Keep in lockstep with concat_and_cache_nvfp4_ds_mla (CUDA) and
# nvfp4_sf_byte() in FlashMLA: byte(s) = 8*(s&3) + (s>>2).
byte_base = (
mla_block_idx * mla_cache_block_stride
+ mla_block_off * mla_cache_entry_stride
)
kv_2d = tl.reshape(kv_c.to(tl.float32), (MLA_NUM_TILES, MLA_TILE_DIM))
amax = tl.max(tl.abs(kv_2d), axis=1, keep_dims=True)
# sf = e4m3(max(amax/6, 2^-9)), round-to-nearest like
# cvt_warp_fp16_to_fp4.
sf8 = tl.maximum(amax * (1.0 / 6.0), 0.001953125).to(tl.float8e4nv)
q = kv_2d * (1.0 / sf8.to(tl.float32))
qp = tl.reshape(q, (KV_DIM // 2, 2))
sel = tl.arange(0, 2)[None, :]
even = tl.sum(tl.where(sel == 0, qp, 0.0), axis=1)
odd = tl.sum(tl.where(sel == 1, qp, 0.0), axis=1)
# Same instruction the CUDA writer uses, so the two are bit-exact
# by construction: dest byte = {high: odd, low: even}.
packed = tl.inline_asm_elementwise(
"{ .reg .b8 t; .reg .b32 w;"
" cvt.rn.satfinite.e2m1x2.f32 t, $2, $1;"
" mov.b32 w, {t, t, t, t}; and.b32 $0, w, 255; }",
"=r,f,f",
[even, odd],
dtype=tl.int32,
is_pure=True,
pack=1,
).to(tl.uint8)
tl.store(
mla_cache_ptr + byte_base + tl.arange(0, KV_DIM // 2),
packed.to(tl.float8e4nv, bitcast=True),
)
# RoPE: unscaled e4m3, interleaved like the fp8_ds_mla path
rope_base = mla_cache_ptr + byte_base + KV_DIM // 2
tl.store(rope_base + dim_off * 2, r1.to(tl.float8e4nv))
tl.store(rope_base + dim_off * 2 + 1, r2.to(tl.float8e4nv))
# scales, permuted: byte(s) = 8*(s&3) + (s>>2)
sf_tile = tl.arange(0, MLA_NUM_TILES)
sf_perm = 8 * (sf_tile % 4) + (sf_tile // 4)
tl.store(
mla_cache_ptr + byte_base + (KV_DIM // 2 + 64) + sf_perm,
tl.reshape(sf8, (MLA_NUM_TILES,)),
)
return
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
@@ -491,7 +542,8 @@ def fused_norm_rope(
idx_cache_stride = 0
# --- MLA KV cache setup ---
mla_cache_ds_mla = mla_kv_cache_dtype == "fp8_ds_mla"
mla_cache_nvfp4 = mla_kv_cache_dtype == "nvfp4_ds_mla"
mla_cache_ds_mla = mla_kv_cache_dtype == "fp8_ds_mla" or mla_cache_nvfp4
mla_cache_fp8 = is_quantized_kv_cache(mla_kv_cache_dtype) and not mla_cache_ds_mla
mla_num_tiles = 1
mla_ds_scale_view = torch.empty(0, dtype=torch.float32, device=device)
@@ -499,11 +551,12 @@ def fused_norm_rope(
if mla_kv_cache is not None:
mla_block_size = mla_kv_cache.shape[1]
if mla_cache_ds_mla:
# 656-byte custom layout addressed in bytes; mla_cache_ptr is the
# 1-byte fp8 view, so block/entry strides are byte offsets and the
# fp32/bf16 views share the same buffer.
assert kv_dim == 512, "fp8_ds_mla requires kv_lora_rank == 512"
mla_num_tiles = kv_dim // 128
# Custom byte-addressed layout: 656 B/token for fp8_ds_mla, 352 B
# for nvfp4_ds_mla. mla_cache_ptr is the 1-byte fp8 view, so
# block/entry strides are byte offsets and the fp32/bf16 views
# (fp8_ds_mla only) share the same buffer.
assert kv_dim == 512, "ds_mla layouts require kv_lora_rank == 512"
mla_num_tiles = kv_dim // 16 if mla_cache_nvfp4 else kv_dim // 128
u8_cache = mla_kv_cache.view(torch.uint8)
mla_block_stride = u8_cache.stride(0)
mla_entry_stride = u8_cache.stride(1)
@@ -596,7 +649,8 @@ def fused_norm_rope(
mla_k_scale,
mla_ds_scale_view,
mla_ds_rope_view,
mla_cache_ds_mla,
mla_cache_ds_mla and not mla_cache_nvfp4,
mla_cache_nvfp4,
mla_num_tiles,
kv_dim // mla_num_tiles if mla_cache_ds_mla else 1,
# Top k indices buffer
+1 -10
View File
@@ -957,16 +957,7 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
self.hc_dim = self.hc_mult * config.hidden_size
self.rms_norm_eps = config.rms_norm_eps
# Three aux streams: one per non-default input GEMM in
# DeepseekV4Attention._run_parallel_input_projections
# (compressor kv_score, indexer.weights_proj, indexer.compressor
# kv_score). fused_wqa_wkv stays on the default stream.
# Disable them on ROCm because of hang issues.
aux_stream_list = (
None
if current_platform.is_rocm()
else [torch.cuda.Stream() for _ in range(3)]
)
aux_stream_list = [torch.cuda.Stream() for _ in range(3)]
self.device = current_platform.device_type
# Reserved topk indices buffer for all Indexer layers to reuse.
+194
View File
@@ -23,6 +23,7 @@ from vllm.models.deepseek_v4.sparse_mla import (
from vllm.platforms import current_platform
from vllm.platforms.rocm import _ON_GFX950
from vllm.triton_utils import tl, triton
from vllm.utils.multi_stream_utils import execute_in_parallel
from vllm.v1.attention.backend import (
CommonAttentionMetadata,
)
@@ -571,6 +572,199 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
self.register_buffer("_fused_compressor_weight", None, persistent=False)
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
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.
Dict metadata marks piecewise cudagraph, whose eager breaks rebuild
the attention inputs on the owning stream. Forking side streams
there would rely on runtime HIP event sync, which is unreliable in
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.
"""
attn_metadata = get_forward_context().attn_metadata
return self.aux_stream_list is not None and (
torch.cuda.is_current_stream_capturing()
or not isinstance(attn_metadata, dict)
)
def _run_sequential_pipeline(
self,
hidden_states: torch.Tensor,
positions: torch.Tensor,
o_padded: torch.Tensor,
) -> None:
"""Disable ROCm streams when the current execution region cannot overlap."""
aux_streams = self.aux_stream_list
self.aux_stream_list = None
try:
qr_kv, kv_score, indexer_kv_score, indexer_weights = (
self._run_parallel_input_projections(hidden_states)
)
qr, qr_scale, kv = self._split_qkv_and_norm(qr_kv)
self._prepare_and_attn_fn(
hidden_states,
qr,
kv,
qr_scale,
kv_score,
indexer_kv_score,
indexer_weights,
positions,
o_padded,
)
finally:
self.aux_stream_list = aux_streams
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
llama_4_scaling: torch.Tensor | None = None,
) -> torch.Tensor:
# Pre-allocate attention output with FlashMLA-padded head count.
# The op writes into `o_padded`; we slice to n_local_heads after.
num_tokens = hidden_states.shape[0]
o_padded = torch.empty(
(num_tokens, self.padded_heads, self.head_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
)
if self._enable_csa_multi_stream():
# The ROCm override consumes these sentinels inside the capture
# boundary, moving the stream fan-out ahead of the projections.
self._prepare_and_attn_fn(
hidden_states,
None,
None,
None,
None,
None,
None,
positions,
o_padded,
)
else:
self._run_sequential_pipeline(hidden_states, positions, o_padded)
o = o_padded[:, : self.n_local_heads, :]
# Inverse-RoPE + wo_a + wo_b output projection (platform-specific).
return self._o_proj(o, positions)
def _prepare_and_attn(
self,
hidden_states: torch.Tensor,
qr: torch.Tensor | None,
kv: torch.Tensor | None,
qr_scale: torch.Tensor | None,
kv_score: torch.Tensor | None,
indexer_kv_score: torch.Tensor | None,
indexer_weights: torch.Tensor | None,
positions: torch.Tensor,
o_padded: torch.Tensor,
) -> None:
"""Run the ROCm CSA fork/join inside the graph 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
# recursion here.
if aux_streams is None:
saved_streams = self.aux_stream_list
self.aux_stream_list = None
try:
super()._prepare_and_attn(
hidden_states,
cast(torch.Tensor, qr),
cast(torch.Tensor, kv),
qr_scale,
cast(torch.Tensor, kv_score),
cast(torch.Tensor, indexer_kv_score),
cast(torch.Tensor, indexer_weights),
positions,
o_padded,
)
finally:
self.aux_stream_list = saved_streams
return
# 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():
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
def default_chain():
qr_kv = self._fused_wqa_wkv_gemm(hidden_states)
qr_out, qr_scale_out, kv_out = self._split_qkv_and_norm(qr_kv)
q = self._wq_b_proj(qr_out, qr_scale_out).view(
-1, self.n_local_heads, self.head_dim
)
attn_metadata = get_forward_context().attn_metadata
q = self._fused_qnorm_rope_kv_insert(q, kv_out, positions, attn_metadata)
return q, qr_out, qr_scale_out, kv_out
def main_compressor_chain() -> None:
score = torch.mm(
hidden_states,
compressor.fused_wkv_wgate.weight.T,
out_dtype=torch.float32,
)
compressor(score, positions, self.rotary_emb)
def indexer_compressor_chain() -> None:
score = torch.mm(
hidden_states,
indexer.compressor.fused_wkv_wgate.weight.T,
out_dtype=torch.float32,
)
indexer.compressor(score, positions, self.indexer_rotary_emb)
(q, qr_out, qr_scale_out, kv_out), _ = execute_in_parallel(
default_chain,
[main_compressor_chain, indexer_compressor_chain],
self.ln_events[0],
self.ln_events[1:3],
aux_streams[:2],
enable=True,
)
indexer_weights_out, _ = indexer.weights_proj(hidden_states)
# The indexer compressor already ran on aux stream 1; build queries only.
index_q, index_q_scale, weights = indexer(
hidden_states,
qr_out,
None,
indexer_weights_out,
positions,
self.indexer_rotary_emb,
qr_scale_out,
skip_compressor=True,
)
self._sparse_indexer_and_attn(
hidden_states,
index_q,
index_q_scale,
weights,
q,
kv_out,
positions,
o_padded,
)
@classmethod
def get_padded_num_q_heads(cls, num_heads: int) -> int:
return num_heads
+17 -14
View File
@@ -318,7 +318,6 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# graph and MRV1 produces garbage (#51430).
self._prepare_and_attn_fn = self._prepare_and_attn_eager
# Will be None on ROCm for now.
self.aux_stream_list = aux_stream_list
# [0]: GEMM start / post-GEMM event0. [1..3]: GEMM done events;
# [1] doubles as post-GEMM event1. Reuse is safe: GEMM fully joins
@@ -584,7 +583,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# Keep Q projection and KV insertion on the default stream. The indexer
# and MLA compressor use aux streams 0 and 1; aux 2 is internal to the
# indexer. ROCm runs the same work sequentially without aux streams.
# indexer.
if indexer is not None:
assert compressor is not None
q, (indexer_inputs, _) = execute_in_parallel(
@@ -671,7 +670,6 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# fused_wqa_wkv (heaviest) on default; the three lighter input GEMMs
# on aux streams 0..2 when their owning module exists. ln_events[0]
# is the fan-out start event; ln_events[1..3] are per-aux done events.
# On ROCm, aux_streams is None and execute_in_parallel runs serially.
aux_fns: list[Callable[[], Any] | None] = [None, None, None]
if self.compressor is not None:
@@ -1055,11 +1053,12 @@ class DeepseekV4Indexer(nn.Module):
self,
hidden_states: torch.Tensor,
qr: torch.Tensor,
compressed_kv_score: torch.Tensor,
compressed_kv_score: torch.Tensor | None,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
rotary_emb: nn.Module,
qr_scale: torch.Tensor | None = None,
skip_compressor: bool = False,
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
compressor = self.compressor
@@ -1072,7 +1071,8 @@ class DeepseekV4Indexer(nn.Module):
):
# candidates num smaller than topk, every candidate is selected
# but we still need to build k cache
compressor(compressed_kv_score, positions, rotary_emb)
if not skip_compressor:
compressor(compressed_kv_score, positions, rotary_emb)
assert self.topk_indices_buffer is not None
num_tokens = (
indexer_metadata.num_decode_tokens
@@ -1102,15 +1102,18 @@ class DeepseekV4Indexer(nn.Module):
use_fp4=self.use_fp4_kv,
)
# compressor returns None and writes K to the indexer KV cache; the
# join orders that write before indexer_op (skip_k_cache_insert=True).
(q_quant, weights), _ = maybe_execute_in_parallel(
wq_b_and_q_quant,
lambda: compressor(compressed_kv_score, positions, rotary_emb),
self.ln_events[0],
self.ln_events[1],
self.aux_stream,
)
if not skip_compressor:
# compressor returns None and writes K to the indexer KV cache; the
# join orders that write before indexer_op (skip_k_cache_insert=True).
(q_quant, weights), _ = maybe_execute_in_parallel(
wq_b_and_q_quant,
lambda: compressor(compressed_kv_score, positions, rotary_emb),
self.ln_events[0],
self.ln_events[1],
self.aux_stream,
)
else:
q_quant, weights = wq_b_and_q_quant()
if isinstance(q_quant, tuple):
q, q_scale = q_quant
else:
@@ -309,12 +309,22 @@ class FusedIndexerQRopeQuantTritonKernel(
)
def _indexer_weights_out_dtypes(vllm_config: Any) -> tuple[torch.dtype, ...]:
"""Weights dtypes the model's indexer layers ask for: fp32 for the dense
scoring kernels, plus bf16 when the DeepSeek V4.1 sparse-logits indexer
(`SparseMQAIndexer`) is enabled."""
if vllm_config.attention_config.indexer_sparse_logits:
return (torch.float32, torch.bfloat16)
return (torch.float32,)
class FusedIndexerQRopeMxFp4TritonKernel(
VllmTritonJitKernel["FusedIndexerQRopeMxFp4TritonKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
dtype: torch.dtype
weights_out_dtype: torch.dtype
num_heads: int
index_q_half_rot_dim: int
index_q_head_dim: int
@@ -434,12 +444,14 @@ class FusedIndexerQRopeMxFp4TritonKernel(
self,
*,
dtype: torch.dtype,
weights_out_dtype: torch.dtype,
num_heads: int,
head_dim: int,
rope_dim: int,
) -> CompileKey:
return self.CompileKey(
dtype=dtype,
weights_out_dtype=weights_out_dtype,
num_heads=num_heads,
index_q_half_rot_dim=rope_dim // 2,
index_q_head_dim=head_dim,
@@ -456,6 +468,7 @@ class FusedIndexerQRopeMxFp4TritonKernel(
return self._trace_dispatch(self.dispatch)(
dtype=vllm_config.model_config.dtype,
weights_out_dtype=_indexer_weights_out_dtypes(vllm_config),
num_heads=num_heads,
head_dim=head_dim,
rope_dim=rope_dim,
@@ -491,7 +504,7 @@ class FusedIndexerQRopeMxFp4TritonKernel(
shape=(1, compile_key.num_heads, scale_head_dim),
),
index_weights_out=TritonWarmupTensor(
torch.float32,
compile_key.weights_out_dtype,
shape=(1, compile_key.num_heads),
),
)
@@ -540,12 +553,17 @@ def fused_indexer_q_rope_quant(
index_weights_softmax_scale: float,
index_weights_head_scale: float,
use_fp4: bool = False,
weights_out_dtype: torch.dtype = torch.float32,
) -> tuple[
torch.Tensor | tuple[torch.Tensor, torch.Tensor],
torch.Tensor,
]:
"""Fused RoPE + quantize Q for the sparse indexer.
``weights_out_dtype`` is the dtype the downstream scoring kernel takes:
fp32 for the dense MQA-logits kernels, bf16 for DeepGEMM's sparse
MQA-logits kernels (CUDA MXFP4 path only).
Weight-fold semantics (important — the two paths differ):
FP8 path (use_fp4=False, default):
@@ -577,7 +595,7 @@ def fused_indexer_q_rope_quant(
num_index_q_heads = index_q.shape[1]
index_q_head_dim = index_q.shape[2]
index_weights_out = torch.empty_like(index_weights, dtype=torch.float32)
index_weights_out = torch.empty_like(index_weights, dtype=weights_out_dtype)
if use_fp4:
assert index_q_head_dim % MXFP4_BLOCK_SIZE == 0, (
@@ -613,6 +631,7 @@ def fused_indexer_q_rope_quant(
weights_out=index_weights_out,
)
elif current_platform.is_xpu():
assert weights_out_dtype == torch.float32, weights_out_dtype
torch.ops.vllm.xpu_deepseek_fused_indexer_q_rope_mxfp4(
index_q,
positions,
@@ -647,6 +666,7 @@ def fused_indexer_q_rope_quant(
index_q_scale.view(torch.int32).squeeze(-1),
), index_weights_out
assert weights_out_dtype == torch.float32, weights_out_dtype
fp8_dtype = current_platform.fp8_dtype()
use_fnuz = fp8_dtype == torch.float8_e4m3fnuz
fp8_max = 224.0 if use_fnuz else 448.0
+2 -1
View File
@@ -198,11 +198,12 @@ class DeepseekV4CPUIndexer(DeepseekV4Indexer):
self,
hidden_states: torch.Tensor,
qr: torch.Tensor,
compressed_kv_score: torch.Tensor,
compressed_kv_score: torch.Tensor | None,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
rotary_emb: nn.Module,
qr_scale: torch.Tensor | None = None,
skip_compressor: bool = False,
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
"""CPU override: no aux streams, so wq_b_and_q_quant and the
compressor run straight-line instead of through
@@ -23,10 +23,11 @@ from vllm.model_executor.warmup.jit_warmup_cutedsl_helper import (
class DequantGatherKCacheKernel(
VllmCuTeDSLJitKernel["DequantGatherKCacheKernel.CompileKey"]
):
# Hard-coded for DSv4.
# DSv4 geometry. The record format (how much of the row is quantized and
# how wide a scale group is) comes from the compile key: V4 quantizes the
# 448 NoPE dims in groups of 64 and keeps a bf16 RoPE tail, V4.1 quantizes
# all 512 dims in groups of 32 (MXFP8) and has no tail.
head_dim = 512
fp8_dim = 448
group_size = 64 # 1 scale per 64 elems
num_warps = 4
tb_size = num_warps * 32
num_stages = 4
@@ -35,17 +36,20 @@ class DequantGatherKCacheKernel(
class CompileKey:
block_size: int
has_gather_lens: bool
fp8_dim: int = 448
group_size: int = 64 # dims per scale
@staticmethod
def kernel(compile_key: CompileKey) -> Any:
head_dim = DequantGatherKCacheKernel.head_dim
fp8_dim = DequantGatherKCacheKernel.fp8_dim
group_size = DequantGatherKCacheKernel.group_size
fp8_dim = compile_key.fp8_dim
group_size = compile_key.group_size
num_warps = DequantGatherKCacheKernel.num_warps
tb_size = DequantGatherKCacheKernel.tb_size
num_stages = DequantGatherKCacheKernel.num_stages
bf16_dim = head_dim - fp8_dim
data_dim = fp8_dim + bf16_dim * 2
scale_bytes = head_dim // group_size
block_size = compile_key.block_size
@cute.jit
@@ -62,8 +66,8 @@ class DequantGatherKCacheKernel(
):
op = cpasync.CopyG2SOp(cute.nvgpu.LoadCacheMode.GLOBAL)
cp16_atom = cute.make_copy_atom(op, Uint32, num_bits_per_copy=128)
cp8_atom = cute.make_copy_atom(
cpasync.CopyG2SOp(), Uint8, num_bits_per_copy=64
cp_scale_atom = cute.make_copy_atom(
cpasync.CopyG2SOp(), Uint8, num_bits_per_copy=scale_bytes * 8
)
page_id = block_table[req_id, pos // block_size]
block_offset = pos % block_size
@@ -88,7 +92,7 @@ class DequantGatherKCacheKernel(
)
elif idx == cutlass.const_expr(data_dim // 16):
cute.copy(
cp8_atom,
cp_scale_atom,
k_scale[page_id, block_offset, None],
s_kscale[None, stage_id],
)
@@ -119,8 +123,8 @@ class DequantGatherKCacheKernel(
)[None, warp_id, None]
s_kscale = smem.allocate_tensor(
Uint8,
cute.make_layout((8, num_warps, num_stages)),
byte_alignment=8,
cute.make_layout((scale_bytes, num_warps, num_stages)),
byte_alignment=scale_bytes,
)[None, warp_id, None]
# Prepare for 16B cp.async, also for BF16 smem loads later.
@@ -239,14 +243,16 @@ class DequantGatherKCacheKernel(
# Last 64 elems are BF16 tail, corresponds to dequant1 of last
# 8 threads. We have 448 FP8 + 64 BF16 -> 28x 16B for FP8 +
# 8x 16B for BF16.
if lane_id + 32 >= fp8_dim // 8:
idx = fp8_dim // 16 + (lane_id + 32) - fp8_dim // 8
cute.copy(
cp16_atom,
s_kdata_16B_slice[(None, idx), compute_stage],
dequant1,
)
# 8x 16B for BF16. The V4.1 record is fully quantized and has
# no tail.
if cutlass.const_expr(bf16_dim > 0): # noqa: SIM102
if lane_id + 32 >= fp8_dim // 8:
idx = fp8_dim // 16 + (lane_id + 32) - fp8_dim // 8
cute.copy(
cp16_atom,
s_kdata_16B_slice[(None, idx), compute_stage],
dequant1,
)
# Store two 16B BF16 chunks per lane: first half, then second half.
dst = out_slice[req_id, offset + i, (None, lane_id)]
@@ -269,7 +275,7 @@ class DequantGatherKCacheKernel(
):
# Split k_cache into k_data and k_scale. Each [block_size, head_bytes]
# block is actually a concat of
# [block_size, fp8_dim + bf16_dim * 2] and [block_size, 8].
# [block_size, fp8_dim + bf16_dim * 2] and [block_size, scale_bytes].
k_data = cute.make_tensor(
k_cache.iterator,
layout=cute.make_layout(
@@ -282,8 +288,8 @@ class DequantGatherKCacheKernel(
k_scale = cute.make_tensor(
k_cache.iterator + (block_size * data_dim),
layout=cute.make_layout(
(k_cache.shape[0], block_size, 8),
stride=(k_cache.stride[0], 8, 1),
(k_cache.shape[0], block_size, scale_bytes),
stride=(k_cache.stride[0], scale_bytes, 1),
),
)
@@ -311,10 +317,14 @@ class DequantGatherKCacheKernel(
*,
block_size: int,
has_gather_lens: bool,
fp8_dim: int = 448,
group_size: int = 64,
) -> CompileKey:
return self.CompileKey(
block_size=block_size,
has_gather_lens=has_gather_lens,
fp8_dim=fp8_dim,
group_size=group_size,
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
@@ -345,9 +355,11 @@ class DequantGatherKCacheKernel(
def warmup_inputs(self, compile_key: CompileKey) -> tuple[Any, ...]:
num_reqs = cute.sym_int()
head_dim = self.head_dim
fp8_dim = self.fp8_dim
fp8_dim = compile_key.fp8_dim
block_size = compile_key.block_size
head_bytes = fp8_dim + (head_dim - fp8_dim) * 2 + 8
head_bytes = (
fp8_dim + (head_dim - fp8_dim) * 2 + head_dim // compile_key.group_size
)
out = make_fake_tensor(BFloat16, (num_reqs, cute.sym_int(), head_dim), 16)
k_cache = cute.runtime.make_fake_tensor(
@@ -384,10 +396,14 @@ class DequantGatherKCacheKernel(
block_table: torch.Tensor,
block_size: int,
offset: int,
fp8_dim: int = 448,
group_size: int = 64,
) -> CuTeDSLLaunchSpec["DequantGatherKCacheKernel.CompileKey"]:
compile_key = self.dispatch(
block_size=block_size,
has_gather_lens=gather_lens is not None,
fp8_dim=fp8_dim,
group_size=group_size,
)
launch_args = (
out,
@@ -165,6 +165,7 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
rope_dim: int
num_heads: int
cos_sin_dtype: type[cutlass.Numeric]
weights_out_dtype: type[cutlass.Numeric]
coarsen: int
@staticmethod
@@ -177,6 +178,7 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
# process multiple heads at the same time to armotize RoPE load costs
coarsen = compile_key.coarsen
tb_size = IndexerQMxFp4Kernel.tb_size
weights_out_dtype = compile_key.weights_out_dtype
assert num_heads % coarsen == 0
# later we will use 32B load = 16 BF16 elems
@@ -287,7 +289,7 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
weight_head_id = global_tid % num_heads
weights_out[weight_token_id, weight_head_id] = (
weights[weight_token_id, weight_head_id].to(Float32) * scale
)
).to(weights_out_dtype)
@cute.jit
def host_entrypoint(
@@ -320,11 +322,13 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
self,
*,
cos_sin_dtype: type[cutlass.Numeric],
weights_out_dtype: type[cutlass.Numeric],
**compile_key_fields: int,
) -> CompileKey:
return self.CompileKey(
**compile_key_fields,
cos_sin_dtype=cos_sin_dtype,
weights_out_dtype=weights_out_dtype,
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
@@ -340,11 +344,17 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
if num_heads <= 0 or head_dim <= 0 or rope_dim <= 0:
return []
# The DeepSeek V4.1 sparse-logits indexer takes bf16 weights; the
# dense scoring kernels take fp32.
weights_out_dtypes: tuple[type[cutlass.Numeric], ...] = (Float32,)
if vllm_config.attention_config.indexer_sparse_logits:
weights_out_dtypes = (Float32, BFloat16)
return self._trace_dispatch(self.dispatch)(
head_dim=head_dim,
rope_dim=rope_dim,
num_heads=num_heads,
cos_sin_dtype=Float32,
weights_out_dtype=weights_out_dtypes,
coarsen=(1, 4),
)
@@ -380,7 +390,9 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
divisibility=4,
)
weights_out = make_fake_tensor(
Float32, (num_tokens, compile_key.num_heads), divisibility=4
compile_key.weights_out_dtype,
(num_tokens, compile_key.num_heads),
divisibility=4,
)
return (
positions,
@@ -413,6 +425,7 @@ class IndexerQMxFp4Kernel(VllmCuTeDSLJitKernel["IndexerQMxFp4Kernel.CompileKey"]
rope_dim=cos_sin_cache.shape[-1],
num_heads=num_heads,
cos_sin_dtype=torch_to_cute_dtype(cos_sin_cache.dtype),
weights_out_dtype=torch_to_cute_dtype(weights_out.dtype),
coarsen=1 if num_tokens < 512 else 4,
)
launch_args = (
@@ -259,6 +259,8 @@ def _insert_context_kv(
attn.padded_heads,
attn.eps,
block_size,
True, # apply_q_norm (unused: the query is a discarded dummy)
attn.kv_mxfp8,
)
elif cache_dtype == torch.bfloat16:
swa_3d = swa_cache.view(-1, block_size, attn.head_dim)
@@ -54,8 +54,8 @@ from vllm.models.common.ops.sequence_parallel import (
from vllm.models.deepseek_v4.amd.model import (
DeepseekV4MoE as DeepseekV4MoEBase,
)
from vllm.models.deepseek_v4_1.amd.rocm import DeepseekV41ROCMAiterMLAAttention
from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention
from vllm.models.deepseek_v41.amd.rocm import DeepseekV41ROCMAiterMLAAttention
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
from vllm.sequence import IntermediateTensors
from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backends.registry import AttentionBackendEnum
@@ -274,7 +274,7 @@ class DeepseekV4DecoderLayer(nn.Module):
# copies and the identity pre-mix selects copy 0.
assert self.hc_attn_fn_broadcast is not None
residual = x.unsqueeze(1).expand(-1, self.hc_mult, -1).contiguous()
post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual, post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual,
self.hc_attn_fn_broadcast,
self.hc_attn_scale,
@@ -288,7 +288,7 @@ class DeepseekV4DecoderLayer(nn.Module):
)
else:
residual = x
post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual, post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual,
self.hc_attn_fn,
self.hc_attn_scale,
@@ -301,18 +301,7 @@ class DeepseekV4DecoderLayer(nn.Module):
pre_mix=pre_mix,
)
else:
residual = self.mhc_post(x, residual, post_mix, res_mix)
if self.engram is not None and engram_hashes is not None:
# Engram injection happens between the previous sublayer's
# post and this block's pre, on the full hc stream, so the
# mix coefficients see the injected stream.
residual = self.engram(
residual,
engram_hashes[:, self.engram.layer_hash_index],
engram_mask,
)
post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual,
pre_args = (
self.hc_attn_fn,
self.hc_attn_scale,
self.hc_attn_base,
@@ -321,8 +310,37 @@ class DeepseekV4DecoderLayer(nn.Module):
self.hc_eps,
self.hc_post_alpha,
self.hc_sinkhorn_iters,
pre_mix=pre_mix,
)
if self.engram is not None and engram_hashes is not None:
# Engram injection happens between the previous sublayer's
# post and this block's pre, on the full hc stream, so the
# mix coefficients see the injected stream. That read of the
# residual is what stops the post from fusing into the pre
# here, unlike the attention seam below.
residual = self.mhc_post(x, residual, post_mix, res_mix)
residual = self.engram(
residual,
engram_hashes[:, self.engram.layer_hash_index],
engram_mask,
)
residual, post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual, *pre_args, pre_mix=pre_mix
)
else:
(
residual,
post_mix,
res_mix,
x,
attn_pre,
) = self.mhc_pre_delayed(
residual,
*pre_args,
pre_mix=pre_mix,
sublayer_out=x,
post_layer_mix=post_mix,
comb_res_mix=res_mix,
)
x = self.attn_norm(x)
if self.use_sequence_parallel:
@@ -332,8 +350,7 @@ class DeepseekV4DecoderLayer(nn.Module):
if self.use_sequence_parallel:
x = sp_reduce_scatter(x)
residual = self.mhc_post(x, residual, post_mix, res_mix)
post_mix, res_mix, x, ffn_pre = self.mhc_pre_delayed(
residual, post_mix, res_mix, x, ffn_pre = self.mhc_pre_delayed(
residual,
self.hc_ffn_fn,
self.hc_ffn_scale,
@@ -344,6 +361,9 @@ class DeepseekV4DecoderLayer(nn.Module):
self.hc_post_alpha,
self.hc_sinkhorn_iters,
pre_mix=attn_pre,
sublayer_out=x,
post_layer_mix=post_mix,
comb_res_mix=res_mix,
)
x = self.ffn_norm(x)
x = self.ffn(x, input_ids)
@@ -13,9 +13,9 @@ from vllm.distributed import (
)
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention
from vllm.models.deepseek_v4_1.common.ops import dequantize_and_gather_k_cache
from vllm.models.deepseek_v4_1.sparse_mla import (
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,
@@ -4,6 +4,7 @@
DeepseekV4 MLA Attention Layer
"""
import math
from abc import ABC, abstractmethod
from collections.abc import Callable
from functools import cached_property
@@ -25,8 +26,9 @@ from vllm.model_executor.layers.linear import (
RowParallelLinear,
)
from vllm.model_executor.layers.sparse_attn_indexer import SparseAttnIndexer
from vllm.model_executor.layers.sparse_mqa_indexer import SparseMQAIndexer
from vllm.models.common.ops import fused_q_kv_rmsnorm
from vllm.models.deepseek_v4_1.common.ops import (
from vllm.models.deepseek_v41.common.ops import (
MXFP4_BLOCK_SIZE,
fused_indexer_q_rope_quant,
indexer_k_norm_rope_store,
@@ -49,8 +51,9 @@ from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.models.utils import extract_layer_index
from vllm.models.deepseek_v4_1.common.rope import build_deepseek_v4_rope
from vllm.models.deepseek_v4_1.compressor import DeepseekCompressor
from vllm.models.deepseek_v41.common.rope import build_deepseek_v4_rope
from vllm.models.deepseek_v41.compressor import DeepseekCompressor
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.multi_stream_utils import (
execute_in_parallel,
@@ -62,6 +65,9 @@ from vllm.v1.attention.backends.mla.indexer import (
dsa_indexer_uses_fp4,
get_max_prefill_buffer_size,
)
from vllm.v1.attention.backends.mla.sparse_indexer import (
DeepseekV41SparseIndexerBackend,
)
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekV4SWACache
from vllm.v1.kv_cache_interface import (
KVCacheSpec,
@@ -109,6 +115,16 @@ def _fill_short_context_topk_indices(
)
# Which packed fp8_ds_mla record a V4.1 layer writes. FlashMLA decodes
# DeepSeek's V4.1 record -- all 512 dims (RoPE included) as fp8 e4m3 with one
# UE8M0 scale per 32 dims, 512 data bytes + 16 scale bytes per token, pages
# rounded to the kernel's 512 B TMA stride -- only in its SM100 sparse-decode
# kernels. Every other arch keeps the V4 record: 448 fp8 NoPE + 64 bf16 RoPE
# plus 7 UE8M0 scales of 64 dims and a pad byte (584 B, 576 B pages).
def _use_v41_mxfp8_kv_record() -> bool:
return current_platform.is_device_capability_family(100)
def _resolve_dsv4_kv_cache_dtype(
use_fp8_ds_mla_layout: bool,
kv_cache_dtype: str,
@@ -156,7 +172,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
``DeepseekV4FlashInferSM120Attention`` /
``DeepseekV4FlashInferMLAAttention`` (CUDA) or
``DeepseekV41ROCMAiterMLAAttention`` (ROCm) — selected by the platform-specific
deepseek_v4_1 model module. The base is never instantiated directly.
deepseek_v41 model module. The base is never instantiated directly.
"""
# Provided by the platform subclass.
@@ -445,6 +461,9 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
self.kv_cache_dtype, self.kv_cache_torch_dtype = _resolve_dsv4_kv_cache_dtype(
self._uses_fp8_ds_mla_layout(), cache_config.cache_dtype, cache_config
)
self.kv_mxfp8 = _use_v41_mxfp8_kv_record()
self.kv_bytes_per_token = 528 if self.kv_mxfp8 else 584
self.kv_page_alignment = 512 if self.kv_mxfp8 else 576
self.swa_cache_layer = DeepseekV4SWACache(
head_dim=self.head_dim,
@@ -454,6 +473,8 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
cache_config=cache_config,
backend_cls=self.swa_backend_cls,
block_size=32,
packed_bytes_per_token=self.kv_bytes_per_token,
packed_page_alignment=self.kv_page_alignment,
)
# The attention layer itself was already registered with the
@@ -536,7 +557,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
"FLASHMLA_SPARSE_DSV41",
"ROCM_FLASHMLA_SPARSE_DSV4",
):
from vllm.models.deepseek_v4_1.common.ops.cache_utils import (
from vllm.models.deepseek_v41.common.ops.cache_utils import (
_COMBINE_TOPK_SWA_INDICES_KERNEL,
)
@@ -581,7 +602,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
@cached_property
def _can_fuse_query_quant(self) -> bool:
from vllm.models.deepseek_v4_1.common.ops.query_quant import (
from vllm.models.deepseek_v41.common.ops.query_quant import (
can_fuse_query_quant,
)
@@ -600,7 +621,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
"""
qr, kv = qr_kv.split([self.q_lora_rank, self.head_dim], dim=-1)
if self.q_lora_rank % 32 == 0 and self._can_fuse_query_quant:
from vllm.models.deepseek_v4_1.common.ops.query_quant import (
from vllm.models.deepseek_v41.common.ops.query_quant import (
fused_q_kv_rmsnorm_quant,
)
@@ -879,6 +900,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
self.eps,
swa_metadata.block_size,
False,
self.kv_mxfp8,
)
# Plain-row path: the [num_blocks, block_size, 512] cache stores the KV
@@ -934,9 +956,9 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# DeepseekV4SWACache.
if not self.is_kv_source:
return None
# fp8_ds_mla is a UE8M0 block-scaled uint8 layout and needs 576B
# alignment; plain bf16 / per-tensor fp8 rows use natural element-size
# pages.
# fp8_ds_mla is a UE8M0 block-scaled uint8 layout whose page rounds up
# to the decode kernel's TMA stride; plain bf16 / per-tensor fp8 rows
# use natural element-size pages.
uses_fp8_ds_mla_layout = self.kv_cache_dtype == "fp8_ds_mla"
return MLAAttentionSpec(
block_size=vllm_config.cache_config.block_size,
@@ -945,12 +967,13 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
dtype=torch.uint8 if uses_fp8_ds_mla_layout else self.kv_cache_torch_dtype,
tokens_per_state=self.compress_ratio,
cache_dtype_str=self.kv_cache_dtype,
alignment=576 if uses_fp8_ds_mla_layout else 512,
alignment=self.kv_page_alignment if uses_fp8_ds_mla_layout else 512,
model_version="deepseek_v4",
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
# DeepseekV4: 448B NoPE + 128B RoPE + 8B fp8 scale = 584B per token;
# head_size stays semantic (512).
state_content_bytes=584 if uses_fp8_ds_mla_layout else None,
# Packed record width; head_size stays semantic (512).
state_content_bytes=(
self.kv_bytes_per_token if uses_fp8_ds_mla_layout else None
),
)
def _compressed_kv_cache(self) -> torch.Tensor:
@@ -979,7 +1002,9 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
self.cache_config = cache_config
self.dtype = dtype
self.compress_ratio = compress_ratio
compilation_config = get_current_vllm_config().compilation_config
vllm_config = get_current_vllm_config()
self.sparse_logits = vllm_config.attention_config.indexer_sparse_logits
compilation_config = 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
@@ -992,19 +1017,34 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
# head_dim already carries the fp8 scale padding
# tokens_per_state=1 for V3.2, >1 for DeepseekV4; same cache layout.
uses_fp8_ds_mla_layout = vllm_config.cache_config.cache_dtype == "fp8_ds_mla"
page_alignment = (
576 if uses_fp8_ds_mla_layout and not _use_v41_mxfp8_kv_record() else 512
)
return MLAAttentionSpec(
block_size=self.cache_config.block_size,
num_kv_heads=1,
head_size=self.head_dim,
dtype=self.dtype,
tokens_per_state=self.compress_ratio,
# 576B for FlashMLA packing; 512B for FlashInfer sparse (#44577).
alignment=576 if uses_fp8_ds_mla_layout else 512,
# The indexer page shares a physical block with the main KV cache
# (the block stride is the sum of every page in the group), so it
# has to carry the same padding: the packed record's TMA stride,
# else 512B for FlashInfer sparse (#44577).
alignment=page_alignment,
# DeepGEMM's paged sparse MQA logits address pages by the block
# stride, which packs every layer's page in this layout, and need
# it 512B-aligned; the main KV record read from the same blocks
# needs its own TMA stride, so keep both.
block_stride_alignment=(
math.lcm(512, page_alignment) if self.sparse_logits else None
),
)
def forward(self): ...
def get_attn_backend(self) -> type[AttentionBackend]:
if self.sparse_logits:
return DeepseekV41SparseIndexerBackend
return DeepseekV41IndexerBackend
@@ -1104,21 +1144,52 @@ class DeepseekV4Indexer(nn.Module):
self.k_norm = RMSNorm(self.head_dim, config.rms_norm_eps)
self.k_cache = k_cache
self.indexer_op = SparseAttnIndexer(
self.k_cache,
self.quant_block_size,
self.scale_fmt,
self.topk_tokens,
self.head_dim,
self.max_model_len,
self.max_total_seq_len,
self.topk_indices_buffer,
skip_k_cache_insert=True,
use_fp4_cache=self.use_fp4_kv,
compress_ratio=self.compress_ratio,
candidate_blocks=candidate_block_buffer,
candidate_block_size=candidate_block_size,
candidate_write=candidate_write,
# Candidate consumers can score only the candidate blocks (opt-in);
# the candidate source and pre-candidate indexers stay dense.
use_sparse_logits = (
vllm_config.attention_config.indexer_sparse_logits
and candidate_block_buffer is not None
and not candidate_write
)
self.indexer_op: SparseAttnIndexer | SparseMQAIndexer
if use_sparse_logits:
if not self.use_fp4_kv:
raise ValueError(
"attention_config.indexer_sparse_logits requires the MXFP4 "
"indexer cache (attention_config.indexer_kv_dtype='mxfp4')."
)
assert candidate_block_buffer is not None
assert topk_indices_buffer is not None
self.indexer_op = SparseMQAIndexer(
self.k_cache,
self.topk_tokens,
self.head_dim,
self.max_total_seq_len,
topk_indices_buffer,
candidate_block_buffer,
candidate_block_size,
)
else:
self.indexer_op = SparseAttnIndexer(
self.k_cache,
self.quant_block_size,
self.scale_fmt,
self.topk_tokens,
self.head_dim,
self.max_model_len,
self.max_total_seq_len,
self.topk_indices_buffer,
skip_k_cache_insert=True,
use_fp4_cache=self.use_fp4_kv,
compress_ratio=self.compress_ratio,
candidate_blocks=candidate_block_buffer,
candidate_block_size=candidate_block_size,
candidate_write=candidate_write,
)
# The fused Q kernel writes the per-head weights in the dtype the
# scoring kernels take, so no cast runs per step.
self.indexer_weights_dtype = (
SparseMQAIndexer.weights_dtype if use_sparse_logits else torch.float32
)
def _produce_k(
@@ -1206,6 +1277,7 @@ class DeepseekV4Indexer(nn.Module):
self.softmax_scale,
self.n_head**-0.5,
use_fp4=self.use_fp4_kv,
weights_out_dtype=self.indexer_weights_dtype,
)
if isinstance(q_quant, tuple):
q, q_scale = q_quant
@@ -36,6 +36,18 @@ from vllm.triton_utils import tl, triton
from vllm.utils.import_utils import has_cutedsl
from vllm.utils.math_utils import next_power_of_2
# Per-token byte width of the two paged fp8 records. Both put a page's whole
# data region ahead of its whole scale region, so ``k_cache.shape[-1]`` -- the
# width the KV-cache spec publishes -- identifies the record:
# V4 (584 B): 448 fp8 e4m3 NoPE + 64 bf16 RoPE, then 7 UE8M0 scales of 64
# dims each plus a pad byte.
# V4.1 (528 B): all 512 dims as fp8 e4m3 (RoPE included), then 16 UE8M0
# scales of 32 dims each. FlashMLA's ``ModelType::V41``.
V4_BYTES_PER_TOKEN = 584
V41_BYTES_PER_TOKEN = 528
V41_QUANT_BLOCK = 32
V41_NUM_SCALES = 512 // V41_QUANT_BLOCK # 16
@triton.jit
def quantize_and_insert_k_kernel(
@@ -163,6 +175,67 @@ def quantize_and_insert_k_kernel(
tl.store(bf16_out_ptr + chunk_offsets, bf16_vals)
@triton.jit
def _quantize_and_insert_k_mxfp8_kernel(
k_ptr, # [num_tokens, 512] bf16
slot_mapping_ptr, # [num_tokens] int64
k_cache_ptr, # [num_blocks, block_bytes] as uint8 (flattened view)
num_tokens,
head_dim: tl.constexpr, # 512, RoPE dims included
scale_dim: tl.constexpr, # 16
quant_block: tl.constexpr, # 32 dims per UE8M0 scale
cache_block_size: tl.constexpr, # paged cache block size, in tokens
block_stride: tl.constexpr, # total bytes per block (padded)
fp8_max: tl.constexpr,
use_fnuz: tl.constexpr = False,
):
"""Quantize a bf16 K row to MXFP8 and insert it into a V4.1 paged cache.
One program per token. Unlike the V4 record there is no bf16 tail, so every
dim is scaled.
"""
pid = tl.program_id(0)
if pid >= num_tokens:
return
slot_idx = tl.load(slot_mapping_ptr + pid)
if slot_idx == -1:
return
block_idx = slot_idx // cache_block_size
pos_in_block = slot_idx % cache_block_size
# int64: block_idx * block_stride can exceed 2^31 with many KV-cache blocks.
cache_block_ptr = k_cache_ptr + block_idx.to(tl.int64) * block_stride
token_data_ptr = cache_block_ptr + pos_in_block * head_dim
token_scale_ptr = (
cache_block_ptr + cache_block_size * head_dim + pos_in_block * scale_dim
)
d = tl.arange(0, head_dim)
x = tl.load(k_ptr + pid.to(tl.int64) * head_dim + d).to(tl.float32)
tiles = tl.reshape(x, (scale_dim, quant_block))
# Floor the absmax like the CUDA encoder so an all-zero tile still lands on
# a finite scale.
amax = tl.maximum(tl.max(tl.abs(tiles), 1), 1e-4)
exponent = tl.ceil(tl.log2(amax * (1.0 / fp8_max)))
scaled = tl.clamp(
tiles * tl.reshape(tl.exp2(-exponent), (scale_dim, 1)), -fp8_max, fp8_max
)
if use_fnuz: # noqa: SIM108
fp8 = scaled.to(tl.float8e4b8)
else:
fp8 = scaled.to(tl.float8e4nv)
tl.store(
token_data_ptr + d, tl.reshape(fp8.to(tl.uint8, bitcast=True), (head_dim,))
)
# UE8M0 encoding: stored_value = exponent + 127 (bias).
encoded = tl.minimum(tl.maximum(exponent + 127.0, 0.0), 255.0)
tl.store(token_scale_ptr + tl.arange(0, scale_dim), encoded.to(tl.uint8))
def quantize_and_insert_k_cache(
k: torch.Tensor, # [num_tokens, 512] bf16
k_cache: torch.Tensor, # [num_blocks, block_bytes] uint8
@@ -170,16 +243,13 @@ def quantize_and_insert_k_cache(
block_size: int = 64,
is_ue8m0: bool = True,
use_fnuz: bool = False,
bytes_per_token: int = V4_BYTES_PER_TOKEN,
):
"""
Quantize K tensor and insert into paged K cache.
K Cache block layout (block_size=64 tokens):
- First 64 * 576 = 36864 bytes: Token data
- Each token: 448 bytes (fp8) + 128 bytes (bf16)
- Next 64 * 8 = 512 bytes: Scales
- Each token: 8 bytes (uint8 scales, 7 real + 1 padding)
- Padded to multiple of 576
``bytes_per_token`` picks the record (see the module header): the V4 one,
or V4.1's all-dims MXFP8 one.
``use_fnuz=True`` selects FNUZ E4M3 cache encoding and is only valid on
platforms whose FP8 format is FNUZ. ``use_fnuz=False`` selects OCP E4M3,
@@ -196,6 +266,26 @@ def quantize_and_insert_k_cache(
num_tokens = slot_mapping.shape[0]
block_stride = k_cache.stride(0) # bytes per block
if bytes_per_token == V41_BYTES_PER_TOKEN:
if use_fnuz and not current_platform.is_fp8_fnuz():
raise ValueError("use_fnuz=True requires a platform using FNUZ FP8")
_quantize_and_insert_k_mxfp8_kernel[(num_tokens,)](
k,
slot_mapping,
k_cache,
num_tokens,
head_dim=512,
scale_dim=V41_NUM_SCALES,
quant_block=V41_QUANT_BLOCK,
cache_block_size=block_size,
block_stride=block_stride,
fp8_max=get_fp8_min_max()[1]
if use_fnuz
else torch.finfo(torch.float8_e4m3fn).max,
use_fnuz=use_fnuz,
)
return
TOKEN_FP8_DIM = 448
TOKEN_BF16_DIM = 64
TOKEN_SCALE_DIM = 8
@@ -343,6 +433,69 @@ def _dequantize_and_gather_k_kernel(
tl.store(output_row_ptr + bf16_output_offset + chunk_offsets, bf16_vals)
@triton.jit
def _dequantize_and_gather_k_mxfp8_kernel(
out_ptr,
out_stride0,
out_stride1,
k_cache_ptr,
seq_lens_ptr,
block_table_ptr,
offset,
gather_lens_ptr,
max_blocks_per_seq: tl.constexpr,
head_dim: tl.constexpr, # 512
scale_dim: tl.constexpr, # 16
quant_block: tl.constexpr, # 32
cache_block_size: tl.constexpr,
block_stride: tl.constexpr,
use_fnuz: tl.constexpr = False,
):
"""Gather V4.1 MXFP8 rows into a bf16 workspace, dequantizing in place."""
batch_idx = tl.program_id(0)
worker_id = tl.program_id(1)
num_workers = tl.num_programs(1)
seq_len = tl.load(seq_lens_ptr + batch_idx)
if gather_lens_ptr is not None: # noqa: SIM108
gather_len = tl.load(gather_lens_ptr + batch_idx)
else:
gather_len = seq_len
start_pos = seq_len - gather_len
d = tl.arange(0, head_dim)
s = tl.arange(0, scale_dim)
for i in range(worker_id, gather_len, num_workers):
pos = start_pos + i
block_in_seq = pos // cache_block_size
pos_in_block = pos % cache_block_size
block_table_row_ptr = block_table_ptr + batch_idx * max_blocks_per_seq
physical_block_idx = tl.load(block_table_row_ptr + block_in_seq) # int32
# int64: physical_block_idx * block_stride can exceed 2^31.
cache_block_ptr = k_cache_ptr + physical_block_idx.to(tl.int64) * block_stride
token_data_ptr = cache_block_ptr + pos_in_block * head_dim
token_scale_ptr = (
cache_block_ptr + cache_block_size * head_dim + pos_in_block * scale_dim
)
x_uint8 = tl.load(token_data_ptr + d)
if use_fnuz:
x_fp8 = x_uint8.to(tl.float8e4b8, bitcast=True)
else:
x_fp8 = x_uint8.to(tl.float8e4nv, bitcast=True)
tiles = tl.reshape(x_fp8.to(tl.float32), (scale_dim, quant_block))
# UE8M0: scale = 2^(stored_value - 127).
encoded = tl.load(token_scale_ptr + s)
scale = tl.exp2(encoded.to(tl.float32) - 127.0)
dequant = tl.reshape(tiles * tl.reshape(scale, (scale_dim, 1)), (head_dim,))
output_row_ptr = out_ptr + batch_idx * out_stride0 + (offset + i) * out_stride1
tl.store(output_row_ptr + d, dequant.to(tl.bfloat16))
def dequantize_and_gather_k_cache_triton(
# [num_reqs, max_num_tokens, head_size]
out: torch.Tensor,
@@ -358,6 +511,28 @@ def dequantize_and_gather_k_cache_triton(
offset: int,
use_fnuz: bool = False,
) -> None:
num_reqs = seq_lens.shape[0]
NUM_WORKERS = 128
if k_cache.shape[-1] == V41_BYTES_PER_TOKEN:
_dequantize_and_gather_k_mxfp8_kernel[(num_reqs, NUM_WORKERS)](
out,
out.stride(0),
out.stride(1),
k_cache,
seq_lens,
block_table,
offset,
gather_lens,
max_blocks_per_seq=block_table.shape[-1],
head_dim=512,
scale_dim=V41_NUM_SCALES,
quant_block=V41_QUANT_BLOCK,
cache_block_size=block_size,
block_stride=k_cache.stride(0),
use_fnuz=use_fnuz,
)
return
TOKEN_FP8_DIM = 448
TOKEN_BF16_DIM = 64
TOKEN_SCALE_DIM = 8
@@ -365,8 +540,6 @@ def dequantize_and_gather_k_cache_triton(
FP8_MAX = 448.0
TOKEN_DATA_SIZE = TOKEN_FP8_DIM + TOKEN_BF16_DIM * 2
num_reqs = seq_lens.shape[0]
NUM_WORKERS = 128
_dequantize_and_gather_k_kernel[(num_reqs, NUM_WORKERS)](
out,
out.stride(0),
@@ -408,6 +581,8 @@ def dequantize_and_gather_k_cache(
) -> None:
"""Dequantize and gather a paged DSv4 K cache.
The record is read off ``k_cache.shape[-1]``; see the module header.
``use_fnuz`` MUST match the encoder of the specific cache being read:
``False`` for ``compressed_k_cache`` (Triton encoder is OCP everywhere),
``current_platform.is_fp8_fnuz()`` for ``swa_k_cache`` (C++ encoder
@@ -419,6 +594,7 @@ def dequantize_and_gather_k_cache(
_DEQUANT_GATHER_K_CACHE_CUTEDSL_KERNEL,
)
mxfp8 = k_cache.shape[-1] == V41_BYTES_PER_TOKEN
_DEQUANT_GATHER_K_CACHE_CUTEDSL_KERNEL(
out=out,
k_cache=k_cache,
@@ -427,6 +603,8 @@ def dequantize_and_gather_k_cache(
block_table=block_table,
block_size=block_size,
offset=offset,
fp8_dim=512 if mxfp8 else 448,
group_size=V41_QUANT_BLOCK if mxfp8 else 64,
)
return
@@ -232,10 +232,13 @@ def rope_quant_insert(
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``.
layout: ``uint8`` is the fp8_ds_mla paged layout, whose record the
per-token byte width names -- 584 B for V4 (576 value bytes and eight
segregated UE8M0 scale bytes, including one zero padding scale) or 528 B
for V4.1 (512 MXFP8 value bytes covering the RoPE dims too, then 16 UE8M0
scales of 32 dims each). ``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
@@ -246,8 +249,15 @@ def rope_quant_insert(
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,)](
assert kv_cache.shape[-1] in (584, 528), (
f"unsupported paged KV record width {kv_cache.shape[-1]}"
)
kernel = (
_rope_quant_insert_mxfp8_kernel
if kv_cache.shape[-1] == 528
else _rope_quant_insert_kernel
)
kernel[(num_tokens,)](
latent,
positions,
cos_sin_cache,
@@ -338,6 +348,60 @@ def _rope_quant_insert_kernel(
tl.store(rope_dst + d - 448, rotated.to(tl.bfloat16), d >= 448)
@triton.jit
def _rope_quant_insert_mxfp8_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,
):
"""V4.1 record: RoPE first, then MXFP8-quantize all 512 dims.
The RoPE dims are quantized here too, so unlike the V4 kernel the rotation
has to happen before the scales are picked.
"""
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)
rotated = tl.interleave(even * c - odd * s, odd * c + even * s)
if SANITIZE_CACHE_NANS:
rotated = tl.where(rotated == rotated, rotated, 0.0)
page = cache + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
values = page + (slot % CACHE_BLOCK) * 512
scales = page + CACHE_BLOCK * 512 + (slot % CACHE_BLOCK) * 16
quant = tl.reshape(rotated, (16, 32))
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), (16, 1))
fp8 = tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv)
tl.store(values + d, tl.reshape(fp8.to(tl.uint8, bitcast=True), (512,)))
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 + tl.arange(0, 16), encoded.to(tl.uint8))
@triton.jit
def _rope_plain_insert_kernel(
latent,
@@ -12,7 +12,7 @@ from vllm.forward_context import get_forward_context
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
from vllm.models.deepseek_v4_1.common.ops.fused_compress_quant_cache import (
from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
fused_save_compress_norm,
rope_quant_insert,
)
@@ -207,7 +207,7 @@ class DSparkDeepseekV4Model(nn.Module):
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, residual, post_mix, res_mix, pre_mix, _ = layer(
hidden_states,
positions,
input_ids,
@@ -217,15 +217,14 @@ class DSparkDeepseekV4Model(nn.Module):
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)
if self.use_sequence_parallel:
hidden_states = sp_all_gather(hidden_states)[:full_num_tokens]
return hidden_states
@@ -235,65 +234,24 @@ def _insert_context_kv(
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,
"""Insert normalized context KV without constructing an unused query."""
# The bound cache already is [num_blocks, block_size, bytes_per_token], so
# the record width needs no per-layer attribute -- one whose name the
# attention layer is free to change (kv_bytes_per_token has to become
# swa_bytes_per_token once the sliding-window and compressed records can
# differ). block_size stays the layer's, so the op's size(1) check still
# cross-checks the two rather than restating the tensor.
cache = attn.swa_cache_layer.kv_cache
torch.ops._C.fused_deepseek_v4_kv_rope_insert(
kv,
cache,
slot_mapping,
positions,
attn.rotary_emb.cos_sin_cache,
attn.swa_cache_layer.block_size,
attn._flashinfer_fp8_kv_scale if cache.dtype == torch.float8_e4m3fn else None,
attn.kv_mxfp8,
)
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):
@@ -23,16 +23,16 @@ 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_v4_1.common.engram import (
from vllm.models.deepseek_v41.common.engram import (
DEAD_ID,
EngramLayout,
_engram_head_shard_weight_loader,
_engram_select_rows,
)
from vllm.models.deepseek_v4_1.common.engram import (
from vllm.models.deepseek_v41.common.engram import (
Engram as BaseEngram,
)
from vllm.models.deepseek_v4_1.common.engram import (
from vllm.models.deepseek_v41.common.engram import (
ParallelEngramEmbedding as BaseParallelEngramEmbedding,
)
from vllm.utils.platform_utils import is_uva_available
@@ -13,12 +13,12 @@ from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
compute_fp8_einsum_recipe,
deep_gemm_fp8_o_proj,
)
from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention
from vllm.models.deepseek_v4_1.common.ops import (
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_v4_1.sparse_mla import (
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4FlashMLAMetadata,
DeepseekV4SparseMLABackend,
DeepseekV4SparseMLAMetadataBuilder,
@@ -10,13 +10,13 @@ from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
compute_fp8_einsum_recipe,
deep_gemm_fp8_o_proj,
)
from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention
from vllm.models.deepseek_v4_1.common.ops import (
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_v4_1.sparse_mla import (
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4FlashMLABackend,
DeepseekV4FlashMLAMetadata,
DeepseekV41SparseSWAMetadataBuilder,
@@ -63,12 +63,12 @@ from vllm.models.deepseek_v4.nvidia.model import (
from vllm.models.deepseek_v4.nvidia.model import (
make_deepseek_v4_expert_params_mapping,
)
from vllm.models.deepseek_v4_1.attention import DeepseekV4Attention
from vllm.models.deepseek_v4_1.nvidia.flashinfer_sparse import (
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
from vllm.models.deepseek_v41.nvidia.flashinfer_sparse import (
DeepseekV4FlashInferMLAAttention,
DeepseekV4FlashInferSM120Attention,
)
from vllm.models.deepseek_v4_1.nvidia.flashmla import DeepseekV4FlashMLAAttention
from vllm.models.deepseek_v41.nvidia.flashmla import DeepseekV4FlashMLAAttention
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from vllm.utils.math_utils import cdiv
@@ -78,6 +78,7 @@ from vllm.v1.worker.ubatching import dbo_current_ubatch_id
from ..common.engram import EngramLayout, NgramHashState
from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask
from .engram import Engram, gather_engram_hashes
from .ops.mega_mhc import mhc_shifted_post_pre
if typing.TYPE_CHECKING:
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
@@ -214,17 +215,45 @@ class DeepseekV4DecoderLayer(nn.Module):
self.hc_eps = config.hc_eps
self.hc_post_alpha = 2.0
if vllm_config.kernel_config.enable_jit_warmup and current_platform.is_cuda():
from vllm.model_executor.kernels.mhc.tilelang_kernels import (
mhc_fused_post_pre_splits,
)
from vllm.model_executor.kernels.mhc.warmup import MHC_PRE_NORM_KERNEL
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
if self.use_sequence_parallel:
tp_size = vllm_config.parallel_config.tensor_parallel_size
max_tokens = (max_tokens + tp_size - 1) // tp_size
for input_size, use_pre_mix in (
(self.hidden_size, False),
(self.hc_mult * self.hidden_size, False),
(self.hc_mult * self.hidden_size, True),
):
# The epilogue compiles per projection width and per pre-mix mode.
# The first layer projects the broadcast embedding, so it reads one
# hidden_size-wide row and selects stream zero; every later sublayer
# projects the full hc stream, and collapses it with the pre-mix the
# previous sublayer carried in. Those later shapes also arrive
# through the fused post + pre-norm GEMM, which picks split-k
# factors the token sweep below never produces.
broadcast_embedding = {
"rms_numel": self.hidden_size,
"use_pre_mix_in": False,
"extra_splits": (),
}
hc_stream = {
"rms_numel": self.hc_mult * self.hidden_size,
"extra_splits": mhc_fused_post_pre_splits(
self.hidden_size, self.hc_mult
),
}
variants = [
broadcast_embedding,
{**hc_stream, "use_pre_mix_in": False},
{**hc_stream, "use_pre_mix_in": True},
]
if vllm_config.speculative_config is not None:
# Draft setups read aux hidden states out of the same collapse,
# which is its own specialization of the kernel.
variants.append(
{**hc_stream, "use_pre_mix_in": True, "write_aux": True}
)
for variant in variants:
MHC_PRE_NORM_KERNEL.register_warmup(
max_tokens=max_tokens,
hidden_size=self.hidden_size,
@@ -235,8 +264,7 @@ class DeepseekV4DecoderLayer(nn.Module):
sinkhorn_repeat=self.hc_sinkhorn_iters,
norm_eps=self.rms_norm_eps,
hc_mult=self.hc_mult,
use_pre_mix_in=use_pre_mix,
rms_numel=input_size,
**variant,
)
mix_hc = (2 + self.hc_mult) * self.hc_mult
hc_dim = self.hc_mult * self.hidden_size
@@ -295,7 +323,17 @@ class DeepseekV4DecoderLayer(nn.Module):
residual: torch.Tensor | None = None,
engram_hashes: torch.Tensor | None = None,
engram_mask: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
*,
capture_previous_aux: bool = False,
) -> tuple[
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor | None,
]:
previous_aux: torch.Tensor | None = None
# The reference collapses each sublayer's input with the *previous*
# sublayer's pre-mix: attention uses the pre-mix carried in (identity
# for the first layer), the FFN uses this layer's attention pre-mix.
@@ -335,17 +373,19 @@ class DeepseekV4DecoderLayer(nn.Module):
norm_weight=self.attn_norm.weight,
norm_eps=self.attn_norm.variance_epsilon,
)
else:
residual = mhc_post_tilelang(x, residual, post_mix, res_mix)
if self.engram is not None and engram_hashes is not None:
# Engram injection happens between the previous sublayer's
# post and this block's pre, on the full hc stream, so the
# mix coefficients see the injected stream.
residual = self.engram(
residual,
engram_hashes[:, self.engram.layer_hash_index],
engram_mask,
)
elif self.engram is not None and engram_hashes is not None:
# Engram injection happens between the previous sublayer's post
# and this block's pre, on the full hc stream, so the mix
# coefficients see the injected stream. The injection also keeps
# the post out of the pre-norm GEMM's fused prologue.
previous_post = mhc_post_tilelang(x, residual, post_mix, res_mix)
if capture_previous_aux:
previous_aux = previous_post.mean(dim=1)
residual = self.engram(
previous_post,
engram_hashes[:, self.engram.layer_hash_index],
engram_mask,
)
post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang(
residual,
self.hc_attn_fn,
@@ -360,6 +400,29 @@ class DeepseekV4DecoderLayer(nn.Module):
norm_weight=self.attn_norm.weight,
norm_eps=self.attn_norm.variance_epsilon,
)
else:
# The collapse already reads the post-mapped streams, so the mean
# aux consumers want comes out of the same kernel.
residual, post_mix, res_mix, x, attn_pre, aux = mhc_shifted_post_pre(
x,
residual,
post_mix,
res_mix,
self.hc_attn_fn,
self.hc_attn_scale,
self.hc_attn_base,
self.rms_norm_eps,
self.hc_eps,
self.hc_eps,
self.hc_post_alpha,
self.hc_sinkhorn_iters,
pre_mix=pre_mix,
norm_weight=self.attn_norm.weight,
norm_eps=self.attn_norm.variance_epsilon,
capture_aux=capture_previous_aux,
)
if capture_previous_aux:
previous_aux = aux
if self.use_sequence_parallel:
x = sp_all_gather(x)[: positions.shape[0]]
@@ -368,9 +431,11 @@ class DeepseekV4DecoderLayer(nn.Module):
if self.use_sequence_parallel:
x = sp_reduce_scatter(x)
residual = mhc_post_tilelang(x, residual, post_mix, res_mix)
post_mix, res_mix, x, ffn_pre = mhc_pre_delayed_tilelang(
residual, post_mix, res_mix, x, ffn_pre, _ = mhc_shifted_post_pre(
x,
residual,
post_mix,
res_mix,
self.hc_ffn_fn,
self.hc_ffn_scale,
self.hc_ffn_base,
@@ -384,7 +449,7 @@ class DeepseekV4DecoderLayer(nn.Module):
norm_eps=self.ffn_norm.variance_epsilon,
)
x = self.ffn(x, input_ids)
return x, residual, post_mix, res_mix, ffn_pre
return x, residual, post_mix, res_mix, ffn_pre, previous_aux
class DeepseekV4Model(nn.Module, EagleModelMixin):
@@ -631,13 +696,14 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
if not get_pp_group().is_first_rank:
assert intermediate_tensors is not None
pre_mix = intermediate_tensors["pre_mix"]
aux_hidden_states: list[torch.Tensor] = []
final_aux_recon: torch.Tensor | None = None # avoid duplicate mhc_post call
# Every layer's post runs inside the next layer's fused pre, so aux
# hidden states are read back from there instead of recomputed.
aux_hidden_by_layer: dict[int, torch.Tensor] = {}
for idx, layer in enumerate(
islice(self.layers, self.start_layer, self.end_layer),
start=self.start_layer,
):
hidden_states, residual, post_mix, res_mix, pre_mix = layer(
hidden_states, residual, post_mix, res_mix, pre_mix, previous_aux = layer(
hidden_states,
positions,
input_ids,
@@ -647,25 +713,29 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
residual,
engram_hashes,
engram_mask,
capture_previous_aux=idx in self.aux_hidden_state_layers,
)
if idx + 1 in self.aux_hidden_state_layers:
# Reconstruct the aux hidden state for draft models
aux_recon = mhc_post_tilelang(
hidden_states, residual, post_mix, res_mix
)
aux_hidden_state = aux_recon.mean(dim=1)
if previous_aux is not None:
# idx is the one-based id of the layer whose post this is.
if self.use_sequence_parallel:
aux_hidden_state = sp_all_gather(aux_hidden_state)[:full_num_tokens]
aux_hidden_states.append(aux_hidden_state)
final_aux_recon = aux_recon
previous_aux = sp_all_gather(previous_aux)[:full_num_tokens]
aux_hidden_by_layer[idx] = previous_aux
if layer is not None:
# Reuse if the last layer was captured as an aux hidden state
# The last layer has no successor to fold its post into.
hidden_states = mhc_post_tilelang(
hidden_states, residual, post_mix, res_mix
)
if self.end_layer in self.aux_hidden_state_layers:
hidden_states = final_aux_recon
else:
hidden_states = mhc_post_tilelang(
hidden_states, residual, post_mix, res_mix
)
final_aux = hidden_states.mean(dim=1)
if self.use_sequence_parallel:
final_aux = sp_all_gather(final_aux)[:full_num_tokens]
aux_hidden_by_layer[self.end_layer] = final_aux
aux_hidden_states = [
aux_hidden_by_layer[layer_id]
for layer_id in self.aux_hidden_state_layers
if layer_id in aux_hidden_by_layer
]
if not get_pp_group().is_last_rank:
return IntermediateTensors(
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,156 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
import torch
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_fused_post_pre_delayed_tilelang,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import (
_import_deep_gemm,
is_deep_gemm_supported,
mega_mhc,
)
@functools.cache
def is_mega_mhc_supported(hidden_size: int, hc_mult: int) -> bool:
"""Return whether DeepGEMM can run the DSV4.1 shifted mHC kernel."""
if not (
is_deep_gemm_supported()
and current_platform.is_device_capability_family(100)
and hidden_size > 0
and hidden_size % 1024 == 0
and hc_mult == 4
):
return False
deep_gemm = _import_deep_gemm()
return deep_gemm is not None and callable(getattr(deep_gemm, "mega_mhc", None))
def mhc_shifted_post_pre_deep_gemm(
x: torch.Tensor,
residual: torch.Tensor,
shifted_prev_mix: torch.Tensor,
post_mix: torch.Tensor,
comb_res_mix: torch.Tensor,
fn: torch.Tensor,
mix_scales: torch.Tensor,
mix_bases: torch.Tensor,
hc_norm_eps: float,
hc_pre_eps: float,
hc_post_scale: float,
sinkhorn_eps: float,
num_sinkhorn_iters: int,
rmsnorm_weight: torch.Tensor,
rmsnorm_eps: float,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run DSV4.1 shifted post, next pre, and BF16 RMSNorm with Mega mHC."""
num_tokens, hidden_size = x.shape
hc_mult = residual.shape[1]
new_residual = torch.empty_like(residual)
new_prev_mix = x.new_empty(num_tokens, hc_mult, 1, dtype=torch.float32)
new_post_mix = torch.empty_like(post_mix)
new_comb_res_mix = torch.empty_like(comb_res_mix)
y_bf16 = x.new_empty(num_tokens, hidden_size, dtype=torch.bfloat16)
mega_mhc(
x=x,
residual=residual,
shifted_prev_mix=shifted_prev_mix.unsqueeze(-1),
post_mix=post_mix,
comb_res_mix=comb_res_mix,
fn=fn,
mix_scales=mix_scales,
mix_bases=mix_bases,
hc_mult=hc_mult,
hc_norm_eps=hc_norm_eps,
hc_pre_eps=hc_pre_eps,
hc_post_scale=hc_post_scale,
sinkhorn_eps=sinkhorn_eps,
num_sinkhorn_iters=num_sinkhorn_iters,
rmsnorm_weight=rmsnorm_weight,
rmsnorm_eps=rmsnorm_eps,
rmsnorm_scale=1.0,
new_residual=new_residual,
new_prev_mix=new_prev_mix,
new_post_mix=new_post_mix,
new_comb_res_mix=new_comb_res_mix,
y_bf16=y_bf16,
)
return (
new_residual,
new_post_mix,
new_comb_res_mix,
y_bf16,
new_prev_mix.squeeze(-1),
)
def mhc_shifted_post_pre(
x: torch.Tensor,
residual: torch.Tensor,
post_layer_mix: torch.Tensor,
comb_res_mix: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
pre_mix: torch.Tensor | None = None,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 1e-6,
capture_aux: bool = False,
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
]:
"""Use Mega-mHC for carried mixing, retaining TileLang for aux capture."""
if (
pre_mix is not None
and norm_weight is not None
and not capture_aux
and x.shape[0] <= 1 << 20
and is_mega_mhc_supported(x.shape[1], residual.shape[1])
):
outputs = mhc_shifted_post_pre_deep_gemm(
x,
residual,
pre_mix,
post_layer_mix,
comb_res_mix,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_post_mult_value,
hc_sinkhorn_eps,
sinkhorn_repeat,
norm_weight,
norm_eps,
)
return *outputs, x.new_empty(0, x.shape[1])
return mhc_fused_post_pre_delayed_tilelang(
x,
residual,
post_layer_mix,
comb_res_mix,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix=pre_mix,
norm_weight=norm_weight,
norm_eps=norm_eps,
capture_aux=capture_aux,
)
+15 -7
View File
@@ -19,7 +19,11 @@ from vllm.model_executor.layers.attention.mla_attention import (
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.utils.torch_utils import (
PIN_MEMORY,
async_tensor_h2d,
is_quantized_kv_cache,
)
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
@@ -231,8 +235,12 @@ def _build_sliding_window_metadata(
query_lens = query_lens_cpu[req_start:req_end]
kv_lens = kv_lens_cpu[req_start:req_end]
num_reqs = req_end - req_start
cu_seq_lens_q_cpu = torch.zeros(num_reqs + 1, dtype=torch.int32)
cu_seq_lens_k_cpu = torch.zeros(num_reqs + 1, dtype=torch.int32)
cu_seq_lens_q_cpu = torch.zeros(
num_reqs + 1, dtype=torch.int32, pin_memory=PIN_MEMORY
)
cu_seq_lens_k_cpu = torch.zeros(
num_reqs + 1, dtype=torch.int32, pin_memory=PIN_MEMORY
)
torch.cumsum(query_lens, 0, out=cu_seq_lens_q_cpu[1:])
torch.cumsum(kv_lens, 0, out=cu_seq_lens_k_cpu[1:])
token_to_seq_cpu = torch.repeat_interleave(
@@ -248,8 +256,8 @@ def _build_sliding_window_metadata(
query_end=query_end,
cu_seq_lens_q=cu_seq_lens_q_cpu.to(device, non_blocking=True),
cu_seq_lens_k=cu_seq_lens_k_cpu.to(device, non_blocking=True),
starts=starts_cpu[req_start:req_end].to(device, non_blocking=True),
token_to_seq=token_to_seq_cpu.to(device, non_blocking=True),
starts=async_tensor_h2d(starts_cpu[req_start:req_end], device),
token_to_seq=async_tensor_h2d(token_to_seq_cpu, device),
num_kv_tokens=num_kv_tokens,
max_seq_len_q=int(query_lens.max().item()),
max_seq_len_k=int(kv_lens.max().item()),
@@ -396,8 +404,8 @@ class Dots3NoteMLAMetadataBuilder(TritonMLAMetadataBuilder):
seq_lens = common_attn_metadata.seq_lens[
reqs_start + req_start : reqs_start + req_end
]
query_lens = query_lens_cpu[req_start:req_end].to(
self.device, non_blocking=True
query_lens = async_tensor_h2d(
query_lens_cpu[req_start:req_end], self.device
)
kv_lens = torch.minimum(seq_lens, query_lens + self.sliding_window - 1)
chunk.cu_seq_lens_k.zero_()
+2 -2
View File
@@ -6,8 +6,8 @@ from vllm.platforms import current_platform
if current_platform.is_xpu():
raise NotImplementedError("GLM-5.3-Flash does not currently support XPU.")
from .nvidia.model import Glm5NextForCausalLM, Glm5NextForConditionalGeneration
from .nvidia.mtp import Glm5NextMTP
from .common.model import Glm5NextForCausalLM, Glm5NextForConditionalGeneration
from .common.mtp import Glm5NextMTP
__all__ = [
"Glm5NextForCausalLM",
@@ -65,50 +65,6 @@ def _hadamard128(x):
return x * 0.08838834764831845 # 1/sqrt(128)
# Map pool ids to physical cache slots.
def compute_pooled_write_locs(
page_table_64: torch.Tensor,
pool_ids: torch.Tensor,
pool_size: int,
) -> torch.Tensor:
"""Map logical pooled-K ids to physical flat cache slots.
``pool_size`` consecutive tokens share one pool slot that lives at the
*first* token page of each page-group. ``page_table_64`` maps token pages
to physical block ids; we gather the block id of each pool's page-group
and add the in-block pool offset.
"""
assert page_table_64.ndim == 1
pool_ids = pool_ids.to(torch.int64)
block_size = 64
pool_page_group = torch.div(pool_ids, block_size, rounding_mode="floor")
token_page_row = pool_page_group * pool_size
packed_page = page_table_64.index_select(0, token_page_row.to(torch.int64))
return packed_page.to(torch.int64) * block_size + torch.remainder(
pool_ids, block_size
)
def build_pooled_page_table(
page_table: torch.Tensor,
pool_size: int,
) -> torch.Tensor:
"""Build a pool-granular page table by taking every ``pool_size``-th
token-page column (one pool maps to ``pool_size`` token pages).
Uses gather (not strided slicing) so the result is always a fresh
row-major tensor — some downstream kernels require stride(-1) == 1.
"""
block_size = page_table.shape[-1]
assert block_size % pool_size == 0, (
f"pool_size ({pool_size}) must divide page columns ({block_size})"
)
idx = torch.arange(0, block_size, pool_size, device=page_table.device)
return page_table[..., idx].contiguous()
# Fused pool compression and cache write.
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -37,6 +37,7 @@ from vllm.platforms import current_platform
from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
from vllm.transformers_utils.configs.glm5_next import Glm5NextConfig
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata
from vllm.v1.worker.workspace import current_workspace_manager
if current_platform.is_rocm():
from vllm.models.glm5next.amd.ops.third_party.kda import (
@@ -123,6 +124,32 @@ def _cast_sigmoid(x: torch.Tensor) -> torch.Tensor:
return x.float().sigmoid()
def _resolve_kda_prefill_backend(
backend: str, head_dim: int, dtype: torch.dtype, lower_bound: float | None
) -> str:
"""Pick the chunked-prefill kernel: FlashKDA (fused CUDA, ~2-4x faster on
SM90/SM10x/SM12x for bf16, head_dim 128 and a bounded gate) or the Triton
``chunk_kda_with_fused_gate`` path. ``backend`` comes from
``additional_config.kda_prefill_backend`` (auto / triton / flashkda)."""
if backend not in ("auto", "triton", "flashkda"):
raise ValueError(f"Unsupported KDA prefill backend: {backend}")
capability = current_platform.get_device_capability()
supported = (
current_platform.is_cuda()
and capability is not None
and capability.major in (9, 10, 12)
and head_dim == 128
and dtype == torch.bfloat16
and lower_bound is not None
)
if backend == "flashkda" and not supported:
raise RuntimeError(
"FlashKDA requires CUDA SM90/SM10x/SM12x, bfloat16, head_dim=128 "
"and a bounded KDA gate."
)
return "flashkda" if supported and backend != "triton" else "triton"
class Glm5NextLinearAttention(GatedDeltaNetAttention):
head_dim: int
num_heads: int
@@ -291,6 +318,85 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
# every _forward call (it reads an env-derived flag each time).
self._conv_state_dim_first = is_conv_state_dim_first()
additional_config = vllm_config.additional_config
self.kda_prefill_backend = _resolve_kda_prefill_backend(
additional_config.get("kda_prefill_backend", "auto")
if isinstance(additional_config, dict)
else "auto",
self.head_dim,
vllm_config.model_config.dtype,
self.kda_lower_bound,
)
self._flashkda_buffer_specs: (
tuple[tuple[tuple[int, ...], torch.dtype], ...] | None
) = None
if self.kda_prefill_backend == "flashkda":
import vllm._flashkda_C # noqa: F401
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
max_seqs = vllm_config.scheduler_config.max_num_seqs
workspace_size = torch.ops._flashkda_C.get_workspace_size(
max_tokens, self.local_num_heads, max_seqs
)
self._flashkda_buffer_specs = (
(
(max_seqs, self.local_num_heads, self.head_dim, self.head_dim),
self.get_state_dtype()[1],
),
((workspace_size,), torch.uint8),
# Output buffer for steps that also carry spec-decode tokens:
# the non-spec tokens are then scattered by non_spec_token_indx.
(
(1, max_tokens, self.local_num_heads, self.head_dim),
vllm_config.model_config.dtype,
),
)
def _flashkda_prefill(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g: torch.Tensor,
beta: torch.Tensor,
initial_state: torch.Tensor,
cu_seqlens: torch.Tensor,
out: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Fused KDA chunked prefill (FlashKDA). Takes the raw gate logits ``g``
and raw ``beta`` logits, l2-normalizes q/k in-kernel and applies the
bounded gate ``lower_bound * sigmoid(exp(A_log) * (g + dt_bias))``,
matching ``chunk_kda_with_fused_gate(..., safe_gate=True)``. Writes the
attention output into ``out`` (a workspace buffer when ``None``) and
returns ``(out, final_state)``."""
assert self._flashkda_buffer_specs is not None
final_state, workspace, workspace_out = (
current_workspace_manager().get_simultaneous(*self._flashkda_buffer_specs)
)
final_state = final_state[: initial_state.shape[0]]
if out is None:
out = workspace_out[:, : q.shape[1]]
# FlashKDA hardcodes dense q/k/v/g strides; beta may be row-strided.
torch.ops._flashkda_C.fwd(
q.contiguous(),
k.contiguous(),
v.contiguous(),
g.contiguous(),
beta,
self.head_dim**-0.5,
out,
workspace,
self.A_log.view(-1),
self.dt_bias.view(-1, self.head_dim),
self.kda_lower_bound,
initial_state.contiguous(),
final_state,
cu_seqlens.contiguous(),
None,
None,
)
return out, final_state
def forward(
self,
hidden_states: torch.Tensor,
@@ -542,26 +648,42 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
initial_state = gather_initial_states(
recurrent_state, non_spec_state_indices_tensor, has_initial_state
)
(
core_attn_out_non_spec,
last_recurrent_state,
) = chunk_kda_with_fused_gate(
q=_rearr(q_ns),
k=_rearr(k_ns),
v=_rearr(v_ns),
raw_g=g1_ns,
# Chunk path wants the pre-sigmoided fp32 beta (its kernels
# don't sigmoid); beta_ns is raw bf16 from forward.
beta=_cast_sigmoid(beta_ns.squeeze(0)).unsqueeze(0),
A_log=self.A_log,
g_bias=self.dt_bias,
initial_state=initial_state,
output_final_state=True,
use_qk_l2norm_in_kernel=True,
cu_seqlens=non_spec_query_start_loc,
safe_gate=safe_gate,
lower_bound=lower_bound,
)
if self.kda_prefill_backend == "flashkda":
# Non-spec step: write straight into the layer output buffer
# (dense token order, no merge copy). Step with spec-decode
# tokens: write to the workspace buffer and scatter below.
ns_out = None if use_spec else core_attn_out[:, :num_actual_tokens]
core_attn_out_non_spec, last_recurrent_state = self._flashkda_prefill(
q=_rearr(q_ns),
k=_rearr(k_ns),
v=_rearr(v_ns),
g=g1_ns,
beta=beta_ns,
initial_state=initial_state,
cu_seqlens=non_spec_query_start_loc,
out=ns_out,
)
else:
(
core_attn_out_non_spec,
last_recurrent_state,
) = chunk_kda_with_fused_gate(
q=_rearr(q_ns),
k=_rearr(k_ns),
v=_rearr(v_ns),
raw_g=g1_ns,
# Chunk path wants the pre-sigmoided fp32 beta (its
# kernels don't sigmoid); beta_ns is raw bf16 from forward.
beta=_cast_sigmoid(beta_ns.squeeze(0)).unsqueeze(0),
A_log=self.A_log,
g_bias=self.dt_bias,
initial_state=initial_state,
output_final_state=True,
use_qk_l2norm_in_kernel=True,
cu_seqlens=non_spec_query_start_loc,
safe_gate=safe_gate,
lower_bound=lower_bound,
)
# Init cache
scatter_states(
recurrent_state,
@@ -600,14 +722,8 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
# --- merge spec / non-spec outputs back into token order ---
if use_spec and core_attn_out_non_spec is not None:
assert core_attn_out_spec is not None
merged = torch.empty(
(1, num_actual_tokens, *core_attn_out_spec.shape[2:]),
dtype=core_attn_out_non_spec.dtype,
device=core_attn_out_non_spec.device,
)
merged.index_copy_(1, spec_token_indx, core_attn_out_spec)
merged.index_copy_(1, non_spec_token_indx, core_attn_out_non_spec)
core_attn_out[0, :num_actual_tokens] = merged.squeeze(0)
core_attn_out.index_copy_(1, spec_token_indx, core_attn_out_spec)
core_attn_out.index_copy_(1, non_spec_token_indx, core_attn_out_non_spec)
elif use_spec:
assert core_attn_out_spec is not None
if spec_out is None:
@@ -1036,6 +1036,17 @@ class Glm5NextForConditionalGeneration(
has_inner_state: ClassVar[Literal[True]] = True
is_hybrid: ClassVar[Literal[True]] = True
# GLM-5.3-Flash stores the dense-MLP gate/up as separate tensors (like
# ``Glm4vMoeForConditionalGeneration``, ``glm4_moe`` and ``deepseek_v2``),
# so the fused ``gate_up_proj`` must expand to its real shard names for
# per-layer quant-scheme resolution. The identity ``gate_up_proj`` entry
# inherited from ``Glm4vForConditionalGeneration`` (pre-fused gate_up_proj)
# would otherwise route the module to ``global_quant_config`` and mismatch
# at load for mixed-precision Quark checkpoints.
packed_modules_mapping = {
"gate_up_proj": ["gate_proj", "up_proj"],
}
# NOTE: weight-prefix mapping is inherited from Glm4vForConditionalGeneration
# (``model.visual.`` -> ``visual.``, ``model.language_model.`` ->
# ``language_model.model.``, ``lm_head.`` -> ``language_model.lm_head.``),
@@ -1259,7 +1270,9 @@ def _try_load_fp8_attn_proj(
return False
suffix, (key, target_base, shard_id, is_kva) = matched
is_weight = name.endswith(".weight") and tensor.dtype == torch.float8_e4m3fn
is_scale = "weight_scale_inv" in name
# Need to accept both the DeepSeek-native ``weight_scale_inv`` and the Quark
# ``weight_scale`` names before feeding the shared block dequant below.
is_scale = "weight_scale_inv" in name or name.endswith(".weight_scale")
if not is_weight and not is_scale:
return False
@@ -22,6 +22,7 @@ from vllm.model_executor.model_loader.weight_utils import (
from vllm.model_executor.models.deepseek_mtp import SharedHead
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MixtureOfExperts
from vllm.model_executor.models.utils import maybe_prefix
from vllm.models.glm5next.nvidia.ops.fused_eh_norm import fused_eh_norm
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
@@ -33,7 +34,6 @@ from .model import (
_try_load_fp8_indexer_wk,
get_spec_layer_idx_from_weight_name,
)
from .ops.fused_eh_norm import fused_eh_norm
class Glm5NextMultiTokenPredictorLayer(nn.Module):
-766
View File
@@ -1,766 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Deadlock-free fused RS + short-conv + AG + residual + RMSNorm.
The public integration surface is ``LamportRSConv.rs_sconv_ag_add_norm``.
Liveness
--------
Large grids are deliberately split at the two communication dependencies:
1. ``_publish_input_kernel`` only publishes rank partials.
2. ``_reduce_insert_kernel`` waits, reduces, and inserts the local shard.
3. ``_sconv_publish_kernel`` only computes and publishes the local result.
4. ``_gather_norm_kernel`` waits, gathers, and normalizes.
Without PDL, CUDA stream order completes a producer before its consumer. With
PDL, every producer CTA posts all peer stores before triggering its dependent,
and the consumer executes ``gdc_wait`` before polling. A consumer therefore
waits only for stores from a producer that is already running (or complete) on
another GPU. It never waits for another block in its own grid. Consequently
spinning consumers cannot occupy resources needed by any producer, and the
wait-for graph has no cycle. The proof is independent of grid size, block
dispatch order, and occupancy.
For one token, the first three phases use eight independent channel slices to
expose enough CTA parallelism for decode latency. Each slice has exclusive
ownership of its cache and Lamport columns; the gather/RMSNorm phase retains
one CTA per token so no cross-CTA reduction or completion counter is needed.
Immediate buffer reuse (including replay of a captured CUDA graph) is also
safe. Rank R cannot republish input for call n+1 until its gather for n has
finished; that gather waited for owner O's output, which O publishes only
after consuming R's input for n. Likewise, R cannot republish output for n+1
until its reduction for n+1 has observed destination D's input; D publishes
that input only after its gather consumed R's output for n. Thus every prior
read happens-before a same-slot rewrite. Three generations reduce incidental
coupling for ordinary launches, but correctness does not depend on rotation.
The payload itself is the Lamport flag. A 32-bit store publishes two bf16s
atomically; 0x80008000 (two negative zeroes) denotes an empty pair. Real
negative zeroes are changed to positive zero before publication. Consumers
use volatile 32-bit loads and restore the sentinel after consuming a slot.
"""
from __future__ import annotations
import os
import torch
from vllm.distributed import get_tp_group
from vllm.distributed.parallel_state import in_the_same_node_as
from vllm.logger import init_logger
from vllm.triton_utils import tl, triton
logger = init_logger(__name__)
_MAX_TOKENS = 16384
_EMPTY_PAIR = tl.constexpr(0x80008000)
@triton.jit
def _pack_bf16_pairs(values):
"""Pack bf16 values into atomic u32 pairs and reserve negative zero."""
lo, hi = tl.split(values.reshape([values.shape[0] // 2, 2]))
lo = lo.to(tl.uint16, bitcast=True)
hi = hi.to(tl.uint16, bitcast=True)
lo = tl.where(lo == 0x8000, 0, lo).to(tl.uint32)
hi = tl.where(hi == 0x8000, 0, hi).to(tl.uint32)
return lo | (hi << 16)
@triton.jit
def _unpack_bf16_pairs(values):
lo = (values & 0xFFFF).to(tl.uint16).to(tl.bfloat16, bitcast=True)
hi = (values >> 16).to(tl.uint16).to(tl.bfloat16, bitcast=True)
return tl.interleave(lo, hi)
@triton.jit
def _wait_pairs(ptr, offsets, mask):
values = tl.load(ptr + offsets, mask=mask, other=0, volatile=True)
while tl.max(tl.where(mask & (values == _EMPTY_PAIR), 1, 0)) != 0:
values = tl.load(ptr + offsets, mask=mask, other=0, volatile=True)
return values
@triton.jit
def _publish_input_kernel(
stage_ptr,
peer_ptrs,
peer_offset_u32,
stride_stage_t,
C: tl.constexpr,
CS: tl.constexpr,
CS_P2: tl.constexpr,
SPLITS: tl.constexpr,
RANK: tl.constexpr,
WORLD: tl.constexpr,
USE_PDL: tl.constexpr,
launch_pdl: tl.constexpr,
):
"""Publish this rank's full partial row into every shard owner's slots."""
token = tl.program_id(0).to(tl.int64)
split = tl.program_id(1).to(tl.int64)
CSS: tl.constexpr = CS // SPLITS
pair = tl.arange(0, CS_P2 // 2)
pair_mask = pair < CSS // 2
elem = tl.arange(0, CS_P2)
elem_mask = elem < CSS
ptrs = peer_ptrs.to(tl.pointer_type(tl.uint64))
# Address generation is independent of the preceding stream kernel. The
# acquire remains before stage/peer loads, which may consume its writes.
if USE_PDL:
tl.extra.cuda.gdc_wait()
for owner in tl.static_range(WORLD):
values = tl.load(
stage_ptr + token * stride_stage_t + owner * CS + split * CSS + elem,
mask=elem_mask,
other=0.0,
)
packed = _pack_bf16_pairs(values)
base = tl.load(ptrs + owner).to(tl.pointer_type(tl.uint32))
dst = (token * WORLD + RANK) * (CS // 2) + split * (CSS // 2) + pair
tl.store(base + peer_offset_u32 + dst, packed, mask=pair_mask)
if USE_PDL:
tl.extra.cuda.gdc_launch_dependents()
@triton.jit
def _reduce_insert_kernel(
input_peer_ptrs,
input_peer_offset_u32,
cache_ptr,
slot_ptr,
stride_cache_block,
stride_cache_head,
stride_cache_token,
stride_cache_dim,
block_size,
C: tl.constexpr,
CS: tl.constexpr,
CS_P2: tl.constexpr,
SPLITS: tl.constexpr,
HEAD_SIZE: tl.constexpr,
CACHE_OFFSET: tl.constexpr,
RANK: tl.constexpr,
WORLD: tl.constexpr,
USE_PDL: tl.constexpr,
launch_pdl: tl.constexpr,
):
"""Consume all partials for this rank and insert the reduced cache row."""
token = tl.program_id(0).to(tl.int64)
split = tl.program_id(1).to(tl.int64)
CSS: tl.constexpr = CS // SPLITS
source = tl.arange(0, WORLD)
pair = tl.arange(0, CS_P2 // 2)
pair_mask = pair < CSS // 2
offsets = (
(token * WORLD + source)[:, None] * (CS // 2)
+ split * (CSS // 2)
+ pair[None, :]
)
mask = tl.full([WORLD], True, tl.int1)[:, None] & pair_mask[None, :]
input_ptrs = input_peer_ptrs.to(tl.pointer_type(tl.uint64))
input_u32 = tl.load(input_ptrs + RANK).to(tl.pointer_type(tl.uint32))
input_u32 += input_peer_offset_u32
# Slot metadata and the cache destination do not depend on input publish.
slot = tl.load(slot_ptr + token)
valid = slot >= 0
channel = tl.arange(0, CS_P2)
channel_mask = channel < CSS
global_channel = split * CSS + channel
head = tl.minimum(global_channel // HEAD_SIZE, CS // HEAD_SIZE - 1)
dim = CACHE_OFFSET + global_channel % HEAD_SIZE
safe_slot = tl.maximum(slot, 0).to(tl.int64)
dst = (
cache_ptr
+ (safe_slot // block_size) * stride_cache_block
+ head * stride_cache_head
+ (safe_slot % block_size) * stride_cache_token
+ dim * stride_cache_dim
)
if USE_PDL:
tl.extra.cuda.gdc_wait()
packed = _wait_pairs(input_u32, offsets, mask)
lo = (packed & 0xFFFF).to(tl.uint16).to(tl.bfloat16, bitcast=True)
hi = (packed >> 16).to(tl.uint16).to(tl.bfloat16, bitcast=True)
reduced = tl.interleave(
tl.sum(lo.to(tl.float32), axis=0).to(tl.bfloat16),
tl.sum(hi.to(tl.float32), axis=0).to(tl.bfloat16),
)
tl.store(
input_u32 + offsets,
tl.full([WORLD, CS_P2 // 2], _EMPTY_PAIR, tl.uint32),
mask=mask,
)
tl.store(dst, reduced, mask=valid & channel_mask)
if USE_PDL:
tl.extra.cuda.gdc_launch_dependents()
@triton.jit
def _sconv_publish_kernel(
peer_ptrs,
peer_offset_u32,
residual_ptr,
weight_ptr,
cache_ptr,
position_ptr,
sequence_ptr,
slot_ptr,
block_table_ptr,
stride_residual_t,
stride_cache_block,
stride_cache_head,
stride_cache_token,
stride_cache_dim,
stride_block_table_r,
max_blocks,
block_size,
C: tl.constexpr,
CS: tl.constexpr,
CS_P2: tl.constexpr,
SPLITS: tl.constexpr,
HEAD_SIZE: tl.constexpr,
CACHE_OFFSET: tl.constexpr,
RANK: tl.constexpr,
WORLD: tl.constexpr,
WINDOW: tl.constexpr,
USE_PDL: tl.constexpr,
launch_pdl: tl.constexpr,
):
"""Compute this rank's shard, then publish it to every rank."""
tl.static_assert(WINDOW == 4)
token = tl.program_id(0).to(tl.int64)
split = tl.program_id(1).to(tl.int64)
CSS: tl.constexpr = CS // SPLITS
channel = tl.arange(0, CS_P2)
channel_mask = channel < CSS
global_channel = split * CSS + channel
head = tl.minimum(global_channel // HEAD_SIZE, CS // HEAD_SIZE - 1)
dim = CACHE_OFFSET + global_channel % HEAD_SIZE
slot = tl.load(slot_ptr + token)
valid = slot >= 0
position = tl.load(position_ptr + token)
sequence = tl.load(sequence_ptr + token)
safe_slot = tl.maximum(slot, 0).to(tl.int64)
own_ptr = (
cache_ptr
+ (safe_slot // block_size) * stride_cache_block
+ head * stride_cache_head
+ (safe_slot % block_size) * stride_cache_token
+ dim * stride_cache_dim
)
# These loads were made visible before reduce/insert could signal us and
# are independent of its cache store. Hoisting them gives PDL useful work
# to overlap while retaining the acquire before every cache read.
residual = tl.load(
residual_ptr + token * stride_residual_t + RANK * CS + global_channel,
mask=channel_mask,
other=0.0,
)
weight0 = tl.load(
weight_ptr + global_channel * WINDOW,
mask=channel_mask,
other=0.0,
).to(tl.float32)
weight1 = tl.load(
weight_ptr + global_channel * WINDOW + 1,
mask=channel_mask,
other=0.0,
).to(tl.float32)
weight2 = tl.load(
weight_ptr + global_channel * WINDOW + 2,
mask=channel_mask,
other=0.0,
).to(tl.float32)
weight3 = tl.load(
weight_ptr + global_channel * WINDOW + 3,
mask=channel_mask,
other=0.0,
).to(tl.float32)
ptrs = peer_ptrs.to(tl.pointer_type(tl.uint64))
if USE_PDL:
tl.extra.cuda.gdc_wait()
current = tl.load(own_ptr, mask=valid & channel_mask, other=0.0)
conv = tl.zeros([CS_P2], tl.float32)
for tap_idx in tl.static_range(WINDOW):
source_position = position - (WINDOW - 1) + tap_idx
take = valid & (source_position >= 0)
if tap_idx == WINDOW - 1:
value = tl.where(take, current.to(tl.float32), 0.0)
else:
safe_position = tl.maximum(source_position, 0)
logical_block = tl.minimum(safe_position // block_size, max_blocks - 1)
physical_block = tl.load(
block_table_ptr + sequence * stride_block_table_r + logical_block,
mask=take,
other=0,
).to(tl.int64)
source_ptr = (
cache_ptr
+ physical_block * stride_cache_block
+ head * stride_cache_head
+ (safe_position % block_size) * stride_cache_token
+ dim * stride_cache_dim
)
cached = tl.load(source_ptr, mask=take & channel_mask, other=0.0)
value = tl.where(take, cached.to(tl.float32), 0.0)
if tap_idx == 0:
weight = weight0
elif tap_idx == 1:
weight = weight1
elif tap_idx == 2:
weight = weight2
else:
weight = weight3
conv += value * weight
# Preserve both bf16 rounding points of the original sublayer.
short_conv_with_skip = (conv + current.to(tl.float32)).to(tl.bfloat16)
output = (residual.to(tl.float32) + short_conv_with_skip.to(tl.float32)).to(
tl.bfloat16
)
pair = tl.arange(0, CS_P2 // 2)
pair_mask = pair < CSS // 2
packed = _pack_bf16_pairs(output)
row_offset = token * (C // 2) + RANK * (CS // 2) + split * (CSS // 2) + pair
for destination in tl.static_range(WORLD):
base = tl.load(ptrs + destination).to(tl.pointer_type(tl.uint32))
tl.store(base + peer_offset_u32 + row_offset, packed, mask=pair_mask)
if USE_PDL:
tl.extra.cuda.gdc_launch_dependents()
@triton.jit
def _gather_norm_kernel(
output_peer_ptrs,
output_peer_offset_u32,
norm_weight_ptr,
normed_ptr,
residual_out_ptr,
eps,
stride_output_t,
C: tl.constexpr,
C_P2: tl.constexpr,
RANK: tl.constexpr,
HAS_NORM: tl.constexpr,
USE_PDL: tl.constexpr,
launch_pdl: tl.constexpr,
):
"""Consume a complete row; one CTA owns all outputs for one token."""
token = tl.program_id(0).to(tl.int64)
pair = tl.arange(0, C_P2 // 2)
pair_mask = pair < C // 2
output_ptrs = output_peer_ptrs.to(tl.pointer_type(tl.uint64))
output_u32 = tl.load(output_ptrs + RANK).to(tl.pointer_type(tl.uint32))
output_u32 += output_peer_offset_u32
offsets = token * (C // 2) + pair
channel = tl.arange(0, C_P2)
channel_mask = channel < C
# Gamma is independent of the preceding sconv publication. Keep the
# acquire immediately before polling the Lamport output slots.
if HAS_NORM:
weight = tl.load(norm_weight_ptr + channel, mask=channel_mask, other=0.0)
if USE_PDL:
tl.extra.cuda.gdc_wait()
packed = _wait_pairs(output_u32, offsets, pair_mask)
row = _unpack_bf16_pairs(packed)
tl.store(
residual_out_ptr + token * stride_output_t + channel, row, mask=channel_mask
)
if HAS_NORM:
row_f32 = tl.where(channel_mask, row.to(tl.float32), 0.0)
inv_rms = tl.rsqrt(tl.sum(row_f32 * row_f32, axis=0) / C + eps)
tl.store(
normed_ptr + token * stride_output_t + channel,
(row_f32 * inv_rms * weight.to(tl.float32)).to(tl.bfloat16),
mask=channel_mask,
)
tl.store(
output_u32 + offsets,
tl.full([C_P2 // 2], _EMPTY_PAIR, tl.uint32),
mask=pair_mask,
)
if USE_PDL:
tl.extra.cuda.gdc_launch_dependents()
@triton.jit
def _validate_lamport_init_kernel(
input_peer_ptrs,
output_peer_ptrs,
bad_ptr,
num_pairs,
RANK: tl.constexpr,
BLOCK: tl.constexpr,
):
"""Validate both complete local allocations through their fabric pointers."""
offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
mask = offsets < num_pairs
ptrs_in = input_peer_ptrs.to(tl.pointer_type(tl.uint64))
ptrs_out = output_peer_ptrs.to(tl.pointer_type(tl.uint64))
local_in = tl.load(ptrs_in + RANK).to(tl.pointer_type(tl.uint32))
local_out = tl.load(ptrs_out + RANK).to(tl.pointer_type(tl.uint32))
value_in = tl.load(local_in + offsets, mask=mask, other=_EMPTY_PAIR)
value_out = tl.load(local_out + offsets, mask=mask, other=_EMPTY_PAIR)
bad = tl.max(
tl.where(mask & ((value_in != _EMPTY_PAIR) | (value_out != _EMPTY_PAIR)), 1, 0)
)
if bad != 0:
tl.atomic_max(bad_ptr, 1)
class LamportRSConv:
"""Persistent symmetric buffers for one TP group."""
def _initialize_lamport_buffers(self) -> None:
"""Arm every slot and collectively verify the exact sentinel bits.
Do not replace this with a zero-fill: Lamport readiness distinguishes
the bf16 bit pattern for -0.0 (0x8000) from every published payload.
The validation is deliberately collective so one rank cannot enter the
first polling kernel while another rank still has an unarmed buffer.
"""
if not self.buf_in.is_contiguous() or not self.buf_out.is_contiguous():
raise RuntimeError("Lamport symmetric buffers must be contiguous")
if self.buf_in.numel() % 2 or self.buf_out.numel() % 2:
raise RuntimeError("Lamport buffers must contain whole uint32 pairs")
# Fill through int16 so each bf16 lane receives the exact -0.0 bits.
# This covers all three generations and all max-token slots, including
# slots that a smaller first invocation does not touch.
self.buf_in.view(torch.int16).fill_(-0x8000)
self.buf_out.view(torch.int16).fill_(-0x8000)
torch.accelerator.synchronize(self.device)
self.tp.barrier()
# Scan the complete local allocations. Since every rank performs the
# scan and participates in MAX, success proves every symmetric backing
# allocation was armed before any rank is allowed to use generation 0.
bad = torch.logical_or(
self.buf_in.view(torch.int16).ne(-0x8000).any(),
self.buf_out.view(torch.int16).ne(-0x8000).any(),
).to(dtype=torch.float32)
bad = self.tp.all_reduce(bad)
if int(bad.item()) != 0:
raise RuntimeError("Lamport sentinel initialization failed on a TP rank")
self.tp.barrier()
def _initialize_mnnvl_buffers(self) -> None:
"""Initialize and validate FlashInfer fabric-mapped Lamport storage."""
self._mnnvl_input_handle.lamport_initialize(self.rank, torch.bfloat16)
self._mnnvl_output_handle.lamport_initialize(self.rank, torch.bfloat16)
torch.accelerator.synchronize(self.device)
self.tp.barrier()
bad = torch.zeros((), dtype=torch.int32, device=self.device)
num_pairs = self.num_buffers * self.max_tokens * self.hidden_size // 2
_validate_lamport_init_kernel[(triton.cdiv(num_pairs, 256),)](
self.input_peer_ptrs,
self.output_peer_ptrs,
bad,
num_pairs,
RANK=self.rank,
BLOCK=256,
num_warps=4,
)
bad = self.tp.all_reduce(bad.to(torch.float32))
if int(bad.item()) != 0:
raise RuntimeError("MNNVL Lamport sentinel initialization failed")
self.tp.barrier()
def __init__(
self, hidden_size: int, window_size: int, max_tokens: int = _MAX_TOKENS
) -> None:
import torch.distributed._symmetric_memory as symm_mem
tp = get_tp_group()
self.tp = tp
self.group = tp.device_group
self.world_size = tp.world_size
self.rank = tp.rank_in_group
self.device = torch.device(tp.device)
if self.world_size not in (2, 4, 8):
raise ValueError(f"TP world size must be 2, 4, or 8, got {self.world_size}")
if hidden_size % (2 * self.world_size) != 0:
raise ValueError("hidden size must produce an even shard on every rank")
if window_size != 4:
raise ValueError(f"short-conv window size must be 4, got {window_size}")
if max_tokens < 1 or max_tokens > _MAX_TOKENS:
raise ValueError(f"max_tokens must be in [1, {_MAX_TOKENS}]")
is_cross_node = not all(in_the_same_node_as(tp.cpu_group))
self.hidden_size = hidden_size
self.window_size = window_size
self.max_tokens = max_tokens
self.shard_size = hidden_size // self.world_size
# Three generations follow FlashInfer's Lamport layout. A generation
# is reused only after two intervening collective calls.
self.num_buffers = 3
self.input_generation_bytes = max_tokens * hidden_size * 2
self.output_generation_bytes = max_tokens * hidden_size * 2
self.use_pdl = torch.cuda.get_device_capability(self.device)[0] >= 9
if is_cross_node:
try:
from flashinfer.comm.mnnvl import (
McastGPUBuffer,
TorchDistBackend,
is_mnnvl_fabric_supported,
)
except ImportError as error:
raise RuntimeError(
"cross-node TP requires FlashInfer MNNVL support"
) from error
local_supported = int(
is_mnnvl_fabric_supported(torch.accelerator.current_device_index())
)
unsupported = torch.tensor(
1 - local_supported, dtype=torch.float32, device=self.device
)
unsupported = tp.all_reduce(unsupported)
if int(unsupported.item()) != 0:
raise RuntimeError("cross-node TP is supported only on MNNVL fabric")
comm_backend = TorchDistBackend(self.group)
allocation_bytes = self.num_buffers * max_tokens * hidden_size * 2
self._mnnvl_input_handle = McastGPUBuffer(
allocation_bytes,
self.world_size,
self.rank,
self.device,
comm_backend,
)
self._mnnvl_output_handle = McastGPUBuffer(
allocation_bytes,
self.world_size,
self.rank,
self.device,
comm_backend,
)
self.input_peer_ptrs = self._mnnvl_input_handle.get_buffer_ptrs_dev()
self.output_peer_ptrs = self._mnnvl_output_handle.get_buffer_ptrs_dev()
self._initialize_mnnvl_buffers()
logger.info("using FlashInfer fabric-mapped MNNVL Lamport buffers")
else:
self.buf_in = symm_mem.empty(
self.num_buffers,
max_tokens,
self.world_size,
self.shard_size,
dtype=torch.bfloat16,
device=self.device,
)
self.buf_out = symm_mem.empty(
self.num_buffers,
max_tokens,
hidden_size,
dtype=torch.bfloat16,
device=self.device,
)
group_name = self.group.group_name
input_handle = symm_mem.rendezvous(self.buf_in, group_name)
output_handle = symm_mem.rendezvous(self.buf_out, group_name)
self.input_peer_ptrs = input_handle.buffer_ptrs_dev
self.output_peer_ptrs = output_handle.buffer_ptrs_dev
self._input_handle = input_handle
self._output_handle = output_handle
self._initialize_lamport_buffers()
self.generation = 0
def usable(self, num_tokens: int) -> bool:
return 0 < num_tokens <= self.max_tokens
def rs_sconv_ag_add_norm(
self,
input_tensor: torch.Tensor,
residual: torch.Tensor,
conv_weight: torch.Tensor,
norm_weight: torch.Tensor | None,
eps: float,
cache: torch.Tensor,
positions: torch.Tensor,
block_table: torch.Tensor,
seq_idx: torch.Tensor,
slot_mapping: torch.Tensor,
off_s: int,
ws: int,
block_size: int,
) -> tuple[torch.Tensor | None, torch.Tensor]:
"""Return ``(normed | None, new_residual)``, both shaped ``[T, 6144]``."""
tokens, hidden_size = residual.shape
if not self.usable(tokens):
raise ValueError(f"num_tokens must be in [1, {self.max_tokens}]")
if hidden_size != self.hidden_size or residual.dtype != torch.bfloat16:
raise ValueError("residual must be bf16 [T, 6144]")
if (
input_tensor.shape != residual.shape
or input_tensor.dtype != torch.bfloat16
or input_tensor.stride(1) != 1
):
raise ValueError("input_tensor must be channel-contiguous bf16 [T, 6144]")
shard_size = hidden_size // self.world_size
if conv_weight.shape != (shard_size, self.window_size):
raise ValueError(
f"conv_weight must have shape [{shard_size}, {self.window_size}]"
)
if (
conv_weight.dtype != torch.bfloat16
or conv_weight.stride(0) != self.window_size
):
raise ValueError("conv_weight must be contiguous bf16")
if norm_weight is not None and (
norm_weight.shape != (hidden_size,) or norm_weight.dtype != torch.bfloat16
):
raise ValueError("norm_weight must be bf16 [6144] or None")
if cache.dtype != torch.bfloat16 or cache.ndim != 4:
raise ValueError("cache must be a 4-D bf16 tensor")
if shard_size % ws != 0 or cache.shape[1] != shard_size // ws:
raise ValueError("cache head layout is inconsistent with ws")
if off_s < 0 or off_s + ws > cache.shape[3]:
raise ValueError("cache channel offset is out of bounds")
index = self.generation
input_offset = index * self.input_generation_bytes // 4
output_offset = index * self.output_generation_bytes // 4
normed = torch.empty_like(residual) if norm_weight is not None else None
residual_out = torch.empty_like(residual)
phase_splits = 8 if tokens == 1 and shard_size % 8 == 0 else 1
phase_tile_p2 = triton.next_power_of_2(shard_size // phase_splits)
phase_grid = (tokens, phase_splits)
# Wide CTAs win before the grid saturates; smaller CTAs reduce register
# pressure once high-throughput batches provide enough parallelism.
if 128 <= tokens <= 2048:
phase_warps = 16
elif tokens > 2048:
phase_warps = 8
else:
phase_warps = 4
gather_warps = 4 if tokens >= 256 else 8
_publish_input_kernel[phase_grid](
input_tensor,
self.input_peer_ptrs,
input_offset,
input_tensor.stride(0),
C=hidden_size,
CS=shard_size,
CS_P2=phase_tile_p2,
SPLITS=phase_splits,
RANK=self.rank,
WORLD=self.world_size,
USE_PDL=self.use_pdl,
launch_pdl=self.use_pdl,
num_warps=phase_warps,
)
_reduce_insert_kernel[phase_grid](
self.input_peer_ptrs,
input_offset,
cache,
slot_mapping,
cache.stride(0),
cache.stride(1),
cache.stride(2),
cache.stride(3),
block_size,
C=hidden_size,
CS=shard_size,
CS_P2=phase_tile_p2,
SPLITS=phase_splits,
HEAD_SIZE=ws,
CACHE_OFFSET=off_s,
RANK=self.rank,
WORLD=self.world_size,
USE_PDL=self.use_pdl,
launch_pdl=self.use_pdl,
num_warps=phase_warps,
)
_sconv_publish_kernel[phase_grid](
self.output_peer_ptrs,
output_offset,
residual,
conv_weight,
cache,
positions,
seq_idx,
slot_mapping,
block_table,
residual.stride(0),
cache.stride(0),
cache.stride(1),
cache.stride(2),
cache.stride(3),
block_table.stride(0),
block_table.shape[1],
block_size,
C=hidden_size,
CS=shard_size,
CS_P2=phase_tile_p2,
SPLITS=phase_splits,
HEAD_SIZE=ws,
CACHE_OFFSET=off_s,
RANK=self.rank,
WORLD=self.world_size,
WINDOW=self.window_size,
USE_PDL=self.use_pdl,
launch_pdl=self.use_pdl,
num_warps=phase_warps,
)
_gather_norm_kernel[(tokens,)](
self.output_peer_ptrs,
output_offset,
norm_weight if norm_weight is not None else residual,
normed if normed is not None else residual_out,
residual_out,
eps,
residual.stride(0),
C=hidden_size,
C_P2=triton.next_power_of_2(hidden_size),
RANK=self.rank,
HAS_NORM=norm_weight is not None,
USE_PDL=self.use_pdl,
launch_pdl=self.use_pdl,
num_warps=gather_warps,
)
self.generation = (index + 1) % self.num_buffers
return normed, residual_out
_STATE: LamportRSConv | None = None
_STATE_FAILED = False
def initialize_lamport_rs_conv(
hidden_size: int, window_size: int, max_num_batched_tokens: int
) -> None:
"""Collectively initialize the TP-group state during model construction."""
global _STATE, _STATE_FAILED
if _STATE is not None:
if _STATE.hidden_size != hidden_size or _STATE.window_size != window_size:
raise RuntimeError("all Lamport users must share hidden and window sizes")
return
if _STATE_FAILED or os.environ.get("LAMPORT_RS_SCONV", "1") == "0":
return
try:
max_tokens = min(_MAX_TOKENS, max_num_batched_tokens)
_STATE = LamportRSConv(hidden_size, window_size, max_tokens=max_tokens)
except Exception:
_STATE_FAILED = True
logger.exception("fused collective unavailable; use the NCCL fallback")
def get_lamport_rs_conv(hidden_size: int, window_size: int) -> LamportRSConv | None:
"""Return the state initialized with the model, or ``None`` for fallback."""
if _STATE is not None and (
_STATE.hidden_size != hidden_size or _STATE.window_size != window_size
):
raise RuntimeError("all Lamport users must share hidden and window sizes")
return _STATE
-190
View File
@@ -1,190 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused CUDA kernels for the Inkling vision/audio towers.
Both kernels keep the reference paths' fp32 accumulation and per-op bf16
rounding points (native ``rms_norm`` / ``F.gelu``); outputs are frequently
bit-identical and otherwise differ by 1-2 bf16 ulps from reduction-order
(real-checkpoint-weight cosine vs reference > 0.9999998).
"""
from __future__ import annotations
import torch
from vllm.triton_utils import tl, tldevice, triton
from .norm import _get_num_warps_from_block_size
@triton.jit
def _dmel_embed_sum_norm_kernel(
idx_ptr, # [T, NB] int32 dMel bin indices (values in [0, VOCAB))
w_ptr, # [NB * VOCAB, D] bf16 embedding table
norm_w_ptr, # [D] (unused if HAS_NORM=False)
out_ptr, # [T, D] bf16
eps,
D,
stride_idx_t,
NB: tl.constexpr,
VOCAB: tl.constexpr,
D_P2: tl.constexpr,
HAS_NORM: tl.constexpr,
):
t = tl.program_id(0).to(tl.int64)
offs = tl.arange(0, D_P2)
mask = offs < D
# One embedding row per mel bin (bin b uses table rows [b*VOCAB, (b+1)*VOCAB)),
# summed in fp32 (matches torch's fp32-accumulated bf16 .sum()).
acc = tl.zeros([D_P2], dtype=tl.float32)
for b in tl.static_range(NB):
v = tl.load(idx_ptr + t * stride_idx_t + b)
row = (b * VOCAB + v).to(tl.int64)
acc += tl.load(w_ptr + row * D + offs, mask=mask, other=0.0).to(tl.float32)
h = acc.to(tl.bfloat16)
if HAS_NORM:
# Match ir.ops.rms_norm: fp32 variance/normalize, then a single-rounded
# bf16 multiply with the bf16 weight.
x32 = h.to(tl.float32)
var = tl.sum(tl.where(mask, x32 * x32, 0.0), axis=0) / D
xn = (x32 * tl.math.rsqrt(var + eps)).to(tl.bfloat16)
w = tl.load(norm_w_ptr + offs, mask=mask, other=0.0)
h = xn * w
tl.store(out_ptr + t * D + offs, h, mask=mask)
def dmel_embed_sum_norm(
dmel_idx: torch.Tensor, # [T, NB] int32
weight: torch.Tensor, # [NB * VOCAB, D] bf16
norm_weight: torch.Tensor | None,
eps: float,
) -> torch.Tensor:
"""``rmsnorm(sum_b weight[b * VOCAB + idx[:, b]])`` in one launch (no
[T, NB, D] intermediate)."""
T, nb = dmel_idx.shape
D = weight.shape[1]
assert weight.shape[0] % nb == 0
vocab = weight.shape[0] // nb
out = torch.empty((T, D), dtype=weight.dtype, device=weight.device)
if T == 0:
return out
d_p2 = triton.next_power_of_2(D)
_dmel_embed_sum_norm_kernel[(T,)](
dmel_idx,
weight,
norm_weight if norm_weight is not None else weight,
out,
eps,
D,
dmel_idx.stride(0),
NB=nb,
VOCAB=vocab,
D_P2=d_p2,
HAS_NORM=norm_weight is not None,
# Swept on GB200: 8 warps beats the block-size heuristic's 16 by ~4%
# at large T (the 80-row gather chain is latency- not lane-bound).
num_warps=8,
)
return out
@triton.jit
def _rmsnorm_gelu_kernel(
x_ptr, # [R, D] bf16
w_ptr, # [D]
out_ptr, # [R, D] bf16 (or the folded layout when FOLD)
eps,
R,
D,
D_P2: tl.constexpr,
BLOCK_M: tl.constexpr, # rows per block (>1 for small D)
HAS_GELU: tl.constexpr,
FOLD: tl.constexpr,
# fold geometry: input rows index [N, T, H, W]; the store scatters each
# row to (out_row, slot) of fold_timespace_to_depth's output layout.
FT: tl.constexpr,
FH: tl.constexpr,
FW: tl.constexpr,
TF: tl.constexpr,
HF: tl.constexpr,
):
pid = tl.program_id(0).to(tl.int64)
rows = pid * BLOCK_M + tl.arange(0, BLOCK_M)
rmask = rows < R
offs = tl.arange(0, D_P2)
mask = rmask[:, None] & (offs < D)[None, :]
x32 = tl.load(x_ptr + rows[:, None] * D + offs[None, :], mask=mask, other=0.0).to(
tl.float32
)
var = tl.sum(x32 * x32, axis=1) / D
xn = (x32 * tl.math.rsqrt(var + eps)[:, None]).to(tl.bfloat16)
w = tl.load(w_ptr + offs, mask=offs < D, other=0.0)
h = xn * w[None, :] # bf16 multiply, matching ir.ops.rms_norm
if HAS_GELU:
# Exact (erf) GELU on the bf16-rounded norm output, fp32 math,
# matching F.gelu's opmath on a bf16 tensor.
g32 = h.to(tl.float32)
h = (0.5 * g32 * (1.0 + tldevice.erf(g32 * 0.7071067811865476))).to(tl.bfloat16)
if FOLD:
# Store directly into the next layer's folded layout (a pure
# permutation — replaces the separate fold copy pass).
t = (rows // (FH * FW)) % FT
hh = (rows // FW) % FH
ww = rows % FW
n = rows // (FT * FH * FW)
slot = ((t % TF) * HF + hh % HF) * HF + ww % HF
out_row = ((n * (FT // TF) + t // TF) * (FH // HF) + hh // HF) * (
FW // HF
) + ww // HF
base = (out_row * (TF * HF * HF) + slot) * D
tl.store(out_ptr + base[:, None] + offs[None, :], h, mask=mask)
else:
tl.store(out_ptr + rows[:, None] * D + offs[None, :], h, mask=mask)
def rmsnorm_gelu(
x: torch.Tensor, # [..., D] bf16 contiguous
weight: torch.Tensor,
eps: float,
gelu: bool = True,
fold: tuple[int, int] | None = None, # (t_fold, hw_fold) of the NEXT fold
) -> torch.Tensor:
"""Fused ``gelu(rmsnorm(x))`` (or plain rmsnorm); multiple rows per block
when D is small. With ``fold``, x must be [N, T, H, W, D] and the output
comes back as ``fold_timespace_to_depth(result, *fold)``."""
D = x.shape[-1]
flat = x.reshape(-1, D)
assert flat.stride(1) == 1 and flat.stride(0) == D
R = flat.shape[0]
if fold is None:
out = torch.empty_like(flat)
ft = fh = fw = tf = hf = 1
out_shape = x.shape
else:
tf, hf = fold
N, ft, fh, fw, _ = x.shape
out_shape = (N, ft // tf, fh // hf, fw // hf, tf * hf * hf * D)
out = torch.empty(out_shape, dtype=x.dtype, device=x.device)
if R == 0:
return out.reshape(out_shape)
d_p2 = triton.next_power_of_2(D)
block_m = max(1, 4096 // d_p2)
_rmsnorm_gelu_kernel[(triton.cdiv(R, block_m),)](
flat,
weight,
out,
eps,
R,
D,
D_P2=d_p2,
BLOCK_M=block_m,
HAS_GELU=gelu,
FOLD=fold is not None,
FT=ft,
FH=fh,
FW=fw,
TF=tf,
HF=hf,
num_warps=_get_num_warps_from_block_size(d_p2 * block_m),
)
return out.reshape(out_shape)
+4 -2
View File
@@ -532,8 +532,10 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
symm_buffer,
activation_clamp=activation_clamp,
activation=self.activation,
situ_beta=self.activation_beta,
situ_linear_beta=self.activation_linear_beta,
# DeepGEMM names the SiTU gate tanh scale `activation_alpha` and the
# linear/up tanh scale `activation_beta`; beta=0 leaves up untouched.
activation_alpha=self.activation_beta or 1.0,
activation_beta=self.activation_linear_beta or 0.0,
fast_math=fast_math,
)
return y
@@ -587,34 +587,3 @@ def warp_sum_specialized(
mask_and_clamp=31,
)
return value
@cute.jit
def block_sum_specialized(
value: Float32,
warp_sums: cute.Tensor,
tidx: Int32,
warps: cutlass.Constexpr[int],
last_warp_lanes: cutlass.Constexpr[int],
last_warp_mask: cutlass.Constexpr[int],
) -> Float32:
"""Upstream-equivalent FP32 block reduction."""
lane = cute.arch.lane_idx()
warp_idx = cute.arch.warp_idx()
value = warp_sum_specialized(
value, warp_idx, lane, warps, last_warp_lanes, last_warp_mask
)
if lane == 0:
warp_sums[warp_idx] = value
cute.arch.barrier()
block_sum = Float32(0.0)
if warp_idx == 0:
if lane < Int32(warps):
block_sum = warp_sums[lane]
block_sum = cute.arch.warp_reduction_sum(block_sum)
if lane == 0:
warp_sums[0] = block_sum
cute.arch.barrier()
return warp_sums[0]
+6 -2
View File
@@ -83,6 +83,8 @@ def _swiglu_oai_quant_kernel(
limit,
HAS_LIMIT: tl.constexpr,
BLOCK_M: tl.constexpr,
FP8_MAX: tl.constexpr,
TINY: tl.constexpr,
):
"""SwiGLU-OAI (split layout) fused with per-32-block MXFP8 (E4M3 + E8M0)
quant. Each program handles ``[BLOCK_M, 32]`` of the ``[M, I]`` output (one
@@ -109,8 +111,8 @@ def _swiglu_oai_quant_kernel(
gate = tl.minimum(gate, limit)
up = tl.minimum(tl.maximum(up, -limit), limit)
act = gate * tl.sigmoid(alpha * gate) * (up + beta) # [BLOCK_M, 32] fp32
amax = tl.maximum(tl.max(tl.abs(act), axis=1), 1e-30) # [BLOCK_M]
sb = tl.minimum(tl.maximum(tl.floor(tl.log2(amax)) + 127.0, 0.0), 254.0)
amax = tl.maximum(tl.max(tl.abs(act), axis=1), TINY) # [BLOCK_M]
sb = tl.minimum(tl.maximum(tl.ceil(tl.log2(amax / FP8_MAX)) + 127.0, 0.0), 254.0)
descale = tl.exp2(sb - 127.0)
aq = (act / descale[:, None]).to(aq_ptr.dtype.element_ty)
tl.store(
@@ -173,6 +175,8 @@ def swiglu_oai_quantize_mxfp8(
0.0 if limit is None else float(limit),
HAS_LIMIT=limit is not None,
BLOCK_M=block_m,
FP8_MAX=float(torch.finfo(MXFP8_VALUE_DTYPE).max),
TINY=float(torch.finfo(torch.float32).tiny),
num_warps=4,
)
return aq, asc
+1 -1
View File
@@ -298,7 +298,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
if input_ids is None or query_start_loc is None or ngram_context is None:
raise RuntimeError("PLE inputs were not prepared")
hidden_states = hidden_states + self.ple(
hidden_states = self.ple(
hidden_states,
input_ids,
query_start_loc,
+15 -2
View File
@@ -322,6 +322,7 @@ def _ple_conv_kernel(
state_ptr,
w_ptr,
residual_ptr,
outer_residual_ptr,
state_idx_ptr,
qsl_ptr,
num_acc_ptr,
@@ -442,11 +443,21 @@ def _ple_conv_kernel(
mask=c_mask,
other=0.0,
)
# Preserve the original eager operation boundaries: short convolution is
# first accumulated into the BF16/FP16 PLE output, then the outer residual
# is added to that rounded value.
ple_output = (residual + conv_output).to(residual_ptr.dtype.element_ty)
outer_residual = tl.load(
outer_residual_ptr + output_t * C + c_offs,
mask=c_mask,
other=0.0,
)
ple_output = outer_residual.to(tl.float32) + ple_output.to(tl.float32)
if launch_pdl:
tl.extra.cuda.gdc_launch_dependents()
tl.store(
residual_ptr + output_t * C + c_offs,
residual + conv_output,
ple_output,
mask=c_mask,
)
@@ -564,6 +575,7 @@ def ple_conv(
conv_state: torch.Tensor,
conv_weights: torch.Tensor,
state_indices: torch.Tensor,
outer_residual: torch.Tensor,
*,
mode: Literal["decode", "spec", "prefill"],
dilation: int,
@@ -573,7 +585,7 @@ def ple_conv(
spec_query_len: int = 1,
token_indices: torch.Tensor | None = None,
) -> None:
"""Add short-convolution output to ``residual`` and update its state."""
"""Add short convolution and the outer residual; update state."""
BLOCK_C = 512
kernel_spec_query_len = spec_query_len if mode == "spec" else 1
T, C = inputs.shape
@@ -624,6 +636,7 @@ def ple_conv(
conv_state,
conv_weights,
residual,
outer_residual,
state_indices,
query_start_loc,
num_accepted_tokens,
+48
View File
@@ -24,6 +24,7 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
partial_output_ptr,
partial_lse_ptr,
output_ptr,
output_gate_ptr,
stride_q_row,
stride_q_head,
stride_k_block,
@@ -36,6 +37,8 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
stride_table_req,
stride_output_row,
stride_output_head,
stride_output_gate_row,
stride_output_gate_head,
num_rows,
num_cache_blocks,
num_requests,
@@ -151,6 +154,18 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
)
output_mask = head_offsets[:, None] < GROUP_SIZE
if NUM_SPLITS == 1:
# Preserve the unfused path's BF16 attention-output rounding before
# applying the gate in FP32.
normalized_output = normalized_output.to(output_ptr.dtype.element_ty)
output_gate = tl.load(
output_gate_ptr
+ row * stride_output_gate_row
+ (first_head + head_offsets[:, None]) * stride_output_gate_head
+ dim_offsets[None, :],
mask=output_mask,
other=0.0,
).to(tl.float32)
normalized_output = normalized_output.to(tl.float32) * tl.sigmoid(output_gate)
tl.store(
output_ptr
+ row * stride_output_row
@@ -186,8 +201,11 @@ def _qsa_merge_splitk_kernel(
partial_output_ptr,
partial_lse_ptr,
output_ptr,
output_gate_ptr,
stride_output_row,
stride_output_head,
stride_output_gate_row,
stride_output_gate_head,
num_rows,
HEAD_DIM: tl.constexpr,
NUM_QUERY_HEADS: tl.constexpr,
@@ -219,6 +237,16 @@ def _qsa_merge_splitk_kernel(
)
merged = tl.sum(partial_output * weights[:, None], axis=0)
merged = tl.where(denominator > 0, merged / denominator, 0.0)
# Preserve the unfused path's BF16 attention-output rounding before
# applying the gate in FP32.
merged = merged.to(output_ptr.dtype.element_ty)
output_gate = tl.load(
output_gate_ptr
+ row * stride_output_gate_row
+ head * stride_output_gate_head
+ dim_offsets
).to(tl.float32)
merged = merged.to(tl.float32) * tl.sigmoid(output_gate)
tl.store(
output_ptr + row * stride_output_row + head * stride_output_head + dim_offsets,
merged,
@@ -455,6 +483,8 @@ def qsa_sparse_paged_attention(
token_to_req: torch.Tensor,
use_prefill_config: bool,
out: torch.Tensor | None = None,
*,
output_gate: torch.Tensor,
) -> torch.Tensor:
"""Run sparse GQA directly over paged BF16 K/V caches.
@@ -496,6 +526,8 @@ def qsa_sparse_paged_attention(
raise ValueError("QSA sparse output must match its query")
assert out.dtype == q.dtype and out.device == q.device
assert out.stride(2) == 1
assert output_gate.is_contiguous()
output_gate_view = output_gate.view_as(q)
if not q.shape[0]:
return out
@@ -533,6 +565,7 @@ def qsa_sparse_paged_attention(
partial_output,
partial_lse,
out,
output_gate_view,
q.stride(0),
q.stride(1),
k_cache.stride(0),
@@ -545,6 +578,8 @@ def qsa_sparse_paged_attention(
block_table.stride(0),
out.stride(0),
out.stride(1),
output_gate_view.stride(0),
output_gate_view.stride(1),
q.shape[0],
k_cache.shape[0],
block_table.shape[0],
@@ -568,8 +603,11 @@ def qsa_sparse_paged_attention(
partial_output,
partial_lse,
out,
output_gate_view,
out.stride(0),
out.stride(1),
output_gate_view.stride(0),
output_gate_view.stride(1),
q.shape[0],
HEAD_DIM=q.shape[2],
NUM_QUERY_HEADS=q.shape[1],
@@ -632,6 +670,10 @@ def warmup_qsa_sparse_paged_attention(
output_ptr = TritonWarmupTensor(
torch.bfloat16, shape=(num_rows, num_query_heads, head_dim)
)
# The output gate is mandatory at runtime; warm the gated specialization.
output_gate_ptr = TritonWarmupTensor(
torch.bfloat16, shape=(num_rows, num_query_heads, head_dim)
)
head_stride = head_dim
row_stride = num_query_heads * head_dim
num_cache_blocks = triton_scalar_specialization_rep(kv_cache.shape[0])
@@ -659,6 +701,7 @@ def warmup_qsa_sparse_paged_attention(
partial_output_ptr,
partial_lse_ptr,
output_ptr,
output_gate_ptr,
row_stride,
head_stride,
key_cache.stride(0),
@@ -671,6 +714,8 @@ def warmup_qsa_sparse_paged_attention(
block_table.stride(0),
row_stride,
head_stride,
row_stride,
head_stride,
num_rows,
num_cache_blocks,
num_requests,
@@ -693,6 +738,9 @@ def warmup_qsa_sparse_paged_attention(
partial_output_ptr,
partial_lse_ptr,
output_ptr,
output_gate_ptr,
row_stride,
head_stride,
row_stride,
head_stride,
num_rows,
+26 -4
View File
@@ -195,6 +195,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
self,
inputs: torch.Tensor,
residual: torch.Tensor,
outer_residual: torch.Tensor,
metadata: PleShortConvAttentionMetadata,
conv_state: torch.Tensor,
conv_weights: torch.Tensor,
@@ -209,6 +210,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
has_non_spec = has_prefill or has_decode
inputs = inputs[: metadata.num_actual_tokens]
residual = residual[: metadata.num_actual_tokens]
outer_residual = outer_residual[: metadata.num_actual_tokens]
spec_token_indices = None
non_spec_token_indices = None
@@ -235,6 +237,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
conv_state=conv_state,
conv_weights=conv_weights,
state_indices=spec_state_indices,
outer_residual=outer_residual,
mode="spec",
dilation=self.short_conv_dilation,
query_start_loc=query_start_loc,
@@ -259,11 +262,17 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
residual_d, residual_p = torch.split(
residual, [num_decode_tokens, num_prefill_tokens], dim=0
)
outer_residual_d, outer_residual_p = torch.split(
outer_residual,
[num_decode_tokens, num_prefill_tokens],
dim=0,
)
token_indices_d = None
token_indices_p = None
else:
inputs_d = inputs_p = inputs
residual_d = residual_p = residual
outer_residual_d = outer_residual_p = outer_residual
token_indices_d, token_indices_p = torch.split(
non_spec_token_indices,
[num_decode_tokens, num_prefill_tokens],
@@ -277,6 +286,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
conv_state=conv_state,
conv_weights=conv_weights,
state_indices=state_indices_d,
outer_residual=outer_residual_d,
mode="decode",
dilation=self.short_conv_dilation,
has_initial_states=metadata.has_initial_states_d,
@@ -298,6 +308,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
conv_state=conv_state,
conv_weights=conv_weights,
state_indices=state_indices_p,
outer_residual=outer_residual_p,
mode="prefill",
dilation=self.short_conv_dilation,
query_start_loc=query_start_loc,
@@ -316,6 +327,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
conv_state=conv_state,
conv_weights=conv_weights,
state_indices=state_indices[:num_decode_rows],
outer_residual=outer_residual,
mode="decode",
dilation=self.short_conv_dilation,
has_initial_states=metadata.has_initial_states_d,
@@ -324,12 +336,18 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
# State routing consumes the current request metadata on every replay.
@eager_break_during_capture
def _short_conv(self, inputs: torch.Tensor, residual: torch.Tensor) -> None:
def _short_conv(
self,
inputs: torch.Tensor,
residual: torch.Tensor,
outer_residual: torch.Tensor,
) -> None:
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
# Profiling omits all metadata or this Mamba entry. The residual
# already contains the gated output, so short convolution is a no-op.
# Profiling omits all metadata or this Mamba entry. Short convolution
# is a no-op there, but preserve the outer residual addition.
if attn_metadata is None:
residual.add_(outer_residual)
return
if not isinstance(attn_metadata, dict):
@@ -340,6 +358,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
layer_attn_metadata = attn_metadata.get(self.prefix)
if layer_attn_metadata is None:
residual.add_(outer_residual)
return
if not isinstance(layer_attn_metadata, PleShortConvAttentionMetadata):
raise TypeError(
@@ -367,6 +386,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
self._short_conv_dilated_dispatch(
inputs=inputs,
residual=residual,
outer_residual=outer_residual,
metadata=layer_attn_metadata,
conv_state=conv_state,
conv_weights=conv_weights.to(dtype=inputs.dtype),
@@ -404,7 +424,9 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
self.norm_conv.weight,
self.norm_key.eps,
)
self._short_conv(conv_input, gated_output)
# State routing depends on runtime request metadata and remains outside
# the graph; short convolution accumulates into gated_output.
self._short_conv(conv_input, gated_output, hidden_states)
return gated_output
+6 -2
View File
@@ -121,6 +121,7 @@ class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
output: torch.Tensor,
token_to_req: torch.Tensor,
use_prefill_config: bool,
output_gate: torch.Tensor,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
@@ -157,6 +158,7 @@ class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
token_to_req,
use_prefill_config,
output[:num_tokens],
output_gate=output_gate[:num_tokens],
)
return output
@@ -353,6 +355,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
key: torch.Tensor,
value: torch.Tensor,
output: torch.Tensor,
output_gate: torch.Tensor,
) -> None:
metadata = get_forward_context().attn_metadata
if isinstance(metadata, list):
@@ -396,6 +399,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
output,
token_to_req=side_metadata.token_to_req,
use_prefill_config=main_metadata.max_query_len > self._max_decode_query_len,
output_gate=output_gate,
)
def forward(
@@ -405,6 +409,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
) -> torch.Tensor:
qkv, _ = self.qkv_proj(hidden_states)
q, k, v, gate = self._project_qkv_gate(qkv, positions)
assert gate is not None
num_tokens = hidden_states.shape[0]
query = q.view(num_tokens, self.num_heads, self.head_dim)
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
@@ -419,10 +424,9 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
key,
value,
attn_output,
gate,
)
flat_output = attn_output.view(num_tokens, -1)
if gate is not None:
flat_output = flat_output * torch.sigmoid(gate)
output, _ = self.o_proj(flat_output)
return output