Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-03 21:59:03 +07:00
1012 changed files with 61873 additions and 14499 deletions
+97 -36
View File
@@ -12,6 +12,9 @@ from vllm.distributed import get_pp_group
from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.vocab_parallel_embedding import (
VocabParallelEmbedding,
@@ -158,6 +161,12 @@ class DeepseekV32Model(torch.nn.Module):
prefix=f"{prefix}.layers",
)
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
self.layers,
DeepseekV2MoE,
"mlp",
)
if get_pp_group().is_last_rank:
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
else:
@@ -226,7 +235,12 @@ class DeepseekV32Model(torch.nn.Module):
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=self.config.n_routed_experts,
num_experts=self.config.n_routed_experts
+ (
self.config.n_shared_experts
if self.is_fused_shared_expert_enabled
else 0
),
num_redundant_experts=self.num_redundant_experts,
)
@@ -239,6 +253,9 @@ class DeepseekV32Model(torch.nn.Module):
continue
if get_spec_layer_idx_from_weight_name(self.config, name) is not None:
continue
is_fusion_moe_shared_experts_layer = (
self.is_fused_shared_expert_enabled and ("mlp.shared_experts" in name)
)
if _try_load_fp8_indexer_wk(
name,
loaded_weight,
@@ -254,6 +271,8 @@ class DeepseekV32Model(torch.nn.Module):
continue
if ("mlp.experts." in name) and name not in params_dict:
continue
if is_fusion_moe_shared_experts_layer:
continue
name_mapped = name.replace(weight_name, param_name)
if (
param_name == "fused_qkv_a_proj"
@@ -269,43 +288,85 @@ class DeepseekV32Model(torch.nn.Module):
break
else:
is_expert_weight = False
for mapping in expert_params_mapping:
param_name, weight_name, expert_id, shard_id = mapping # type: ignore[assignment]
if weight_name not in name:
continue
is_expert_weight = True
name_mapped = name.replace(weight_name, param_name)
if is_pp_missing_parameter(name_mapped, self):
continue
param = params_dict[name_mapped]
weight_loader = typing.cast(
Callable[..., bool], param.weight_loader
# When AITER fusion_shared_experts is enabled the checkpoint
# provides a single widened shared_experts tensor per layer with
# no expert index. Split it evenly and route the slices into the
# expert slots appended after the routed experts.
num_chunks = 1
if is_fusion_moe_shared_experts_layer:
num_chunks = getattr(self.config, "n_shared_experts", 1) or 1
# gate/up are ColumnParallel (dim 0), down is RowParallel (dim 1).
split_dim = (
1
if ("down_proj.weight" in name and loaded_weight.ndim > 1)
else 0
)
success = weight_loader(
param,
loaded_weight,
name_mapped,
shard_id=shard_id,
expert_id=expert_id,
return_success=True,
total = loaded_weight.shape[split_dim]
assert total % num_chunks == 0, (
f"Shared expert weight dim {total} "
f"not divisible by num_chunks {num_chunks}"
)
if success:
name = name_mapped
break
else:
if is_expert_weight:
continue
if name.endswith(".bias") and name not in params_dict:
continue
name = maybe_remap_kv_scale_name(name, params_dict) # type: ignore[assignment]
if name is None:
continue
if is_pp_missing_parameter(name, self):
continue
param = params_dict[name]
loader = getattr(param, "weight_loader", default_weight_loader)
loader(param, loaded_weight)
loaded_params.add(name)
chunk_size = total // num_chunks
for j in range(num_chunks):
chunk_name = name
weight_to_load = loaded_weight
if is_fusion_moe_shared_experts_layer:
chunk_slice = slice(j * chunk_size, (j + 1) * chunk_size)
if loaded_weight.ndim == 1:
weight_to_load = loaded_weight[chunk_slice]
elif split_dim == 0:
weight_to_load = loaded_weight[chunk_slice, :]
else:
weight_to_load = loaded_weight[:, chunk_slice]
chunk_name = name.replace(
"mlp.shared_experts",
f"mlp.experts.{self.config.n_routed_experts + j}",
)
for mapping in expert_params_mapping:
param_name, weight_name, expert_id, shard_id = mapping # type: ignore[assignment]
if weight_name not in chunk_name:
continue
is_expert_weight = True
name_mapped = chunk_name.replace(weight_name, param_name)
if is_pp_missing_parameter(name_mapped, self):
continue
param = params_dict[name_mapped]
weight_loader = typing.cast(
Callable[..., bool], param.weight_loader
)
success = weight_loader(
param,
weight_to_load,
name_mapped,
shard_id=shard_id,
expert_id=expert_id,
return_success=True,
)
if success:
if not is_fusion_moe_shared_experts_layer:
name = name_mapped
else:
loaded_params.add(name_mapped)
break
else:
if is_expert_weight:
continue
if name.endswith(".bias") and name not in params_dict:
continue
name = maybe_remap_kv_scale_name(name, params_dict) # type: ignore[assignment]
if name is None:
continue
if is_pp_missing_parameter(name, self):
continue
param = params_dict[name]
loader = getattr(param, "weight_loader", default_weight_loader)
loader(param, loaded_weight)
if name is not None and not is_fusion_moe_shared_experts_layer:
loaded_params.add(name)
return loaded_params
+9
View File
@@ -130,6 +130,15 @@ class DeepseekV32MultiTokenPredictor(nn.Module):
if self_attn is not None and hasattr(self_attn, "skip_topk"):
self_attn.skip_topk = skip
def compact_topk_indices(self, slot_ids: torch.Tensor):
"""Gather the top-k index rows at ``slot_ids`` to the front of the buffer."""
num_slots = slot_ids.numel()
for layer in self.layers.values():
self_attn = getattr(layer.mtp_block, "self_attn", None)
if self_attn is not None and hasattr(self_attn, "topk_indices_buffer"):
topk_indices_buffer = self_attn.topk_indices_buffer
topk_indices_buffer[:num_slots] = topk_indices_buffer[slot_ids]
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
+29 -5
View File
@@ -7,7 +7,7 @@ import torch.nn as nn
from transformers import DeepseekV2Config, DeepseekV3Config
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import CacheConfig, VllmConfig
from vllm.config import CacheConfig, CUDAGraphMode, VllmConfig
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.distributed.parallel_state import get_tp_group
from vllm.forward_context import get_forward_context
@@ -84,7 +84,7 @@ class DeepseekV32Indexer(nn.Module):
disable_tp=True,
prefix=f"{prefix}.wk_weights_proj",
)
self.k_norm = LayerNorm(self.head_dim, eps=1e-6)
self.k_norm = LayerNorm(self.head_dim, eps=1e-6, dtype=torch.float32)
self.softmax_scale = self.head_dim**-0.5
self.scale_fmt = "ue8m0"
@@ -283,6 +283,18 @@ class DeepseekV32Attention(MLAAttention):
is_neox_style=not getattr(config, "indexer_rope_interleave", False),
)
def _should_prepare_mqa_query(
self,
attn_metadata: "MLACommonMetadata | None",
cudagraph_runtime_mode: CUDAGraphMode,
) -> bool:
return (
attn_metadata is None
or not self._use_sparse_mha(attn_metadata)
or cudagraph_runtime_mode == CUDAGraphMode.FULL
or torch.cuda.is_current_stream_capturing()
)
def forward( # type: ignore[override]
self,
positions: torch.Tensor,
@@ -321,6 +333,9 @@ class DeepseekV32Attention(MLAAttention):
layer_attn_metadata, _, _, _ = get_attention_context(self.layer_name)
self.impl.prepare_for_batch(layer_attn_metadata)
prepare_mqa_query = self._should_prepare_mqa_query(
layer_attn_metadata, forward_context.cudagraph_runtime_mode
)
if self.indexer is not None and not self.skip_topk:
has_indexer = True
indexer_k_norm_w = self.indexer.k_norm.weight
@@ -404,7 +419,10 @@ class DeepseekV32Attention(MLAAttention):
q = self.q_b_proj(q_c)[0].view(-1, self.num_local_heads, self.qk_head_dim)
q_nope, q_pe = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
ql_nope = torch.bmm(q_nope.transpose(0, 1), self.W_UK_T).transpose(0, 1)
if prepare_mqa_query:
ql_nope = torch.bmm(q_nope.transpose(0, 1), self.W_UK_T).transpose(0, 1)
else:
ql_nope = q_nope
if self.indexer is not None and not self.skip_topk:
index_q = self.indexer.wq_b(q_c)[0]
@@ -425,7 +443,7 @@ class DeepseekV32Attention(MLAAttention):
indexer_n_head_scale,
has_indexer=has_indexer,
index_rope_interleave=self._index_rope_interleave,
quantize_mqa=self._fp8_query,
quantize_mqa=self._fp8_query and prepare_mqa_query,
)
self._sparse_indexer_and_attn(
@@ -482,6 +500,7 @@ class DeepseekV32Attention(MLAAttention):
self.topk_indices_buffer,
skip_k_cache_insert=not self.use_pcp,
use_pcp=self.use_pcp,
pcp_shard_decode_requests=self.pcp_shard_decode_requests,
dense_mha_metadata_layer_name=self._dense_mha_metadata_layer_name,
dcp_rank=(
self.dcp_manager.group.rank_in_group
@@ -517,6 +536,7 @@ class DeepseekV32Attention(MLAAttention):
layer_slot_mapping,
attn_metadata.num_decode_tokens,
True,
pcp_shard_decode_requests=self.pcp_shard_decode_requests,
)
)
self.impl.do_kv_cache_update( # type: ignore[attr-defined]
@@ -535,7 +555,11 @@ class DeepseekV32Attention(MLAAttention):
if self._use_sparse_mha(attn_metadata):
assert kv_c is not None and k_pe is not None
mha_q_pe = self.rotary_emb(positions, q_pe)[0] if self._fp8_query else mqa_q
mha_q_pe = (
self.rotary_emb(positions, q_pe)[0]
if mqa_q.dtype != q_pe.dtype
else mqa_q
)
mha_q = torch.cat((q_nope, mha_q_pe), dim=-1)
self.forward_impl(
mha_q,
@@ -1052,6 +1052,7 @@ def fused_q(
index_weights_out,
has_indexer=has_indexer,
index_rope_interleave=index_rope_interleave,
quantize_mqa=quantize_mqa,
)
return index_q_fp8, index_weights_out, mqa_q
@@ -35,10 +35,12 @@ def is_fused_q_cutedsl_supported(
) -> bool:
if not (
current_platform.has_device_capability(100)
and quantize_mqa
and q_pe.dtype == ql_nope.dtype == torch.bfloat16
and q_pe.dtype == torch.bfloat16
and q_pe.shape[-1] == 64
and ql_nope.shape[-1] == 512
and (
not quantize_mqa
or (ql_nope.dtype == torch.bfloat16 and ql_nope.shape[-1] == 512)
)
# One warp per head group; a non-multiple would trip the kernel's own
# assert instead of falling back to Triton.
and q_pe.shape[1] % 4 == 0
@@ -68,9 +70,10 @@ def fused_q_cutedsl(
idx_weights_out: torch.Tensor,
has_indexer: bool = True,
index_rope_interleave: bool = True,
quantize_mqa: bool = True,
) -> None:
_, num_heads, rope_dim = q_pe.shape
_, _, nope_dim = ql_nope.shape
nope_dim = ql_nope.shape[-1] if quantize_mqa else 0
_, num_idx_heads, idx_dim = idx_q.shape
if has_indexer:
@@ -98,8 +101,8 @@ def fused_q_cutedsl(
positions,
q_pe,
rope_cache,
ql_nope,
q_scale.view(1),
ql_nope if quantize_mqa else None,
q_scale.view(1) if quantize_mqa else None,
mqa_output,
idx_q,
idx_rope_cache,
@@ -121,7 +124,7 @@ class FusedQKernel:
index_rope_interleave: bool,
) -> None:
assert rope_dim == 64
assert nope_dim == 512
assert nope_dim in (0, 512)
assert idx_dim in (128, 0)
self.rope_dim = rope_dim
@@ -262,6 +265,17 @@ class FusedQKernel:
cute.arch.griddepcontrol_wait()
pos = positions[token_id]
# no need to do Q calculation for MHA
if cutlass.const_expr(self.nope_dim == 0):
q0, q1 = cvt.bf16x2_to_fp32x2(
cute.recast_tensor(q_pe, Uint32)[token_id, head_id, lane_id]
)
cos = q_pe_rope_cache[pos, lane_id].to(Float32)
sin = q_pe_rope_cache[pos, 32 + lane_id].to(Float32)
result = cvt.fp32x2_to_bf16x2(q0 * cos - q1 * sin, q1 * cos + q0 * sin)
cute.arch.griddepcontrol_launch_dependents()
cute.recast_tensor(mqa_output, Uint32)[token_id, head_id, lane_id] = result
return
inv_scale = 1.0 / q_scale[0]
cp_op = cute.nvgpu.CopyUniversalOp()
@@ -479,12 +493,16 @@ class FusedQKernel:
BFloat16, (num_tokens, num_heads, rope_dim), divisibility=16
)
rope_cache = _make_fake_tensor(rope_type, (max_pos, rope_dim), divisibility=8)
ql_nope = _make_fake_tensor(
BFloat16, (num_tokens, num_heads, nope_dim), divisibility=16
ql_nope = (
_make_fake_tensor(
BFloat16, (num_tokens, num_heads, nope_dim), divisibility=16
)
if nope_dim
else None
)
q_scale = _make_fake_tensor(Float32, (1,), divisibility=4)
q_scale = _make_fake_tensor(Float32, (1,), divisibility=4) if nope_dim else None
mqa_output = _make_fake_tensor(
Float8E4M3FN,
Float8E4M3FN if nope_dim else BFloat16,
(num_tokens, num_heads, nope_dim + rope_dim),
divisibility=16,
)
+11 -16
View File
@@ -1426,7 +1426,6 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
swa_only = attn_metadata is None
num_prefills = swa_metadata.num_prefills
num_prefill_tokens = swa_metadata.num_prefill_tokens
num_decodes = swa_metadata.num_decodes
num_decode_tokens = swa_metadata.num_decode_tokens
@@ -1458,26 +1457,22 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
topk_indices = attn_metadata.c128a_prefill_topk_indices
assert topk_indices is not None
top_k = topk_indices.shape[-1]
N = (self.max_model_len + self.compress_ratio - 1) // self.compress_ratio
else:
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[num_decode_tokens:]
top_k = 0
N = 0
M = N + self.window_size + self.max_num_batched_tokens
num_chunks = (num_prefills + self.PREFILL_CHUNK_SIZE - 1) // (
self.PREFILL_CHUNK_SIZE
chunk_plan = swa_metadata.get_prefill_chunk_plan(
compress_ratio=self.compress_ratio,
prefill_chunk_size=self.PREFILL_CHUNK_SIZE,
)
assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0"
workspace_manager = current_workspace_manager()
kv = workspace_manager.get_simultaneous(
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
)[0]
for chunk_idx in range(num_chunks):
chunk_start = chunk_idx * self.PREFILL_CHUNK_SIZE
chunk_end = min(chunk_start + self.PREFILL_CHUNK_SIZE, num_prefills)
for chunk_start, chunk_end, chunk_N, chunk_M in chunk_plan:
chunk_size = chunk_end - chunk_start
kv = workspace_manager.get_simultaneous(
((chunk_size, chunk_M, q.shape[-1]), torch.bfloat16),
)[0]
if not swa_only:
assert attn_metadata is not None
assert compressed_k_cache is not None
@@ -1502,7 +1497,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
gather_lens=gather_lens[chunk_start:chunk_end],
block_table=swa_block_table[chunk_start:chunk_end],
block_size=swa_metadata.block_size,
offset=N,
offset=chunk_N,
use_fnuz=current_platform.is_fp8_fnuz(),
)
@@ -1523,8 +1518,8 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
self.window_size,
self.compress_ratio,
top_k,
M,
N,
chunk_M,
chunk_N,
max_image_tokens=self.max_image_tokens,
left_visible=(
left_visible[query_start:query_end]
+2
View File
@@ -865,6 +865,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
return MLAAttentionSpec(
block_size=vllm_config.cache_config.block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=self.head_dim,
dtype=torch.uint8 if uses_fp8_ds_mla_layout else self.kv_cache_torch_dtype,
tokens_per_state=self.compress_ratio,
@@ -910,6 +911,7 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
return MLAAttentionSpec(
block_size=self.cache_config.block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=self.head_dim,
dtype=self.dtype,
tokens_per_state=self.compress_ratio,
@@ -354,15 +354,34 @@ class DeepseekV4VLProcessingInfo(BaseProcessingInfo):
hf_config = self.get_hf_config()
patch_size = hf_config.vision_patch_size
downsample_ratio = hf_config.vision_downsample_ratio
# A square maximizes the ViT patch count (area) within the token
# budget; solve the budget-derived size directly to keep the dummy
# image small.
max_wh_ratio = hf_config.vision_max_wh_ratio
# Every aligner row costs an extra IMAGE_NEW_LINE token, so height is
# more expensive than width and a square is *not* optimal: search the
# LLM grids that fit the budget for the one with the most ViT patches
# (ties broken by the longer sentinel block).
budget = hf_config.vision_max_n_token - (COMPRESS_PAD_TO - 1)
side = budget * patch_size * downsample_ratio
_, _, best_h, best_w, _ = solve_resize_ratio(
side, side, patch_size, downsample_ratio, budget
)
return ImageSize(width=best_w, height=best_h)
step = patch_size * downsample_ratio
best_grid = (1, 1)
best_key = (0, 0)
for n_llm_h in range(1, budget):
if (
grid_tokens(n_llm_h * step, step, patch_size, downsample_ratio)[2]
> budget
):
break
for n_llm_w in range(1, budget):
if max_wh_ratio is not None and n_llm_w > n_llm_h * max_wh_ratio:
break
num_tokens = grid_tokens(
n_llm_h * step, n_llm_w * step, patch_size, downsample_ratio
)[2]
if num_tokens > budget:
break
key = (n_llm_h * n_llm_w, num_tokens)
if key > best_key:
best_key, best_grid = key, (n_llm_h, n_llm_w)
n_llm_h, n_llm_w = best_grid
return ImageSize(width=n_llm_w * step, height=n_llm_h * step)
class DeepseekV4VLDummyInputsBuilder(
+1
View File
@@ -184,6 +184,7 @@ class CompressorStateCache(torch.nn.Module, AttentionLayerBase):
return SlidingWindowMLASpec( # only has one vector instead of K + V
block_size=self.block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=self.state_dim,
dtype=self.dtype,
sliding_window=self.sliding_window,
+1 -5
View File
@@ -65,13 +65,9 @@ from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.worker.ubatching import dbo_current_ubatch_id
from ..common.engram import EngramLayout, NgramHashState
from ..common.engram import Engram, EngramLayout, NgramHashState
from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask
# Engram host offload and its prefetch stream are neither ROCm- nor
# NVIDIA-specific, so they are imported rather than duplicated.
from ..nvidia.engram import Engram
if typing.TYPE_CHECKING:
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
+160 -11
View File
@@ -2,8 +2,9 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
from collections.abc import Callable
from dataclasses import dataclass
from typing import cast
from typing import Any, cast
import torch
@@ -15,8 +16,14 @@ 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.model_executor.layers.rocm_paged_mxfp4_indexer import (
RocmSparseAttnIndexer,
RocmSparseMQAIndexer,
)
from vllm.models.deepseek_v41.attention import (
DeepseekV4Attention,
DeepseekV4Indexer,
DeepseekV4IndexerCache,
_replace_layer_index,
)
from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
@@ -32,6 +39,7 @@ from vllm.triton_utils import tl, triton
from vllm.utils.multi_stream_utils import execute_in_parallel
from vllm.v1.attention.backend import (
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.mla.sparse_swa import (
DeepseekSparseSWABackend,
@@ -47,6 +55,9 @@ from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_sparse_attn_decode,
rocm_sparse_attn_prefill,
)
from vllm.v1.attention.ops.rocm_paged_mxfp4_indexer import (
rocm_paged_mxfp4_cache_layout,
)
from vllm.v1.worker.workspace import current_workspace_manager
logger = init_logger(__name__)
@@ -517,11 +528,141 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBu
)
@functools.cache
def _aiter_indexer_cache_ops() -> tuple[Callable[..., None], Callable[..., tuple]]:
"""The aiter indexer key writer and query quantizer."""
from aiter.ops.triton.fusions.k_norm_rope_mxfp4_cache import (
k_norm_rope_mxfp4_cache,
)
from aiter.ops.triton.rope.q_rope_mxfp4_quant import q_rope_mxfp4_quant
return k_norm_rope_mxfp4_cache, q_rope_mxfp4_quant
def rocm_mxfp4_indexer_k_store(
k_pre: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
rms_norm_weight: torch.Tensor,
rms_norm_eps: float,
k_cache: torch.Tensor,
kv_slot_mapping: torch.Tensor,
compress_ratio: int,
use_fp4_cache: bool,
*,
num_heads: int,
) -> None:
"""`indexer_k_norm_rope_store` for the ROCm MXFP4 cache: aiter's cache op
writes the key in the order its MQA-logits kernel reads with ``num_heads``
query heads."""
assert use_fp4_cache, "the ROCm indexer cache op writes MXFP4 only"
layout = rocm_paged_mxfp4_cache_layout(num_heads, k_pre.shape[1], k_cache.shape[1])
k_norm_rope_mxfp4_cache, _ = _aiter_indexer_cache_ops()
k_norm_rope_mxfp4_cache(
k_pre,
positions,
cos_sin_cache,
rms_norm_weight,
rms_norm_eps,
k_cache,
kv_slot_mapping,
compress_ratio,
shuffle=layout,
)
def rocm_mxfp4_indexer_q_quant(
positions: torch.Tensor,
index_q: torch.Tensor,
index_q_cos_sin_cache: torch.Tensor,
index_weights: torch.Tensor,
index_weights_softmax_scale: float,
index_weights_head_scale: float,
use_fp4: bool = True,
weights_out_dtype: torch.dtype = torch.float32,
) -> tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
"""`fused_indexer_q_rope_quant` for the ROCm MXFP4 indexer, on aiter's op:
((packed [T, H, D // 2], e8m0 as one int32 per head [T, H]), fp32
weights)."""
assert use_fp4 and weights_out_dtype == torch.float32, (
"the ROCm indexer quantizes Q to MXFP4 and scores with fp32 weights"
)
_, q_rope_mxfp4_quant = _aiter_indexer_cache_ops()
q_packed, q_scale, weights_out = q_rope_mxfp4_quant(
index_q,
positions,
index_q_cos_sin_cache,
index_weights,
index_weights_softmax_scale * index_weights_head_scale,
)
return (q_packed, q_scale.view(torch.int32).squeeze(-1)), weights_out
class DeepseekV41RocmMxfp4Indexer(DeepseekV4Indexer):
"""The indexer on aiter's paged MXFP4 cache: its K store and Q quant write
in the order aiter's MQA-logits kernel reads, and its layers score with it.
``_produce_k`` and ``forward_q`` mirror ``DeepseekV4Indexer``'s except for
those two calls."""
mqa_cls = RocmSparseMQAIndexer
attn_cls = RocmSparseAttnIndexer
def _produce_k(
self,
latent: torch.Tensor | None,
positions: torch.Tensor,
rotary_emb: torch.nn.Module,
) -> None:
attn_metadata = get_forward_context().attn_metadata
if not isinstance(attn_metadata, dict) or latent is None:
return
assert self.owns_k
indexer_metadata = cast(Any, attn_metadata[self.k_cache.prefix])
k_pre, _ = self.wk(latent)
rocm_mxfp4_indexer_k_store(
k_pre,
positions,
rotary_emb.cos_sin_cache,
self.k_norm.weight,
self.k_norm.variance_epsilon,
self.k_cache.kv_cache,
indexer_metadata.slot_mapping,
self.compress_ratio,
self.use_fp4_kv,
num_heads=self.n_head,
)
def forward_q(
self,
qr: torch.Tensor | QuantizedActivation,
qr_scale: torch.Tensor | None,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
rotary_emb: torch.nn.Module,
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
q = self._wq_b_proj(qr, qr_scale).view(-1, self.n_head, self.head_dim)
(q, q_scale), weights = rocm_mxfp4_indexer_q_quant(
positions,
q,
rotary_emb.cos_sin_cache,
indexer_weights,
self.softmax_scale,
self.n_head**-0.5,
use_fp4=self.use_fp4_kv,
weights_out_dtype=self.indexer_weights_dtype,
)
return q, q_scale, weights
class DeepseekV4ROCMAiterMLASparseBackend(DeepseekV4SparseMLABackend):
@staticmethod
def get_name() -> str:
return "ROCM_FLASHMLA_SPARSE_DSV4"
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [64, 128]
@staticmethod
def get_builder_cls() -> type[DeepseekV4SparseMLAMetadataBuilder]:
return DeepseekV4SparseMLAMetadataBuilder
@@ -540,6 +681,13 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
swa_backend_cls = DeepseekV41ROCMAiterSparseSWABackend
_use_aiter_sparse_mla = False
def _indexer_cls(
self, k_cache: DeepseekV4IndexerCache | None
) -> type[DeepseekV4Indexer]:
if k_cache is not None and k_cache.rocm_mxfp4:
return DeepseekV41RocmMxfp4Indexer
return super()._indexer_cls(k_cache)
def __init__(self, *args, **kwargs):
vllm_config = args[0] if args else kwargs["vllm_config"]
super().__init__(*args, **kwargs)
@@ -1231,7 +1379,6 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
swa_only = attn_metadata is None
num_prefills = swa_metadata.num_prefills
num_prefill_tokens = swa_metadata.num_prefill_tokens
num_decodes = swa_metadata.num_decodes
num_decode_tokens = swa_metadata.num_decode_tokens
@@ -1260,21 +1407,23 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
N = 0
M = N + self.window_size + self.max_num_batched_tokens
num_chunks = (num_prefills + self.PREFILL_CHUNK_SIZE - 1) // (
self.PREFILL_CHUNK_SIZE
chunk_plan = swa_metadata.get_prefill_chunk_plan(
compress_ratio=self.compress_ratio,
prefill_chunk_size=self.PREFILL_CHUNK_SIZE,
has_compressed=not swa_only,
)
assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0"
workspace = current_workspace_manager().get_simultaneous(
*self._prefill_workspace_shapes(M, num_prefill_tokens, q)
)
kv = workspace[0]
kv_rows = workspace[0].view(-1, q.shape[-1])
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)
for chunk_start, chunk_end, chunk_N, chunk_M in chunk_plan:
chunk_size = chunk_end - chunk_start
kv = kv_rows[: chunk_size * chunk_M].view(chunk_size, chunk_M, -1)
if not swa_only:
assert attn_metadata is not None
assert compressed_k_cache is not None
@@ -1299,7 +1448,7 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
gather_lens=gather_lens[chunk_start:chunk_end],
block_table=swa_block_table[chunk_start:chunk_end],
block_size=swa_metadata.block_size,
offset=N,
offset=chunk_N,
use_fnuz=current_platform.is_fp8_fnuz(),
)
@@ -1320,8 +1469,8 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
self.window_size,
self.compress_ratio,
top_k,
M,
N,
chunk_M,
chunk_N,
)
rocm_sparse_attn_prefill(
q=q[query_start:query_end],
+34 -6
View File
@@ -35,6 +35,9 @@ from vllm.models.deepseek_v41.common.ops import (
if TYPE_CHECKING:
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import GemmRsAr
from vllm.model_executor.layers.rocm_paged_mxfp4_indexer import (
RocmSparseMQAIndexer,
)
from vllm.v1.attention.backends.mla.sparse_swa import (
DeepseekSparseSWAMetadata,
)
@@ -261,6 +264,13 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
"""Return whether this instance stores fp8 KV in fp8_ds_mla layout."""
return self.use_fp8_ds_mla_layout
def _indexer_cls(
self, k_cache: "DeepseekV4IndexerCache | None"
) -> type["DeepseekV4Indexer"]:
"""The indexer for this layer's index K cache. A platform subclass
returns one that writes and scores its own cache layout."""
return DeepseekV4Indexer
def __init__(
self,
vllm_config: VllmConfig,
@@ -449,7 +459,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
)
is_candidate_source = layer_id == self.candidate_source_layer
uses_candidates = 0 <= self.candidate_source_layer < layer_id
self.indexer = DeepseekV4Indexer(
self.indexer = self._indexer_cls(index_k_cache)(
vllm_config,
config=config,
hidden_size=self.hidden_size,
@@ -1152,6 +1162,10 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
self.compress_ratio = compress_ratio
vllm_config = get_current_vllm_config()
self.sparse_logits = vllm_config.attention_config.indexer_sparse_logits
# aiter's paged MXFP4 kernels write this cache and read it in place.
self.rocm_mxfp4 = current_platform.is_rocm() and dsa_indexer_uses_fp4(
vllm_config
)
compilation_config = vllm_config.compilation_config
if prefix in compilation_config.static_forward_context:
raise ValueError(f"Duplicate layer name: {prefix}")
@@ -1190,13 +1204,21 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
# it 512B-aligned; the main KV record read from the same blocks
# needs its own TMA stride, so keep both.
block_stride_alignment=(
math.lcm(512, page_alignment) if self.sparse_logits else None
math.lcm(512, page_alignment)
if self.sparse_logits and not self.rocm_mxfp4
else None
),
)
def forward(self): ...
def get_attn_backend(self) -> type[AttentionBackend]:
if self.rocm_mxfp4:
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
DeepseekV41RocmMxfp4IndexerBackend,
)
return DeepseekV41RocmMxfp4IndexerBackend
if self.sparse_logits:
return DeepseekV41SparseIndexerBackend
return DeepseekV41IndexerBackend
@@ -1218,6 +1240,12 @@ class DeepseekV4Indexer(nn.Module):
later indexers mask their scores to those blocks before their own top-k.
"""
# The scoring layers; a platform subclass swaps in its own.
mqa_cls: ClassVar[type["SparseMQAIndexer | RocmSparseMQAIndexer"]] = (
SparseMQAIndexer
)
attn_cls: ClassVar[type[SparseAttnIndexer]] = SparseAttnIndexer
def __init__(
self,
vllm_config: VllmConfig,
@@ -1305,7 +1333,7 @@ class DeepseekV4Indexer(nn.Module):
and candidate_block_buffer is not None
and not candidate_write
)
self.indexer_op: SparseAttnIndexer | SparseMQAIndexer
self.indexer_op: SparseAttnIndexer | SparseMQAIndexer | RocmSparseMQAIndexer
if use_sparse_logits:
if not self.use_fp4_kv:
raise ValueError(
@@ -1314,7 +1342,7 @@ class DeepseekV4Indexer(nn.Module):
)
assert candidate_block_buffer is not None
assert topk_indices_buffer is not None
self.indexer_op = SparseMQAIndexer(
self.indexer_op = self.mqa_cls(
self.k_cache,
self.topk_tokens,
self.head_dim,
@@ -1324,7 +1352,7 @@ class DeepseekV4Indexer(nn.Module):
candidate_block_size,
)
else:
self.indexer_op = SparseAttnIndexer(
self.indexer_op = self.attn_cls(
self.k_cache,
self.quant_block_size,
self.scale_fmt,
@@ -1343,7 +1371,7 @@ class DeepseekV4Indexer(nn.Module):
# The fused Q kernel writes the per-head weights in the dtype the
# scoring kernels take, so no cast runs per step.
self.indexer_weights_dtype = (
SparseMQAIndexer.weights_dtype if use_sparse_logits else torch.float32
self.mqa_cls.weights_dtype if use_sparse_logits else torch.float32
)
def _produce_k(
+499 -22
View File
@@ -34,23 +34,41 @@ chunk-by-chunk while an n-gram at position ``p`` needs the token ids at
cache for the rest.
"""
import ctypes
import mmap
import os
import tempfile
import weakref
from contextlib import ExitStack
import numpy as np
import torch
from torch import nn
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import VllmConfig, get_current_vllm_config
from vllm.distributed import (
get_dp_group,
get_engram_dp_group,
get_engram_dp_size,
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
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, is_forward_context_available
from vllm.logger import init_logger
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.platforms import current_platform
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
logger = init_logger(__name__)
@@ -58,6 +76,18 @@ logger = init_logger(__name__)
DEAD_ID = -1
def _engram_lookup_thresholds(device: torch.device) -> tuple[int | None, int | None]:
"""Host lookup thresholds on `device`: the rows from which to sort, and the
tokens (max over DP ranks) from which to run inline. None disables that path."""
if current_platform.is_cuda() and current_platform.is_device_capability_family(
100, device.index or 0
):
# Measured on GB200.
return 36864, 4096
# TODO: Add hand-tuned thresholds for other GPU families.
return None, None
def _is_prime(n: int) -> bool:
"""Deterministic Miller-Rabin for n < 2**32 (avoids a sympy import)."""
if n < 2:
@@ -575,6 +605,15 @@ def _engram_head_shard_weight_loader(
param.data.copy_(shard)
# Branching on SORTED at runtime intermittently crashes Triton 3.8's
# RemoveLayoutConversions.
# TODO: Remove the 3.8 check once Triton ships
# https://github.com/triton-lang/triton/pull/10706.
_SORTED_IS_CONSTEXPR = tl.constexpr(
triton.__version__.startswith("3.8") and current_platform.is_rocm()
)
@triton.jit(
do_not_specialize=[
"vocab_start",
@@ -583,12 +622,14 @@ def _engram_head_shard_weight_loader(
"ids_stride_t",
"ids_stride_h",
"GRID",
*(() if _SORTED_IS_CONSTEXPR else ("SORTED",)),
]
)
def _engram_lookup_kernel(
weight,
scales,
ids,
sorted_dst,
out,
vocab_start,
vocab_end,
@@ -602,27 +643,37 @@ def _engram_lookup_kernel(
QUANT_BLOCK: tl.constexpr,
BLOCK_R: tl.constexpr,
GRID,
SORTED: tl.constexpr if _SORTED_IS_CONSTEXPR else None, # type: ignore[valid-type]
):
"""Gather fp8 rows, apply their ue8m0 block scales, write bf16.
Only this rank's heads are read; padded heads write zeros for all-gather.
`weight`/`scales` may address pinned host memory through UVA.
`weight`/`scales` may address pinned host memory through UVA. If SORTED,
`ids` holds rows relative to vocab_start in table order and `sorted_dst`
their output rows.
"""
cols = tl.arange(0, DIM)
scale_cols = cols // QUANT_BLOCK
for base in tl.range(tl.program_id(0) * BLOCK_R, num_rows, GRID * BLOCK_R):
rows = base + tl.arange(0, BLOCK_R)
valid = rows < num_rows
head = HEAD_START + rows % LOCAL_HEADS
token = (rows // LOCAL_HEADS).to(tl.int64)
index = tl.load(
ids + token * ids_stride_t + head * ids_stride_h,
mask=valid & (head < TOTAL_HEADS),
other=-1,
).to(tl.int64)
owned = valid & (head < TOTAL_HEADS)
owned &= (index >= vocab_start) & (index < vocab_end)
local = tl.where(owned, index - vocab_start, 0)
if SORTED:
local = tl.load(ids + rows, mask=valid, other=-1).to(tl.int64)
dst = tl.load(sorted_dst + rows, mask=valid, other=0).to(tl.int32)
owned = (local >= 0) & (local < vocab_end - vocab_start)
else:
head = HEAD_START + rows % LOCAL_HEADS
token = (rows // LOCAL_HEADS).to(tl.int64)
index = tl.load(
ids + token * ids_stride_t + head * ids_stride_h,
mask=valid & (head < TOTAL_HEADS),
other=-1,
).to(tl.int64)
dst = rows
owned = valid & (head < TOTAL_HEADS)
owned &= (index >= vocab_start) & (index < vocab_end)
local = index - vocab_start
local = tl.where(owned, local, 0)
values = tl.load(
weight + local[:, None] * DIM + cols[None, :],
mask=owned[:, None],
@@ -636,16 +687,240 @@ def _engram_lookup_kernel(
# ue8m0 is a power of two, so its byte *is* the fp32 exponent field.
scale = (scale.to(tl.int32) << 23).to(tl.float32, bitcast=True)
tl.store(
out + rows[:, None] * DIM + cols[None, :],
out + dst[:, None] * DIM + cols[None, :],
(values.to(tl.float32) * scale).to(tl.bfloat16),
mask=valid[:, None],
)
def engram_head_shard_rank() -> int:
"""This rank's slot among the hash-head shards of one engram table.
TP-major, so the shards a DP gather brings in are contiguous heads and
the following TP gather completes the head order.
"""
dp_group = get_engram_dp_group()
dp_size = dp_group.world_size if dp_group is not None else 1
dp_rank = dp_group.rank_in_group if dp_group is not None else 0
return get_tensor_model_parallel_rank() * dp_size + dp_rank
def engram_gathered_num_tokens() -> int:
"""Per-replica token slot for the node-local Engram DP group."""
dp_metadata = get_forward_context().dp_metadata
if dp_metadata is None:
raise RuntimeError("a DP-shared engram table needs DP token metadata")
group = get_engram_dp_group()
assert group is not None
# Engram groups are contiguous slices of the full DP group.
start = get_dp_group().rank_in_group - group.rank_in_group
return int(
dp_metadata.num_tokens_across_dp_cpu[start : start + group.world_size].max()
)
def gather_engram_hashes(
hash_ids: torch.Tensor, *, dp_shared_memory: bool = False
) -> torch.Tensor:
"""Collect the n-gram ids of every DP replica sharing one table.
Replicas are padded to a common token slot, so the gathered shape is
static under CUDA graph capture (where DP already pads alike).
"""
dp_group = get_engram_dp_group()
if dp_group is None or dp_shared_memory:
return hash_ids
slot = engram_gathered_num_tokens()
if hash_ids.shape[0] > slot:
raise ValueError("Engram token count exceeds the DP token slot")
if hash_ids.shape[0] < slot:
pad = hash_ids.new_full(
(slot - hash_ids.shape[0], *hash_ids.shape[1:]), DEAD_ID
)
hash_ids = torch.cat((hash_ids, pad))
return dp_group.all_gather(hash_ids, dim=0)
class DPSharedEngramStorage:
"""Registered host weights shared by a node-local DP group with one writer."""
def __init__(
self, num_rows: int, dim: int, block_size: int, group: GroupCoordinator
) -> None:
self.group = group
weight_bytes = num_rows * dim
storage = self._allocate(weight_bytes + weight_bytes // block_size)
self.weight = storage[:weight_bytes].view(torch.float8_e4m3fn).view(-1, dim)
self.weight_scale_inv = storage[weight_bytes:].view(-1, dim // block_size)
self._views: tuple[torch.Tensor, torch.Tensor] | None = None
def _allocate(self, num_bytes: int) -> torch.Tensor:
"""Map and register one physical allocation across a node-local DP group."""
group = self.group
with ExitStack() as stack:
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=SHM_PATH)
)
backing_file.truncate(num_bytes)
path = backing_file.name
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
path, error = group.broadcast_object((path, error))
if error is not None:
raise RuntimeError(
"Engram shared-memory creation failed on EDP rank 0: " + error
)
mapping = owner = tensor = None
try:
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(
"cudaHostRegister did not pin the shared Engram mapping"
)
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:
# Torch storage retains the numpy owner, including through cached UVA views.
# Keep its mmap alive until CUDA has released the registration.
result = torch.cuda.cudart().cudaHostUnregister(pointer)
if result.value != 0:
logger.warning("Engram cudaHostUnregister failed: %s", result)
def load_weight(
self, param: torch.nn.Parameter, loaded_weight: torch.Tensor
) -> None:
if self.group.rank_in_group == 0:
_engram_head_shard_weight_loader(param, loaded_weight)
# Read order may differ across ranks. Equal load counts ensure all shared
# weights are ready after the last weight-loader call returns.
torch.distributed.barrier(group=self.group.cpu_group)
def get_views(
self, weight: torch.Tensor, scales: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
if (weight.data_ptr(), scales.data_ptr()) != (
self.weight.data_ptr(),
self.weight_scale_inv.data_ptr(),
):
raise RuntimeError("Shared Engram parameter storage must not be replaced")
if self._views is None:
self._views = (
get_accelerator_view_from_cpu_tensor(self.weight),
get_accelerator_view_from_cpu_tensor(self.weight_scale_inv),
)
return self._views
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 get_engram_dp_size() == 1:
logger.warning_once(
"Engram DP replicas are not co-located on one node; "
"storing the offloaded tables per rank instead of sharing them."
)
return False
num_bytes = sum(layout.num_embeddings) * (
layout.head_dim + layout.head_dim // block_size
)
group = get_engram_dp_group()
assert group is not None
# Only the leader allocates, so every replica follows its check.
error = None
if group.rank_in_group == 0:
if not os.path.isdir(SHM_PATH):
error = f"{SHM_PATH} is not mounted"
else:
try:
check_shm_free_space(num_bytes, allocation_name="Engram tables")
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
error = group.broadcast_object(error)
if error is not None:
logger.warning_once(
"Sharding the offloaded Engram tables across DP replicas: %s", error
)
return error is None
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
class ParallelEngramEmbedding(nn.Module):
"""TP-sharded hash heads with FP8 rows and per-block E8M0 scales."""
"""Hash heads with FP8 rows and per-block E8M0 scales.
Heads are TP-sharded, and additionally DP-sharded across a node-local
group unless the table lives in (DP-shared) pinned host memory.
"""
_weight_loader = staticmethod(_engram_head_shard_weight_loader)
_shared_memory: DPSharedEngramStorage | None = None
_packed: torch.Tensor | None = None
def __init__(
self,
@@ -653,10 +928,32 @@ class ParallelEngramEmbedding(nn.Module):
dim: int,
head_sizes: tuple[int, ...],
block_size: int = 32,
cpu_offload: bool = False,
dp_shared_memory: bool = False,
use_thp: bool = False,
) -> None:
super().__init__()
assert head_sizes and all(size > 0 for size in head_sizes)
assert sum(head_sizes) <= num_embeddings
self.cpu_offload = cpu_offload
self.dp_shared_memory = dp_shared_memory
self.use_thp = use_thp
self.dp_size = get_engram_dp_size()
if dp_shared_memory:
if not cpu_offload:
raise ValueError("dp_shared_memory requires cpu_offload=True")
if self.dp_size <= 1:
raise ValueError(
"dp_shared_memory requires a node-local Engram DP "
f"group with size > 1; effective Engram DP size is {self.dp_size}. "
"Check that the node layout and rank placement allow complete "
"DP replicas to be co-located."
)
self.dp_size = 1
if cpu_offload and not is_uva_available():
raise RuntimeError("Engram CPU offload requires UVA support")
self._views: tuple[torch.Tensor, torch.Tensor] | None = None
self._view_src: tuple[int, int] | None = None
self.num_embeddings = num_embeddings
self.dim = dim
self.block_size = block_size
@@ -688,20 +985,99 @@ class ParallelEngramEmbedding(nn.Module):
"engram_vocab_start": self.vocab_start_idx,
},
)
if cpu_offload:
# Constant dummy values avoid randomizing huge CPU lookup tables.
set_weight_attrs(self.weight, {"dummy_weight_value": 1.0})
# The ue8m0 encoding of scale 1.0 is exponent byte 127.
set_weight_attrs(self.weight_scale_inv, {"dummy_weight_value": 127})
logger.info(
"Engram table offloaded to pinned host memory: %d rows x %d, "
"%.2f GiB %s",
self.part_num_embeddings,
dim,
self.part_num_embeddings * (dim + dim // block_size) / 1024**3,
"shared across DP replicas" if dp_shared_memory else "per rank",
)
def _get_shard_info(self) -> tuple[int, int]:
return self.tp_size, get_tensor_model_parallel_rank()
if self.dp_size == 1:
return self.tp_size, get_tensor_model_parallel_rank()
return self.tp_size * self.dp_size, engram_head_shard_rank()
def _allocate_weights(self) -> tuple[torch.Tensor, torch.Tensor]:
if self.dp_shared_memory:
group = get_engram_dp_group()
assert group is not None
storage = DPSharedEngramStorage(
self.part_num_embeddings, self.dim, self.block_size, group
)
self._shared_memory = storage
self._weight_loader = storage.load_weight
return storage.weight, storage.weight_scale_inv
scale_dim = self.dim // self.block_size
if not self.cpu_offload:
return (
torch.empty(
self.part_num_embeddings, self.dim, dtype=torch.float8_e4m3fn
),
torch.empty(self.part_num_embeddings, scale_dim, dtype=torch.uint8),
)
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, scale_dim),
)
# Model initialization may be inside a CUDA device context.
return (
torch.empty(self.part_num_embeddings, self.dim, dtype=torch.float8_e4m3fn),
torch.empty(
self.part_num_embeddings, self.dim // self.block_size, dtype=torch.uint8
self.part_num_embeddings,
self.dim,
dtype=torch.float8_e4m3fn,
device="cpu",
pin_memory=True,
),
torch.empty(
self.part_num_embeddings,
scale_dim,
dtype=torch.uint8,
device="cpu",
pin_memory=True,
),
)
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]:
return self.weight.data, self.weight_scale_inv.data
if self._shared_memory is not None:
return self._shared_memory.get_views(self.weight, self.weight_scale_inv)
if not self.cpu_offload:
return self.weight.data, self.weight_scale_inv.data
src = (self.weight.data_ptr(), self.weight_scale_inv.data_ptr())
if self._view_src != src:
self._views = (
get_accelerator_view_from_cpu_tensor(self.weight.data),
get_accelerator_view_from_cpu_tensor(self.weight_scale_inv.data),
)
self._view_src = src
assert self._views is not None
return self._views
def lookup(
self, indices: torch.Tensor, out: torch.Tensor, background: bool = False
@@ -714,6 +1090,24 @@ class ParallelEngramEmbedding(nn.Module):
if not rows:
return
weight, scales = self._storage()
ids_stride_t, ids_stride_h = indices.stride()
sort_min_rows, _ = _engram_lookup_thresholds(indices.device)
sort = (
self.cpu_offload
and self._packed is None
and sort_min_rows is not None
and rows >= sort_min_rows
)
dst = indices
if sort:
# Small-page host tables miss the TLB per row; in table order, rows on
# one page share it.
head_end = self.head_start + self.part_n_hash_cols
local = indices[:, self.head_start : head_end] - self.vocab_start_idx
if (pad := self.part_n_hash_cols - local.shape[1]) > 0:
local = nn.functional.pad(local, (0, pad), value=-1)
indices, dst = local.flatten().sort()
dst = dst.int()
# The table dwarfs TLB reach, so a persistent grid near the SM count
# beats one program per row; halve it to leave SMs for the main stream.
tiles = triton.cdiv(rows, 16)
@@ -722,12 +1116,13 @@ class ParallelEngramEmbedding(nn.Module):
weight,
scales,
indices,
dst,
out,
self.vocab_start_idx,
self.vocab_end_idx,
rows,
indices.stride(0),
indices.stride(1),
ids_stride_t,
ids_stride_h,
HEAD_START=self.head_start,
LOCAL_HEADS=self.part_n_hash_cols,
TOTAL_HEADS=self.n_hash_cols,
@@ -735,17 +1130,23 @@ class ParallelEngramEmbedding(nn.Module):
QUANT_BLOCK=self.block_size,
BLOCK_R=16,
GRID=grid,
SORTED=sort,
)
def forward(self, indices: torch.Tensor) -> torch.Tensor:
"""indices: [num_tokens, n_hash_cols] -> [num_tokens, n_hash_cols, dim]
bf16, gathered from all shards for this replica's tokens."""
num_tokens = indices.shape[0]
if self.dp_size > 1:
indices = gather_engram_hashes(indices)
out = torch.empty(
(indices.shape[0], self.part_n_hash_cols, self.dim),
dtype=torch.bfloat16,
device=indices.device,
)
self.lookup(indices, out)
if self.dp_size > 1:
out = _gather_engram_rows(out, num_tokens)
if self.tp_size > 1:
out = tensor_model_parallel_all_gather(out, dim=1)
return out[:, : self.n_hash_cols]
@@ -891,6 +1292,25 @@ def _engram_select_rows(
)
def _gather_engram_rows(staged: torch.Tensor, num_tokens: int) -> torch.Tensor:
"""Exchange DP tokens for heads, retaining only this replica's tokens."""
dp_group = get_engram_dp_group()
assert dp_group is not None
slot, remainder = divmod(staged.shape[0], dp_group.world_size)
assert remainder == 0 and 0 <= num_tokens <= slot
gathered = dp_group.all_gather(staged, dim=0)
local_heads, dim = staged.shape[1:]
rows = staged.new_empty((num_tokens, dp_group.world_size * local_heads, dim))
_engram_select_rows(
gathered,
rows,
staged.shape[0],
dp_group.rank_in_group * slot,
local_heads * dim,
)
return rows
class Engram(nn.Module):
"""Writes an n-gram lookup into the residual stream, gated by how well it
matches that stream.
@@ -901,6 +1321,9 @@ class Engram(nn.Module):
training kernel).
"""
_prefetch_stream: torch.cuda.Stream | None = None
_prefetch_done: torch.cuda.Event | None = None
def __init__(
self,
config,
@@ -909,8 +1332,12 @@ class Engram(nn.Module):
layer_hash_index: int,
use_sequence_parallel: bool,
prefix: str,
prefetch_stream: torch.cuda.Stream | None = None,
) -> None:
super().__init__()
# 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
self.layer_hash_index = layer_hash_index
self.dim = config.hidden_size
self.hc_mult = config.hc_mult
@@ -950,28 +1377,78 @@ class Engram(nn.Module):
def _create_embedding(
self, layout: EngramLayout, layer_hash_index: int
) -> ParallelEngramEmbedding:
engram_config = get_current_vllm_config().engram_config
assert engram_config is not None
return ParallelEngramEmbedding(
layout.num_embeddings[layer_hash_index],
layout.head_dim,
tuple(size for order in layout.primes[layer_hash_index] for size in order),
cpu_offload=engram_config.cpu_offload,
dp_shared_memory=bool(engram_config.dp_shared_memory),
use_thp=engram_config.use_thp,
)
def _init_staging(self, max_tokens: int, head_dim: int) -> None:
# Persistent storage keeps lookup addresses stable across graph replays.
self.staged_rows = torch.empty(
max_tokens,
max_tokens * self.embed_tokens.dp_size,
self.embed_tokens.part_n_hash_cols,
head_dim,
dtype=torch.bfloat16,
)
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:
"""Look up rows before the decoder layers consume them."""
"""Look up, or prefetch from host memory, rows before the decoder layers
consume them; DP-sharded tables take the group's gathered hash IDs."""
rows = self.staged_rows[: hash_ids.shape[0]]
assert rows.shape[0] == hash_ids.shape[0], "engram staging buffer too small"
self.embed_tokens.lookup(hash_ids, rows)
if self._prefetch_stream is None:
self.embed_tokens.lookup(hash_ids, rows)
else:
self._start_prefetch(hash_ids, rows)
@eager_break_during_capture
def _start_prefetch(self, hash_ids: torch.Tensor, rows: torch.Tensor) -> None:
# Eager boundaries let the lookup span piecewise graph segments, and
# decide per replay (on the replay stream) whether it runs inline.
num_tokens = hash_ids.shape[0]
# All DP ranks must agree, or EP collectives wait on the slowest one.
if is_forward_context_available() and (dp := get_forward_context().dp_metadata):
num_tokens = int(dp.num_tokens_across_dp_cpu.max())
current = stream = torch.cuda.current_stream()
# Big lookups stall persistent main-stream kernels anyway: run them inline.
_, inline_min_tokens = _engram_lookup_thresholds(hash_ids.device)
if inline_min_tokens is not None and num_tokens >= inline_min_tokens:
self.embed_tokens.lookup(hash_ids, rows)
else:
stream = self._prefetch_stream
assert stream is not None
stream.wait_stream(current)
# Keep temporary hash storage alive until lookup finishes reading it.
hash_ids.record_stream(stream)
with torch.cuda.stream(stream):
self.embed_tokens.lookup(hash_ids, rows, background=True)
assert self._prefetch_done is not None
self._prefetch_done.record(stream)
@eager_break_during_capture
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_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]
return _gather_engram_rows(staged, num_tokens)
return self.staged_rows[:num_tokens]
def embed(self, hash_ids: torch.Tensor) -> torch.Tensor:
@@ -275,15 +275,28 @@ class DeepseekV4VLProcessingInfo(BaseProcessingInfo):
hf_config = self.get_hf_config()
patch_size = hf_config.vision_patch_size
downsample_ratio = hf_config.vision_downsample_ratio
# A square maximizes the ViT patch count (area) within the token
# budget; solve the budget-derived size directly to keep the dummy
# image small.
budget = hf_config.vision_max_n_token
side = budget * patch_size * downsample_ratio
best_h, best_w = solve_resize_ratio(
side, side, patch_size, downsample_ratio, budget
)
return ImageSize(width=best_w, height=best_h)
max_wh_ratio = hf_config.vision_max_wh_ratio
best_h = best_w = 0
# Each LLM row costs an extra newline token. Maximize the ViT grid,
# including the patch rounding after the optional aspect-ratio clamp.
for n_llm_h in range(1, (budget - 2) // 2 + 1):
n_vit_h = n_llm_h * downsample_ratio
n_vit_w = ((budget - 2) // n_llm_h - 1) * downsample_ratio
if max_wh_ratio is not None:
n_vit_w = min(n_vit_w, math.ceil(n_vit_h * max_wh_ratio))
if n_vit_h * n_vit_w > best_h * best_w:
best_h, best_w = n_vit_h, n_vit_w
if best_h == 0:
raise ValueError(
"Image token budget and aspect ratio allow no image patches"
)
height, width = best_h * patch_size, best_w * patch_size
# Avoid the min-pixels upscaler perturbing the selected aspect ratio.
scale = 1
while height * width * scale * scale < hf_config.vision_min_pixels:
scale *= 2
return ImageSize(width=width * scale, height=height * scale)
class DeepseekV4VLDummyInputsBuilder(
+1 -1
View File
@@ -57,7 +57,7 @@ class CompressorMetadata:
token_to_req_indices: torch.Tensor # [num_tokens]
@triton.jit
@triton.jit(do_not_specialize=["block_table_stride", "num_actual_tokens", "num_tokens"])
def _ring_slot_mapping_kernel(
slot_mapping_ptr,
block_table_ptr,
@@ -0,0 +1,67 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Decoder-side SWA bounded replay: running the replay layers on their batch.
The layers past the last KV-source layer own nothing but sliding-window KV, so
in eager prefill steps they run on each request's last ``window`` rows only.
``DeepseekV41ModelState`` prepares those rows as a sub-batch with attention
metadata and a forward context of its own, like a microbatch;
``DecoderReplayLayers`` gathers the layer inputs by its rows, runs the layers
under that context and scatters the outputs back to batch rows. Steps that run
in a CUDA graph keep the layers on the whole batch, inside the graph.
"""
from collections.abc import Callable
import torch
from vllm.forward_context import ForwardContext, override_forward_context
from vllm.model_executor.layers.fused_moe.moe_output import MoEOutput
class DecoderReplayLayers:
"""Runs the replay layers on the step's replay batch.
``run_layers`` takes a batch's layer inputs and returns its per-row
outputs. ``row_buffers`` hold per-row results the source layer's indexer
publishes for the layers after it; they are compacted to the replay rows
in place.
"""
def __init__(
self,
window: int,
run_layers: Callable[..., tuple[torch.Tensor, ...]],
row_buffers: list[torch.Tensor],
) -> None:
self.window = window
self.run_layers = run_layers
self.row_buffers = row_buffers
# The replay batch, set by the model state every step: its rows of the
# batch and its forward context. None runs the layers on the batch.
self.rows: torch.Tensor | None = None
self.forward_context: ForwardContext | None = None
def __call__(
self, hidden_states: torch.Tensor | MoEOutput, *states: torch.Tensor | None
) -> tuple[torch.Tensor, ...]:
rows = self.rows
if rows is None:
return self.run_layers(hidden_states, *states)
# A trimming step holds a prefill longer than the window, more tokens
# than any step whose MoE leaves its finalize to the next layer.
assert isinstance(hidden_states, torch.Tensor)
num_rows = rows.shape[0]
for buf in self.row_buffers:
buf[:num_rows].copy_(buf.index_select(0, rows))
with override_forward_context(self.forward_context):
row_outputs = self.run_layers(
hidden_states.index_select(0, rows),
*(None if t is None else t.index_select(0, rows) for t in states),
)
# The trimmed rows' outputs stay zero; nothing reads them.
num_tokens = hidden_states.shape[0]
return tuple(
out.new_zeros((num_tokens, *out.shape[1:])).index_copy_(0, rows, out)
for out in row_outputs
)
-497
View File
@@ -1,497 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""NVIDIA Engram DP sharding, shared host storage, and asynchronous prefetch."""
import ctypes
import mmap
import os
import shutil
import tempfile
import weakref
from contextlib import ExitStack
import numpy as np
import torch
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import get_current_vllm_config
from vllm.distributed import (
get_dp_group,
get_engram_dp_group,
get_engram_dp_size,
get_tensor_model_parallel_rank,
tensor_model_parallel_all_gather,
)
from vllm.distributed.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
from vllm.model_executor.utils import set_weight_attrs
from vllm.models.deepseek_v41.common.engram import (
DEAD_ID,
EngramLayout,
_engram_head_shard_weight_loader,
_engram_select_rows,
)
from vllm.models.deepseek_v41.common.engram import (
Engram as BaseEngram,
)
from vllm.models.deepseek_v41.common.engram import (
ParallelEngramEmbedding as BaseParallelEngramEmbedding,
)
from vllm.utils.platform_utils import is_uva_available
from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
logger = init_logger(__name__)
def _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.
TP-major, so the shards a DP gather brings in are contiguous heads and
the following TP gather completes the head order.
"""
dp_group = get_engram_dp_group()
dp_size = dp_group.world_size if dp_group is not None else 1
dp_rank = dp_group.rank_in_group if dp_group is not None else 0
return get_tensor_model_parallel_rank() * dp_size + dp_rank
def engram_gathered_num_tokens() -> int:
"""Per-replica token slot for the node-local Engram DP group."""
dp_metadata = get_forward_context().dp_metadata
if dp_metadata is None:
raise RuntimeError("a DP-shared engram table needs DP token metadata")
group = get_engram_dp_group()
assert group is not None
# Engram groups are contiguous slices of the full DP group.
start = get_dp_group().rank_in_group - group.rank_in_group
return int(
dp_metadata.num_tokens_across_dp_cpu[start : start + group.world_size].max()
)
def gather_engram_hashes(
hash_ids: torch.Tensor, *, dp_shared_memory: bool = False
) -> torch.Tensor:
"""Collect the n-gram ids of every DP replica sharing one table.
Replicas are padded to a common token slot, so the gathered shape is
static under CUDA graph capture (where DP already pads alike).
"""
dp_group = get_engram_dp_group()
if dp_group is None or dp_shared_memory:
return hash_ids
slot = engram_gathered_num_tokens()
if hash_ids.shape[0] > slot:
raise ValueError("Engram token count exceeds the DP token slot")
if hash_ids.shape[0] < slot:
pad = hash_ids.new_full(
(slot - hash_ids.shape[0], *hash_ids.shape[1:]), DEAD_ID
)
hash_ids = torch.cat((hash_ids, pad))
return dp_group.all_gather(hash_ids, dim=0)
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; "
"storing the offloaded tables per rank instead of sharing them."
)
return False
num_bytes = sum(layout.num_embeddings) * (
layout.head_dim + layout.head_dim // block_size
)
if shutil.disk_usage(SHM_PATH).total < num_bytes:
logger.warning_once(
"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
class DPSharedEngramStorage:
"""Registered host weights shared by a node-local DP group with one writer."""
def __init__(
self, num_rows: int, dim: int, block_size: int, group: GroupCoordinator
) -> None:
self.group = group
weight_bytes = num_rows * dim
storage = self._allocate(weight_bytes + weight_bytes // block_size)
self.weight = storage[:weight_bytes].view(torch.float8_e4m3fn).view(-1, dim)
self.weight_scale_inv = storage[weight_bytes:].view(-1, dim // block_size)
self._views: tuple[torch.Tensor, torch.Tensor] | None = None
def _allocate(self, num_bytes: int) -> torch.Tensor:
"""Map and register one physical allocation across a node-local DP group."""
group = self.group
with ExitStack() as stack:
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=SHM_PATH)
)
backing_file.truncate(num_bytes)
path = backing_file.name
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
path, error = group.broadcast_object((path, error))
if error is not None:
raise RuntimeError(
"Engram shared-memory creation failed on EDP rank 0: " + error
)
mapping = owner = tensor = None
try:
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(
"cudaHostRegister did not pin the shared Engram mapping"
)
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:
# Torch storage retains the numpy owner, including through cached UVA views.
# Keep its mmap alive until CUDA has released the registration.
result = torch.cuda.cudart().cudaHostUnregister(pointer)
if result.value != 0:
logger.warning("Engram cudaHostUnregister failed: %s", result)
def load_weight(
self, param: torch.nn.Parameter, loaded_weight: torch.Tensor
) -> None:
if self.group.rank_in_group == 0:
_engram_head_shard_weight_loader(param, loaded_weight)
# Read order may differ across ranks. Equal load counts ensure all shared
# weights are ready after the last weight-loader call returns.
torch.distributed.barrier(group=self.group.cpu_group)
def get_views(
self, weight: torch.Tensor, scales: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
if (weight.data_ptr(), scales.data_ptr()) != (
self.weight.data_ptr(),
self.weight_scale_inv.data_ptr(),
):
raise RuntimeError("Shared Engram parameter storage must not be replaced")
if self._views is None:
self._views = (
get_accelerator_view_from_cpu_tensor(self.weight),
get_accelerator_view_from_cpu_tensor(self.weight_scale_inv),
)
return self._views
class ParallelEngramEmbedding(BaseParallelEngramEmbedding):
"""Extend TP lookup with DP head sharding or shared, CPU-offloaded TP slices."""
_shared_memory: DPSharedEngramStorage | None = None
def __init__(
self,
num_embeddings: int,
dim: int,
head_sizes: tuple[int, ...],
block_size: int = 32,
cpu_offload: bool = False,
dp_shared_memory: bool = False,
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:
raise ValueError("dp_shared_memory requires cpu_offload=True")
if self.dp_size <= 1:
raise ValueError(
"dp_shared_memory requires a node-local Engram DP "
f"group with size > 1; effective Engram DP size is {self.dp_size}. "
"Check that the node layout and rank placement allow complete "
"DP replicas to be co-located."
)
self.dp_size = 1
if cpu_offload and not is_uva_available():
raise RuntimeError("Engram CPU offload requires UVA support")
self._views: tuple[torch.Tensor, torch.Tensor] | None = None
self._view_src: tuple[int, int] | None = None
super().__init__(num_embeddings, dim, head_sizes, block_size)
if cpu_offload:
# Constant dummy values avoid randomizing huge CPU lookup tables.
set_weight_attrs(self.weight, {"dummy_weight_value": 1.0})
# The ue8m0 encoding of scale 1.0 is exponent byte 127.
set_weight_attrs(self.weight_scale_inv, {"dummy_weight_value": 127})
logger.info(
"Engram table offloaded to pinned host memory: %d rows x %d, "
"%.2f GiB %s",
self.part_num_embeddings,
dim,
self.part_num_embeddings * (dim + dim // block_size) / 1024**3,
"shared across DP replicas" if dp_shared_memory else "per rank",
)
def _get_shard_info(self) -> tuple[int, int]:
if self.dp_size == 1:
return super()._get_shard_info()
return self.tp_size * self.dp_size, engram_head_shard_rank()
def _allocate_weights(self) -> tuple[torch.Tensor, torch.Tensor]:
if self.dp_shared_memory:
group = get_engram_dp_group()
assert group is not None
storage = DPSharedEngramStorage(
self.part_num_embeddings, self.dim, self.block_size, group
)
self._shared_memory = storage
self._weight_loader = storage.load_weight
return storage.weight, storage.weight_scale_inv
if not self.cpu_offload:
return super()._allocate_weights()
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(
self.part_num_embeddings,
self.dim,
dtype=torch.float8_e4m3fn,
device="cpu",
pin_memory=True,
),
torch.empty(
self.part_num_embeddings,
self.dim // self.block_size,
dtype=torch.uint8,
device="cpu",
pin_memory=True,
),
)
def 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)
if not self.cpu_offload:
return super()._storage()
src = (self.weight.data_ptr(), self.weight_scale_inv.data_ptr())
if self._view_src != src:
self._views = (
get_accelerator_view_from_cpu_tensor(self.weight.data),
get_accelerator_view_from_cpu_tensor(self.weight_scale_inv.data),
)
self._view_src = src
assert self._views is not None
return self._views
def forward(self, indices: torch.Tensor) -> torch.Tensor:
if self.dp_size == 1:
return super().forward(indices)
num_tokens = indices.shape[0]
indices = gather_engram_hashes(indices)
out = torch.empty(
(indices.shape[0], self.part_n_hash_cols, self.dim),
dtype=torch.bfloat16,
device=indices.device,
)
self.lookup(indices, out)
out = _gather_engram_rows(out, num_tokens)
if self.tp_size > 1:
out = tensor_model_parallel_all_gather(out, dim=1)
return out[:, : self.n_hash_cols]
def _gather_engram_rows(staged: torch.Tensor, num_tokens: int) -> torch.Tensor:
"""Exchange DP tokens for heads, retaining only this replica's tokens."""
dp_group = get_engram_dp_group()
assert dp_group is not None
slot, remainder = divmod(staged.shape[0], dp_group.world_size)
assert remainder == 0 and 0 <= num_tokens <= slot
gathered = dp_group.all_gather(staged, dim=0)
local_heads, dim = staged.shape[1:]
rows = staged.new_empty((num_tokens, dp_group.world_size * local_heads, dim))
_engram_select_rows(
gathered,
rows,
staged.shape[0],
dp_group.rank_in_group * slot,
local_heads * dim,
)
return rows
class Engram(BaseEngram):
"""NVIDIA Engram with asynchronous offload and node-local DP lookup."""
_prefetch_stream: torch.cuda.Stream | None = None
_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
) -> ParallelEngramEmbedding:
engram_config = get_current_vllm_config().engram_config
assert engram_config is not None
return ParallelEngramEmbedding(
layout.num_embeddings[layer_hash_index],
layout.head_dim,
tuple(size for order in layout.primes[layer_hash_index] for size in order),
cpu_offload=engram_config.cpu_offload,
dp_shared_memory=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 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."""
if self._prefetch_stream is None:
return super().prepare_embeddings(hash_ids)
rows = self.staged_rows[: hash_ids.shape[0]]
assert rows.shape[0] == hash_ids.shape[0], "engram staging buffer too small"
self._start_prefetch(hash_ids, rows, self._prefetch_stream)
@eager_break_during_capture
def _start_prefetch(
self, hash_ids: torch.Tensor, rows: torch.Tensor, stream: torch.cuda.Stream
) -> None:
# Eager boundaries let the lookup span piecewise graph segments.
stream.wait_stream(torch.cuda.current_stream())
# Keep temporary hash storage alive until lookup finishes reading it.
hash_ids.record_stream(stream)
with torch.cuda.stream(stream):
self.embed_tokens.lookup(hash_ids, rows, background=True)
assert self._prefetch_done is not None
self._prefetch_done.record(stream)
@eager_break_during_capture
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_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]
return _gather_engram_rows(staged, num_tokens)
return super()._ready_rows(num_tokens)
+229 -42
View File
@@ -83,6 +83,7 @@ from vllm.models.deepseek_v4.nvidia.model import (
prepare_mega_gate_routing_metadata,
)
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
from vllm.models.deepseek_v41.nvidia.flash_mla_mega_attn import (
DeepseekV4MegaAttnAttention,
)
@@ -97,9 +98,14 @@ from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.worker.ubatching import dbo_current_ubatch_id
from ..common.engram import EngramLayout, NgramHashState
from ..common.engram import (
Engram,
EngramLayout,
NgramHashState,
can_share_engram_tables,
gather_engram_hashes,
)
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,
@@ -741,6 +747,35 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
if successor.engram is None:
layer.ffn.defer_finalize()
# Decoder-side SWA bounded replay: in eager prefill steps the layers past
# the last KV source run on each request's trailing window only
# (decoder_replay_layers.py).
self.decoder_replay_layers: DecoderReplayLayers | None = None
self.decoder_replay_start = self.end_layer
cut = max(config.kv_source_layer_ids)
if (
cut < self.end_layer - 1
and self._decoder_replay_supported(vllm_config, cut)
and self.layers[cut].attn.swa_cache_layer.bounded_replay
):
self.decoder_replay_start = cut + 1
self.decoder_replay_layers = DecoderReplayLayers(
config.sliding_window,
self._run_replay_layers,
[
buf
for buf in (self.topk_indices_buffer, self.candidate_block_buffer)
if buf is not None
],
)
logger.info_once(
"Decoder SWA bounded replay: in eager prefill steps, layers "
"%d-%d run on each request's last %d tokens only.",
cut + 1,
self.end_layer - 1,
config.sliding_window,
)
# The n-gram hash needs a slot-keyed rolling store of compressed ids
# (chunked prefill / decode lookback); key it off the first local
# layer's sliding-window KV cache. Only PP ranks owning an engram
@@ -904,29 +939,28 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
hidden_states = sp_shard(hidden_states)
input_ids = sp_shard(input_ids)
mega_gate_metadata = None
if self.use_mega_moe:
mega_gate_metadata = prepare_mega_gate_routing_metadata(
input_ids,
has_hash_routing=False,
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
if getattr(self.config, "vision_n_layers", 0) > 0
else None,
)
residual, post_mix, res_mix = None, None, None
pre_mix: torch.Tensor | None = None
if not get_pp_group().is_first_rank:
assert intermediate_tensors is not None
pre_mix = intermediate_tensors["pre_mix"]
# Every layer's post runs inside the next layer's fused pre, so aux
# hidden states are read back from there instead of recomputed.
aux_hidden_by_layer: dict[int, torch.Tensor] = {}
for idx, layer in enumerate(
islice(self.layers, self.start_layer, self.end_layer),
start=self.start_layer,
):
hidden_states, residual, post_mix, res_mix, pre_mix, previous_aux = layer(
hidden_states, residual, post_mix, res_mix, pre_mix = self._run_layers(
range(self.start_layer, self.decoder_replay_start),
hidden_states,
positions,
input_ids,
pre_mix,
post_mix,
res_mix,
residual,
aux_hidden_by_layer,
engram_hashes,
engram_mask,
)
late_aux: list[torch.Tensor] = []
if self.decoder_replay_layers is not None:
hidden_states, pre_mix, *late_aux = self.decoder_replay_layers(
hidden_states,
positions,
input_ids,
@@ -934,36 +968,22 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
post_mix,
res_mix,
residual,
engram_hashes,
engram_mask,
capture_previous_aux=idx in self.aux_hidden_state_layers,
mega_gate_metadata=mega_gate_metadata,
)
if previous_aux is not None:
# idx is the one-based id of the layer whose post this is.
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:
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
hidden_states = mhc_post_tilelang(
hidden_states, residual, post_mix, res_mix
else:
hidden_states = self._collapse(
hidden_states,
residual,
post_mix,
res_mix,
aux_hidden_by_layer,
full_num_tokens,
)
if self.end_layer in self.aux_hidden_state_layers:
final_aux = hidden_states.mean(dim=1)
if self.use_sequence_parallel:
final_aux = sp_all_gather(final_aux)[:full_num_tokens]
aux_hidden_by_layer[self.end_layer] = final_aux
aux_hidden_states = [
aux_hidden_by_layer[layer_id]
for layer_id in self.aux_hidden_state_layers
if layer_id in aux_hidden_by_layer
]
] + late_aux
if not get_pp_group().is_last_rank:
return IntermediateTensors(
@@ -992,6 +1012,169 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
return hidden_states, aux_hidden_states
return hidden_states
def _mega_gate_metadata(
self, input_ids: torch.Tensor | None
) -> MegaGateRoutingMetadata | None:
if not self.use_mega_moe:
return None
assert input_ids is not None
return prepare_mega_gate_routing_metadata(
input_ids,
has_hash_routing=False,
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
if getattr(self.config, "vision_n_layers", 0) > 0
else None,
)
def _run_layers(
self,
layer_ids: range,
hidden_states: torch.Tensor | MoEOutput,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
pre_mix: torch.Tensor | None,
post_mix: torch.Tensor | None,
res_mix: torch.Tensor | None,
residual: torch.Tensor | None,
aux_hidden_by_layer: dict[int, torch.Tensor],
engram_hashes: torch.Tensor | None = None,
engram_mask: torch.Tensor | None = None,
) -> tuple[
torch.Tensor | MoEOutput, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
]:
# Every layer's post runs inside the next layer's fused pre, so aux
# hidden states are read back from there instead of recomputed.
full_num_tokens = positions.shape[0]
mega_gate_metadata = self._mega_gate_metadata(input_ids)
for idx in layer_ids:
hidden_states, residual, post_mix, res_mix, pre_mix, previous_aux = (
self.layers[idx](
hidden_states,
positions,
input_ids,
pre_mix,
post_mix,
res_mix,
residual,
engram_hashes,
engram_mask,
capture_previous_aux=idx in self.aux_hidden_state_layers,
mega_gate_metadata=mega_gate_metadata,
)
)
if previous_aux is not None:
# idx is the one-based id of the layer whose post this is.
if self.use_sequence_parallel:
previous_aux = sp_all_gather(previous_aux)[:full_num_tokens]
aux_hidden_by_layer[idx] = previous_aux
assert residual is not None and post_mix is not None
assert res_mix is not None and pre_mix is not None
return hidden_states, residual, post_mix, res_mix, pre_mix
def _collapse(
self,
hidden_states: torch.Tensor | MoEOutput,
residual: torch.Tensor,
post_mix: torch.Tensor,
res_mix: torch.Tensor,
aux_hidden_by_layer: dict[int, torch.Tensor],
full_num_tokens: int,
) -> torch.Tensor:
# Without a successor boundary, the last layer finalized its own MoE.
assert isinstance(hidden_states, torch.Tensor)
# The last layer has no successor to fold its post into.
if self.fuse_mhc_all_reduce:
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix)
if self.end_layer in self.aux_hidden_state_layers:
final_aux = hidden_states.mean(dim=1)
if self.use_sequence_parallel:
final_aux = sp_all_gather(final_aux)[:full_num_tokens]
aux_hidden_by_layer[self.end_layer] = final_aux
return hidden_states
def _run_replay_layers(
self,
hidden_states: torch.Tensor | MoEOutput,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
pre_mix: torch.Tensor,
post_mix: torch.Tensor,
res_mix: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, ...]:
"""The layers past the last KV source, on whatever rows they are given;
returns their output, the last FFN's pre-mix and the aux hidden states
they capture."""
aux_hidden_by_layer: dict[int, torch.Tensor] = {}
hidden_states, residual, post_mix, res_mix, pre_mix = self._run_layers(
range(self.decoder_replay_start, self.end_layer),
hidden_states,
positions,
input_ids,
pre_mix,
post_mix,
res_mix,
residual,
aux_hidden_by_layer,
)
hidden_states = self._collapse(
hidden_states,
residual,
post_mix,
res_mix,
aux_hidden_by_layer,
positions.shape[0],
)
return (
hidden_states,
pre_mix,
*(
aux_hidden_by_layer[layer_id]
for layer_id in self.aux_hidden_state_layers
if layer_id in aux_hidden_by_layer
),
)
def _decoder_replay_supported(self, vllm_config: VllmConfig, cut: int) -> bool:
"""Whether this rank may trim the layers after ``cut``; warns when not."""
parallel_config = vllm_config.parallel_config
spec_config = vllm_config.speculative_config
draft_config = spec_config.draft_model_config if spec_config else None
draft_hf_config = getattr(draft_config, "hf_config", None)
draft_window = getattr(draft_hf_config, "sliding_window", None)
draft_layer_types = getattr(draft_hf_config, "layer_types", None) or ()
window = self.config.sliding_window
if self.start_layer > cut or self.end_layer < self.config.num_hidden_layers:
reason = (
"the pipeline stage holding the last KV source layer must also "
"hold every layer after it"
)
elif (
self.use_sequence_parallel
or parallel_config.prefill_context_parallel_size > 1
or parallel_config.use_ubatching
):
reason = (
"the replay-layer batch shrinks per rank, which sequence and "
"prefill-context parallelism and microbatching cannot follow"
)
elif any(i > cut for i in getattr(self.config, "engram_layer_ids", ())):
reason = "an Engram layer sits after the last KV source layer"
elif draft_config is not None and (
draft_window is None
or draft_window > window
or any(t != "sliding_attention" for t in draft_layer_types)
):
reason = (
f"the drafter (sliding window {draft_window}) reads hidden states "
f"outside the target's {window}-token window"
)
else:
return True
logger.warning_once("Decoder SWA bounded replay is off: %s.", reason)
return False
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stacked_params_mapping = [
# (param_name, shard_name, shard_id)
@@ -1397,6 +1580,10 @@ class DeepseekV41LLMForCausalLM(
engram_hash = self.model.engram_hash
return engram_hash.lookback_depth if engram_hash is not None else 0
@property
def decoder_replay_layers(self) -> DecoderReplayLayers | None:
return self.model.decoder_replay_layers
def forward(
self,
input_ids: torch.Tensor,
+321 -2
View File
@@ -1,17 +1,24 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import replace
from typing import Any
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from vllm.config import CUDAGraphMode, VllmConfig
from vllm.distributed.parallel_state import get_dp_group
from vllm.forward_context import DPMetadata, create_forward_context
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
from vllm.triton_utils import tl, triton
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadataBuilder
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
from vllm.v1.core.sched.output import NewRequestData
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.dp_utils import should_skip_dp_coordination
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
from vllm.v1.worker.gpu.buffer_utils import UvaBufferPool
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
@@ -81,6 +88,61 @@ def _pad_replayed_slots_kernel(
)
@triton.jit
def _gather_replay_batch_kernel(
query_start_loc_ptr, # [num_reqs + 1]
dropped_before_ptr, # [num_reqs + 1] rows trimmed before each boundary
seq_lens_ptr, # [num_reqs]
replay_start_ptr, # [num_reqs] the encoder-side replay start
positions_ptr,
slot_mappings_ptr, # [num_groups, num_tokens]
slot_mappings_stride,
rows_ptr, # out: [num_kept] batch row of every kept row
kept_query_start_loc_ptr, # out: [num_reqs + 1]
kept_positions_ptr, # out: [num_kept]
kept_slot_mappings_ptr, # out: [num_groups, num_kept]
kept_slot_mappings_stride,
kept_kv_start_ptr, # out: [num_reqs]
window,
NUM_GROUPS: tl.constexpr,
BLOCK: tl.constexpr,
):
"""One program per request: its kept rows are the last ones before its
boundary, and land at that boundary minus the rows trimmed before it."""
req = tl.program_id(0)
begin = tl.load(query_start_loc_ptr + req)
end = tl.load(query_start_loc_ptr + req + 1)
kept_begin = begin - tl.load(dropped_before_ptr + req)
kept_end = end - tl.load(dropped_before_ptr + req + 1)
if req == 0:
tl.store(kept_query_start_loc_ptr, kept_begin)
tl.store(kept_query_start_loc_ptr + req + 1, kept_end)
# A trimmed request holds no replay-layer window KV below its kept rows.
kv_start = tl.load(replay_start_ptr + req)
if kept_end - kept_begin < end - begin:
kv_start = tl.maximum(kv_start, tl.load(seq_lens_ptr + req) - window)
tl.store(kept_kv_start_ptr + req, kv_start)
first_row = end - (kept_end - kept_begin)
for tok in range(kept_begin, kept_end, BLOCK):
offs = tok + tl.arange(0, BLOCK)
mask = offs < kept_end
row = first_row + (offs - kept_begin)
tl.store(rows_ptr + offs, row.to(tl.int64), mask=mask)
tl.store(
kept_positions_ptr + offs,
tl.load(positions_ptr + row, mask=mask),
mask=mask,
)
for g in tl.static_range(NUM_GROUPS):
tl.store(
kept_slot_mappings_ptr + g * kept_slot_mappings_stride + offs,
tl.load(slot_mappings_ptr + g * slot_mappings_stride + row, mask=mask),
mask=mask,
)
class ReplayAttnMetadata(ModelSpecificAttnMetadata):
"""Hands the batch's replay starts to the sliding-window builders."""
@@ -111,7 +173,10 @@ class DeepseekV41ModelState(DefaultModelState):
``prepare_attn`` gathers those per batch, pads the replayed tokens' slots
in the prefix-cacheable groups so the cached KV stays as is, and hands the
starts to the sliding-window metadata builders, whose kernels read no
window KV below them.
window KV below them. With the decoder side on
(``model.decoder_replay_layers``) it also prepares the replay layers'
batch in eager steps: each prefill's last ``window`` rows as a sub-batch
with metadata and a forward context of its own, like a microbatch.
"""
def __init__(
@@ -140,9 +205,40 @@ class DeepseekV41ModelState(DefaultModelState):
# the KV cache config on first use; None until then.
self._replay: tuple[int, torch.Tensor] | None = None
self.decoder_replay_layers: DecoderReplayLayers | None = getattr(
model, "decoder_replay_layers", None
)
if self.decoder_replay_layers is not None:
# Requests whose every prompt row is read (prompt logprobs) never trim.
self._keeps_rows_np = np.zeros(self.max_num_reqs, dtype=np.bool_)
self._dropped_before = UvaBufferPool(self.max_num_reqs + 1, torch.int32)
# The replay batch's inputs: its rows of the batch, query offsets,
# positions, slot mappings (sized with the KV cache groups on first
# use) and the position from which each request holds replay-layer
# window KV.
self._kept_rows = torch.zeros(
self.max_num_tokens, dtype=torch.int64, device=device
)
self._kept_query_start_loc = torch.zeros(
self.max_num_reqs + 1, dtype=torch.int32, device=device
)
self._kept_positions = torch.zeros(
self.max_num_tokens, dtype=torch.int64, device=device
)
self._kept_slot_mappings: torch.Tensor | None = None
self._kept_kv_start = torch.zeros(
self.max_num_reqs, dtype=torch.int32, device=device
)
self._replay_attn_groups: list[list[AttentionGroup]] | None = None
def add_request(self, req_index: int, new_req_data: NewRequestData) -> None:
super().add_request(req_index, new_req_data)
self._replay_start_np[req_index] = new_req_data.replay_start
if self.decoder_replay_layers is not None:
params = new_req_data.sampling_params
self._keeps_rows_np[req_index] = (
params is not None and params.prompt_logprobs is not None
)
def prepare_inputs(
self, input_batch: InputBatch, req_states: RequestState
@@ -196,7 +292,16 @@ class DeepseekV41ModelState(DefaultModelState):
device=self.device,
),
)
if self.decoder_replay_layers is not None:
self._kept_slot_mappings = torch.zeros(
len(specs),
self.max_num_tokens,
dtype=torch.int64,
device=self.device,
)
self._warm_up_replay_kernels(input_batch, slot_mappings)
window, cacheable_groups = self._replay
replay_start: torch.Tensor | None = None
if window:
num_reqs = input_batch.num_reqs
# Decode rows sit above the hit, so only prefills carry a replay
@@ -226,7 +331,7 @@ class DeepseekV41ModelState(DefaultModelState):
)
assert model_specific_attn_metadata is None
model_specific_attn_metadata = ReplayAttnMetadata(replay_start)
return super().prepare_attn(
attn_metadata = super().prepare_attn(
input_batch,
cudagraph_mode,
block_tables,
@@ -237,3 +342,217 @@ class DeepseekV41ModelState(DefaultModelState):
ubatch_idx=ubatch_idx,
model_specific_attn_metadata=model_specific_attn_metadata,
)
if self.decoder_replay_layers is not None:
assert replay_start is not None
self._prepare_replay_batch(
input_batch,
cudagraph_mode,
block_tables,
slot_mappings,
attn_groups,
kv_cache_config,
replay_start,
)
return attn_metadata
def _warm_up_replay_kernels(
self, input_batch: InputBatch, slot_mappings: torch.Tensor
) -> None:
"""Compile the replay kernels on the buffers they run on: the startup
dummy batches never replay or trim, so they would not launch them."""
assert self._replay is not None
window, cacheable_groups = self._replay
if not window:
return
_pad_replayed_slots_kernel.warmup(
slot_mappings,
slot_mappings.stride(0),
cacheable_groups,
input_batch.query_start_loc,
input_batch.positions,
self._replay_start,
window,
PAD_SLOT_ID,
NUM_GROUPS=cacheable_groups.numel(),
BLOCK=1024,
grid=(1,),
)
if self.decoder_replay_layers is None:
return
assert self._kept_slot_mappings is not None
_gather_replay_batch_kernel.warmup(
input_batch.query_start_loc,
self._dropped_before.copy_to_uva(np.zeros(1, dtype=np.int32)),
input_batch.seq_lens,
self._replay_start,
input_batch.positions,
slot_mappings,
slot_mappings.stride(0),
self._kept_rows,
self._kept_query_start_loc,
self._kept_positions,
self._kept_slot_mappings,
self._kept_slot_mappings.stride(0),
self._kept_kv_start,
self.decoder_replay_layers.window,
NUM_GROUPS=slot_mappings.shape[0],
BLOCK=1024,
grid=(1,),
)
def _prepare_replay_batch(
self,
input_batch: InputBatch,
cudagraph_mode: CUDAGraphMode,
block_tables: tuple[torch.Tensor, ...],
slot_mappings: torch.Tensor,
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
replay_start: torch.Tensor,
) -> None:
"""Set the replay layers' batch for this forward, or none when nothing
trims. Only eager steps trim: a CUDA graph keeps the layers on the whole
batch, and ranks share the graph mode. Under data parallelism every rank
replays if any does."""
layers = self.decoder_replay_layers
assert layers is not None
layers.rows = layers.forward_context = None
if cudagraph_mode != CUDAGraphMode.NONE:
return
num_reqs = input_batch.num_reqs
query_lens = np.diff(input_batch.query_start_loc_np[: num_reqs + 1])
kept_lens = np.where(
self._keeps_rows_np[input_batch.idx_mapping_np[:num_reqs]],
query_lens,
np.minimum(query_lens, layers.window),
)
# Dummy batches (captures, an idle DP rank's) are not prefills: they
# keep their rows unless a rank trims.
trims = bool(
(kept_lens < query_lens)[input_batch.is_prefilling_np[:num_reqs]].any()
)
num_tokens = int(kept_lens.sum())
dp_metadata = None
if self.vllm_config.parallel_config.data_parallel_size > 1:
trims, dp_metadata = self._agree_across_dp(trims, num_tokens)
if not trims:
return
kept_batch, kept_slot_mappings = self._kept_input_batch(
input_batch, slot_mappings, replay_start, kept_lens
)
attn_metadata = super().prepare_attn(
kept_batch,
CUDAGraphMode.NONE,
block_tables,
kept_slot_mappings,
self._replay_groups(attn_groups),
kv_cache_config,
model_specific_attn_metadata=ReplayAttnMetadata(
self._kept_kv_start[:num_reqs]
),
)
layers.rows = self._kept_rows[:num_tokens]
layers.forward_context = create_forward_context(
attn_metadata,
self.vllm_config,
dp_metadata=dp_metadata,
slot_mapping=build_slot_mappings_by_layer(
kept_slot_mappings, kv_cache_config
),
)
def _kept_input_batch(
self,
input_batch: InputBatch,
slot_mappings: torch.Tensor,
replay_start: torch.Tensor,
kept_lens: np.ndarray,
) -> tuple[InputBatch, torch.Tensor]:
"""Build the sub-``InputBatch`` of each request's last ``kept_lens``
rows, and its slot mappings.
The kept rows follow the device boundaries minus the rows trimmed before
them: adaptive verification resizes the decodes on the GPU alone, and
decodes never trim. Like a microbatch's, the sub-batch describes the
forward only; its sampling fields are carried over and must not be read.
"""
num_reqs = input_batch.num_reqs
num_tokens = int(kept_lens.sum())
kept_query_start_loc_np = np.zeros(num_reqs + 1, dtype=np.int32)
np.cumsum(kept_lens, out=kept_query_start_loc_np[1:])
dropped_before = self._dropped_before.copy_to_uva(
input_batch.query_start_loc_np[: num_reqs + 1] - kept_query_start_loc_np
)
assert self._kept_slot_mappings is not None
kept_slot_mappings = self._kept_slot_mappings[:, :num_tokens]
_gather_replay_batch_kernel[(num_reqs,)](
input_batch.query_start_loc,
dropped_before,
input_batch.seq_lens,
replay_start,
input_batch.positions,
slot_mappings,
slot_mappings.stride(0),
self._kept_rows,
self._kept_query_start_loc,
self._kept_positions,
kept_slot_mappings,
kept_slot_mappings.stride(0),
self._kept_kv_start,
self.decoder_replay_layers.window, # type: ignore[union-attr]
NUM_GROUPS=slot_mappings.shape[0],
BLOCK=1024,
)
# Adaptive verification may lengthen the decodes on the device, up to
# the batch's bound.
max_query_len = max(int(kept_lens.max()), input_batch.max_query_len or 0)
kept_batch = replace(
input_batch,
num_tokens=num_tokens,
num_tokens_after_padding=num_tokens,
query_start_loc=self._kept_query_start_loc[: num_reqs + 1],
query_start_loc_np=kept_query_start_loc_np,
max_query_len=max_query_len,
positions=self._kept_positions[:num_tokens],
fast_prefill=None,
)
return kept_batch, kept_slot_mappings
def _agree_across_dp(
self, trims: bool, num_tokens: int
) -> tuple[bool, DPMetadata | None]:
"""Whether any rank trims and, then, the replay layers' DP metadata from
every rank's replay token count."""
parallel_config = self.vllm_config.parallel_config
agreed = torch.zeros(2, parallel_config.data_parallel_size, dtype=torch.int32)
agreed[:, parallel_config.data_parallel_rank] = torch.tensor(
[trims, num_tokens]
)
if not should_skip_dp_coordination():
dist.all_reduce(agreed, group=get_dp_group().cpu_group)
if not agreed[0].any():
return False, None
return True, DPMetadata.make(parallel_config, num_tokens, agreed[1])
def _replay_groups(
self, attn_groups: list[list[AttentionGroup]]
) -> list[list[AttentionGroup]]:
"""The attention groups with metadata builders of their own, like each
microbatch's: a builder keeps the metadata it built, and the runner's
hold the batch's."""
if self._replay_attn_groups is None:
self._replay_attn_groups = []
for groups in attn_groups:
replay_groups = []
for group in groups:
replay_group = replace(group, metadata_builders=[])
replay_group.create_metadata_builders(
self.vllm_config,
self.device,
group.metadata_builders[0].kernel_block_size,
)
replay_groups.append(replay_group)
self._replay_attn_groups.append(replay_groups)
return self._replay_attn_groups
@@ -51,6 +51,7 @@ from ..common.mm_preprocess import (
DeepseekV4VLProcessingInfo,
)
from ..common.vl_cudagraph import DeepseekV4VLEncoderCudaGraphMixin
from ..decoder_replay_layers import DecoderReplayLayers
from .model import (
DeepseekV41LLMForCausalLM,
_linear_scale_param_name,
@@ -281,6 +282,10 @@ class DeepseekV41ForCausalLM(
def token_lookback_depth(self) -> int:
return self.language_model.token_lookback_depth
@property
def decoder_replay_layers(self) -> DecoderReplayLayers | None:
return self.language_model.decoder_replay_layers
def forward(
self,
input_ids: torch.Tensor,
@@ -15,6 +15,23 @@ from vllm.third_party.flash_linear_attention.ops.op import exp
from vllm.triton_utils import tl, triton
def token_stride(x: torch.Tensor) -> int:
"""Token stride (elements) of a ``[B, T, H, D]`` or ``[B, T, H]`` tensor.
The recurrent kernel walks tokens with this stride and addresses heads
densely inside a token, so each token's ``[H, D]`` (or ``[H]``) block must
be contiguous, tokens must not overlap, and with ``B > 1`` sequence ``n``
must start at token ``n * T`` (dense batch). Column slices of a wider
per-token projection buffer satisfy this and are consumed in place.
"""
st = x.stride()
assert x.dim() in (3, 4) and st[-1] == 1, (x.shape, st)
assert x.dim() == 3 or st[2] == x.shape[3], (x.shape, st)
assert st[1] >= x.shape[2] * (x.shape[3] if x.dim() == 4 else 1), (x.shape, st)
assert x.shape[0] == 1 or st[0] == x.shape[1] * st[1], (x.shape, st)
return st[1]
@triton.heuristics(
{
"USE_INITIAL_STATE": lambda args: args["h0"] is not None,
@@ -52,6 +69,11 @@ def fused_recurrent_gated_delta_rule_fwd_kernel(
stride_final_state_token: tl.constexpr,
stride_indices_seq: tl.constexpr,
stride_indices_tok: tl.constexpr,
# Token strides of q/k/v/beta (elements), see `token_stride`.
stride_q_t,
stride_k_t,
stride_v_t,
stride_beta_t,
USE_INITIAL_STATE: tl.constexpr, # whether to use initial state
INPLACE_FINAL_STATE: tl.constexpr, # whether to store final state inplace
IS_BETA_HEADWISE: tl.constexpr, # whether beta is headwise vector or scalar,
@@ -86,13 +108,13 @@ def fused_recurrent_gated_delta_rule_fwd_kernel(
o_k = i_k * BK + tl.arange(0, BK)
o_v = i_v * BV + tl.arange(0, BV)
p_q = q + (bos * H + i_h) * K + o_k
p_k = k + (bos * H + i_h) * K + o_k
p_v = v + (bos * HV + i_hv) * V + o_v
p_q = q + bos * stride_q_t + i_h * K + o_k
p_k = k + bos * stride_k_t + i_h * K + o_k
p_v = v + bos * stride_v_t + i_hv * V + o_v
if IS_BETA_HEADWISE:
p_beta = beta + (bos * HV + i_hv) * V + o_v
p_beta = beta + bos * stride_beta_t + i_hv * V + o_v
else:
p_beta = beta + bos * HV + i_hv
p_beta = beta + bos * stride_beta_t + i_hv
if not IS_KDA:
p_g = g + bos * HV + i_hv
@@ -188,15 +210,15 @@ def fused_recurrent_gated_delta_rule_fwd_kernel(
p_ht = p_ht + i_hv * V * K + o_v[:, None] * K + o_k[None, :]
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
p_q += H * K
p_k += H * K
p_q += stride_q_t
p_k += stride_k_t
p_o += HV * V
p_v += HV * V
p_v += stride_v_t
if not IS_KDA:
p_g += HV
else:
p_gk += HV * K
p_beta += HV * (V if IS_BETA_HEADWISE else 1)
p_beta += stride_beta_t
def fused_recurrent_gated_delta_rule_fwd(
@@ -265,6 +287,10 @@ def fused_recurrent_gated_delta_rule_fwd(
stride_final_state_token=stride_final_state_token,
stride_indices_seq=stride_indices_seq,
stride_indices_tok=stride_indices_tok,
stride_q_t=token_stride(q),
stride_k_t=token_stride(k),
stride_v_t=token_stride(v),
stride_beta_t=token_stride(beta),
IS_BETA_HEADWISE=beta.ndim == v.ndim,
USE_QK_L2NORM_IN_KERNEL=use_qk_l2norm_in_kernel,
INPLACE_FINAL_STATE=inplace_final_state,
+16 -6
View File
@@ -24,7 +24,10 @@ from vllm.third_party.flash_linear_attention.ops.utils import FLA_CHUNK_SIZE, is
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import RCP_LN2, cdiv, next_power_of_2
from .fused_recurrent import fused_recurrent_gated_delta_rule_fwd_kernel
from .fused_recurrent import (
fused_recurrent_gated_delta_rule_fwd_kernel,
token_stride,
)
BT_LIST_AUTOTUNE = [32, 64, 128]
NUM_WARPS_AUTOTUNE = [2, 4, 8, 16] if is_amd else [4, 8, 16, 32]
@@ -70,7 +73,7 @@ def fused_recurrent_kda_fwd(
g_bias = g_bias.reshape(-1).contiguous()
if out is None:
o = torch.empty_like(k)
o = torch.empty(k.shape, dtype=k.dtype, device=k.device)
else:
# Caller-provided output buffer; must be layout-compatible with the
# tensor the kernel indexes (contiguous, same shape/dtype as k).
@@ -119,6 +122,10 @@ def fused_recurrent_kda_fwd(
stride_final_state_token=stride_final_state_token,
stride_indices_seq=stride_indices_seq,
stride_indices_tok=stride_indices_tok,
stride_q_t=token_stride(q),
stride_k_t=token_stride(k),
stride_v_t=token_stride(v),
stride_beta_t=token_stride(beta),
IS_BETA_HEADWISE=beta.ndim == v.ndim,
USE_QK_L2NORM_IN_KERNEL=use_qk_l2norm_in_kernel,
INPLACE_FINAL_STATE=inplace_final_state,
@@ -165,12 +172,15 @@ def fused_recurrent_kda(
if scale is None:
scale = k.shape[-1] ** -0.5
# q/k/v/beta are consumed in place with an explicit token stride, so
# column slices of the fused projection buffer need no copy; layouts the
# kernel cannot address fail loudly in `token_stride`.
o, final_state = fused_recurrent_kda_fwd(
q=q.contiguous(),
k=k.contiguous(),
v=v.contiguous(),
q=q,
k=k,
v=v,
g=g.contiguous(),
beta=beta.contiguous(),
beta=beta,
scale=scale,
initial_state=initial_state,
inplace_final_state=inplace_final_state,
+22 -16
View File
@@ -4,6 +4,7 @@
import torch
import torch.nn.functional as F
from torch import nn
from transformers import Glm5NextTextConfig
from vllm.config import (
CacheConfig,
@@ -32,7 +33,6 @@ from vllm.model_executor.utils import maybe_disable_graph_partition
from vllm.models.glm5next.nvidia.ops.kpool_compress import fwht128_quant_fp8
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
@@ -221,7 +221,7 @@ class Indexer(nn.Module):
def __init__(
self,
vllm_config: VllmConfig,
config: Glm5NextConfig,
config: Glm5NextTextConfig,
hidden_size: int,
q_lora_rank: int,
quant_config: QuantizationConfig | None,
@@ -236,7 +236,7 @@ class Indexer(nn.Module):
# self.indexer_cfg = config.attn_module_list_cfg[0]["attn_index"]
# Indexer is only constructed for v32 configs, where these sparse-indexer
# fields are guaranteed populated; narrow away the `int | None` declared
# on Glm5NextConfig for the optional-indexer case.
# on Glm5NextTextConfig for the optional-indexer case.
assert config.index_topk is not None
assert config.index_n_heads is not None
assert config.index_head_dim is not None
@@ -276,7 +276,7 @@ class Indexer(nn.Module):
disable_tp=True,
prefix=f"{prefix}.wk_weights_proj",
)
self.k_norm = LayerNorm(self.head_dim, eps=1e-6)
self.k_norm = LayerNorm(self.head_dim, eps=1e-6, dtype=torch.float32)
self.softmax_scale = self.head_dim**-0.5
# Hadamard-128 rotation of the indexer query is fused with the FP8
@@ -312,7 +312,9 @@ class Indexer(nn.Module):
self.prefix = prefix
from vllm.v1.attention.backends.mla.indexer import get_max_prefill_buffer_size
self.max_total_seq_len = get_max_prefill_buffer_size(vllm_config)
self.max_total_seq_len = (
get_max_prefill_buffer_size(vllm_config) // self.index_kpool
)
self.indexer_op = SparseAttnIndexerKpool(
self.k_cache,
self.quant_block_size,
@@ -417,7 +419,7 @@ class Glm5NextMLAAttention(nn.Module):
def __init__(
self,
vllm_config: VllmConfig,
config: Glm5NextConfig,
config: Glm5NextTextConfig,
hidden_size: int,
num_heads: int,
qk_nope_head_dim: int,
@@ -504,28 +506,32 @@ class Glm5NextMLAAttention(nn.Module):
prefix=f"{prefix}.o_proj",
)
# `Glm5NextTextConfig` is NoPE-only and so declares no `rope_parameters`;
# a checkpoint may still ship one.
rope_parameters = getattr(config, "rope_parameters", None)
if not skip_rope:
assert config.rope_parameters is not None
if config.rope_parameters["rope_type"] != "default":
config.rope_parameters["rope_type"] = (
assert rope_parameters is not None
if rope_parameters["rope_type"] != "default":
rope_parameters["rope_type"] = (
"deepseek_llama_scaling"
if config.rope_parameters.get("attention_factor") == 1.0
if rope_parameters.get("attention_factor") == 1.0
else "deepseek_yarn"
)
self.rotary_emb: RotaryEmbedding | None = get_rope(
qk_rope_head_dim,
max_position=max_position_embeddings,
rope_parameters=config.rope_parameters,
rope_parameters=rope_parameters,
is_neox_style=False,
)
if (
config.rope_parameters["rope_type"] != "default"
and config.rope_parameters["rope_type"] == "deepseek_yarn"
rope_parameters["rope_type"] != "default"
and rope_parameters["rope_type"] == "deepseek_yarn"
):
mscale_all_dim = config.rope_parameters.get("mscale_all_dim", False)
scaling_factor = config.rope_parameters["factor"]
mscale_all_dim = rope_parameters.get("mscale_all_dim", False)
scaling_factor = rope_parameters["factor"]
mscale = yarn_get_mscale(scaling_factor, float(mscale_all_dim))
self.scaling = self.scaling * mscale * mscale
else:
@@ -537,7 +543,7 @@ class Glm5NextMLAAttention(nn.Module):
self.indexer_rope_emb: RotaryEmbedding | None = get_rope(
qk_rope_head_dim,
max_position=max_position_embeddings,
rope_parameters=config.rope_parameters,
rope_parameters=rope_parameters,
is_neox_style=not config.indexer_rope_interleave,
)
# The sparse indexer projects from the MLA q-lora rank, which is
+61 -5
View File
@@ -2,8 +2,11 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-5.3-Flash KDA layer with separate convolutions and a bounded safe gate."""
from dataclasses import replace
import torch
from torch import nn
from transformers import Glm5NextTextConfig
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import VllmConfig, get_current_vllm_config
@@ -14,7 +17,14 @@ from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.mamba.checkpoint import (
MambaPrefillCheckpointMetadata,
)
from vllm.model_executor.layers.mamba.gdn.base import GatedDeltaNetAttention
from vllm.model_executor.layers.mamba.kda_checkpoint import (
FlashKDAPrefillCheckpointExporter,
kda_prefill_checkpoint_alignment,
)
from vllm.model_executor.layers.mamba.mamba_utils import (
MambaStateDtypeCalculator,
MambaStateShapeCalculator,
@@ -35,8 +45,8 @@ from vllm.model_executor.utils import (
)
from vllm.platforms import current_platform
from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
from vllm.transformers_utils.configs.glm5_next import Glm5NextConfig
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata
from vllm.v1.kv_cache_interface import MambaSpec
from vllm.v1.worker.workspace import current_workspace_manager
if current_platform.is_rocm():
@@ -155,6 +165,16 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
num_heads: int
conv_size: int
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> MambaSpec:
spec = super().get_kv_cache_spec(vllm_config)
assert isinstance(spec, MambaSpec)
alignment = kda_prefill_checkpoint_alignment(self.kda_prefill_backend)
return replace(
spec,
num_prefill_checkpoint_blocks=int(alignment is not None),
prefill_checkpoint_alignment=alignment,
)
def get_state_dtype(
self,
) -> tuple[torch.dtype, torch.dtype]:
@@ -181,7 +201,7 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
def __init__(
self,
config: Glm5NextConfig,
config: Glm5NextTextConfig,
vllm_config: VllmConfig,
prefix: str = "",
) -> None:
@@ -330,6 +350,7 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
self._flashkda_buffer_specs: (
tuple[tuple[tuple[int, ...], torch.dtype], ...] | None
) = None
self._checkpoint_exporter: FlashKDAPrefillCheckpointExporter | None = None
if self.kda_prefill_backend == "flashkda":
import vllm._flashkda_C # noqa: F401
@@ -339,6 +360,10 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
max_tokens, self.local_num_heads, max_seqs
)
self._flashkda_buffer_specs = (
(
(max_seqs, self.local_num_heads, self.head_dim, self.head_dim),
self.get_state_dtype()[1],
),
(
(max_seqs, self.local_num_heads, self.head_dim, self.head_dim),
self.get_state_dtype()[1],
@@ -351,6 +376,9 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
vllm_config.model_config.dtype,
),
)
self._checkpoint_exporter = FlashKDAPrefillCheckpointExporter(
state_len=self.conv_size - 1
)
def _flashkda_prefill(
self,
@@ -362,6 +390,10 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
initial_state: torch.Tensor,
cu_seqlens: torch.Tensor,
out: torch.Tensor | None,
checkpoint: MambaPrefillCheckpointMetadata | None = None,
raw_qkv: torch.Tensor | None = None,
conv_state: torch.Tensor | None = None,
recurrent_state: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Fused KDA chunked prefill (FlashKDA). Takes the raw gate logits ``g``
and raw ``beta`` logits, l2-normalizes q/k in-kernel and applies the
@@ -370,10 +402,15 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
attention output into ``out`` (a workspace buffer when ``None``) and
returns ``(out, final_state)``."""
assert self._flashkda_buffer_specs is not None
final_state, workspace, workspace_out = (
final_state, checkpoint_state, workspace, workspace_out = (
current_workspace_manager().get_simultaneous(*self._flashkda_buffer_specs)
)
final_state = final_state[: initial_state.shape[0]]
checkpoint_state = (
checkpoint_state[: initial_state.shape[0]]
if checkpoint is not None
else None
)
if out is None:
out = workspace_out[:, : q.shape[1]]
# FlashKDA hardcodes dense q/k/v/g strides; beta may be row-strided.
@@ -392,9 +429,23 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
initial_state.contiguous(),
final_state,
cu_seqlens.contiguous(),
None,
None,
checkpoint_state,
checkpoint.checkpoint_offsets.contiguous()
if checkpoint is not None
else None,
)
if checkpoint is not None:
assert self._checkpoint_exporter is not None
assert raw_qkv is not None and conv_state is not None
assert recurrent_state is not None
self._checkpoint_exporter.export(
checkpoint,
raw_qkv=raw_qkv,
conv_state=conv_state,
recurrent_checkpoint=checkpoint_state,
recurrent_state=recurrent_state,
cu_seqlens=cu_seqlens,
)
return out, final_state
def forward(
@@ -565,6 +616,7 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
q_spec, k_spec, v_spec = qkv_spec.split(self.local_projection_size, dim=-1)
# --- causal conv1d: non-spec path (prefill or plain decode) ---
raw_qkv_ns = qkv_ns
q_ns = k_ns = v_ns = None
if attn_metadata_narrowed.num_prefills > 0:
assert qkv_ns is not None
@@ -662,6 +714,10 @@ class Glm5NextLinearAttention(GatedDeltaNetAttention):
initial_state=initial_state,
cu_seqlens=non_spec_query_start_loc,
out=ns_out,
checkpoint=attn_metadata_narrowed.checkpoint,
raw_qkv=raw_qkv_ns,
conv_state=conv_state,
recurrent_state=recurrent_state,
)
else:
(
+76 -26
View File
@@ -6,6 +6,7 @@ from typing import ClassVar, Literal
import torch
from torch import nn
from transformers import Glm5NextTextConfig
from vllm.config import ParallelConfig, VllmConfig
from vllm.distributed import (
@@ -22,6 +23,7 @@ from vllm.model_executor.layers.fused_moe import (
GateLinear,
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
@@ -82,7 +84,6 @@ from vllm.models.common.ops.sequence_parallel import (
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from vllm.transformers_utils.configs.glm5_next import Glm5NextConfig
from .attention import Glm5NextMLAAttention
from .kda import Glm5NextLinearAttention
@@ -94,6 +95,57 @@ from .multimodal import (
logger = init_logger(__name__)
_MHC_TAU = 0.05
"""mHC routing temperature. A GLM-5.3-Flash trained value that neither the
checkpoint nor `Glm5NextTextConfig` carries."""
_MHC_POST_MULT_VALUE = 2.0
"""mHC post-multiplier. A GLM-5.3-Flash trained value that neither the
checkpoint nor `Glm5NextTextConfig` carries."""
_LOGIT_SCALE = 1.0
"""Output logit scale. A GLM-5.3-Flash trained value that neither the
checkpoint nor `Glm5NextTextConfig` carries."""
_VISION_RMS_NORM_EPS = 1e-6
"""Vision tower RMSNorm epsilon.
GLM-5.3-Flash checkpoints ship `vision_config.rms_norm_eps = 1e-5`, but the
vision tower was trained with 1e-6. Serving with 1e-5 drifts the RMSNorm and
produces repetitive/degraded image descriptions, so force the trained value
regardless of the checkpoint field.
"""
def _is_moe(config: Glm5NextTextConfig) -> bool:
return config.n_routed_experts is not None
def _is_kda_layer(config: Glm5NextTextConfig, layer_idx: int) -> bool:
layer_types = config.layer_types
return (
layer_types is not None
and layer_idx < len(layer_types)
and layer_types[layer_idx] == "linear_attention"
)
def _is_linear_attn(config: Glm5NextTextConfig) -> bool:
layer_types = config.layer_types
return layer_types is not None and "linear_attention" in layer_types
def _validate_supported_config(config: Glm5NextTextConfig) -> None:
"""Reject checkpoints using config options this implementation lacks.
The kpool indexer kernels always keep the incomplete trailing pool, so a
checkpoint asking otherwise would be served silently wrong.
"""
if config.index_topk is not None and not config.index_kpool_always_select_tail:
raise NotImplementedError(
"GLM-5.3 sparse indexer requires index_kpool_always_select_tail=True"
)
class Glm5NextMLP(nn.Module):
def __init__(
@@ -151,7 +203,7 @@ class Glm5NextMLP(nn.Module):
class Glm5NextMoE(nn.Module):
def __init__(
self,
config: Glm5NextConfig,
config: Glm5NextTextConfig,
parallel_config: ParallelConfig,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
@@ -226,10 +278,10 @@ class Glm5NextMoE(nn.Module):
shared_experts=self.shared_experts,
gate=self.gate,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_token,
top_k=config.num_experts_per_tok,
hidden_size=config.hidden_size,
intermediate_size=config.moe_intermediate_size,
renormalize=config.moe_renormalize,
renormalize=config.norm_topk_prob,
quant_config=quant_config,
use_grouped_topk=True,
num_expert_group=config.n_group,
@@ -279,7 +331,7 @@ class Glm5NextDecoderLayer(nn.Module):
def __init__(
self,
vllm_config: VllmConfig,
config: Glm5NextConfig,
config: Glm5NextTextConfig,
layer_idx: int,
prefix: str = "",
topk_indices_buffer: torch.Tensor | None = None,
@@ -294,13 +346,13 @@ class Glm5NextDecoderLayer(nn.Module):
self.hidden_size = config.hidden_size
self.layer_idx = layer_idx
self.is_moe = config.is_moe
self.is_moe = _is_moe(config)
self.num_hidden_layers = config.num_hidden_layers
self.rms_norm_eps = config.rms_norm_eps
self.num_experts = config.n_routed_experts
self.is_mtp_layer = is_mtp_layer
self.mhc = config.mhc
is_kda_layer = not is_mtp_layer and config.is_kda_layer(layer_idx)
is_kda_layer = not is_mtp_layer and _is_kda_layer(config, layer_idx)
self.layer_kind = "kda" if is_kda_layer else "mla"
self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe
@@ -330,7 +382,7 @@ class Glm5NextDecoderLayer(nn.Module):
quant_config=None, # MLA projections are BF16 in checkpoint
prefix=f"{prefix}.self_attn",
topk_indices_buffer=topk_indices_buffer,
skip_rope=config.mla_nope,
skip_rope=config.mla_use_nope,
)
# MTP layers sit past the base model's hidden layers (layer_idx >=
@@ -374,13 +426,13 @@ class Glm5NextDecoderLayer(nn.Module):
if self.mhc and not is_mtp_layer:
# mhc config
self.mhc_num_residual_streams = config.mhc_num_residual_streams
self.mhc_tau = config.mhc_tau
self.mhc_num_residual_streams = config.hc_mult
self.mhc_tau = _MHC_TAU
self.hc_eps = config.hc_eps
self.mhc_sinkhorn_iterations = config.mhc_sinkhorn_iterations
self.mhc_post_mult_value = config.mhc_post_mult_value
self.mhc_sinkhorn_iterations = config.hc_sinkhorn_iters
self.mhc_post_mult_value = _MHC_POST_MULT_VALUE
n = config.mhc_num_residual_streams
n = config.hc_mult
d_model = n * self.hidden_size
mix_hc = (2 + n) * n
@@ -624,7 +676,8 @@ class Glm5NextModel(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
config = vllm_config.model_config.hf_text_config
_validate_supported_config(config)
self.config = config
self.vocab_size = config.vocab_size
@@ -767,7 +820,7 @@ class Glm5NextModel(nn.Module):
(".in_proj_qkvbfg_a", ".f_a_proj", 4),
(".in_proj_qkvbfg_a", ".g_a_proj", 5),
]
if self.config.is_moe:
if _is_moe(self.config):
# Params for weights, fp8 weight scales, fp8 activation scales
# (param_name, weight_name, expert_id, shard_id)
# EPLB: the mapping enumerates physical experts, so it must cover
@@ -797,7 +850,7 @@ class Glm5NextModel(nn.Module):
# GLM-5.3-Flash NoPE checkpoints omit the RoPE rows from
# ``kv_a_proj_with_mqa``; pad them with zeros for the model shape.
kv_a_pad_size = 0
if self.config.mla_nope and self.config.qk_rope_head_dim > 0:
if self.config.mla_use_nope and self.config.qk_rope_head_dim > 0:
kv_a_pad_size = self.config.qk_rope_head_dim
_pending_wk_fp8: dict = {}
@@ -911,7 +964,7 @@ class Glm5NextModel(nn.Module):
if (
name.endswith(".bias")
and name not in params_dict
and not self.config.is_linear_attn
and not _is_linear_attn(self.config)
): # noqa: E501
continue
# Remapping the name of FP8 kv-scale.
@@ -938,7 +991,7 @@ class Glm5NextForCausalLM(
super().__init__()
self.model_config = vllm_config.model_config
self.vllm_config = vllm_config
self.config = self.model_config.hf_config
self.config = self.model_config.hf_text_config
quant_config = vllm_config.quant_config
self.quant_config = quant_config
self.model = Glm5NextModel(
@@ -954,7 +1007,7 @@ class Glm5NextForCausalLM(
else:
self.lm_head = PPMissingLayer()
self.logits_processor = LogitsProcessor(
self.config.vocab_size, scale=self.config.logit_scale
self.config.vocab_size, scale=_LOGIT_SCALE
)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
@@ -987,7 +1040,7 @@ class Glm5NextForCausalLM(
cls, vllm_config: "VllmConfig"
) -> tuple[tuple[int, int], tuple[int, int, int]]:
parallel_config = vllm_config.parallel_config
hf_config = vllm_config.model_config.hf_config
hf_config = vllm_config.model_config.hf_text_config
tp_size = parallel_config.tensor_parallel_size
num_spec = (
vllm_config.speculative_config.num_speculative_tokens
@@ -1091,11 +1144,7 @@ class Glm5NextForConditionalGeneration(
self.visual = Glm5NextVisionTransformer(
config.text_config,
config.vision_config,
# Read eps from the VISION sub-config, not the top-level
# `config.rms_norm_eps`: Glm5NextConfig.__getattribute__ mirrors
# the latter onto text_config (1e-5), silently ignoring the
# vision tower's own (1e-6) rms_norm_eps.
norm_eps=config.vision_config.rms_norm_eps,
norm_eps=_VISION_RMS_NORM_EPS,
# Vision tower ships BF16 weights in this fp8 checkpoint (no
# weight_scale_inv for visual.*), so it must NOT inherit the
# global fp8 quant_config -- doing so incorrectly quantizes
@@ -1103,6 +1152,7 @@ class Glm5NextForConditionalGeneration(
# and yields NaN image features. Mirrors the MLA/KDA proj
# pattern (quant_config=None for BF16 submodules).
quant_config=None,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
@@ -1164,7 +1214,7 @@ class Glm5NextForConditionalGeneration(
def get_spec_layer_idx_from_weight_name(
config: Glm5NextConfig, weight_name: str
config: Glm5NextTextConfig, weight_name: str
) -> int | None:
if hasattr(config, "num_nextn_predict_layers") and (
config.num_nextn_predict_layers > 0
+4 -4
View File
@@ -40,7 +40,7 @@ class Glm5NextMultiTokenPredictorLayer(nn.Module):
def __init__(self, vllm_config: VllmConfig, prefix: str) -> None:
super().__init__()
assert vllm_config.speculative_config is not None
config = vllm_config.speculative_config.draft_model_config.hf_config
config = vllm_config.speculative_config.draft_model_config.hf_text_config
self.config = config
self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -114,7 +114,7 @@ class Glm5NextMultiTokenPredictorLayer(nn.Module):
class Glm5NextMultiTokenPredictor(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
config = vllm_config.model_config.hf_text_config
self.mtp_start_layer_idx = config.num_hidden_layers
self.num_mtp_layers = config.num_nextn_predict_layers
self.layers = torch.nn.ModuleDict(
@@ -211,7 +211,7 @@ class Glm5NextMultiTokenPredictor(nn.Module):
class Glm5NextMTP(nn.Module, DeepseekV2MixtureOfExperts):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
self.config = vllm_config.model_config.hf_config
self.config = vllm_config.model_config.hf_text_config
self.quant_config = vllm_config.quant_config
self.model = Glm5NextMultiTokenPredictor(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
@@ -313,7 +313,7 @@ class Glm5NextMTP(nn.Module, DeepseekV2MixtureOfExperts):
# GLM-5.3-Flash NoPE checkpoints omit the RoPE rows from
# ``kv_a_proj_with_mqa``; the FP8-to-BF16 path pads them for the model.
kv_a_pad_size = 0
if self.config.mla_nope and self.config.qk_rope_head_dim > 0:
if self.config.mla_use_nope and self.config.qk_rope_head_dim > 0:
kv_a_pad_size = self.config.qk_rope_head_dim
for name, loaded_weight in weights:
if "rotary_emb.inv_freq" in name:
+123 -45
View File
@@ -3,12 +3,14 @@
"""GLM-5.3-Flash vision tower and multimodal processor."""
from collections.abc import Mapping
from functools import cached_property, partial
from functools import partial
from typing import Any
import numpy as np
import torch
import torch.nn as nn
from einops import rearrange
from transformers.video_utils import VideoMetadata
from vllm.distributed import (
get_tensor_model_parallel_world_size,
@@ -18,6 +20,7 @@ from vllm.distributed import utils as dist_utils
from vllm.model_executor.layers.activation import SiluAndMulWithClamp
from vllm.model_executor.layers.attention import MMEncoderAttention
from vllm.model_executor.layers.conv import Conv2dLayer, Conv3dLayer
from vllm.model_executor.layers.fusion.mm_input_norm import IdentityInputNorm
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
@@ -351,6 +354,7 @@ class Glm5NextVisionTransformer(nn.Module):
vision_config,
norm_eps: float = 1e-6,
quant_config: QuantizationConfig | None = None,
input_norm: nn.Module | None = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -384,6 +388,7 @@ class Glm5NextVisionTransformer(nn.Module):
in_channels=in_channels,
hidden_size=self.hidden_size,
)
self.input_norm = input_norm if input_norm is not None else IdentityInputNorm()
norm_layer = partial(RMSNorm, eps=norm_eps)
head_dim = self.hidden_size // self.num_heads
@@ -564,7 +569,7 @@ class Glm5NextVisionTransformer(nn.Module):
encoder_metadata: dict[str, torch.Tensor] | None = None,
) -> torch.Tensor:
# patchify
x = x.to(device=self.device, dtype=self.dtype)
x = self.input_norm(x.to(device=self.device), self.dtype)
x = self.patch_embed(x)
if encoder_metadata is not None:
@@ -611,37 +616,48 @@ class Glm5NextVisionTransformer(nn.Module):
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
class Glm5NextProcessingInfo(Glm4vProcessingInfo):
"""Wires up the vLLM-native processor for the multimodal checkpoint.
_MAX_VIDEO_TOKENS = 30000
The checkpoint's ``processor_config.json`` declares a custom ``processor_class``
and stores its image/video processor configs inline (no standalone
``preprocessor_config.json``), so ``AutoProcessor`` cannot resolve the
config. We bypass it and build our own ``Glm5NextProcessor``
(``vllm/transformers_utils/processors/glm5next.py``), a port of the
training-side pipeline that no longer imports transformers' GLM processor
classes. The port applies ``patch_expand_factor`` (checkpoint ships 1)
inside ``smart_resize``'s spatial factor.
class Glm5NextProcessingInfo(Glm4vProcessingInfo):
"""Token-budget geometry for the multimodal checkpoint.
This checkpoint's ``processor_config.json`` ships the token-budget style
(``min_image_tokens`` / ``max_image_tokens``) with no ``size`` key, so the
inherited Glm4v ``size.longest_edge`` path does not apply.
"""
@cached_property
def _glm5_hf_processor(self):
from vllm.transformers_utils.processors.glm5next import Glm5NextProcessor
return Glm5NextProcessor.from_pretrained(self.ctx.model_config.model)
def get_hf_processor(self, **kwargs: object):
return self._glm5_hf_processor
processor = super().get_hf_processor(**kwargs)
# Cap video inputs to keep encoder profiling from starving the KV cache.
video_processor = processor.video_processor
video_processor.max_image_tokens = min(
video_processor.max_image_tokens, _MAX_VIDEO_TOKENS
)
return processor
@staticmethod
def _alignment_factor(proc) -> int:
"""Spatial factor canvases align to, as ``smart_resize`` takes it."""
return proc.patch_size * proc.merge_size * proc.patch_expand_factor
@classmethod
def _pixels_per_token(cls, proc) -> int:
"""Pixels one vision token covers, matching ``smart_resize``'s own
``temporal_factor * factor ** 2``."""
return proc.temporal_patch_size * cls._alignment_factor(proc) ** 2
def _processor_pixel_budget(self, proc) -> tuple[int, int]:
from vllm.transformers_utils.processors.glm5next import _pixel_budget
return _pixel_budget(
proc.min_image_tokens,
proc.max_image_tokens,
proc.patch_size,
proc.merge_size,
proc.temporal_patch_size,
"""(min_pixels, max_pixels) from the processor's token bounds."""
if proc.min_image_tokens is None or proc.max_image_tokens is None:
raise ValueError(
"min_image_tokens and max_image_tokens must be provided by "
"processor_config.json (or per-call kwargs)."
)
pixels_per_token = self._pixels_per_token(proc)
return (
proc.min_image_tokens * pixels_per_token,
proc.max_image_tokens * pixels_per_token,
)
def _get_image_max_pixels(self) -> int:
@@ -656,6 +672,64 @@ class Glm5NextProcessingInfo(Glm4vProcessingInfo):
return int(override)
return self._processor_pixel_budget(self.get_hf_processor().video_processor)[1]
def _get_video_second_idx_glm46v(
self, metadata: dict[str, Any], total_frames: int
) -> list[int]:
"""Timestamps for the video placeholder, from the pixel path's sampler.
The inherited GLM-4.6V timestamp sampling uses different constants
than this checkpoint's ``Glm5NextVideoProcessor`` pixel sampling, so
placeholder count and ``video_grid_thw`` disagree outside 30-300s
durations. Sampling with the pixel path's own policy makes one
timestamp per temporal patch == ``grid_t``.
"""
video_processor = self.get_video_processor()
temporal_patch_size = int(
getattr(video_processor, "temporal_patch_size", 1) or 1
)
video_fps = float(metadata["fps"])
if not metadata.get("do_sample_frames", True):
# The loader already picked the frames and the processor keeps them
# as they are, so the frame count is what was handed in and
# ``frames_indices`` only supplies the timestamp values.
frame_indices = [int(idx) for idx in metadata["frames_indices"]]
num_frames = int(total_frames)
else:
frame_indices = [
int(idx)
for idx in video_processor.sample_frames(
VideoMetadata(
total_num_frames=int(
metadata.get("total_num_frames", total_frames)
),
fps=video_fps,
duration=metadata.get("duration"),
)
)
]
num_frames = len(frame_indices)
if not frame_indices or num_frames <= 0:
# ``duration * fps < 1`` selects no frames at all; the
# pixel path raises an opaque IndexError on the same input a moment
# later, so say what happened while there is still a request.
raise ValueError(
"The GLM-5-Next frame sampler selected no frames for this "
f"video (fps={video_fps}, duration={metadata.get('duration')!r},"
f" total_num_frames={metadata.get('total_num_frames')!r}). "
"Clips shorter than one frame sampling interval cannot be "
"processed."
)
num_padded_frames = num_frames + (-num_frames % temporal_patch_size)
grid_t = max(num_padded_frames // temporal_patch_size, 1)
last = len(frame_indices) - 1
return [
int(frame_indices[min(i * temporal_patch_size, last)] / video_fps)
for i in range(grid_t)
]
def _get_vision_info(
self,
*,
@@ -669,12 +743,13 @@ class Glm5NextProcessingInfo(Glm4vProcessingInfo):
The inherited Glm4v path resolves the pixel budget from
``size.longest_edge`` and resizes with GLM-4V's ``smart_resize``. This
checkpoint's ``processor_config.json`` ships the token-budget style
(``min_image_tokens`` / ``max_image_tokens``) with no ``size`` key, and
the alignment factor carries ``patch_expand_factor`` — resolve both
from the vLLM-native processor so profiling matches runtime geometry.
checkpoint ships token bounds instead, and the alignment factor carries
``patch_expand_factor`` — resolve both from the processor so profiling
matches runtime geometry.
"""
from vllm.transformers_utils.processors.glm5next import smart_resize
from transformers.models.glm5_next.image_processing_glm5_next import (
smart_resize,
)
vision_config = self.get_hf_config().vision_config
patch_size = vision_config.patch_size
@@ -682,22 +757,25 @@ class Glm5NextProcessingInfo(Glm4vProcessingInfo):
temporal_patch_size = vision_config.temporal_patch_size
image_processor = self.get_hf_processor().image_processor
factor = patch_size * merge_size * image_processor.patch_expand_factor
# Keep the profiling search viable when the caller's budget is below
# one aligned canvas of the requested duration.
max_image_pixels = max(max_image_pixels, temporal_patch_size * factor * factor)
factor = self._alignment_factor(image_processor)
temporal_factor = image_processor.temporal_patch_size
# `smart_resize` denominates its bounds in vision tokens. Round down,
# but keep the profiling search viable when the caller's budget is
# below one aligned canvas of the requested duration.
max_image_tokens = max(
max_image_pixels // self._pixels_per_token(image_processor), 1
)
if do_resize:
t = num_frames if num_frames > temporal_patch_size else temporal_patch_size
t = num_frames if num_frames > temporal_factor else temporal_factor
resized_height, resized_width = smart_resize(
t=t,
h=image_height,
w=image_width,
t_factor=temporal_patch_size,
h_factor=factor,
w_factor=factor,
num_frames=t,
height=image_height,
width=image_width,
temporal_factor=temporal_factor,
factor=factor,
min_pixels=1,
max_pixels=max_image_pixels,
max_pixels=max_image_tokens,
)
preprocessed_size = ImageSize(width=resized_width, height=resized_height)
else:
@@ -715,7 +793,7 @@ class Glm5NextProcessingInfo(Glm4vProcessingInfo):
class Glm5NextMultiModalProcessor(Glm4vMultiModalProcessor):
"""The vLLM-native ``Glm5NextProcessor`` extracts image/video features
"""``Glm5NextProcessor`` extracts image/video features
only and passes the prompt text through unchanged, so prompt expansion
(image token repeat, video frame/timestamp structure) is owned by vLLM's
prompt-update machinery — the inherited ``_get_prompt_updates`` builds
+1 -1
View File
@@ -166,7 +166,7 @@ class Indexer(nn.Module):
disable_tp=True,
prefix=f"{prefix}.wk_weights_proj",
)
self.k_norm = LayerNorm(self.head_dim, eps=1e-6)
self.k_norm = LayerNorm(self.head_dim, eps=1e-6, dtype=torch.float32)
self.softmax_scale = self.head_dim**-0.5
self.scale_fmt = "ue8m0"
+5 -1
View File
@@ -323,7 +323,11 @@ class InklingMTP(nn.Module, SupportsMultiModalEmbeddings):
logits = logits[..., : self.logits_processor.org_vocab_size]
return logits
def get_top_tokens(self, hidden_states: torch.Tensor) -> torch.Tensor:
def get_top_tokens(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
"""Greedy draft tokens via rank-local argmax + tiny (value, index)
reduction — no full-vocab logits all-gather. The muP divisor is a
positive scalar, so the argmax is invariant and the scaling is
+5 -1
View File
@@ -323,7 +323,11 @@ class InklingMTP(nn.Module, SupportsMultiModalEmbeddings):
logits = logits[..., : self.logits_processor.org_vocab_size]
return logits
def get_top_tokens(self, hidden_states: torch.Tensor) -> torch.Tensor:
def get_top_tokens(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
"""Greedy draft tokens via rank-local argmax + tiny (value, index)
reduction — no full-vocab logits all-gather. The muP divisor is a
positive scalar, so the argmax is invariant and the scaling is
+56 -6
View File
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import replace
import torch
from einops import rearrange
from torch import nn
@@ -38,7 +40,11 @@ from vllm.model_executor.layers.mamba.ops.causal_conv1d import (
from vllm.model_executor.model_loader.weight_utils import sharded_weight_loader
from vllm.model_executor.utils import set_weight_attrs
from vllm.models.kimi_k3.amd.kda_metadata import KimiK3ROCmKDABackend
from vllm.models.kimi_k3.amd.ops.kda_checkpoint import (
KimiK3ROCmKDAPrefillCheckpointExporter,
)
from vllm.models.kimi_k3.amd.ops.kda_chunk import (
KDA_CHECKPOINT_ALIGNMENT,
is_fused_kda_chunk_supported,
)
from vllm.models.kimi_k3.amd.ops.kda_decode import (
@@ -55,6 +61,7 @@ from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
from vllm.v1.attention.backend import AttentionBackend
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata
from vllm.v1.kv_cache_interface import MambaSpec
logger = init_logger(__name__)
@@ -79,6 +86,23 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
num_spec=self.num_spec,
)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> MambaSpec:
spec = super().get_kv_cache_spec(vllm_config)
assert isinstance(spec, MambaSpec)
# Only the fused path exports the checkpoint snapshots
can_checkpoint = (
self.use_prefill_checkpoint and self.use_fused_chunk and self.use_safe_gate
)
if can_checkpoint and vllm_config.cache_config.mamba_cache_mode == "align":
logger.info_once("Kimi-K3 KDA prefill checkpoint enabled.")
return replace(
spec,
num_prefill_checkpoint_blocks=int(can_checkpoint),
prefill_checkpoint_alignment=(
KDA_CHECKPOINT_ALIGNMENT if can_checkpoint else None
),
)
def __init__(
self,
config: KimiLinearConfig,
@@ -226,6 +250,15 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
"Kimi-K3 KDA prefill backend: %s",
"fused" if self.use_fused_chunk else "triton",
)
# TODO: Remove the extra config arg once tested
self.use_prefill_checkpoint = (
additional_config.get("kda_prefill_checkpoint", True)
if isinstance(additional_config, dict)
else True
)
self._checkpoint_exporter = KimiK3ROCmKDAPrefillCheckpointExporter(
state_len=self.conv_size - 1
)
self.o_norm = FusedRMSNormGated(self.head_dim, activation="sigmoid")
decode_norm_weight = None
@@ -511,10 +544,9 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
assert non_spec_state_indices_tensor is not None
assert has_initial_state is not None
# A mixed non-spec batch is decode-first: the decodes are
# length-1 sequences, and the chunk kernel returns NaN for those.
# Send them to the recurrent kernel and give the chunk kernel the
# prefill tail only.
# Decode-first, so peel the length-1 decodes to the recurrent
# kernel. A spec batch interleaves its non-spec rows, so the
# peel cannot apply and the chunk kernel takes them.
core_attn_out_decode = None
split_non_spec = spec_sequence_masks is None and m.num_decodes > 0
# Without a spec split the non-spec tokens are exactly
@@ -522,7 +554,6 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
# can write their slice straight into it. With one, the tokens
# are interleaved and have to be scattered by index afterwards.
direct = spec_sequence_masks is None
use_fused_chunk = self.use_fused_chunk and spec_sequence_masks is None
if split_non_spec:
assert non_spec_query_start_loc is not None
nd_tok = m.num_decode_tokens
@@ -559,6 +590,22 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
prefill_has_initial_state = has_initial_state
nd_tok = 0
checkpoint = getattr(m, "checkpoint", None)
checkpoint_state = None
checkpoint_offsets = None
checkpoint_state_indices = None
if checkpoint is not None:
assert prefill_query_start_loc is not None
checkpoint_state = recurrent_state
checkpoint_offsets = checkpoint.checkpoint_offsets
checkpoint_state_indices = checkpoint.state_indices
self._checkpoint_exporter.export(
checkpoint,
raw_qkv=mixed_qkv_ns[nd_tok:],
conv_state=conv_state,
cu_seqlens=prefill_query_start_loc,
)
(
core_attn_out_non_spec,
_,
@@ -578,8 +625,11 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
cu_seqlens=prefill_query_start_loc,
chunk_indices=m.chunk_indices,
chunk_offsets=m.chunk_offsets,
use_fused_chunk=use_fused_chunk,
use_fused_chunk=self.use_fused_chunk,
out=core_attn_out[:, nd_tok:num_actual_tokens] if direct else None,
checkpoint_state=checkpoint_state,
checkpoint_offsets=checkpoint_offsets,
checkpoint_state_indices=checkpoint_state_indices,
)
# chunk_kda_prefill updates `recurrent_state` in place, so
# there is no final state to write back here.
+56
View File
@@ -7,16 +7,23 @@ The request classification and cudagraph staging intentionally mirror
differently on device rather than on the host.
"""
from dataclasses import replace
import torch
from vllm.logger import init_logger
from vllm.model_executor.layers.mamba.checkpoint import (
MambaPrefillCheckpointMetadata,
)
from vllm.third_party.flash_linear_attention.ops.utils import FLA_CHUNK_SIZE
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import next_power_of_2
from vllm.v1.attention.backends.gdn_attn import (
GDNAttentionBackend,
GDNAttentionMetadata,
GDNAttentionMetadataBuilder,
)
from vllm.v1.attention.backends.utils import CommonAttentionMetadata
logger = init_logger(__name__)
@@ -86,6 +93,55 @@ def prepare_chunk_metadata_device(
class KimiK3ROCmKDAMetadataBuilder(GDNAttentionMetadataBuilder):
def build( # type: ignore[override]
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
num_accepted_tokens: torch.Tensor | None = None,
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
fast_build: bool = False,
) -> GDNAttentionMetadata:
attn_metadata = super().build(
common_prefix_len,
common_attn_metadata,
num_accepted_tokens,
num_decode_draft_tokens_cpu,
fast_build,
)
if attn_metadata.checkpoint is None:
return attn_metadata
# The shared builder keys checkpoint rows on every request; the ROCm
# prefill path indexes them by prefill_query_start_loc, so rebuild with
# those rows.
return replace(
attn_metadata,
checkpoint=self._build_checkpoint_metadata(
common_attn_metadata, attn_metadata, num_decode_draft_tokens_cpu
),
)
def _build_checkpoint_metadata(
self,
m: CommonAttentionMetadata,
attn_metadata: GDNAttentionMetadata,
num_decode_draft_tokens_cpu: torch.Tensor | None,
) -> MambaPrefillCheckpointMetadata | None:
if attn_metadata.num_prefills == 0:
return None
# request_rows must line up with prefill_query_start_loc, either the
# prefill tail of a decode-first batch, or every non-spec row
# including padding
num_decodes = attn_metadata.num_decodes
request_rows = list(
range(num_decodes, num_decodes + attn_metadata.num_prefills)
)
if attn_metadata.spec_sequence_masks is not None:
assert num_decode_draft_tokens_cpu is not None
request_rows = (
(num_decode_draft_tokens_cpu < 0).nonzero().flatten().tolist()
)
return self.checkpoint_builder.build(m, request_rows)
def _build_chunk_metadata(
self,
prefill_query_start_loc: torch.Tensor,
+170 -8
View File
@@ -7,16 +7,47 @@ from typing import cast
import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.model_executor.layers.attention.attention import get_attention_context
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.mla import MultiHeadLatentAttentionWrapper
from vllm.platforms import current_platform
_OPT_KV_LORA_RANK = 512
_OPT_ROT_DIM = 64
_OPT_MIN_SIZE = 2048
class KimiK3MultiHeadLatentAttentionWrapper(MultiHeadLatentAttentionWrapper):
"""Kimi-K3 MLA wrapper with eager AITER q/kv RMSNorm fusion."""
"""Kimi-K3 MLA wrapper with eager AITER q/kv RMSNorm fusion and a fused
decode Q-prep path."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._use_eager_qk_rmsnorm_fusion = bool(rocm_aiter_ops.is_enabled())
self._fused_qk_prep = self._fused_qk_prep_supported()
self._identity_rope: tuple[torch.Tensor, torch.Tensor] | None = None
def _fused_qk_prep_supported(self) -> bool:
attn = self.mla_attn
if not (
rocm_aiter_ops.is_mla_enabled()
and attn.kv_cache_dtype.startswith("fp8")
and self.kv_lora_rank == _OPT_KV_LORA_RANK
and self.qk_rope_head_dim == _OPT_ROT_DIM
and self.kv_lora_rank * self.num_heads >= _OPT_MIN_SIZE
):
return False
# The fused kernel writes q_out only for slot >= 0, so padded rows would
# be garbage after a DCP query all-gather. PCP and HiSparse rewrite the
# KV inputs/slots before the standalone write, which this path bypasses.
if attn.impl.dcp_world_size > 1 or attn.use_pcp:
return False
if attn.hisparse_cache is not None or attn.q_pad_num_heads is not None:
return False
# Only the W_UK variants reproduced in _fused_decode are supported.
return attn.is_aiter_triton_fp4_bmm_enabled or (
not attn.is_aiter_triton_fp8_bmm_enabled and attn.W_UK_T is not None
)
def _normalize_q_kv(
self,
@@ -38,6 +69,107 @@ class KimiK3MultiHeadLatentAttentionWrapper(MultiHeadLatentAttentionWrapper):
return q_layernorm(q_c), kv_layernorm(kv_c)
def _fused_decode(
self,
q: torch.Tensor,
kv_c_normed: torch.Tensor,
k_pe: torch.Tensor,
positions: torch.Tensor,
output_shape: tuple[int, int],
attn_metadata,
layer,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
) -> torch.Tensor:
"""Decode-only MLA through one fused AITER launch.
Replaces the fp8 KV-cache write plus the ``[ql_nope | q_pe]`` concat and
that query's static fp8 quant with a single
``fused_qk_rope_concat_and_cache_mla``. On an untouched upstream build
the concat and quant already arrive as one inductor-fused kernel, so
this collapses two launches into one.
"""
from aiter.ops.cache import fused_qk_rope_concat_and_cache_mla
attn = self.mla_attn
q_nope, q_pe = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
# (B, N, P) -> (N, B, P)
q_nope_t = q_nope.transpose(0, 1)
# Mirror MLAAttention.forward_impl's W_UK dispatch, *including its
# precedence* -- fp4 is checked before fp8 there, and both flags can be
# set at once. ql_nope must come out bit-identical to what the unfused
# path feeds its concat+quant, because this only replaces what happens
# after the bmm. Both variants return bf16, which the kernel consumes.
if attn.is_aiter_triton_fp4_bmm_enabled:
from aiter.ops.triton.batched_gemm_a16wfp4 import batched_gemm_a16wfp4
ql_nope = batched_gemm_a16wfp4(
q_nope_t,
attn.W_K,
attn.W_K_scale,
transpose_bm=True,
prequant=True,
y_scale=layer._q_scale,
)
else:
assert attn.W_UK_T is not None # guaranteed by _fused_qk_prep_supported
B, N = q_nope.shape[0], q_nope.shape[1]
L = attn.W_UK_T.shape[-1]
ql_nope = q_nope_t.new_empty((B, N, L))
torch.bmm(q_nope_t, attn.W_UK_T, out=ql_nope.transpose(0, 1))
if self._identity_rope is None:
# cos = 1, sin = 0 makes the kernel's RoPE the identity, which is
# what a NoPE model needs. One row suffices because the `_opt`
# kernel clamps `pos` into [0, cos_cache.size(0)); a full-length
# cache would cost ~268 MB at K3's 1M max_position_embeddings.
half = self.qk_rope_head_dim // 2
opts = {"dtype": kv_c_normed.dtype, "device": kv_c_normed.device}
self._identity_rope = (
torch.ones(1, half, **opts),
torch.zeros(1, half, **opts),
)
cos_cache, sin_cache = self._identity_rope
# An fp8 KV cache is allocated as uint8 and re-viewed as fp8 before use;
# the AITER kernel rejects the raw uint8 dtype outright.
fp8_dtype = current_platform.fp8_dtype()
if kv_cache.dtype != fp8_dtype:
kv_cache = kv_cache.view(fp8_dtype)
head_size = attn.kv_lora_rank + self.qk_rope_head_dim
num_tokens, num_heads = ql_nope.shape[:2]
q_out = torch.empty(
(num_tokens, num_heads, head_size),
dtype=fp8_dtype,
device=ql_nope.device,
)
fused_qk_rope_concat_and_cache_mla(
# the W_UK bmm hands back a transposed view; the kernel reads dense
ql_nope.contiguous(),
q_pe,
kv_c_normed,
k_pe.squeeze(1),
kv_cache.view(kv_cache.shape[0], -1, head_size),
q_out,
slot_mapping.flatten(),
layer._k_scale,
layer._q_scale,
positions,
cos_cache,
sin_cache,
is_neox=True,
is_nope_first=True,
)
# forward_mqa is MLA-specific and not on AttentionImpl; MLAAttention
# annotates its own call to it the same way.
attn_out, _ = attn.impl.forward_mqa(q_out, kv_cache, attn_metadata, attn) # type: ignore[attr-defined]
output = q.new_empty(output_shape)
attn._v_up_proj(attn_out, out=output)
return output
def forward(
self,
positions: torch.Tensor,
@@ -106,13 +238,43 @@ class KimiK3MultiHeadLatentAttentionWrapper(MultiHeadLatentAttentionWrapper):
if self.dcp_q_replicate:
q_dcp_replicated, q = q, q_proj_layer._local_view(q)
attn_out = self.mla_attn(
q,
kv_c_normed,
k_pe,
output_shape=(hidden_states.shape[0], self.num_heads * self.v_head_dim),
q_dcp_replicated=q_dcp_replicated,
)
output_shape = (hidden_states.shape[0], self.num_heads * self.v_head_dim)
# The fused decode path covers only the MQA slice, so it is taken for
# decode-only batches; anything else falls through to MLAAttention.
attn_metadata = layer = kv_cache = slot_mapping = None
fuse = self._fused_qk_prep and q_dcp_replicated is None
if fuse:
attn_metadata, layer, kv_cache, slot_mapping = get_attention_context(
self.mla_attn.layer_name
)
fuse = (
attn_metadata is not None
and slot_mapping is not None
and kv_cache.numel() > 0
and attn_metadata.num_actual_tokens == attn_metadata.num_decode_tokens
)
if fuse:
attn_out = self._fused_decode(
q,
kv_c_normed,
k_pe,
positions,
output_shape,
attn_metadata,
layer,
kv_cache,
slot_mapping,
)
else:
attn_out = self.mla_attn(
q,
kv_c_normed,
k_pe,
output_shape=output_shape,
q_dcp_replicated=q_dcp_replicated,
)
if self.g_proj is not None:
attn_out = attn_out * self.g_proj(hidden_states)[0].sigmoid()
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Conv half of the ROCm Kimi-K3 prefill checkpoint."""
from dataclasses import dataclass
import torch
from vllm.model_executor.layers.mamba.checkpoint import (
MambaPrefillCheckpointMetadata,
)
from vllm.model_executor.layers.mamba.kda_checkpoint import (
FlashKDAPrefillCheckpointExporter,
)
@dataclass(frozen=True)
class KimiK3ROCmKDAPrefillCheckpointExporter(FlashKDAPrefillCheckpointExporter):
"""Conv window only; `fused_kda_chunk` writes the recurrent half itself.
`state_len` is `conv_kernel_size - 1`, not the spec-widened conv row.
"""
def export( # type: ignore[override]
self,
checkpoint: MambaPrefillCheckpointMetadata,
*,
raw_qkv: torch.Tensor,
conv_state: torch.Tensor,
cu_seqlens: torch.Tensor,
) -> None:
assert self.state_len is not None
# An empty recurrent checkpoint masks the kernel's recurrent half off.
super().export(
checkpoint,
raw_qkv=raw_qkv,
conv_state=conv_state,
recurrent_checkpoint=conv_state[:, :0],
recurrent_state=conv_state,
cu_seqlens=cu_seqlens,
)
+11 -1
View File
@@ -16,6 +16,7 @@ from vllm.third_party.flash_linear_attention.ops.index import (
prepare_chunk_indices,
prepare_chunk_offsets,
)
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
CHUNK_SIZE = 64
HEAD_DIM = 128
@@ -28,6 +29,15 @@ _DEEP_LEN = 12
_MAX_GROUPS = 32
def _hip_checkpoint_state_indices(state_indices: torch.Tensor) -> torch.Tensor:
"""NULL_BLOCK_ID marks no checkpoint; the HIP kernel skips negative rows."""
return (
torch.where(state_indices != NULL_BLOCK_ID, state_indices, -1)
.to(torch.int32)
.contiguous()
)
@cache
def is_fused_kda_chunk_supported() -> bool:
from vllm.platforms.rocm import on_gfx950
@@ -295,7 +305,7 @@ def fused_kda_chunk(
None if checkpoint_offsets is None else checkpoint_offsets.to(torch.int32),
None
if checkpoint_state_indices is None
else checkpoint_state_indices.to(torch.int32).contiguous(),
else _hip_checkpoint_state_indices(checkpoint_state_indices),
state_cache,
None if state_indices is None else state_indices.to(torch.int32).contiguous(),
has_initial_state,
+7 -1
View File
@@ -155,7 +155,13 @@ def chunk_kda_prefill(
aqk=ws["aqk"],
decay=ws["decay"],
# v is dead by this point, so it doubles as the output buffer.
out=out if out is not None else v,
out=out
if out is not None
else (
v
if v.is_contiguous()
else torch.empty_like(v, memory_format=torch.contiguous_format)
),
scale=scale,
cu_seqlens=cu_seqlens,
initial_state=initial_state,
+47 -175
View File
@@ -17,7 +17,11 @@ from vllm.third_party.flash_linear_attention.ops.chunk_delta_h import (
from vllm.third_party.flash_linear_attention.ops.cumsum import chunk_local_cumsum
from vllm.third_party.flash_linear_attention.ops.index import prepare_chunk_indices
from vllm.third_party.flash_linear_attention.ops.l2norm import l2norm_fwd
from vllm.third_party.flash_linear_attention.ops.op import exp2, log
from vllm.third_party.flash_linear_attention.ops.op import (
exp2,
log,
make_tensor_descriptor,
)
from vllm.third_party.flash_linear_attention.ops.utils import FLA_CHUNK_SIZE, is_amd
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import RCP_LN2, cdiv, next_power_of_2
@@ -90,86 +94,35 @@ def recompute_w_u_fwd_kernel(
T = eos - bos
else:
bos, eos = i_b * T, i_b * T + T
p_b = tl.make_block_ptr(beta + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
b_b = tl.load(p_b, boundary_check=(0,)).to(tl.float32)
o_b = i_t * BT + tl.arange(0, BT)
b_b = tl.load(beta + (bos + o_b) * H + i_h, mask=o_b < T, other=0).to(tl.float32)
p_A = tl.make_block_ptr(
A + (bos * H + i_h) * BT, (T, BT), (H * BT, 1), (i_t * BT, 0), (BT, BT), (1, 0)
)
b_A = tl.load(p_A, boundary_check=(0, 1))
desc_A = make_tensor_descriptor(A + (bos * H + i_h) * BT, [T, BT], [H * BT, 1], [BT, BT])
b_A = desc_A.load([i_t * BT, 0])
desc_v = make_tensor_descriptor(v + (bos * H + i_h) * V, [T, V], [H * V, 1], [BT, BV])
desc_u = make_tensor_descriptor(u + (bos * H + i_h) * V, [T, V], [H * V, 1], [BT, BV])
for i_v in range(tl.cdiv(V, BV)):
p_v = tl.make_block_ptr(
v + (bos * H + i_h) * V,
(T, V),
(H * V, 1),
(i_t * BT, i_v * BV),
(BT, BV),
(1, 0),
)
p_u = tl.make_block_ptr(
u + (bos * H + i_h) * V,
(T, V),
(H * V, 1),
(i_t * BT, i_v * BV),
(BT, BV),
(1, 0),
)
b_v = tl.load(p_v, boundary_check=(0, 1))
b_v = desc_v.load([i_t * BT, i_v * BV])
b_vb = (b_v * b_b[:, None]).to(b_v.dtype)
b_u = tl.dot(b_A, b_vb, input_precision=DOT_PRECISION)
tl.store(p_u, b_u.to(p_u.dtype.element_ty), boundary_check=(0, 1))
desc_u.store([i_t * BT, i_v * BV], b_u.to(desc_u.dtype))
desc_w = make_tensor_descriptor(w + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
desc_k = make_tensor_descriptor(k + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
desc_gk = make_tensor_descriptor(gk + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
for i_k in range(tl.cdiv(K, BK)):
p_w = tl.make_block_ptr(
w + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
p_k = tl.make_block_ptr(
k + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
b_k = tl.load(p_k, boundary_check=(0, 1))
b_k = desc_k.load([i_t * BT, i_k * BK])
b_kb = b_k * b_b[:, None]
p_gk = tl.make_block_ptr(
gk + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
b_gk = tl.load(p_gk, boundary_check=(0, 1))
b_gk = desc_gk.load([i_t * BT, i_k * BK])
b_kb *= exp2(b_gk)
if STORE_QG:
p_q = tl.make_block_ptr(
q + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
p_qg = tl.make_block_ptr(
qg + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
b_q = tl.load(p_q, boundary_check=(0, 1))
desc_q = make_tensor_descriptor(q + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
desc_qg = make_tensor_descriptor(qg + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
b_q = desc_q.load([i_t * BT, i_k * BK])
b_qg = b_q * exp2(b_gk)
tl.store(p_qg, b_qg.to(p_qg.dtype.element_ty), boundary_check=(0, 1))
desc_qg.store([i_t * BT, i_k * BK], b_qg.to(desc_qg.dtype))
if STORE_KG:
last_idx = min(i_t * BT + BT, T) - 1
@@ -180,18 +133,11 @@ def recompute_w_u_fwd_kernel(
)
b_kg = b_k * exp2(b_gn - b_gk)
p_kg = tl.make_block_ptr(
kg + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
tl.store(p_kg, b_kg.to(p_kg.dtype.element_ty), boundary_check=(0, 1))
desc_kg = make_tensor_descriptor(kg + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
desc_kg.store([i_t * BT, i_k * BK], b_kg.to(desc_kg.dtype))
b_w = tl.dot(b_A, b_kb.to(b_k.dtype))
tl.store(p_w, b_w.to(p_w.dtype.element_ty), boundary_check=(0, 1))
desc_w.store([i_t * BT, i_k * BK], b_w.to(desc_w.dtype))
def recompute_w_u_fwd(
@@ -294,70 +240,32 @@ def chunk_gla_fwd_kernel_o(
m_s = tl.arange(0, BT)[:, None] >= tl.arange(0, BT)[None, :]
b_o = tl.zeros([BT, BV], dtype=tl.float32)
desc_q = make_tensor_descriptor(q + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
desc_g = make_tensor_descriptor(g + (bos * H + i_h) * K, [T, K], [H * K, 1], [BT, BK])
desc_h = make_tensor_descriptor(h + (i_tg * H + i_h) * K * V, [V, K], [K, 1], [BV, BK])
for i_k in range(tl.cdiv(K, BK)):
p_q = tl.make_block_ptr(
q + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
p_g = tl.make_block_ptr(
g + (bos * H + i_h) * K,
(T, K),
(H * K, 1),
(i_t * BT, i_k * BK),
(BT, BK),
(1, 0),
)
p_h = tl.make_block_ptr(
h + (i_tg * H + i_h) * K * V,
(V, K),
(K, 1),
(i_v * BV, i_k * BK),
(BV, BK),
(1, 0),
)
# [BT, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
b_q = desc_q.load([i_t * BT, i_k * BK])
b_q = (b_q * scale).to(b_q.dtype)
# [BT, BK]
b_g = tl.load(p_g, boundary_check=(0, 1))
b_g = desc_g.load([i_t * BT, i_k * BK])
# [BT, BK]
b_qg = (b_q * exp2(b_g)).to(b_q.dtype)
# [BV, BK]
b_h = tl.load(p_h, boundary_check=(0, 1))
b_h = desc_h.load([i_v * BV, i_k * BK])
# [BT, BV]
if i_k >= 0:
b_o += tl.dot(b_qg, tl.trans(b_h).to(b_qg.dtype))
p_v = tl.make_block_ptr(
v + (bos * H + i_h) * V,
(T, V),
(H * V, 1),
(i_t * BT, i_v * BV),
(BT, BV),
(1, 0),
)
p_o = tl.make_block_ptr(
o + (bos * H + i_h) * V,
(T, V),
(H * V, 1),
(i_t * BT, i_v * BV),
(BT, BV),
(1, 0),
)
p_A = tl.make_block_ptr(
A + (bos * H + i_h) * BT, (T, BT), (H * BT, 1), (i_t * BT, 0), (BT, BT), (1, 0)
)
desc_v = make_tensor_descriptor(v + (bos * H + i_h) * V, [T, V], [H * V, 1], [BT, BV])
desc_o = make_tensor_descriptor(o + (bos * H + i_h) * V, [T, V], [H * V, 1], [BT, BV])
desc_A = make_tensor_descriptor(A + (bos * H + i_h) * BT, [T, BT], [H * BT, 1], [BT, BT])
# [BT, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
b_v = desc_v.load([i_t * BT, i_v * BV])
# [BT, BT]
b_A = tl.load(p_A, boundary_check=(0, 1))
b_A = desc_A.load([i_t * BT, 0])
b_A = tl.where(m_s, b_A, 0.0).to(b_v.dtype)
b_o += tl.dot(b_A, b_v, allow_tf32=False)
tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
desc_o.store([i_t * BT, i_v * BV], b_o.to(desc_o.dtype))
def chunk_gla_fwd_o_gk(
@@ -479,34 +387,13 @@ def kda_gate_chunk_cumsum_vector_kernel(
i_s -= 1
p_s = tl.make_block_ptr(
s + (bos * H + i_h) * S,
(T, S),
(H * S, 1),
(i_t * BT, i_s * BS),
(BT, BS),
(1, 0),
)
p_o = tl.make_block_ptr(
o + (bos * H + i_h) * S,
(T, S),
(H * S, 1),
(i_t * BT, i_s * BS),
(BT, BS),
(1, 0),
)
desc_s = make_tensor_descriptor(s + (bos * H + i_h) * S, [T, S], [H * S, 1], [BT, BS])
desc_o = make_tensor_descriptor(o + (bos * H + i_h) * S, [T, S], [H * S, 1], [BT, BS])
b_s = tl.load(p_s, boundary_check=(0, 1)).to(tl.float32)
b_s = desc_s.load([i_t * BT, i_s * BS]).to(tl.float32)
if HAS_BIAS:
p_bias = tl.make_block_ptr(
g_bias + i_h * S,
(S,),
(1,),
(i_s * BS,),
(BS,),
(0,),
)
b_bias = tl.load(p_bias, boundary_check=(0,)).to(tl.float32)
desc_bias = make_tensor_descriptor(g_bias + i_h * S, [S], [1], [BS])
b_bias = desc_bias.load([i_s * BS]).to(tl.float32)
b_s += b_bias[None, :]
b_a = tl.exp(tl.load(A_log + i_h).to(tl.float32))
@@ -524,7 +411,7 @@ def kda_gate_chunk_cumsum_vector_kernel(
# Boundary loads return zero, but bias and gate activation can make padded
# rows nonzero. Padding trails valid rows, so it only affects masked stores.
b_o = tl.cumsum(b_gate, axis=0) * cumsum_scale
tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
desc_o.store([i_t * BT, i_s * BS], b_o.to(desc_o.dtype))
def fused_kda_gate_chunk_cumsum(
@@ -862,25 +749,10 @@ def kda_gate_fwd_kernel(
stride_row = H * D
stride_col = 1
g_ptr = tl.make_block_ptr(
base=g + i_h * D,
shape=(T, D),
strides=(stride_row, stride_col),
offsets=(n_t, 0),
block_shape=(BT, BD),
order=(1, 0),
)
desc_g = make_tensor_descriptor(g + i_h * D, [T, D], [stride_row, stride_col], [BT, BD])
desc_y = make_tensor_descriptor(y + i_h * D, [T, D], [stride_row, stride_col], [BT, BD])
y_ptr = tl.make_block_ptr(
base=y + i_h * D,
shape=(T, D),
strides=(stride_row, stride_col),
offsets=(n_t, 0),
block_shape=(BT, BD),
order=(1, 0),
)
b_g = tl.load(g_ptr, boundary_check=(0, 1)).to(tl.float32)
b_g = desc_g.load([n_t, 0]).to(tl.float32)
if HAS_BIAS:
n_d = tl.arange(0, BD)
@@ -898,7 +770,7 @@ def kda_gate_fwd_kernel(
sp = tl.where(use_linear, b_g, (1.0 / beta) * log(1.0 + tl.exp(g_scaled)))
b_y = -b_a * sp
tl.store(y_ptr, b_y.to(y.dtype.element_ty), boundary_check=(0, 1))
desc_y.store([n_t, 0], b_y.to(desc_y.dtype))
def fused_kda_gate(
+59 -165
View File
@@ -12,7 +12,11 @@ import torch
from vllm.platforms import current_platform
from vllm.third_party.flash_linear_attention.ops.index import prepare_chunk_indices
from vllm.third_party.flash_linear_attention.ops.op import exp2, gather
from vllm.third_party.flash_linear_attention.ops.op import (
exp2,
gather,
make_tensor_descriptor,
)
from vllm.third_party.flash_linear_attention.ops.utils import is_gather_supported
from vllm.triton_utils import tl, triton
@@ -125,33 +129,21 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
################################################################################
# off-diagonal blocks
################################################################################
desc_qk = make_tensor_descriptor(q, [T, K], [H * K, 1], [BC, BK])
desc_kk = make_tensor_descriptor(k, [T, K], [H * K, 1], [BC, BK])
desc_gk = make_tensor_descriptor(g, [T, K], [HV * K, 1], [BC, BK])
for i_k in range(tl.cdiv(K, BK)):
o_k = i_k * BK + tl.arange(0, BK)
m_k = o_k < K
p_k0 = tl.make_block_ptr(
k, (T, K), (H * K, 1), (i_tc0, i_k * BK), (BC, BK), (1, 0)
)
p_g0 = tl.make_block_ptr(
g, (T, K), (HV * K, 1), (i_tc0, i_k * BK), (BC, BK), (1, 0)
)
b_k0 = tl.load(p_k0, boundary_check=(0, 1)).to(tl.float32)
b_g0 = tl.load(p_g0, boundary_check=(0, 1)).to(tl.float32)
b_k0 = desc_kk.load([i_tc0, i_k * BK]).to(tl.float32)
b_g0 = desc_gk.load([i_tc0, i_k * BK]).to(tl.float32)
if i_tc1 < T:
p_q1 = tl.make_block_ptr(
q, (T, K), (H * K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0)
)
p_k1 = tl.make_block_ptr(
k, (T, K), (H * K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0)
)
p_g1 = tl.make_block_ptr(
g, (T, K), (HV * K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0)
)
# [BC, BK]
b_q1 = tl.load(p_q1, boundary_check=(0, 1)).to(tl.float32)
b_k1 = tl.load(p_k1, boundary_check=(0, 1)).to(tl.float32)
b_g1 = tl.load(p_g1, boundary_check=(0, 1)).to(tl.float32)
b_q1 = desc_qk.load([i_tc1, i_k * BK]).to(tl.float32)
b_k1 = desc_kk.load([i_tc1, i_k * BK]).to(tl.float32)
b_g1 = desc_gk.load([i_tc1, i_k * BK]).to(tl.float32)
# [BK]
b_gn1 = tl.load(g + i_tc1 * HV * K + o_k, mask=m_k, other=0).to(tl.float32)
# [BC, BK]
@@ -163,19 +155,10 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
b_Akk10 += tl.dot(b_k1 * b_gqn, b_kgt)
if i_tc2 < T:
p_q2 = tl.make_block_ptr(
q, (T, K), (H * K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0)
)
p_k2 = tl.make_block_ptr(
k, (T, K), (H * K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0)
)
p_g2 = tl.make_block_ptr(
g, (T, K), (HV * K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0)
)
# [BC, BK]
b_q2 = tl.load(p_q2, boundary_check=(0, 1)).to(tl.float32)
b_k2 = tl.load(p_k2, boundary_check=(0, 1)).to(tl.float32)
b_g2 = tl.load(p_g2, boundary_check=(0, 1)).to(tl.float32)
b_q2 = desc_qk.load([i_tc2, i_k * BK]).to(tl.float32)
b_k2 = desc_kk.load([i_tc2, i_k * BK]).to(tl.float32)
b_g2 = desc_gk.load([i_tc2, i_k * BK]).to(tl.float32)
# [BK]
b_gn2 = tl.load(g + i_tc2 * HV * K + o_k, mask=m_k, other=0).to(
tl.float32
@@ -195,19 +178,10 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
b_Akk21 += tl.dot(b_kg2, b_kgt)
if i_tc3 < T:
p_q3 = tl.make_block_ptr(
q, (T, K), (H * K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0)
)
p_k3 = tl.make_block_ptr(
k, (T, K), (H * K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0)
)
p_g3 = tl.make_block_ptr(
g, (T, K), (HV * K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0)
)
# [BC, BK]
b_q3 = tl.load(p_q3, boundary_check=(0, 1)).to(tl.float32)
b_k3 = tl.load(p_k3, boundary_check=(0, 1)).to(tl.float32)
b_g3 = tl.load(p_g3, boundary_check=(0, 1)).to(tl.float32)
b_q3 = desc_qk.load([i_tc3, i_k * BK]).to(tl.float32)
b_k3 = desc_kk.load([i_tc3, i_k * BK]).to(tl.float32)
b_g3 = desc_gk.load([i_tc3, i_k * BK]).to(tl.float32)
# [BK]
b_gn3 = tl.load(g + i_tc3 * HV * K + o_k, mask=m_k, other=0).to(
tl.float32
@@ -235,83 +209,36 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
################################################################################
# save off-diagonal Aqk blocks and prepare Akk
################################################################################
desc_Aqk = make_tensor_descriptor(Aqk, [T, BT], [HV * BT, 1], [BC, BC])
p_beta = beta + bos * HV + i_hv
o_bc = tl.arange(0, BC)
if i_tc1 < T:
p_Aqk10 = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_tc1, 0), (BC, BC), (1, 0)
)
tl.store(
p_Aqk10, (b_Aqk10 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
)
desc_Aqk.store([i_tc1, 0], (b_Aqk10 * scale).to(desc_Aqk.dtype))
p_b1 = tl.make_block_ptr(
beta + bos * HV + i_hv, (T,), (HV,), (i_tc1,), (BC,), (0,)
)
b_b1 = tl.load(p_b1, boundary_check=(0,)).to(tl.float32)
b_b1 = tl.load(p_beta + (i_tc1 + o_bc) * HV, mask=i_tc1 + o_bc < T, other=0).to(tl.float32)
b_Akk10 = b_Akk10 * b_b1[:, None]
if i_tc2 < T:
p_Aqk20 = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_tc2, 0), (BC, BC), (1, 0)
)
p_Aqk21 = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_tc2, BC), (BC, BC), (1, 0)
)
tl.store(
p_Aqk20, (b_Aqk20 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
)
tl.store(
p_Aqk21, (b_Aqk21 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
)
desc_Aqk.store([i_tc2, 0], (b_Aqk20 * scale).to(desc_Aqk.dtype))
desc_Aqk.store([i_tc2, BC], (b_Aqk21 * scale).to(desc_Aqk.dtype))
p_b2 = tl.make_block_ptr(
beta + bos * HV + i_hv, (T,), (HV,), (i_tc2,), (BC,), (0,)
)
b_b2 = tl.load(p_b2, boundary_check=(0,)).to(tl.float32)
b_b2 = tl.load(p_beta + (i_tc2 + o_bc) * HV, mask=i_tc2 + o_bc < T, other=0).to(tl.float32)
b_Akk20 = b_Akk20 * b_b2[:, None]
b_Akk21 = b_Akk21 * b_b2[:, None]
if i_tc3 < T:
p_Aqk30 = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_tc3, 0), (BC, BC), (1, 0)
)
p_Aqk31 = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_tc3, BC), (BC, BC), (1, 0)
)
p_Aqk32 = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_tc3, 2 * BC), (BC, BC), (1, 0)
)
tl.store(
p_Aqk30, (b_Aqk30 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
)
tl.store(
p_Aqk31, (b_Aqk31 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
)
tl.store(
p_Aqk32, (b_Aqk32 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
)
desc_Aqk.store([i_tc3, 0], (b_Aqk30 * scale).to(desc_Aqk.dtype))
desc_Aqk.store([i_tc3, BC], (b_Aqk31 * scale).to(desc_Aqk.dtype))
desc_Aqk.store([i_tc3, 2 * BC], (b_Aqk32 * scale).to(desc_Aqk.dtype))
p_b3 = tl.make_block_ptr(
beta + bos * HV + i_hv, (T,), (HV,), (i_tc3,), (BC,), (0,)
)
b_b3 = tl.load(p_b3, boundary_check=(0,)).to(tl.float32)
b_b3 = tl.load(p_beta + (i_tc3 + o_bc) * HV, mask=i_tc3 + o_bc < T, other=0).to(tl.float32)
b_Akk30 = b_Akk30 * b_b3[:, None]
b_Akk31 = b_Akk31 * b_b3[:, None]
b_Akk32 = b_Akk32 * b_b3[:, None]
p_Akk00 = tl.make_block_ptr(
Akkd, (T, BC), (HV * BC, 1), (i_tc0, 0), (BC, BC), (1, 0)
)
p_Akk11 = tl.make_block_ptr(
Akkd, (T, BC), (HV * BC, 1), (i_tc1, 0), (BC, BC), (1, 0)
)
p_Akk22 = tl.make_block_ptr(
Akkd, (T, BC), (HV * BC, 1), (i_tc2, 0), (BC, BC), (1, 0)
)
p_Akk33 = tl.make_block_ptr(
Akkd, (T, BC), (HV * BC, 1), (i_tc3, 0), (BC, BC), (1, 0)
)
b_Ai00 = tl.load(p_Akk00, boundary_check=(0, 1)).to(tl.float32)
b_Ai11 = tl.load(p_Akk11, boundary_check=(0, 1)).to(tl.float32)
b_Ai22 = tl.load(p_Akk22, boundary_check=(0, 1)).to(tl.float32)
b_Ai33 = tl.load(p_Akk33, boundary_check=(0, 1)).to(tl.float32)
desc_Akkd = make_tensor_descriptor(Akkd, [T, BC], [HV * BC, 1], [BC, BC])
b_Ai00 = desc_Akkd.load([i_tc0, 0]).to(tl.float32)
b_Ai11 = desc_Akkd.load([i_tc1, 0]).to(tl.float32)
b_Ai22 = desc_Akkd.load([i_tc2, 0]).to(tl.float32)
b_Ai33 = desc_Akkd.load([i_tc3, 0]).to(tl.float32)
################################################################################
# forward substitution on diagonals
@@ -397,47 +324,18 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
# store full Akk_inv to Akk
################################################################################
p_Akk00 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc0, 0), (BC, BC), (1, 0)
)
p_Akk10 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc1, 0), (BC, BC), (1, 0)
)
p_Akk11 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc1, BC), (BC, BC), (1, 0)
)
p_Akk20 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc2, 0), (BC, BC), (1, 0)
)
p_Akk21 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc2, BC), (BC, BC), (1, 0)
)
p_Akk22 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc2, 2 * BC), (BC, BC), (1, 0)
)
p_Akk30 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc3, 0), (BC, BC), (1, 0)
)
p_Akk31 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc3, BC), (BC, BC), (1, 0)
)
p_Akk32 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc3, 2 * BC), (BC, BC), (1, 0)
)
p_Akk33 = tl.make_block_ptr(
Akk, (T, BT), (HV * BT, 1), (i_tc3, 3 * BC), (BC, BC), (1, 0)
)
desc_Akk = make_tensor_descriptor(Akk, [T, BT], [HV * BT, 1], [BC, BC])
tl.store(p_Akk00, b_Ai00.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk10, b_Ai10.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk11, b_Ai11.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk20, b_Ai20.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk21, b_Ai21.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk22, b_Ai22.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk30, b_Ai30.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk31, b_Ai31.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk32, b_Ai32.to(Akk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk33, b_Ai33.to(Akk.dtype.element_ty), boundary_check=(0, 1))
desc_Akk.store([i_tc0, 0], b_Ai00.to(desc_Akk.dtype))
desc_Akk.store([i_tc1, 0], b_Ai10.to(desc_Akk.dtype))
desc_Akk.store([i_tc1, BC], b_Ai11.to(desc_Akk.dtype))
desc_Akk.store([i_tc2, 0], b_Ai20.to(desc_Akk.dtype))
desc_Akk.store([i_tc2, BC], b_Ai21.to(desc_Akk.dtype))
desc_Akk.store([i_tc2, 2 * BC], b_Ai22.to(desc_Akk.dtype))
desc_Akk.store([i_tc3, 0], b_Ai30.to(desc_Akk.dtype))
desc_Akk.store([i_tc3, BC], b_Ai31.to(desc_Akk.dtype))
desc_Akk.store([i_tc3, 2 * BC], b_Ai32.to(desc_Akk.dtype))
desc_Akk.store([i_tc3, 3 * BC], b_Ai33.to(desc_Akk.dtype))
@triton.heuristics(
@@ -505,16 +403,14 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
Aqk = Aqk + (bos * HV + i_hv) * BT
Akk = Akk + (bos * HV + i_hv) * BC
p_q = tl.make_block_ptr(q, (T, K), (H * K, 1), (i_ti, 0), (BC, BK), (1, 0))
p_k = tl.make_block_ptr(k, (T, K), (H * K, 1), (i_ti, 0), (BC, BK), (1, 0))
p_g = tl.make_block_ptr(g, (T, K), (HV * K, 1), (i_ti, 0), (BC, BK), (1, 0))
desc_q = make_tensor_descriptor(q, [T, K], [H * K, 1], [BC, BK])
desc_k = make_tensor_descriptor(k, [T, K], [H * K, 1], [BC, BK])
desc_g = make_tensor_descriptor(g, [T, K], [HV * K, 1], [BC, BK])
p_beta = tl.make_block_ptr(beta, (T,), (HV,), (i_ti,), (BC,), (0,))
b_q = tl.load(p_q, boundary_check=(0, 1))
b_k = tl.load(p_k, boundary_check=(0, 1))
b_g = tl.load(p_g, boundary_check=(0, 1))
b_beta = tl.load(p_beta, boundary_check=(0,)).to(tl.float32)
b_q = desc_q.load([i_ti, 0])
b_k = desc_k.load([i_ti, 0])
b_g = desc_g.load([i_ti, 0])
b_beta = tl.load(beta + o_c * HV, mask=m_c, other=0).to(tl.float32)
if USE_GATHER:
b_gn = gather(
@@ -546,12 +442,10 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
b_Aqk = tl.where(m_Aqk, b_Aqk, 0.0)
b_Akk = tl.where(m_Akk, b_Akk, 0.0)
p_Aqk = tl.make_block_ptr(
Aqk, (T, BT), (HV * BT, 1), (i_ti, i_i * BC), (BC, BC), (1, 0)
)
p_Akk = tl.make_block_ptr(Akk, (T, BC), (HV * BC, 1), (i_ti, 0), (BC, BC), (1, 0))
tl.store(p_Aqk, b_Aqk.to(Aqk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_Akk, b_Akk.to(Akk.dtype.element_ty), boundary_check=(0, 1))
desc_Aqk = make_tensor_descriptor(Aqk, [T, BT], [HV * BT, 1], [BC, BC])
desc_Akk = make_tensor_descriptor(Akk, [T, BC], [HV * BC, 1], [BC, BC])
desc_Aqk.store([i_ti, i_i * BC], b_Aqk.to(desc_Aqk.dtype))
desc_Akk.store([i_ti, 0], b_Akk.to(desc_Akk.dtype))
tl.debug_barrier()
@@ -566,7 +460,7 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
b_a += tl.sum(b_a[:, None] * b_Ai, 0)
b_Ai = tl.where((o_i == i)[:, None], b_a, b_Ai)
b_Ai += m_I
tl.store(p_Akk, b_Ai.to(Akk.dtype.element_ty), boundary_check=(0, 1))
desc_Akk.store([i_ti, 0], b_Ai.to(desc_Akk.dtype))
def chunk_kda_fwd_intra(
@@ -12,7 +12,7 @@
import torch
from vllm.third_party.flash_linear_attention.ops.op import exp2
from vllm.third_party.flash_linear_attention.ops.op import exp2, make_tensor_descriptor
from vllm.triton_utils import tl, triton
@@ -108,20 +108,15 @@ def chunk_kda_fwd_kernel_intra_token_parallel(
b_k = tl.load(k + i_t * H * K + p_qk, mask=m_hk, other=0).to(tl.float32)
# g: [B, T, HV, K], beta: [B, T, HV]
p_g = tl.make_block_ptr(
g + i_t * HV * K, (HV, K), (K, 1), (i_hg * BH, 0), (BH, BK), (1, 0)
)
p_beta = tl.make_block_ptr(beta + i_t * HV, (HV,), (1,), (i_hg * BH,), (BH,), (0,))
b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
b_beta = tl.load(p_beta, boundary_check=(0,)).to(tl.float32)
desc_g = make_tensor_descriptor(g + i_t * HV * K, [HV, K], [K, 1], [BH, BK])
b_g = desc_g.load([i_hg * BH, 0]).to(tl.float32)
b_beta = tl.load(beta + i_t * HV + o_hv, mask=m_hv, other=0).to(tl.float32)
b_k *= b_beta[:, None]
for j in range(i_ts, min(i_t + 1, min(T, i_ts + BC))):
b_kj = tl.load(k + j * H * K + p_qk, mask=m_hk, other=0).to(tl.float32)
p_gj = tl.make_block_ptr(
g + j * HV * K, (HV, K), (K, 1), (i_hg * BH, 0), (BH, BK), (1, 0)
)
b_gj = tl.load(p_gj, boundary_check=(0, 1)).to(tl.float32)
desc_gj = make_tensor_descriptor(g + j * HV * K, [HV, K], [K, 1], [BH, BK])
b_gj = desc_gj.load([i_hg * BH, 0]).to(tl.float32)
b_kgj = tl.where(m_k[None, :], b_kj * exp2(b_g - b_gj), 0.0)
b_Aqk = tl.sum(b_q * b_kgj, axis=1) * scale
+130 -9
View File
@@ -55,8 +55,10 @@ from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
from vllm.utils.flashinfer import (
flashinfer_fused_kda_decode,
flashinfer_packed_fused_kda_decode,
flashinfer_recurrent_kda,
has_flashinfer_fused_kda_decode,
has_flashinfer_packed_fused_kda_decode,
has_flashinfer_recurrent_kda,
)
from vllm.v1.attention.backend import AttentionBackend
@@ -214,6 +216,73 @@ def is_flashinfer_fused_kda_decode_supported(
)
def is_flashinfer_fused_kda_spec_decode_supported(
num_heads: int,
head_dim: int,
conv_width: int,
num_spec: int,
input_dtype: torch.dtype,
conv_state_dtype: torch.dtype,
recurrent_state_dtype: torch.dtype,
lower_bound: float | None,
use_recoverssm: bool,
) -> bool:
return (
has_flashinfer_packed_fused_kda_decode()
and current_platform.is_device_capability_family(100)
and num_heads in (12, 24, 32, 48, 96)
and head_dim == 128
and conv_width == 4
and 1 <= num_spec <= 7
and input_dtype == torch.bfloat16
and conv_state_dtype == torch.bfloat16
and recurrent_state_dtype in (torch.float32, torch.bfloat16)
and lower_bound is not None
and lower_bound < 0
and not use_recoverssm
and not is_conv_state_dim_first()
)
def resolve_kda_spec_decode_backend(
backend: str,
num_heads: int,
head_dim: int,
conv_width: int,
num_spec: int,
input_dtype: torch.dtype,
conv_state_dtype: torch.dtype,
recurrent_state_dtype: torch.dtype,
lower_bound: float | None,
use_recoverssm: bool,
) -> str:
if backend not in ("auto", "native", "flashinfer"):
raise ValueError(f"Unsupported KDA speculative decode backend: {backend}")
supported = is_flashinfer_fused_kda_spec_decode_supported(
num_heads,
head_dim,
conv_width,
num_spec,
input_dtype,
conv_state_dtype,
recurrent_state_dtype,
lower_bound,
use_recoverssm,
)
if backend == "flashinfer" and not supported:
raise RuntimeError(
"FlashInfer packed fused KDA decode requires its "
"packed_fused_kda_decode API, CUDA SM10x, bfloat16 inputs and "
"convolution state, float32 or bfloat16 recurrent state, D=128, "
"W=4, a bounded gate, 1-7 speculative tokens, a supported head "
"count, the SD convolution-state layout, and RecoverSSM disabled."
)
if supported and backend != "native":
logger.info_once("Using FlashInfer packed fused KDA speculative decode.")
return "flashinfer"
return "native"
def resolve_kda_decode_backend(
backend: str,
num_heads: int,
@@ -537,6 +606,13 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
self.projection_size = self.head_dim * self.num_heads
self.local_projection_size = divide(self.projection_size, self.tp_size)
self.conv_size = kda_config["short_conv_kernel_size"]
self.gate_lower_bound: float | None = kda_config.get("gate_lower_bound", None)
if self.gate_lower_bound is not None:
assert _KDA_GATE_LOGBOUND_MIN <= self.gate_lower_bound < 0, (
"KDA gate lower bound must be in "
f"[{_KDA_GATE_LOGBOUND_MIN}, 0). "
f"Got {self.gate_lower_bound}."
)
assert kda_config.get("use_full_rank_gate", False), (
"KimiK3DeltaAttention requires a full-rank gate"
)
@@ -618,8 +694,28 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
conv_state_dtype,
recurrent_state_dtype,
)
spec_decode_backend = (
additional_config.get("kda_spec_decode_backend", "auto")
if isinstance(additional_config, dict)
else "auto"
)
self.kda_spec_decode_backend = resolve_kda_spec_decode_backend(
spec_decode_backend,
self.local_num_heads,
self.head_dim,
self.conv_size,
self.num_spec,
vllm_config.model_config.dtype,
conv_state_dtype,
recurrent_state_dtype,
self.gate_lower_bound,
self.use_recoverssm,
)
decode_conv1d_weight = None
if self.kda_decode_backend != "triton":
if (
self.kda_decode_backend != "triton"
or self.kda_spec_decode_backend == "flashinfer"
):
decode_conv1d_weight = torch.empty(
3,
self.conv_size,
@@ -648,14 +744,6 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
)
set_weight_attrs(self.A_log, {"weight_loader": a_log_weight_loader(0)})
self.gate_lower_bound: float | None = kda_config.get("gate_lower_bound", None)
if self.gate_lower_bound is not None:
assert _KDA_GATE_LOGBOUND_MIN <= self.gate_lower_bound < 0, (
"KDA gate lower bound must be in "
f"[{_KDA_GATE_LOGBOUND_MIN}, 0). "
f"Got {self.gate_lower_bound}."
)
backend = (
additional_config.get("kda_prefill_backend", "auto")
if isinstance(additional_config, dict)
@@ -860,6 +948,39 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
if not is_conv_state_dim_first():
conv_state = conv_state.transpose(-1, -2)
if (
self.kda_spec_decode_backend == "flashinfer"
and has_spec_decode
and m.num_prefills == 0
and m.num_decodes == 0
):
assert self.decode_conv1d_weight is not None
assert self.decode_norm_weight is not None
assert spec_state_indices_tensor is not None
assert spec_query_start_loc is not None
assert num_accepted_tokens is not None
assert self.gate_lower_bound is not None
# "Packed" is FlashInfer's name for the varlen T>1 speculative path.
flashinfer_packed_fused_kda_decode(
x=mixed_qkv,
weight=self.decode_conv1d_weight,
conv_state=conv_state,
raw_gate=g1,
raw_beta=beta,
A_log=self.A_log,
dt_bias=self.dt_bias,
state_indices=spec_state_indices_tensor,
query_start_loc=spec_query_start_loc,
num_accepted_tokens=num_accepted_tokens,
state=recurrent_state,
output_gate=g2[:num_actual_tokens],
norm_weight=self.decode_norm_weight,
lower_bound=self.gate_lower_bound,
norm_eps=self.o_norm.eps,
output=core_attn_out[:, :num_actual_tokens],
)
return
if (
self.kda_decode_backend != "triton"
and self.decode_conv1d_weight is not None
+1 -9
View File
@@ -18,10 +18,6 @@ from typing import TYPE_CHECKING
import torch
from vllm.config import VllmConfig
from vllm.model_executor.layers.mamba.checkpoint import (
MambaPrefillCheckpointBuilder,
MambaPrefillCheckpointMetadata,
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import async_tensor_h2d
@@ -108,7 +104,7 @@ def _mamba_get_block_table_tensor(
kv_cache_spec: MambaSpec,
mamba_cache_mode: str,
) -> torch.Tensor:
if mamba_cache_mode in ("all", "none"):
if mamba_cache_mode == "none":
return block_table
assert block_table.is_cuda and seq_lens.is_cuda
@@ -271,7 +267,6 @@ class KimiK3KDAMetadata(GDNAttentionMetadata, RecoverSSMMetadata):
recoverssm_context: "KDARecoverSSMCommitContext | None" = field(
default=None, repr=False, compare=False
)
checkpoint: MambaPrefillCheckpointMetadata | None = None
def commit_recoverssm_state(
self, num_accepted_tokens: torch.Tensor
@@ -319,9 +314,6 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
self.checkpoint_builder = MambaPrefillCheckpointBuilder(
vllm_config, kv_cache_spec
)
additional_config = vllm_config.additional_config
self.use_flashinfer_prefill = (
isinstance(additional_config, dict)
+4 -1
View File
@@ -85,6 +85,7 @@ from vllm.model_executor.models.utils import (
make_empty_intermediate_tensors_factory,
make_layers,
maybe_prefix,
spec_decode_needs_target_embed,
)
from vllm.model_executor.models.vision import run_dp_sharded_mrope_vision_model
from vllm.models.minimax_m3.amd.indexer_aiter import (
@@ -1370,7 +1371,9 @@ class MiniMaxM3Model(nn.Module, EagleModelMixin):
self.vocab_size = config.vocab_size
if get_pp_group().is_first_rank:
if get_pp_group().is_first_rank or spec_decode_needs_target_embed(
vllm_config, include_mtp=vllm_config.use_v2_model_runner
):
self.embed_tokens = VocabParallelEmbedding(
config.vocab_size,
config.hidden_size,
+11
View File
@@ -24,6 +24,7 @@ import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
@@ -164,6 +165,10 @@ class MiniMaxM3MTP(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
if vllm_config.use_v2_model_runner and get_pp_group().world_size > 1:
# Preserve embeddings from loaders that bypass load_weights.
self.has_own_embed_tokens = vllm_config.load_config.load_format != "dummy"
assert vllm_config.speculative_config is not None
self.config = vllm_config.speculative_config.draft_model_config.hf_config
self.quant_config = vllm_config.quant_config
@@ -333,4 +338,10 @@ class MiniMaxM3MTP(nn.Module):
f"Failed to load MTP layer {layer_idx} weights from checkpoint."
)
if hasattr(self, "has_own_embed_tokens"):
if "model.embed_tokens.weight" in loaded_params:
self.has_own_embed_tokens = True
elif is_mtp_completeness_check_enabled():
# A complete checkpoint without embeddings borrows the target's.
self.has_own_embed_tokens = False
return loaded_params
@@ -101,6 +101,7 @@ def _index_block_score_kernel(
stride_bt_b,
BLOCK_SIZE_Q: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr, # == SPARSE_BLOCK_SIZE (128)
USE_SPLIT_K: tl.constexpr,
):
pid_q = tl.program_id(0)
pid_bh = tl.program_id(1)
@@ -136,8 +137,19 @@ def _index_block_score_kernel(
bt_row = block_table_ptr + pid_b * stride_bt_b
# Causal window: only blocks up to the last query token's position.
hi = min(seq_len, prefix_len + (pid_q + 1) * BLOCK_SIZE_Q)
for i in tl.range(0, hi, BLOCK_SIZE_K):
blk = i // BLOCK_SIZE_K
num_blocks = tl.cdiv(hi, BLOCK_SIZE_K)
if USE_SPLIT_K:
pid_k = tl.program_id(2)
blocks_per_split = tl.cdiv(num_blocks, tl.num_programs(2))
block_start = pid_k * blocks_per_split
block_end = tl.minimum(block_start + blocks_per_split, num_blocks)
if block_start >= block_end:
return
else:
block_start = 0
block_end = num_blocks
for blk in tl.range(block_start, block_end):
i = blk * BLOCK_SIZE_K
page = tl.load(bt_row + blk).to(tl.int64)
pos = i + off_k
# index-K for this page: [BLOCK_SIZE_D, BLOCK_SIZE_K] (transposed)
@@ -686,7 +698,17 @@ def minimax_m3_index_score(
device=idx_q.device,
)
BLOCK_SIZE_Q = 64
grid_score = (triton.cdiv(max_query_len, BLOCK_SIZE_Q), batch * num_idx_heads)
n_q_tiles = triton.cdiv(max_query_len, BLOCK_SIZE_Q)
SCORE_TARGET_GRID = 48
split_k = max(
1,
min(max_block, SCORE_TARGET_GRID // max(1, n_q_tiles * batch * num_idx_heads)),
)
if not (
current_platform.is_cuda() and current_platform.is_device_capability((12, 0))
):
split_k = 1
grid_score = (n_q_tiles, batch * num_idx_heads, split_k)
_index_block_score_kernel[grid_score](
idx_q,
index_kv_cache,
@@ -709,6 +731,7 @@ def minimax_m3_index_score(
block_table.stride(0),
BLOCK_SIZE_Q=BLOCK_SIZE_Q,
BLOCK_SIZE_K=SPARSE_BLOCK_SIZE,
USE_SPLIT_K=split_k > 1,
)
return score
@@ -822,7 +845,7 @@ def minimax_m3_index_decode_score(
)
# split-K over seq blocks; chunk count depends only on shape constants so
# the grid is fixed within a cuda graph.
TARGET_GRID = 512
TARGET_GRID = 4096
MAX_NUM_KV_CHUNKS = 256
# Use the configured max decode length to avoid Triton recompiles when
# switching between qlen=1 and spec-decode verification batches.
@@ -921,7 +944,7 @@ def minimax_m3_index_decode(
)
# Chunk count is shape-constant (cudagraph-safe), capped so the merge sorts
# pow2(num_topk_chunks * pow2(topk)) candidates.
TOPK_TARGET_GRID = 64
TOPK_TARGET_GRID = 512
MAX_NUM_TOPK_CHUNKS = 16
topk_target = max(
1, min(MAX_NUM_TOPK_CHUNKS, TOPK_TARGET_GRID // max(1, batch * num_idx_heads))
@@ -56,6 +56,7 @@ from vllm.v1.attention.backends.utils import (
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
get_kv_quant_mode,
is_quantized_kv_cache,
)
@@ -531,10 +532,10 @@ def select_main_backend_and_impl_cls(
"""Pick the main attention backend and implementation.
Blackwell (SM100) uses the MSA attend for supported top-k block counts
when the KV cache is BF16 or FP8 E4M3; MI355 uses AITER sparse PA
when the KV cache is BF16, FP8 E4M3 or NVFP4; MI355 uses AITER sparse PA
with shuffle KV cache layout; Other platforms and FP8 E5M2 fall
back to Triton. The MSA modules are imported lazily to avoid import errors
on unsupported platforms.
back to Triton. NVFP4 is MSA-only. The MSA modules are imported lazily to
avoid import errors on unsupported platforms.
"""
use_aiter_sparse_pa = minimax_m3_use_aiter_sparse_pa(
num_kv_heads, emits_sparse_block_table=emits_sparse_block_table
@@ -545,6 +546,18 @@ def select_main_backend_and_impl_cls(
and topk_blocks in (4, 8, 16, 32)
and kv_cache_dtype != "fp8_e5m2"
)
use_nvfp4 = get_kv_quant_mode(kv_cache_dtype).is_nvfp4
if use_nvfp4 and kv_cache_dtype != "nvfp4":
raise ValueError(
"MiniMax M3 sparse attention supports only the 'nvfp4' NVFP4 KV "
f"cache dtype, got {kv_cache_dtype}"
)
if use_nvfp4 and (use_aiter_sparse_pa or not use_msa):
raise ValueError(
"MiniMax M3 sparse attention supports an NVFP4 KV cache only with "
f"the SM100 MSA backend (kv_cache_dtype={kv_cache_dtype}, "
f"topk_blocks={topk_blocks})"
)
selected = (
"AITER_SPARSE_PA" if use_aiter_sparse_pa else ("MSA" if use_msa else "Triton")
)
@@ -565,8 +578,11 @@ def select_main_backend_and_impl_cls(
from vllm.models.minimax_m3.nvidia.sparse_attention_msa import (
MiniMaxM3SparseMSABackend,
MiniMaxM3SparseMSAImpl,
MiniMaxM3SparseMSANvfp4Backend,
)
if use_nvfp4:
return MiniMaxM3SparseMSANvfp4Backend, MiniMaxM3SparseMSAImpl
return MiniMaxM3SparseMSABackend, MiniMaxM3SparseMSAImpl
return MiniMaxM3SparseBackend, MiniMaxM3SparseTritonImpl
+30 -6
View File
@@ -68,6 +68,7 @@ from vllm.model_executor.models.utils import (
make_empty_intermediate_tensors_factory,
make_layers,
maybe_prefix,
spec_decode_needs_target_embed,
)
from vllm.model_executor.models.vision import run_dp_sharded_mrope_vision_model
from vllm.models.minimax_m3.common.encoder_cudagraph import (
@@ -499,6 +500,8 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
# of wrapping the generic Attention module. Keep the same runtime scale
# attributes so FP8 KV reads can honor vLLM's per-layer descale contract.
set_default_quant_scales(self, register_buffer=True)
# The fused insert quantizes k/v into NVFP4 pages with these scales.
self.use_nvfp4_kv = get_kv_quant_mode(self.kv_cache_dtype).is_nvfp4
# Indexer side-cache dtype, mirroring --kv-cache-dtype for the main
# cache (--attention-config '{"indexer_kv_dtype": ...}').
self.indexer_kv_dtype = vllm_config.attention_config.resolve_indexer_kv_dtype(
@@ -610,6 +613,8 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
main_slot_mapping = fwd_slot_mapping[self.layer_name]
index_slot_mapping = fwd_slot_mapping[self.indexer.index_cache.prefix]
q = qkv.new_empty((num_tokens, self.q_size))
# With query_fp8, q is emitted only in fp8; the attend dequantizes it
# into ``q`` for the tokens that run on bf16-query kernels.
query_fp8 = self._allocate_query_fp8(qkv)
# index_q matches the index-K cache dtype (e4m3 for the fp8 score path);
# the fused kernel emits fp8 directly when this buffer is e4m3.
@@ -635,11 +640,13 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
self.kv_cache,
self.indexer.index_cache.kv_cache,
self.kv_cache.size(2), # paged-cache block size
q,
q if query_fp8 is None else None,
index_q,
self.kv_cache_dtype,
q_fp8_out=query_fp8,
q_fp8_scale=self._q_scale_float,
kv_k_scale=self._k_scale if self.use_nvfp4_kv else None,
kv_v_scale=self._v_scale if self.use_nvfp4_kv else None,
)
output = torch.empty_like(q)
@@ -793,6 +800,7 @@ class MiniMaxM3DecoderLayer(nn.Module):
class MiniMaxM3Model(nn.Module, EagleModelMixin):
fall_back_to_pt_during_load = False
supports_aux_hidden_states_over_pp = True
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -803,7 +811,9 @@ class MiniMaxM3Model(nn.Module, EagleModelMixin):
self.vocab_size = config.vocab_size
if get_pp_group().is_first_rank:
if get_pp_group().is_first_rank or spec_decode_needs_target_embed(
vllm_config, include_mtp=vllm_config.use_v2_model_runner
):
self.embed_tokens = VocabParallelEmbedding(
config.vocab_size,
config.hidden_size,
@@ -883,9 +893,18 @@ class MiniMaxM3Model(nn.Module, EagleModelMixin):
hidden_states = intermediate_tensors["hidden_states"]
residual = intermediate_tensors["residual"]
# EAGLE3 is not yet compatible with pipeline parallel
aux_hidden_states = self._maybe_add_hidden_state([], 0, hidden_states, residual)
for idx, layer in enumerate(self.layers[self.start_layer : self.end_layer]):
remote_aux = self.collect_remote_aux_hidden_states(intermediate_tensors)
aux_hidden_states: list[torch.Tensor] = []
if get_pp_group().is_first_rank:
self._maybe_add_hidden_state(
aux_hidden_states, self.start_layer, hidden_states, residual
)
# Preserve the entry tap before in-place residual updates.
if aux_hidden_states:
aux_hidden_states[0] = aux_hidden_states[0].clone()
for idx, layer in enumerate(
self.layers[self.start_layer : self.end_layer], start=self.start_layer
):
hidden_states, residual = layer(positions, hidden_states, residual)
self._maybe_add_hidden_state(
aux_hidden_states, idx + 1, hidden_states, residual
@@ -893,7 +912,11 @@ class MiniMaxM3Model(nn.Module, EagleModelMixin):
if not get_pp_group().is_last_rank:
return IntermediateTensors(
{"hidden_states": hidden_states, "residual": residual}
{
"hidden_states": hidden_states,
"residual": residual,
**self.pack_local_aux_hidden_states(aux_hidden_states),
}
)
if self.fuse_final_norm_allreduce:
@@ -903,6 +926,7 @@ class MiniMaxM3Model(nn.Module, EagleModelMixin):
else:
hidden_states, _ = self.norm(hidden_states, residual)
aux_hidden_states = remote_aux + aux_hidden_states
if len(aux_hidden_states) > 0:
return hidden_states, aux_hidden_states
return hidden_states
@@ -12,6 +12,7 @@ import torch
from vllm.config.attention import MiniMaxM3MSADecodeBackend
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.v1.kv_cache_interface import get_kv_quant_mode
_MAX_NUM_Q_HEADS = 64
_MAX_NUM_KV_HEADS = 4
@@ -23,9 +24,36 @@ _TOPK = 16
_MAX_QUERY_HEAD_ROWS = 65536
_MAX_DECODE_QUERY_LEN = 32
# Kernel benchmarks put the CUTLASS crossover at 16 requests for TP1 and TP4.
# NVFP4 has no Triton fallback, so it takes CUTLASS at every batch size.
_MIN_CUTLASS_BATCH_SIZE = 16
def is_nvfp4_kv_cache(kv_cache_dtype: str) -> bool:
return get_kv_quant_mode(kv_cache_dtype).is_nvfp4
def nvfp4_kv_cache_views(
kv_cache: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Return the K data, K scale, V data and V scale views of an NVFP4 cache.
``kv_cache`` is uint8 ``[pages, 2 * Hkv, page_size, 72]``; slot
``2 * head + side`` (K = 0, V = 1) is that head's E2M1 data
``[page_size, 64]`` followed by its E4M3 block scales ``[page_size, 8]``,
the one page layout ``fmha_sm100`` reads.
"""
from vllm.third_party.fmha_sm100.nvfp4_kv import nvfp4_head_slot_views
return nvfp4_head_slot_views(*nvfp4_kv_cache_slots(kv_cache))
def nvfp4_kv_cache_slots(
kv_cache: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Return the per-head K and V slots of an NVFP4 cache."""
return kv_cache[:, 0::2], kv_cache[:, 1::2]
@dataclass
class MSACutlassDecodeMetadata:
plan: Any
@@ -91,6 +119,9 @@ class MSACutlassDecodePlanCache:
use_fp8_kvcache=True,
split_prefill_decode=False,
device=device,
# The Q8KV4 route keeps plan-time lengths and its own page offsets,
# which this cached plan does not refresh.
decode_backend="kv_mode3",
)
plan_info = plan[3]
@@ -214,11 +245,12 @@ def supports_cutlass_sparse_decode(
topk_blocks: int,
) -> bool:
"""Return whether static model geometry supports CUTLASS sparse decode."""
nvfp4 = is_nvfp4_kv_cache(kv_cache_dtype)
return (
decode_backend == "cutlass"
(decode_backend == "cutlass" or nvfp4)
and current_platform.is_cuda()
and current_platform.is_device_capability_family(100)
and kv_cache_dtype in ("fp8", "fp8_e4m3")
and (kv_cache_dtype in ("fp8", "fp8_e4m3") or nvfp4)
and _supported_head_geometry(num_q_heads, num_kv_heads)
and page_size == _PAGE_SIZE
and topk_blocks == _TOPK
@@ -248,7 +280,7 @@ def should_prepare_decode_metadata(
topk_blocks=topk_blocks,
)
and 1 <= decode_query_len <= _MAX_DECODE_QUERY_LEN
and batch_size >= _MIN_CUTLASS_BATCH_SIZE
and (batch_size >= _MIN_CUTLASS_BATCH_SIZE or is_nvfp4_kv_cache(kv_cache_dtype))
and total_q * num_q_heads <= _MAX_QUERY_HEAD_ROWS
)
@@ -292,9 +324,22 @@ def msa_cutlass_sparse_decode(
q_scale_float: float,
k_scale_float: float,
v_scale_float: float,
k_scale: torch.Tensor | None = None,
v_scale: torch.Tensor | None = None,
) -> None:
"""Run CUTLASS sparse decode with metadata prepared by the MSA builder."""
key, value = kv_cache.split(_HEAD_DIM, dim=-1)
"""Run CUTLASS sparse decode with metadata prepared by the MSA builder.
NVFP4 caches are uint8 head-slot pages (see ``nvfp4_kv_cache_views``) and
take the device global scales ``k_scale``/``v_scale``.
"""
if kv_cache.dtype == torch.uint8:
assert k_scale is not None and v_scale is not None
key, value = nvfp4_kv_cache_slots(kv_cache)
k_scale_arg: float | torch.Tensor = k_scale
v_scale_arg: float | torch.Tensor = v_scale
else:
key, value = kv_cache.split(_HEAD_DIM, dim=-1)
k_scale_arg, v_scale_arg = k_scale_float, v_scale_float
from vllm.third_party.fmha_sm100.api import fmha_sm100
@@ -310,7 +355,7 @@ def msa_cutlass_sparse_decode(
output_o=True,
sm_scale=scale,
q_scale=q_scale_float,
k_scale=k_scale_float,
v_scale=v_scale_float,
k_scale=k_scale_arg,
v_scale=v_scale_arg,
o_scale=1.0,
)
+11
View File
@@ -8,6 +8,7 @@ import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
@@ -146,6 +147,10 @@ class MiniMaxM3MTP(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
if vllm_config.use_v2_model_runner and get_pp_group().world_size > 1:
# Preserve embeddings from loaders that bypass load_weights.
self.has_own_embed_tokens = vllm_config.load_config.load_format != "dummy"
assert vllm_config.speculative_config is not None
self.config = vllm_config.speculative_config.draft_model_config.hf_config
self.quant_config = vllm_config.quant_config
@@ -315,4 +320,10 @@ class MiniMaxM3MTP(nn.Module):
f"Failed to load MTP layer {layer_idx} weights from checkpoint."
)
if hasattr(self, "has_own_embed_tokens"):
if "model.embed_tokens.weight" in loaded_params:
self.has_own_embed_tokens = True
elif is_mtp_completeness_check_enabled():
# A complete checkpoint without embeddings borrows the target's.
self.has_own_embed_tokens = False
return loaded_params
@@ -4,15 +4,18 @@
Prefill attends with ``fmha_sm100`` (``build_k2q_csr`` + ``sparse_atten_func``).
Decode uses Triton split-K by default, with an opt-in CUTLASS ``fmha_sm100``
path for regular decode and speculative verification.
path for regular decode and speculative verification. NVFP4 KV caches read the
vLLM packed pages directly in both prefill and CUTLASS decode.
"""
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import ClassVar
import torch
from vllm.config import VllmConfig
from vllm.config.attention import MiniMaxM3MSADecodeBackend
from vllm.config.cache import CacheDType
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.models.minimax_m3.common.ops.sparse_attn import (
@@ -29,20 +32,33 @@ from vllm.models.minimax_m3.common.sparse_attention import (
from vllm.models.minimax_m3.nvidia.msa_cutlass_sparse_decode import (
MSACutlassDecodeMetadata,
MSACutlassDecodePlanCache,
is_nvfp4_kv_cache,
msa_cutlass_sparse_decode,
nvfp4_kv_cache_views,
prepare_decode_metadata,
should_prepare_decode_metadata,
supports_cutlass_sparse_decode,
)
from vllm.utils.torch_utils import get_dtype_size, nvfp4_kv_cache_full_dim
from vllm.v1.attention.backend import (
AttentionLayer,
CommonAttentionMetadata,
)
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
logger = init_logger(__name__)
def _dequantize_query(
query_fp8: torch.Tensor, q_scale: float, out: torch.Tensor
) -> torch.Tensor:
"""Write ``query_fp8 * q_scale`` into ``out`` (E4M3 is exact in BF16)."""
out.copy_(query_fp8)
if q_scale != 1.0:
out.mul_(q_scale)
return out
class MiniMaxM3SparseMSABackend(MiniMaxM3SparseBackend):
"""MiniMax M3 backend with NVIDIA MSA-specific decode metadata."""
@@ -51,6 +67,30 @@ class MiniMaxM3SparseMSABackend(MiniMaxM3SparseBackend):
return MiniMaxM3SparseMSAMetadataBuilder
class MiniMaxM3SparseMSANvfp4Backend(MiniMaxM3SparseMSABackend):
"""MSA backend over HND NVFP4 KV cache pages in per-head K/V slots."""
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["nvfp4"]
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
"""Store each head's K and V as two slots of packed data + block scales
(see ``nvfp4_kv_cache_views``)."""
if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4:
return spec
return replace(
spec,
num_head_slots=2 * spec.num_kv_heads,
state_content_bytes=nvfp4_kv_cache_full_dim(spec.head_size)
* get_dtype_size(spec.dtype),
)
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
# Every head's K/V slots are one contiguous run of the page.
return (KVCacheLayout.LBHNC,)
class MiniMaxM3SparseCutlassBackend(MiniMaxM3SparseMSABackend):
"""Attention-backend alias selecting CUTLASS MSA sparse decode."""
@@ -166,6 +206,7 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
topk_blocks=topk_blocks,
sparse_block_size=sparse_block_size,
)
self.use_nvfp4_kv = is_nvfp4_kv_cache(kv_cache_dtype)
self.use_cutlass_decode = supports_cutlass_sparse_decode(
decode_backend=msa_decode_backend,
num_q_heads=self.num_heads,
@@ -174,6 +215,12 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
page_size=self.block_size,
topk_blocks=self.topk_blocks,
)
if self.use_nvfp4_kv and not self.use_cutlass_decode:
raise ValueError(
"MiniMax M3 NVFP4 KV cache requires CUTLASS MSA sparse decode "
f"(num_heads={self.num_heads}, num_kv_heads={self.num_kv_heads}, "
f"block_size={self.block_size}, topk_blocks={self.topk_blocks})"
)
logger.info_once(
"MiniMax M3 MSA sparse decode selected %s",
"CUTLASS" if self.use_cutlass_decode else "Triton",
@@ -218,9 +265,17 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
hd = self.head_size
q = query[:num_tokens].view(-1, self.num_heads, hd)
out = output[:num_tokens].view(-1, self.num_heads, hd)
kv_cache = (
kv_cache.view(self.kv_cache_fp8_dtype) if self.use_fp8_kv else kv_cache
# Given query_fp8, it is the only q the fused insert wrote: CUTLASS
# decode reads it directly, and the bf16-query kernels read it
# dequantized into ``query``.
q_fp8 = (
None
if query_fp8 is None
else query_fp8[:num_tokens].view(-1, self.num_heads, hd)
)
q_scale_float = getattr(layer, "_q_scale_float", 1.0)
if self.use_fp8_kv and not self.use_nvfp4_kv:
kv_cache = kv_cache.view(self.kv_cache_fp8_dtype)
k_scale = getattr(layer, "_k_scale", None) if self.use_fp8_kv else None
v_scale = getattr(layer, "_v_scale", None) if self.use_fp8_kv else None
@@ -234,21 +289,31 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
else None
)
if self.use_cutlass_decode and msa_metadata is not None:
assert query_fp8 is not None
assert q_fp8 is not None
msa_cutlass_sparse_decode(
query_fp8[:nd].view(-1, self.num_heads, hd),
q_fp8[:nd],
kv_cache,
topk[:nd],
out[:nd],
msa_metadata,
scale=self.scale,
q_scale_float=getattr(layer, "_q_scale_float", 1.0),
q_scale_float=q_scale_float,
k_scale_float=getattr(layer, "_k_scale_float", 1.0),
v_scale_float=getattr(layer, "_v_scale_float", 1.0),
k_scale=k_scale if self.use_nvfp4_kv else None,
v_scale=v_scale if self.use_nvfp4_kv else None,
)
elif self.use_nvfp4_kv:
raise RuntimeError(
"MiniMax M3 NVFP4 KV cache has no Triton decode fallback; "
f"CUTLASS decode was not planned for {main_md.num_decodes} "
f"requests with query length {d.decode_query_len}"
)
else:
minimax_m3_sparse_attn_decode(
q[:nd],
q[:nd]
if q_fp8 is None
else _dequantize_query(q_fp8[:nd], q_scale_float, q[:nd]),
kv_cache,
topk[:nd].transpose(0, 1),
d.block_table,
@@ -266,6 +331,7 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
from vllm.third_party.fmha_sm100.sparse import (
build_k2q_csr,
sparse_atten_func,
sparse_atten_nvfp4_kv_func,
)
p = main_md.prefill
@@ -273,8 +339,11 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
# [H, prefill, MK] transposed view; build_k2q_csr consumes the
# strided view directly (topK stays innermost-contiguous).
prefill_topk = topk[nd:num_tokens].transpose(0, 1)
qp = q[nd:]
k_cache, v_cache = kv_cache.split(self.head_size, dim=-1)
qp = (
q[nd:]
if q_fp8 is None
else _dequantize_query(q_fp8[nd:], q_scale_float, q[nd:])
)
k2q_row_ptr, k2q_q_indices, schedule = build_k2q_csr(
prefill_topk,
p.cu_seqlens_q,
@@ -287,6 +356,34 @@ class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl):
qhead_per_kv=qp.shape[1] // self.num_kv_heads,
return_schedule=True,
)
if self.use_nvfp4_kv:
k_data, k_sf, v_data, v_sf = nvfp4_kv_cache_views(kv_cache)
sparse_atten_nvfp4_kv_func(
qp,
k_data,
v_data,
k_sf,
v_sf,
k_scale,
v_scale,
k2q_row_ptr,
k2q_q_indices,
self.topk_blocks,
cu_seqlens_q=p.cu_seqlens_q,
cu_seqlens_k=p.cu_seqlens_k,
max_seqlen_q=p.max_query_len,
max_seqlen_k=p.max_seq_len,
blk_kv=SPARSE_BLOCK_SIZE,
causal=True,
softmax_scale=self.scale,
page_table=p.block_table,
seqused_k=p.seq_lens,
schedule=schedule,
out=out[nd:],
kv_layout="vllm",
)
return output
k_cache, v_cache = kv_cache.split(self.head_size, dim=-1)
sparse_atten_func(
qp,
k_cache,
+1 -3
View File
@@ -8,6 +8,7 @@ from typing import cast
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import VllmConfig
from vllm.forward_context import get_forward_context
@@ -15,9 +16,6 @@ from vllm.model_executor.layers.layernorm import GemmaRMSNorm
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from ..common.qsa_cache import (
QSACompressedKeyCache,
+10 -42
View File
@@ -7,6 +7,7 @@ from itertools import islice
import torch
from torch import nn
from transformers import Qwen4ExpConfig, Qwen4ExpTextConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import VllmConfig
@@ -47,7 +48,6 @@ from vllm.model_executor.models.qwen3_5 import (
)
from vllm.model_executor.models.qwen3_next import (
Qwen3NextAttention,
Qwen3NextMLP,
Qwen3NextSparseMoeBlock,
)
from vllm.model_executor.models.qwen3_vl import (
@@ -71,14 +71,10 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.inputs import MultiModalFeatureSpec
from vllm.sequence import IntermediateTensors
from vllm.tokenizers.registry import cached_tokenizer_from_config
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.kv_cache_interface import MambaSpec
from ..common.mtp import make_mtp_hidden_buffer
from ..config import ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
from .ple_layer import Qwen4ExpPLELayer
@@ -180,8 +176,6 @@ class Qwen4ExpDecoderLayer(nn.Module):
) -> None:
super().__init__()
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
model_config = vllm_config.model_config
cache_config = vllm_config.cache_config
quant_config = vllm_config.quant_config
self.config = config
@@ -214,16 +208,13 @@ class Qwen4ExpDecoderLayer(nn.Module):
prefix=f"{prefix}.linear_attn",
gqa_interleaved_layout=False,
)
elif layer_type in ATTENTION_LAYER_TYPES:
use_qsa = (
layer_type == QSA_LAYER_TYPE
or getattr(config, "indexer_n_heads", None) is not None
)
elif layer_type == "qwen_sparse_attention":
use_qsa = getattr(config, "indexer_n_heads", None) is not None
if not use_qsa:
self.self_attn = Qwen3NextAttention(
config,
model_config=model_config,
cache_config=cache_config,
model_config=vllm_config.model_config,
cache_config=vllm_config.cache_config,
quant_config=quant_config,
prefix=f"{prefix}.self_attn",
)
@@ -238,24 +229,9 @@ class Qwen4ExpDecoderLayer(nn.Module):
else:
raise ValueError(f"Invalid layer_type {layer_type}")
mlp_only_layers = getattr(config, "mlp_only_layers", [])
num_experts = getattr(config, "num_experts", 0) or 0
absolute_layer_id = self.layer_idx + 1
is_moe_layer = self.layer_idx not in mlp_only_layers and (
num_experts > 0 and absolute_layer_id % config.decoder_sparse_step == 0
self.mlp = Qwen4ExpSparseMoeBlock(
vllm_config=vllm_config, prefix=f"{prefix}.mlp"
)
if is_moe_layer:
self.mlp = Qwen4ExpSparseMoeBlock(
vllm_config=vllm_config, prefix=f"{prefix}.mlp"
)
else:
self.mlp = Qwen3NextMLP(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
prefix=f"{prefix}.mlp",
)
hc_config = HyperConnectionConfig(
hc_count=config.hc_count,
@@ -314,7 +290,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
if self.layer_type == "linear_attention":
attn_out = self.linear_attn(hidden_states=block_input)
elif self.layer_type in ATTENTION_LAYER_TYPES:
elif self.layer_type == "qwen_sparse_attention":
attn_out = self.self_attn(
hidden_states=block_input,
positions=positions,
@@ -405,11 +381,8 @@ class Qwen4ExpModel(nn.Module):
self._qsa_layer_ids = frozenset(
layer_idx
for layer_idx, layer_type in enumerate(config.layer_types)
if layer_type == QSA_LAYER_TYPE
or (
layer_type == "full_attention"
and getattr(config, "indexer_n_heads", None) is not None
)
if layer_type == "qwen_sparse_attention"
and getattr(config, "indexer_n_heads", None) is not None
)
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, config.hidden_size)
@@ -625,11 +598,6 @@ class Qwen4ExpForCausalLM(
self.quant_config = vllm_config.quant_config
self.config = config
self.scheduler_config = vllm_config.scheduler_config
if vllm_config.cache_config.mamba_cache_mode == "all":
raise NotImplementedError(
"Qwen4Exp currently does not support 'all' prefix caching, "
"please use '--mamba-cache-mode=align' instead"
)
self.model = Qwen4ExpModel(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
+2 -11
View File
@@ -18,6 +18,7 @@ from collections.abc import Iterable
import regex as re
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import VllmConfig, replace, set_current_vllm_config
@@ -45,9 +46,6 @@ from vllm.model_executor.models.utils import (
maybe_prefix,
)
from vllm.sequence import IntermediateTensors
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
@@ -222,7 +220,7 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
self.layers = nn.ModuleList(
Qwen4ExpDecoderLayer(
draft_vllm_config,
layer_type="full_attention",
layer_type="qwen_sparse_attention",
prefix=f"{prefix}.layers.{self.mtp_start_layer_idx + idx}",
)
for idx in range(self.num_mtp_layers)
@@ -395,13 +393,6 @@ class Qwen4ExpMTP(LocalArgmaxMixin, nn.Module, SupportsPP, Qwen4ExpMixtureOfExpe
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
self.vllm_config = vllm_config
cache_config = vllm_config.cache_config
if cache_config.mamba_cache_mode == "all":
raise NotImplementedError(
"Qwen4ExpMTP currently does not support 'all' prefix caching, "
"please use '--mamba-cache-mode=align' instead"
)
self.quant_config = vllm_config.quant_config
super().__init__()
+1 -3
View File
@@ -8,6 +8,7 @@ from collections.abc import Iterable, Sequence
import torch
import torch.nn.functional as F
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import CacheConfig, ModelConfig, VllmConfig, get_current_vllm_config
from vllm.forward_context import get_forward_context
@@ -23,9 +24,6 @@ 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,
)
from vllm.utils.torch_utils import direct_register_custom_op
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.attention.backends.short_conv_attn import (
+1 -3
View File
@@ -8,6 +8,7 @@ from typing import ClassVar, cast
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
@@ -23,9 +24,6 @@ from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding import get_rope
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
from vllm.platforms import current_platform
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from vllm.utils.torch_utils import (
LayerNameType,
_encode_layer_name,
+57 -15
View File
@@ -7,6 +7,7 @@ n-gram embedding table can be kept in pinned host memory and looked up through
Unified Virtual Addressing on any CUDA-alike platform.
"""
import threading
from abc import ABC, abstractmethod
from typing import ClassVar
@@ -22,6 +23,9 @@ from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
QuantizeMethodBase,
)
from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors import ( # noqa: E501
CompressedTensorsConfig,
)
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptMixedPrecisionConfig,
@@ -181,6 +185,11 @@ class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
quant_config, ModelOptQuantConfigBase
) and quant_config.is_layer_excluded(prefix):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if (
isinstance(quant_config, CompressedTensorsConfig)
and quant_config.get_scheme_dict(None, layer_name=prefix) is None
):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if not isinstance(quant_config, Fp8Config):
raise NotImplementedError(
"Qwen4Exp PLE embedding does not support quantization config "
@@ -422,14 +431,11 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
)
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._prefetch_stream: torch.cuda.Stream | None = None
self._prefetch_buffer: torch.Tensor | None = None
self._prefetch_alloc_lock = threading.Lock()
self._prefetch_rows = max_total_tokens * self.etp_data_parallel_size
self._num_ngram_heads = num_ngram_heads
self._output_dim = num_ngram_heads * self.embedding_dim
def allocate_embedding_weight(
@@ -520,10 +526,42 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
ngram_ids: torch.Tensor,
) -> None:
"""Gather ETP IDs and launch their UVA lookup on the side stream."""
buffer = self._prefetch_buffer
if buffer is None:
# First use allocates. The eager profile run always precedes
# cudagraph capture, so allocation never happens mid-capture;
# the lock keeps concurrent first callers from tearing the
# stream/buffer pair.
with self._prefetch_alloc_lock:
buffer = self._prefetch_buffer
if buffer is None:
if torch.cuda.is_current_stream_capturing():
raise RuntimeError(
"pinned PLE prefetch buffer must be allocated "
"eagerly, before cudagraph capture"
)
self._prefetch_stream = torch.cuda.Stream(
device=self._uva_weight.device
)
buffer = torch.empty(
self._prefetch_rows,
self._num_ngram_heads,
self.embedding_dim,
dtype=self.weight.dtype,
device=self._uva_weight.device,
)
self._prefetch_buffer = buffer
prefetch_stream = self._prefetch_stream
if prefetch_stream is None:
raise RuntimeError("pinned PLE prefetch stream was not allocated")
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
if gathered_ids.shape[0] > buffer.shape[0]:
raise ValueError(
f"pinned PLE prefetch buffer holds {buffer.shape[0]} rows, "
f"but the batch needs {gathered_ids.shape[0]}"
)
active_output = buffer[: gathered_ids.shape[0]]
prefetch_stream.wait_stream(torch.cuda.current_stream())
gathered_ids.record_stream(prefetch_stream)
with torch.cuda.stream(prefetch_stream):
@@ -536,7 +574,10 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
output: torch.Tensor,
) -> None:
"""Join the side stream, reduce ETP shards, and select local rows."""
torch.cuda.current_stream().wait_stream(self._prefetch_stream)
prefetch_stream = self._prefetch_stream
if prefetch_stream is None:
raise RuntimeError("pinned PLE finalize requires a prior start_prefetch")
torch.cuda.current_stream().wait_stream(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)
@@ -549,8 +590,9 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
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)
buffer = self._prefetch_buffer
if buffer is None:
raise RuntimeError("pinned PLE lookup requires a prior start_prefetch")
output = buffer.new_empty((hidden_states.shape[0], self._output_dim))
self._finalize_prefetch(buffer, output)
return output
-284
View File
@@ -1,284 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Qwen4Exp model configuration."""
from typing import Any, ClassVar, cast
from transformers import PreTrainedConfig
from transformers.models.qwen3_vl.configuration_qwen3_vl import (
Qwen3VLVisionConfig,
)
from vllm.transformers_utils.configs.qwen3_next import Qwen3NextConfig
_QSA_CONFIG_FIELDS = (
"indexer_n_heads",
"indexer_kv_heads",
"indexer_head_dim",
"indexer_budget",
"indexer_compress_ratio",
)
# Transformers labels Qwen4Exp's sparse-attention layers `qwen_sparse_attention`.
# Older checkpoints label them `full_attention` and mark QSA by setting the
# indexer fields for the whole model.
QSA_LAYER_TYPE = "qwen_sparse_attention"
ATTENTION_LAYER_TYPES = ("full_attention", QSA_LAYER_TYPE)
class Qwen4ExpVisionConfig(Qwen3VLVisionConfig):
model_type = "qwen4_exp"
base_config_key = "vision_config"
class Qwen4ExpTextConfig(Qwen3NextConfig):
model_type = "qwen4_exp_text"
base_config_key = "text_config"
keys_to_ignore_at_inference = ["past_key_values"]
# Qwen4Exp drives M-RoPE through these two rope_parameters entries, which
# transformers' rope validator does not know about for rope_type="default".
# Declare them here so validation stays strict for every other key instead
# of warning on a configuration the model genuinely uses.
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
def __init__(
self,
hc_count: int = 4,
hc_lowrank: int = 320,
ple_layer_ids: list[int] | None = None,
ple_embed_dim: int | None = None,
ple_conv_kernel_size: int = 4,
ngram_size: int = 3,
heads_per_ngram: int = 8,
ngram_vocab_size_base: int = 20_000_000,
make_ngram_vocab_size_divisible_by: int = 128,
output_gate_type: str = "sigmoid",
rope_parameters: dict[str, Any] | None = None,
layer_types: list[str] | None = None,
**kwargs: Any,
) -> None:
if hc_count <= 1:
raise ValueError(f"Qwen4Exp requires hc_count > 1, got {hc_count}.")
if layer_types is not None:
# Transformers' Qwen4Exp config canonicalizes "full_attention"
# entries to "qwen_sparse_attention" in memory, so checkpoints
# re-exported through it (e.g. quantized exports) serialize that
# name. vLLM keys QSA off "full_attention" plus indexer_n_heads,
# so map the transformers spelling back.
layer_types = [
"full_attention"
if layer_type == "qwen_sparse_attention"
else layer_type
for layer_type in layer_types
]
if rope_parameters is not None:
if kwargs.get("rope_scaling") is None:
kwargs["rope_scaling"] = rope_parameters
if kwargs.get("rope_theta") is None and "rope_theta" in rope_parameters:
kwargs["rope_theta"] = rope_parameters["rope_theta"]
if (
kwargs.get("partial_rotary_factor") is None
and "partial_rotary_factor" in rope_parameters
):
kwargs["partial_rotary_factor"] = rope_parameters[
"partial_rotary_factor"
]
rope_scaling = kwargs.get("rope_scaling")
rope_theta = kwargs.get("rope_theta", 10_000.0)
super().__init__(layer_types=layer_types, **kwargs)
normalized_rope_parameters = self.rope_parameters
self.rope_scaling = (
rope_scaling or rope_parameters or normalized_rope_parameters
)
self.rope_parameters = rope_parameters or normalized_rope_parameters
self.rope_theta = rope_theta
self.hc_count = hc_count
self.hc_lowrank = hc_lowrank
self.ple_layer_ids = ple_layer_ids or []
self.ple_embed_dim = (
self.hidden_size if ple_embed_dim is None else ple_embed_dim
)
self.ple_conv_kernel_size = ple_conv_kernel_size
self.ngram_size = ngram_size
self.heads_per_ngram = heads_per_ngram
self.ngram_vocab_size_base = ngram_vocab_size_base
self.make_ngram_vocab_size_divisible_by = make_ngram_vocab_size_divisible_by
self.output_gate_type = output_gate_type
self._validate_ple_config()
self._validate_ple_layer_ids()
self._validate_qsa_config()
def _validate_ple_config(self) -> None:
if self.hc_lowrank <= 0:
raise ValueError(f"hc_lowrank must be positive, got {self.hc_lowrank}")
if self.ngram_size < 2:
raise ValueError(f"ngram_size must be >= 2, got {self.ngram_size}")
if self.heads_per_ngram <= 0:
raise ValueError(
f"heads_per_ngram must be positive, got {self.heads_per_ngram}"
)
if self.ple_embed_dim <= 0:
raise ValueError(
f"ple_embed_dim must be positive, got {self.ple_embed_dim}"
)
ngram_heads = (self.ngram_size - 1) * self.heads_per_ngram
if self.ple_embed_dim % ngram_heads:
raise ValueError(
"ple_embed_dim must be divisible by total ngram heads: "
f"{self.ple_embed_dim} % {ngram_heads} != 0"
)
if self.ple_conv_kernel_size <= 0:
raise ValueError(
"ple_conv_kernel_size must be positive, got "
f"{self.ple_conv_kernel_size}"
)
if self.ngram_vocab_size_base <= 0:
raise ValueError("ngram_vocab_size_base must be positive")
if self.make_ngram_vocab_size_divisible_by <= 0:
raise ValueError("make_ngram_vocab_size_divisible_by must be positive")
def _validate_ple_layer_ids(self) -> None:
invalid = [
layer_id
for layer_id in self.ple_layer_ids
if not 1 <= int(layer_id) <= self.num_hidden_layers
]
if invalid:
raise ValueError(
"ple_layer_ids are 1-based and must refer to an existing layer; "
f"got {invalid} for {self.num_hidden_layers} layers"
)
def _validate_qsa_config(self) -> None:
configured = {name: getattr(self, name, None) for name in _QSA_CONFIG_FIELDS}
if all(value is None for value in configured.values()):
if QSA_LAYER_TYPE in (self.layer_types or ()):
raise ValueError(
f"{QSA_LAYER_TYPE} layers require the QSA config fields: "
f"{list(_QSA_CONFIG_FIELDS)}"
)
return
missing = [name for name, value in configured.items() if value is None]
if missing:
raise ValueError(f"QSA config is missing required fields: {missing}")
values = {name: int(cast(int, value)) for name, value in configured.items()}
if any(value <= 0 for value in values.values()):
raise ValueError(f"QSA config values must be positive: {values}")
if values["indexer_kv_heads"] != 1:
raise ValueError("the QSA MQA operators require indexer_kv_heads=1")
if values["indexer_budget"] % values["indexer_compress_ratio"] != 0:
raise ValueError(
"indexer_budget must be divisible by indexer_compress_ratio"
)
block_topk = values["indexer_budget"] // values["indexer_compress_ratio"]
if block_topk not in (512, 2048):
raise ValueError(
"QSA requires indexer_budget / indexer_compress_ratio "
f"to be 512 or 2048, got {block_topk}"
)
rotary_dim = int(self.head_dim * self.partial_rotary_factor)
if rotary_dim > values["indexer_head_dim"]:
raise ValueError(
"QSA indexer_head_dim must cover the attention rotary "
f"dimension, got {values['indexer_head_dim']} < {rotary_dim}"
)
@property
def layers_block_type(self) -> list[str]:
return [
"attention" if layer_type in ATTENTION_LAYER_TYPES else layer_type
for layer_type in self.layer_types
]
@property
def short_conv_layer_ids(self) -> list[int]:
if not self.ple_layer_ids:
return []
return sorted({int(layer_id) - 1 for layer_id in self.ple_layer_ids})
@property
def short_conv_state_shape(self) -> tuple[int, int] | None:
if not self.short_conv_layer_ids:
return None
ple_state_len = (self.ple_conv_kernel_size - 1) * self.ngram_size
ple_channels = self.hidden_size * self.hc_count
return ple_channels, ple_state_len
@property
def ngram_context_len(self) -> int:
if not self.ple_layer_ids:
return 0
return max(int(self.ngram_size) - 1, 0)
class Qwen4ExpConfig(PreTrainedConfig):
model_type = "qwen4_exp"
sub_configs: ClassVar[dict[str, type[PreTrainedConfig]]] = {
"vision_config": Qwen4ExpVisionConfig,
"text_config": Qwen4ExpTextConfig,
}
keys_to_ignore_at_inference = ["past_key_values"]
# The outer config mirrors the text config's rope_parameters (see below),
# so it is validated a second time and needs the same allowance.
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
def __init__(
self,
text_config: Qwen4ExpTextConfig | dict[str, Any] | None = None,
vision_config: Qwen4ExpVisionConfig | dict[str, Any] | None = None,
image_token_id: int = 248056,
video_token_id: int = 248057,
vision_start_token_id: int = 248053,
vision_end_token_id: int = 248054,
tie_word_embeddings: bool = False,
rope_parameters: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
if text_config is not None:
kwargs.pop("split_ngram_parts", None)
text_kwargs = (
dict(kwargs)
if text_config is None
and "hidden_size" in kwargs
and "num_hidden_layers" in kwargs
else {}
)
if isinstance(vision_config, dict):
self.vision_config = self.sub_configs["vision_config"](**vision_config)
elif vision_config is None:
self.vision_config = self.sub_configs["vision_config"]()
else:
self.vision_config = vision_config
if isinstance(text_config, dict):
self.text_config = self.sub_configs["text_config"](**text_config)
elif text_config is None:
self.text_config = self.sub_configs["text_config"](**text_kwargs)
else:
self.text_config = text_config
self.image_token_id = image_token_id
self.video_token_id = video_token_id
self.vision_start_token_id = vision_start_token_id
self.vision_end_token_id = vision_end_token_id
self.rope_parameters = rope_parameters or getattr(
self.text_config, "rope_parameters", {}
)
super().__init__(**kwargs, tie_word_embeddings=tie_word_embeddings)
__all__ = [
"Qwen4ExpConfig",
"Qwen4ExpTextConfig",
"Qwen4ExpVisionConfig",
]
+37 -13
View File
@@ -2,10 +2,11 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Qwen4Exp weight-free QSA indexer."""
from typing import cast
from typing import TYPE_CHECKING, cast
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import VllmConfig
from vllm.forward_context import get_forward_context
@@ -13,9 +14,6 @@ from vllm.model_executor.layers.layernorm import GemmaRMSNorm
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from ..common.qsa_cache import (
QSACompressedKeyCache,
@@ -23,7 +21,10 @@ from ..common.qsa_cache import (
QSAKeyStateCache,
canonical_qsa_rope_positions,
)
from .ops.qsa_pre_indexer import qsa_pre_indexer
from .ops.qsa_prepare import qsa_prepare
if TYPE_CHECKING:
from .qsa import Qwen4ExpQSAAttention
def apply_qsa_rope(
@@ -235,7 +236,11 @@ class QSAIndexer(nn.Module):
projected_qk: torch.Tensor,
positions: torch.Tensor,
out: torch.Tensor | None = None,
) -> torch.Tensor:
*,
attn: "Qwen4ExpQSAAttention",
qkv: torch.Tensor | None = None,
slot_mapping: torch.Tensor | None = None,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
"""Update side caches and select token indices from pre-projected Q/K.
Returns the packed buffer of shape [num_tokens, output_width + 1]:
@@ -243,12 +248,17 @@ class QSAIndexer(nn.Module):
request-relative token indices, and the trailing column is the row's
valid-entry count (the attention kernel's loop bound, never a token
index).
With ``attn.use_fused_qsa_prepare``, the same launch also writes
``attn``'s K/V into ``attn.kv_cache`` at ``slot_mapping`` and prepares
its Q and gate from ``qkv``, returned as the second element (None
otherwise). ``qkv`` and ``slot_mapping`` are only read in that mode.
"""
metadata = self._metadata()
if metadata is None:
# Preserve step-0 indices when later MTP steps reuse the buffer.
if self.skip_topk and out is not None:
return out
return out, None
result = torch.full(
(projected_qk.shape[0], self.packed_output_width),
-1,
@@ -259,8 +269,8 @@ class QSAIndexer(nn.Module):
result[:, -1] = 0
if out is not None:
out.copy_(result)
return out
return result
return out, None
return result, None
from .ops.qsa import qsa_compress_groups_with_ratio, qsa_store_cache_rows
from .ops.qsa_indexer import (
@@ -284,14 +294,20 @@ class QSAIndexer(nn.Module):
raw_key_state_cache = self.raw_key_cache
compressed_key_cache = self.compressed_key_cache.kv_cache
if self.use_fused_pre_indexer:
main_outputs: tuple[torch.Tensor, torch.Tensor] | None = None
if attn.use_fused_qsa_prepare:
if qkv is None or slot_mapping is None:
raise ValueError("fused QSA prepare requires qkv and slot_mapping")
q = projected_q.new_empty(
num_tokens,
self.index_n_heads,
self.index_head_dim,
dtype=self.indexer_dtype,
)
qsa_pre_indexer(
main_kv_cache = attn.kv_cache.transpose(1, 2)
if attn.kv_cache_dtype in ("fp8", "fp8_e4m3"):
main_kv_cache = main_kv_cache.view(torch.float8_e4m3fn)
main_outputs = qsa_prepare(
projected_q,
raw_keys,
positions,
@@ -315,6 +331,14 @@ class QSAIndexer(nn.Module):
if raw_key_state_cache.rope_position_cache is not None
else None
),
main_qkv=qkv[:num_tokens],
main_q_norm_weight=attn.q_norm.weight,
main_k_norm_weight=attn.k_norm.weight,
main_eps=attn.q_norm.variance_epsilon,
main_kv_cache=main_kv_cache,
main_slot_mapping=slot_mapping[:num_tokens],
main_k_scale=attn._k_scale_float,
main_v_scale=attn._v_scale_float,
)
else:
# Unfused reference path
@@ -385,7 +409,7 @@ class QSAIndexer(nn.Module):
if self.skip_topk:
if out is None:
raise RuntimeError("QSA top-k reuse requires an output buffer")
return out
return out, main_outputs
if out is None:
out = torch.empty(
@@ -448,7 +472,7 @@ class QSAIndexer(nn.Module):
self.token_topk,
out,
)
return out
return out, main_outputs
__all__ = ["QSAIndexer", "apply_qsa_rope"]
@@ -144,6 +144,73 @@ QWEN4_EXP_SM90_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
}
# B200 plans; the winning configs differ from the B300 table.
QWEN4_EXP_SM100_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] = {
# GDN fused B/A projection, TP=4.
(24, 2560): {
1: SkinnyGemmConfig(1, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 128, 2, k_unroll=4, vector_width=4, static_k=2560),
4: SkinnyGemmConfig(4, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
16: SkinnyGemmConfig(16, 128, 1, k_unroll=2, vector_width=4, static_k=2560),
},
# Shared-expert fused gate/up projection, TP=4.
(320, 2560): {
1: SkinnyGemmConfig(1, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
4: SkinnyGemmConfig(4, 160, 1, k_unroll=2, static_k=2560),
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
16: SkinnyGemmConfig(16, 128, 1, vector_width=4, static_k=2560),
},
# Final HC down projection, replicated in a TP=4 deployment.
(320, 10240): {
1: SkinnyGemmConfig(1, 256, 1, k_unroll=4, static_k=10240),
2: SkinnyGemmConfig(2, 256, 1, k_unroll=4, static_k=10240),
4: SkinnyGemmConfig(4, 256, 1, k_unroll=2),
8: SkinnyGemmConfig(8, 256, 1),
},
# HC merged down/injection projection, replicated in a TP=4 deployment.
(336, 10240): {
1: SkinnyGemmConfig(1, 256, 1, k_unroll=4, static_k=10240),
2: SkinnyGemmConfig(2, 256, 1, k_unroll=4, static_k=10240),
8: SkinnyGemmConfig(8, 256, 3, static_k=10240),
},
# QSA indexer Q/K projection, replicated in a TP=4 deployment.
(640, 2560): {
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
4: SkinnyGemmConfig(4, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
},
# GDN and QSA output projections, TP=4.
(2560, 1536): {
1: SkinnyGemmConfig(1, 128, 2, k_unroll=2, vector_width=4, static_k=1536),
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2, static_k=1536),
4: SkinnyGemmConfig(4, 64, 2, k_unroll=2, static_k=1536),
},
# QSA fused QKV/gate projection, TP=4.
(3584, 2560): {
1: SkinnyGemmConfig(1, 128, 4, k_unroll=2, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 128, 4, k_unroll=2, vector_width=4, static_k=2560),
4: SkinnyGemmConfig(4, 64, 2, k_unroll=4, vector_width=4, static_k=2560),
},
# GDN fused QKVZ projection, TP=4.
(4096, 2560): {
1: SkinnyGemmConfig(1, 128, 2, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2, static_k=2560),
4: SkinnyGemmConfig(4, 64, 2, k_unroll=4, vector_width=4, static_k=2560),
},
# LM head, TP=4.
(62080, 2560): {
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4),
},
}
def _is_sm100() -> bool:
return current_platform.is_device_capability((10, 0))
def _is_sm103() -> bool:
return current_platform.is_device_capability((10, 3))
@@ -155,6 +222,8 @@ def _is_sm90() -> bool:
def _gemm_plans() -> dict[tuple[int, int], dict[int, SkinnyGemmConfig]]:
if _is_sm103():
return QWEN4_EXP_GEMM_PLANS
if _is_sm100():
return QWEN4_EXP_SM100_GEMM_PLANS
if _is_sm90():
return QWEN4_EXP_SM90_GEMM_PLANS
return {}
+10 -42
View File
@@ -7,6 +7,7 @@ from itertools import islice
import torch
from torch import nn
from transformers import Qwen4ExpConfig, Qwen4ExpTextConfig
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
@@ -48,7 +49,6 @@ from vllm.model_executor.models.qwen3_5 import (
)
from vllm.model_executor.models.qwen3_next import (
Qwen3NextAttention,
Qwen3NextMLP,
Qwen3NextSparseMoeBlock,
)
from vllm.model_executor.models.qwen3_vl import (
@@ -72,14 +72,10 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.inputs import MultiModalFeatureSpec
from vllm.sequence import IntermediateTensors
from vllm.tokenizers.registry import cached_tokenizer_from_config
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.kv_cache_interface import MambaSpec
from ..common.mtp import make_mtp_hidden_buffer
from ..config import ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
from .ops.cute_dsl.hc_down_silu import request_hc_down_silu_warmup
@@ -184,8 +180,6 @@ class Qwen4ExpDecoderLayer(nn.Module):
) -> None:
super().__init__()
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
model_config = vllm_config.model_config
cache_config = vllm_config.cache_config
quant_config = vllm_config.quant_config
self.config = config
@@ -218,16 +212,13 @@ class Qwen4ExpDecoderLayer(nn.Module):
prefix=f"{prefix}.linear_attn",
gqa_interleaved_layout=False,
)
elif layer_type in ATTENTION_LAYER_TYPES:
use_qsa = (
layer_type == QSA_LAYER_TYPE
or getattr(config, "indexer_n_heads", None) is not None
)
elif layer_type == "qwen_sparse_attention":
use_qsa = getattr(config, "indexer_n_heads", None) is not None
if not use_qsa:
self.self_attn = Qwen3NextAttention(
config,
model_config=model_config,
cache_config=cache_config,
model_config=vllm_config.model_config,
cache_config=vllm_config.cache_config,
quant_config=quant_config,
prefix=f"{prefix}.self_attn",
)
@@ -242,24 +233,9 @@ class Qwen4ExpDecoderLayer(nn.Module):
else:
raise ValueError(f"Invalid layer_type {layer_type}")
mlp_only_layers = getattr(config, "mlp_only_layers", [])
num_experts = getattr(config, "num_experts", 0) or 0
absolute_layer_id = self.layer_idx + 1
is_moe_layer = self.layer_idx not in mlp_only_layers and (
num_experts > 0 and absolute_layer_id % config.decoder_sparse_step == 0
self.mlp = Qwen4ExpSparseMoeBlock(
vllm_config=vllm_config, prefix=f"{prefix}.mlp"
)
if is_moe_layer:
self.mlp = Qwen4ExpSparseMoeBlock(
vllm_config=vllm_config, prefix=f"{prefix}.mlp"
)
else:
self.mlp = Qwen3NextMLP(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
prefix=f"{prefix}.mlp",
)
hc_config = HyperConnectionConfig(
hc_count=config.hc_count,
@@ -320,7 +296,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
if self.layer_type == "linear_attention":
attn_out = self.linear_attn(hidden_states=block_input)
elif self.layer_type in ATTENTION_LAYER_TYPES:
elif self.layer_type == "qwen_sparse_attention":
attn_out = self.self_attn(
hidden_states=block_input,
positions=positions,
@@ -400,11 +376,8 @@ class Qwen4ExpModel(nn.Module):
self._qsa_layer_ids = frozenset(
layer_idx
for layer_idx, layer_type in enumerate(config.layer_types)
if layer_type == QSA_LAYER_TYPE
or (
layer_type == "full_attention"
and getattr(config, "indexer_n_heads", None) is not None
)
if layer_type == "qwen_sparse_attention"
and getattr(config, "indexer_n_heads", None) is not None
)
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, config.hidden_size)
@@ -659,11 +632,6 @@ class Qwen4ExpForCausalLM(
self.quant_config = vllm_config.quant_config
self.config = config
self.scheduler_config = vllm_config.scheduler_config
if vllm_config.cache_config.mamba_cache_mode == "all":
raise NotImplementedError(
"Qwen4Exp currently does not support 'all' prefix caching, "
"please use '--mamba-cache-mode=align' instead"
)
self.model = Qwen4ExpModel(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
+2 -11
View File
@@ -18,6 +18,7 @@ from collections.abc import Iterable
import regex as re
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import VllmConfig, replace, set_current_vllm_config
from vllm.distributed import get_pp_group
@@ -48,9 +49,6 @@ from vllm.model_executor.models.utils import (
maybe_prefix,
)
from vllm.sequence import IntermediateTensors
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
@@ -216,7 +214,7 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
self.layers = nn.ModuleList(
Qwen4ExpDecoderLayer(
draft_vllm_config,
layer_type="full_attention",
layer_type="qwen_sparse_attention",
prefix=f"{prefix}.layers.{self.mtp_start_layer_idx + idx}",
)
for idx in range(self.num_mtp_layers)
@@ -381,13 +379,6 @@ class Qwen4ExpMTP(
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
self.vllm_config = vllm_config
cache_config = vllm_config.cache_config
if cache_config.mamba_cache_mode == "all":
raise NotImplementedError(
"Qwen4ExpMTP currently does not support 'all' prefix caching, "
"please use '--mamba-cache-mode=align' instead"
)
self.quant_config = vllm_config.quant_config
super().__init__()
@@ -8,6 +8,7 @@ from collections.abc import Iterable
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
@@ -15,9 +16,6 @@ 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,
)
from ..common.ngram_embedding import (
Qwen4ExpPLEDeviceEmbedding,
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused QSA pre-indexer kernel for Qwen4Exp."""
"""Fused QSA prepare kernel for Qwen4Exp."""
import torch
@@ -80,6 +80,27 @@ def _norm_rope(
return tl.reshape(result, (TILE_T, TILE_H, D))
@triton.jit
def _to_dst_dtype(x, dst, scale):
"""Round to BF16 like the unfused path, then scale for an FP8 destination."""
out_ty = dst.dtype.element_ty
x = x.to(tl.bfloat16)
if out_ty == tl.float8e4nv:
x = x.to(tl.float32) / scale
return x.to(out_ty)
@triton.jit
def _store_rotated(dst, y, o1, o2, scale):
"""Store a normalized head whose first ``2 * len(o1)`` dims are rotated."""
HALF: tl.constexpr = o1.shape[0]
dims = tl.arange(0, y.shape[0])
rot = tl.arange(0, HALF)
tl.store(dst + dims, _to_dst_dtype(y, dst, scale), mask=dims >= 2 * HALF)
tl.store(dst + rot, _to_dst_dtype(o1, dst, scale))
tl.store(dst + HALF + rot, _to_dst_dtype(o2, dst, scale))
@triton.jit(
do_not_specialize=[
"num_tokens",
@@ -88,7 +109,7 @@ def _norm_rope(
"num_k_work",
]
)
def _qsa_pre_indexer_kernel(
def _qsa_prepare_kernel(
q_ptr,
q_stride_token,
k_ptr,
@@ -132,8 +153,86 @@ def _qsa_pre_indexer_kernel(
CACHE_HAS_ROPE_POS: tl.constexpr,
MROPE_H: tl.constexpr,
MROPE_W: tl.constexpr,
main_qkv_ptr,
main_q_norm_weight_ptr,
main_k_norm_weight_ptr,
main_eps,
main_q_out_ptr,
main_gate_out_ptr,
main_cache_ptr,
main_cache_stride_block,
main_cache_stride_token,
main_cache_stride_head,
main_slots_ptr,
main_k_scale,
main_v_scale,
MAIN_HQ: tl.constexpr,
MAIN_HK: tl.constexpr,
MAIN_D: tl.constexpr,
MAIN_PAGE_SIZE: tl.constexpr,
):
pid = tl.program_id(0)
num_index_work = num_k_work + tl.cdiv(num_tokens, TILE_T_Q) * tl.cdiv(HQ, TILE_H_Q)
if pid >= num_index_work:
# Main attention: one program per (token, Q or KV head) after the
# indexer work. RoPE covers the first D // 2 dims, the width of the
# shared cos/sin table.
main_pid = pid - num_index_work
token = main_pid // (MAIN_HQ + MAIN_HK)
head = main_pid % (MAIN_HQ + MAIN_HK)
HALF: tl.constexpr = D // 4
dims = tl.arange(0, MAIN_D)
rot = tl.arange(0, HALF)
row = main_qkv_ptr + token * (2 * (MAIN_HQ + MAIN_HK) * MAIN_D)
is_k = head >= MAIN_HQ
kv_head = head - MAIN_HQ
if is_k:
src = row + (2 * MAIN_HQ + kv_head) * MAIN_D
weight_ptr = main_k_norm_weight_ptr
else:
src = row + 2 * head * MAIN_D
weight_ptr = main_q_norm_weight_ptr
x = tl.load(src + dims).to(tl.float32)
inv_rms = tl.rsqrt(tl.sum(x * x, axis=0) / MAIN_D + main_eps)
w = tl.load(weight_ptr + dims).to(tl.float32) + 1.0
y = x * inv_rms * w
x1 = tl.load(src + rot).to(tl.float32)
x2 = tl.load(src + HALF + rot).to(tl.float32)
w1 = tl.load(weight_ptr + rot).to(tl.float32) + 1.0
w2 = tl.load(weight_ptr + HALF + rot).to(tl.float32) + 1.0
x1 = (x1 * inv_rms * w1).to(tl.bfloat16).to(tl.float32)
x2 = (x2 * inv_rms * w2).to(tl.bfloat16).to(tl.float32)
pos = tl.load(pos_ptr + token * pos_stride_token).to(tl.int64)
if IS_2D_POSITIONS:
pos_h = tl.load(pos_ptr + pos_stride_axis + token * pos_stride_token)
pos_w = tl.load(pos_ptr + 2 * pos_stride_axis + token * pos_stride_token)
is_h = (rot % 3 == 1) & (rot < 3 * MROPE_H)
is_w = (rot % 3 == 2) & (rot < 3 * MROPE_W)
pos = tl.where(
is_h, pos_h.to(tl.int64), tl.where(is_w, pos_w.to(tl.int64), pos)
)
cos = tl.load(cos_sin_ptr + pos * (D // 2) + rot).to(tl.float32)
sin = tl.load(cos_sin_ptr + pos * (D // 2) + HALF + rot).to(tl.float32)
o1 = x1 * cos - x2 * sin
o2 = x2 * cos + x1 * sin
if is_k:
slot = tl.load(main_slots_ptr + token).to(tl.int64)
if slot >= 0:
dst = (
main_cache_ptr
+ (slot // MAIN_PAGE_SIZE) * main_cache_stride_block
+ (slot % MAIN_PAGE_SIZE) * main_cache_stride_token
+ kv_head * main_cache_stride_head
)
_store_rotated(dst, y, o1, o2, main_k_scale)
v = tl.load(src + MAIN_HK * MAIN_D + dims)
tl.store(dst + MAIN_D + dims, _to_dst_dtype(v, dst, main_v_scale))
else:
out = (token * MAIN_HQ + head) * MAIN_D
_store_rotated(main_q_out_ptr + out, y, o1, o2, None)
gate = tl.load(src + MAIN_D + dims)
tl.store(main_gate_out_ptr + out + dims, gate)
return
# K work occupies the first programs; the remaining programs tile Q. This
# keeps both paths in one launch while leaving their register shapes
# independent.
@@ -400,7 +499,7 @@ def _qsa_pre_indexer_kernel(
tl.store(tail + 2, pos_w.to(tl.int64), mask=valid_slot)
def qsa_pre_indexer(
def qsa_prepare(
q: torch.Tensor,
k: torch.Tensor,
positions: torch.Tensor,
@@ -421,11 +520,28 @@ def qsa_pre_indexer(
compress_ratio: int,
mrope_section: tuple[int, int, int] | None,
rope_pos_offset: int | None,
) -> None:
"""Normalize Q, compress K, then update the circular raw state."""
main_qkv: torch.Tensor,
main_q_norm_weight: torch.Tensor,
main_k_norm_weight: torch.Tensor,
main_eps: float,
main_kv_cache: torch.Tensor,
main_slot_mapping: torch.Tensor,
main_k_scale: float,
main_v_scale: float,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Normalize Q, compress K, then update the circular raw state.
Also prepares the main attention (QK-norm/RoPE, gate copy, K/V cache write)
and returns its Q and gate.
"""
num_tokens = q.shape[0]
main_head_dim = main_kv_cache.shape[-1] // 2
num_main_kv_heads = main_kv_cache.shape[2]
num_main_q_heads = main_qkv.shape[1] // (2 * main_head_dim) - num_main_kv_heads
main_q_out = main_qkv.new_empty(num_tokens, num_main_q_heads, main_head_dim)
main_gate_out = torch.empty_like(main_q_out)
if num_tokens == 0:
return
return main_q_out, main_gate_out
num_q_heads, head_dim = q_out.shape[1:]
assert cos_sin_cache.shape[-1] * 2 == head_dim
assert q.shape == (num_tokens, num_q_heads * head_dim)
@@ -450,6 +566,9 @@ def qsa_pre_indexer(
pos_stride_axis, pos_stride_token = 0, positions.stride(0)
section = mrope_section if mrope_section is not None else (0, 0, 0)
assert len(section) == 3
qkv_width = 2 * (num_main_q_heads + num_main_kv_heads) * main_head_dim
assert main_qkv.shape == (num_tokens, qkv_width) and main_qkv.is_contiguous()
assert main_slot_mapping.shape == (num_tokens,)
if num_tokens <= 4096:
TILE_T_Q, TILE_H_Q = 2, 2
@@ -457,7 +576,8 @@ def qsa_pre_indexer(
TILE_T_Q, TILE_H_Q = 2, 4
num_k_work = k_work_metadata.shape[0]
num_q_work = triton.cdiv(num_tokens, TILE_T_Q) * triton.cdiv(num_q_heads, TILE_H_Q)
_qsa_pre_indexer_kernel[(num_k_work + num_q_work,)](
num_main_work = num_tokens * (num_main_q_heads + num_main_kv_heads)
_qsa_prepare_kernel[(num_k_work + num_q_work + num_main_work,)](
q,
q.stride(0),
k,
@@ -501,8 +621,26 @@ def qsa_pre_indexer(
CACHE_HAS_ROPE_POS=cache_has_rope_pos,
MROPE_H=section[1],
MROPE_W=section[2],
main_qkv_ptr=main_qkv,
main_q_norm_weight_ptr=main_q_norm_weight,
main_k_norm_weight_ptr=main_k_norm_weight,
main_eps=main_eps,
main_q_out_ptr=main_q_out,
main_gate_out_ptr=main_gate_out,
main_cache_ptr=main_kv_cache,
main_cache_stride_block=main_kv_cache.stride(0),
main_cache_stride_token=main_kv_cache.stride(1),
main_cache_stride_head=main_kv_cache.stride(2),
main_slots_ptr=main_slot_mapping,
main_k_scale=main_k_scale,
main_v_scale=main_v_scale,
MAIN_HQ=num_main_q_heads,
MAIN_HK=num_main_kv_heads,
MAIN_D=main_head_dim,
MAIN_PAGE_SIZE=main_kv_cache.shape[1],
num_warps=1,
)
return main_q_out, main_gate_out
__all__ = ["qsa_pre_indexer"]
__all__ = ["qsa_prepare"]
+1 -3
View File
@@ -6,6 +6,7 @@ from collections.abc import Sequence
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import CacheConfig, ModelConfig, VllmConfig, get_current_vllm_config
@@ -17,9 +18,6 @@ from vllm.model_executor.layers.mamba.mamba_utils import (
MambaStateShapeCalculator,
is_conv_state_dim_first,
)
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.attention.backends.short_conv_attn import (
PleShortConvAttentionBackend,
+41 -21
View File
@@ -8,6 +8,7 @@ from typing import ClassVar, cast
import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import VllmConfig
@@ -25,9 +26,6 @@ from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding, get_ro
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.transformers_utils.configs.qwen4_exp import (
Qwen4ExpTextConfig,
)
from vllm.utils.torch_utils import (
kv_cache_dtype_str_to_dtype,
)
@@ -407,6 +405,12 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
quant_config=quant_config,
prefix=f"{prefix}.indexer",
)
# One launch does the indexer prepare, the main QK-norm/RoPE/gate and
# the main K/V cache write (see QSAIndexer.forward); otherwise all of
# them take the separate kernels.
self.use_fused_qsa_prepare = (
self.use_fused_qk_norm_rope_gate and self.indexer.use_fused_pre_indexer
)
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
# PACKED selection buffer: the trailing column holds each row's
# valid-entry count (written by the expand kernel) — never a token
@@ -446,12 +450,15 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
self,
projected_qk: torch.Tensor,
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
query: torch.Tensor | None,
key: torch.Tensor | None,
value: torch.Tensor | None,
output: torch.Tensor,
output_gate: torch.Tensor,
output_gate: torch.Tensor | None,
qkv: torch.Tensor,
) -> None:
# query/key/value/output_gate are None when the fused prepare runs
# inside the indexer launch.
metadata = get_forward_context().attn_metadata
if isinstance(metadata, list):
metadata = metadata[0]
@@ -469,21 +476,29 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
)
if side_metadata.num_actual_tokens != num_tokens:
raise RuntimeError("QSA main and side metadata token counts disagree")
selected = self.indexer(
selected, main_outputs = self.indexer(
projected_qk,
positions,
self.topk_indices_buffer[:num_tokens],
attn=self,
qkv=qkv,
slot_mapping=main_metadata.slot_mapping,
)
if selected.shape != (num_tokens, self.indexer.packed_output_width):
raise RuntimeError("QSA indexer returned an invalid selection shape")
impl = cast(Qwen4ExpQSAFlashAttentionImpl, self.impl)
impl.do_kv_cache_update(
self,
key,
value,
self.kv_cache,
main_metadata.slot_mapping,
)
if main_outputs is None:
assert key is not None and value is not None
impl.do_kv_cache_update(
self,
key,
value,
self.kv_cache,
main_metadata.slot_mapping,
)
else:
query, output_gate = main_outputs
assert query is not None and output_gate is not None
impl.forward_qsa(
self,
query,
@@ -503,13 +518,17 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
hidden_states: torch.Tensor,
) -> torch.Tensor:
qkv, _ = self.qkv_proj(hidden_states)
q, k, v, gate = self._project_qkv_gate(qkv, positions)
assert gate is not None
num_tokens = hidden_states.shape[0]
query = q.view(num_tokens, self.num_heads, self.head_dim)
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
value = v.view(num_tokens, self.num_kv_heads, self.head_dim)
attn_output = torch.empty_like(query)
if not self.use_fused_qsa_prepare:
q, k, v, gate = self._project_qkv_gate(qkv, positions)
assert gate is not None
query = q.view(num_tokens, self.num_heads, self.head_dim)
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
value = v.view(num_tokens, self.num_kv_heads, self.head_dim)
else:
# Norm/RoPE/gate and the K/V cache write happen inside _run_qsa.
query = key = value = gate = None
attn_output = qkv.new_empty(num_tokens, self.num_heads, self.head_dim)
# Keep the index projection outside the eager break.
projected_qk, _ = self.indexer.index_qk_proj(hidden_states)
self._run_qsa(
@@ -520,6 +539,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
value,
attn_output,
gate,
qkv,
)
flat_output = attn_output.view(num_tokens, -1)
output, _ = self.o_proj(flat_output)