Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-16 17:35:42 +07:00
347 changed files with 29531 additions and 3472 deletions
+10
View File
@@ -950,6 +950,16 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
"""Whether this implementation supports fused QKNorm+MRoPE+KVCache."""
return False
def set_interleaved_v_cache(self):
"""Opt this implementation into the interleaved V-cache layout for all of
its cache writers and readers. QkNormRopeKvCacheFusionPass calls this
for every eligible layer when it is constructed, i.e. before any KV
cache is written, so fused and unfused paths stay consistent whether or
not the pattern matches. Default is a no-op; backends whose kernels
read an interleaved V-cache under this fusion (e.g. ROCM_ATTN) override.
"""
return False
def fused_rope_kvcache_supported(self):
"""Does this attention implementation support RoPE+KVCache fusion.
This is used by the RopeKVCacheFusionPass to only fuse the RoPE ops
@@ -35,6 +35,7 @@ from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
prepare_sparse_mla_safe_lengths,
)
from vllm.v1.attention.ops.metadata import compute_token_to_req_indices
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec
if TYPE_CHECKING:
@@ -297,6 +298,11 @@ class FlashInferMLASparseTRTLLMMetadataBuilder(FlashInferMLASparseMetadataBuilde
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
self.supports_draft_decode_metadata_update = (
self.dcp_world_size == 1
and self.pcp_world_size == 1
and vllm_config.attention_config.hisparse_config is None
)
# Under DCP the workspace must hold the trtllm-gen softmax-stats slab.
# The buffer address is baked into CUDA graphs, so it has to reach its
@@ -314,6 +320,18 @@ class FlashInferMLASparseTRTLLMMetadataBuilder(FlashInferMLASparseMetadataBuilde
),
)
def update_draft_decode_metadata(
self, metadata: FlashInferMLASparseMetadata
) -> None:
num_tokens = metadata.num_decode_tokens
if num_tokens:
compute_token_to_req_indices(
metadata.query_start_loc,
metadata.req_id_per_token,
num_tokens,
num_tokens,
)
# Global workspace buffer (lazily initialized)
_fi_sparse_workspace: torch.Tensor | None = None
@@ -103,10 +103,11 @@ For DeepSeek V4.1, each token's KV cache is 528 Bytes, structured as:
- **Last 16 bytes:** Scale factors, containing 16 `ue8m0` values, one per 32
consecutive `float8_e4m3` values (i.e. MXFP8).
The V4 and V4.1 records are not laid out token-by-token within a page: a page
holds all its data rows first and all its scale rows after, so a page is
`block_size * bytes_per_token` bytes rounded up to the decode kernel's TMA
stride (576 B for V4, 512 B for V4.1).
The V4 record is not laid out token-by-token within a page: a page holds all
its data rows first and all its scale rows after, so a page is
`block_size * bytes_per_token` bytes rounded up to the decode kernel's 576 B
TMA stride. The V4.1 records are interleaved: each token's scales directly
follow its own data, and the decode kernel's TMA stride is the record width.
In the "nvfp4_ds_mla" format (SM100 only, DeepSeek V3.2 geometry), each
token's KV cache is 352 Bytes, structured as:
+3 -5
View File
@@ -205,19 +205,16 @@ class PrepareUniformDecodeKernel(
)
# Below this many rows per rank, stay replicated (TP4 engages at 64K rows).
MIN_TP_SHARD_ROWS_PER_RANK = 16_384
def balanced_prefill_row_shard(
seq_lens_cpu: torch.Tensor,
query_lens_cpu: torch.Tensor,
compress_ratio: int,
tp_size: int,
min_rows: int,
) -> list[int] | None:
"""Return contiguous TP row counts balanced by indexer MQA work."""
num_rows = int(query_lens_cpu.sum())
if tp_size < 2 or num_rows < MIN_TP_SHARD_ROWS_PER_RANK * tp_size:
if tp_size < 2 or num_rows < max(min_rows, tp_size):
return None
query_lens = query_lens_cpu.to(torch.int64)
@@ -1584,6 +1581,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
prefill_query_lens_cpu,
self.compress_ratio,
self.tp_size,
self.vllm_config.attention_config.indexer_tp_shard_min_rows,
)
prefill_metadata = DeepseekV32IndexerPrefillMetadata(
chunks,
+9 -1
View File
@@ -85,6 +85,7 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
block_size: int = 64,
packed_bytes_per_token: int = 584,
packed_page_alignment: int = 576,
packed_block_stride_alignment: int | None = None,
bounded_replay: bool = False,
):
super().__init__()
@@ -99,6 +100,7 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
self.dtype = dtype
self.packed_bytes_per_token = packed_bytes_per_token
self.packed_page_alignment = packed_page_alignment
self.packed_block_stride_alignment = packed_block_stride_alignment
compilation_config = get_current_vllm_config().compilation_config
if prefix in compilation_config.static_forward_context:
raise ValueError(f"Duplicate layer name: {prefix}")
@@ -135,8 +137,11 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
state_content_bytes=(
self.packed_bytes_per_token if uses_fp8_ds_mla_layout else None
),
# FlashMLA packing stride; 512B for FlashInfer sparse (#44577).
# Packed page alignment; 512B for FlashInfer sparse (#44577).
alignment=self.packed_page_alignment if uses_fp8_ds_mla_layout else 512,
block_stride_alignment=(
self.packed_block_stride_alignment if uses_fp8_ds_mla_layout else None
),
model_version="deepseek_v4",
kv_quant_mode=get_kv_quant_mode(self.cache_config.cache_dtype),
)
@@ -211,6 +216,9 @@ class DeepseekSparseSWAMetadata:
# window attention may read (SWA bounded replay);
# zeros when nothing replays.
replay_start: torch.Tensor | None = None
# PCP cache writes use the gathered slots; queries use rank-local slots.
cache_slot_mapping: torch.Tensor | None = None
cache_positions: torch.Tensor | None = None
# Number of decode/prefill requests/tokens (batch is reordered: decodes first)
num_decodes: int = 0
+3
View File
@@ -117,6 +117,9 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
"vllm.models.deepseek_v41.nvidia.flashinfer_sparse."
"DeepseekV4FlashInferMLASparseBackend"
)
ROCM_FLASHMLA_SPARSE_DSV41 = (
"vllm.models.deepseek_v41.amd.rocm.DeepseekV41ROCMAiterMLASparseBackend"
)
FLASHMLA_MEGA_ATTN_DSV41 = (
"vllm.models.deepseek_v41.sparse_mla.FlashMLAMegaAttnBackend"
)
+95 -54
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention layer with AiterFlashAttention."""
from dataclasses import dataclass, replace
from dataclasses import dataclass, field, replace
from typing import ClassVar
import torch
@@ -152,8 +152,8 @@ if current_platform.is_rocm():
k_reg = tl.load(key_cache_ptr_offset + k_reg_offset)
v_reg = tl.load(value_cache_ptr_offset + v_reg_offset)
if DEQUANT:
k_scale = 1.0
v_scale = 1.0
k_scale = tl.load(k_scale_ptr)
v_scale = tl.load(v_scale_ptr)
k_reg = k_reg.to(tl.float32) * k_scale
v_reg = v_reg.to(tl.float32) * v_scale
tl.store(key_ptr_offset + col_offsets, k_reg)
@@ -270,8 +270,8 @@ if current_platform.is_rocm():
k_val = tl.load(key_ptr + src_offset_k + offset)
v_val = tl.load(value_ptr + src_offset_v + offset)
if QUANT:
k_scale = 1.0
v_scale = 1.0
k_scale = tl.load(k_scale_ptr)
v_scale = tl.load(v_scale_ptr)
k_dtype = key_cache_ptr.type.element_ty
v_dtype = value_cache_ptr.type.element_ty
k_val = (k_val.to(tl.float32) / k_scale).to(k_dtype)
@@ -410,11 +410,48 @@ class AiterFlashAttentionMetadata:
kv_sharing_metadata: AiterKVSharingMetadata | None = None
@dataclass
class AsmKvScaleTables:
"""Dense per-slot scale tables the asm decode kernel reads for an fp8 cache.
One table per distinct (device, shape, scale), shared by every layer and
every metadata builder in the process, so the target and draft models with
equal scales reuse a single allocation. Tables are constants: never write
to one in place; a per-token or dynamic scale needs its own buffer.
"""
tables: dict[tuple[str, int, int, int, float], torch.Tensor] = field(
default_factory=dict
)
def get(
self,
device: torch.device,
num_blocks: int,
num_kv_heads: int,
block_size: int,
scale: float,
) -> torch.Tensor:
key = (str(device), num_blocks, num_kv_heads, block_size, scale)
table = self.tables.get(key)
if table is None:
table = torch.full(
(num_blocks, num_kv_heads, block_size),
scale,
dtype=torch.float32,
device=device,
)
self.tables[key] = table
return table
class AiterFlashAttentionMetadataBuilder(
AttentionMetadataBuilder[AiterFlashAttentionMetadata]
):
_cudagraph_support = AttentionCGSupport.UNIFORM_BATCH
asm_kv_scale_tables: ClassVar[AsmKvScaleTables] = AsmKvScaleTables()
def __init__(
self,
kv_cache_spec: AttentionSpec,
@@ -466,7 +503,8 @@ class AiterFlashAttentionMetadataBuilder(
dtype=self.model_config.dtype,
device=device,
)
self.scale = torch.tensor([1.0], dtype=torch.float, device=self.device)
self.k_scale: dict[str, torch.Tensor] | None = None
self.v_scale: dict[str, torch.Tensor] | None = None
self.kv_sharing_workspace = (
torch.empty(
(
@@ -488,6 +526,38 @@ class AiterFlashAttentionMetadataBuilder(
common_prefix_len=0, common_attn_metadata=common_attn_metadata
)
def _build_asm_kv_scale_tables(self) -> None:
# Only for fp8 shuffle kv cache: the asm decode kernel reads a dense
# [num_blocks, num_kv_heads, block_size] scale table per layer. Map each
# layer to the shared table for its scale once the KV cache is bound.
if (
self.k_scale is not None
or not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
or not is_quantized_kv_cache(self.vllm_config.cache_config.cache_dtype)
):
return
attn_layers = self.vllm_config.compilation_config.static_forward_context
k_scale_tables: dict[str, torch.Tensor] = {}
v_scale_tables: dict[str, torch.Tensor] = {}
for layer_name in self.layer_names:
layer = attn_layers[layer_name]
num_blocks = layer.kv_cache.shape[0]
k_scale_tables[layer_name] = self.asm_kv_scale_tables.get(
self.device,
num_blocks,
self.num_heads_kv,
self.block_size,
layer._k_scale_float,
)
v_scale_tables[layer_name] = self.asm_kv_scale_tables.get(
self.device,
num_blocks,
self.num_heads_kv,
self.block_size,
layer._v_scale_float,
)
self.k_scale, self.v_scale = k_scale_tables, v_scale_tables
def build(
self,
common_prefix_len: int,
@@ -499,24 +569,7 @@ class AiterFlashAttentionMetadataBuilder(
common_attn_metadata,
decode_threshold=self.reorder_batch_threshold,
)
# Allocate scales for fp8 shuffle kv cache with shuffle_kv_cache enabled
if (
rocm_aiter_ops.is_shuffle_kv_cache_enabled()
and self.scale.numel() == 1
and is_quantized_kv_cache(self.vllm_config.cache_config.cache_dtype)
):
# Size the scales from a layer this builder owns. The draft model
# runs its own builder over its own KV cache, so the first layer of
# the whole config can carry an unrelated block count.
kv_cache_shape = self.vllm_config.compilation_config.static_forward_context[
self.layer_names[0]
].kv_cache.shape
num_blocks = kv_cache_shape[0]
self.scale = torch.ones(
[num_blocks, self.num_heads_kv, self.block_size],
dtype=torch.float32,
device=self.device,
)
self._build_asm_kv_scale_tables()
(
num_decodes,
num_extends,
@@ -709,8 +762,8 @@ class AiterFlashAttentionMetadataBuilder(
decode_metadata=decode_metadata,
prefill_metadata=prefill_metadata,
extend_metadata=extend_metadata,
k_scale=self.scale,
v_scale=self.scale,
k_scale=self.k_scale,
v_scale=self.v_scale,
kv_sharing_metadata=kv_sharing_metadata,
)
return attn_metadata
@@ -726,6 +779,7 @@ class AiterFlashAttentionMetadataBuilder(
skip split_decodes_prefills_and_extends() and avoid all .cpu() /
.item() calls that would otherwise break CUDA graph capture.
"""
self._build_asm_kv_scale_tables()
num_reqs = common_attn_metadata.num_reqs
num_tokens = common_attn_metadata.num_actual_tokens
@@ -749,8 +803,8 @@ class AiterFlashAttentionMetadataBuilder(
decode_metadata=decode_metadata,
prefill_metadata=None,
extend_metadata=None,
k_scale=self.scale,
v_scale=self.scale,
k_scale=self.k_scale,
v_scale=self.v_scale,
)
@@ -1249,9 +1303,6 @@ class AiterFlashAttentionImpl(AttentionImpl):
extend_outputs = output[extend_tokens_slice]
k_scale = layer._k_scale
v_scale = layer._v_scale
if rocm_aiter_ops.is_shuffle_kv_cache_enabled():
k_scale = attn_metadata.k_scale
v_scale = attn_metadata.v_scale
self.extend_forward(
attn_metadata=attn_metadata,
query=extend_queries,
@@ -1428,16 +1479,13 @@ class AiterFlashAttentionImpl(AttentionImpl):
device=query.device,
)
max_logits = torch.empty_like(exp_sums)
k_qscale = (
layer._k_scale
if attn_metadata.k_scale is None
else attn_metadata.k_scale
)
v_qscale = (
layer._v_scale
if attn_metadata.v_scale is None
else attn_metadata.v_scale
)
# asm indexes this layer's dense scale buffer from build();
# the HIP kernel reads the per-tensor scale directly.
k_qscale_asm = v_qscale_asm = None
if attn_metadata.k_scale is not None:
assert attn_metadata.v_scale is not None
k_qscale_asm = attn_metadata.k_scale[layer.layer_name]
v_qscale_asm = attn_metadata.v_scale[layer.layer_name]
rocm_aiter_ops.paged_attention_common(
Q=query[:num_decode_tokens],
K=new_key_cache,
@@ -1452,10 +1500,10 @@ class AiterFlashAttentionImpl(AttentionImpl):
0
),
scale=self.scale,
K_QScale_hip=k_qscale,
V_QScale_hip=v_qscale,
K_QScale_asm=k_qscale,
V_QScale_asm=v_qscale,
K_QScale_hip=layer._k_scale,
V_QScale_hip=layer._v_scale,
K_QScale_asm=k_qscale_asm,
V_QScale_asm=v_qscale_asm,
out_=output[:num_decode_tokens],
kv_cache_dtype=self.kv_cache_dtype,
)
@@ -1542,9 +1590,6 @@ class AiterFlashAttentionImpl(AttentionImpl):
# the reshape_and_cache_flash op uses the slot_mapping's shape
# to determine the number of actual tokens.
if rocm_aiter_ops.is_shuffle_kv_cache_enabled():
# We may calculate per token quant scale in
# reshape_and_cache_shuffle_triton which might differ from
# vllm's style when shuffle layout is used.
k_scale = layer._k_scale
v_scale = layer._v_scale
assert k_scale is not None and v_scale is not None, (
@@ -1581,12 +1626,7 @@ class AiterFlashAttentionImpl(AttentionImpl):
)
def fused_qk_norm_rope_kvcache_supported(self):
# Only fuse when shuffle layout is off; the shuffle write path uses a
# dedicated cache update, mirroring fused_rope_kvcache_supported.
return (
rocm_aiter_ops.is_enabled()
and not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
)
return rocm_aiter_ops.is_enabled()
def do_qk_norm_rope_kvcache_update(
self,
@@ -1624,6 +1664,7 @@ class AiterFlashAttentionImpl(AttentionImpl):
v_scale=layer._v_scale_cpu,
kv_cache_dtype=self.kv_cache_dtype,
use_shuffle_layout=rocm_aiter_ops.is_shuffle_kv_cache_enabled(),
return_kv=True,
)
def do_rope_and_kv_cache_update(
@@ -15,6 +15,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kFp8StaticTensorSym,
)
from vllm.platforms.rocm import on_gfx1250
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionLayer,
@@ -28,7 +29,12 @@ from vllm.v1.attention.backends.rocm_attn import (
RocmAttentionMetadata,
RocmAttentionMetadataBuilder,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
KVQuantMode,
get_kv_quant_mode,
)
logger = init_logger(__name__)
@@ -186,12 +192,34 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
# RDNA3 has no low precision MMA, preserve query precision
self.supports_quant_query_input = not on_gfx11()
# Layout flag: must mirror get_kv_cache_shape, which is attn_type
# agnostic because the allocation is shared across layers.
self._shuffle_kv_layout = (
rocm_aiter_ops.is_shuffle_kv_cache_enabled() and on_gfx1250()
)
# Kernel flag: the shuffled reader/writer is causal decoder only.
self._use_shuffle_kv = (
self._shuffle_kv_layout and self.attn_type != AttentionType.ENCODER_DECODER
)
def _split_kv_cache(
self, kv_cache: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
if self._shuffle_kv_layout:
# (2, B, N, H, hs) -> ((B, N, H, hs), (B, N, H, hs))
return kv_cache.unbind(0)
# (B, H, N, 2*hs) -> ((B, N, H, hs), (B, N, H, hs))
return kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
def _shuffle_kv_views(
self, key_cache: torch.Tensor, value_cache: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
nb, bs, nkv, hd = key_cache.shape
x = 16 // key_cache.element_size()
kc = key_cache.reshape(nb, nkv, hd // x, bs, x)
vc = value_cache.reshape(nb, nkv, bs // x, hd, x)
return kc, vc
def forward(
self,
layer: torch.nn.Module,
@@ -264,6 +292,9 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
if self._use_shuffle_kv:
key_cache, value_cache = self._shuffle_kv_views(key_cache, value_cache)
cu_seqlens_q = attn_metadata.query_start_loc
seqused_k = attn_metadata.seq_lens
max_seqlen_q = attn_metadata.max_query_len
@@ -291,6 +322,7 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
v_descale=layer._v_scale,
sinks=self.sinks,
output_scale=output_scale,
shuffled_kv_cache=self._use_shuffle_kv,
)
else:
# The aiter kernel is causal-only. Non-causal cross-attention
@@ -339,6 +371,27 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
return
key_cache, value_cache = self._split_kv_cache(kv_cache)
if self._use_shuffle_kv:
from vllm.v1.attention.backends.rocm_aiter_fa import (
reshape_and_cache_shuffle_triton,
)
if get_kv_quant_mode(self.kv_cache_dtype) == KVQuantMode.FP8_PER_TENSOR:
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
_dummy = torch.empty(1, dtype=torch.float32, device=key.device)
reshape_and_cache_shuffle_triton(
key,
value,
key_cache,
value_cache,
slot_mapping,
self.kv_cache_dtype,
_dummy,
_dummy,
)
return
# Reshape the input keys and values and store them in the cache.
ops.reshape_and_cache_flash(
key,
@@ -360,6 +413,11 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
def fused_qk_norm_mrope_kvcache_supported(self) -> bool:
return IS_AITER_FOUND
def set_interleaved_v_cache(self):
# No-op override of RocmAttentionImpl: this backend
# decodes with the AITER triton unified-attention kernel
pass
def do_qk_norm_rope_kvcache_update(
self,
layer: AttentionLayer,
@@ -395,7 +453,8 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
k_scale=layer._k_scale_cpu,
v_scale=layer._v_scale_cpu,
kv_cache_dtype=self.kv_cache_dtype,
use_shuffle_layout=False,
use_shuffle_layout=self._use_shuffle_kv,
return_kv=False,
)
def do_qk_norm_mrope_kvcache_update(
@@ -456,13 +515,16 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
# we use direct Q, K, V tensors without caching
return
key_cache, value_cache = self._split_kv_cache(kv_cache)
flash_layout = True
is_fp8_kv_cache = is_quantized_kv_cache(self.kv_cache_dtype)
if is_fp8_kv_cache:
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
if self._use_shuffle_kv:
key_cache, value_cache = self._shuffle_kv_views(key_cache, value_cache)
flash_layout = not self._use_shuffle_kv
rocm_aiter_ops.triton_rope_and_cache(
query,
key,
+63
View File
@@ -292,6 +292,8 @@ class RocmAttentionImpl(AttentionImpl):
f"num_heads: {num_heads}."
)
self._use_interleaved_v_cache = False
def _forward_encoder_attention(
self,
query: torch.Tensor,
@@ -450,6 +452,7 @@ class RocmAttentionImpl(AttentionImpl):
sm_scale=self.scale,
output_scale=output_scale,
sinks=self.sinks,
use_interleaved_v_cache=self._use_interleaved_v_cache,
causal=attn_metadata.causal,
)
@@ -475,6 +478,12 @@ class RocmAttentionImpl(AttentionImpl):
block_size = value_cache.shape[3]
has_native_layout = has_native_kv_cache_layout(key_cache, value_cache)
# Match the fused writer's interleaved V-cache when fusion is active.
interleaved_v = self._use_interleaved_v_cache
interleaved_v_pack_factor = (
(16 // value_cache.element_size()) if interleaved_v else 0
)
if block_size in (16, 32) and has_native_layout:
# Normal 16, 32 with contiguous blocks: use vLLM native HIP C++ logic.
PagedAttention.write_to_paged_cache(
@@ -486,6 +495,7 @@ class RocmAttentionImpl(AttentionImpl):
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
interleaved_v,
)
else:
# Non-standard blocks and hybrid attention/Mamba layouts need the
@@ -501,8 +511,61 @@ class RocmAttentionImpl(AttentionImpl):
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
interleaved_v_pack_factor,
)
def fused_qk_norm_rope_kvcache_supported(self):
return rocm_aiter_ops.is_enabled()
def set_interleaved_v_cache(self):
# Decode/prefill kernels must read the interleaved V-cache the AITER
# fused write emits when use_shuffle_layout=True.
self._use_interleaved_v_cache = True
def do_qk_norm_rope_kvcache_update(
self,
layer: AttentionLayer,
qkv: torch.Tensor,
q_out: torch.Tensor,
k_out: torch.Tensor,
positions: torch.Tensor,
q_weight: torch.Tensor,
k_weight: torch.Tensor,
rms_norm_eps: float,
cos_sin_cache: torch.Tensor,
is_neox: bool,
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
# kv_cache is logical [num_blocks, 2, block_size, num_kv_heads * head_size]
# (see forward); the AITER shuffle writer takes one (B, N, H, hs) per side.
key_cache, value_cache = kv_cache.unflatten(
-1, (self.num_kv_heads, self.head_size)
).unbind(1)
use_shuffle_layout = self._use_interleaved_v_cache
rocm_aiter_ops.do_qk_norm_rope_kvcache_update(
qkv=qkv,
q_weight=q_weight,
k_weight=k_weight,
cos_sin_cache=cos_sin_cache,
positions=positions,
num_heads_q=self.num_heads,
num_heads_k=self.num_kv_heads,
head_dim=self.head_size,
is_neox=is_neox,
rms_norm_eps=rms_norm_eps,
q_out=q_out,
k_out=k_out,
key_cache=key_cache,
value_cache=value_cache,
slot_mapping=layer_slot_mapping,
k_scale=layer._k_scale_cpu,
v_scale=layer._v_scale_cpu,
kv_cache_dtype=self.kv_cache_dtype,
use_shuffle_layout=use_shuffle_layout,
return_kv=True,
)
def fused_rope_kvcache_supported(self):
return rocm_aiter_ops.is_enabled()
+124 -12
View File
@@ -18,6 +18,7 @@ from typing_extensions import runtime_checkable
from vllm.config import CacheConfig, VllmConfig, get_layers_from_vllm_config
from vllm.config.cache import _layout_from_name
from vllm.triton_utils import tl, triton
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.math_utils import cdiv
from vllm.utils.torch_utils import PIN_MEMORY, async_tensor_h2d, np_to_pinned_tensor
@@ -1160,6 +1161,75 @@ def get_dcp_local_seq_lens(
return dcp_local_seq_lens
@triton.jit(
do_not_specialize_on_alignment=["out_ptr", "block_table_ptr", "seq_lens_ptr"]
)
def _mamba_align_block_table_kernel(
out_ptr,
block_table_ptr,
block_table_stride_0: tl.int64,
block_table_stride_1,
seq_lens_ptr,
seq_lens_stride,
block_size,
n_out,
BLOCK: tl.constexpr,
):
"""Gather the last ``n_out`` block-table entries of each request.
One program per request. This replaces a five-statement PyTorch expression
that expanded to seven kernels over a ``(num_reqs,)`` tensor -- one element
in a single-request decode -- so almost all of its cost was launch
overhead rather than work.
Both block-table strides are passed explicitly. The expression this replaces
was ``torch.gather(block_table, 1, ...)``, which honours any layout, and
this is a shared utility -- ``gdn_attn``, ``mamba_attn``, ``short_conv_attn``
and ``linear_attn`` all call it -- so assuming a column stride of 1 would
silently read the wrong slots for a caller holding a non-contiguous view.
``kimi_k3/nvidia/kda_metadata.py`` passes both strides for the same reason.
Two annotations above are load-bearing and easy to drop by accident:
``block_table_stride_0: tl.int64``
Without it ``req_idx * block_table_stride_0`` is computed in i32 --
``program_id`` is i32 and Triton specializes a stride below 2^31 to
i32 -- so the product wraps once a row offset reaches 2^31 elements
(a 4096 x 625000 table faults from row 3436 on MI355X).
``torch.gather``, which this replaces, indexes in 64-bit and has no
such limit, so narrowing it would be a regression.
``mamba_utils.py:43`` annotates its row stride the same way.
``do_not_specialize_on_alignment`` on the three pointers
Triton puts pointer alignment in the specialization key, and the MRV1
DBO path hands this kernel ``seq_lens[request_slice]`` /
``block_table_tensor[request_slice]`` VIEWS (ubatch_utils.py:278/316).
When a ubatch starts at a request index that is not a multiple of 4
the view is differently aligned and a fresh variant JIT-compiles
mid-step -- 25-28 ms cold, ~1.5 ms warm, and an error under
``jit_monitor_mode=error``. The torch expression this replaced never
compiled anything, so that recompile would be a regression introduced
by this change.
"""
req_idx = tl.program_id(0)
seq_len = tl.load(seq_lens_ptr + req_idx * seq_lens_stride)
# A zero-length request in a CUDA graph has an invalid block table; clamp
# to 0 so it reads a valid row, exactly as the previous clamp_ did.
start = tl.maximum((seq_len - 1) // block_size, 0)
offs = tl.arange(0, BLOCK)
mask = offs < n_out
vals = tl.load(
block_table_ptr
+ req_idx * block_table_stride_0
+ (start + offs) * block_table_stride_1,
mask=mask,
other=0,
)
# `out` is freshly allocated by the caller and therefore contiguous, so its
# row stride is exactly n_out.
tl.store(out_ptr + req_idx * n_out + offs, vals, mask=mask)
def mamba_get_block_table_tensor(
block_table: torch.Tensor,
seq_lens: torch.Tensor,
@@ -1180,16 +1250,58 @@ def mamba_get_block_table_tensor(
return block_table
else:
assert isinstance(kv_cache_spec, MambaSpec)
# NOTE: For 0-length requests in CUDA graph, use a start_index of 0
# to handle the invalid block table.
start_indices = (seq_lens - 1) // kv_cache_spec.block_size
start_indices.clamp_(min=0)
# Use int32 for arithmetic to avoid dtype promotion overhead,
# then convert to int64 for gather (which requires Long indices)
offsets = torch.arange(
1 + kv_cache_spec.num_speculative_blocks,
device=block_table.device,
dtype=torch.int32,
# The arithmetic here is trivial -- a divide, a clamp, an arange, an
# add, a cast and a gather -- but as PyTorch ops it was seven kernel
# launches over a (num_reqs,) tensor, which holds a single element in a
# one-request decode. One Triton kernel does the same work in one
# launch. Zero-length requests in a CUDA graph still clamp to row 0.
num_reqs = block_table.shape[0]
n_out = 1 + kv_cache_spec.num_speculative_blocks
# The expression this replaced took its row count from `seq_lens` (a
# `torch.gather` whose index tensor is built from it), so a mismatch
# raised and a cross-device pair raised. Taking `num_reqs` from
# `block_table` instead silently changed all of that: with 4 block-table
# rows and 2 `seq_lens`, the old code returned 2 correct rows and the new
# kernel returns 4, two of them read from memory past the end of
# `seq_lens`; a pinned-CPU `seq_lens` with a GPU `block_table` used to
# raise and would now be read zero-copy from host memory.
#
# No in-tree caller does any of that today, but this helper is shared by
# gdn_attn, mamba_attn, short_conv_attn and linear_attn. Both are host
# metadata, so this costs no synchronisation, and it keeps the CPU
# branch below and the GPU kernel agreeing on the same inputs.
assert seq_lens.shape[0] == num_reqs, (
f"seq_lens has {seq_lens.shape[0]} rows, block_table has {num_reqs}"
)
indices_to_gather = (start_indices.unsqueeze(1) + offsets).to(torch.int64)
return torch.gather(block_table, 1, indices_to_gather)
assert seq_lens.device == block_table.device, (
f"seq_lens is on {seq_lens.device}, block_table on {block_table.device}"
)
if not block_table.is_cuda:
# Triton runs on the accelerator only, and this helper IS called
# with CPU tensors: the GDN and linear-attention metadata builders
# are unit-tested on CPU (`DEVICE = torch.device("cpu")`). The
# expression this replaced was plain torch and handled that, so
# keep it for the CPU path rather than narrowing the contract.
# kimi_k3/nvidia/kda_metadata.py asserts `is_cuda` instead; a
# shared utility cannot, because its callers legitimately pass CPU.
start_indices = (seq_lens - 1) // kv_cache_spec.block_size
start_indices = start_indices.clamp(min=0)
offsets = torch.arange(n_out, device=block_table.device, dtype=torch.int32)
return torch.gather(
block_table, 1, (start_indices.unsqueeze(1) + offsets).to(torch.int64)
)
out = block_table.new_empty((num_reqs, n_out))
if num_reqs == 0:
return out
_mamba_align_block_table_kernel[(num_reqs,)](
out,
block_table,
block_table.stride(0),
block_table.stride(1),
seq_lens,
seq_lens.stride(0),
kv_cache_spec.block_size,
n_out,
BLOCK=triton.next_power_of_2(n_out),
)
return out
@@ -84,6 +84,7 @@ def kernel_paged_attention_2d(
query_start_len_ptr, # [num_seqs+1]
USE_SINKS: tl.constexpr, # bool
USE_FP8: tl.constexpr,
INTERLEAVED_V_PACK_FACTOR: tl.constexpr,
FP8_MIN: tl.constexpr = float8_info.min,
FP8_MAX: tl.constexpr = float8_info.max,
):
@@ -170,13 +171,24 @@ def kernel_paged_attention_2d(
+ (offs_d[:, None] % x) * stride_k_cache_4
)
# 4D addressing logic of V (Slot is innermost)
v_offset = (
p_block_idx[:, None] * stride_v_cache_0
+ kv_head_idx * stride_v_cache_1
+ offs_d[None, :] * stride_v_cache_2
+ internal_offsets[:, None] * stride_v_cache_3
)
# V addressing: standard 4D or interleaved 5D
if INTERLEAVED_V_PACK_FACTOR > 0:
v_offset = (
p_block_idx[:, None] * stride_v_cache_0
+ kv_head_idx * stride_v_cache_1
+ (internal_offsets[:, None] // INTERLEAVED_V_PACK_FACTOR)
* HEAD_SIZE
* INTERLEAVED_V_PACK_FACTOR
+ offs_d[None, :] * INTERLEAVED_V_PACK_FACTOR
+ (internal_offsets[:, None] % INTERLEAVED_V_PACK_FACTOR)
)
else:
v_offset = (
p_block_idx[:, None] * stride_v_cache_0
+ kv_head_idx * stride_v_cache_1
+ offs_d[None, :] * stride_v_cache_2
+ internal_offsets[:, None] * stride_v_cache_3
)
# Only the final tile can straddle seq_len. Slots >= seq_len are
# unwritten KV cache that may hold NaN/garbage; they are score-masked
@@ -304,6 +316,7 @@ def chunked_prefill_paged_decode(
# Optional tensor for sinks
sinks=None,
is_block_table_ptr: bool = False,
use_interleaved_v_cache: bool = False,
causal: bool = True,
):
if sm_scale is None:
@@ -314,6 +327,10 @@ def chunked_prefill_paged_decode(
if sliding_window is None or sliding_window <= 0:
sliding_window = 0
interleaved_v_pack_factor = (
(16 // value_cache.element_size()) if use_interleaved_v_cache else 0
)
if max_query_len > 1:
context_attention_fwd(
q=query,
@@ -336,6 +353,7 @@ def chunked_prefill_paged_decode(
skip_decode=True,
fp8_out_scale=output_scale,
sinks=sinks,
interleaved_v_pack_factor=interleaved_v_pack_factor,
causal=causal,
)
@@ -428,6 +446,7 @@ def chunked_prefill_paged_decode(
k_scale=k_scale,
v_scale=v_scale,
fp8_out_scale=output_scale,
use_interleaved_v_cache=use_interleaved_v_cache,
)
else:
logger.warning_once(
@@ -504,4 +523,5 @@ def chunked_prefill_paged_decode(
query_start_len_ptr=query_start_loc,
USE_SINKS=sinks is not None,
USE_FP8=output_scale is not None,
INTERLEAVED_V_PACK_FACTOR=interleaved_v_pack_factor,
)
+2
View File
@@ -38,6 +38,7 @@ class PagedAttention:
kv_cache_dtype: str,
k_scale: torch.Tensor,
v_scale: torch.Tensor,
interleaved_v: bool,
) -> None:
ops.reshape_and_cache(
key,
@@ -48,4 +49,5 @@ class PagedAttention:
kv_cache_dtype,
k_scale,
v_scale,
interleaved_v,
)
+51 -13
View File
@@ -56,6 +56,8 @@ def _paged_kv_cache_offsets(
stride_v_cache_d,
stride_v_cache_bl,
PHYSICAL_BLOCK_SIZE: tl.constexpr,
BLOCK_DMODEL: tl.constexpr,
INTERLEAVED_V_PACK_FACTOR: tl.constexpr = 0,
MASK_BLOCK_TABLE: tl.constexpr = False,
):
"""Compute paged K/V cache element offsets for a tile of token positions.
@@ -65,7 +67,9 @@ def _paged_kv_cache_offsets(
tiles), then the physical element offsets are built with the same layout the
kernel uses everywhere:
K cache: [num_blocks, num_kv_heads, head_size // x, block_size, x]
V cache: [num_blocks, num_kv_heads, head_size, block_size]
V cache: [num_blocks, num_kv_heads, head_size, block_size], or the
interleaved layout [num_blocks, num_kv_heads, block_size // x,
head_size, x] when `INTERLEAVED_V_PACK_FACTOR` (= x) > 0.
Returns `(off_k, off_v)` with shapes [D, N] and [N, D] respectively.
When `MASK_BLOCK_TABLE` is set, the block-table load is masked with
@@ -94,12 +98,25 @@ def _paged_kv_cache_offsets(
+ internal[None, :] * stride_k_cache_bl
+ (offs_d[:, None] % x) * stride_k_cache_x
)
off_v = (
bn[:, None] * stride_v_cache_bs
+ cur_kv_head * stride_v_cache_h
+ offs_d[None, :] * stride_v_cache_d
+ internal[:, None] * stride_v_cache_bl
)
if INTERLEAVED_V_PACK_FACTOR > 0:
# Interleaved V-cache: [num_blocks, num_kv_heads, block_size/x,
# head_size, x] flattened onto the 4D stride layout.
off_v = (
bn[:, None] * stride_v_cache_bs
+ cur_kv_head * stride_v_cache_h
+ (internal[:, None] // INTERLEAVED_V_PACK_FACTOR)
* BLOCK_DMODEL
* INTERLEAVED_V_PACK_FACTOR
+ offs_d[None, :] * INTERLEAVED_V_PACK_FACTOR
+ (internal[:, None] % INTERLEAVED_V_PACK_FACTOR)
)
else:
off_v = (
bn[:, None] * stride_v_cache_bs
+ cur_kv_head * stride_v_cache_h
+ offs_d[None, :] * stride_v_cache_d
+ internal[:, None] * stride_v_cache_bl
)
return off_k, off_v
@@ -159,6 +176,7 @@ def _fwd_kernel(
USE_FP8: tl.constexpr,
CAUSAL: tl.constexpr = True,
MAX_Q_LEN: tl.constexpr = 0,
INTERLEAVED_V_PACK_FACTOR: tl.constexpr = 0,
MAX_CTX_LEN: tl.constexpr = 0,
FP8_MIN: tl.constexpr = float8_info.min,
FP8_MAX: tl.constexpr = float8_info.max,
@@ -263,6 +281,8 @@ def _fwd_kernel(
stride_v_cache_d,
stride_v_cache_bl,
PHYSICAL_BLOCK_SIZE,
BLOCK_DMODEL,
INTERLEAVED_V_PACK_FACTOR,
)
if (
@@ -403,6 +423,8 @@ def _fwd_kernel(
stride_v_cache_d,
stride_v_cache_bl,
PHYSICAL_BLOCK_SIZE,
BLOCK_DMODEL,
INTERLEAVED_V_PACK_FACTOR,
MASK_BLOCK_TABLE=True,
)
k_cur_load = tl.load(
@@ -540,6 +562,7 @@ def _fwd_kernel_alibi(
BLOCK_DMODEL_PADDED: tl.constexpr, # head size padded to a power of 2
BLOCK_N: tl.constexpr,
SKIP_DECODE: tl.constexpr,
INTERLEAVED_V_PACK_FACTOR: tl.constexpr,
):
# attn_bias[]
cur_batch = tl.program_id(0)
@@ -608,12 +631,24 @@ def _fwd_kernel_alibi(
+ ((start_n + offs_n[None, :]) % block_size) * stride_k_cache_bl
+ (offs_d[:, None] % x) * stride_k_cache_x
)
off_v = (
bn[:, None] * stride_v_cache_bs
+ cur_kv_head * stride_v_cache_h
+ offs_d[None, :] * stride_v_cache_d
+ (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl
)
if INTERLEAVED_V_PACK_FACTOR > 0:
v_internal = (start_n + offs_n[:, None]) % block_size
off_v = (
bn[:, None] * stride_v_cache_bs
+ cur_kv_head * stride_v_cache_h
+ (v_internal // INTERLEAVED_V_PACK_FACTOR)
* BLOCK_DMODEL
* INTERLEAVED_V_PACK_FACTOR
+ offs_d[None, :] * INTERLEAVED_V_PACK_FACTOR
+ (v_internal % INTERLEAVED_V_PACK_FACTOR)
)
else:
off_v = (
bn[:, None] * stride_v_cache_bs
+ cur_kv_head * stride_v_cache_h
+ offs_d[None, :] * stride_v_cache_d
+ (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl
)
k_load = tl.load(
K_cache + off_k,
mask=dim_mask[:, None] & ((start_n + offs_n[None, :]) < cur_batch_ctx_len),
@@ -796,6 +831,7 @@ def context_attention_fwd(
fp8_out_scale=None,
sinks=None,
is_block_table_ptr: bool = False,
interleaved_v_pack_factor: int = 0,
causal: bool = True,
):
q_dtype_is_f32 = q.dtype is torch.float32
@@ -937,6 +973,7 @@ def context_attention_fwd(
BLOCK_DMODEL_PADDED=Lk_padded,
BLOCK_N=BLOCK,
SKIP_DECODE=skip_decode,
INTERLEAVED_V_PACK_FACTOR=interleaved_v_pack_factor,
num_warps=NUM_WARPS,
num_stages=1,
)
@@ -1010,6 +1047,7 @@ def context_attention_fwd(
num_warps=4,
num_stages=1,
USE_SINKS=sinks is not None,
INTERLEAVED_V_PACK_FACTOR=interleaved_v_pack_factor,
CAUSAL=causal,
KV_FROM_CACHE=kv_from_cache,
**extra_kargs,
@@ -52,6 +52,9 @@ def reshape_and_cache_kernel_flash(
block_size: tl.constexpr,
x: tl.constexpr,
USE_HEAD_MAJOR_LAYOUT: tl.constexpr,
# >0 writes V interleaved as [Block, Head, Slot//kx, Dim, kx] (head-major
# layout only); 0 keeps the standard [Block, Head, Dim, Slot] V layout.
INTERLEAVED_V_PACK_FACTOR: tl.constexpr,
# FP8 flags
FP8_KV_CACHE: tl.constexpr,
# tune parameters
@@ -76,13 +79,25 @@ def reshape_and_cache_kernel_flash(
# Decompose the tile index back into head and dim coordinates.
cur_head = tile_pos // head_size
cur_dim = tile_pos % head_size
# Value addressing (4D): [Block, Head, Dim, Slot]
tgt_idx_v = (
block_idx * block_stride
+ cur_head * head_stride
+ cur_dim * dim_stride_v
+ block_offset * 1
)
# Value addressing: standard 4D [Block, Head, Dim, Slot], or the
# interleaved 5D [Block, Head, Slot//kx, Dim, kx] the fused AITER
# writer emits and the interleaved read path expects.
if INTERLEAVED_V_PACK_FACTOR > 0:
tgt_idx_v = (
block_idx * block_stride
+ cur_head * head_stride
+ (block_offset // INTERLEAVED_V_PACK_FACTOR)
* (head_size * INTERLEAVED_V_PACK_FACTOR)
+ cur_dim * INTERLEAVED_V_PACK_FACTOR
+ (block_offset % INTERLEAVED_V_PACK_FACTOR)
)
else:
tgt_idx_v = (
block_idx * block_stride
+ cur_head * head_stride
+ cur_dim * dim_stride_v
+ block_offset * 1
)
# Key addressing (5D): [Block, Head, Dim//8, Slot, 8]
tgt_idx_k = (
block_idx * block_stride
@@ -371,11 +386,18 @@ def triton_reshape_and_cache_flash(
kv_cache_dtype: str, # "auto", "fp8"
k_scale: torch.Tensor, # float32
v_scale: torch.Tensor, # float32
interleaved_v_pack_factor: int = 0, # >0: interleave V (head-major); 0: standard
):
num_heads = key.shape[1]
head_size = key.shape[2]
use_head_major_layout = key_cache.ndim == 5
if interleaved_v_pack_factor and not use_head_major_layout:
raise NotImplementedError(
"Interleaved V-cache write is only implemented for the head-major "
"(5D) cache layout; got a non-head-major cache with "
f"interleaved_v_pack_factor={interleaved_v_pack_factor}."
)
if use_head_major_layout:
block_size = key_cache.shape[3]
x = key_cache.shape[4]
@@ -452,6 +474,7 @@ def triton_reshape_and_cache_flash(
block_size=block_size,
x=x,
USE_HEAD_MAJOR_LAYOUT=use_head_major_layout,
INTERLEAVED_V_PACK_FACTOR=interleaved_v_pack_factor,
FP8_KV_CACHE=FP8_KV_CACHE,
# autotune parameters
TILE_SIZE=TILE_SIZE,