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-27 18:25:21 +09:00
1165 changed files with 51759 additions and 14579 deletions
+8 -4
View File
@@ -7,9 +7,9 @@ MLA + a "lightning indexer" that selects the top-k tokens for a sparse MLA
attend. The same model code serves any DSA checkpoint, including GLM-5.2
(``glm_moe_dsa``), which reuses this architecture.
The CUDA implementation selects capability-specific kernels internally and
falls back when an optimization is unavailable. Other platforms use the
generic implementation by default.
The CUDA and ROCm implementations select capability-specific kernels
internally and fall back when an optimization is unavailable. Other platforms
use the generic implementation by default.
"""
from vllm.platforms import current_platform
@@ -20,8 +20,12 @@ if current_platform.is_cuda():
from .nvidia.model import DeepseekV32ForCausalLM
from .nvidia.model import DeepseekV32ForCausalLM as GlmMoeDsaForCausalLM
from .nvidia.mtp import DeepseekV32MTP
elif current_platform.is_rocm():
from .amd.model import DeepseekV32ForCausalLM
from .amd.model import DeepseekV32ForCausalLM as GlmMoeDsaForCausalLM
from .amd.mtp import DeepseekV32MTP
else:
# ROCm, XPU, and CPU keep the generic implementation.
# XPU and CPU keep the generic implementation.
from vllm.model_executor.models.deepseek_mtp import DeepSeekMTP as DeepseekV32MTP
from vllm.model_executor.models.deepseek_v2 import (
DeepseekV3ForCausalLM as DeepseekV32ForCausalLM,
+16 -25
View File
@@ -3,12 +3,14 @@
import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.forward_context import get_forward_context
from vllm.model_executor.layers.sparse_attn_indexer import SparseAttnIndexer
from vllm.model_executor.models.deepseek_v2 import DeepseekV32IndexerCache
from vllm.models.deepseek_v32.attention import DeepseekV32Attention, DeepseekV32Indexer
from vllm.models.deepseek_v32.common.kernels import fused_norm_rope, fused_q
from vllm.platforms import current_platform
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backends.mla.indexer import DeepseekV32IndexerBackend
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
@@ -16,21 +18,15 @@ from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
)
class DeepseekV32MLASparseBackend(ROCMAiterMLASparseBackend):
@staticmethod
def get_supported_kernel_block_sizes() -> list:
return [16, 32]
class DeepseekV32ROCmIndexerBackend(DeepseekV32IndexerBackend):
@staticmethod
def get_supported_kernel_block_sizes() -> list:
return [16, 32]
class DeepseekV32ROCmIndexerCache(DeepseekV32IndexerCache):
def get_attn_backend(self):
return DeepseekV32ROCmIndexerBackend
return DeepseekV32IndexerBackend
@property
def uses_shuffled_layout(self) -> bool:
# aiter's gather/insert pair shuffles the cache above block size 1:
# [n_blocks, blk/16, head_dim/16, 16, 16] instead of [n_blocks, blk, head_dim].
return self.kv_cache.ndim == 3 and self.kv_cache.shape[1] != 1
class DeepseekV32ROCmIndexer(DeepseekV32Indexer):
@@ -46,7 +42,7 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
config,
prefix,
topk_indices_buffer,
attn_backend=DeepseekV32MLASparseBackend,
attn_backend=ROCMAiterMLASparseBackend,
)
self.indexer_op: SparseAttnIndexer | None = None
@@ -100,14 +96,10 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
q_nope = q_nope.transpose(0, 1) # (N, tokens, P)
if self.is_aiter_triton_fp4_bmm_enabled:
from aiter.ops.triton.batched_gemm_a16wfp4 import batched_gemm_a16wfp4
ql_nope = batched_gemm_a16wfp4(
ql_nope = rocm_aiter_ops.batched_gemm_a16wfp4(
q_nope, self.W_K, self.W_K_scale, transpose_bm=True, prequant=True
)
elif self.is_aiter_triton_fp8_bmm_enabled:
from vllm._aiter_ops import rocm_aiter_ops
ql_nope = rocm_aiter_ops.triton_fp8_bmm(
q_nope, self.W_K, self.W_K_scale, group_size=128, transpose_bm=True
)
@@ -152,14 +144,10 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
)
if self.is_aiter_triton_fp4_bmm_enabled:
from aiter.ops.triton.batched_gemm_a16wfp4 import batched_gemm_a16wfp4
batched_gemm_a16wfp4(
rocm_aiter_ops.batched_gemm_a16wfp4(
x, self.W_V, self.W_V_scale, out_view, transpose_bm=True, prequant=True
)
elif self.is_aiter_triton_fp8_bmm_enabled:
from vllm._aiter_ops import rocm_aiter_ops
rocm_aiter_ops.triton_fp8_bmm(
x,
self.W_V,
@@ -202,6 +190,7 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
indexer_k_norm_eps = self.indexer.k_norm.eps
indexer_k_rope_cos_sin_cache = self.indexer_rope_emb.cos_sin_cache
indexer_k_cache = self.indexer.k_cache.kv_cache
indexer_cache_shuffled = self.indexer.k_cache.uses_shuffled_layout
indexer_softmax_scale = self.indexer.softmax_scale
indexer_n_head_scale = self.indexer.n_head**-0.5
else:
@@ -211,6 +200,7 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
indexer_k_norm_eps = 1e-6
indexer_k_rope_cos_sin_cache = None
indexer_k_cache = None
indexer_cache_shuffled = False
indexer_softmax_scale = 0.0
indexer_n_head_scale = 0.0
@@ -241,6 +231,7 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
self.topk_indices_buffer,
slot_mapping=mla_slot,
indexer_k_cache=indexer_k_cache,
indexer_cache_shuffled=indexer_cache_shuffled,
mla_kv_cache=mla_kv_cache,
mla_kv_cache_dtype=self.kv_cache_dtype,
mla_k_scale=mla_k_scale,
@@ -282,7 +273,7 @@ class DeepseekV32MLAAttention(DeepseekV32Attention):
num_actual = attn_metadata.num_actual_tokens # type: ignore[attr-defined]
kv_cache = self.kv_cache
if self._fp8_kv_needs_view:
kv_cache = kv_cache.view(torch.float8_e4m3fn)
kv_cache = kv_cache.view(current_platform.fp8_dtype())
q_for_attn = self._build_q_for_attn(ql_nope, mqa_q, num_actual)
attn_out, _ = self.impl.forward_mqa( # type: ignore[attr-defined]
+5 -1
View File
@@ -327,6 +327,7 @@ class DeepseekV32Attention(MLAAttention):
indexer_k_norm_bias = self.indexer.k_norm.bias
indexer_k_norm_eps = self.indexer.k_norm.eps
indexer_k_rope_cos_sin_cache = self.indexer_rope_emb.cos_sin_cache
indexer_cache_shuffled = self.indexer.k_cache.uses_shuffled_layout
indexer_k_cache = None if self.use_pcp else self.indexer.k_cache.kv_cache
index_k_out = torch.empty_like(index_k) if self.use_pcp else None
indexer_softmax_scale = self.indexer.softmax_scale
@@ -338,6 +339,7 @@ class DeepseekV32Attention(MLAAttention):
indexer_k_norm_eps = 1e-6
indexer_k_rope_cos_sin_cache = None
indexer_k_cache = None
indexer_cache_shuffled = False
index_k_out = None
indexer_softmax_scale = 0.0
indexer_n_head_scale = 0.0
@@ -377,6 +379,7 @@ class DeepseekV32Attention(MLAAttention):
slot_mapping=mla_slot,
indexer_slot_mapping=indexer_slot,
indexer_k_cache=indexer_k_cache,
indexer_cache_shuffled=indexer_cache_shuffled,
mla_kv_cache=mla_kv_cache,
mla_kv_cache_dtype=self.kv_cache_dtype,
mla_k_scale=mla_k_scale,
@@ -492,6 +495,7 @@ class DeepseekV32Attention(MLAAttention):
self._vllm_config.parallel_config.cp_kv_cache_interleave_size
),
skip_topk_buffer_clear=True,
topk_backend=self.indexer.indexer_op.topk_backend,
)
self.impl.record_logical_topk_ready() # type: ignore[attr-defined]
@@ -544,7 +548,7 @@ class DeepseekV32Attention(MLAAttention):
return
if self._fp8_kv_needs_view:
kv_cache = kv_cache.view(torch.float8_e4m3fn)
kv_cache = kv_cache.view(current_platform.fp8_dtype())
if self._fp8_query:
# FlashInfer sparse: single packed fp8 query.
mqa_q_arg: torch.Tensor | tuple[torch.Tensor, torch.Tensor] = mqa_q[
+97 -27
View File
@@ -12,6 +12,18 @@ from vllm.utils.torch_utils import is_quantized_kv_cache
# has_indexer=False path so the indexer args don't allocate every call.
_DUMMY_CACHE: dict[tuple, torch.Tensor] = {}
# Tile shape of the indexer-K cache's shuffled layout, used when the cache reports
# uses_shuffled_layout. The block tile is a token count; the head tile is a byte
# count, which the kernel converts to cache elements.
_INDEXER_CACHE_BLOCK_TILE = 16
_INDEXER_CACHE_HEAD_TILE_BYTES = 16
# FNUZ (e4m3fnuz) on gfx942, OCP (e4m3fn) elsewhere. 224.0 keeps the ue8m0
# power-of-two scale inside the FNUZ range after its ceil.
_FP8_DTYPE = current_platform.fp8_dtype()
_USE_FNUZ = torch.float8_e4m3fnuz == _FP8_DTYPE
_FP8_MAX = 224.0 if _USE_FNUZ else 448.0
def _dummy(shape: tuple, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
key = (shape, dtype, device)
@@ -47,16 +59,17 @@ def _get_cos_sin(
@triton.jit
def _fp8_ue8m0_quantize(vals):
def _fp8_ue8m0_quantize(vals, FP8_MAX: tl.constexpr, USE_FNUZ: tl.constexpr):
"""Quantize float32 values to FP8 E4M3 with a ue8m0 (power-of-2) scale.
Returns (fp8_vals, scale) so the caller can store them or reuse the scale.
"""
vals = vals.to(tl.float32)
amax = tl.max(tl.abs(vals))
scale = tl.div_rn(tl.maximum(amax, 1e-4), 448.0)
scale = tl.div_rn(tl.maximum(amax, 1e-4), FP8_MAX)
scale = tl.math.exp2(tl.math.ceil(tl.math.log2(scale)))
fp8_vals = tl.div_rn(vals, scale).to(tl.float8e4nv)
fp8_dtype = tl.float8e4b8 if USE_FNUZ else tl.float8e4nv
fp8_vals = tl.div_rn(vals, scale).to(fp8_dtype)
return fp8_vals, scale
@@ -71,18 +84,32 @@ def _fp8_quant_and_cache_write(
cache_block_stride,
offsets,
HEAD_DIM: tl.constexpr,
SHUFFLE: tl.constexpr,
BLOCK_TILE: tl.constexpr,
HEAD_TILE: tl.constexpr,
FP8_MAX: tl.constexpr,
USE_FNUZ: tl.constexpr,
):
k_fp8, scale = _fp8_ue8m0_quantize(vals)
k_fp8, scale = _fp8_ue8m0_quantize(vals, FP8_MAX, USE_FNUZ)
block_idx = slot_idx // cache_block_size
block_offset = slot_idx % cache_block_size
block_start = block_idx * cache_block_stride
tl.store(
kv_cache_ptr + block_start + block_offset * HEAD_DIM + offsets,
k_fp8,
mask=mask,
)
# Shuffled layout: [blk/BLOCK_TILE, HEAD_DIM/HEAD_TILE, BLOCK_TILE, HEAD_TILE],
# so one contiguous run holds BLOCK_TILE tokens x HEAD_TILE bytes and the
# reader's coalesced loads land on the bytes we wrote.
if SHUFFLE:
value_off = (
block_offset // BLOCK_TILE * BLOCK_TILE * HEAD_DIM
+ block_offset % BLOCK_TILE * HEAD_TILE
+ offsets // HEAD_TILE * BLOCK_TILE * HEAD_TILE
+ offsets % HEAD_TILE
)
else:
value_off = block_offset * HEAD_DIM + offsets
tl.store(kv_cache_ptr + block_start + value_off, k_fp8, mask=mask)
scale_byte_off = block_start + cache_block_size * HEAD_DIM + block_offset * 4
tl.store(kv_cache_scale_ptr + scale_byte_off // 4, scale)
@@ -137,6 +164,9 @@ def _fused_norm_rope_kernel(
indexer_cache_scale_ptr,
indexer_cache_block_size,
indexer_cache_stride,
INDEXER_CACHE_SHUFFLE: tl.constexpr,
INDEXER_CACHE_BLOCK_TILE: tl.constexpr,
INDEXER_CACHE_HEAD_TILE: tl.constexpr,
# MLA KV cache (concat kv_c_normed + k_pe_roped, uses slot_mapping_ptr)
mla_cache_ptr,
mla_cache_block_stride,
@@ -161,12 +191,15 @@ def _fused_norm_rope_kernel(
HAS_INDEXER: tl.constexpr,
INDEX_ROPE_INTERLEAVE: tl.constexpr,
USE_PDL: tl.constexpr,
FP8_MAX: tl.constexpr,
USE_FNUZ: tl.constexpr,
):
tok_idx = tl.program_id(0).to(tl.int64)
pid = tl.program_id(1)
if USE_PDL:
tl.extra.cuda.gdc_wait()
tl.extra.cuda.gdc_launch_dependents()
fp8_dtype = tl.float8e4b8 if USE_FNUZ else tl.float8e4nv
if pid == 3:
if not HAS_INDEXER:
# Shared layer: reuse the previous indexer layer's top-k; do not
@@ -327,9 +360,11 @@ def _fused_norm_rope_kernel(
)
kv_2d = tl.reshape(kv_c, (MLA_NUM_TILES, MLA_TILE_DIM))
tile_amax = tl.max(tl.abs(kv_2d), axis=1, keep_dims=True)
tile_scale = tl.maximum(tile_amax * (1.0 / 448.0), 1e-4)
# scale = amax / FP8_MAX (fp8 e4m3 max), matching the reference
# concat_and_cache_ds_mla kernel; floored to FLT_MIN.
tile_scale = tl.maximum(tile_amax * (1.0 / FP8_MAX), 1e-4)
tile_scale = tl.math.exp2(tl.math.ceil(tl.math.log2(tile_scale)))
kv_c_fp8 = tl.reshape((kv_2d / tile_scale).to(tl.float8e4nv), (KV_DIM,))
kv_c_fp8 = tl.reshape((kv_2d / tile_scale).to(fp8_dtype), (KV_DIM,))
tl.store(mla_cache_ptr + byte_base + kv_block, kv_c_fp8)
tile_off = tl.arange(0, MLA_NUM_TILES)
tl.store(
@@ -349,16 +384,16 @@ def _fused_norm_rope_kernel(
# kv_c_normed (KV_DIM elements)
if MLA_CACHE_FP8:
scale = tl.load(mla_cache_scale_ptr)
kv_c_fp8 = (kv_c.to(tl.float32) / scale).to(tl.float8e4nv)
kv_c_fp8 = (kv_c.to(tl.float32) / scale).to(fp8_dtype)
tl.store(dst + kv_block, kv_c_fp8)
else:
tl.store(dst + kv_block, kv_c)
# k_pe_roped (from registers, interleaved layout)
if MLA_CACHE_FP8:
tl.store(dst + KV_DIM + dim_off * 2, (r1 / scale).to(tl.float8e4nv))
tl.store(dst + KV_DIM + dim_off * 2, (r1 / scale).to(fp8_dtype))
tl.store(
dst + KV_DIM + dim_off * 2 + 1,
(r2 / scale).to(tl.float8e4nv),
(r2 / scale).to(fp8_dtype),
)
else:
tl.store(dst + KV_DIM + dim_off * 2, r1)
@@ -463,6 +498,11 @@ def _fused_norm_rope_kernel(
indexer_cache_stride,
index_k_block,
INDEX_K_DIM,
INDEXER_CACHE_SHUFFLE,
INDEXER_CACHE_BLOCK_TILE,
INDEXER_CACHE_HEAD_TILE,
FP8_MAX,
USE_FNUZ,
)
@@ -486,6 +526,7 @@ def fused_norm_rope(
slot_mapping: torch.Tensor | None = None,
indexer_slot_mapping: torch.Tensor | None = None,
indexer_k_cache: torch.Tensor | None = None,
indexer_cache_shuffled: bool = False,
mla_kv_cache: torch.Tensor | None = None,
mla_kv_cache_dtype: str = "auto",
mla_k_scale: torch.Tensor | None = None,
@@ -532,13 +573,28 @@ def fused_norm_rope(
indexer_slot_mapping = slot_mapping
idx_cache_scale_view = indexer_k_cache.view(torch.uint8).view(torch.float32)
idx_cache_block_size = indexer_k_cache.shape[1]
idx_cache_stride = indexer_k_cache.shape[2]
# The caller's cache reports whether its reader expects the shuffled
# layout; see DeepseekV32IndexerCache.uses_shuffled_layout.
idx_cache_shuffle = indexer_cache_shuffled
if idx_cache_shuffle:
assert idx_cache_block_size % _INDEXER_CACHE_BLOCK_TILE == 0, (
f"indexer K cache block size {idx_cache_block_size} must be a "
f"multiple of {_INDEXER_CACHE_BLOCK_TILE} for the shuffled layout"
)
idx_cache_stride = indexer_k_cache.stride(0)
if indexer_k_cache.dtype == torch.uint8:
indexer_k_cache = indexer_k_cache.view(torch.float8_e4m3fn)
indexer_k_cache = indexer_k_cache.view(_FP8_DTYPE)
# The head tile is a byte count; the kernel indexes the cache in elements.
idx_cache_head_tile = (
_INDEXER_CACHE_HEAD_TILE_BYTES // indexer_k_cache.element_size()
)
else:
idx_cache_scale_view = None
idx_cache_block_size = 1
idx_cache_stride = 0
idx_cache_shuffle = False
idx_cache_head_tile = _INDEXER_CACHE_HEAD_TILE_BYTES
# --- MLA KV cache setup ---
mla_cache_nvfp4 = mla_kv_cache_dtype == "nvfp4_ds_mla"
@@ -561,12 +617,12 @@ def fused_norm_rope(
mla_entry_stride = u8_cache.stride(1)
mla_ds_scale_view = u8_cache.view(torch.float32)
mla_ds_rope_view = u8_cache.view(torch.bfloat16)
mla_kv_cache = u8_cache.view(torch.float8_e4m3fn)
mla_kv_cache = u8_cache.view(_FP8_DTYPE)
else:
mla_block_stride = mla_kv_cache.stride(0)
mla_entry_stride = mla_kv_cache.stride(1)
if mla_cache_fp8 and mla_kv_cache.dtype == torch.uint8:
mla_kv_cache = mla_kv_cache.view(torch.float8_e4m3fn)
mla_kv_cache = mla_kv_cache.view(_FP8_DTYPE)
if mla_k_scale is None:
mla_k_scale = torch.ones(1, dtype=torch.float32, device=device)
else:
@@ -592,6 +648,9 @@ def fused_norm_rope(
assert index_k_out.shape == index_k.shape
index_k_out_stride = index_k_out.stride(0)
use_pdl = current_platform.is_arch_support_pdl()
pdl_kwargs = (
{"USE_PDL": use_pdl, "launch_pdl": True} if use_pdl else {"USE_PDL": use_pdl}
)
_fused_norm_rope_kernel[(num_tokens, 4)](
positions,
# Q RMS norm
@@ -639,6 +698,9 @@ def fused_norm_rope(
idx_cache_scale_view,
idx_cache_block_size,
idx_cache_stride,
idx_cache_shuffle,
_INDEXER_CACHE_BLOCK_TILE,
idx_cache_head_tile,
# MLA KV cache (uses same slot_mapping)
mla_kv_cache,
mla_block_stride,
@@ -659,8 +721,9 @@ def fused_norm_rope(
TOPK_BLOCK_SIZE=1024,
HAS_INDEXER=has_indexer,
INDEX_ROPE_INTERLEAVE=index_rope_interleave,
USE_PDL=use_pdl,
launch_pdl=use_pdl,
FP8_MAX=_FP8_MAX,
USE_FNUZ=_USE_FNUZ,
**pdl_kwargs,
)
return q_c_out
@@ -715,6 +778,8 @@ def _fused_q_kernel(
INDEX_ROPE_INTERLEAVE: tl.constexpr,
QUANTIZE_MQA: tl.constexpr,
USE_PDL: tl.constexpr,
FP8_MAX: tl.constexpr,
USE_FNUZ: tl.constexpr,
):
tok_idx = tl.program_id(0).to(tl.int64)
pid = tl.program_id(1)
@@ -722,6 +787,7 @@ def _fused_q_kernel(
if USE_PDL:
tl.extra.cuda.gdc_wait()
tl.extra.cuda.gdc_launch_dependents()
fp8_dtype = tl.float8e4b8 if USE_FNUZ else tl.float8e4nv
if pid == 2:
# ql_nope quantize + pack into the front of mqa_q_fp8. On the bf16
@@ -744,7 +810,7 @@ def _fused_q_kernel(
+ ql_nope_off,
mask=ql_nope_mask,
).to(tl.float32)
ql_nope_fp8 = (ql_nope / scale).to(tl.float8e4nv)
ql_nope_fp8 = (ql_nope / scale).to(fp8_dtype)
tl.store(
mqa_q_fp8_ptr
+ tok_idx * mqa_q_fp8_stride0
@@ -794,7 +860,7 @@ def _fused_q_kernel(
+ q_head_idx * mqa_q_fp8_stride1
+ QL_NOPE_DIM
+ rot_off * 2,
(r1 / scale).to(tl.float8e4nv),
(r1 / scale).to(fp8_dtype),
)
tl.store(
mqa_q_fp8_ptr
@@ -803,7 +869,7 @@ def _fused_q_kernel(
+ QL_NOPE_DIM
+ rot_off * 2
+ 1,
(r2 / scale).to(tl.float8e4nv),
(r2 / scale).to(fp8_dtype),
)
else:
# bf16 query: write the RoPE'd q_pe unquantized.
@@ -861,7 +927,7 @@ def _fused_q_kernel(
index_q = tl.where(in_rope, roped, index_q)
# Index Q Quantize (from registers)
index_q_fp8, index_q_scale = _fp8_ue8m0_quantize(index_q)
index_q_fp8, index_q_scale = _fp8_ue8m0_quantize(index_q, FP8_MAX, USE_FNUZ)
tl.store(
index_q_fp8_ptr
+ tok_idx * index_q_fp8_stride0
@@ -955,7 +1021,7 @@ def fused_q(
q_pe.shape[0],
q_pe.shape[1],
ql_nope.shape[2] + q_pe.shape[2],
dtype=torch.float8_e4m3fn,
dtype=_FP8_DTYPE,
device=q_pe.device,
)
# Placeholder; pid 0 packs q_pe into mqa_q_fp8 instead.
@@ -967,7 +1033,7 @@ def fused_q(
mqa_q_fp8 = q_pe_out # unused placeholder for the fp8 pack pointer
mqa_q = q_pe_out
index_q_fp8 = torch.empty_like(index_q, dtype=torch.float8_e4m3fn)
index_q_fp8 = torch.empty_like(index_q, dtype=_FP8_DTYPE)
index_weights_out = torch.empty_like(index_weights, dtype=torch.float32)
if cutedsl_kernel is not None:
cutedsl_kernel(
@@ -990,6 +1056,9 @@ def fused_q(
return index_q_fp8, index_weights_out, mqa_q
use_pdl = current_platform.is_arch_support_pdl()
pdl_kwargs = (
{"USE_PDL": use_pdl, "launch_pdl": True} if use_pdl else {"USE_PDL": use_pdl}
)
_fused_q_kernel[(num_tokens, 3, grid_heads)](
positions,
q_pe,
@@ -1031,8 +1100,9 @@ def fused_q(
HAS_INDEXER=has_indexer,
INDEX_ROPE_INTERLEAVE=index_rope_interleave,
QUANTIZE_MQA=quantize_mqa,
USE_PDL=use_pdl,
launch_pdl=use_pdl,
FP8_MAX=_FP8_MAX,
USE_FNUZ=_USE_FNUZ,
**pdl_kwargs,
# num_warps=1 is optimal here: each program is a single 128-element
# rope+quant, so the kernel is program-count/occupancy bound, not
# per-program compute bound (swept 1/2/4/8 — 1 wins or ties everywhere).
+27 -3
View File
@@ -37,6 +37,7 @@ from vllm.v1.attention.backends.mla.sparse_swa import (
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
build_ragged_indices_from_dense,
rocm_inv_rope_einsum,
rocm_inverse_rope_rows_,
rocm_sparse_attn_decode,
rocm_sparse_attn_prefill,
)
@@ -1175,6 +1176,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
self.n_local_groups,
self.o_lora_rank,
self.wo_a,
inverse_rope=False,
)
zf = z.flatten(1)
if self._wo_b_scale is not None and zf.dim() == 2:
@@ -1245,9 +1247,15 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
attn_metadata=rocm_metadata,
swa_metadata=swa_metadata,
)
# The fp8 wo_a path rotates inside inverse_rope_group_quant, so folding
# the rotation into the decode reduce would apply it twice. Only the
# BF16 einsum path hands its rotation off to the decode.
fuse_inv_rope = self._wo_a_fp8_weight is None
rotated = 0
if num_decodes > 0:
self._forward_decode(
rotated = self._forward_decode(
q=q[:num_decode_tokens],
positions=positions[:num_decode_tokens] if fuse_inv_rope else None,
kv_cache=self_kv_cache,
swa_metadata=swa_metadata,
attn_metadata=rocm_metadata,
@@ -1261,17 +1269,31 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
and rocm_metadata.for_cudagraph_capture
),
)
if fuse_inv_rope:
# Only the decode reduce rotates its own rows, and only the leading
# `rotated` of them; prefill rows and any decode path that did not
# fuse still owe the standalone pass. Settle that here rather than
# in _o_proj: the split is batch-dependent and _o_proj runs
# compiled, where such a value freezes at its trace-time value.
rocm_inverse_rope_rows_(
output[rotated:, : self.n_local_heads, :],
positions[rotated:],
self.rotary_emb.cos_sin_cache,
self.rope_head_dim,
)
def _forward_decode(
self,
q: torch.Tensor,
positions: torch.Tensor | None,
kv_cache: torch.Tensor | None,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
attn_metadata: DeepseekV4ROCMAiterMLASparseMetadata | None,
swa_only: bool,
output: torch.Tensor,
adaptive_splits: bool,
) -> None:
) -> int:
"""Returns how many leading rows the decode epilogue inverse-RoPE'd."""
num_decodes = swa_metadata.num_decodes
num_decode_tokens = swa_metadata.num_decode_tokens
@@ -1303,7 +1325,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
topk_ragged_indices = attn_metadata.c128a_decode_topk_ragged_indices
topk_ragged_indptr = attn_metadata.c128a_decode_topk_ragged_indptr
rocm_sparse_attn_decode(
return rocm_sparse_attn_decode(
q=q,
kv_cache=kv_cache,
swa_k_cache=self.swa_cache_layer.kv_cache,
@@ -1323,6 +1345,8 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
rope_head_dim=self.rope_head_dim,
output=output,
adaptive_splits=adaptive_splits,
inv_rope_positions=positions,
inv_rope_cos_sin_cache=self.rotary_emb.cos_sin_cache,
extra_cache_nan_free=_trust_dsv4_extra_cache_nan_free(
self.kv_cache_dtype,
self._has_kv_transfer,
+36 -19
View File
@@ -43,6 +43,7 @@ from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
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
@@ -171,14 +172,20 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
output: torch.Tensor,
output: "torch.Tensor | QuantizedActivation",
) -> None:
"""Platform-specific sparse MLA forward; writes attention into ``output``."""
raise NotImplementedError
@abstractmethod
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
"""Inverse-RoPE + wo_a + wo_b output projection (platform-specific)."""
def _o_proj(
self, o: "torch.Tensor | QuantizedActivation", positions: torch.Tensor
) -> torch.Tensor:
"""Inverse-RoPE + wo_a + wo_b output projection (platform-specific).
``o`` is the live heads of the bf16 attention output, or the
QuantizedActivation of a layer whose ``_alloc_attn_out`` returns one.
"""
raise NotImplementedError
def _uses_fp8_ds_mla_layout(self) -> bool:
@@ -467,14 +474,9 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
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,
)
# The eager attention region writes into a caller-owned buffer
# (breakable_cudagraph needs in-place outputs).
attn_out = self._alloc_attn_out(hidden_states.shape[0], hidden_states)
# Keep the attention input preparation in the captured graph. Only the
# sparse indexer and MLA attention run in the eager break below.
@@ -492,12 +494,27 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
indexer_kv_score,
indexer_weights,
positions,
o_padded,
attn_out,
)
o = o_padded[:, : self.n_local_heads, :]
if isinstance(attn_out, torch.Tensor):
attn_out = attn_out[:, : self.n_local_heads, :]
return self._o_proj(attn_out, positions)
# Inverse-RoPE + wo_a + wo_b output projection (platform-specific).
return self._o_proj(o, positions)
def _alloc_attn_out(
self, num_tokens: int, hidden_states: torch.Tensor
) -> "torch.Tensor | QuantizedActivation":
"""The buffer ``forward_mqa`` fills.
A bf16 ``[num_tokens, padded_heads, head_dim]`` buffer by default, whose
padding heads are sliced off before ``_o_proj``. A layer whose kernel
also does the inverse RoPE and the FP8 cast returns a
QuantizedActivation instead and gets it back in ``_o_proj`` whole.
"""
return torch.empty(
(num_tokens, self.padded_heads, self.head_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
)
def _split_qkv_and_norm(
self, qr_kv: torch.Tensor
@@ -529,7 +546,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
indexer_kv_score: torch.Tensor,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
o_padded: torch.Tensor,
o_padded: "torch.Tensor | QuantizedActivation",
) -> None:
"""Wide eager region: the whole of ``_prepare_and_attn`` runs eagerly.
@@ -558,7 +575,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
indexer_kv_score: torch.Tensor,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
o_padded: torch.Tensor,
o_padded: "torch.Tensor | QuantizedActivation",
) -> None:
"""Attention input preparation followed by the sparse indexer and MLA.
@@ -723,7 +740,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
out: torch.Tensor,
out: "torch.Tensor | QuantizedActivation",
) -> None:
if self.indexer is not None and index_q is not None:
assert index_weights is not None
@@ -736,7 +753,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
)
# MLA attention writes into the pre-allocated `out` buffer
# ([num_tokens, padded_heads, head_dim]).
# (see _alloc_attn_out).
self.forward_mqa(q, kv, positions, out)
def _fused_qnorm_rope_kv_insert(
@@ -1099,6 +1099,7 @@ def build_flashinfer_mixed_sparse_indices(
prefill_left_visible: torch.Tensor | None = None,
prefill_right_visible: torch.Tensor | None = None,
max_image_tokens: int = 0,
num_rows: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Build the FlashInfer DSV4 sparse-index matrix for decode-first batches.
@@ -1109,6 +1110,9 @@ def build_flashinfer_mixed_sparse_indices(
tokens derive their SWA window from the position and translate local
compressed indices to global slots via the block tables.
``num_rows`` (>= ``num_tokens``) sizes both outputs for a kernel call that
spans a CUDA-graph-padded batch; the rows past ``num_tokens`` stay unset.
When ``prefill_left_visible``/``prefill_right_visible`` are given (vision
variant), the SWA column region widens by ``max_image_tokens`` and prefill
tokens inside an image span get a bidirectionally widened window; decode
@@ -1170,13 +1174,15 @@ def build_flashinfer_mixed_sparse_indices(
# by ``sparse_topk_lens``, so padding never changes the attention result.
padded_topk = max(topk, decode_compressed_topk)
padded_topk = (padded_topk + 3) // 4 * 4
num_rows = num_tokens if num_rows is None else num_rows
assert num_rows >= num_tokens
sparse_indices = torch.empty(
(num_tokens, swa_total_width + padded_topk),
(num_rows, swa_total_width + padded_topk),
dtype=torch.int32,
device=decode_swa_indices.device,
)
sparse_topk_lens = torch.empty(
num_tokens, dtype=torch.int32, device=decode_swa_indices.device
num_rows, dtype=torch.int32, device=decode_swa_indices.device
)
if num_tokens == 0:
return sparse_indices, sparse_topk_lens
@@ -1193,9 +1199,10 @@ def build_flashinfer_mixed_sparse_indices(
if compressed_block_span is None
else compressed_block_span
)
# The launch grid follows the output rows, so hand over only the real ones.
_BUILD_FLASHINFER_MIXED_SPARSE_INDICES_KERNEL(
sparse_indices,
sparse_topk_lens,
sparse_indices[:num_tokens],
sparse_topk_lens[:num_tokens],
decode_swa_indices,
decode_compressed_indices,
decode_compressed_topk_lens,
@@ -1234,7 +1241,7 @@ def build_flashinfer_mixed_sparse_indices(
def _remap_flashinfer_index(values, block_size, block_span):
# FlashInfer's DSv4 kernel indexes sparse KV by physical token stride, so
# packed pages (#44577) need block*block_size+off -> block*block_span+off.
# TODO: remove once flashinfer-ai/flashinfer#3856 is fixed.
# The launcher declares these indices with sparse_indices_are_storage_offsets=True.
is_valid = values >= 0
safe_values = tl.where(is_valid, values, 0)
values = (safe_values // block_size) * block_span
@@ -1322,12 +1329,52 @@ class BuildFlashinferMixedSparseIndicesKernel(
SWA_TOTAL_WIDTH: tl.constexpr = SWA_INDEX_WIDTH + IMAGE_WIDTH
if token_idx < NUM_DECODE_TOKENS:
# A decode row wider than the window is DSpark's non-causal block:
# the block-anchored window of context followed by the whole block,
# contiguous from column 0. The kernel treats every entry of its
# active ranges as a key -- the first min(WINDOW_SIZE, pos + 1)
# columns and [WINDOW_SIZE, sparse_topk_lens) -- so -1 must not
# appear in either. Fill the causal window with the first visible
# entries and put the rest from column WINDOW_SIZE on, followed
# directly by the compressed entries.
NONCAUSAL: tl.constexpr = SWA_INDEX_WIDTH > WINDOW_SIZE
compressed_start = SWA_TOTAL_WIDTH
if NONCAUSAL:
req_idx = tl.load(token_to_req_indices_ptr + token_idx)
query_start = tl.load(query_start_loc_ptr + req_idx)
query_len = tl.load(query_start_loc_ptr + req_idx + 1) - query_start
context_len = tl.load(seq_lens_ptr + req_idx) - query_len
token_in_query = token_idx - query_start
window_len = tl.minimum(context_len + token_in_query + 1, WINDOW_SIZE)
spill_len = (
tl.minimum(context_len, WINDOW_SIZE) + query_len - window_len
)
# A CUDA-graph pad token sits outside its empty request, so
# the kernel never reads its row; keep it the shape of a
# causal pad row (all -1, WINDOW_SIZE long) rather than let
# the formulas above go negative.
is_block_token = (token_in_query >= 0) & (token_in_query < query_len)
window_len = tl.where(is_block_token, window_len, 0)
spill_len = tl.where(is_block_token, spill_len, 0)
compressed_start = WINDOW_SIZE + spill_len
for i in range(0, SWA_TOTAL_WIDTH, WINDOW_BLOCK_SIZE):
offset = i + tl.arange(0, WINDOW_BLOCK_SIZE)
mask = offset < SWA_TOTAL_WIDTH
src = offset
src_mask = offset < SWA_INDEX_WIDTH
if NONCAUSAL:
# Columns from compressed_start on belong to the loops below.
mask = mask & (offset < compressed_start)
spill = offset >= WINDOW_SIZE
src = tl.where(spill, offset - WINDOW_SIZE + window_len, offset)
src_mask = tl.where(
spill,
offset < WINDOW_SIZE + spill_len,
offset < window_len,
)
values = tl.load(
decode_swa_indices_ptr + token_idx * decode_swa_stride + offset,
mask=offset < SWA_INDEX_WIDTH,
decode_swa_indices_ptr + token_idx * decode_swa_stride + src,
mask=src_mask,
other=-1,
)
values = _remap_flashinfer_index(values, swa_block_size, swa_block_span)
@@ -1372,12 +1419,27 @@ class BuildFlashinferMixedSparseIndicesKernel(
tl.store(
sparse_indices_ptr
+ token_idx * sparse_indices_stride
+ SWA_TOTAL_WIDTH
+ compressed_start
+ offset,
values,
mask=mask,
)
if NONCAUSAL:
# The row's remaining columns, left over by the shifted
# compressed block.
for i in range(0, SWA_TOTAL_WIDTH - WINDOW_SIZE, WINDOW_BLOCK_SIZE):
offset = i + tl.arange(0, WINDOW_BLOCK_SIZE)
tl.store(
sparse_indices_ptr
+ token_idx * sparse_indices_stride
+ compressed_start
+ PADDED_TOP_K
+ offset,
tl.full((WINDOW_BLOCK_SIZE,), -1, dtype=tl.int32),
mask=offset < SWA_TOTAL_WIDTH - compressed_start,
)
if DECODE_COMPRESSED_TOPK == 0:
compressed_len = tl.zeros((), dtype=tl.int32)
elif not DECODE_COMPRESSED_INDICES_ARE_LOCAL:
@@ -1388,7 +1450,9 @@ class BuildFlashinferMixedSparseIndicesKernel(
else:
compressed_len = tl.full((), DECODE_COMPRESSED_TOPK, dtype=tl.int32)
tl.store(sparse_topk_lens_ptr + token_idx, SWA_TOTAL_WIDTH + compressed_len)
tl.store(
sparse_topk_lens_ptr + token_idx, compressed_start + compressed_len
)
return
prefill_idx = token_idx - NUM_DECODE_TOKENS
+10 -7
View File
@@ -38,6 +38,7 @@ from vllm.model_executor.models.vision import (
get_load_balance_assignment,
is_vit_use_data_parallel,
)
from vllm.utils.torch_utils import async_tensor_h2d
def _compute_vision_cos_sin(
@@ -219,8 +220,8 @@ class DeepseekV4ViT(nn.Module):
) -> torch.Tensor:
x = self.patch_embed(patches)
cos, sin = get_vision_cos_sin(n_vit_h, n_vit_w, self.rope_dim, self.rope_theta)
cos = cos.to(device=x.device)
sin = sin.to(device=x.device)
cos = async_tensor_h2d(cos, x.device)
sin = async_tensor_h2d(sin, x.device)
for block in self.blocks:
x = block(x, cos, sin)
return self.norm(x)
@@ -279,8 +280,8 @@ def build_packed_vit_metadata(
cu_seqlens.append(cu_seqlens[-1] + n)
max_seqlen = max(max_seqlen, n)
if cos_list:
cos = torch.cat(cos_list).to(device)
sin = torch.cat(sin_list).to(device)
cos = async_tensor_h2d(torch.cat(cos_list), device)
sin = async_tensor_h2d(torch.cat(sin_list), device)
else:
cos = torch.zeros((0, 1, rope_dim), dtype=torch.float32, device=device)
sin = torch.zeros((0, 1, rope_dim), dtype=torch.float32, device=device)
@@ -289,7 +290,7 @@ def build_packed_vit_metadata(
return {
"vit_cos": cos,
"vit_sin": sin,
"cu_seqlens": torch.tensor(cu_seqlens, dtype=torch.int32, device=device),
"cu_seqlens": async_tensor_h2d(cu_seqlens, device, dtype=torch.int32),
# Read on the host by the attention wrapper; keep on CPU.
"max_seqlen": torch.tensor(max_seqlen, dtype=torch.int32),
}
@@ -327,8 +328,10 @@ def build_packed_merge_metadata(
mask_list.append(valid)
offset += n_h * n_w
if idx_list:
merge_idx = torch.cat(idx_list).to(device)
merge_mask = torch.cat(mask_list).unsqueeze(-1).to(device=device, dtype=dtype)
merge_idx = async_tensor_h2d(torch.cat(idx_list), device)
merge_mask = async_tensor_h2d(
torch.cat(mask_list).unsqueeze(-1), device, dtype=dtype
)
else:
merge_idx = torch.zeros((0, r * r), dtype=torch.int64, device=device)
merge_mask = torch.zeros((0, r * r, 1), dtype=dtype, device=device)
+1 -1
View File
@@ -66,7 +66,7 @@ class CompressorBackend(AttentionBackend):
return "CompressorBackend"
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(1)]
@classmethod
@@ -9,6 +9,8 @@ import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.models.deepseek_v4.attention import DeepseekV4Attention
from vllm.models.deepseek_v4.common.ops import (
build_flashinfer_mixed_sparse_indices,
@@ -17,6 +19,8 @@ from vllm.models.deepseek_v4.common.ops import (
from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
compute_fp8_einsum_recipe,
deep_gemm_fp8_o_proj,
rope_quant_attn_out,
rope_quant_unsupported_reason,
)
from vllm.models.deepseek_v4.sparse_mla import (
DeepseekV4FlashMLAMetadata,
@@ -37,6 +41,8 @@ from vllm.v1.attention.backends.mla.sparse_swa import (
if TYPE_CHECKING:
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
logger = init_logger(__name__)
_FLASHINFER_DSV4_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024
_flashinfer_dsv4_workspace_by_device: dict[torch.device, torch.Tensor] = {}
@@ -111,7 +117,7 @@ class DeepseekV4FlashInferMLASparseBackend(DeepseekV4SparseMLABackend):
]
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [256]
@staticmethod
@@ -203,7 +209,9 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
def get_padded_num_q_heads(cls, num_heads: int) -> int:
return _pad_to_supported_q_heads(num_heads)
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
def _o_proj(
self, o: torch.Tensor | QuantizedActivation, positions: torch.Tensor
) -> torch.Tensor:
return deep_gemm_fp8_o_proj(
o,
positions,
@@ -219,9 +227,30 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
tma_aligned_scales=self._tma_aligned_scales,
)
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def _alloc_attn_out(
self, num_tokens: int, hidden_states: torch.Tensor
) -> torch.Tensor | QuantizedActivation:
if self._fuse_rope_quant:
return rope_quant_attn_out(num_tokens, hidden_states.device)
return super()._alloc_attn_out(num_tokens, hidden_states)
def __init__(self, vllm_config: VllmConfig, *args, **kwargs) -> None:
super().__init__(vllm_config, *args, **kwargs)
self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe()
# RopeQuant derives each query's RoPE position as seq_len - q_len + i,
# which matches `positions` for DSpark's non-causal draft block too,
# since every call passes the real per-request seq_lens. The one
# exception is a draft block running past max_model_len, whose clamped
# positions it does not reproduce; that only costs those drafts.
reason = rope_quant_unsupported_reason(self)
self._fuse_rope_quant = reason is None
if reason is None:
logger.info_once(
"FLASHINFER_MLA_SPARSE_DSV4 fuses the inverse RoPE and FP8 "
"quant of the attention output."
)
else:
logger.debug_once("FLASHINFER_MLA_SPARSE_DSV4 RopeQuant off: %s", reason)
# Per-tensor FP8 scale buffers + precomputed scalar BMM scales. Only the
# per-tensor FP8 cache path consumes these; bf16 reads ``self.scale``.
if self.kv_cache_torch_dtype != torch.float8_e4m3fn:
@@ -253,32 +282,39 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
output: torch.Tensor,
output: torch.Tensor | QuantizedActivation,
) -> None:
# The TRTLLM-gen kernel requires h_q in {64, 128}, so the output buffer
# is allocated at the padded head count while q arrives at the local
# head count; _forward pads q to match before the launcher.
assert output.shape[0] == q.shape[0] and output.shape[-1] == q.shape[-1], (
f"output buffer shape {output.shape} incompatible with q shape {q.shape}"
)
assert output.shape[1] >= q.shape[1], (
f"output heads {output.shape[1]} must be >= q heads {q.shape[1]}"
)
# Per-tensor FP8 q produces a bf16 attention output.
expected_output_dtype = (
torch.bfloat16 if q.dtype == torch.float8_e4m3fn else q.dtype
)
assert output.dtype == expected_output_dtype, (
f"output dtype {output.dtype} must match expected {expected_output_dtype} "
f"for q dtype {q.dtype}"
)
if isinstance(output, QuantizedActivation):
assert output.data.shape[0] == q.shape[0]
else:
# The TRTLLM-gen kernel requires h_q in {64, 128}, so the output
# buffer is allocated at the padded head count while q arrives at
# the local head count; _forward pads q to match before the launcher.
assert output.shape[0] == q.shape[0] and output.shape[-1] == q.shape[-1], (
f"output buffer shape {output.shape} incompatible with q {q.shape}"
)
assert output.shape[1] >= q.shape[1], (
f"output heads {output.shape[1]} must be >= q heads {q.shape[1]}"
)
# Per-tensor FP8 q produces a bf16 attention output.
expected_output_dtype = (
torch.bfloat16 if q.dtype == torch.float8_e4m3fn else q.dtype
)
assert output.dtype == expected_output_dtype, (
f"output dtype {output.dtype} must match expected "
f"{expected_output_dtype} for q dtype {q.dtype}"
)
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
if attn_metadata is None:
# Warmup dummy run: FlashInfer reads the cache directly and lazily
# allocates its workspace, so nothing to reserve here.
output.zero_()
if isinstance(output, QuantizedActivation):
output.data.zero_()
output.scale.zero_()
else:
output.zero_()
return
assert isinstance(attn_metadata, dict)
@@ -313,11 +349,12 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
swa_metadata: "DeepseekSparseSWAMetadata",
attn_metadata: DeepseekV4FlashMLAMetadata | None,
swa_only: bool,
num_rows: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Build the combined sparse-index tensors for the mixed batch.
Returns ``(compressed_kv_cache, seq_lens, sparse_indices,
sparse_topk_lens)``.
sparse_topk_lens)``, sized ``num_rows`` (default: the real tokens).
"""
num_decodes = swa_metadata.num_decodes
num_prefills = swa_metadata.num_prefills
@@ -412,6 +449,8 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
if swa_only
else ("c128a" if self.compress_ratio == 128 else "c4a")
)
if num_rows is not None:
cache_key = f"{cache_key}:{num_rows}"
cached_sparse = swa_metadata.flashinfer_sparse_index_cache.get(cache_key, None)
if cached_sparse is None:
swa_block_span = _packed_block_span(swa_k_cache)
@@ -439,8 +478,9 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
prefill_right_visible=swa_metadata.prefill_right_visible,
# getattr for tests that bypass __init__ via object.__new__.
max_image_tokens=getattr(self, "max_image_tokens", 0),
num_rows=num_rows,
)
if cache_key != "c4a":
if not cache_key.startswith("c4a"):
swa_metadata.flashinfer_sparse_index_cache[cache_key] = (
sparse_indices,
sparse_topk_lens,
@@ -457,7 +497,7 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
swa_metadata: "DeepseekSparseSWAMetadata",
attn_metadata: DeepseekV4FlashMLAMetadata | None,
swa_only: bool,
output: torch.Tensor,
output: torch.Tensor | QuantizedActivation,
) -> None:
assert self.kv_cache_torch_dtype in (torch.bfloat16, torch.float8_e4m3fn)
num_decodes = swa_metadata.num_decodes
@@ -468,6 +508,11 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
num_tokens = num_decode_tokens + num_prefill_tokens
if num_tokens == 0:
return
# RopeQuant's output is group-major with a group stride of exactly
# sum_q tokens, so both calls span every row of the (CUDA-graph
# padded) buffers and select their tokens through cum_seq_lens_q
# alone; the kernel never touches rows outside it.
rope_quant = isinstance(output, QuantizedActivation)
(
compressed_kv_cache,
@@ -480,12 +525,12 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
swa_metadata=swa_metadata,
attn_metadata=attn_metadata,
swa_only=swa_only,
num_rows=q.shape[0] if rope_quant else None,
)
# CUDA graph execution can pad q/output past the scheduled token count;
# restrict to the real tokens (the launcher validates sparse indices).
query = q[:num_tokens]
output = output[:num_tokens]
query = q if rope_quant else q[:num_tokens]
bmm1_scale: float | torch.Tensor = self.scale
bmm2_scale: float | torch.Tensor = 1.0
if self.kv_cache_torch_dtype == torch.float8_e4m3fn:
@@ -499,7 +544,9 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
# The TRTLLM-gen sparse-MLA kernel requires h_q in {64, 128}; zero-pad
# the query heads to the allocated output head count. Padded heads attend
# to the shared KV and are sliced off downstream (output is padded too).
padded_heads = output.shape[1]
padded_heads = (
output.shape[1] if isinstance(output, torch.Tensor) else self.padded_heads
)
if query.shape[1] < padded_heads:
padded_query = query.new_zeros(
(query.shape[0], padded_heads, query.shape[2])
@@ -512,49 +559,60 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
query_start_loc_cpu = swa_metadata.query_start_loc_cpu
assert query_start_loc is not None and query_start_loc_cpu is not None
def run(
rows: slice, reqs: slice, cum_seq_lens_q: torch.Tensor, max_q_len: int
) -> None:
if rope_quant:
assert isinstance(output, QuantizedActivation)
rows = slice(None)
out_kwargs = dict(
out=output.data,
dsv4_output_scale=output.scale,
dsv4_inv_rope_cos_sin_cache=self.rotary_emb.cos_sin_cache,
)
else:
assert isinstance(output, torch.Tensor)
out_kwargs = dict(out=output[rows])
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
query=query[rows],
swa_kv_cache=swa_k_cache,
workspace_buffer=workspace,
sparse_indices=sparse_indices[rows],
sparse_indices_are_storage_offsets=True,
compressed_kv_cache=compressed_kv_cache,
sparse_topk_lens=sparse_topk_lens[rows],
seq_lens=seq_lens[reqs],
bmm1_scale=bmm1_scale,
bmm2_scale=bmm2_scale,
sinks=self.attn_sink,
cum_seq_lens_q=cum_seq_lens_q,
max_q_len=max_q_len,
**out_kwargs,
)
# Keep the TRTLLM-gen decode/prefill split: the launcher is tuned for
# uniform-q batches, and this avoids flattening mixed batches into one call.
if num_decode_tokens > 0:
decode_cu = query_start_loc[: num_decodes + 1]
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
query=query[:num_decode_tokens],
swa_kv_cache=swa_k_cache,
workspace_buffer=workspace,
sparse_indices=sparse_indices[:num_decode_tokens],
compressed_kv_cache=compressed_kv_cache,
sparse_topk_lens=sparse_topk_lens[:num_decode_tokens],
seq_lens=seq_lens[:num_decodes],
out=output[:num_decode_tokens],
bmm1_scale=bmm1_scale,
bmm2_scale=bmm2_scale,
sinks=self.attn_sink,
cum_seq_lens_q=decode_cu,
max_q_len=swa_metadata.max_decode_query_len,
run(
slice(0, num_decode_tokens),
slice(0, num_decodes),
query_start_loc[: num_decodes + 1],
swa_metadata.max_decode_query_len,
)
if num_prefill_tokens > 0:
# The prefill query view re-anchors at offset 0, so rebase the
# cumulative query offsets to start at 0.
prefill_cu = (
query_start_loc[num_decodes : num_reqs + 1]
- query_start_loc[num_decodes]
)
prefill_cu = query_start_loc[num_decodes : num_reqs + 1]
if not rope_quant:
# The prefill query view re-anchors at offset 0, so rebase the
# cumulative query offsets to start at 0.
prefill_cu = prefill_cu - query_start_loc[num_decodes]
prefill_cu_cpu = query_start_loc_cpu[num_decodes : num_reqs + 1]
prefill_lens_cpu = prefill_cu_cpu[1:] - prefill_cu_cpu[:-1]
flashinfer_trtllm_batch_decode_sparse_mla_dsv4(
query=query[num_decode_tokens:num_tokens],
swa_kv_cache=swa_k_cache,
workspace_buffer=workspace,
sparse_indices=sparse_indices[num_decode_tokens:num_tokens],
compressed_kv_cache=compressed_kv_cache,
sparse_topk_lens=sparse_topk_lens[num_decode_tokens:num_tokens],
seq_lens=seq_lens[num_decodes:num_reqs],
out=output[num_decode_tokens:num_tokens],
bmm1_scale=bmm1_scale,
bmm2_scale=bmm2_scale,
sinks=self.attn_sink,
cum_seq_lens_q=prefill_cu,
max_q_len=int(prefill_lens_cpu.max().item()),
run(
slice(num_decode_tokens, num_tokens),
slice(num_decodes, num_reqs),
prefill_cu,
int(prefill_lens_cpu.max().item()),
)
+83 -16
View File
@@ -5,11 +5,15 @@ from collections.abc import Callable
import torch
import torch.nn as nn
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8Dynamic128Sym,
)
from vllm.models.deepseek_v4.common.ops.fused_inv_rope_fp8_quant import (
fused_inv_rope_fp8_quant,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import fp8_einsum
from vllm.utils.deep_gemm import fp8_einsum, get_tma_aligned_size
def compute_fp8_einsum_recipe(
@@ -29,7 +33,7 @@ def compute_fp8_einsum_recipe(
def deep_gemm_fp8_o_proj(
o: torch.Tensor,
o: torch.Tensor | QuantizedActivation,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
wo_a: nn.Module,
@@ -49,23 +53,31 @@ def deep_gemm_fp8_o_proj(
layer selects the recipe at initialization. ``wo_b`` is any callable over
the flattened ``z``: the projection module itself, or a wrapper that also
reduce-scatters its output (DeepSeek-V4.1 GEMM-RS).
A QuantizedActivation ``o`` was already rotated and cast by the attention
kernel, one ``wo_a`` group per slot with the live groups first, so only
the padding groups are sliced off.
"""
use_fp8 = wo_a.weight.dtype == torch.float8_e4m3fn
o_proj_input, o_scale = fused_inv_rope_fp8_quant(
o,
positions,
cos_sin_cache,
n_groups=n_groups,
heads_per_group=heads_per_group,
nope_dim=nope_dim,
rope_dim=rope_dim,
quant_group_size=einsum_recipe[2],
tma_aligned_scales=tma_aligned_scales,
quantize=use_fp8,
)
if isinstance(o, QuantizedActivation):
assert use_fp8
o_proj_input, o_scale = o.data[:, :n_groups], o.scale[:, :n_groups]
else:
o_proj_input, o_scale = fused_inv_rope_fp8_quant(
o,
positions,
cos_sin_cache,
n_groups=n_groups,
heads_per_group=heads_per_group,
nope_dim=nope_dim,
rope_dim=rope_dim,
quant_group_size=einsum_recipe[2],
tma_aligned_scales=tma_aligned_scales,
quantize=use_fp8,
)
z = torch.empty(
(o.shape[0], n_groups, o_lora_rank),
device=o.device,
(o_proj_input.shape[0], n_groups, o_lora_rank),
device=o_proj_input.device,
dtype=torch.bfloat16,
)
if use_fp8:
@@ -89,3 +101,58 @@ def deep_gemm_fp8_o_proj(
out=z.transpose(0, 1),
)
return wo_b(z.flatten(1))
# TRTLLM-gen's DSv4 RopeQuant epilogue (flashinfer-ai/flashinfer#4918) has one
# fixed schedule: 128 query heads in groups of 8 512-wide heads, and FP8 with
# one packed UE8M0 scale per 128 elements.
_ROPE_QUANT_NUM_HEADS = 128
_ROPE_QUANT_HEADS_PER_GROUP = 8
_ROPE_QUANT_HEAD_DIM = 512
_ROPE_QUANT_BLOCK = 128
def rope_quant_unsupported_reason(layer: torch.nn.Module) -> str | None:
"""Why ``layer`` cannot take FlashInfer's fused inverse RoPE + FP8 output.
DSv4 always has 8 heads per ``wo_a`` group at any TP size, and the rest of
the kernel's fixed shape (head/RoPE dims, per-128 einsum scales, FP32 RoPE
cache) is what the SM100 layer uses anyway. What varies is the local head
count and the configs the layer also serves unquantized.
"""
if layer.n_local_heads != _ROPE_QUANT_NUM_HEADS:
# Padding fewer heads up to the kernel's fixed 128 costs more
# attention than the fused epilogue saves.
return f"RopeQuant needs {_ROPE_QUANT_NUM_HEADS} local query heads"
if layer.kv_cache_torch_dtype != torch.float8_e4m3fn:
return "RopeQuant needs the per-tensor FP8 KV cache"
if layer.wo_a.weight.dtype != torch.float8_e4m3fn:
return "RopeQuant needs an FP8 wo_a"
return None
def rope_quant_attn_out(num_tokens: int, device: torch.device) -> QuantizedActivation:
"""Allocate the output pair the RopeQuant kernel writes.
Values are group-major, ``[num_tokens, 16, 8 * 512]`` over physical
``[group, token, K]``. Scales are MN-major packed UE8M0, one int32 per
head over its four 128-wide blocks. Both are what ``fp8_einsum`` consumes.
"""
n_groups = _ROPE_QUANT_NUM_HEADS // _ROPE_QUANT_HEADS_PER_GROUP
group_width = _ROPE_QUANT_HEADS_PER_GROUP * _ROPE_QUANT_HEAD_DIM
data = torch.empty(
(n_groups, num_tokens, group_width), dtype=torch.float8_e4m3fn, device=device
).transpose(0, 1)
aligned = get_tma_aligned_size(num_tokens, torch.int32.itemsize)
scale = torch.empty(
(n_groups, group_width // (_ROPE_QUANT_BLOCK * 4), aligned),
dtype=torch.int32,
device=device,
).permute(2, 0, 1)[:num_tokens]
return QuantizedActivation(
data=data,
scale=scale,
orig_dtype=torch.bfloat16,
orig_shape=data.shape,
quant_key=kFp8Dynamic128Sym,
)
+7 -7
View File
@@ -135,15 +135,15 @@ class DeepseekV4FP8Config(Fp8Config):
def override_quantization_method(
cls, hf_quant_cfg, user_quant, hf_config=None
) -> QuantizationMethods | None:
# Quark checkpoints are always handled by QuarkConfig.
if (
isinstance(hf_quant_cfg, dict)
and hf_quant_cfg.get("quant_method") == "quark"
):
return None
if not (
isinstance(hf_quant_cfg, dict)
and (
hf_quant_cfg.get("quant_method") in ("fp8", "deepseek_v4_fp8")
or (
hf_quant_cfg.get("quant_method") == "quark"
and cls._is_quark_mxfp4_ocp(hf_quant_cfg)
)
)
and hf_quant_cfg.get("quant_method") in ("fp8", "deepseek_v4_fp8")
):
return None
model_type = getattr(hf_config, "model_type", None)
+1 -1
View File
@@ -57,7 +57,7 @@ class DeepseekV4SparseMLABackend(AttentionBackend):
]
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [256]
@staticmethod
+10
View File
@@ -895,6 +895,11 @@ def _make_deepseek_v4_weights_mapper(
# renames the engram fp8 table but not its scale; route the
# scale explicitly to the same module.
re.compile(r"(engram\.embed)\.scale$"): r"\1_tokens.weight_scale_inv",
# Quark exports spell the same tensor ``embed.weight_scale``,
# which the ``\.scale$`` rules never match.
re.compile(
r"(engram\.embed)\.weight_scale$"
): r"\1_tokens.weight_scale_inv",
re.compile(r"\.scale$"): f".{linear_scale_name}",
}
else:
@@ -908,6 +913,11 @@ def _make_deepseek_v4_weights_mapper(
): r"\1.weight_scale_inv",
# Same engram reroute as the fp4 branch above.
re.compile(r"(engram\.embed)\.scale$"): r"\1_tokens.weight_scale_inv",
# Quark exports spell the same tensor ``embed.weight_scale``,
# which the ``\.scale$`` rules never match.
re.compile(
r"(engram\.embed)\.weight_scale$"
): r"\1_tokens.weight_scale_inv",
re.compile(r"\.scale$"): f".{linear_scale_name}",
}
return WeightsMapper(
+158 -25
View File
@@ -13,6 +13,8 @@ from vllm.distributed import (
)
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
from vllm.models.deepseek_v41.attention import (
DeepseekV4Attention,
_replace_layer_index,
@@ -37,6 +39,9 @@ from vllm.v1.attention.backends.mla.sparse_swa import (
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
build_ragged_indices_from_dense,
rocm_inv_rope_einsum,
rocm_inverse_rope_mxfp8_rows,
rocm_inverse_rope_rows_,
rocm_mxfp8_wo_a_bmm,
rocm_sparse_attn_decode,
rocm_sparse_attn_prefill,
)
@@ -662,7 +667,40 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
transpose_scale=False,
)
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
def _alloc_attn_out(
self, num_tokens: int, hidden_states: torch.Tensor
) -> torch.Tensor | QuantizedActivation:
if not _ON_GFX950:
return super()._alloc_attn_out(num_tokens, hidden_states)
# wo_a's MXFP8 input: the decode reduce writes it directly, prefill
# rows are rotated and quantized after their bf16 attention.
width = self.n_local_heads * self.head_dim
data = torch.empty(
(num_tokens, width), dtype=torch.float8_e4m3fn, device=hidden_states.device
)
scale = torch.empty(
(num_tokens, width // 32), dtype=torch.uint8, device=hidden_states.device
)
return QuantizedActivation(
data=data,
scale=scale,
orig_dtype=hidden_states.dtype,
orig_shape=data.shape,
quant_key=kMxfp8Dynamic,
)
def _o_proj(
self, attn_out: torch.Tensor | QuantizedActivation, positions: torch.Tensor
) -> torch.Tensor:
if isinstance(attn_out, QuantizedActivation):
z = rocm_mxfp8_wo_a_bmm(
attn_out.data,
attn_out.scale,
self.wo_a,
self.n_local_groups,
self.o_lora_rank,
)
return self._wo_b_after_wo_a(z)
o = attn_out[:, : self.n_local_heads, :]
# ROCm BF16 reference wo_a path (inverse RoPE + einsum) + wo_b.
z = rocm_inv_rope_einsum(
@@ -673,27 +711,31 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
self.n_local_groups,
self.o_lora_rank,
self.wo_a,
inverse_rope=False,
)
zf = z.flatten(1)
return self._wo_b_after_wo_a(z.flatten(1))
def _wo_b_after_wo_a(self, zf: torch.Tensor) -> torch.Tensor:
if self._wo_b_scale is not None and zf.dim() == 2:
result = self._bpre_attn_gemm(self.wo_b.weight, self._wo_b_scale, zf, True)
else:
result = self.wo_b(zf)
return result
return self._bpre_attn_gemm(self.wo_b.weight, self._wo_b_scale, zf, True)
return self.wo_b(zf)
def forward_mqa(
self,
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
output: torch.Tensor,
output: torch.Tensor | QuantizedActivation,
) -> None:
assert output.shape == q.shape, (
f"output buffer shape {output.shape} must match q shape {q.shape}"
)
assert output.dtype == q.dtype, (
f"output buffer dtype {output.dtype} must match q dtype {q.dtype}"
)
mxfp8_out = output if isinstance(output, QuantizedActivation) else None
if mxfp8_out is None:
assert isinstance(output, torch.Tensor)
assert output.shape == q.shape, (
f"output buffer shape {output.shape} must match q shape {q.shape}"
)
assert output.dtype == q.dtype, (
f"output buffer dtype {output.dtype} must match q dtype {q.dtype}"
)
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
@@ -711,9 +753,13 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
)
M = N + self.window_size + self.max_num_batched_tokens
current_workspace_manager().get_simultaneous(
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
*self._prefill_workspace_shapes(M, self.max_num_batched_tokens, q)
)
output.zero_()
if mxfp8_out is None:
output.zero_()
else:
mxfp8_out.data.zero_()
mxfp8_out.scale.zero_()
return
assert isinstance(attn_metadata, dict)
@@ -743,19 +789,63 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
positions=positions[num_decode_tokens:],
compressed_k_cache=self_kv_cache,
swa_k_cache=swa_kv_cache,
output=output[num_decode_tokens:],
output=(
output[num_decode_tokens:]
if isinstance(output, torch.Tensor)
else None
),
attn_metadata=rocm_metadata,
swa_metadata=swa_metadata,
mxfp8_out=(
None
if mxfp8_out is None
else (
mxfp8_out.data[num_decode_tokens:],
mxfp8_out.scale[num_decode_tokens:],
)
),
)
if mxfp8_out is not None:
# The reduce epilogue rotates and quantizes every decode row and
# the prefill path already did its own, so nothing is owed here.
if num_decodes > 0:
self._forward_decode(
q=q[:num_decode_tokens],
positions=positions[:num_decode_tokens],
kv_cache=self_kv_cache,
swa_metadata=swa_metadata,
attn_metadata=rocm_metadata,
swa_only=swa_only,
output=None,
output_mxfp8=(
mxfp8_out.data[:num_decode_tokens],
mxfp8_out.scale[:num_decode_tokens],
),
)
return
assert isinstance(output, torch.Tensor)
rotated = 0
if num_decodes > 0:
self._forward_decode(
rotated = self._forward_decode(
q=q[:num_decode_tokens],
positions=positions[:num_decode_tokens],
kv_cache=self_kv_cache,
swa_metadata=swa_metadata,
attn_metadata=rocm_metadata,
swa_only=swa_only,
output=output[:num_decode_tokens],
)
# Only the decode reduce rotates its own rows, and only the leading
# `rotated` of them; prefill rows and any decode path that did not
# fuse still owe the standalone pass. Settle that here rather than in
# _o_proj: the split is batch-dependent and _o_proj runs compiled,
# where such a value freezes at its trace-time value.
rocm_inverse_rope_rows_(
output[rotated:, : self.n_local_heads, :],
positions[rotated:],
self.rotary_emb.cos_sin_cache,
self.rope_head_dim,
)
def _decode_topk_ragged(
self,
@@ -796,12 +886,15 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
def _forward_decode(
self,
q: torch.Tensor,
positions: torch.Tensor,
kv_cache: torch.Tensor | None,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
attn_metadata: DeepseekV4FlashMLAMetadata | None,
swa_only: bool,
output: torch.Tensor,
) -> None:
output: torch.Tensor | None,
output_mxfp8: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> int:
"""Returns how many leading rows the decode epilogue inverse-RoPE'd."""
num_decodes = swa_metadata.num_decodes
num_decode_tokens = swa_metadata.num_decode_tokens
@@ -820,7 +913,7 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
num_decode_tokens=num_decode_tokens,
)
rocm_sparse_attn_decode(
return rocm_sparse_attn_decode(
q=q,
kv_cache=kv_cache,
swa_k_cache=self.swa_cache_layer.kv_cache,
@@ -839,6 +932,9 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
nope_head_dim=self.nope_head_dim,
rope_head_dim=self.rope_head_dim,
output=output,
output_mxfp8=output_mxfp8,
inv_rope_positions=positions,
inv_rope_cos_sin_cache=self.rotary_emb.cos_sin_cache,
extra_cache_nan_free=_trust_dsv4_extra_cache_nan_free(
self.kv_cache_dtype,
self._has_kv_transfer,
@@ -852,10 +948,16 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
positions: torch.Tensor,
compressed_k_cache: torch.Tensor | None,
swa_k_cache: torch.Tensor,
output: torch.Tensor,
output: torch.Tensor | None,
attn_metadata: DeepseekV4FlashMLAMetadata | None,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
mxfp8_out: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> None:
"""Sparse prefill into bf16 ``output``, or into ``mxfp8_out``.
With ``mxfp8_out`` the rows go to a bf16 workspace first and are then
inverse-RoPE'd and quantized into it in one pass.
"""
swa_only = attn_metadata is None
num_prefills = swa_metadata.num_prefills
@@ -891,10 +993,13 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
self.PREFILL_CHUNK_SIZE
)
workspace_manager = current_workspace_manager()
kv = workspace_manager.get_simultaneous(
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
)[0]
workspace = current_workspace_manager().get_simultaneous(
*self._prefill_workspace_shapes(M, num_prefill_tokens, q)
)
kv = workspace[0]
if mxfp8_out is not None:
output = workspace[1]
assert output is not None
for chunk_idx in range(num_chunks):
chunk_start = chunk_idx * self.PREFILL_CHUNK_SIZE
chunk_end = min(chunk_start + self.PREFILL_CHUNK_SIZE, num_prefills)
@@ -959,3 +1064,31 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
attn_sink=self.attn_sink,
output=output[query_start:query_end],
)
if mxfp8_out is not None:
rocm_inverse_rope_mxfp8_rows(
output,
positions[:num_prefill_tokens],
self.rotary_emb.cos_sin_cache,
self.rope_head_dim,
mxfp8_out[0][:num_prefill_tokens],
mxfp8_out[1][:num_prefill_tokens],
)
def _prefill_workspace_shapes(
self, M: int, num_prefill_tokens: int, q: torch.Tensor
) -> list[tuple[tuple[int, ...], torch.dtype]]:
"""The prefill gather buffer, plus bf16 rows for the MXFP8 output.
One ``get_simultaneous`` call: separate calls alias the same memory.
"""
shapes: list[tuple[tuple[int, ...], torch.dtype]] = [
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16)
]
if _ON_GFX950:
shapes.append(
(
(num_prefill_tokens, self.n_local_heads, self.head_dim),
torch.bfloat16,
)
)
return shapes
+26 -8
View File
@@ -79,20 +79,22 @@ class DeepseekV4VLImagePixelInputs(TensorSchema):
types: Annotated[torch.Tensor, TensorShape("ns", dynamic_dims={"ns"})]
_VL_PREFIX_MAPPING: dict[str, str | None] = {
"layers.": "language_model.model.layers.",
"embed.": "language_model.model.embed.",
"norm.": "language_model.model.norm.",
"hc_head": "language_model.model.hc_head",
"mtp.": "language_model.model.mtp.",
}
def _make_deepseek_v4_vl_weights_mapper(
expert_dtype: str, linear_scale_name: str
) -> WeightsMapper:
"""Text-checkpoint mapping rules re-rooted under ``language_model.``."""
base = _make_deepseek_v4_weights_mapper(expert_dtype, linear_scale_name)
orig_to_new_prefix: dict[str, str | None] = {
"layers.": "language_model.model.layers.",
"embed.": "language_model.model.embed.",
"norm.": "language_model.model.norm.",
"hc_head": "language_model.model.hc_head",
"mtp.": "language_model.model.mtp.",
}
return WeightsMapper(
orig_to_new_prefix=orig_to_new_prefix,
orig_to_new_prefix=dict(_VL_PREFIX_MAPPING),
orig_to_new_regex=base.orig_to_new_regex,
orig_to_new_suffix={
"head.weight": "language_model.lm_head.weight",
@@ -131,6 +133,22 @@ class DeepseekV41ForCausalLM(
supports_encoder_tp_data = True
# Both of these are read off the *class* by
# ``configure_quant_config``/``SupportsQuant``, before ``__init__`` runs,
# to translate a quantization config's checkpoint-style module names into
# runtime prefixes. ``__init__`` later overwrites the instance
# ``hf_to_vllm_mapper`` with the full weight-loading mapper; only the
# prefix rules matter here. Without the class attributes, per-layer specs
# naming ``layers.N.attn.wq_a`` never match this wrapper's
# ``language_model.model.layers.N.attn.wq_a`` and silently fall back to
# the global spec.
packed_modules_mapping = DeepseekV41LLMForCausalLM.packed_modules_mapping
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix=dict(_VL_PREFIX_MAPPING),
orig_to_new_substr={".shared_experts.w2": ".shared_experts.down_proj"},
)
# The MoE router needs raw token ids to detect image-span tokens
# (all carrying image_token_id, see common/mm_preprocess.py) and apply
# bias_vl.
+2 -2
View File
@@ -697,7 +697,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
else:
gemm_rs.warn_incompatible_projection()
def _wo_b_proj(self, z: torch.Tensor) -> torch.Tensor:
def _wo_b_proj(self, z: torch.Tensor | QuantizedActivation) -> torch.Tensor:
"""Apply ``wo_b``; with GEMM-RS bound, also reduce-scatter the result.
Every ``_o_proj`` implementation projects through this so the decoder
@@ -707,7 +707,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
"""
if self.gemm_rs is None:
return self.wo_b(z)
if self.gemm_rs.should_run(z):
if isinstance(z, torch.Tensor) and self.gemm_rs.should_run(z):
return self.gemm_rs.apply(z, self.wo_b)
# Small batches stay on the unfused path, which is faster there.
return sp_reduce_scatter(self.wo_b(z))
+6 -2
View File
@@ -47,7 +47,7 @@ from vllm.distributed import (
tensor_model_parallel_all_gather,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.utils import set_weight_attrs
from vllm.triton_utils import tl, triton
@@ -923,13 +923,17 @@ class Engram(nn.Module):
# suffix rule.
self.embed_tokens = self._create_embedding(layout, layer_hash_index)
n_hash_cols = (layout.max_ngram_size - 1) * layout.n_heads
self.wkv = ReplicatedLinear(
# Without sequence parallelism every TP rank holds every token, so
# shard the output columns instead of replicating the projection.
self.wkv = ColumnParallelLinear(
n_hash_cols * layout.head_dim,
self.dim * (self.hc_mult + 1),
bias=False,
gather_output=True,
quant_config=quant_config,
return_bias=False,
prefix=f"{prefix}.wkv",
disable_tp=use_sequence_parallel,
)
self.q_weight = nn.Parameter(
torch.empty(self.hc_mult, self.dim, dtype=torch.bfloat16),
@@ -1266,7 +1266,7 @@ def build_flashinfer_mixed_sparse_indices(
def _remap_flashinfer_index(values, block_size, block_span):
# FlashInfer's DSv4 kernel indexes sparse KV by physical token stride, so
# packed pages (#44577) need block*block_size+off -> block*block_span+off.
# TODO: remove once flashinfer-ai/flashinfer#3856 is fixed.
# The launcher declares these indices with sparse_indices_are_storage_offsets=True.
is_valid = values >= 0
safe_values = tl.where(is_valid, values, 0)
values = (safe_values // block_size) * block_span
@@ -3,7 +3,10 @@
import torch
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.model_executor.layers.fusion.quant_activation import (
QuantizedActivation,
get_input_quant_key,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
@@ -102,6 +105,7 @@ def fused_q_kv_rmsnorm_quant(
)
if tokens:
block = triton.next_power_of_2(max(q_size, kv_size))
launch_pdl = current_platform.is_arch_support_pdl()
_q_kv_norm_quant_kernel[(padded_tokens, 2)](
qr,
kv,
@@ -117,8 +121,9 @@ def fused_q_kv_rmsnorm_quant(
q_size,
kv_size,
block,
current_platform.is_arch_support_pdl(),
launch_pdl,
num_warps=8 if block >= 2048 else 4,
launch_pdl=launch_pdl,
)
return QuantizedActivation(qo, scales, qr.dtype, qr.shape, kMxfp8Dynamic), kvo
@@ -135,7 +140,7 @@ def can_fuse_query_quant(linears: list[torch.nn.Module]) -> bool:
# QuantKey does not encode scale layout; restrict this producer to the
# consumers that accept F8_128x4 swizzled scales.
return all(
getattr(linear, "input_quant_key", None) == kMxfp8Dynamic
get_input_quant_key(linear) == kMxfp8Dynamic
and type(getattr(getattr(linear, "quant_method", None), "kernel", None))
in (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel)
for linear in linears
@@ -25,6 +25,7 @@ from vllm.models.deepseek_v4.common.vision import (
build_packed_merge_metadata,
build_packed_vit_metadata,
)
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.worker.encoder_cudagraph_defs import (
EncoderCudaGraphCaptureInputs,
EncoderCudaGraphConfig,
@@ -370,18 +371,23 @@ class DeepseekV4VLEncoderCudaGraphMixin:
r = self.config.vision_downsample_ratio
vit_grid = self._get_grid_list(batch_mm_kwargs, "vit_grid")
llm_grid = self._get_grid_list(batch_mm_kwargs, "llm_grid")
types = batch_mm_kwargs["types"].to(aligner_out.device)
types = batch_mm_kwargs["types"]
n_rows = sum(-(-h // r) * (-(-w // r)) for h, w in vit_grid)
span_lens = [lh * (lw + 1) + 2 for lh, lw in llm_grid]
# Batched span assembly: one masked fill per role across all items.
dtype = aligner_out.dtype
span = aligner_out.new_empty(sum(span_lens), self.config.hidden_size)
span[types == IMAGE] = aligner_out[:n_rows]
span[types == IMAGE_START] = self.image_start.to(dtype)
span[types == IMAGE_END] = self.image_end.to(dtype)
span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype)
# Batched span assembly: one gather over [aligner rows, START,
# NEW_LINE, END] for all items. The index is built from the host-side
# ``types`` so that neither the copy nor the gather syncs.
is_image = types == IMAGE
src_idx = torch.where(
is_image,
is_image.cumsum(0) - 1,
n_rows + (types == IMAGE_NEW_LINE).long() + 2 * (types == IMAGE_END).long(),
)
delims = torch.stack([self.image_start, self.image_newline, self.image_end])
src = torch.cat([aligner_out[:n_rows], delims.to(aligner_out.dtype)])
span = src[async_tensor_h2d(src_idx, aligner_out.device)]
# Freshly allocated, so later replays cannot clobber the results.
offset = 0
+1 -1
View File
@@ -37,7 +37,7 @@ class CompressorBackend(AttentionBackend):
return "CompressorBackend"
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(1)]
@classmethod
+135 -63
View File
@@ -2,7 +2,9 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""NVIDIA Engram DP sharding, shared host storage, and asynchronous prefetch."""
import ctypes
import mmap
import os
import shutil
import tempfile
import weakref
@@ -20,6 +22,10 @@ from vllm.distributed import (
get_tensor_model_parallel_rank,
tensor_model_parallel_all_gather,
)
from vllm.distributed.device_communicators.shm_broadcast import (
SHM_PATH,
check_shm_free_space,
)
from vllm.distributed.parallel_state import GroupCoordinator
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
@@ -42,6 +48,41 @@ from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
logger = init_logger(__name__)
def _allocate_huge_page_storage(num_bytes: int) -> torch.Tensor | None:
"""Register prefaulted huge pages, or return None for pinned-memory fallback."""
try:
mapping = mmap.mmap(-1, num_bytes, flags=mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS)
mapping.madvise(mmap.MADV_HUGEPAGE)
except OSError as exc:
logger.warning(
"Engram huge-page allocation failed (%s); using pinned memory.", exc
)
return None
owner = np.frombuffer(mapping, dtype=np.uint8)
# Fault the pages in before CUDA pins them, so they can be huge.
owner[:: mmap.PAGESIZE] = 0
tensor = torch.from_numpy(owner)
pointer = tensor.data_ptr()
result = torch.cuda.cudart().cudaHostRegister(pointer, num_bytes, 0)
if result.value != 0:
logger.warning(
"Engram cudaHostRegister failed (%s); using pinned memory.", result
)
return None
# Tensor views retain owner; its finalizer retains mapping until unregister.
finalizer = weakref.finalize(
owner, DPSharedEngramStorage._unregister, mapping, pointer
)
finalizer.atexit = False # type: ignore[misc]
if not tensor.is_pinned():
logger.warning(
"CUDA did not recognize Engram registration; using pinned memory."
)
return None
return tensor
def engram_head_shard_rank() -> int:
"""This rank's slot among the hash-head shards of one engram table.
@@ -92,6 +133,13 @@ def gather_engram_hashes(
def can_share_engram_tables(layout: EngramLayout, block_size: int = 32) -> bool:
"""Whether co-located DP replicas exist and /dev/shm can hold the full tables."""
if not os.path.isdir(SHM_PATH):
logger.warning_once(
"%s is not mounted; storing the offloaded Engram tables per rank "
"instead of sharing them across DP replicas.",
SHM_PATH,
)
return False
if get_engram_dp_size() == 1:
logger.warning_once(
"Engram DP replicas are not co-located on one node; "
@@ -101,11 +149,12 @@ def can_share_engram_tables(layout: EngramLayout, block_size: int = 32) -> bool:
num_bytes = sum(layout.num_embeddings) * (
layout.head_dim + layout.head_dim // block_size
)
if shutil.disk_usage("/dev/shm").total < num_bytes:
if shutil.disk_usage(SHM_PATH).total < num_bytes:
logger.warning_once(
"Sharing Engram tables across DP replicas needs %.1f GiB of /dev/shm "
"Sharing Engram tables across DP replicas needs %.1f GiB of %s "
"(--shm-size or --ipc=host); sharding them across replicas instead.",
num_bytes / 1024**3,
SHM_PATH,
)
return False
return True
@@ -126,20 +175,14 @@ class DPSharedEngramStorage:
def _allocate(self, num_bytes: int) -> torch.Tensor:
"""Map and register one physical allocation across a node-local DP group."""
from vllm.distributed.device_communicators.shm_broadcast import (
check_shm_free_space,
)
group = self.group
with ExitStack() as stack:
path, error = None, None
path = error = None
if group.rank_in_group == 0:
try:
check_shm_free_space(num_bytes)
backing_file = stack.enter_context(
tempfile.NamedTemporaryFile(
prefix="vllm_engram_", dir="/dev/shm"
)
tempfile.NamedTemporaryFile(prefix="vllm_engram_", dir=SHM_PATH)
)
backing_file.truncate(num_bytes)
path = backing_file.name
@@ -151,57 +194,42 @@ class DPSharedEngramStorage:
"Engram shared-memory creation failed on EDP rank 0: " + error
)
mapping = owner = tensor = finalizer = None
stage = "open"
mapping = owner = tensor = None
try:
try:
with open(path, "r+b") as file:
stage = "mmap"
mapping = mmap.mmap(
file.fileno(), num_bytes, flags=mmap.MAP_SHARED
)
stage = "cudaHostRegister"
owner = np.frombuffer(mapping, dtype=np.uint8)
pointer = owner.ctypes.data
tensor = torch.from_numpy(owner)
result = torch.cuda.cudart().cudaHostRegister(pointer, num_bytes, 0)
if result.value != 0:
raise RuntimeError(f"cudaHostRegister failed: {result}")
finalizer = weakref.finalize(
owner, self._unregister, mapping, pointer
)
finalizer.atexit = False # type: ignore[misc]
# The UVA helper otherwise allocates a private pinned copy.
if not tensor.is_pinned():
raise RuntimeError(
"CUDA did not recognize the shared Engram registration"
)
except Exception as exc:
error = f"{stage}: {type(exc).__name__}: {exc}"
errors: list[str | None] = [None] * group.world_size
# Also fences peer mappings before the leader unlinks the file.
torch.distributed.all_gather_object(
errors, error, group=group.cpu_group
)
failures = "; ".join(
f"EDP rank {rank}: {error}"
for rank, error in enumerate(errors)
if error is not None
)
if failures:
with open(path, "r+b") as file:
mapping = mmap.mmap(file.fileno(), num_bytes, flags=mmap.MAP_SHARED)
owner = np.frombuffer(mapping, dtype=np.uint8)
pointer = owner.ctypes.data
tensor = torch.from_numpy(owner)
result = torch.cuda.cudart().cudaHostRegister(pointer, num_bytes, 0)
if result.value != 0:
raise RuntimeError(f"cudaHostRegister failed: {result}")
finalizer = weakref.finalize(owner, self._unregister, mapping, pointer)
finalizer.atexit = False # type: ignore[misc]
# The UVA helper otherwise allocates a private pinned copy.
if not tensor.is_pinned():
raise RuntimeError(
"Engram shared-memory initialization failed: " + failures
"cudaHostRegister did not pin the shared Engram mapping"
)
assert tensor is not None
return tensor
except Exception:
if finalizer is not None:
finalizer()
tensor = owner = None
if mapping is not None:
mapping.close()
raise
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
# Also fences peer mappings before the leader unlinks the file.
errors: list[str | None] = [None] * group.world_size
torch.distributed.all_gather_object(errors, error, group=group.cpu_group)
failures = "; ".join(
f"EDP rank {rank}: {error}"
for rank, error in enumerate(errors)
if error is not None
)
if failures:
# Dropping the owner runs the finalizer; the mapping then unmaps.
del tensor, owner, mapping
raise RuntimeError(
"Engram shared-memory initialization failed: " + failures
)
assert tensor is not None
return tensor
@staticmethod
def _unregister(mapping: mmap.mmap, pointer: int) -> None:
@@ -249,9 +277,12 @@ class ParallelEngramEmbedding(BaseParallelEngramEmbedding):
block_size: int = 32,
cpu_offload: bool = False,
dp_shared_memory: bool = False,
use_thp: bool = False,
) -> None:
self.cpu_offload = cpu_offload
self.dp_shared_memory = dp_shared_memory
self.use_thp = use_thp
self._packed: torch.Tensor | None = None
self.dp_size = get_engram_dp_size()
if dp_shared_memory:
if not cpu_offload:
@@ -300,6 +331,17 @@ class ParallelEngramEmbedding(BaseParallelEngramEmbedding):
return storage.weight, storage.weight_scale_inv
if not self.cpu_offload:
return super()._allocate_weights()
if self.use_thp:
weight_bytes = self.part_num_embeddings * self.dim
packed = _allocate_huge_page_storage(
weight_bytes + weight_bytes // self.block_size
)
if packed is not None:
self._packed = packed
return (
packed[:weight_bytes].view(torch.float8_e4m3fn).view(-1, self.dim),
packed[weight_bytes:].view(-1, self.dim // self.block_size),
)
# Model initialization may be inside a CUDA device context.
return (
torch.empty(
@@ -318,6 +360,19 @@ class ParallelEngramEmbedding(BaseParallelEngramEmbedding):
),
)
def collapse_huge_pages(self) -> None:
"""Best-effort MADV_COLLAPSE (Linux >= 6.1) of pages that faulted small."""
if self._packed is None:
return
addr, num_bytes = self._packed.data_ptr(), self._packed.nbytes
libc = ctypes.CDLL(None, use_errno=True)
libc.madvise.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int)
if libc.madvise(addr, num_bytes, 25) != 0:
logger.warning(
"Engram MADV_COLLAPSE failed; keeping existing pages: %s",
os.strerror(ctypes.get_errno()),
)
def _storage(self) -> tuple[torch.Tensor, torch.Tensor]:
if self._shared_memory is not None:
return self._shared_memory.get_views(self.weight, self.weight_scale_inv)
@@ -373,6 +428,15 @@ class Engram(BaseEngram):
"""NVIDIA Engram with asynchronous offload and node-local DP lookup."""
_prefetch_stream: torch.cuda.Stream | None = None
_prefetch_done: torch.cuda.Event | None = None
def __init__(
self, *args, prefetch_stream: torch.cuda.Stream | None = None, **kwargs
) -> None:
# Layers sharing one stream serialize their offloaded lookups, so they
# take turns instead of jointly starving decoder compute of SMs.
self._prefetch_stream = prefetch_stream
super().__init__(*args, **kwargs)
def _create_embedding(
self, layout: EngramLayout, layer_hash_index: int
@@ -385,12 +449,17 @@ class Engram(BaseEngram):
tuple(size for order in layout.primes[layer_hash_index] for size in order),
cpu_offload=engram_config.cpu_offload,
dp_shared_memory=bool(engram_config.dp_shared_memory),
use_thp=engram_config.use_thp,
)
def _init_staging(self, max_tokens: int, head_dim: int) -> None:
super()._init_staging(max_tokens * self.embed_tokens.dp_size, head_dim)
if self.embed_tokens.cpu_offload:
if not self.embed_tokens.cpu_offload:
self._prefetch_stream = None
return
if self._prefetch_stream is None:
self._prefetch_stream = torch.cuda.Stream(device=self.staged_rows.device)
self._prefetch_done = torch.cuda.Event()
def prepare_embeddings(self, hash_ids: torch.Tensor) -> None:
"""Prefetch local shared rows or the DP group's gathered hash IDs."""
@@ -410,14 +479,17 @@ class Engram(BaseEngram):
hash_ids.record_stream(stream)
with torch.cuda.stream(stream):
self.embed_tokens.lookup(hash_ids, rows, background=True)
assert self._prefetch_done is not None
self._prefetch_done.record(stream)
@eager_break_during_capture
def _finish_prefetch(self, stream: torch.cuda.Stream) -> None:
torch.cuda.current_stream().wait_stream(stream)
def _finish_prefetch(self, event: torch.cuda.Event) -> None:
# Wait for this layer's lookup only, not for later layers on the stream.
torch.cuda.current_stream().wait_event(event)
def _ready_rows(self, num_tokens: int) -> torch.Tensor:
if self._prefetch_stream is not None:
self._finish_prefetch(self._prefetch_stream)
if self._prefetch_done is not None:
self._finish_prefetch(self._prefetch_done)
if self.embed_tokens.dp_size > 1:
slot = engram_gathered_num_tokens()
staged = self.staged_rows[: slot * self.embed_tokens.dp_size]
@@ -9,15 +9,16 @@ import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.forward_context import get_forward_context
from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
compute_fp8_einsum_recipe,
deep_gemm_fp8_o_proj,
)
from vllm.models.deepseek_v4.nvidia.ops.o_proj import compute_fp8_einsum_recipe
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
from vllm.models.deepseek_v41.common.ops import (
build_flashinfer_mixed_sparse_indices,
compute_global_topk_indices_and_lens,
)
from vllm.models.deepseek_v41.nvidia.ops.o_proj import (
dsv41_o_proj,
register_dsv41_o_proj_warmup,
)
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4FlashMLAMetadata,
DeepseekV4SparseMLABackend,
@@ -113,7 +114,7 @@ class DeepseekV4FlashInferMLASparseBackend(DeepseekV4SparseMLABackend):
]
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [128]
@staticmethod
@@ -242,27 +243,14 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
return _pad_to_supported_q_heads(num_heads)
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
return deep_gemm_fp8_o_proj(
o,
positions,
self.rotary_emb.cos_sin_cache,
self.wo_a,
self._wo_b_proj,
n_groups=self.n_local_groups,
heads_per_group=self.n_local_heads // self.n_local_groups,
nope_dim=self.nope_head_dim,
rope_dim=self.rope_head_dim,
o_lora_rank=self.o_lora_rank,
einsum_recipe=self._einsum_recipe,
tma_aligned_scales=self._tma_aligned_scales,
)
return dsv41_o_proj(self, attn_out, positions)
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe(
self._o_proj_block_size
)
register_dsv41_o_proj_warmup(self)
# Per-tensor FP8 scale buffers + precomputed scalar BMM scales. Only the
# per-tensor FP8 cache path consumes these; bf16 reads ``self.scale``.
if self.kv_cache_torch_dtype != torch.float8_e4m3fn:
@@ -560,6 +548,7 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
swa_kv_cache=swa_k_cache,
workspace_buffer=workspace,
sparse_indices=sparse_indices[:num_decode_tokens],
sparse_indices_are_storage_offsets=True,
compressed_kv_cache=compressed_kv_cache,
sparse_topk_lens=decode_topk_lens,
seq_lens=decode_seq_lens,
@@ -585,6 +574,7 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
swa_kv_cache=swa_k_cache,
workspace_buffer=workspace,
sparse_indices=sparse_indices[num_decode_tokens:num_tokens],
sparse_indices_are_storage_offsets=True,
compressed_kv_cache=compressed_kv_cache,
sparse_topk_lens=sparse_topk_lens[num_decode_tokens:num_tokens],
seq_lens=seq_lens[num_decodes:num_reqs],
@@ -621,21 +611,7 @@ class DeepseekV4FlashInferSM120Attention(DeepseekV4Attention):
return _pad_to_supported_q_heads(num_heads)
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
return deep_gemm_fp8_o_proj(
o,
positions,
self.rotary_emb.cos_sin_cache,
self.wo_a,
self._wo_b_proj,
n_groups=self.n_local_groups,
heads_per_group=self.n_local_heads // self.n_local_groups,
nope_dim=self.nope_head_dim,
rope_dim=self.rope_head_dim,
o_lora_rank=self.o_lora_rank,
einsum_recipe=self._einsum_recipe,
tma_aligned_scales=self._tma_aligned_scales,
)
return dsv41_o_proj(self, attn_out, positions)
def __init__(self, vllm_config: VllmConfig, *args, **kwargs) -> None:
super().__init__(vllm_config, *args, **kwargs)
+7 -19
View File
@@ -6,16 +6,17 @@ from typing import TYPE_CHECKING, ClassVar, cast
import torch
from vllm.forward_context import get_forward_context
from vllm.models.deepseek_v4.nvidia.ops.o_proj import (
compute_fp8_einsum_recipe,
deep_gemm_fp8_o_proj,
)
from vllm.models.deepseek_v4.nvidia.ops.o_proj import compute_fp8_einsum_recipe
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
from vllm.models.deepseek_v41.common.ops import (
combine_topk_swa_indices,
compute_global_topk_indices_and_lens,
dequantize_and_gather_k_cache,
)
from vllm.models.deepseek_v41.nvidia.ops.o_proj import (
dsv41_o_proj,
register_dsv41_o_proj_warmup,
)
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4FlashMLABackend,
DeepseekV4FlashMLAMetadata,
@@ -57,23 +58,10 @@ class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
self._einsum_recipe, self._tma_aligned_scales = compute_fp8_einsum_recipe(
self._o_proj_block_size
)
register_dsv41_o_proj_warmup(self)
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
return deep_gemm_fp8_o_proj(
o,
positions,
self.rotary_emb.cos_sin_cache,
self.wo_a,
self._wo_b_proj,
n_groups=self.n_local_groups,
heads_per_group=self.n_local_heads // self.n_local_groups,
nope_dim=self.nope_head_dim,
rope_dim=self.rope_head_dim,
o_lora_rank=self.o_lora_rank,
einsum_recipe=self._einsum_recipe,
tma_aligned_scales=self._tma_aligned_scales,
)
return dsv41_o_proj(self, attn_out, positions)
@classmethod
def get_padded_num_q_heads(cls, num_heads: int) -> int:
+114 -5
View File
@@ -33,6 +33,14 @@ from vllm.model_executor.kernels.mhc.triton import hc_collapse_triton
from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.experts.trtllm_mxfp4_moe import (
TrtLlmMxfp4ExpertsModular,
)
from vllm.model_executor.layers.fused_moe.moe_output import (
MoEOutput,
UnfinalizedMoEOutput,
)
from vllm.model_executor.layers.fused_moe.runner.moe_runner import _unpack
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.quantization import QuantizationConfig
@@ -40,7 +48,10 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
ParallelLMHead,
VocabParallelEmbedding,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader,
drop_checkpoint_cache,
)
from vllm.model_executor.models.interfaces import (
EagleModelMixin,
MixtureOfExperts,
@@ -91,6 +102,7 @@ from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask
from .engram import Engram, can_share_engram_tables, gather_engram_hashes
from .ops.mhc import (
MHC_OVERLAP_MAX_TOKENS,
init_mhc_all_reduce,
mhc_pre_delayed_overlap,
mhc_shifted_post_pre,
supports_mhc_all_reduce,
@@ -132,6 +144,48 @@ class DeepseekV4MoE(DeepseekV4MoEBase):
image_sentinel_lo=IMAGE_SENTINEL_BASE_ID,
)
def defer_finalize(self) -> None:
"""Leave the routed top-k reduction to the next fused all-reduce + mHC.
Only the modular TRTLLM MXFP4 experts can stop after GEMM2; the fused
kernel takes as many tokens as the mHC overlap path.
"""
moe_config = self.experts.moe_config
experts_cls = getattr(
self.experts.routed_experts.quant_method, "experts_cls", None
)
if (
experts_cls is TrtLlmMxfp4ExpertsModular
and self.experts.routed_scaling_factor == 1.0
):
moe_config.defer_moe_finalize(MHC_OVERLAP_MAX_TOKENS)
if moe_config.use_deferred_moe_finalize:
logger.info_once(
"DSV4.1 mHC: MoE top-k finalize fused into the all-reduce for "
"up to %d tokens.",
MHC_OVERLAP_MAX_TOKENS,
)
def defers_finalize(self, num_tokens: int) -> bool:
return (
not self.use_mega_moe
and self.experts.moe_config.should_defer_moe_finalize(num_tokens)
)
def forward_unfinalized(
self, hidden_states: torch.Tensor, input_ids: torch.Tensor | None
) -> MoEOutput:
"""``forward`` with the routed top-k reduction and all-reduce left open."""
# The runner's custom op returns tensors only, so run its body directly.
shared_output, routed = _unpack(
self.experts._forward_impl(
hidden_states, hidden_states, hidden_states, input_ids
)
)
assert shared_output is not None
assert isinstance(routed, UnfinalizedMoEOutput)
return MoEOutput(routed=routed, shared_output=shared_output)
def _select_dsv4_attn_cls(vllm_config: VllmConfig) -> type[DeepseekV4Attention]:
"""Pick the CUDA sparse-MLA attention class for the configured backend.
@@ -226,6 +280,7 @@ class DeepseekV4DecoderLayer(nn.Module):
aux_stream_list: list[torch.cuda.Stream] | None = None,
candidate_block_buffer: torch.Tensor | None = None,
engram_layout: EngramLayout | None = None,
engram_prefetch_stream: torch.cuda.Stream | None = None,
run_gemm_rs: bool = False,
mhc_stream: torch.cuda.Stream | None = None,
fuse_mhc_all_reduce: bool = False,
@@ -249,6 +304,7 @@ class DeepseekV4DecoderLayer(nn.Module):
engram_layout.layer_ids.index(layer_id),
use_sequence_parallel=self.use_sequence_parallel,
prefix=f"{prefix}.engram",
prefetch_stream=engram_prefetch_stream,
)
self.rms_norm_eps = config.rms_norm_eps
@@ -389,7 +445,7 @@ class DeepseekV4DecoderLayer(nn.Module):
def forward(
self,
x: torch.Tensor,
x: torch.Tensor | MoEOutput,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
pre_mix: torch.Tensor | None = None,
@@ -402,7 +458,7 @@ class DeepseekV4DecoderLayer(nn.Module):
capture_previous_aux: bool = False,
mega_gate_metadata: MegaGateRoutingMetadata | None = None,
) -> tuple[
torch.Tensor,
torch.Tensor | MoEOutput,
torch.Tensor,
torch.Tensor,
torch.Tensor,
@@ -427,6 +483,7 @@ class DeepseekV4DecoderLayer(nn.Module):
# 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.
if residual is None:
assert isinstance(x, torch.Tensor)
if x.dim() == 2:
# First layer: the stream is the embedding broadcast to hc
# copies and the identity pre-mix selects copy 0.
@@ -466,7 +523,9 @@ class DeepseekV4DecoderLayer(nn.Module):
# 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.
# the post out of the pre-norm GEMM's fused prologue. The layer
# before an engram layer finalizes its own MoE.
assert isinstance(x, torch.Tensor)
if self.fuse_mhc_all_reduce:
x = tensor_model_parallel_all_reduce(x)
previous_post = mhc_post_tilelang(x, residual, post_mix, res_mix)
@@ -547,7 +606,11 @@ class DeepseekV4DecoderLayer(nn.Module):
stream=mhc_stream,
reduce_results=self.fuse_mhc_all_reduce,
)
x = self.ffn(x, input_ids, mega_gate_metadata)
if self.fuse_mhc_all_reduce and self.ffn.defers_finalize(x.shape[0]):
# The next layer's first boundary finalizes it with the all-reduce.
x = self.ffn.forward_unfinalized(x, input_ids)
else:
x = self.ffn(x, input_ids, mega_gate_metadata)
if mhc_stream is not None:
torch.cuda.current_stream().wait_stream(mhc_stream)
return x, residual, post_mix, res_mix, ffn_pre, previous_aux
@@ -586,6 +649,8 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
self.fuse_mhc_all_reduce = mhc_stream is not None and supports_mhc_all_reduce(
vllm_config
)
if self.fuse_mhc_all_reduce:
init_mhc_all_reduce(vllm_config)
# Reserved topk indices buffer for all Indexer layers to reuse.
self.topk_indices_buffer = torch.empty(
@@ -621,6 +686,14 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
self.engram_layout = EngramLayout.from_config(config)
engram_config = vllm_config.engram_config
self.vllm_config = vllm_config
engram_prefetch_stream = (
torch.cuda.Stream()
if self.engram_layout is not None
and engram_config is not None
and engram_config.cpu_offload
else None
)
if (
self.engram_layout is not None
and engram_config is not None
@@ -628,6 +701,15 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
):
engram_config.dp_shared_memory = can_share_engram_tables(self.engram_layout)
if self.engram_layout is not None and engram_config and engram_config.use_thp:
# Release old checkpoint cache before allocating the Engram host tables.
model_config = vllm_config.model_config
drop_checkpoint_cache(
model_config.model_weights or model_config.model,
revision=model_config.revision,
cache_dir=vllm_config.load_config.download_dir,
)
# GEMM-RS uses NCCL symmetric-memory multicast, which requires all TP
# ranks to belong to one NVLink domain. Collective: run before layers.
self.run_gemm_rs = maybe_init_gemm_rs(vllm_config, self.use_sequence_parallel)
@@ -641,12 +723,23 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
aux_stream_list=aux_stream_list,
candidate_block_buffer=self.candidate_block_buffer,
engram_layout=self.engram_layout,
engram_prefetch_stream=engram_prefetch_stream,
run_gemm_rs=self.run_gemm_rs,
mhc_stream=mhc_stream,
fuse_mhc_all_reduce=self.fuse_mhc_all_reduce,
),
prefix=f"{prefix}.layers",
)
if self.fuse_mhc_all_reduce:
# A MoE's top-k finalize folds into the next layer's first mHC
# boundary, which the last local layer lacks and an engram layer
# replaces with its own all-reduce.
local_layers = list(islice(self.layers, self.start_layer, self.end_layer))
for layer, successor in zip(local_layers, local_layers[1:]):
assert isinstance(layer, DeepseekV4DecoderLayer)
assert isinstance(successor, DeepseekV4DecoderLayer)
if successor.engram is None:
layer.ffn.defer_finalize()
# The n-gram hash needs a slot-keyed rolling store of compressed ids
# (chunked prefill / decode lookback); key it off the first local
@@ -851,6 +944,8 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
if self.use_sequence_parallel:
previous_aux = sp_all_gather(previous_aux)[:full_num_tokens]
aux_hidden_by_layer[idx] = previous_aux
# Without a successor boundary, the last layer finalized its own MoE.
assert isinstance(hidden_states, torch.Tensor)
if layer is not None:
# The last layer has no successor to fold its post into.
if self.fuse_mhc_all_reduce:
@@ -1329,6 +1424,20 @@ class DeepseekV41LLMForCausalLM(
loader = AutoWeightsLoader(self)
loaded_params = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
self.process_weights_after_loading()
config = self.model.vllm_config
if config.engram_config and config.engram_config.use_thp:
# Loading weights refills the file cache; release it before MADV_COLLAPSE.
model_config = config.model_config
drop_checkpoint_cache(
model_config.model_weights or model_config.model,
revision=model_config.revision,
cache_dir=config.load_config.download_dir,
)
for layer in islice(
self.model.layers, self.model.start_layer, self.model.end_layer
):
if layer.engram is not None:
layer.engram.embed_tokens.collapse_huge_pages()
return loaded_params
def process_weights_after_loading(self) -> None:
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CuTe DSL kernels for DSV4.1 mHC."""
from .all_reduce_mhc import AllReduceMHC
__all__ = ["AllReduceMHC"]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,396 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from FlashInfer's flashinfer/comm/mnnvl_cutedsl/cute_dsl_primitives.py
# and runtime.py (flashinfer-ai/flashinfer@139af6f6).
"""PTX building blocks and launch helpers for the DSV4.1 LL all-reduce."""
import cuda.bindings.driver as cuda
import cutlass
import cutlass.cute as cute
import torch
from cutlass import Float32, Int32, Int64, Uint16, Uint32
from cutlass._mlir import ir
from cutlass._mlir.dialects import llvm, vector
from cutlass.cute.runtime import from_dlpack, make_fake_compact_tensor
from cutlass.cutlass_dsl import T, dsl_user_op
WARP_SIZE = 32
VEC_BF16 = 8
QUAD_BF16 = 4
NEGATIVE_ZERO_BF16_BITS = 0x8000
NEGATIVE_ZERO_BF16_PAIR = 0x80008000
def _asm(result, operands, text, constraints, *, side_effects, loc, ip):
return llvm.inline_asm(
result,
operands,
text,
constraints,
has_side_effects=side_effects,
is_align_stack=False,
asm_dialect=llvm.AsmDialect.AD_ATT,
loc=loc,
ip=ip,
)
@dsl_user_op
def load_global_u32x4(
pointer: cute.Pointer,
*,
volatile: cutlass.Constexpr[bool] = False,
loc=None,
ip=None,
):
address = pointer.toint(loc=loc, ip=ip)
opcode = "ld.volatile.global.v4.u32" if volatile else "ld.global.v4.u32"
loaded = _asm(
llvm.StructType.get_literal([T.i32()] * 4),
[address.ir_value(loc=loc, ip=ip)],
f"{opcode} {{$0, $1, $2, $3}}, [$4];",
"=r,=r,=r,=r,l",
side_effects=volatile,
loc=loc,
ip=ip,
)
packed = vector.from_elements(
ir.VectorType.get([4], T.i32(), loc=loc),
[
llvm.extractvalue(T.i32(), loaded, [index], loc=loc, ip=ip)
for index in range(4)
],
loc=loc,
ip=ip,
)
return cute.TensorSSA(packed, 4, Uint32)
@dsl_user_op
def load_global_u32x2(pointer: cute.Pointer, *, loc=None, ip=None):
address = pointer.toint(loc=loc, ip=ip)
loaded = _asm(
llvm.StructType.get_literal([T.i32()] * 2),
[address.ir_value(loc=loc, ip=ip)],
"ld.global.v2.u32 {$0, $1}, [$2];",
"=r,=r,l",
side_effects=False,
loc=loc,
ip=ip,
)
packed = vector.from_elements(
ir.VectorType.get([2], T.i32(), loc=loc),
[
llvm.extractvalue(T.i32(), loaded, [index], loc=loc, ip=ip)
for index in range(2)
],
loc=loc,
ip=ip,
)
return cute.TensorSSA(packed, 2, Uint32)
@dsl_user_op
def load_global_bf16_as_f32(address: Int64, *, loc=None, ip=None) -> Float32:
return Float32(
_asm(
T.f32(),
[address.ir_value(loc=loc, ip=ip)],
"{\n\t.reg .b16 bits;\n\tld.global.b16 bits, [$1];\n\t"
"cvt.f32.bf16 $0, bits;\n\t}",
"=f,l",
side_effects=False,
loc=loc,
ip=ip,
)
)
@dsl_user_op
def store_global_u32x4(address: Int64, packed, *, loc=None, ip=None) -> None:
words = [packed[index].ir_value(loc=loc, ip=ip) for index in range(4)]
_asm(
None,
[address.ir_value(loc=loc, ip=ip), *words],
"st.global.v4.u32 [$0], {$1, $2, $3, $4};",
"l,r,r,r,r",
side_effects=True,
loc=loc,
ip=ip,
)
@dsl_user_op
def store_lamport_sentinel_u32x4(address: Int64, *, loc=None, ip=None) -> None:
sentinel = Uint32(NEGATIVE_ZERO_BF16_PAIR).ir_value(loc=loc, ip=ip)
_asm(
None,
[address.ir_value(loc=loc, ip=ip), sentinel, sentinel, sentinel, sentinel],
"st.global.v4.u32 [$0], {$1, $2, $3, $4};",
"l,r,r,r,r",
side_effects=True,
loc=loc,
ip=ip,
)
@dsl_user_op
def load_volatile_u32(pointer: cute.Pointer, *, loc=None, ip=None) -> Uint32:
address = pointer.toint(loc=loc, ip=ip)
return Uint32(
_asm(
T.i32(),
[address.ir_value(loc=loc, ip=ip)],
"ld.volatile.global.u32 $0, [$1];",
"=r,l",
side_effects=True,
loc=loc,
ip=ip,
)
)
@dsl_user_op
def store_global_u32(
pointer: cute.Pointer, value: Uint32, *, loc=None, ip=None
) -> None:
address = pointer.toint(loc=loc, ip=ip)
_asm(
None,
[address.ir_value(loc=loc, ip=ip), value.ir_value(loc=loc, ip=ip)],
"st.global.u32 [$0], $1;",
"l,r",
side_effects=True,
loc=loc,
ip=ip,
)
@dsl_user_op
def packed_u32x4_to_bf16x8(packed, *, loc=None, ip=None):
values = llvm.bitcast(
ir.VectorType.get([VEC_BF16], cutlass.BFloat16.mlir_type, loc=loc),
packed.ir_value(loc=loc, ip=ip),
loc=loc,
ip=ip,
)
return cute.TensorSSA(values, VEC_BF16, cutlass.BFloat16)
@dsl_user_op
def packed_u32x2_to_bf16x4(packed, *, loc=None, ip=None):
values = llvm.bitcast(
ir.VectorType.get([QUAD_BF16], cutlass.BFloat16.mlir_type, loc=loc),
packed.ir_value(loc=loc, ip=ip),
loc=loc,
ip=ip,
)
return cute.TensorSSA(values, QUAD_BF16, cutlass.BFloat16)
@dsl_user_op
def bf16x4_to_packed_u32x2(values, *, loc=None, ip=None):
packed = llvm.bitcast(
ir.VectorType.get([2], T.i32(), loc=loc),
values.ir_value(loc=loc, ip=ip),
loc=loc,
ip=ip,
)
return cute.TensorSSA(packed, 2, Uint32)
@dsl_user_op
def bf16x8_to_packed_u32x4(values, *, loc=None, ip=None):
packed = llvm.bitcast(
ir.VectorType.get([4], T.i32(), loc=loc),
values.ir_value(loc=loc, ip=ip),
loc=loc,
ip=ip,
)
return cute.TensorSSA(packed, 4, Uint32)
@cute.jit
def sanitize_negative_zero_u32(word: Uint32) -> Uint32:
low = Uint16(word & Uint32(0xFFFF))
high = Uint16(word >> Uint32(16))
if low == Uint16(NEGATIVE_ZERO_BF16_BITS):
word = word & Uint32(0xFFFF0000)
if high == Uint16(NEGATIVE_ZERO_BF16_BITS):
word = word & Uint32(0x0000FFFF)
return word
@cute.jit
def sanitize_negative_zero_u32x4(packed):
sanitized = cute.make_rmem_tensor(cute.make_layout((4,)), Uint32)
for index in cutlass.range_constexpr(4):
sanitized[index] = sanitize_negative_zero_u32(packed[index])
return sanitized.load()
@cute.jit
def sanitize_negative_zero_u32x2(packed):
sanitized = cute.make_rmem_tensor(cute.make_layout((2,)), Uint32)
for index in cutlass.range_constexpr(2):
sanitized[index] = sanitize_negative_zero_u32(packed[index])
return sanitized.load()
@cute.jit
def fragment_has_negative_zero(packed):
dirty = False
for index in cutlass.range_constexpr(4):
word = packed[index]
dirty = (
dirty
| (Uint16(word & Uint32(0xFFFF)) == Uint16(NEGATIVE_ZERO_BF16_BITS))
| (Uint16(word >> Uint32(16)) == Uint16(NEGATIVE_ZERO_BF16_BITS))
)
return dirty
@dsl_user_op
def map_shared_to_peer(
smem_pointer: cute.Pointer, peer_rank: Int32, *, loc=None, ip=None
) -> Int32:
address = smem_pointer.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip)
return Int32(
_asm(
T.i32(),
[address, peer_rank.ir_value(loc=loc, ip=ip)],
"mapa.shared::cluster.u32 $0, $1, $2;",
"=r,r,r",
side_effects=False,
loc=loc,
ip=ip,
)
)
@dsl_user_op
def store_shared_cluster_f32(
remote_address: Int32, value: Float32, *, loc=None, ip=None
) -> None:
_asm(
None,
[remote_address.ir_value(loc=loc, ip=ip), value.ir_value(loc=loc, ip=ip)],
"st.shared::cluster.f32 [$0], $1;",
"r,f",
side_effects=True,
loc=loc,
ip=ip,
)
@dsl_user_op
def f32_to_bf16_bits(value: Float32, *, loc=None, ip=None) -> Uint32:
return Uint32(
_asm(
T.i32(),
[value.ir_value(loc=loc, ip=ip)],
"{\n\t.reg .b16 bits;\n\tcvt.rn.bf16.f32 bits, $1;\n\t"
"cvt.u32.u16 $0, bits;\n\t}",
"=r,f",
side_effects=False,
loc=loc,
ip=ip,
)
)
@dsl_user_op
def shuffle_sync_idx_u32(
value: Uint32, source_lane: Int32, *, loc=None, ip=None
) -> Uint32:
return Uint32(
_asm(
T.i32(),
[value.ir_value(loc=loc, ip=ip), source_lane.ir_value(loc=loc, ip=ip)],
"shfl.sync.idx.b32 $0, $1, $2, 0x1f, 0xffffffff;",
"=r,r,r",
# Preserve full-warp execution across later divergent consumers.
side_effects=True,
loc=loc,
ip=ip,
)
)
@dsl_user_op
def stmc_bf16x2(address: Int64, packed: Uint32, *, loc=None, ip=None) -> None:
_asm(
None,
[address.ir_value(loc=loc, ip=ip), packed.ir_value(loc=loc, ip=ip)],
"multimem.st.relaxed.sys.global.bf16x2 [$0], $1;",
"l,r",
side_effects=True,
loc=loc,
ip=ip,
)
@dsl_user_op
def stmc_bf16x4(address: Int64, values, *, loc=None, ip=None) -> None:
words = [values[index].ir_value(loc=loc, ip=ip) for index in range(2)]
_asm(
None,
[address.ir_value(loc=loc, ip=ip), *words],
"multimem.st.relaxed.sys.global.v2.bf16x2 [$0], {$1, $2};",
"l,r,r",
side_effects=True,
loc=loc,
ip=ip,
)
@dsl_user_op
def stmc_bf16x8(address: Int64, values, *, loc=None, ip=None) -> None:
words = [values[index].ir_value(loc=loc, ip=ip) for index in range(4)]
_asm(
None,
[address.ir_value(loc=loc, ip=ip), *words],
"multimem.st.relaxed.sys.global.v4.bf16x2 [$0], {$1, $2, $3, $4};",
"l,r,r,r,r",
side_effects=True,
loc=loc,
ip=ip,
)
class _GraphSafeDLPack:
__slots__ = ("tensor",)
def __init__(self, tensor: torch.Tensor) -> None:
self.tensor = tensor
def __dlpack__(self, stream=None):
# stream=-1 skips producer sync; CuTe launches on the current stream,
# which is the capturing one under CUDA graphs.
return self.tensor.__dlpack__(stream=-1)
def __dlpack_device__(self):
return self.tensor.__dlpack_device__()
def to_cute(tensor: torch.Tensor, alignment: int) -> cute.Tensor:
return from_dlpack(_GraphSafeDLPack(tensor.detach()), assumed_align=alignment)
def to_cute_dynamic(
tensor: torch.Tensor, alignment: int, *, divisibility: int
) -> cute.Tensor:
return to_cute(tensor, alignment).mark_compact_shape_dynamic(
mode=0, divisibility=divisibility
)
def make_fake_dynamic_compact_tensor(dtype, *, alignment: int, divisibility: int):
return make_fake_compact_tensor(
dtype, (cute.sym_int32(divisibility=divisibility),), assumed_align=alignment
)
def current_cu_stream() -> cuda.CUstream:
return cuda.CUstream(torch.cuda.current_stream().cuda_stream)
@@ -0,0 +1,599 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DSV4.1 small-batch MXFP8 WO-A with inverse RoPE and quantization."""
from dataclasses import dataclass
from typing import Any
import cutlass
import cutlass.cute as cute
import cutlass.utils as utils
import torch
from cuda.bindings.driver import CUstream
from cutlass import (
BFloat16,
Float8E4M3FN,
Float32,
Int32,
Int64,
Uint8,
Uint32,
Uint64,
)
from cutlass._mlir.dialects import llvm
from cutlass.cute.nvgpu import cpasync, tcgen05
from cutlass.cute.runtime import make_fake_tensor
from cutlass.cutlass_dsl import dsl_user_op
from vllm.cute_utils import _tcgen05, mbarrier, recast_val, simple_tma_copy
from vllm.model_executor.warmup.jit_warmup import WarmupIntRange, kernel_launcher
from vllm.model_executor.warmup.jit_warmup_cutedsl_helper import (
CuTeDSLLaunchSpec,
VllmCuTeDSLJitKernel,
)
# Each head is [nope | rope] as in fused_inv_rope_fp8_quant: only the last
# _ROPE_DIM columns carry RoPE.
_HEAD_DIM = 512
_ROPE_DIM = 64
@dsl_user_op
def _ue8m0_rp(value, *, loc=None, ip=None):
result = llvm.inline_asm(
Uint32.mlir_type,
[value.ir_value(loc=loc, ip=ip)],
"{ .reg .b16 sf; cvt.rp.satfinite.ue8m0x2.f32 sf, $1, $1; "
"cvt.u32.u16 $0, sf; and.b32 $0, $0, 255; }",
"=r,f",
has_side_effects=False,
loc=loc,
ip=ip,
)
return Uint32(result)
@dsl_user_op
def _rope_fma(value, cos, other, sin, *, subtract=False, loc=None, ip=None):
"""Preserve multiply/FMA rounding when RoPE loads are hoisted."""
result = llvm.inline_asm(
Float32.mlir_type,
[v.ir_value(loc=loc, ip=ip) for v in (value, cos, other, sin)],
"{ .reg .f32 product; mul.rn.f32 product, $3, $4; "
+ (
"neg.f32 product, product; fma.rn.f32 $0, $1, $2, product; }"
if subtract
else "fma.rn.f32 $0, $1, $2, product; }"
),
"=f,f,f,f,f",
has_side_effects=False,
loc=loc,
ip=ip,
)
return Float32(result)
@cute.jit
def _scale(amax: Float32):
exponent = _ue8m0_rp(amax * Float32(1.0 / 448.0))
inv = recast_val((Uint32(254) - exponent) << 23, Float32)
if exponent == 0:
inv = Float32(0)
return exponent, inv
class FusedWoAKernel(VllmCuTeDSLJitKernel["FusedWoAKernel.CompileKey"]):
@dataclass(frozen=True)
class CompileKey:
# T=1..96 uses at most 46 keys per (n_groups, heads_per_group, o_lora_rank).
tokens_per_tile: int
token_tiles: int
full_tiles: bool
n_groups: int
heads_per_group: int
o_lora_rank: int
@staticmethod
def kernel(compile_key: CompileKey) -> Any:
tokens = compile_key.tokens_per_tile
token_tiles = compile_key.token_tiles
full_tiles = compile_key.full_tiles
acc_cols = 1 << (tokens - 1).bit_length()
tile_m = max(8, acc_cols)
tile_n = 128
tile_k = 128
# tcgen05 MXFP8 MMA consumes K = 32, one MX block, per instruction.
mma_k = 32
# Each group's heads split K across one cluster, one head per CTA.
heads_per_group = compile_key.heads_per_group
tiles_per_group = compile_key.o_lora_rank // tile_n
n_tiles = compile_key.n_groups * tiles_per_group
# Each CTA keeps one whole head of K in SMEM, one TMA box per stage.
num_stages = _HEAD_DIM // tile_k
w_stage_bytes = tile_n * tile_k
nope_dim = _HEAD_DIM - _ROPE_DIM
threads_per_token = _HEAD_DIM // 4
sf_col = max(16, tile_m)
tmem_cols = sf_col * 2
threads = min(acc_cols * threads_per_token, 512)
tokens_per_iter = threads // threads_per_token
@cute.kernel
def device_kernel(
x: cute.Tensor,
positions: cute.Tensor,
rope: cute.Tensor,
w: cpasync.TmaInfo,
ws: cpasync.TmaInfo,
q: cute.Tensor,
qs: cute.Tensor,
num_tokens: Int32,
):
total_tokens = num_tokens
if cutlass.const_expr(full_tiles):
total_tokens = Int32(tokens * token_tiles)
tid, _, _ = cute.arch.thread_idx()
bid, token_tile, _ = cute.arch.block_idx()
token_start = Int32(0)
if cutlass.const_expr(token_tiles > 1):
token_start = token_tile * tokens
warp = cute.arch.make_warp_uniform(tid // 32)
lane = tid % 32
split = bid % heads_per_group
tile = bid // heads_per_group
group = tile // tiles_per_group
smem = utils.SmemAllocator()
sW = smem.allocate_tensor(
Float8E4M3FN,
w.smem_layout.outer,
byte_alignment=128,
swizzle=w.smem_layout.inner,
)
sX = smem.allocate_tensor(
Float8E4M3FN,
cute.make_layout(
(tile_m, tile_k, num_stages), stride=(tile_k, 1, tile_m * tile_k)
),
byte_alignment=1024,
swizzle=cute.make_swizzle(3, 4, 3),
)
# tcgen05.cp 32x128b.warpx4 order: row r at byte (r % 32) * 16 +
# (r // 32) * 4, one 4-byte cell of MX-block scales per row.
sW_SF = smem.allocate_tensor(
Int32,
cute.make_layout(((32, 4), num_stages), stride=((4, 1), tile_n)),
128,
)
sW_SF_raw = smem.allocate_tensor(
Int32, cute.make_layout((tile_n, num_stages)), 128
)
sX_SF = smem.allocate_tensor(
Uint8,
cute.make_layout(
((32, 4), tile_k // mma_k, num_stages),
stride=((16, 4), 1, tile_n * 4),
),
128,
)
copy_fp8x4 = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), Float8E4M3FN, num_bits_per_copy=32
)
partial = smem.allocate_tensor(
Float32,
cute.make_layout(
(tile_n, cute.ceil_div(tokens, heads_per_group), heads_per_group)
),
128,
)
mbar_loaded = smem.allocate_array(Int64, num_stages)
mbar_ws_loaded = smem.allocate_array(Int64, 1)
mbar_done = smem.allocate_array(Int64, 1)
mbar_reduced = smem.allocate_array(Int64, 1)
taddr = smem.allocate(Int32, 4)
if tid == 0:
for stage in cutlass.range_constexpr(num_stages):
# Wait for weight TMA and this stage's quantization threads.
cute.arch.mbarrier_init(mbar_loaded + stage, 1 + threads // 4)
cute.arch.mbarrier_init(mbar_ws_loaded, 1)
cute.arch.mbarrier_init(mbar_done, 1)
cute.arch.mbarrier_init(mbar_reduced, 1)
cute.arch.mbarrier_init_fence()
# Local users of the barriers (warp 0's TMA below) need the init too.
cute.arch.sync_threads()
# Paired with cluster_wait() below: peers must see mbar_reduced
# initialized before their st.async; the split hides the barrier.
cute.arch.cluster_arrive_relaxed()
if warp == 0:
# Raw DeepGEMM MN-major scales; the MMA warp transposes them to
# the UTCCP order, which TMA cannot scatter at 4-byte granularity.
ws_tiles = cute.zipped_divide(ws.tma_tensor, (tile_n, num_stages))
with cute.arch.elect_one():
mbarrier.arrive_expect_tx(mbar_ws_loaded, tile_n * num_stages * 4)
simple_tma_copy(
ws.atom,
ws_tiles[None, (tile % tiles_per_group, split, group)],
sW_SF_raw,
mbar_ws_loaded,
)
tiles = cute.zipped_divide(w.tma_tensor, (tile_n, tile_k))
for stage in cutlass.range_constexpr(num_stages):
with cute.arch.elect_one():
mbarrier.arrive_expect_tx(mbar_loaded + stage, w_stage_bytes)
simple_tma_copy(
w.atom,
tiles[None, (tile, split * num_stages + stage)],
sW[None, None, stage],
mbar_loaded + stage,
)
# x and positions come from the PDL predecessor; everything above
# only touches weights. Padded sX rows only feed unread MMA columns.
cute.arch.griddepcontrol_wait()
# TMEM is allocated at runtime, and a PDL predecessor on this SM may
# hold it until it exits; allocating earlier can deadlock.
if warp == 0:
cute.arch.alloc_tmem(tmem_cols, taddr)
cute.arch.relinquish_tmem_alloc_permit()
copy_x = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), BFloat16, num_bits_per_copy=64
)
n_iters = cute.ceil_div(tokens, tokens_per_iter)
qid = (tid + 32) % threads_per_token
k = qid * 4
# Tail rows repeat the last input; their output stores are masked.
# Issue every token's x load before any math so their latencies overlap.
x_bf16 = cute.make_rmem_tensor((4, n_iters), BFloat16)
for iteration in cutlass.range_constexpr(n_iters):
token = iteration * tokens_per_iter + tid // threads_per_token
if cutlass.const_expr(tokens % tokens_per_iter == 0) or token < tokens:
x_src = cute.local_tile(
x[
cute.min(token_start + token, total_tokens - 1),
group * heads_per_group + split,
None,
],
(4,),
(qid,),
)
cute.copy(copy_x, x_src, x_bf16[None, iteration])
# Overlap the RoPE loads across tokens before consuming any of them.
cos_reg = cute.make_rmem_tensor((2, n_iters), Float32)
sin_reg = cute.make_rmem_tensor((2, n_iters), Float32)
if cutlass.const_expr(n_iters > 1):
copy_rope = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), Float32, num_bits_per_copy=32
)
if k >= nope_dim:
for iteration in cutlass.range_constexpr(n_iters):
token = iteration * tokens_per_iter + tid // threads_per_token
if (
cutlass.const_expr(tokens % tokens_per_iter == 0)
or token < tokens
):
src_token = cute.min(token_start + token, total_tokens - 1)
pos = positions[src_token]
freq = (k - nope_dim) // 2
rope_row = rope[pos, None]
cos_src = cute.local_tile(rope_row, (2,), (freq // 2,))
cute.copy(copy_rope, cos_src, cos_reg[None, iteration])
sin_tile = (freq + _ROPE_DIM // 2) // 2
sin_src = cute.local_tile(rope_row, (2,), (sin_tile,))
cute.copy(copy_rope, sin_src, sin_reg[None, iteration])
for iteration in cutlass.range_constexpr(n_iters):
token = iteration * tokens_per_iter + tid // threads_per_token
if cutlass.const_expr(tokens % tokens_per_iter == 0) or token < tokens:
x_f32 = cute.make_rmem_tensor((4,), Float32)
x_f32.store(x_bf16[None, iteration].load().to(Float32))
if k >= nope_dim:
# Inverse RoPE on the interleaved pairs (k, k+1) and
# (k+2, k+3); each rope row is cos || sin.
for pair in cutlass.range_constexpr(2):
if cutlass.const_expr(n_iters > 1):
cos = cos_reg[pair, iteration]
sin = sin_reg[pair, iteration]
else:
pos = positions[
cute.min(token_start + token, total_tokens - 1)
]
freq = (k - nope_dim) // 2 + pair
cos = Float32(rope[pos, freq])
sin = Float32(rope[pos, freq + _ROPE_DIM // 2])
even, odd = x_f32[2 * pair], x_f32[2 * pair + 1]
x_f32[2 * pair] = _rope_fma(even, cos, odd, sin)
x_f32[2 * pair + 1] = _rope_fma(
odd, cos, even, sin, subtract=True
)
amax = cute.arch.fmax(
cute.arch.fmax(cute.abs(x_f32[0]), cute.abs(x_f32[1])),
cute.arch.fmax(cute.abs(x_f32[2]), cute.abs(x_f32[3])),
)
amax = cute.arch.warp_reduction_max(amax, threads_in_group=8)
exponent, inv = _scale(cute.arch.fmax(amax, Float32(1e-10)))
x_fp8 = cute.make_rmem_tensor((4,), Float8E4M3FN)
x_fp8.store((x_f32.load() * inv).to(Float8E4M3FN))
cute.copy(
copy_fp8x4,
x_fp8,
cute.local_tile(
sX[token, None, k // tile_k], (4,), (qid % 32,)
),
)
if lane % 8 == 0:
sX_SF[token, k % tile_k // mma_k, k // tile_k] = Uint8(exponent)
cute.arch.fence_proxy("async.shared", space="cta")
mbarrier.arrive(mbar_loaded + qid // 32, order="release")
if warp == 0:
base = cute.make_tensor(taddr, cute.make_layout(1))[0]
# sW / sX are 128B-swizzled K-major; one stage's K fills the
# swizzle atom, so the leading byte offset is unused.
sdesc = _tcgen05.make_sdesc_128B_swizzle(LBO=0)
# Unswizzled 32 x 16 B scale tiles: SBO = one 8-row core matrix
# (16 B units at bit 32); bit 46 is the SM100 descriptor version.
sf_sbo = 8 * 16
sfdesc = Uint64((sf_sbo >> 4 << 32) | (1 << 46))
# M = tile_n weight rows (A), N = tile_m token rows (B).
idesc = _tcgen05.make_mxfp8_idesc(tile_n, tile_m)
# sW_SF's layout is the UTCCP order, so a plain copy transposes;
# fence the generic-proxy writes before tcgen05.cp reads them.
cute.arch.mbarrier_wait(mbar_ws_loaded, 0)
for stage in cutlass.range_constexpr(num_stages):
for i in cutlass.range_constexpr(4):
sW_SF[i * 32 + lane, stage] = sW_SF_raw[i * 32 + lane, stage]
cute.arch.fence_proxy("async.shared", space="cta")
cute.arch.sync_warp()
for stage in cutlass.range_constexpr(num_stages):
cute.arch.mbarrier_wait(mbar_loaded + stage, 0)
_tcgen05.fence_after_thread_sync()
if cutlass.const_expr(stage == num_stages - 1):
with cute.arch.elect_one():
cute.arch.griddepcontrol_launch_dependents()
adesc = sdesc | (sW[None, None, stage].iterator.toint() >> 4)
bdesc = sdesc | (sX[None, None, stage].iterator.toint() >> 4)
_tcgen05.cp(
base + sf_col,
sfdesc | (sW_SF[None, stage].iterator.toint() >> 4),
"32x128b",
"warpx4",
)
_tcgen05.cp(
base + sf_col + 4,
sfdesc | (sX_SF[None, None, stage].iterator.toint() >> 4),
"32x128b",
"warpx4",
)
# Advance mma_k FP8 bytes (16 B units) and pick MX block kk of
# each 4-byte scale (B sf_id at bit 4, A sf_id at bit 29).
for kk in cutlass.range_constexpr(tile_k // mma_k):
_tcgen05.mma_mxfp8(
base,
adesc + kk * mma_k // 16,
bdesc + kk * mma_k // 16,
idesc + ((kk << 4) | (kk << 29)),
base + sf_col,
base + sf_col + 4,
stage > 0 or kk > 0,
)
_tcgen05.commit(mbar_done)
# Only the MMA warp waits; barrier 2 releases the TMEM readers.
cute.arch.mbarrier_wait(mbar_done, 0)
if tid < tile_n:
cute.arch.barrier(barrier_id=2, number_of_threads=tile_n)
# Tokens t with t % heads_per_group == split arrive from every peer
# (this CTA included), tile_n Float32 rows each.
if tid == 0:
owned = cute.ceil_div(tokens - split, heads_per_group)
mbarrier.arrive_expect_tx(
mbar_reduced, owned * tile_n * heads_per_group * 4
)
# Pairs with cluster_arrive_relaxed() above: every peer's
# mbar_reduced is initialized before the st.async below.
cute.arch.cluster_wait()
# quack's process-wide const_expr-if rewrite can leave these unbound
# after the dynamic path above; bind them so the regions join.
amax, exponent, inv = Float32(0), Uint32(0), Float32(0)
if tid < tile_n:
base = cute.make_tensor(taddr, cute.make_layout(1))[0]
_tcgen05.fence_after_thread_sync()
acc = cute.make_rmem_tensor(acc_cols, Float32)
if cutlass.const_expr(tokens == 1):
acc[0] = _tcgen05.ld(warp * 32, base, "32x32b", 1)
else:
acc.store(_tcgen05.ld(warp * 32, base, "32x32b", acc_cols))
_tcgen05.wait_ld()
for token in cutlass.range_constexpr(tokens):
ptr = cute.domain_offset(
(tid, token // heads_per_group, split), partial
).iterator
cute.arch.store_async_dsmem(
ptr,
recast_val(acc[token], Int32),
mbar_reduced,
token % heads_per_group,
)
if split < tokens:
# One warp waits for the peers' bytes; named barrier 1 (0 is
# sync_threads) releases the other tile_n epilogue threads.
if warp == 0:
cute.arch.mbarrier_wait(mbar_reduced, 0)
cute.arch.barrier(barrier_id=1, number_of_threads=tile_n)
for i in cutlass.range_constexpr(
cute.ceil_div(tokens, heads_per_group)
):
token = split + i * heads_per_group
if cutlass.const_expr(
full_tiles
and (
tokens <= heads_per_group
or tokens % heads_per_group == 0
)
) or (token < tokens and token_start + token < total_tokens):
value = Float32(0)
for peer in cutlass.range_constexpr(heads_per_group):
value += partial[tid, i, peer]
value = Float32(BFloat16(value))
amax = cute.arch.warp_redux_sync(value, "max", abs=True)
exponent, inv = _scale(amax)
q[token_start + token, tile * tile_n + tid] = Float8E4M3FN(
value * inv
)
if lane == 0:
row = token_start + token
offset = row % 32 * 16 + row // 32 * 4 + warp
qs[tile * 512 + offset] = Uint8(exponent)
# Every scale tile owns its padding, with no second memset kernel.
for i in cutlass.range_constexpr(4):
offset = i * tile_n + tid
row = offset // 16 + (offset % 16 // 4) * 32
if token_tile == 0 and split == 0 and row >= total_tokens:
qs[tile * 512 + offset] = Uint8(0)
# Each receiver drained all writes into its own inbox. Only local
# TMEM readers must finish before deallocation; no peer reads SMEM.
if tid < tile_n:
cute.arch.barrier(barrier_id=2, number_of_threads=tile_n)
if warp == 0:
cute.arch.dealloc_tmem(
cute.make_ptr(
Float32,
cute.make_tensor(taddr, cute.make_layout(1))[0],
cute.AddressSpace.tmem,
),
tmem_cols,
)
@cute.jit
def host_entrypoint(
x: cute.Tensor,
positions: cute.Tensor,
rope: cute.Tensor,
w: cute.Tensor,
ws: cute.Tensor,
q: cute.Tensor,
qs: cute.Tensor,
num_tokens: Int32,
stream: CUstream,
):
layout = cute.make_composed_layout(
cute.make_swizzle(3, 4, 3),
0,
cute.make_layout(
(tile_n, tile_k, num_stages), stride=(tile_k, 1, w_stage_bytes)
),
)
tma = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileG2SOp(cta_group=tcgen05.CtaGroup.ONE),
w,
layout,
(tile_n, tile_k),
)
ws_tma = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileG2SOp(cta_group=tcgen05.CtaGroup.ONE),
cute.make_tensor(ws.iterator, cute.select(ws.layout, mode=[1, 2, 0])),
cute.make_layout((tile_n, num_stages)),
(tile_n, num_stages),
)
device_kernel(x, positions, rope, tma, ws_tma, q, qs, num_tokens).launch(
grid=(n_tiles * heads_per_group, token_tiles, 1),
block=(threads, 1, 1),
cluster=(heads_per_group, 1, 1),
stream=stream,
use_pdl=True,
)
return host_entrypoint
def dispatch( # type: ignore[override]
self, *, tokens: int, n_groups: int, heads_per_group: int, o_lora_rank: int
) -> CompileKey:
token_tiles = (tokens + 31) // 32
# Host integer arithmetic: balance tiles in multiples of four tokens.
tile_tokens = (
tokens
if token_tiles == 1
else (tokens + 4 * token_tiles - 1) // (4 * token_tiles) * 4
)
return self.CompileKey(
tokens_per_tile=tile_tokens,
token_tiles=token_tiles,
full_tiles=tokens % tile_tokens == 0,
n_groups=n_groups,
heads_per_group=heads_per_group,
o_lora_rank=o_lora_rank,
)
def get_warmup_keys(
self, *, max_tokens: int, n_groups: int, heads_per_group: int, o_lora_rank: int
) -> list[CompileKey]:
# Trace all accepted token counts and deduplicate shared tile shapes.
return self._trace_dispatch(self.dispatch)(
tokens=WarmupIntRange(1, max_tokens + 1),
n_groups=n_groups,
heads_per_group=heads_per_group,
o_lora_rank=o_lora_rank,
)
def warmup_inputs(self, compile_key: CompileKey) -> tuple[Any, ...]:
tokens = (
compile_key.tokens_per_tile * compile_key.token_tiles
if compile_key.full_tiles
else cute.sym_int()
)
groups = compile_key.n_groups
rank = compile_key.o_lora_rank
n = groups * rank
k = compile_key.heads_per_group * _HEAD_DIM
return (
make_fake_tensor(
BFloat16,
(tokens, groups * compile_key.heads_per_group, _HEAD_DIM),
(cute.sym_int(divisibility=8), _HEAD_DIM, 1),
assumed_align=16,
),
make_fake_tensor(Int64, (tokens,), (1,)),
make_fake_tensor(Float32, (cute.sym_int(), _ROPE_DIM), (_ROPE_DIM, 1)),
make_fake_tensor(Float8E4M3FN, (n, k), (k, 1), assumed_align=16),
make_fake_tensor(
Int32,
(groups, rank, k // 128),
(rank * k // 128, 1, rank),
assumed_align=16,
),
make_fake_tensor(Float8E4M3FN, (tokens, n), (n, 1)),
make_fake_tensor(Uint8, (128 * n // 32,), (1,)),
Int32(0),
)
@kernel_launcher
def __call__(
self,
*,
x: torch.Tensor,
positions: torch.Tensor,
rope: torch.Tensor,
weight: torch.Tensor,
weight_scale: torch.Tensor,
) -> CuTeDSLLaunchSpec["FusedWoAKernel.CompileKey"]:
"""Return FP8 WO-A output and FlashInfer F8_128x4 scale bytes."""
tokens = x.shape[0]
groups, rank = weight_scale.shape[:2]
n = groups * rank
q = torch.empty((tokens, n), device=x.device, dtype=torch.float8_e4m3fn)
scales = torch.empty(128 * n // 32, device=x.device, dtype=torch.uint8)
launch_args = (
x,
positions,
rope,
weight.view(n, -1),
weight_scale,
q,
scales,
tokens,
)
compile_key = self.dispatch(
tokens=tokens,
n_groups=groups,
heads_per_group=x.shape[1] // groups,
o_lora_rank=rank,
)
return compile_key, launch_args, (q, scales)
_FUSED_WO_A_KERNEL = FusedWoAKernel()
+73 -18
View File
@@ -9,10 +9,15 @@ import torch
from vllm.config import VllmConfig
from vllm.distributed import get_tp_group
from vllm.logger import init_logger
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_fused_post_pre_delayed_tilelang,
mhc_post_tilelang,
)
from vllm.model_executor.layers.fused_moe.moe_output import (
MoEOutput,
UnfinalizedMoEOutput,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import is_deep_gemm_supported
@@ -24,9 +29,17 @@ from .mega_mhc import (
if TYPE_CHECKING:
from vllm.distributed.device_communicators.cuda_communicator import CudaCommunicator
from .cute_dsl import AllReduceMHC
logger = init_logger(__name__)
# GB200 TP4/FlashInfer improves through 16 tokens; larger screens tie or regress.
MHC_OVERLAP_MAX_TOKENS = 16
# The fused all-reduce + mHC kernel of the overlap path, built once by
# init_mhc_all_reduce.
_all_reduce_mhc: "AllReduceMHC | None" = None
def supports_mhc_overlap(vllm_config: VllmConfig) -> bool:
"""Check kernel requirements and safety of sharing the coefficient stream."""
@@ -53,10 +66,35 @@ def supports_mhc_all_reduce(vllm_config: VllmConfig) -> bool:
or config.hc_mult != 4
):
return False
# The custom all-reduce's MNNVL buffers succeed exactly when NVLink
# multicast does, which the fused kernel's own mailbox needs too.
comm = cast("CudaCommunicator", get_tp_group().device_communicator).ca_comm
return comm is not None and bool(comm.mnnvl_lamport_ag_multicast_ptr)
def init_mhc_all_reduce(vllm_config: VllmConfig) -> None:
"""Build the fused all-reduce + mHC kernel the overlap path reduces with.
Collective over the TP group, so every rank must call it, and only when
``supports_mhc_all_reduce`` holds.
"""
global _all_reduce_mhc
from .cute_dsl import AllReduceMHC
config = vllm_config.model_config.hf_config
_all_reduce_mhc = AllReduceMHC(
hidden_size=config.hidden_size,
hc_mult=config.hc_mult,
max_num_tokens=MHC_OVERLAP_MAX_TOKENS,
top_k=config.num_experts_per_tok,
device=current_platform.current_device(),
)
logger.info_once(
"DSV4.1 mHC: CuTe DSL Lamport all-reduce fused with mHC for up to %d tokens.",
MHC_OVERLAP_MAX_TOKENS,
)
def mhc_pre_delayed_overlap(
residual: torch.Tensor,
fn: torch.Tensor,
@@ -151,7 +189,7 @@ def mhc_pre_delayed_overlap(
def mhc_shifted_post_pre(
x: torch.Tensor,
x: torch.Tensor | MoEOutput,
residual: torch.Tensor,
post_layer_mix: torch.Tensor,
comb_res_mix: torch.Tensor,
@@ -175,39 +213,55 @@ def mhc_shifted_post_pre(
]:
"""Dispatch shifted post/pre to overlap, Mega-mHC, or fused TileLang.
A MoE output left unfinalized is finalized inside the fused all-reduce.
When stream is supplied, join it before consuming the returned coefficients.
"""
layer_input = None
if reduce_results:
tp = get_tp_group()
if isinstance(x, MoEOutput):
assert _all_reduce_mhc is not None, "init_mhc_all_reduce was not called"
assert pre_mix is not None and norm_weight is not None
routed = x.routed
assert isinstance(routed, UnfinalizedMoEOutput)
assert x.shared_output is not None
residual, layer_input = _all_reduce_mhc.finalize(
routed.gemm2_permuted,
routed.expert_weights,
routed.expanded_idx_to_permuted_idx,
x.shared_output,
residual,
post_layer_mix,
comb_res_mix,
pre_mix,
norm_weight,
norm_eps,
)
if stream is None:
# Outside FULL graphs, compute the next mixes inline.
stream = torch.cuda.current_stream()
elif reduce_results:
if stream is not None and 0 < x.shape[0] <= MHC_OVERLAP_MAX_TOKENS:
comm = cast("CudaCommunicator", tp.device_communicator).ca_comm
assert comm is not None and comm.mnnvl_lamport_epochs is not None
output = torch.empty_like(residual)
layer_input = torch.empty_like(x)
torch.ops._C_custom_ar.all_reduce_mhc(
assert _all_reduce_mhc is not None, "init_mhc_all_reduce was not called"
assert pre_mix is not None and norm_weight is not None
residual, layer_input = _all_reduce_mhc(
x,
residual,
post_layer_mix,
comb_res_mix,
pre_mix,
norm_weight,
output,
layer_input,
comm.mnnvl_lamport_ag_local_ptr,
comm.mnnvl_lamport_ag_multicast_ptr,
comm.mnnvl_lamport_epochs[0],
comm.rank,
comm.mnnvl_buffer_size,
norm_eps,
)
residual = output
else:
x = tp.all_reduce(x)
x = get_tp_group().all_reduce(x)
if stream is not None:
if layer_input is None:
assert isinstance(x, torch.Tensor)
residual = mhc_post_tilelang(x, residual, post_layer_mix, comb_res_mix)
aux = residual.mean(dim=1) if capture_aux else x.new_empty(0, x.shape[1])
aux = (
residual.mean(dim=1)
if capture_aux
else residual.new_empty(0, residual.shape[-1])
)
pre_outputs = mhc_pre_delayed_overlap(
residual,
fn,
@@ -226,6 +280,7 @@ def mhc_shifted_post_pre(
)
return residual, *pre_outputs, aux
assert isinstance(x, torch.Tensor)
if can_use_mega_mhc(x, residual, pre_mix, norm_weight, capture_aux):
assert pre_mix is not None and norm_weight is not None
outputs = mhc_shifted_post_pre_deep_gemm(
@@ -0,0 +1,95 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DSV4.1 output projection with a small-batch SM100/SM103 fusion."""
import torch
from torch import nn
from vllm.model_executor.kernels.linear.mxfp8.flashinfer import (
FlashInferCutedslMxfp8LinearKernel,
)
from vllm.model_executor.layers.fusion.quant_activation import (
QuantizedActivation,
get_input_quant_key,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
from vllm.models.deepseek_v4.nvidia.ops.o_proj import deep_gemm_fp8_o_proj
from vllm.platforms import current_platform
def _fused_wo_a_max_tokens(layer: nn.Module) -> int:
max_tokens = getattr(layer, "_fused_wo_a_token_limit", None)
if max_tokens is None:
# Additional token tiles only pay off for smaller grids.
ctas_per_tile = layer.n_local_heads * (layer.o_lora_rank // 128)
max_tokens = 96 if ctas_per_tile <= 128 else 32
layer._fused_wo_a_token_limit = max_tokens
return max_tokens
def _can_fuse_wo_a(layer: nn.Module) -> bool:
"""Whether the attention layer matches the fused WO-A kernel's layout."""
method = getattr(layer.wo_b, "scheme", layer.wo_b.quant_method)
return (
current_platform.is_device_capability_family(100)
# WO-A is FP8 with per-32 scales, and WO-B takes MXFP8 input directly.
and layer._einsum_recipe == (1, 1, 32)
and get_input_quant_key(layer.wo_b) == kMxfp8Dynamic
and isinstance(
getattr(method, "kernel", None), FlashInferCutedslMxfp8LinearKernel
)
# A group's heads form one portable (<= 8 CTA) cluster.
and layer.n_local_heads // layer.n_local_groups <= 8
and (layer.nope_head_dim, layer.rope_head_dim) == (448, 64)
and layer.o_lora_rank % 128 == 0
)
def register_dsv41_o_proj_warmup(layer: nn.Module) -> None:
"""Warm the fused WO-A token counts ``dsv41_o_proj`` can dispatch."""
# Draft models load outside the warmup registry; their layers share the
# target's attention shapes, so the target's registration covers them too.
if _can_fuse_wo_a(layer):
from .fused_wo_a import _FUSED_WO_A_KERNEL
_FUSED_WO_A_KERNEL.register_warmup(
max_tokens=_fused_wo_a_max_tokens(layer),
n_groups=layer.n_local_groups,
heads_per_group=layer.n_local_heads // layer.n_local_groups,
o_lora_rank=layer.o_lora_rank,
)
def dsv41_o_proj(
layer: nn.Module, attn_out: torch.Tensor, positions: torch.Tensor
) -> torch.Tensor:
"""``deep_gemm_fp8_o_proj`` with WO-A fused for small SM100/SM103 batches."""
o = attn_out[:, : layer.n_local_heads, :]
cos_sin_cache = layer.rotary_emb.cos_sin_cache
if 1 <= o.shape[0] <= _fused_wo_a_max_tokens(layer) and _can_fuse_wo_a(layer):
from .fused_wo_a import _FUSED_WO_A_KERNEL
q, scales = _FUSED_WO_A_KERNEL(
x=o,
positions=positions,
rope=cos_sin_cache,
weight=layer.wo_a.weight,
weight_scale=layer.wo_a.weight_scale,
)
return layer._wo_b_proj(
QuantizedActivation(q, scales, o.dtype, q.shape, kMxfp8Dynamic)
)
return deep_gemm_fp8_o_proj(
o,
positions,
cos_sin_cache,
layer.wo_a,
layer._wo_b_proj,
n_groups=layer.n_local_groups,
heads_per_group=layer.n_local_heads // layer.n_local_groups,
nope_dim=layer.nope_head_dim,
rope_dim=layer.rope_head_dim,
o_lora_rank=layer.o_lora_rank,
einsum_recipe=layer._einsum_recipe,
tma_aligned_scales=layer._tma_aligned_scales,
)
+9 -7
View File
@@ -139,15 +139,17 @@ class DeepseekV4FP8Config(Fp8Config):
def override_quantization_method(
cls, hf_quant_cfg, user_quant, hf_config=None
) -> QuantizationMethods | None:
# Quark checkpoints are always handled by QuarkConfig, which knows
# how to dispatch each per-layer scheme (MXFP4, MXFP8, etc.).
# ``from_config`` below rewrites the config into a single global FP8
# scheme, which would discard per-layer specs — so never claim Quark.
if isinstance(hf_quant_cfg, dict) and (
hf_quant_cfg.get("quant_method") == "quark"
):
return None
if not (
isinstance(hf_quant_cfg, dict)
and (
hf_quant_cfg.get("quant_method") in ("fp8", "deepseek_v4_fp8")
or (
hf_quant_cfg.get("quant_method") == "quark"
and cls._is_quark_mxfp4_ocp(hf_quant_cfg)
)
)
and hf_quant_cfg.get("quant_method") in ("fp8", "deepseek_v4_fp8")
):
return None
model_type = getattr(hf_config, "model_type", None)
+2 -2
View File
@@ -86,7 +86,7 @@ class DeepseekV4SparseMLABackend(AttentionBackend):
]
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [64 if current_platform.is_device_capability_family(90) else 128]
@staticmethod
@@ -255,7 +255,7 @@ class FlashMLAMegaAttnBackend(DeepseekV4FlashMLABackend):
return "FLASHMLA_MEGA_ATTN_DSV41"
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [128]
@classmethod
+2 -1
View File
@@ -353,9 +353,10 @@ class Dots3NoteMLAMetadataBuilder(TritonMLAMetadataBuilder):
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
max_query_len: int,
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> Dots3NoteDecodeMetadata:
del max_seq_len, query_start_loc_device, num_decode_tokens
del max_seq_len, query_start_loc_device, num_decode_tokens, max_query_len
query_len = int(query_start_loc_cpu[1] - query_start_loc_cpu[0])
return Dots3NoteDecodeMetadata(
block_table=block_table_tensor,
+2 -2
View File
@@ -9,7 +9,7 @@ import torch
import torch.nn.functional as F
from torch import nn
from torch.nn import LayerNorm
from transformers.configuration_utils import PretrainedConfig
from transformers.configuration_utils import PreTrainedConfig
from transformers.modeling_utils import PreTrainedModel
from vllm.third_party.deep_gemm import per_block_cast_to_fp8
@@ -27,7 +27,7 @@ from .vision_attention import (
from .vision_moe import note_vision_fused_moe_fp8
class DotsMoEVitConfig(PretrainedConfig):
class DotsMoEVitConfig(PreTrainedConfig):
model_type: str = "dots_moe_vit"
def __init__(
+18 -16
View File
@@ -327,37 +327,38 @@ def _kpool_tail_seed_kernel(
KPOOL_HEAD: tl.constexpr,
HEAD_DIM: tl.constexpr,
KPOOL: tl.constexpr,
RING: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Copy token ``i``'s raw K + gate into its request's tail block.
"""Copy token ``i``'s raw K + gate into its request's tail ring.
Token ``i`` is among its request's last KPOOL tokens iff the token KPOOL
ahead belongs to a different tail block (or is past the batch / padding,
slot < 0). ``tslot = block * KPOOL + pos % KPOOL``; the destination is
``tail[block, {0:K, 1:score}, pos % KPOOL, :]``.
slot < 0). ``tslot = block * RING + pos % RING``; the destination is
``tail[block, {0:K, 1:score}, pos % RING, :]``.
"""
i = tl.program_id(0)
t = tl.load(tslot_ptr + i).to(tl.int64)
if t < 0:
return
blk = t // KPOOL # t >= 0 here, so trunc == floor
blk = t // RING # t >= 0 here, so trunc == floor
ahead = tl.load(tslot_ptr + i + KPOOL, mask=i + KPOOL < n_tokens, other=-1).to(
tl.int64
)
# Match the torch semantics exactly: a negative ahead slot floors to a
# block id that differs from every real block -> token is in the tail.
# Only divide non-negative slots (Triton int div truncates, torch floors).
if ahead >= 0 and ahead // KPOOL == blk:
if ahead >= 0 and ahead // RING == blk:
return
offs = tl.arange(0, BLOCK_D)
m = offs < HEAD_DIM
block_base = blk * TAIL_BLOCK_ELEMS
base = block_base + (t % KPOOL) * HEAD_DIM
base = block_base + (t % RING) * HEAD_DIM
k = tl.load(key_ptr + i * HEAD_DIM + offs, mask=m)
s = tl.load(score_ptr + i * HEAD_DIM + offs, mask=m)
tl.store(tail_ptr + base + offs, k, mask=m)
tl.store(
tail_ptr + block_base + KPOOL_HEAD + (t % KPOOL) * HEAD_DIM + offs, s, mask=m
tail_ptr + block_base + KPOOL_HEAD + (t % RING) * HEAD_DIM + offs, s, mask=m
)
@@ -385,6 +386,7 @@ def kpool_seed_tail_cache(
KPOOL_HEAD=tail_kv_cache.stride(1),
HEAD_DIM=head_dim,
KPOOL=kpool,
RING=tail_kv_cache.shape[2],
BLOCK_D=triton.next_power_of_2(head_dim),
)
@@ -412,6 +414,7 @@ def _kpool_decode_update_batched_kernel(
PAGE_SIZE: tl.constexpr,
BUF_NUMEL_PER_PAGE: tl.constexpr,
POOL_SIZE: tl.constexpr,
RING: tl.constexpr,
TAIL_BLOCK_ELEMS: tl.constexpr,
KPOOL_HEAD: tl.constexpr,
HEAD_DIM: tl.constexpr,
@@ -428,10 +431,7 @@ def _kpool_decode_update_batched_kernel(
the tail-ring slots that tokens t < t* (same request) just stashed in this
same invocation. ``tl.range`` iterates sequentially within the program, so
those stashes are visible to the later completion read. Cross-request
programs are independent (distinct tail blocks). With NEXT_N < POOL_SIZE
(the spec-verify case: NEXT_N ~= num_spec+1, POOL_SIZE=16) at most one
completion can occur per request per call, but the ordered loop is correct
for any NEXT_N.
programs are independent (distinct tail blocks). RING >= POOL_SIZE.
"""
req = tl.program_id(0)
offs = tl.arange(0, BLOCK_D)
@@ -445,7 +445,7 @@ def _kpool_decode_update_batched_kernel(
pos_valid = (cache_loc >= 0) & (pos >= 0)
slot = safe_pos % POOL_SIZE
phys_slot = safe_pos % POOL_SIZE
phys_slot = safe_pos % RING
# Derive the tail block from THIS token's tail_slot (the request's block
# is constant across a pool, but a padded / invalid entry carries a
@@ -453,7 +453,7 @@ def _kpool_decode_update_batched_kernel(
# token's base address). Clamp so an invalid entry can never form an
# out-of-bounds base; the accesses below are gated on pos_valid anyway.
tail_slot = tl.load(tail_slot_mapping_ptr + idx)
block = tl.maximum(tail_slot, 0).to(tl.int64) // POOL_SIZE
block = tl.maximum(tail_slot, 0).to(tl.int64) // RING
block_base = block * TAIL_BLOCK_ELEMS
# The tail-ring stash must run for EVERY real token, so it is gated on
@@ -481,7 +481,7 @@ def _kpool_decode_update_batched_kernel(
max_score = tl.full((BLOCK_D,), -float("inf"), tl.float32)
for pool_slot in tl.static_range(0, POOL_SIZE):
is_current = pool_slot == slot
phys = (pool_logical_start + pool_slot) % POOL_SIZE
phys = (pool_logical_start + pool_slot) % RING
score_buf = tl.load(
tail_kv_ptr + block_base + KPOOL_HEAD + phys * HEAD_DIM + offs,
mask=dim_mask,
@@ -499,7 +499,7 @@ def _kpool_decode_update_batched_kernel(
denom = tl.full((BLOCK_D,), 0.0, tl.float32)
for pool_slot in tl.static_range(0, POOL_SIZE):
is_current = pool_slot == slot
phys = (pool_logical_start + pool_slot) % POOL_SIZE
phys = (pool_logical_start + pool_slot) % RING
score_buf = tl.load(
tail_kv_ptr + block_base + KPOOL_HEAD + phys * HEAD_DIM + offs,
mask=dim_mask,
@@ -609,7 +609,8 @@ def kpool_decode_update_and_maybe_write_cache_batched(
return
assert tail_kv_cache.ndim == 4
assert tail_kv_cache.shape[1] == 2
assert tail_kv_cache.shape[2] == pool_size
ring = tail_kv_cache.shape[2]
assert ring >= pool_size and ring % pool_size == 0, (ring, pool_size)
assert tail_kv_cache.shape[3] == head_dim
assert tail_kv_cache.dtype == torch.bfloat16
assert key.ndim == 3 and key.shape[2] == head_dim
@@ -658,6 +659,7 @@ def kpool_decode_update_and_maybe_write_cache_batched(
PAGE_SIZE=page_size,
BUF_NUMEL_PER_PAGE=buf.stride(0),
POOL_SIZE=pool_size,
RING=ring,
TAIL_BLOCK_ELEMS=tail_kv_cache.stride(0),
KPOOL_HEAD=tail_kv_cache.stride(1),
HEAD_DIM=head_dim,
+15 -3
View File
@@ -34,6 +34,7 @@ from vllm.models.glm5next.sparse_indexer import SparseAttnIndexerKpool
from vllm.platforms import current_platform
from vllm.transformers_utils.configs.glm5_next import Glm5NextConfig
from vllm.utils.deep_gemm import PAGED_MQA_PAGE_SIZES
from vllm.utils.math_utils import cdiv, next_power_of_2
from vllm.v1.kv_cache_interface import KpoolTailSpec, MLAAttentionSpec
logger = init_logger(__name__)
@@ -160,7 +161,7 @@ class Glm5NextTailCache(DeepseekV32IndexerCache):
"""Paged circular buffer for the kpool indexer's in-progress (tail) pool.
Holds the trailing incomplete pool's raw K + gate score: one block of
``index_kpool`` slots per request, overwritten in place by ``pos % kpool``
``ring`` slots per request, overwritten in place by ``pos % ring``
as decode/spec-decode advances. Prefill seeds it (instead of discarding the
tail raw K+gate); the connector transfers it across PD; decode reads it to
compress the boundary pool correctly. ``KpoolTailSpec`` /
@@ -190,13 +191,24 @@ class Glm5NextTailCache(DeepseekV32IndexerCache):
def get_kv_cache_spec(self, vllm_config: VllmConfig):
# The two head slots form [K, gate score] in the generic
# [block, head, state, content] cache view.
# Drafts are stashed before acceptance. With a one-pool ring, the
# drafts behind a rejected pool-completing draft overwrite the keys
# read by its redo.
span = self._index_kpool + vllm_config.num_speculative_tokens
ring = self._index_kpool * next_power_of_2(cdiv(span, self._index_kpool))
# ring must divide the attention block size (a multiple of 128).
assert self.cache_config.block_size % ring == 0, (
f"Glm5NextTailCache: cache_config.block_size "
f"({self.cache_config.block_size}) must be a multiple of the "
f"tail ring ({ring})"
)
return KpoolTailSpec(
block_size=self._index_kpool,
block_size=ring,
num_kv_heads=2,
head_size=self.head_dim,
head_size_v=0,
dtype=torch.bfloat16,
sliding_window=self._index_kpool,
sliding_window=ring,
)
def get_attn_backend(self):
+3 -2
View File
@@ -42,7 +42,6 @@ class Glm5NextMultiTokenPredictorLayer(nn.Module):
assert vllm_config.speculative_config is not None
config = vllm_config.speculative_config.draft_model_config.hf_config
self.config = config
quant_config = vllm_config.quant_config
self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -66,7 +65,9 @@ class Glm5NextMultiTokenPredictorLayer(nn.Module):
device=current_platform.device_type,
)
self.shared_head = SharedHead(
config=config, prefix=prefix, quant_config=quant_config
config=config,
prefix=prefix,
defer_lm_head=True,
)
# MTP layers sit past the base model's hidden layers; parse the index
# from the prefix (e.g. "...layers.32") so the decoder builds an MLA
@@ -387,14 +387,15 @@ def _kpool_tail_seed_kernel(
KPOOL_HEAD: tl.constexpr,
HEAD_DIM: tl.constexpr,
KPOOL: tl.constexpr,
RING: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Copy token ``i``'s raw K + gate into its request's tail block.
"""Copy token ``i``'s raw K + gate into its request's tail ring.
Token ``i`` is among its request's last KPOOL tokens iff the token KPOOL
ahead belongs to a different tail block (or is past the batch / padding,
slot < 0). ``tslot = block * KPOOL + pos % KPOOL``; the destination is
``tail[block, {0:K, 1:score}, pos % KPOOL, :]``.
slot < 0). ``tslot = block * RING + pos % RING``; the destination is
``tail[block, {0:K, 1:score}, pos % RING, :]``.
The tail cache aliases the indexer cache with the indexer's (padded) block
stride, so blocks are addressed through ``TAIL_BLOCK_ELEMS`` /
@@ -405,18 +406,18 @@ def _kpool_tail_seed_kernel(
t = tl.load(tslot_ptr + i).to(tl.int64)
if t < 0:
return
blk = t // KPOOL # t >= 0 here, so trunc == floor
blk = t // RING # t >= 0 here, so trunc == floor
ahead = tl.load(tslot_ptr + i + KPOOL, mask=i + KPOOL < n_tokens, other=-1).to(
tl.int64
)
# Match the torch semantics exactly: a negative ahead slot floors to a
# block id that differs from every real block -> token is in the tail.
# Only divide non-negative slots (Triton int div truncates, torch floors).
if ahead >= 0 and ahead // KPOOL == blk:
if ahead >= 0 and ahead // RING == blk:
return
offs = tl.arange(0, BLOCK_D)
m = offs < HEAD_DIM
base = blk * TAIL_BLOCK_ELEMS + (t % KPOOL) * HEAD_DIM
base = blk * TAIL_BLOCK_ELEMS + (t % RING) * HEAD_DIM
k = tl.load(key_ptr + i * HEAD_DIM + offs, mask=m)
s = tl.load(score_ptr + i * HEAD_DIM + offs, mask=m)
tl.store(tail_ptr + base + offs, k, mask=m)
@@ -449,6 +450,7 @@ def kpool_seed_tail_cache(
KPOOL_HEAD=tail_kv_cache.stride(1),
HEAD_DIM=head_dim,
KPOOL=kpool,
RING=tail_kv_cache.shape[2],
BLOCK_D=triton.next_power_of_2(head_dim),
)
@@ -476,6 +478,7 @@ def _kpool_decode_update_batched_kernel(
PAGE_SIZE: tl.constexpr,
BUF_NUMEL_PER_PAGE: tl.constexpr,
POOL_SIZE: tl.constexpr,
RING: tl.constexpr,
TAIL_BLOCK_ELEMS: tl.constexpr,
KPOOL_HEAD: tl.constexpr,
HEAD_DIM: tl.constexpr,
@@ -490,10 +493,7 @@ def _kpool_decode_update_batched_kernel(
the tail-ring slots that tokens t < t* (same request) just stashed in this
same invocation. ``tl.range`` iterates sequentially within the program, so
those stashes are visible to the later completion read. Cross-request
programs are independent (distinct tail blocks). With NEXT_N < POOL_SIZE
(the spec-verify case: NEXT_N ~= num_spec+1, POOL_SIZE=16) at most one
completion can occur per request per call, but the ordered loop is correct
for any NEXT_N.
programs are independent (distinct tail blocks). RING >= POOL_SIZE.
"""
req = tl.program_id(0)
offs = tl.arange(0, BLOCK_D)
@@ -507,7 +507,7 @@ def _kpool_decode_update_batched_kernel(
pos_valid = (cache_loc >= 0) & (pos >= 0)
slot = safe_pos % POOL_SIZE
phys_slot = safe_pos % POOL_SIZE
phys_slot = safe_pos % RING
# Derive the tail block from THIS token's tail_slot (the request's block
# is constant across a pool, but a padded / invalid entry carries a
@@ -515,7 +515,7 @@ def _kpool_decode_update_batched_kernel(
# token's base address). Clamp so an invalid entry can never form an
# out-of-bounds base; the accesses below are gated on pos_valid anyway.
tail_slot = tl.load(tail_slot_mapping_ptr + idx)
block = tl.maximum(tail_slot, 0).to(tl.int64) // POOL_SIZE
block = tl.maximum(tail_slot, 0).to(tl.int64) // RING
block_base = block * TAIL_BLOCK_ELEMS
# The tail-ring stash must run for EVERY real token, so it is gated on
@@ -543,7 +543,7 @@ def _kpool_decode_update_batched_kernel(
max_score = tl.full((BLOCK_D,), -float("inf"), tl.float32)
for pool_slot in tl.static_range(0, POOL_SIZE):
is_current = pool_slot == slot
phys = (pool_logical_start + pool_slot) % POOL_SIZE
phys = (pool_logical_start + pool_slot) % RING
score_buf = tl.load(
tail_kv_ptr + block_base + KPOOL_HEAD + phys * HEAD_DIM + offs,
mask=dim_mask,
@@ -561,7 +561,7 @@ def _kpool_decode_update_batched_kernel(
denom = tl.full((BLOCK_D,), 0.0, tl.float32)
for pool_slot in tl.static_range(0, POOL_SIZE):
is_current = pool_slot == slot
phys = (pool_logical_start + pool_slot) % POOL_SIZE
phys = (pool_logical_start + pool_slot) % RING
score_buf = tl.load(
tail_kv_ptr + block_base + KPOOL_HEAD + phys * HEAD_DIM + offs,
mask=dim_mask,
@@ -671,7 +671,8 @@ def kpool_decode_update_and_maybe_write_cache_batched(
return
assert tail_kv_cache.ndim == 4
assert tail_kv_cache.shape[1] == 2
assert tail_kv_cache.shape[2] == pool_size
ring = tail_kv_cache.shape[2]
assert ring >= pool_size and ring % pool_size == 0, (ring, pool_size)
assert tail_kv_cache.shape[3] == head_dim
assert tail_kv_cache.dtype == torch.bfloat16
assert key.ndim == 3 and key.shape[2] == head_dim
@@ -717,6 +718,7 @@ def kpool_decode_update_and_maybe_write_cache_batched(
PAGE_SIZE=page_size,
BUF_NUMEL_PER_PAGE=buf.stride(0),
POOL_SIZE=pool_size,
RING=ring,
TAIL_BLOCK_ELEMS=tail_kv_cache.stride(0),
KPOOL_HEAD=tail_kv_cache.stride(1),
HEAD_DIM=head_dim,
@@ -558,6 +558,7 @@ def sparse_attn_indexer_kpool(
decode_metadata.schedule_metadata,
max_model_len=max_pool_len,
clean_logits=False,
indices=decode_metadata.indices,
)
num_rows = logits.shape[0]
# kpool: logits are pool-granular -> select topk_tokens//kpool pools,
+3 -3
View File
@@ -30,7 +30,7 @@ from itertools import islice
import regex as re
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
@@ -75,7 +75,7 @@ from ..nvidia.moe import HYV4FeedForward, HYV4MoEFused
logger = init_logger(__name__)
def _normalize_hyv4_config(config: PretrainedConfig) -> PretrainedConfig:
def _normalize_hyv4_config(config: PreTrainedConfig) -> PreTrainedConfig:
"""Populate the aliases consumed by the shared MoE implementation."""
config.router_scaling_factor = config.routed_scaling_factor
config.num_experts = config.n_routed_experts
@@ -95,7 +95,7 @@ class HYV4DecoderLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
vllm_config: VllmConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
+3 -3
View File
@@ -18,7 +18,7 @@ from typing import cast
import regex as re
import torch
from torch import nn
from transformers import DeepseekV2Config, DeepseekV3Config, PretrainedConfig
from transformers import DeepseekV2Config, DeepseekV3Config, PreTrainedConfig
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config
@@ -51,7 +51,7 @@ _SPARSE_LAYER_TYPES = ("sparse_attention", "sparse", "deepseek_sparse_attention"
_WEIGHT_LAYER_INDEX_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?:\.|$)")
def compute_skip_topk_layers(config: PretrainedConfig) -> set[int]:
def compute_skip_topk_layers(config: PreTrainedConfig) -> set[int]:
"""Return the backbone layers that reuse a previous layer's top-k indices.
A "shared" indexer layer performs sparse attention with the indices computed
@@ -280,7 +280,7 @@ class HYV4MLAAttention(nn.Module):
def __init__(
self,
vllm_config: VllmConfig,
config: PretrainedConfig,
config: PreTrainedConfig,
hidden_size: int,
num_heads: int,
qk_nope_head_dim: int,
+5 -5
View File
@@ -17,7 +17,7 @@ requires restructuring the decoder-layer forward scheduling.
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.model_executor.layers.hpc import HpcIHCHead, HpcIHCPost, HpcIHCPre
from vllm.model_executor.layers.linear import ReplicatedLinear
@@ -40,7 +40,7 @@ class HYV4HCPreLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
hidden_dim: int,
hc_mult: int = 4,
magnitude: float = 2.0,
@@ -163,7 +163,7 @@ class HYV4HCPostLayer(nn.Module):
y[n, i, d] = post[n, i] * x[n, d] + residual[n, i, d]
"""
def __init__(self, config: PretrainedConfig):
def __init__(self, config: PreTrainedConfig):
super().__init__()
self.config = config
@@ -213,7 +213,7 @@ class HYV4HCHeadLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
hidden_size: int,
hc_mult: int = 4,
hc_eps: float = 1e-6,
@@ -301,7 +301,7 @@ class HYV4HCLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_idx: int,
init_std: float = 6e-3,
base_noise_std: float = 0.0,
+3 -3
View File
@@ -30,7 +30,7 @@ from itertools import islice
import regex as re
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import (
@@ -74,7 +74,7 @@ from .moe import HYV4FeedForward, HYV4MoEFused
logger = init_logger(__name__)
def _normalize_hyv4_config(config: PretrainedConfig) -> PretrainedConfig:
def _normalize_hyv4_config(config: PreTrainedConfig) -> PreTrainedConfig:
"""Populate the aliases consumed by the shared MoE implementation."""
config.router_scaling_factor = config.routed_scaling_factor
config.num_experts = config.n_routed_experts
@@ -94,7 +94,7 @@ class HYV4DecoderLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
vllm_config: VllmConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
+2 -2
View File
@@ -4,7 +4,7 @@
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import get_current_vllm_config
from vllm.distributed import get_ep_group, get_tensor_model_parallel_world_size
@@ -87,7 +87,7 @@ class HYV4MoEFused(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
enable_eplb: bool = False,
+5 -5
View File
@@ -8,7 +8,7 @@ from collections.abc import Callable, Iterable
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import CacheConfig, ModelConfig, VllmConfig
from vllm.distributed import (
@@ -59,7 +59,7 @@ _MTP_QUANT_EXCLUSION_ATTRS = ("ignored_layers", "exclude_modules")
def _get_spec_layer_idx_from_weight_name(
config: PretrainedConfig, weight_name: str
config: PreTrainedConfig, weight_name: str
) -> int | None:
"""Return the MTP layer index a checkpoint weight belongs to, or None.
@@ -147,7 +147,7 @@ def _prepare_mtp_fp8_expert_scale(
def _create_mtp_quant_config(
hf_config: PretrainedConfig,
hf_config: PreTrainedConfig,
backbone_quant_config: QuantizationConfig | None = None,
) -> QuantizationConfig | None:
"""Create the quantization config for the MTP layers.
@@ -303,7 +303,7 @@ class HYV4SharedHead(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
quant_config: QuantizationConfig | None = None,
) -> None:
super().__init__()
@@ -329,7 +329,7 @@ class HYV4MultiTokenPredictorLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
prefix: str,
vllm_config: VllmConfig,
model_config: ModelConfig,
+6 -6
View File
@@ -8,10 +8,10 @@ from dataclasses import dataclass, field
from typing import Any, ClassVar, Literal, cast
import torch
from transformers.configuration_utils import PretrainedConfig
from transformers.configuration_utils import PreTrainedConfig
class InklingModelConfig(PretrainedConfig):
class InklingModelConfig(PreTrainedConfig):
model_type = "inkling_model"
keys_to_ignore_at_inference = ["past_key_values"]
@@ -215,7 +215,7 @@ class InklingModelConfig(PretrainedConfig):
return TMLConvCacheParams(shape=shape, layers=self.conv_layer_ids, dtype=dtype)
class InklingAudioConfig(PretrainedConfig):
class InklingAudioConfig(PreTrainedConfig):
model_type = "inkling_audio_model"
def __init__(
@@ -255,7 +255,7 @@ class InklingAudioConfig(PretrainedConfig):
super().__init__(**kwargs)
class InklingVisionConfig(PretrainedConfig):
class InklingVisionConfig(PreTrainedConfig):
model_type = "inkling_vision_model"
def __init__(
@@ -295,10 +295,10 @@ class InklingVisionConfig(PretrainedConfig):
super().__init__(**kwargs)
class InklingMMConfig(PretrainedConfig):
class InklingMMConfig(PreTrainedConfig):
model_type = "inkling_mm_model"
keys_to_ignore_at_inference = ["past_key_values"]
sub_configs: ClassVar[dict[str, type[PretrainedConfig]]] = {
sub_configs: ClassVar[dict[str, type[PreTrainedConfig]]] = {
"text_config": InklingModelConfig,
"audio_config": InklingAudioConfig,
"vision_config": InklingVisionConfig,
+9
View File
@@ -438,6 +438,14 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
for x in mixed_qkv_spec.split(self.local_projection_size, dim=-1)
)
spec_cu_seqlens = spec_query_start_loc[: m.num_spec_decodes + 1]
uniform_sequence_length = m.uniform_spec_sequence_length
# Token padding can make the packed tensor larger than the
# request-local metadata represented by this length.
if (
uniform_sequence_length is not None
and q_spec.shape[1] != m.num_spec_decodes * uniform_sequence_length
):
uniform_sequence_length = None
# Spec-only batches write directly into core_attn_out.
spec_out = (
core_attn_out[:, : q_spec.shape[1]]
@@ -457,6 +465,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
cu_seqlens=spec_cu_seqlens,
ssm_state_indices=spec_state_indices_tensor,
num_accepted_tokens=num_accepted_tokens,
uniform_sequence_length=uniform_sequence_length,
out=spec_out,
)
+4 -3
View File
@@ -16,9 +16,10 @@
# - OOB-mask correctness fix: present (all tl.load use mask=..., other=0).
# Validated on gfx950: no core-dump, gsm8k 94.1%.
#
# AMD-specific deltas vs the NVIDIA copy: NONE yet (byte-identical). Keep in sync
# with the NVIDIA copy on FLA updates; any divergence should be an intentional,
# documented gfx950-specific change (a #869-style AMD-only fix).
# AMD-specific deltas vs the NVIDIA copy:
# - fused recurrent gated speculative-decode launch geometry is tuned for
# gfx950.
# Keep the copies in sync on FLA updates outside documented platform tuning.
from .chunk import (
chunk_kda,
+103 -15
View File
@@ -164,15 +164,24 @@ def fused_recurrent_kda_fwd_kernel(
APPLY_BETA_SIGMOID: tl.constexpr,
HAS_DT_BIAS: tl.constexpr,
USE_LOWER_BOUND: tl.constexpr,
IS_SINGLE_SEQUENCE: tl.constexpr,
SEQUENCE_LENGTH: tl.constexpr,
num_stages: tl.constexpr,
):
pid = tl.program_id(0)
i_v = pid % tl.cdiv(V, BV)
i_nh = pid // tl.cdiv(V, BV)
i_n, i_h = i_nh // H, i_nh % H
bos = tl.load(cu_seqlens + i_n).to(tl.int64)
eos = tl.load(cu_seqlens + i_n + 1).to(tl.int64)
sequence_length = eos - bos
if IS_SINGLE_SEQUENCE:
i_n, i_h = 0, i_nh
else:
i_n, i_h = i_nh // H, i_nh % H
if SEQUENCE_LENGTH:
bos = i_n * SEQUENCE_LENGTH
sequence_length = SEQUENCE_LENGTH
else:
bos = tl.load(cu_seqlens + i_n).to(tl.int64)
eos = tl.load(cu_seqlens + i_n + 1).to(tl.int64)
sequence_length = eos - bos
if sequence_length == 0:
return
@@ -208,6 +217,14 @@ def fused_recurrent_kda_fwd_kernel(
p_v = v + bos * stride_qkv_token + i_h * V + o_v
p_g = g + bos * stride_g_token + i_h * K + o_k
p_beta = beta + bos * stride_beta_token + i_h
if USE_GATE_IN_KERNEL:
b_a = exp(tl.load(A_log + i_h).to(tl.float32))
if HAS_DT_BIAS:
b_bias = tl.load(
dt_bias + i_h * K + o_k,
mask=m_k,
other=0.0,
).to(tl.float32)
for i_t in tl.range(0, sequence_length, num_stages=num_stages):
b_q = tl.load(p_q, mask=m_k, other=0.0, eviction_policy="evict_last").to(
tl.float32
@@ -219,8 +236,8 @@ def fused_recurrent_kda_fwd_kernel(
tl.float32
)
if USE_QK_L2NORM_IN_KERNEL:
b_q = b_q / tl.sqrt(tl.sum(b_q * b_q) + 1e-6)
b_k = b_k / tl.sqrt(tl.sum(b_k * b_k) + 1e-6)
b_q *= tl.rsqrt(tl.sum(b_q * b_q) + 1e-6)
b_k *= tl.rsqrt(tl.sum(b_k * b_k) + 1e-6)
b_q *= scale
b_gate = tl.load(
@@ -231,13 +248,7 @@ def fused_recurrent_kda_fwd_kernel(
).to(tl.float32)
if USE_GATE_IN_KERNEL:
if HAS_DT_BIAS:
b_bias = tl.load(
dt_bias + i_h * K + o_k,
mask=m_k,
other=0.0,
).to(tl.float32)
b_gate += b_bias
b_a = exp(tl.load(A_log + i_h).to(tl.float32))
if USE_LOWER_BOUND:
b_gate = lower_bound * tl.sigmoid(b_a * b_gate)
else:
@@ -288,6 +299,60 @@ def fused_recurrent_kda_fwd_kernel(
p_out += stride_out_token
def _get_static_sequence_length(
total_tokens: int,
head_sequences: int,
is_single_sequence: bool,
uniform_sequence_length: int | None,
) -> int:
if is_single_sequence:
return total_tokens
# MI355X performance gate: 192 head-sequences is 16 sequences at H=12.
# Static loops win through 16; dynamic loops win at 32 for short queries.
if (
uniform_sequence_length is not None
and uniform_sequence_length > 1
and head_sequences <= 192
):
return uniform_sequence_length
return 0
def _select_kda_launch_config(
use_gate_in_kernel: bool,
is_spec_decoding: bool,
head_sequences: int,
static_sequence_length: int,
has_multi_token_sequence: bool,
) -> tuple[int, int, int]:
if static_sequence_length:
BV = 4 if head_sequences <= 24 else 8
if static_sequence_length == 1:
num_stages = 2
elif static_sequence_length <= 3:
num_stages = 8 if head_sequences <= 24 else 4
elif static_sequence_length <= 6:
num_stages = 6
elif static_sequence_length <= 10:
num_stages = 10
else:
num_stages = 12
return BV, 1, num_stages
if use_gate_in_kernel and is_spec_decoding:
if head_sequences <= 24:
return 4, 1, 4 if has_multi_token_sequence else 2
if has_multi_token_sequence and head_sequences <= 48:
return 8, 1, 4
if has_multi_token_sequence:
return 8, 1, 2
return 32, 4, 2
if use_gate_in_kernel:
return 32, 4, 2
return 8, 1, 2
def fused_recurrent_kda_fwd(
q: torch.Tensor,
k: torch.Tensor,
@@ -300,6 +365,7 @@ def fused_recurrent_kda_fwd(
cu_seqlens: torch.Tensor | None = None,
ssm_state_indices: torch.Tensor | None = None,
num_accepted_tokens: torch.Tensor | None = None,
uniform_sequence_length: int | None = None,
use_qk_l2norm_in_kernel: bool = True,
A_log: torch.Tensor | None = None,
dt_bias: torch.Tensor | None = None,
@@ -336,6 +402,10 @@ def fused_recurrent_kda_fwd(
assert num_accepted_tokens is None
else:
assert ssm_state_indices.stride(1) == 1
if uniform_sequence_length is not None:
assert num_accepted_tokens is not None
assert uniform_sequence_length > 0
assert N * uniform_sequence_length == T
assert cu_seqlens.is_contiguous()
if use_gate_in_kernel:
assert A_log is not None and A_log.is_contiguous()
@@ -344,8 +414,22 @@ def fused_recurrent_kda_fwd(
if scale is None:
scale = K**-0.5
BV = 32 if use_gate_in_kernel else 8
num_warps = 4 if use_gate_in_kernel else 1
is_spec_decoding = num_accepted_tokens is not None
is_single_sequence = is_spec_decoding and N == 1
head_sequences = H * N
static_sequence_length = _get_static_sequence_length(
total_tokens=T,
head_sequences=head_sequences,
is_single_sequence=is_single_sequence,
uniform_sequence_length=uniform_sequence_length,
)
BV, num_warps, num_stages = _select_kda_launch_config(
use_gate_in_kernel=use_gate_in_kernel,
is_spec_decoding=is_spec_decoding,
head_sequences=head_sequences,
static_sequence_length=static_sequence_length,
has_multi_token_sequence=T > N,
)
grid = (cdiv(V, BV) * N * H,)
fused_recurrent_kda_fwd_kernel[grid](
q=q,
@@ -379,8 +463,10 @@ def fused_recurrent_kda_fwd(
USE_QK_L2NORM_IN_KERNEL=use_qk_l2norm_in_kernel,
USE_GATE_IN_KERNEL=use_gate_in_kernel,
APPLY_BETA_SIGMOID=use_beta_sigmoid_in_kernel,
IS_SINGLE_SEQUENCE=is_single_sequence,
SEQUENCE_LENGTH=static_sequence_length,
num_warps=num_warps,
num_stages=2,
num_stages=num_stages,
)
return out, initial_state
@@ -398,6 +484,7 @@ def fused_recurrent_kda(
cu_seqlens: torch.Tensor,
ssm_state_indices: torch.Tensor,
num_accepted_tokens: torch.Tensor | None = None,
uniform_sequence_length: int | None = None,
out: torch.Tensor | None = None,
fuse_gate: bool | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
@@ -433,6 +520,7 @@ def fused_recurrent_kda(
cu_seqlens=cu_seqlens,
ssm_state_indices=ssm_state_indices,
num_accepted_tokens=num_accepted_tokens,
uniform_sequence_length=uniform_sequence_length,
use_qk_l2norm_in_kernel=True,
A_log=A_log if fuse_gate else None,
dt_bias=dt_bias if fuse_gate else None,
+29 -1
View File
@@ -15,7 +15,10 @@ from vllm.model_executor.layers.linear import (
ReplicatedLinear,
)
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.models.qwen3_dspark import DSparkMarkovHead
from vllm.model_executor.models.qwen3_dspark import (
DSparkConfidenceHead,
DSparkMarkovHead,
)
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
WeightsMapper,
@@ -188,6 +191,18 @@ class K3DSparkModel(nn.Module):
self.config.markov_rank,
prefix=maybe_prefix(prefix, "markov_head"),
)
self.confidence_head: DSparkConfidenceHead | None = None
if getattr(self.config, "enable_confidence_head", False):
with_markov = getattr(self.config, "confidence_head_with_markov", False)
input_dim = self.config.hidden_size + (
self.config.markov_rank if with_markov else 0
)
self.confidence_head = DSparkConfidenceHead(
input_dim,
prefix=maybe_prefix(prefix, "confidence_head"),
bias=True,
with_markov=with_markov,
)
self._max_num_context_tokens = (
vllm_config.scheduler_config.max_num_batched_tokens
)
@@ -436,6 +451,12 @@ class K3DSparkForCausalLM(nn.Module):
assert vllm_config.speculative_config is not None
self.draft_model_config = vllm_config.speculative_config.draft_model_config
self.config = self.draft_model_config.hf_config
if getattr(self.config, "enable_confidence_head", False):
# The class mapper drops the head as training-only; keep it for drafts
# that actually built one, since adaptive verification reads it.
self.hf_to_vllm_mapper = self.hf_to_vllm_mapper | WeightsMapper(
orig_to_new_substr={"confidence_head": "confidence_head"}
)
target_layer_num = vllm_config.model_config.get_total_num_hidden_layers()
self.model = K3DSparkModel(
vllm_config=vllm_config,
@@ -494,6 +515,13 @@ class K3DSparkForCausalLM(nn.Module):
def markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor:
return self.model.markov_head.bias(markov_embed, self.logits_processor)
def compute_confidence(
self, head_hidden: torch.Tensor, markov_embed: torch.Tensor
) -> torch.Tensor:
"""Per-position acceptance probability for each drafted token."""
assert self.model.confidence_head is not None
return torch.sigmoid(self.model.confidence_head(head_hidden, markov_embed))
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
# read: 1. all weights. 2. context kv weights
+17 -1
View File
@@ -25,7 +25,7 @@ from vllm.model_executor.layers.mamba.checkpoint import (
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backend import AttentionCGSupport, CommonAttentionMetadata
from vllm.v1.attention.backends.gdn_attn import (
GDNAttentionBackend,
GDNAttentionMetadata,
@@ -305,6 +305,10 @@ class KimiK3KDAMetadata(GDNAttentionMetadata, RecoverSSMMetadata):
class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
# Overrides GDN's UNIFORM_BATCH: adaptive verification requires ALWAYS from every
# builder, and KDA reads per-request offsets off device within a fixed k+1 window,
# so one k+1 graph replays any 1..k+1 mix.
_cudagraph_support = AttentionCGSupport.ALWAYS
mamba_aligned_state_indices: torch.Tensor | None = None
def __init__(
@@ -407,6 +411,12 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
query_start_loc_cpu.diff() > 0
)
spec_sequence_masks_cpu |= active_decode_mask_cpu
# Adaptive's cost-table profiler probes eager dummy rows longer than
# RecoverSSM's num_spec+1 activation capacity; route them out instead
# of tripping the capacity check below.
spec_sequence_masks_cpu &= (
query_start_loc_cpu.diff() <= self.num_spec + 1
)
# Native KDA can use its regular decode path when no draft token
# was scheduled. RecoverSSM must preserve its extended conv window.
if (
@@ -750,3 +760,9 @@ class KimiK3KDAAttentionBackend(GDNAttentionBackend):
@staticmethod
def get_builder_cls() -> type[KimiK3KDAMetadataBuilder]:
return KimiK3KDAMetadataBuilder
@classmethod
def supports_device_cpu_query_lens_mismatch(cls) -> bool:
# Pure spec-decode reads its plan from DEVICE offsets, so CPU/device
# mismatch is fine; the mixed branch still assumes CPU totals match.
return True
@@ -115,10 +115,11 @@ class LatentMoERunner(MoERunner):
experts_cls = getattr(self._quant_method, "experts_cls", None)
# The kernel instance is built after weight loading, while the tail
# must register its CuTeDSL warmup units during runner construction.
self.moe_config.defer_moe_finalize = (
if (
experts_cls is TrtLlmMxfp4ExpertsMonolithic
or experts_cls is TrtLlmNvFp4ExpertsMonolithic
) and self.moe_config.hidden_dim == self.moe_config.hidden_dim_unpadded
) and self.moe_config.hidden_dim == self.moe_config.hidden_dim_unpadded:
self.moe_config.defer_moe_finalize()
from vllm.models.kimi_k3.nvidia.ops.latent_moe_tail import (
KimiK3LatentMoETailOp,
)
@@ -136,20 +137,13 @@ class LatentMoERunner(MoERunner):
rms_eps=norm.variance_epsilon,
)
self._k3_latent_moe_tail_op = op
self.moe_config.defer_moe_finalize_max_num_tokens = (
op.contract.max_num_tokens
if self.moe_config.use_deferred_moe_finalize
else -1
)
if self.moe_config.use_deferred_moe_finalize:
self.moe_config.limit_deferred_moe_finalize(op.contract.max_num_tokens)
logger.info_once(
"K3 latent-MoE tail fusion with deferred top-k finalization "
"is enabled for up to %d tokens.",
op.contract.max_num_tokens,
)
else:
self.moe_config.defer_moe_finalize = False
self.moe_config.defer_moe_finalize_max_num_tokens = -1
def _get_zero_residual(
self,
+6 -15
View File
@@ -58,6 +58,7 @@ from vllm.model_executor.layers.attention.mla_attention import (
accumulate_mla_context_chunk,
init_mla_context_partial,
neutralize_empty_context_partials,
split_kv_b_proj,
)
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.model_executor.layers.layernorm import RMSNorm
@@ -73,9 +74,6 @@ from vllm.model_executor.layers.quantization import (
QuantizationConfig,
resolve_quant_method,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
get_and_maybe_dequant_weights,
)
from vllm.model_executor.layers.rotary_embedding import RotaryEmbedding, get_rope
from vllm.model_executor.utils import replace_parameter
from vllm.models.common.ops import fused_q_kv_rmsnorm
@@ -441,20 +439,13 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
projected into latent space by ``W_UK_T`` and the attention output is
projected back to ``v`` by ``W_UV`` -- avoiding materializing full K/V.
"""
kv_b_proj_weight = get_and_maybe_dequant_weights(
self.kv_b_proj, out_dtype=act_dtype
).T
assert kv_b_proj_weight.shape == (
self.kv_lora_rank,
self.num_local_heads * (self.qk_nope_head_dim + self.v_head_dim),
), f"{kv_b_proj_weight.shape=}"
kv_b_proj_weight = kv_b_proj_weight.view(
W_UK, W_UV = split_kv_b_proj(
self.kv_b_proj,
act_dtype,
self.kv_lora_rank,
self.num_local_heads,
self.qk_nope_head_dim + self.v_head_dim,
)
W_UK, W_UV = kv_b_proj_weight.split(
[self.qk_nope_head_dim, self.v_head_dim], dim=-1
self.qk_nope_head_dim,
self.v_head_dim,
)
# (L, N, V) -> (N, L, V)
replace_parameter(self, "W_UV", W_UV.transpose(0, 1), prefer_copy=True)
+6 -5
View File
@@ -52,7 +52,11 @@ from vllm.models.minimax_m3.common.sparse_attention import (
_minimax_m3_aiter_sparse_pa_requested,
)
from vllm.platforms import current_platform
from vllm.v1.attention.backend import AttentionBackend, CommonAttentionMetadata
from vllm.v1.attention.backend import (
AttentionBackend,
CommonAttentionMetadata,
max_decode_query_len,
)
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
from vllm.v1.kv_cache_interface import AttentionSpec
@@ -97,10 +101,7 @@ def aiter_indexer_max_decode_query_len(vllm_config: VllmConfig) -> int:
since that is what the builder splits the batch on and therefore what the
decode kernel will actually be handed.
"""
spec = vllm_config.speculative_config
if spec is None or spec.num_speculative_tokens is None:
return 1
return 1 + (2 if spec.parallel_drafting else 1) * spec.num_speculative_tokens
return max_decode_query_len(vllm_config)
@cache
+12 -12
View File
@@ -21,7 +21,7 @@ from collections.abc import Iterable
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm import _custom_ops as ops
from vllm import envs
@@ -134,7 +134,7 @@ from vllm.v1.kv_cache_interface import (
logger = init_logger(__name__)
def _sparse_attention_layer_ids(config: PretrainedConfig) -> set[int]:
def _sparse_attention_layer_ids(config: PreTrainedConfig) -> set[int]:
"""Layer ids whose attention runs the extra sparse "index" branch."""
cfg = getattr(config, "sparse_attention_config", None)
if not cfg:
@@ -145,7 +145,7 @@ def _sparse_attention_layer_ids(config: PretrainedConfig) -> set[int]:
return {i for i, f in enumerate(freq) if f != 0}
def _sparse_attention_layer_ordinals(config: PretrainedConfig) -> dict[int, int]:
def _sparse_attention_layer_ordinals(config: PreTrainedConfig) -> dict[int, int]:
"""Map each sparse-attention layer id to its ordinal among sparse layers."""
return {
lid: ordinal
@@ -153,7 +153,7 @@ def _sparse_attention_layer_ordinals(config: PretrainedConfig) -> dict[int, int]
}
def _should_skip_index_topk(config: PretrainedConfig, layer_id: int) -> bool:
def _should_skip_index_topk(config: PreTrainedConfig, layer_id: int) -> bool:
"""ATOM ``index_topk_freq`` (cross-layer index sharing).
Only 1 of every ``index_topk_freq`` sparse-attention layers recomputes the
@@ -176,7 +176,7 @@ def _should_skip_index_topk(config: PretrainedConfig, layer_id: int) -> bool:
return max(ordinal - offset, 0) % freq != 0
def _is_moe_layer(config: PretrainedConfig, layer_id: int) -> bool:
def _is_moe_layer(config: PreTrainedConfig, layer_id: int) -> bool:
"""Whether this layer's MLP is a sparse MoE block (vs a dense MLP)."""
moe_layer_freq = getattr(config, "moe_layer_freq", None)
if moe_layer_freq is None:
@@ -184,7 +184,7 @@ def _is_moe_layer(config: PretrainedConfig, layer_id: int) -> bool:
return moe_layer_freq[layer_id] != 0
def _build_rotary_emb(config: PretrainedConfig, head_dim: int):
def _build_rotary_emb(config: PreTrainedConfig, head_dim: int):
"""Build the (partial NeoX) RoPE, honoring an optional ``rope_scaling`` config.
Without scaling the cos/sin cache is sized to ``max_position_embeddings``
@@ -262,7 +262,7 @@ class MiniMaxM3MLP(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
intermediate_size: int,
quant_config: QuantizationConfig | None = None,
reduce_results: bool = True,
@@ -338,7 +338,7 @@ class MiniMaxM3MoE(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_id: int,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -488,7 +488,7 @@ class MiniMaxM3Attention(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_id: int,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -623,7 +623,7 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_id: int,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -1264,7 +1264,7 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
class MiniMaxM3DecoderLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
prefix: str,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
@@ -1738,7 +1738,7 @@ class MiniMaxM3SparseForConditionalGeneration(
with self._mark_tower_model(vllm_config, {"image", "video"}):
vision_config = config.vision_config
self.vision_tower = MiniMaxVLVisionModel(
config=PretrainedConfig.from_dict(vision_config),
config=PreTrainedConfig.from_dict(vision_config),
text_hidden_size=text_hidden_size,
projector_hidden_size=projector_hidden_size,
quant_config=self.quant_config,
+4 -2
View File
@@ -113,8 +113,10 @@ def _swiglu_oai_quant_kernel(
act = gate * tl.sigmoid(alpha * gate) * (up + beta) # [BLOCK_M, 32] fp32
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)
# Computing the E8M0 byte-0 divisor (2^-127) can flush to zero on CDNA.
# Use its finite reciprocal so all-zero blocks do not produce 0/0.
rescale = tl.exp2(127.0 - sb)
aq = (act * rescale[:, None]).to(aq_ptr.dtype.element_ty)
tl.store(
aq_ptr + offs_m[:, None] * stride_qm + offs_c[None, :] * stride_qn,
aq,
+1 -1
View File
@@ -91,7 +91,7 @@ class MiniMaxM3IndexerBackend(AttentionBackend):
return [128]
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [128]
@classmethod
@@ -159,7 +159,7 @@ class MiniMaxM3SparseBackend(AttentionBackend):
return [128]
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
# Page size == sparse block size (one sparse block per KV page).
return [128]
+49 -177
View File
@@ -6,7 +6,7 @@ import numpy as np
import torch
import torch.nn as nn
from einops import rearrange
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.distributed import parallel_state
from vllm.distributed import utils as dist_utils
@@ -14,26 +14,23 @@ from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.layers.attention.mm_encoder_attention import (
MMEncoderAttention,
)
from vllm.model_executor.layers.conv import Conv3dLayer
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
QKVParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding.common import ApplyRotaryEmb
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
from vllm.model_executor.layers.rotary_embedding.mrope_vit_setup import (
vit_mrope_setup,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.utils import maybe_prefix
from vllm.model_executor.models.vision import (
get_vit_attn_backend,
is_vit_use_data_parallel,
)
from vllm.platforms import current_platform
# ROCm caps a kernel-launch gridDim.y at 65536. The HIP flash-attn Triton
# rotary kernel launches grid.y = cdiv(seqlen, BLOCK_M), so it fails with
# hipErrorInvalidValue once cdiv(seqlen, BLOCK_M) > 65536. Used below to decide
# when RoPE must be applied per video segment instead of in one launch.
_HIP_MAX_GRID_DIM_Y = 65536
class MiniMaxVLPatchEmbed(nn.Module):
@@ -43,7 +40,7 @@ class MiniMaxVLPatchEmbed(nn.Module):
and projects each to a hidden-size embedding.
"""
def __init__(self, config: PretrainedConfig) -> None:
def __init__(self, config: PreTrainedConfig) -> None:
super().__init__()
compression = config.img_token_compression_config
temporal_patch_size = compression.get("temporal_patch_size", 2)
@@ -55,7 +52,7 @@ class MiniMaxVLPatchEmbed(nn.Module):
self.num_channels = num_channels
self.hidden_size = config.hidden_size
self.patch_embedding = nn.Conv3d(
self.patch_embedding = Conv3dLayer(
in_channels=num_channels,
out_channels=config.hidden_size,
kernel_size=(temporal_patch_size, patch_size, patch_size),
@@ -124,56 +121,13 @@ class MiniMaxVLAttention(nn.Module):
head_size=self.head_dim,
prefix=f"{prefix}.attn",
)
# ApplyRotaryEmb handles the internal cos/sin repeat and partial
# rotation (ro_dim = half_rot_dim * 2 < head_dim for MiniMax).
# enable_fp32_compute=True runs the rotation in fp32 (q/k upcast,
# fp32 cos/sin), matching the reference ``_minimax_rope_applier``.
self.apply_rotary_emb = ApplyRotaryEmb(
enforce_enable=True, enable_fp32_compute=True
)
def _apply_rotary_emb(
self,
qk_reshaped: torch.Tensor,
rotary_cos: torch.Tensor,
rotary_sin: torch.Tensor,
seq_len: int,
rotary_segment_lengths: list[int] | None,
) -> torch.Tensor:
# Default fast path (all NVIDIA inputs, and ROCm short clips/images):
# a single rotary kernel launch. ``rotary_segment_lengths`` is only
# populated on ROCm (see ``MiniMaxVLVisionTransformer.forward``), so
# the per-segment path below is ROCm-only and never touches the
# NVIDIA/CUDA code path.
if not current_platform.is_rocm() or rotary_segment_lengths is None:
return self.apply_rotary_emb(qk_reshaped, rotary_cos, rotary_sin)
# ROCm only: the HIP flash-attn Triton rotary kernel fails with
# hipErrorInvalidValue once grid.y = cdiv(seqlen, BLOCK_M) exceeds
# _HIP_MAX_GRID_DIM_Y (65536). BLOCK_M is 8 for rotary_dim <= 128
# (MiniMax-M3 vision: rotary_dim=78), giving a hard limit of
# 65536 * BLOCK_M tokens — measured exactly as 524288 OK / 524289 fail.
# Only long videos cross it; since vision_segment_max_frames caps each
# segment at a few frames (<< limit), applying RoPE per segment keeps
# every sub-call in range. Splitting on segment boundaries is
# mathematically exact because rotary_cos/sin are precomputed per token.
# Images and short clips stay on the single-kernel fast path above.
rotary_dim = rotary_cos.shape[-1] * 2
block_m = 8 if rotary_dim <= 128 else 4
hip_rotary_max_seqlen = _HIP_MAX_GRID_DIM_Y * block_m
if seq_len <= hip_rotary_max_seqlen or len(rotary_segment_lengths) <= 1:
return self.apply_rotary_emb(qk_reshaped, rotary_cos, rotary_sin)
qk_segments = qk_reshaped.split(rotary_segment_lengths, dim=1)
cos_segments = rotary_cos.split(rotary_segment_lengths, dim=0)
sin_segments = rotary_sin.split(rotary_segment_lengths, dim=0)
return torch.cat(
[
self.apply_rotary_emb(qk_s, cos_s, sin_s)
for qk_s, cos_s, sin_s in zip(qk_segments, cos_segments, sin_segments)
],
dim=1,
)
# Partial 3D RoPE geometry: rot_dim is split evenly across t/h/w
# (same formula as MiniMaxVLVisionTransformer; rot_dim may be <
# head_dim). mrope_section is in half-dim units for triton_mrope.
rope_dims = 2 * (self.head_dim // 2)
axis_dim = 2 * ((rope_dims // 3) // 2)
self.rotary_dim = 3 * axis_dim
self.mrope_section = [axis_dim // 2] * 3
def forward(
self,
@@ -182,33 +136,34 @@ class MiniMaxVLAttention(nn.Module):
rotary_cos: torch.Tensor,
rotary_sin: torch.Tensor,
max_seqlen: torch.Tensor,
rotary_segment_lengths: list[int] | None = None,
sequence_lengths: torch.Tensor | None = None,
) -> torch.Tensor:
# x: (N, 1, embed_dim) [seq=N, batch=1, chan=embed_dim]
x_qkv, _ = self.qkv_proj(x) # (N, 1, 3 * heads_per_part * head_dim)
seq_len, batch_size, _ = x_qkv.shape
# Rearrange to (b=1, N, 3, heads, head_dim) — same as Qwen2_5_VisionAttention
qkv = rearrange(
x_qkv,
"s b (three head d) -> b s three head d",
three=3,
head=self.num_heads_per_partition,
)
qk, v = qkv[:, :, :2], qkv[:, :, 2] # (b,N,2,h,d) and (b,N,h,d)
qkv = x_qkv.view(seq_len, 3, self.num_heads_per_partition, self.head_dim)
v = qkv[:, 2].unsqueeze(0) # (b=1, N, heads, head_dim) strided view
# Stack q/k → (2*b, N, heads, head_dim) for joint RoPE application.
# rotary_cos/sin: (N, half_rot_dim) — ApplyRotaryEmb expands internally
# and rotates only the first 2*half_rot_dim dims, passing the rest through.
qk_reshaped = rearrange(qk, "b s two h d -> (two b) s h d", two=2).contiguous()
qk_rotated = self._apply_rotary_emb(
qk_reshaped, rotary_cos, rotary_sin, seq_len, rotary_segment_lengths
# In-place partial 3D RoPE on strided q/k views of the packed qkv
# tensor: one kernel launch, no repack/upcast copies. fp32 cos/sin
# make the kernel compute in fp32, matching the reference
# ``_minimax_rope_applier`` precision.
q = qkv[:, 0].reshape(seq_len, -1)
k = qkv[:, 1].reshape(seq_len, -1)
triton_mrope(
q,
k,
rotary_cos,
rotary_sin,
self.mrope_section,
self.head_dim,
self.rotary_dim,
mrope_interleaved=False,
is_neox_style=True,
)
qk_rotated = qk_rotated.view(
2, batch_size, seq_len, self.num_heads_per_partition, self.head_dim
)
q, k = qk_rotated.unbind(dim=0) # each (b=1, N, heads, head_dim)
q = q.view(batch_size, seq_len, self.num_heads_per_partition, self.head_dim)
k = k.view(batch_size, seq_len, self.num_heads_per_partition, self.head_dim)
# Flash attention → (b, N, heads, head_dim)
context = self.attn(
@@ -231,7 +186,7 @@ class MiniMaxVLEncoderLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
@@ -271,7 +226,6 @@ class MiniMaxVLEncoderLayer(nn.Module):
rotary_cos: torch.Tensor,
rotary_sin: torch.Tensor,
max_seqlen: torch.Tensor,
rotary_segment_lengths: list[int] | None = None,
sequence_lengths: torch.Tensor | None = None,
) -> torch.Tensor:
# x: (N, 1, hidden_size)
@@ -281,7 +235,6 @@ class MiniMaxVLEncoderLayer(nn.Module):
rotary_cos,
rotary_sin,
max_seqlen,
rotary_segment_lengths,
sequence_lengths,
)
residual = x
@@ -294,7 +247,7 @@ class MiniMaxVLEncoderLayer(nn.Module):
class MiniMaxVLEncoder(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
num_hidden_layers_override: int | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -323,7 +276,6 @@ class MiniMaxVLEncoder(nn.Module):
rotary_cos: torch.Tensor,
rotary_sin: torch.Tensor,
max_seqlen: torch.Tensor,
rotary_segment_lengths: list[int] | None = None,
sequence_lengths: torch.Tensor | None = None,
) -> torch.Tensor:
for layer in self.layers:
@@ -333,7 +285,6 @@ class MiniMaxVLEncoder(nn.Module):
rotary_cos,
rotary_sin,
max_seqlen,
rotary_segment_lengths,
sequence_lengths,
)
return x
@@ -348,7 +299,7 @@ class MiniMaxVLVisionTransformer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
num_hidden_layers_override: int | None = None,
require_post_norm: bool | None = None,
quant_config: QuantizationConfig | None = None,
@@ -426,82 +377,6 @@ class MiniMaxVLVisionTransformer(nn.Module):
# out_hidden_size needed by run_dp_sharded_mrope_vision_model
self.out_hidden_size = embed_dim
# ── RoPE helpers ─────────────────────────────────────────────────────
def _get_3d_rope_embed(
self, grid_t: int, grid_h: int, grid_w: int, spatial_merge_size: int
) -> torch.Tensor:
"""Compute 3D RoPE frequencies for a single (T, H, W) grid.
Returns (T*H*W, half_rot_dim) on the same device as inv_freq buffers.
Mirrors the reference ``_get_3d_rope_embed`` exactly.
"""
tokens_per_frame = grid_h * grid_w
tpos_ids = (
torch.arange(grid_t, device=self.inv_freq_t.device)
.unsqueeze(1)
.expand(-1, tokens_per_frame)
.flatten()
)
hpos_ids = (
torch.arange(grid_h, device=self.inv_freq_h.device)
.unsqueeze(1)
.expand(-1, grid_w)
.reshape(
grid_h // spatial_merge_size,
spatial_merge_size,
grid_w // spatial_merge_size,
spatial_merge_size,
)
.permute(0, 2, 1, 3)
.unsqueeze(0)
.expand(grid_t, -1, -1, -1, -1)
.flatten()
)
wpos_ids = (
torch.arange(grid_w, device=self.inv_freq_w.device)
.unsqueeze(0)
.expand(grid_h, -1)
.reshape(
grid_h // spatial_merge_size,
spatial_merge_size,
grid_w // spatial_merge_size,
spatial_merge_size,
)
.permute(0, 2, 1, 3)
.unsqueeze(0)
.expand(grid_t, -1, -1, -1, -1)
.flatten()
)
max_t = max(grid_t, 1)
max_hw = max(grid_h, grid_w)
seq_t = torch.arange(
max_t, device=self.inv_freq_t.device, dtype=self.inv_freq_t.dtype
)
seq_hw = torch.arange(
max_hw, device=self.inv_freq_h.device, dtype=self.inv_freq_h.dtype
)
freqs_t = torch.outer(seq_t, self.inv_freq_t) # (max_t, t_dim/2)
freqs_h = torch.outer(seq_hw, self.inv_freq_h) # (max_hw, h_dim/2)
freqs_w = torch.outer(seq_hw, self.inv_freq_w) # (max_hw, w_dim/2)
return torch.cat(
[freqs_t[tpos_ids], freqs_h[hpos_ids], freqs_w[wpos_ids]], dim=-1
) # (T*H*W, half_rot_dim)
def _get_rope_embed_3d(
self, grid_thw: list[list[int]], spatial_merge_size: int
) -> torch.Tensor:
embeds = [
self._get_3d_rope_embed(t, h, w, spatial_merge_size) for t, h, w in grid_thw
]
return torch.cat(embeds, dim=0) # (total_N, half_rot_dim)
# ── Frame-limit helper (mirrors the reference) ───────────────────────
def _apply_max_frames_limit(self, grid_thw: list[list[int]]) -> list[list[int]]:
@@ -556,21 +431,19 @@ class MiniMaxVLVisionTransformer(nn.Module):
hidden.device,
)
# 3D RoPE: (total_N, half_rot_dim); ApplyRotaryEmb expands internally
freqs = self._get_rope_embed_3d(limited, self.spatial_merge_size)
freqs = freqs.to(device=hidden.device)
# Keep cos/sin in fp32; ApplyRotaryEmb(enable_fp32_compute=True) runs the
# rotation in fp32 to match the reference precision.
rotary_cos, rotary_sin = freqs.cos(), freqs.sin()
# 3D RoPE cos/sin: (3, total_N, half_rot_dim) fp32 t/h/w planes for
# triton_mrope from one fused setup kernel. Kept fp32 so the kernel
# computes the rotation in fp32, matching the reference.
rotary_cos, rotary_sin = vit_mrope_setup(
self.inv_freq_t,
self.inv_freq_h,
self.inv_freq_w,
limited,
self.spatial_merge_size,
)
# Encoder expects (N, 1, hidden_size) — add batch dim
hidden = hidden.unsqueeze(1)
# On ROCm, the flash_attn Triton rotary kernel can fail with
# hipErrorInvalidValue when seqlen is very large, e.g. 192k video
# tokens; pass per-segment lengths so RoPE can be applied in chunks.
# On other platforms leave it None -> single-kernel fast path, so the
# NVIDIA/CUDA code path is unchanged.
rotary_segment_lengths = lens if current_platform.is_rocm() else None
hidden = self.encoder(
hidden,
@@ -578,7 +451,6 @@ class MiniMaxVLVisionTransformer(nn.Module):
rotary_cos,
rotary_sin,
max_seqlen,
rotary_segment_lengths,
sequence_lengths=sequence_lengths,
)
hidden = hidden.squeeze(1) # back to (total_N, hidden_size)
@@ -678,7 +550,7 @@ class MiniMaxVLVisionModel(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
text_hidden_size: int,
projector_hidden_size: int | None = None,
quant_config: QuantizationConfig | None = None,
+8 -8
View File
@@ -16,7 +16,7 @@ from collections.abc import Iterable
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm import _custom_ops as ops
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
@@ -92,7 +92,7 @@ from vllm.v1.kv_cache_interface import (
)
def _sparse_attention_layer_ids(config: PretrainedConfig) -> set[int]:
def _sparse_attention_layer_ids(config: PreTrainedConfig) -> set[int]:
"""Layer ids whose attention runs the extra sparse "index" branch."""
cfg = getattr(config, "sparse_attention_config", None)
if not cfg:
@@ -103,7 +103,7 @@ def _sparse_attention_layer_ids(config: PretrainedConfig) -> set[int]:
return {i for i, f in enumerate(freq) if f != 0}
def _is_moe_layer(config: PretrainedConfig, layer_id: int) -> bool:
def _is_moe_layer(config: PreTrainedConfig, layer_id: int) -> bool:
"""Whether this layer's MLP is a sparse MoE block (vs a dense MLP)."""
moe_layer_freq = getattr(config, "moe_layer_freq", None)
if moe_layer_freq is None:
@@ -147,7 +147,7 @@ class MiniMaxM3MLP(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
intermediate_size: int,
quant_config: QuantizationConfig | None = None,
reduce_results: bool = True,
@@ -194,7 +194,7 @@ class MiniMaxM3MoE(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_id: int,
quant_config: QuantizationConfig | None = None,
reduce_results: bool = True,
@@ -290,7 +290,7 @@ class MiniMaxM3Attention(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_id: int,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -403,7 +403,7 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
layer_id: int,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -1130,7 +1130,7 @@ class MiniMaxM3SparseForConditionalGeneration(
with self._mark_tower_model(vllm_config, {"image", "video"}):
vision_config = config.vision_config
self.vision_tower = MiniMaxVLVisionModel(
config=PretrainedConfig.from_dict(vision_config),
config=PreTrainedConfig.from_dict(vision_config),
text_hidden_size=text_hidden_size,
projector_hidden_size=projector_hidden_size,
quant_config=self.quant_config,
+90 -4
View File
@@ -11,6 +11,7 @@ from torch import nn
from vllm.config import CacheConfig, ModelConfig, VllmConfig, get_current_vllm_config
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.mamba.abstract import MambaBase
from vllm.model_executor.layers.mamba.mamba_utils import (
@@ -18,6 +19,9 @@ from vllm.model_executor.layers.mamba.mamba_utils import (
MambaStateShapeCalculator,
is_conv_state_dim_first,
)
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
)
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
@@ -30,7 +34,13 @@ from vllm.v1.attention.backends.short_conv_attn import (
)
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from ..common.ple import PLEVocabParallelEmbedding
from ..common.ngram_embedding import (
Qwen4ExpPLEDeviceEmbedding,
Qwen4ExpPLEEmbeddingMethod,
Qwen4ExpPLEPinnedHostEmbedding,
)
logger = init_logger(__name__)
class Qwen4ExpPLEGroupedNorm(nn.Module):
@@ -172,6 +182,10 @@ class Qwen4ExpNGramEmbedding(nn.Module):
max_num_reqs: int,
prefix: str,
layer_name: str,
*,
data_parallel_rank: int = 0,
quant_config: QuantizationConfig | None = None,
params_dtype: torch.dtype | None = None,
) -> None:
super().__init__()
self.embedding_dim = embedding_dim
@@ -224,11 +238,39 @@ class Qwen4ExpNGramEmbedding(nn.Module):
)
divisor = int(config.make_ngram_vocab_size_divisible_by)
padded_vocab_size = ((total_vocab_size + divisor - 1) // divisor) * divisor
self.ngram_embedding = PLEVocabParallelEmbedding(
if params_dtype is None:
params_dtype = torch.get_default_dtype()
embedding_prefix = f"{prefix}.ngram_embedding"
embedding_quant_method = Qwen4ExpPLEEmbeddingMethod.from_quant_config(
quant_config,
embedding_prefix,
getattr(config, "ple_embedding_dtype", None),
)
engram_config = get_current_vllm_config().engram_config
embedding_cls = (
Qwen4ExpPLEPinnedHostEmbedding
if engram_config is not None and engram_config.cpu_offload
else Qwen4ExpPLEDeviceEmbedding
)
self.ngram_embedding = embedding_cls(
padded_vocab_size,
self.head_dim,
params_dtype=params_dtype,
padding_size=divisor,
prefix=f"{prefix}.ngram_embedding",
prefix=embedding_prefix,
embedding_method=embedding_quant_method,
num_ngram_heads=self.ngram_heads,
max_total_tokens=max_total_tokens,
data_parallel_rank=data_parallel_rank,
)
logger.info(
"Initialized AMD PLE embedding %s: quantization_method=%s, "
"weight_dtype=%s, weight_device=%s, pinned=%s",
embedding_prefix,
type(embedding_quant_method).__name__,
self.ngram_embedding.weight.dtype,
self.ngram_embedding.weight.device,
self.ngram_embedding.weight.is_pinned(),
)
self.register_buffer(
"positions_buffer",
@@ -344,9 +386,21 @@ class Qwen4ExpNGramEmbedding(nn.Module):
ids = torch.remainder(mixed.unsqueeze(-1), sizes) + offsets
id_blocks.append(ids[request_indices, adjusted_columns])
ngram_ids = torch.cat(id_blocks, dim=-1)
embedding = self.ngram_embedding
if embedding.supports_prefetch:
output = ngram_ids.new_empty(
(ngram_ids.shape[0], self.embedding_dim),
dtype=embedding.weight.dtype,
)
torch.ops.vllm.qwen4_exp_amd_ple_ngram_embedding_pinned(
ngram_ids,
output,
self.layer_name,
)
return output
output = ngram_ids.new_empty(
(ngram_ids.shape[0], self.embedding_dim),
dtype=self.ngram_embedding.params_dtype,
dtype=embedding.params_dtype,
)
torch.ops.vllm.qwen4_exp_amd_ple_ngram_embedding(
ngram_ids,
@@ -459,6 +513,9 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
vllm_config.scheduler_config.max_num_seqs,
f"{prefix}.ple_embedding",
prefix,
data_parallel_rank=vllm_config.parallel_config.data_parallel_rank,
quant_config=quant_config,
params_dtype=model_config.dtype,
)
self.key_proj = ReplicatedLinear(
int(config.ple_embed_dim),
@@ -1044,6 +1101,10 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
f"{hidden_states.shape[0]}"
)
embeddings = self.ple_embedding(input_ids, query_start_loc, ngram_context)
embeddings = self.ple_embedding.ngram_embedding.dequantize(
embeddings,
self.ple_embedding.ngram_embedding.params_dtype,
)
key, _ = self.key_proj(embeddings)
value, _ = self.value_proj(embeddings)
token_count = hidden_states.shape[0]
@@ -1081,6 +1142,24 @@ def qwen4_exp_amd_ple_ngram_embedding(
output.copy_(result)
def qwen4_exp_amd_ple_ngram_embedding_pinned(
ngram_ids: torch.Tensor,
output: torch.Tensor,
layer_name: str,
) -> None:
"""Run the pinned PLE UVA lookup outside Inductor's FX graph.
Same rationale as the device-path escape: keeping the large embedding weight
out of the graph prevents AOT compile-time autotuning from materializing a
synthetic copy of the weight.
"""
layer = get_forward_context().no_compile_layers[layer_name]
if not isinstance(layer, Qwen4ExpPLELayer):
raise TypeError(f"{layer_name} is not a Qwen4Exp PLE owner")
result = layer.ple_embedding.ngram_embedding.sync_lookup(ngram_ids).flatten(-2)
output.copy_(result)
def qwen4_exp_ple_short_conv(
inputs: torch.Tensor,
output: torch.Tensor,
@@ -1098,6 +1177,13 @@ direct_register_custom_op(
)
direct_register_custom_op(
op_name="qwen4_exp_amd_ple_ngram_embedding_pinned",
op_func=qwen4_exp_amd_ple_ngram_embedding_pinned,
mutates_args=["output"],
)
direct_register_custom_op(
op_name="qwen4_exp_ple_short_conv",
op_func=qwen4_exp_ple_short_conv,
+1 -1
View File
@@ -75,7 +75,7 @@ class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
return "QWEN4_EXP_QSA_TRITON"
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
# QSA consumes manager pages directly and does not use FA4 paged attention.
return [MultipleOf(16)]
@@ -0,0 +1,542 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared Qwen4Exp n-gram embedding storage with device and pinned-host backends.
Both the NVIDIA and AMD Qwen4Exp implementations use these classes so the (large)
n-gram embedding table can be kept in pinned host memory and looked up through
Unified Virtual Addressing on any CUDA-alike platform.
"""
from abc import ABC, abstractmethod
from typing import ClassVar
import torch
import torch.nn.functional as F
from torch import nn
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.distributed import get_dp_group, get_etp_group, get_tp_group
from vllm.forward_context import DPMetadata, get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
QuantizeMethodBase,
)
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptMixedPrecisionConfig,
ModelOptQuantConfigBase,
)
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
create_fp8_scale_parameter,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
is_layer_skipped,
)
from vllm.model_executor.parameter import (
ModelWeightParameter,
PerTensorScaleParameter,
)
from vllm.model_executor.utils import set_weight_attrs
from vllm.triton_utils import tl, triton
from vllm.utils.platform_utils import is_uva_available
from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
from .ple import PLEVocabParallelEmbedding
logger = init_logger(__name__)
class Qwen4ExpPLEEmbedding(PLEVocabParallelEmbedding, ABC):
"""ETP-sharded PLE table shared by device and pinned-host backends."""
supports_prefetch: ClassVar[bool] = False
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
*,
params_dtype: torch.dtype,
padding_size: int,
prefix: str,
embedding_method: "Qwen4ExpPLEEmbeddingMethod",
num_ngram_heads: int = 1,
max_total_tokens: int = 0,
data_parallel_rank: int = 0,
) -> None:
del num_ngram_heads, max_total_tokens
super().__init__(
num_embeddings,
embedding_dim,
params_dtype=params_dtype,
padding_size=padding_size,
prefix=prefix,
quant_method=embedding_method,
parallel_group=get_etp_group(),
)
self.embedding_method = embedding_method
self.data_parallel_rank = data_parallel_rank
tp_size = get_tp_group().world_size
if self.tp_size % tp_size:
raise ValueError(
"ETP size must be divisible by TP size, but got "
f"ETP={self.tp_size} and TP={tp_size}"
)
self.etp_data_parallel_size = self.tp_size // tp_size
@abstractmethod
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate storage for the complete embedding weight."""
raise NotImplementedError
def dequantize(
self,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
"""Delegate storage-format conversion to the embedding method."""
return self.embedding_method.dequantize(self, embeddings, output_dtype)
def _get_dp_gather_slot(self, local_num_tokens: int) -> tuple[int, int]:
"""Return the per-DP slot size and this rank's slot offset."""
if self.etp_data_parallel_size == 1:
return local_num_tokens, 0
dp_metadata: DPMetadata | None = get_forward_context().dp_metadata
if dp_metadata is None:
raise RuntimeError("ETP spanning DP requires DP token metadata")
group_start = (self.data_parallel_rank // self.etp_data_parallel_size) * (
self.etp_data_parallel_size
)
group_end = group_start + self.etp_data_parallel_size
token_counts = dp_metadata.num_tokens_across_dp_cpu.tolist()
group_counts = token_counts[group_start:group_end]
slot_size = max(group_counts)
dp_rank = get_dp_group().rank_in_group
return slot_size, dp_rank * slot_size
def _gather_dp_ids(
self,
ngram_ids: torch.Tensor,
slot_size: int,
) -> torch.Tensor:
"""Gather DP-local IDs that share one ETP-sharded PLE table."""
if self.etp_data_parallel_size == 1:
return ngram_ids
if ngram_ids.shape[0] < slot_size:
padding = ngram_ids.new_zeros(
slot_size - ngram_ids.shape[0], ngram_ids.shape[1]
)
ngram_ids = torch.cat((ngram_ids, padding), dim=0)
return get_dp_group().all_gather(ngram_ids, dim=0)
def _select_embeddings(
self,
embeddings: torch.Tensor,
local_num_tokens: int,
slot_offset: int,
) -> torch.Tensor:
"""Select this DP rank's rows from the ETP-reduced embeddings."""
if self.etp_data_parallel_size == 1:
return embeddings
return embeddings.narrow(0, slot_offset, local_num_tokens)
@abstractmethod
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Start an asynchronous lookup when supported."""
raise NotImplementedError
class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
"""Quantization interface shared by resident and pinned PLE tables."""
# PLE post-load processing only validates scales in their current storage.
requires_device_loading: bool = False
@staticmethod
def from_quant_config(
quant_config: QuantizationConfig | None,
prefix: str,
embedding_dtype: str | None = None,
) -> "Qwen4ExpPLEEmbeddingMethod":
"""Select the concrete PLE embedding format for a layer."""
if embedding_dtype == "float8_e4m3fn":
return Qwen4ExpPLEFp8EmbeddingMethod()
if quant_config is None:
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if isinstance(quant_config, ModelOptMixedPrecisionConfig):
if quant_config._resolve_quant_algo(prefix) == "FP8":
return Qwen4ExpPLEFp8EmbeddingMethod()
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if isinstance(
quant_config, ModelOptQuantConfigBase
) and quant_config.is_layer_excluded(prefix):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if not isinstance(quant_config, Fp8Config):
raise NotImplementedError(
"Qwen4Exp PLE embedding does not support quantization config "
f"{type(quant_config).__name__}"
)
ignored_layers = quant_config.ignored_layers
if is_layer_skipped(
prefix,
ignored_layers,
quant_config.packed_modules_mapping,
match_mode=quant_config.ignored_layers_match_mode,
):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
# PLE checkpoint shards form one runtime embedding parameter.
shard_prefix = f"{prefix}.shard_"
if any(name.startswith(shard_prefix) for name in ignored_layers):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if not quant_config.is_checkpoint_fp8_serialized:
raise NotImplementedError(
"Qwen4Exp PLE embedding only supports serialized FP8 checkpoints"
)
return Qwen4ExpPLEFp8EmbeddingMethod()
def apply(
self,
layer: nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
raise NotImplementedError("PLE weights only support embedding lookup")
def embedding(self, layer: nn.Module, input_: torch.Tensor) -> torch.Tensor:
return F.embedding(input_, layer.weight)
@abstractmethod
def dequantize(
self,
layer: nn.Module,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
"""Convert looked-up PLE rows to the activation dtype."""
raise NotImplementedError
class Qwen4ExpPLEUnquantizedEmbeddingMethod(Qwen4ExpPLEEmbeddingMethod):
"""Unquantized PLE embedding storage and lookup semantics."""
def create_weights(
self,
layer: Qwen4ExpPLEEmbedding,
input_size_per_partition: int,
output_partition_sizes: list[int],
input_size: int,
output_size: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
) -> None:
del input_size, output_size
weight = nn.Parameter(
layer.allocate_embedding_weight(
sum(output_partition_sizes),
input_size_per_partition,
params_dtype,
),
requires_grad=False,
)
set_weight_attrs(weight, {"input_dim": 1, "output_dim": 0})
set_weight_attrs(weight, extra_weight_attrs)
layer.register_parameter("weight", weight)
def dequantize(
self,
layer: nn.Module,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
del layer, output_dtype
return embeddings
class Qwen4ExpPLEFp8EmbeddingMethod(Qwen4ExpPLEEmbeddingMethod):
"""FP8 PLE embedding with one global checkpoint scale."""
def create_weights(
self,
layer: Qwen4ExpPLEEmbedding,
input_size_per_partition: int,
output_partition_sizes: list[int],
input_size: int,
output_size: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
) -> None:
del input_size, output_size, params_dtype
weight_loader = extra_weight_attrs.get("weight_loader")
weight = ModelWeightParameter(
data=layer.allocate_embedding_weight(
sum(output_partition_sizes),
input_size_per_partition,
torch.float8_e4m3fn,
),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
)
layer.register_parameter("weight", weight)
weight_scale = create_fp8_scale_parameter(
PerTensorScaleParameter,
output_partition_sizes,
input_size_per_partition,
None,
weight_loader,
scale_dtype=torch.float32,
)
layer.register_parameter("weight_scale", weight_scale)
def process_weights_after_loading(self, layer: nn.Module) -> None:
"""Reject FP8 PLE checkpoints without a global scale."""
sentinel = torch.finfo(torch.float32).min
if torch.any(layer.weight_scale == sentinel):
raise ValueError("FP8 PLE checkpoint is missing its global scale")
def dequantize(
self,
layer: nn.Module,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
weight_scale = getattr(layer, "weight_scale", None)
if weight_scale is None:
raise RuntimeError("FP8 PLE embedding is missing its global scale")
if weight_scale.device != embeddings.device:
raise RuntimeError("FP8 PLE embedding scale must be on the output device")
return embeddings.to(output_dtype) * weight_scale.to(output_dtype)
class Qwen4ExpPLEDeviceEmbedding(Qwen4ExpPLEEmbedding):
"""PLE table allocated on the active model device."""
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate the complete PLE weight on the active device."""
return torch.empty(num_embeddings, embedding_dim, dtype=dtype)
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Resident embedding prefetch is a no-op."""
return None
def forward(self, ngram_ids: torch.Tensor) -> torch.Tensor:
"""Gather ETP inputs, look up embeddings, and select local rows."""
slot_size, slot_offset = self._get_dp_gather_slot(ngram_ids.shape[0])
gathered_ids = self._gather_dp_ids(ngram_ids, slot_size)
embeddings = super().forward(gathered_ids)
return self._select_embeddings(
embeddings,
ngram_ids.shape[0],
slot_offset,
)
@triton.jit
def _lookup_ple_embedding_from_pinned_kernel(
weight_ptr,
ids_ptr,
output_ptr,
embedding_dim,
tp_vocab_start,
tp_vocab_end,
BLOCK_D: tl.constexpr,
):
"""Look up TP-owned PLE rows through a CUDA view of pinned host memory."""
row_id = tl.program_id(0)
global_idx = tl.load(ids_ptr + row_id)
in_range = (global_idx >= tp_vocab_start) & (global_idx < tp_vocab_end)
local_idx = tl.where(in_range, global_idx - tp_vocab_start, 0)
offsets = tl.arange(0, BLOCK_D)
store_mask = offsets < embedding_dim
load_mask = store_mask & in_range
values = tl.load(
weight_ptr + local_idx * embedding_dim + offsets,
mask=load_mask,
other=0.0,
)
tl.store(
output_ptr + row_id * embedding_dim + offsets,
values,
mask=store_mask,
)
class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
"""PLE table loaded into pinned CPU memory and looked up through UVA."""
supports_prefetch: ClassVar[bool] = True
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
*,
params_dtype: torch.dtype,
padding_size: int,
prefix: str,
embedding_method: Qwen4ExpPLEEmbeddingMethod,
num_ngram_heads: int = 1,
max_total_tokens: int = 0,
data_parallel_rank: int = 0,
) -> None:
if not is_uva_available():
raise RuntimeError("Engram CPU offload requires UVA support")
super().__init__(
num_embeddings,
embedding_dim,
params_dtype=params_dtype,
padding_size=padding_size,
prefix=prefix,
embedding_method=embedding_method,
num_ngram_heads=num_ngram_heads,
max_total_tokens=max_total_tokens,
data_parallel_rank=data_parallel_rank,
)
self._uva_weight = get_accelerator_view_from_cpu_tensor(self.weight)
self._block_d = triton.next_power_of_2(self.embedding_dim)
self._prefetch_stream = torch.cuda.Stream(device=self._uva_weight.device)
self._prefetch_buffer = torch.empty(
max_total_tokens * self.etp_data_parallel_size,
num_ngram_heads,
self.embedding_dim,
dtype=self.weight.dtype,
device=self._uva_weight.device,
)
self._output_dim = num_ngram_heads * self.embedding_dim
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate the complete PLE weight directly in pinned CPU memory."""
return torch.empty(
num_embeddings,
embedding_dim,
dtype=dtype,
device="cpu",
pin_memory=True,
)
def _lookup(
self,
input_ids: torch.Tensor,
output: torch.Tensor | None = None,
) -> torch.Tensor:
"""Look up local ETP rows while preserving the weight storage dtype."""
expected_shape = (*input_ids.shape, self.embedding_dim)
if output is None:
output = torch.empty(
expected_shape,
dtype=self.weight.dtype,
device=input_ids.device,
)
elif (
tuple(output.shape) != expected_shape
or output.dtype != self.weight.dtype
or output.device != input_ids.device
):
raise ValueError(
"PLE prefetch output must match the input shape, weight dtype, "
"and input device"
)
flat_ids = input_ids.reshape(-1).long()
if flat_ids.numel():
_lookup_ple_embedding_from_pinned_kernel[(flat_ids.numel(),)](
self._uva_weight,
flat_ids,
output,
self.embedding_dim,
self.shard_indices.org_vocab_start_index,
self.shard_indices.org_vocab_end_index,
BLOCK_D=self._block_d,
)
return output
def sync_lookup(self, ngram_ids: torch.Tensor) -> torch.Tensor:
"""Synchronous UVA lookup for platforms without prefetch wiring."""
slot_size, slot_offset = self._get_dp_gather_slot(ngram_ids.shape[0])
gathered_ids = self._gather_dp_ids(ngram_ids, slot_size)
embeddings = self._lookup(gathered_ids)
embeddings = self._reduce_etp_embeddings(embeddings)
return self._select_embeddings(
embeddings,
ngram_ids.shape[0],
slot_offset,
)
def _reduce_etp_embeddings(self, embeddings: torch.Tensor) -> torch.Tensor:
"""Combine pinned lookup results owned by different ETP ranks."""
if self.tp_size == 1:
return embeddings
assert self.parallel_group is not None
if embeddings.dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
# Each vocabulary row has one owner, so reduce the raw FP8 bytes.
reduced = self.parallel_group.all_reduce(embeddings.view(torch.int8))
return reduced.view(embeddings.dtype)
return self.parallel_group.all_reduce(embeddings)
@eager_break_during_capture
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Gather ETP IDs and launch their UVA lookup on the side stream."""
slot_size, _ = self._get_dp_gather_slot(ngram_ids.shape[0])
gathered_ids = self._gather_dp_ids(ngram_ids, slot_size)
active_output = self._prefetch_buffer[: gathered_ids.shape[0]]
prefetch_stream = self._prefetch_stream
prefetch_stream.wait_stream(torch.cuda.current_stream())
gathered_ids.record_stream(prefetch_stream)
with torch.cuda.stream(prefetch_stream):
self._lookup(gathered_ids, output=active_output)
@eager_break_during_capture
def _finalize_prefetch(
self,
prefetch_output: torch.Tensor,
output: torch.Tensor,
) -> None:
"""Join the side stream, reduce ETP shards, and select local rows."""
torch.cuda.current_stream().wait_stream(self._prefetch_stream)
slot_size, slot_offset = self._get_dp_gather_slot(output.shape[0])
active_output = prefetch_output[: slot_size * self.etp_data_parallel_size]
embeddings = self._reduce_etp_embeddings(active_output)
embeddings = self._select_embeddings(
embeddings,
output.shape[0],
slot_offset,
)
output.copy_(embeddings.flatten(-2))
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Finish the pinned lookup into graph-owned output storage."""
output = self._prefetch_buffer.new_empty(
(hidden_states.shape[0], self._output_dim)
)
self._finalize_prefetch(self._prefetch_buffer, output)
return output
+3 -3
View File
@@ -4,7 +4,7 @@
from typing import Any, ClassVar, cast
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from transformers.models.qwen3_vl.configuration_qwen3_vl import (
Qwen3VLVisionConfig,
)
@@ -219,9 +219,9 @@ class Qwen4ExpTextConfig(Qwen3NextConfig):
return max(int(self.ngram_size) - 1, 0)
class Qwen4ExpConfig(PretrainedConfig):
class Qwen4ExpConfig(PreTrainedConfig):
model_type = "qwen4_exp"
sub_configs: ClassVar[dict[str, type[PretrainedConfig]]] = {
sub_configs: ClassVar[dict[str, type[PreTrainedConfig]]] = {
"vision_config": Qwen4ExpVisionConfig,
"text_config": Qwen4ExpTextConfig,
}
+24 -509
View File
@@ -2,534 +2,42 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Qwen4Exp n-gram embeddings with device and pinned-host storage."""
from abc import ABC, abstractmethod
from collections.abc import Iterable
from typing import ClassVar
import torch
import torch.nn.functional as F
from torch import nn
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import get_current_vllm_config
from vllm.distributed import get_dp_group, get_etp_group, get_tp_group
from vllm.forward_context import DPMetadata, get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
QuantizeMethodBase,
)
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptMixedPrecisionConfig,
ModelOptQuantConfigBase,
)
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
create_fp8_scale_parameter,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
is_layer_skipped,
)
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.parameter import (
ModelWeightParameter,
PerTensorScaleParameter,
)
from vllm.model_executor.utils import set_weight_attrs
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from vllm.triton_utils import tl, triton
from vllm.utils.platform_utils import is_uva_available
from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
from ..common.ple import PLEVocabParallelEmbedding
from ..common.ngram_embedding import (
Qwen4ExpPLEDeviceEmbedding,
Qwen4ExpPLEEmbedding,
Qwen4ExpPLEEmbeddingMethod,
Qwen4ExpPLEFp8EmbeddingMethod,
Qwen4ExpPLEPinnedHostEmbedding,
Qwen4ExpPLEUnquantizedEmbeddingMethod,
)
from .ops.ple import ple_ngram_ids
logger = init_logger(__name__)
class Qwen4ExpPLEEmbedding(PLEVocabParallelEmbedding, ABC):
"""ETP-sharded PLE table shared by device and pinned-host backends."""
supports_prefetch: ClassVar[bool] = False
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
*,
params_dtype: torch.dtype,
padding_size: int,
prefix: str,
embedding_method: "Qwen4ExpPLEEmbeddingMethod",
num_ngram_heads: int = 1,
max_total_tokens: int = 0,
data_parallel_rank: int = 0,
) -> None:
del num_ngram_heads, max_total_tokens
super().__init__(
num_embeddings,
embedding_dim,
params_dtype=params_dtype,
padding_size=padding_size,
prefix=prefix,
quant_method=embedding_method,
parallel_group=get_etp_group(),
)
self.embedding_method = embedding_method
self.data_parallel_rank = data_parallel_rank
tp_size = get_tp_group().world_size
if self.tp_size % tp_size:
raise ValueError(
"ETP size must be divisible by TP size, but got "
f"ETP={self.tp_size} and TP={tp_size}"
)
self.etp_data_parallel_size = self.tp_size // tp_size
@abstractmethod
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate storage for the complete embedding weight."""
raise NotImplementedError
def dequantize(
self,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
"""Delegate storage-format conversion to the embedding method."""
return self.embedding_method.dequantize(self, embeddings, output_dtype)
def _get_dp_gather_slot(self, local_num_tokens: int) -> tuple[int, int]:
"""Return the per-DP slot size and this rank's slot offset."""
if self.etp_data_parallel_size == 1:
return local_num_tokens, 0
dp_metadata: DPMetadata | None = get_forward_context().dp_metadata
if dp_metadata is None:
raise RuntimeError("ETP spanning DP requires DP token metadata")
group_start = (self.data_parallel_rank // self.etp_data_parallel_size) * (
self.etp_data_parallel_size
)
group_end = group_start + self.etp_data_parallel_size
token_counts = dp_metadata.num_tokens_across_dp_cpu.tolist()
group_counts = token_counts[group_start:group_end]
slot_size = max(group_counts)
dp_rank = get_dp_group().rank_in_group
return slot_size, dp_rank * slot_size
def _gather_dp_ids(
self,
ngram_ids: torch.Tensor,
slot_size: int,
) -> torch.Tensor:
"""Gather DP-local IDs that share one ETP-sharded PLE table."""
if self.etp_data_parallel_size == 1:
return ngram_ids
if ngram_ids.shape[0] < slot_size:
padding = ngram_ids.new_zeros(
slot_size - ngram_ids.shape[0], ngram_ids.shape[1]
)
ngram_ids = torch.cat((ngram_ids, padding), dim=0)
return get_dp_group().all_gather(ngram_ids, dim=0)
def _select_embeddings(
self,
embeddings: torch.Tensor,
local_num_tokens: int,
slot_offset: int,
) -> torch.Tensor:
"""Select this DP rank's rows from the ETP-reduced embeddings."""
if self.etp_data_parallel_size == 1:
return embeddings
return embeddings.narrow(0, slot_offset, local_num_tokens)
@abstractmethod
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Start an asynchronous lookup when supported."""
raise NotImplementedError
class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
"""Quantization interface shared by resident and pinned PLE tables."""
# PLE post-load processing only validates scales in their current storage.
requires_device_loading: bool = False
@staticmethod
def from_quant_config(
quant_config: QuantizationConfig | None,
prefix: str,
embedding_dtype: str | None = None,
) -> "Qwen4ExpPLEEmbeddingMethod":
"""Select the concrete PLE embedding format for a layer."""
if embedding_dtype == "float8_e4m3fn":
return Qwen4ExpPLEFp8EmbeddingMethod()
if quant_config is None:
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if isinstance(quant_config, ModelOptMixedPrecisionConfig):
if quant_config._resolve_quant_algo(prefix) == "FP8":
return Qwen4ExpPLEFp8EmbeddingMethod()
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if isinstance(
quant_config, ModelOptQuantConfigBase
) and quant_config.is_layer_excluded(prefix):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if not isinstance(quant_config, Fp8Config):
raise NotImplementedError(
"Qwen4Exp PLE embedding does not support quantization config "
f"{type(quant_config).__name__}"
)
ignored_layers = quant_config.ignored_layers
if is_layer_skipped(
prefix,
ignored_layers,
quant_config.packed_modules_mapping,
match_mode=quant_config.ignored_layers_match_mode,
):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
# PLE checkpoint shards form one runtime embedding parameter.
shard_prefix = f"{prefix}.shard_"
if any(name.startswith(shard_prefix) for name in ignored_layers):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if not quant_config.is_checkpoint_fp8_serialized:
raise NotImplementedError(
"Qwen4Exp PLE embedding only supports serialized FP8 checkpoints"
)
return Qwen4ExpPLEFp8EmbeddingMethod()
def apply(
self,
layer: nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
raise NotImplementedError("PLE weights only support embedding lookup")
def embedding(self, layer: nn.Module, input_: torch.Tensor) -> torch.Tensor:
return F.embedding(input_, layer.weight)
@abstractmethod
def dequantize(
self,
layer: nn.Module,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
"""Convert looked-up PLE rows to the activation dtype."""
raise NotImplementedError
class Qwen4ExpPLEUnquantizedEmbeddingMethod(Qwen4ExpPLEEmbeddingMethod):
"""Unquantized PLE embedding storage and lookup semantics."""
def create_weights(
self,
layer: Qwen4ExpPLEEmbedding,
input_size_per_partition: int,
output_partition_sizes: list[int],
input_size: int,
output_size: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
) -> None:
del input_size, output_size
weight = nn.Parameter(
layer.allocate_embedding_weight(
sum(output_partition_sizes),
input_size_per_partition,
params_dtype,
),
requires_grad=False,
)
set_weight_attrs(weight, {"input_dim": 1, "output_dim": 0})
set_weight_attrs(weight, extra_weight_attrs)
layer.register_parameter("weight", weight)
def dequantize(
self,
layer: nn.Module,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
del layer, output_dtype
return embeddings
class Qwen4ExpPLEFp8EmbeddingMethod(Qwen4ExpPLEEmbeddingMethod):
"""FP8 PLE embedding with one global checkpoint scale."""
def create_weights(
self,
layer: Qwen4ExpPLEEmbedding,
input_size_per_partition: int,
output_partition_sizes: list[int],
input_size: int,
output_size: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
) -> None:
del input_size, output_size, params_dtype
weight_loader = extra_weight_attrs.get("weight_loader")
weight = ModelWeightParameter(
data=layer.allocate_embedding_weight(
sum(output_partition_sizes),
input_size_per_partition,
torch.float8_e4m3fn,
),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
)
layer.register_parameter("weight", weight)
weight_scale = create_fp8_scale_parameter(
PerTensorScaleParameter,
output_partition_sizes,
input_size_per_partition,
None,
weight_loader,
scale_dtype=torch.float32,
)
layer.register_parameter("weight_scale", weight_scale)
def process_weights_after_loading(self, layer: nn.Module) -> None:
"""Reject FP8 PLE checkpoints without a global scale."""
sentinel = torch.finfo(torch.float32).min
if torch.any(layer.weight_scale == sentinel):
raise ValueError("FP8 PLE checkpoint is missing its global scale")
def dequantize(
self,
layer: nn.Module,
embeddings: torch.Tensor,
output_dtype: torch.dtype,
) -> torch.Tensor:
weight_scale = getattr(layer, "weight_scale", None)
if weight_scale is None:
raise RuntimeError("FP8 PLE embedding is missing its global scale")
if weight_scale.device != embeddings.device:
raise RuntimeError("FP8 PLE embedding scale must be on the output device")
return embeddings.to(output_dtype) * weight_scale.to(output_dtype)
class Qwen4ExpPLEDeviceEmbedding(Qwen4ExpPLEEmbedding):
"""PLE table allocated on the active model device."""
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate the complete PLE weight on the active device."""
return torch.empty(num_embeddings, embedding_dim, dtype=dtype)
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Resident embedding prefetch is a no-op."""
return None
def forward(self, ngram_ids: torch.Tensor) -> torch.Tensor:
"""Gather ETP inputs, look up embeddings, and select local rows."""
slot_size, slot_offset = self._get_dp_gather_slot(ngram_ids.shape[0])
gathered_ids = self._gather_dp_ids(ngram_ids, slot_size)
embeddings = super().forward(gathered_ids)
return self._select_embeddings(
embeddings,
ngram_ids.shape[0],
slot_offset,
)
@triton.jit
def _lookup_ple_embedding_from_pinned_kernel(
weight_ptr,
ids_ptr,
output_ptr,
embedding_dim,
tp_vocab_start,
tp_vocab_end,
BLOCK_D: tl.constexpr,
):
"""Look up TP-owned PLE rows through a CUDA view of pinned host memory."""
row_id = tl.program_id(0)
global_idx = tl.load(ids_ptr + row_id)
in_range = (global_idx >= tp_vocab_start) & (global_idx < tp_vocab_end)
local_idx = tl.where(in_range, global_idx - tp_vocab_start, 0)
offsets = tl.arange(0, BLOCK_D)
store_mask = offsets < embedding_dim
load_mask = store_mask & in_range
values = tl.load(
weight_ptr + local_idx * embedding_dim + offsets,
mask=load_mask,
other=0.0,
)
tl.store(
output_ptr + row_id * embedding_dim + offsets,
values,
mask=store_mask,
)
class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
"""PLE table loaded into pinned CPU memory and looked up through UVA."""
supports_prefetch: ClassVar[bool] = True
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
*,
params_dtype: torch.dtype,
padding_size: int,
prefix: str,
embedding_method: Qwen4ExpPLEEmbeddingMethod,
num_ngram_heads: int = 1,
max_total_tokens: int = 0,
data_parallel_rank: int = 0,
) -> None:
if not is_uva_available():
raise RuntimeError("Engram CPU offload requires UVA support")
super().__init__(
num_embeddings,
embedding_dim,
params_dtype=params_dtype,
padding_size=padding_size,
prefix=prefix,
embedding_method=embedding_method,
num_ngram_heads=num_ngram_heads,
max_total_tokens=max_total_tokens,
data_parallel_rank=data_parallel_rank,
)
self._uva_weight = get_accelerator_view_from_cpu_tensor(self.weight)
self._block_d = triton.next_power_of_2(self.embedding_dim)
self._prefetch_stream = torch.cuda.Stream(device=self._uva_weight.device)
self._prefetch_buffer = torch.empty(
max_total_tokens * self.etp_data_parallel_size,
num_ngram_heads,
self.embedding_dim,
dtype=self.weight.dtype,
device=self._uva_weight.device,
)
self._output_dim = num_ngram_heads * self.embedding_dim
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate the complete PLE weight directly in pinned CPU memory."""
return torch.empty(
num_embeddings,
embedding_dim,
dtype=dtype,
device="cpu",
pin_memory=True,
)
def _lookup(
self,
input_ids: torch.Tensor,
output: torch.Tensor | None = None,
) -> torch.Tensor:
"""Look up local ETP rows while preserving the weight storage dtype."""
expected_shape = (*input_ids.shape, self.embedding_dim)
if output is None:
output = torch.empty(
expected_shape,
dtype=self.weight.dtype,
device=input_ids.device,
)
elif (
tuple(output.shape) != expected_shape
or output.dtype != self.weight.dtype
or output.device != input_ids.device
):
raise ValueError(
"PLE prefetch output must match the input shape, weight dtype, "
"and input device"
)
flat_ids = input_ids.reshape(-1).long()
if flat_ids.numel():
_lookup_ple_embedding_from_pinned_kernel[(flat_ids.numel(),)](
self._uva_weight,
flat_ids,
output,
self.embedding_dim,
self.shard_indices.org_vocab_start_index,
self.shard_indices.org_vocab_end_index,
BLOCK_D=self._block_d,
)
return output
def _reduce_etp_embeddings(self, embeddings: torch.Tensor) -> torch.Tensor:
"""Combine pinned lookup results owned by different ETP ranks."""
if self.tp_size == 1:
return embeddings
assert self.parallel_group is not None
if embeddings.dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
# Each vocabulary row has one owner, so reduce the raw FP8 bytes.
reduced = self.parallel_group.all_reduce(embeddings.view(torch.int8))
return reduced.view(embeddings.dtype)
return self.parallel_group.all_reduce(embeddings)
@eager_break_during_capture
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Gather ETP IDs and launch their UVA lookup on the side stream."""
slot_size, _ = self._get_dp_gather_slot(ngram_ids.shape[0])
gathered_ids = self._gather_dp_ids(ngram_ids, slot_size)
active_output = self._prefetch_buffer[: gathered_ids.shape[0]]
prefetch_stream = self._prefetch_stream
prefetch_stream.wait_stream(torch.cuda.current_stream())
gathered_ids.record_stream(prefetch_stream)
with torch.cuda.stream(prefetch_stream):
self._lookup(gathered_ids, output=active_output)
@eager_break_during_capture
def _finalize_prefetch(
self,
prefetch_output: torch.Tensor,
output: torch.Tensor,
) -> None:
"""Join the side stream, reduce ETP shards, and select local rows."""
torch.cuda.current_stream().wait_stream(self._prefetch_stream)
slot_size, slot_offset = self._get_dp_gather_slot(output.shape[0])
active_output = prefetch_output[: slot_size * self.etp_data_parallel_size]
embeddings = self._reduce_etp_embeddings(active_output)
embeddings = self._select_embeddings(
embeddings,
output.shape[0],
slot_offset,
)
output.copy_(embeddings.flatten(-2))
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Finish the pinned lookup into graph-owned output storage."""
output = self._prefetch_buffer.new_empty(
(hidden_states.shape[0], self._output_dim)
)
self._finalize_prefetch(self._prefetch_buffer, output)
return output
__all__ = [
"Qwen4ExpPLEDeviceEmbedding",
"Qwen4ExpPLEEmbedding",
"Qwen4ExpPLEEmbeddingMethod",
"Qwen4ExpPLEFp8EmbeddingMethod",
"Qwen4ExpPLEPinnedHostEmbedding",
"Qwen4ExpPLEUnquantizedEmbeddingMethod",
"Qwen4ExpNGramEmbedding",
]
class Qwen4ExpNGramEmbedding(nn.Module):
@@ -716,6 +224,12 @@ class Qwen4ExpNGramEmbedding(nn.Module):
max_total_tokens=max_total_tokens,
data_parallel_rank=data_parallel_rank,
)
if self.ngram_embedding.supports_prefetch:
# The side-stream lookup outlives eager-break args, whose
# graph-pool storage later segments may reuse.
self._prefetch_ids = torch.empty(
max_total_tokens, self.ngram_heads, dtype=torch.long
)
weight = self.ngram_embedding.weight
logger.info(
"Initialized PLE embedding %s: quantization_method=%s, "
@@ -864,6 +378,7 @@ class Qwen4ExpNGramEmbedding(nn.Module):
input_ids,
query_start_loc,
ngram_context,
output=self._prefetch_ids[: input_ids.numel()],
)
embedding.start_prefetch(hidden_states, ngram_ids)
@@ -383,6 +383,7 @@ def _prefill_logits(
page_table: torch.Tensor,
query_start_loc: torch.Tensor,
visible_blocks: torch.Tensor,
logits_workspace: torch.Tensor,
max_query_len: int,
logits_width: int,
query_offset: int,
@@ -392,10 +393,14 @@ def _prefill_logits(
assert visible_blocks.shape == (q.shape[0],)
assert 0 <= query_offset <= query_offset + num_queries <= q.shape[0]
assert 0 < logits_width <= page_table.shape[1] * k_cache.shape[1]
assert logits_workspace.is_contiguous()
assert logits_workspace.numel() >= num_queries * logits_width
logits = torch.empty(
(num_queries, logits_width), dtype=torch.float32, device=q.device
# slice from pre-allocated workspace
logits = logits_workspace[: num_queries * logits_width].view(
num_queries, logits_width
)
# tuned on GB300
if k_cache.dtype == torch.float8_e4m3fn:
TILE_R, STAGES, num_warps = 32, 2, 8
@@ -610,8 +615,13 @@ def qsa_select_paged_prefill(
logits_width = min(max(64, logits_width), page_table.shape[1] * k_cache.shape[1])
# chunk the inputs to keep temp logits below VLLM_SPARSE_INDEXER_MAX_LOGITS_MB
# always allocate the worst case to avoid memory fragmentation.
max_logits_bytes = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
rows_per_chunk = max(1, max_logits_bytes // (logits_width * 4))
budget_bytes = max(max_logits_bytes, page_table.shape[1] * k_cache.shape[1] * 4)
logits_workspace = q.new_empty(budget_bytes // 4, dtype=torch.float32)
topk_workspace = torch.empty(
(_TOPK_WORKSPACE_BYTES,), dtype=torch.uint8, device=q.device
)
@@ -625,6 +635,7 @@ def qsa_select_paged_prefill(
page_table,
query_start_loc,
visible_blocks,
logits_workspace,
max_query_len,
logits_width,
query_offset=query_start,
+1 -1
View File
@@ -103,7 +103,7 @@ class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
return "QWEN4_EXP_QSA_TRITON"
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
# QSA consumes manager pages directly and does not use FA4 paged attention.
return [MultipleOf(16)]