[Mini-vLLM] SM86-only cut: models, backends, Rust, tests

- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries
- Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels
- Remove inc/quark quant loaders; keep compressed-tensors and Marlin
- Drop the Rust frontend, pooling entrypoints, and idle test suites
- Rebuild kernels for sm_80;sm_86 and strip the extensions
- Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-18 19:19:56 +07:00
co-authored by Hinata
parent c5ab42bc0f
commit e61dcb9143
2728 changed files with 159 additions and 950401 deletions
File diff suppressed because it is too large Load Diff
-558
View File
@@ -1,558 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar
if TYPE_CHECKING:
from vllm.config.cache import CacheDType
import torch
from vllm import _custom_ops as ops
from vllm import envs
from vllm.config import (
VllmConfig,
get_current_vllm_config,
get_layers_from_vllm_config,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
from vllm.platforms import CpuArchEnum, current_platform
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionImpl,
AttentionLayer,
AttentionMetadataBuilder,
AttentionType,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
get_num_attention_heads_from_layers,
)
from vllm.v1.attention.backends.zentorch_sdpa import (
should_use_zentorch_sdpa,
zentorch_sdpa_attn,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
CrossAttentionSpec,
EncoderOnlyAttentionSpec,
KVCacheLayout,
)
logger = init_logger(__name__)
class CPUAttentionBackend(AttentionBackend):
forward_includes_kv_cache_update: bool = False
supported_dtypes: ClassVar[list[torch.dtype]] = [
torch.float16,
torch.bfloat16,
torch.float32,
]
supported_kv_cache_dtypes: ClassVar[list["CacheDType"]] = [
"auto",
"fp8",
"fp8_e4m3",
"fp8_e5m2",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(32)]
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [32, 64, 80, 96, 112, 128, 160, 192, 224, 256, 512]
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
# The CPU backend only reads head-major block interiors.
return (KVCacheLayout.LBHNC,)
@staticmethod
def get_name() -> str:
return "CPU_ATTN"
@classmethod
def supports_non_causal(cls) -> bool:
return True
@classmethod
def supports_sliding_window(cls) -> bool:
return True
@classmethod
def supports_attn_type(cls, attn_type: str) -> bool:
"""CPU attention supports decoder,
encoder-only and encoder-decoder attention."""
return attn_type in (
AttentionType.DECODER,
AttentionType.ENCODER,
AttentionType.ENCODER_ONLY,
AttentionType.ENCODER_DECODER,
)
@staticmethod
def get_impl_cls() -> type["CPUAttentionBackendImpl"]:
return CPUAttentionBackendImpl
@staticmethod
def get_builder_cls() -> type["CPUAttentionMetadataBuilder"]:
return CPUAttentionMetadataBuilder
@dataclass
class CPUAttentionMetadata:
num_actual_tokens: int # Number of tokens excluding padding.
max_query_len: int
query_start_loc: torch.Tensor
max_seq_len: int
seq_lens: torch.Tensor
block_table: torch.Tensor
slot_mapping: torch.Tensor
scheduler_metadata: torch.Tensor | None
causal: bool = True
dynamic_causal: torch.Tensor | None = None
# can be removed after deprecate sdpa
use_sdpa_prefill: bool = False
num_decode_tokens: int = 0
sdpa_attn_masks: list[torch.Tensor | None] | None = None
sdpa_start_loc: torch.Tensor | None = None
encoder_cache: torch.Tensor | None = None
class CPUAttentionMetadataBuilder(AttentionMetadataBuilder[CPUAttentionMetadata]):
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
self.kv_cache_spec = kv_cache_spec
self.vllm_config = vllm_config
parallel_config = vllm_config.parallel_config
self.num_kv_heads = kv_cache_spec.num_kv_heads
# The scheduler metadata built here sizes a scratchpad from the query
# head count, so it must come from this group's layers: the model-wide
# count is wrong for models that vary it per layer (e.g. Laguna).
self.num_heads = get_num_attention_heads_from_layers(
vllm_config, layer_names
) or vllm_config.model_config.get_num_attention_heads(parallel_config)
self.head_dim = kv_cache_spec.head_size
self.dtype = vllm_config.model_config.dtype
self.window_size = self._group_sliding_window()
self.block_size = kv_cache_spec.block_size
self.kv_cache_dtype = vllm_config.cache_config.cache_dtype
self.isa = _get_attn_isa(
self.dtype,
self.block_size,
self.head_dim,
self.kv_cache_dtype,
)
self._set_isa_to_layers(layer_names)
self.is_cross_attention = isinstance(kv_cache_spec, CrossAttentionSpec)
self.is_encoder_only_attention = isinstance(
kv_cache_spec, EncoderOnlyAttentionSpec
)
def _set_isa_to_layers(self, layer_names: list[str]) -> None:
attn_layers = get_layers_from_vllm_config(
self.vllm_config,
Attention,
layer_names,
)
for layer in attn_layers.values():
layer.isa = self.isa # type: ignore
def _group_sliding_window(self) -> int:
"""The window shared by every layer in this group, else -1 (no window).
Taken from the layers rather than the group spec: one KV cache group can
hold both windowed and global layers (e.g. Gemma-3 with the hybrid KV
cache manager disabled), and the scheduler metadata built here is shared
by the whole group, so it may only assume a window all of them agree on.
"""
layers = get_layers_from_vllm_config(
self.vllm_config, Attention, self.layer_names
)
windows = {
layer.impl.sliding_window
for layer in layers.values()
if isinstance(layer.impl, CPUAttentionBackendImpl)
}
if len(windows) != 1:
return -1
window = windows.pop()
return -1 if window is None else window
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> CPUAttentionMetadata:
num_reqs = common_attn_metadata.num_reqs
num_actual_tokens = common_attn_metadata.num_actual_tokens
max_query_len = common_attn_metadata.max_query_len
max_seq_len = common_attn_metadata.max_seq_len
query_start_loc = common_attn_metadata.query_start_loc
seq_lens = common_attn_metadata.seq_lens
block_table_tensor = common_attn_metadata.block_table_tensor
slot_mapping = common_attn_metadata.slot_mapping
is_dynamic_casual = isinstance(common_attn_metadata.causal, torch.Tensor)
dynamic_casual = None
if is_dynamic_casual:
dynamic_casual = common_attn_metadata.causal
causal = (
False
if self.is_cross_attention or is_dynamic_casual
else common_attn_metadata.causal
)
encoder_cache_tensor = None
if self.is_encoder_only_attention:
block_nums = (seq_lens + self.block_size - 1) // self.block_size
start_block_ids = torch.zeros_like(seq_lens)
torch.cumsum(block_nums[:-1], 0, out=start_block_ids[1:])
total_block_num: int = block_nums.sum().item()
max_block_num = block_nums.max().item()
block_offsets = torch.arange(
0, max_block_num, dtype=block_table_tensor.dtype
)
encoder_block_table = start_block_ids[:, None] + block_offsets[None, :]
torch.ops._C.compute_slot_mapping_kernel_impl(
query_start_loc,
common_attn_metadata.positions,
encoder_block_table,
slot_mapping,
self.block_size,
)
encoder_cache_tensor = torch.zeros(
(
total_block_num,
self.num_kv_heads,
self.block_size,
2 * self.head_dim,
),
dtype=self.dtype,
)
block_table_tensor = encoder_block_table
scheduler_metadata = ops.cpu_attn_get_scheduler_metadata(
num_reqs=num_reqs,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads,
head_dim=self.head_dim,
seq_lens=seq_lens,
dtype=self.dtype,
query_start_loc=query_start_loc,
causal=causal,
sliding_window_size=self.window_size,
isa=self.isa,
enable_kv_split=envs.VLLM_CPU_ATTN_SPLIT_KV,
dynamic_causal=dynamic_casual,
kv_cache_dtype=self.kv_cache_dtype,
)
attn_metadata = CPUAttentionMetadata(
num_actual_tokens=num_actual_tokens,
max_query_len=max_query_len,
query_start_loc=query_start_loc,
max_seq_len=max_seq_len,
seq_lens=seq_lens,
block_table=block_table_tensor,
slot_mapping=slot_mapping,
scheduler_metadata=scheduler_metadata,
causal=causal,
encoder_cache=encoder_cache_tensor,
dynamic_causal=dynamic_casual,
)
return attn_metadata
class CPUAttentionBackendImpl(AttentionImpl):
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None = None,
attn_type: str = AttentionType.DECODER,
kv_sharing_target_layer_name: str | None = None,
sinks: torch.Tensor | None = None,
) -> None:
self.kv_sharing_target_layer_name = kv_sharing_target_layer_name
self.num_heads = num_heads
self.head_size = head_size
self.scale = float(scale)
if logits_soft_cap is not None and attn_type in (
AttentionType.ENCODER,
AttentionType.ENCODER_ONLY,
):
logger.warning_once(
"CPU_ATTN does not support logits softcap for"
" ENCODER and ENCODER_ONLY, outputs may be slightly off"
)
if logits_soft_cap is None:
logits_soft_cap = 0
self.logits_soft_cap = logits_soft_cap
self.num_kv_heads = num_kv_heads
if alibi_slopes is not None:
alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
self.alibi_slopes = alibi_slopes
if sliding_window is None:
self.sliding_window = -1
else:
self.sliding_window = sliding_window
self.kv_cache_dtype = kv_cache_dtype
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
self.is_fp8_kv_cache = is_quantized_kv_cache(kv_cache_dtype)
self.attn_type = attn_type
self.sinks = sinks
if self.sinks is not None:
assert self.sinks.shape[0] == num_heads, (
"Sinks must have the same number of heads as the number of "
"heads in the layer"
)
vllm_config = get_current_vllm_config()
self.use_zentorch_sdpa = should_use_zentorch_sdpa(
attn_type,
vllm_config.model_config.dtype,
)
def forward(
self,
layer: AttentionLayer,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: CPUAttentionMetadata | None,
output: torch.Tensor,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass for CPU attention backend.
Args:
layer: The attention layer, providing the q/k/v quantization scales.
query: shape = [num_tokens, num_heads, head_size]
key: shape = [num_tokens, num_kv_heads, head_size]
value: shape = [num_tokens, num_kv_heads, head_size]
kv_cache: shape =
[num_blocks, num_kv_heads, block_size, 2 * head_size]
attn_metadata: Metadata for attention.
output: Tensor that the attention result is written into.
output_scale: Scale for fused output quantization; not supported
by this backend.
output_block_scale: Block scale for fused output quantization;
not supported by this backend.
Returns:
shape = [num_tokens, num_heads * head_size]
"""
if output_scale is not None or output_block_scale is not None:
raise NotImplementedError(
"fused output quantization is not yet supported"
" for CPUAttentionBackendImpl"
)
# For warming-up
if attn_metadata is None:
return output
num_actual_tokens = attn_metadata.num_actual_tokens
is_encoder_attention = self.attn_type in (
AttentionType.ENCODER_ONLY,
AttentionType.ENCODER,
)
if is_encoder_attention:
if self.use_zentorch_sdpa:
# Encoder attention never reads the KV cache back, so the
# zentorch path attends the packed QKV directly instead of
# staging it through the scratch encoder cache.
zentorch_sdpa_attn(
query[:num_actual_tokens],
key[:num_actual_tokens],
value[:num_actual_tokens],
output[:num_actual_tokens],
attn_metadata,
self.scale,
self.sliding_window,
self.alibi_slopes,
)
return output
# For encoder attention,
kv_cache = attn_metadata.encoder_cache
# KV cache size are [num_blocks, num_kv_heads, block_size,
# 2 * head_size]. Make a view [num_blocks, num_kv_heads,
# block_size * 2, head_size]. Then slice KV at dim 2
num_blocks, num_kv_heads, block_size, _ = kv_cache.size()
kv_cache = kv_cache.view((num_blocks, num_kv_heads, block_size * 2, -1))
key_cache, value_cache = kv_cache.chunk(2, dim=2)
if is_encoder_attention:
ops.cpu_attn_reshape_and_cache(
key,
value,
key_cache,
value_cache,
attn_metadata.slot_mapping,
layer.isa, # type: ignore
k_scale=layer._k_scale_float,
v_scale=layer._v_scale_float,
kv_cache_dtype=self.kv_cache_dtype,
)
# The CPU kernel executes attention sinks natively in bf16. If the
# sinks tensor is anything other than bf16, cast it to fp32 so it is
# executed in full float precision (done lazily here, after weights
# are loaded, rather than at __init__ time).
if self.sinks is not None and self.sinks.dtype not in [
torch.bfloat16,
torch.float32,
]:
self.sinks = self.sinks.to(torch.float32)
ops.cpu_attention_with_kv_cache(
query=query[:num_actual_tokens],
key_cache=key_cache,
value_cache=value_cache,
output=output[:num_actual_tokens], # type: ignore
query_start_loc=attn_metadata.query_start_loc,
seq_lens=attn_metadata.seq_lens,
scale=self.scale,
causal=attn_metadata.causal,
alibi_slopes=self.alibi_slopes, # type: ignore
sliding_window=self.sliding_window,
block_table=attn_metadata.block_table,
softcap=self.logits_soft_cap,
scheduler_metadata=attn_metadata.scheduler_metadata,
s_aux=self.sinks,
dynamic_causal=attn_metadata.dynamic_causal,
k_scale=layer._k_scale_float,
v_scale=layer._v_scale_float,
kv_cache_dtype=self.kv_cache_dtype,
)
return output
def do_kv_cache_update(
self,
layer: torch.nn.Module,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
) -> None:
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return
num_blocks, num_kv_heads, block_size, _ = kv_cache.size()
kv_cache = kv_cache.view((num_blocks, num_kv_heads, block_size * 2, -1))
key_cache, value_cache = kv_cache.chunk(2, dim=2)
ops.cpu_attn_reshape_and_cache(
key,
value,
key_cache,
value_cache,
slot_mapping,
layer.isa, # type: ignore
k_scale=layer._k_scale_float,
v_scale=layer._v_scale_float,
kv_cache_dtype=self.kv_cache_dtype,
)
@functools.lru_cache(maxsize=1)
def _riscv_supports_rvv() -> bool:
"""Whether the C++ RVV attention path is usable.
The kernel in csrc/cpu/cpu_attn_rvv.hpp uses VLEN-agnostic RVVI()
macros and supports VLEN=128 and VLEN=256. CMake auto-detects the
largest zvl<N>b from /proc/cpuinfo and passes it via -mrvv-vector-bits.
The RVV path is compiled whenever __riscv_v_min_vlen is defined, so
we check that at least one supported zvl<N>b is advertised.
"""
# The C++ compile-time check is the ground truth: it knows which
# VLEN the binary was actually compiled for. The cpuinfo check
# below is only a fast-path shortcut.
try:
import torch
if torch.ops._C.cpu_attn_has_isa("rvv"):
return True
except Exception:
pass
# Fallback: check /proc/cpuinfo for zvl128b/zvl256b.
try:
with open("/proc/cpuinfo") as f:
cpuinfo = f.read()
except OSError:
return False
return any(f"zvl{n}b" in cpuinfo for n in (128, 256))
def _get_attn_isa(
dtype: torch.dtype,
block_size: int,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> str:
fp8_kv = is_quantized_kv_cache(kv_cache_dtype) if kv_cache_dtype else False
if head_size is not None and head_size % 32 != 0 and head_size % 16 == 0:
if fp8_kv:
raise NotImplementedError(
"FP8 KV cache requires head_size divisible by 32 on CPU."
)
return "vec16"
supports_amx = torch.cpu._is_amx_tile_supported()
arch = current_platform.get_cpu_architecture()
supports_arm = arch == CpuArchEnum.ARM
supports_vxe = arch == CpuArchEnum.S390X
supports_riscv = arch == CpuArchEnum.RISCV
supports_vsx = arch == CpuArchEnum.POWERPC
supports_avx512 = torch.cpu._is_avx512_supported()
if fp8_kv and not supports_amx and not supports_avx512:
raise NotImplementedError(
"FP8 KV cache on CPU requires x86 with AVX-512 or AMX."
)
if supports_amx and dtype in (torch.bfloat16,) and block_size % 32 == 0:
return "amx"
elif supports_arm:
return "neon"
elif block_size % 32 == 0:
if supports_riscv and _riscv_supports_rvv():
return "rvv"
elif supports_vxe:
return "vxe"
elif supports_vsx:
return "vsx"
else:
return "vec"
else:
return "vec16"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-580
View File
@@ -1,580 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""HPC Attention Backend.
Pure attention (prefill + decode), without RoPE or RMSNorm.
Independent metadata / builder; KV cache layout is NHD:
(num_blocks, 2, block_size, num_kv_heads, head_size).
"""
import importlib.util
from dataclasses import dataclass
from typing import ClassVar
import torch
from typing_extensions import override
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.torch_utils import PIN_MEMORY
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionImpl,
AttentionMetadata,
AttentionMetadataBuilder,
AttentionType,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
split_decodes_and_prefills,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout, KVCacheSpec
logger = init_logger(__name__)
FP8_DTYPE = current_platform.fp8_dtype()
def _get_fp8_dtype_for_kv_cache(kv_cache_dtype: str) -> torch.dtype:
"""Return the torch FP8 dtype for the given kv_cache_dtype string."""
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
return torch.float8_e4m3fn
elif kv_cache_dtype == "fp8_e5m2":
return torch.float8_e5m2
else:
raise ValueError(f"Unrecognized FP8 dtype: {kv_cache_dtype}")
@dataclass
class HpcAttnMetadata(AttentionMetadata):
"""Metadata required by the HPC attention kernel."""
num_actual_tokens: int
num_decodes: int
num_decode_tokens: int
num_prefills: int
num_prefill_tokens: int
max_query_len: int
slot_mapping: torch.Tensor
"""Slot mapping for KV cache writes. shape = [num_actual_tokens]"""
seq_lens: torch.Tensor
"""KV cache length per request. shape = [batch_size]"""
block_table_tensor: torch.Tensor
"""Paged KV-cache block table.
shape = [batch_size, max_num_blocks_per_seq]"""
qo_indptr: torch.Tensor | None = None
"""Cumulative query lengths for prefill requests (GPU tensor).
shape = [num_prefills + 1]. None when num_prefills == 0."""
# --- HPC RopeNorm pass-through fields ---
# Set by HpcRopeNorm._forward_impl(); consumed & reset by
# HpcAttentionImpl.forward(). Defaults are safe for the standard
# (non-RopeNorm) path and for profiling runs (attn_metadata=None).
hpc_kv_written: bool = False
"""True when HpcRopeNorm has already written K/V into the paged cache."""
hpc_prefill_q_scale: torch.Tensor | None = None
"""FP8 per-token-per-head Q scale for prefill (from RopeNorm)."""
hpc_decode_q_scale: torch.Tensor | None = None
"""FP8 per-token-per-head Q scale for decode (persistent buffer).
shape = [max_decode_tokens, num_q_heads], contiguous.
Only the first num_decode_q_scale_tokens rows are valid."""
hpc_split_k_flag: torch.Tensor | None = None
"""Split-K flag tensor for FP8 decode (persistent buffer).
shape = [max_num_seqs, num_kv_heads], int32."""
# --- MTP (Multi-Token Prediction) fields ---
decode_query_len: int = 1
"""Number of query tokens per decode request.
1 for standard decoding, mtp+1 for speculative decoding (2 or 3)."""
qo_indptr_decode: torch.Tensor | None = None
"""Cumulative query offsets for decode requests (GPU tensor).
shape = [num_decodes + 1]. Only set when decode_query_len > 1.
e.g. 3 requests with dql=2: [0, 2, 4, 6]."""
task_map: torch.Tensor | None = None
"""Used for HPC dynamic schedule attention"""
class HpcAttnMetadataBuilder(AttentionMetadataBuilder[HpcAttnMetadata]):
"""Build HpcAttnMetadata from CommonAttentionMetadata."""
_cudagraph_support = AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
reorder_batch_threshold: int = 1
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
):
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
import hpc
self.num_kv_heads = kv_cache_spec.num_kv_heads
self.hpc_dynamic_sched_attn_min_split_len = 1024
# MTP constraint: HPC decode kernel only supports mtp in {0, 1, 2, 3}
spec_config = vllm_config.speculative_config
if (
spec_config is not None
and spec_config.num_speculative_tokens is not None
and spec_config.num_speculative_tokens > 3
):
raise ValueError(
f"HPC attention only supports up to 3 speculative tokens "
f"(mtp ∈ {{0, 1, 2, 3}}), got "
f"num_speculative_tokens={spec_config.num_speculative_tokens}. "
f"Please reduce num_speculative_tokens or use a different "
f"attention backend."
)
# Dynamic decode threshold for MTP support.
# _init_reorder_batch_threshold computes:
# no spec_config → threshold=1 (unchanged)
# with spec_config → threshold=1+num_speculative_tokens
self._init_reorder_batch_threshold(
reorder_batch_threshold=1,
supports_spec_as_decode=True,
)
# Dynamic-scheduled decode:
# - fp8 KV cache path always uses task_map (FP8 decode kernel
# requires it).
# - bf16 KV cache path only uses task_map when the installed hpc
# version supports it (hpc >= 6e2eced / PR #73). Older builds
# take the static split-K path with no task_map.
kv_cache_dtype = kv_cache_spec.dtype
self.use_fp8 = kv_cache_dtype == torch.float8_e4m3fn
self._dynamic_sched = True
if self._dynamic_sched:
self.task_map = hpc.get_attention_decode_task_workspace(
vllm_config.scheduler_config.max_num_seqs,
vllm_config.model_config.max_model_len or 4096,
self.num_kv_heads,
min_process_len=self.hpc_dynamic_sched_attn_min_split_len,
)
else:
self.task_map = None
@override # type: ignore[misc]
@classmethod
def get_cudagraph_support(
cls: type["HpcAttnMetadataBuilder"],
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> AttentionCGSupport:
spec_config = vllm_config.speculative_config
if (
spec_config is not None
and spec_config.num_speculative_tokens is not None
and spec_config.num_speculative_tokens > 0
):
return AttentionCGSupport.UNIFORM_BATCH
return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> HpcAttnMetadata:
"""Build HpcAttnMetadata from CommonAttentionMetadata."""
num_actual_tokens = common_attn_metadata.num_actual_tokens
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=self.reorder_batch_threshold,
# MTP requires uniform query lengths across decode requests
require_uniform=(self.reorder_batch_threshold > 1),
)
)
seq_lens = common_attn_metadata.seq_lens
block_table_tensor = common_attn_metadata.block_table_tensor
slot_mapping = common_attn_metadata.slot_mapping
max_query_len = common_attn_metadata.max_query_len
# Compute decode_query_len (tokens per decode request).
# Non-MTP: 1, MTP: mtp+1 (2 or 3).
if num_decodes > 0 and num_decode_tokens > num_decodes:
decode_query_len = num_decode_tokens // num_decodes
else:
decode_query_len = 1
seq_lens_decode = None
qo_indptr = None
qo_indptr_decode = None
if num_prefills > 0:
qo_indptr_cpu = common_attn_metadata.query_start_loc_cpu
prefill_start = num_decodes
qo_indptr_prefill_cpu = torch.empty(
num_prefills + 1, dtype=torch.int32, pin_memory=PIN_MEMORY
)
torch.subtract(
qo_indptr_cpu[prefill_start:],
qo_indptr_cpu[prefill_start],
out=qo_indptr_prefill_cpu,
)
qo_indptr = qo_indptr_prefill_cpu.to(self.device, non_blocking=True)
if num_decodes > 0:
seq_lens_decode = seq_lens[:num_decodes]
# block_table is per-request, indexed by num_decodes (not tokens)
qo_indptr_decode = common_attn_metadata.query_start_loc[: num_decodes + 1]
# Skip the task-map scheduler pass when dynamic scheduling is off
# (bf16 KV cache on an older hpc that lacks bf16 decode task_map).
if self._dynamic_sched:
import hpc
hpc.assign_attention_decode_task(
seq_lens_decode,
self.task_map,
self.num_kv_heads,
decode_query_len,
new_kv_included=True,
min_process_len=self.hpc_dynamic_sched_attn_min_split_len,
)
return HpcAttnMetadata(
num_actual_tokens=num_actual_tokens,
num_decodes=num_decodes,
num_decode_tokens=num_decode_tokens,
num_prefills=num_prefills,
num_prefill_tokens=num_prefill_tokens,
max_query_len=max_query_len,
slot_mapping=slot_mapping,
seq_lens=seq_lens,
block_table_tensor=block_table_tensor,
qo_indptr=qo_indptr,
hpc_kv_written=False,
hpc_prefill_q_scale=None,
hpc_decode_q_scale=None,
hpc_split_k_flag=None,
decode_query_len=decode_query_len,
qo_indptr_decode=qo_indptr_decode,
task_map=self.task_map,
)
class HpcAttentionBackend(AttentionBackend):
"""HPC attention backend (pure attention, no RoPE/Norm).
KV cache layout: LBNHC (num_blocks, num_kv_heads, block_size, 2 * head_size).
"""
accept_output_buffer: bool = True
supported_dtypes: ClassVar[list[torch.dtype]] = [
torch.float16,
torch.bfloat16,
]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"bfloat16",
"fp8_e4m3",
]
# Avoid attention abstracted method call cache insert
forward_includes_kv_cache_update: bool = True
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [64]
@staticmethod
def get_name() -> str:
return "HPC_ATTN"
@staticmethod
def get_impl_cls() -> type["HpcAttentionImpl"]:
return HpcAttentionImpl
@staticmethod
def get_builder_cls() -> type["HpcAttnMetadataBuilder"]:
return HpcAttnMetadataBuilder
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [128]
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability == DeviceCapability(9, 0)
@classmethod
def supports_kv_cache_dtype(cls, kv_cache_dtype: "CacheDType | None") -> bool:
if kv_cache_dtype is None:
return True
return kv_cache_dtype in cls.supported_kv_cache_dtypes
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
return (KVCacheLayout.LBNHC,)
class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
"""HPC pure attention implementation (no RoPE/Norm).
Constraints:
- head_dim == 128
- num_heads // num_kv_heads in {4, 8}
- kv_cache_dtype in {"auto", "fp8_e4m3"}
"""
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None = None,
sliding_window: int | None = None,
kv_cache_dtype: str = "auto",
logits_soft_cap: float | None = None,
attn_type: str = AttentionType.DECODER,
kv_sharing_target_layer_name: str | None = None,
) -> None:
if importlib.util.find_spec("hpc") is None:
raise ImportError(
"HPC attention requires the hpc module to be installed. "
"Please install it from https://github.com/Tencent/hpc-ops"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError("HPC attention only supports decoder attention")
if alibi_slopes is not None:
raise NotImplementedError("HPC attention does not support ALiBi")
if logits_soft_cap is not None:
raise NotImplementedError("HPC attention does not support logits_soft_cap")
if head_size != 128:
raise ValueError(
f"HPC attention only supports head_dim=128, got {head_size}"
)
num_queries_per_kv = num_heads // num_kv_heads
if num_queries_per_kv not in (4, 8):
raise ValueError(
f"HPC attention only supports head_per_group in {{4, 8}}, "
f"got {num_queries_per_kv} "
f"(num_heads={num_heads}, num_kv_heads={num_kv_heads})"
)
if kv_cache_dtype not in ("auto", "fp8_e4m3", "bfloat16"):
raise ValueError(
f"HPC attention only supports kv_cache_dtype 'auto' or "
f"'fp8_e4m3' or 'bfloat16', got '{kv_cache_dtype}'"
)
self.num_heads = num_heads
self.head_size = head_size
self.scale = float(scale)
self.num_kv_heads = num_kv_heads
self.kv_cache_dtype = kv_cache_dtype
self.kv_sharing_target_layer_name = kv_sharing_target_layer_name
self.num_queries_per_kv = num_queries_per_kv
if sliding_window is None:
self.sliding_window = (-1, -1)
else:
self.sliding_window = (sliding_window - 1, 0)
self.use_fp8 = kv_cache_dtype == "fp8_e4m3"
self.supports_quant_query_input = False
self.splitk = True
import hpc
if self.use_fp8:
self._quant_type = hpc.QuantType.QPERTOKEN_PERHEAD_KPERTENSOR_VPERTENSOR
else:
self._quant_type = None
def forward(
self,
layer: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: HpcAttnMetadata | None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""HPC attention forward (standard vLLM backend interface).
Two modes:
1. Standard: upstream handles RoPE/Norm; this backend writes KV + attn.
2. HpcRopeNorm: fused op already did RoPE/Norm/KV-Write/Q-Quant;
extra params passed via attn_metadata.hpc_* fields.
"""
import hpc
assert output is not None, "Output tensor must be provided."
assert output_scale is None, "HPC attention does not support fused output quant"
assert output_block_scale is None
if attn_metadata is None:
return output.fill_(0)
hpc_kv_written = attn_metadata.hpc_kv_written
hpc_prefill_q_scale = attn_metadata.hpc_prefill_q_scale
hpc_decode_q_scale = attn_metadata.hpc_decode_q_scale
hpc_split_k_flag = attn_metadata.hpc_split_k_flag
num_actual_tokens = attn_metadata.num_actual_tokens
num_prefill_reqs = attn_metadata.num_prefills
num_decode_reqs = attn_metadata.num_decodes
num_decode_tokens = attn_metadata.num_decode_tokens
# Logical (B, H, N, 2*head_size) -> (B, N, H, head_size) K/V views.
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
# Standard-path KV write: when no upstream fused op wrote KV cache
# (i.e. the model didn't wire HpcRopeNorm), fall back to the generic
# reshape_and_cache_flash. This is what lets non-HunYuan-V3 models use
# the HPC attention backend with bf16 KV cache without any model-side
# changes. FP8 KV cache always needs HpcRopeNorm (see check below), so
# we never take this path in fp8 mode.
if (
not self.use_fp8
and self.kv_sharing_target_layer_name is None
and not hpc_kv_written
):
torch.ops._C_cache_ops.reshape_and_cache_flash(
key,
value,
key_cache,
value_cache,
attn_metadata.slot_mapping,
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
)
if self.use_fp8:
if not hpc_kv_written:
raise RuntimeError(
"HpcAttentionImpl: FP8 KV cache mode requires HpcRopeNorm "
"(the fused rope_norm_store_kv_fp8 op produces the "
"per-token-per-head Q scales the FP8 attention kernel "
"needs). Ensure the model wires hpc_rope_norm, or switch "
"to --kv-cache-dtype auto / bfloat16."
f" (layer={getattr(layer, 'layer_name', '?')})"
)
torch_dtype = _get_fp8_dtype_for_kv_cache(self.kv_cache_dtype)
key_cache = key_cache.view(torch_dtype)
value_cache = value_cache.view(torch_dtype)
k_scale = layer._k_scale.reshape(1)
v_scale = layer._v_scale.reshape(1)
query = query[:num_actual_tokens]
key = key[:num_actual_tokens]
value = value[:num_actual_tokens]
output_padded = output
output = output[:num_actual_tokens]
# --- Prefill ---
if num_prefill_reqs > 0:
seq_lens_prefill = attn_metadata.seq_lens[num_decode_reqs:]
cu_seqlens_prefill = attn_metadata.qo_indptr
max_seqlens = attn_metadata.max_query_len
block_table_prefill = attn_metadata.block_table_tensor[num_decode_reqs:]
q_prefill = query[num_decode_tokens:]
output_prefill = output[num_decode_tokens:]
if self.use_fp8:
hpc.attention_with_kvcache_prefill_fp8(
q_prefill,
key_cache,
value_cache,
hpc_prefill_q_scale,
k_scale,
v_scale,
cu_seqlens_prefill,
block_table_prefill,
seq_lens_prefill,
max_seqlens,
quant_type=self._quant_type,
output=output_prefill,
)
else:
hpc.attention_with_kvcache_prefill_bf16(
q_prefill,
key_cache,
value_cache,
cu_seqlens_prefill,
block_table_prefill,
seq_lens_prefill,
max_seqlens,
output=output_prefill,
)
# --- Decode ---
if num_decode_reqs > 0:
num_seq_kvcache = attn_metadata.seq_lens[:num_decode_reqs]
block_table_decode = attn_metadata.block_table_tensor[:num_decode_reqs]
q_decode = query[:num_decode_tokens]
output_decode = output[:num_decode_tokens]
mtp = attn_metadata.decode_query_len - 1
if self.use_fp8:
hpc.attention_decode_fp8(
q_decode,
key_cache,
value_cache,
block_table_decode,
num_seq_kvcache,
hpc_decode_q_scale,
k_scale,
v_scale,
mtp=mtp,
# MTP: split_flag from rope_norm is unavailable
# when using prefill-mode kernel; let HPC decide.
# splitk=(self.splitk if mtp == 0 else True),
new_kv_included=True,
quant_type=self._quant_type,
splitk=self.splitk,
task_map=attn_metadata.task_map,
split_flag=hpc_split_k_flag,
output=output_decode,
)
else:
# Older hpc's bf16 decode has no task_map kwarg; the map is
# only ever built when the installed hpc supports it (see
# HpcAttnMetadataBuilder._dynamic_sched). Pass task_map
# conditionally to stay compatible with both versions
task_map_kwargs = (
{"task_map": attn_metadata.task_map}
if attn_metadata.task_map is not None
else {}
)
hpc.attention_decode_bf16(
q_decode,
key_cache,
value_cache,
block_table_decode,
num_seq_kvcache,
mtp=mtp,
output=output_decode,
new_kv_included=True,
splitk=self.splitk,
**task_map_kwargs,
)
return output_padded
@@ -1,66 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLABackend, AiterMLAImpl
class AiterTritonMLABackend(AiterMLABackend):
@staticmethod
def get_name() -> str:
return "AITER_TRITON_MLA"
@staticmethod
def get_impl_cls() -> type["AiterTritonMLAImpl"]:
return AiterTritonMLAImpl
class AiterTritonMLAImpl(AiterMLAImpl):
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
from aiter.ops.triton.mha import flash_attn_varlen_func
self.flash_attn_varlen_func = flash_attn_varlen_func
def _flash_attn_varlen_diff_headdims(
self, q, k, v, return_softmax_lse=False, softmax_scale=None, **kwargs
):
result = self.flash_attn_varlen_func( # type: ignore[call-arg]
q,
k,
v,
softmax_scale=softmax_scale,
return_lse=return_softmax_lse,
**kwargs,
)
# Transpose the LSE if Triton MHA is used:
# (q.shape[0], num_q_heads) to (num_q_heads, q.shape[0])
if type(result) is tuple and return_softmax_lse:
output, lse = result
lse = lse.T.contiguous()
return (output, lse)
return result
-476
View File
@@ -1,476 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""AMX-only, high-performance MLA backend for DeepSeek V2/V3/R1 on CPU.
Built on the AMX decode/extend/bmm kernels vendored under
``csrc/cpu/sgl-kernels/``, plugged into vLLM's ``MLACommonBackend``/
``MLACommonImpl`` abstraction the same way every other concrete MLA backend
(``TritonMLAImpl``, etc.) does.
This is a separate backend from the reference ``CPUMLABackend``
(``vllm/v1/attention/backends/mla/cpu_mla.py``): that one targets every CPU
(any dtype, block_size=16, ``mla_decode_kvcache`` decode kernel + inherited
SDPA-style prefill) as a functional/CI reference, not performance. This
backend instead requires AMX (bf16 only, block_size a multiple of 32) and is
selected by the platform layer in preference to the reference backend
whenever the host supports it -- see ``CpuPlatform.get_attn_backend_cls``.
Two points where this backend differs structurally from the GPU backends,
both explained in the CPU MLA design plan:
- ``forward_mha`` is fully overridden (not inherited from
``MLACommonBaseImpl``): the GPU "compute-friendly" prefill path depends on
a pluggable ``MLAPrefillBackend`` and CUDA-only chunked-context gather ops,
neither of which exist on CPU. Instead, this attends directly in
latent-MQA space via the ``extend_attention_cpu`` kernel, which handles
cached-prefix continuation and fresh prefill in one causal pass (the KV
cache already contains the new tokens by the time this runs, since
``do_kv_cache_update`` executes first).
- Weight absorption for the prefill path is done with this impl's own
VNNI-packed copies of ``W_UK``/``W_UV`` (computed in
``process_weights_after_loading``, using ``bmm_cpu``), rather than reading
the generic ``layer.W_UK_T``/``layer.W_UV``/``layer._v_up_proj`` the way
GPU backends do, since ``forward_mha``'s abstract signature has no
``layer`` parameter (only ``forward_mqa`` does) and that signature is left
untouched. The decode path needs no such packing: ``MLAAttention.forward_impl``
already absorbs/de-absorbs Q around the ``forward_mqa`` call using the
generic (unpacked) ``layer.W_UK_T``/``layer._v_up_proj``, so
``forward_mqa`` here only has to invoke the decode kernel.
"""
from __future__ import annotations
from typing import ClassVar
import torch
from vllm import _custom_ops as ops
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
get_and_maybe_dequant_weights,
)
from vllm.platforms import current_platform
from vllm.v1.attention.backend import AttentionLayer, AttentionType, MultipleOf
_MIN_WORK_PER_SPLIT = 512
_SPLIT_OCCUPANCY_MULTIPLIER = 2
def _block_quant_to_tensor_quant(
weight: torch.Tensor, # FP8 [N, K] block-quantized weight
weight_scale: torch.Tensor, # [ceil(N/bn), ceil(K/bk)] block scales
block_size: list[int], # [block_n, block_k]
) -> tuple[torch.Tensor, torch.Tensor]:
"""Re-quantize FP8 block-quant weight to FP8 per-tensor quant.
Returns (fp8_weight, dequant_scale) where fp8_weight * dequant_scale
approximates the original float weight. dequant_scale is a 0-dim
scalar tensor as expected by bmm_cpu's ``scale`` argument.
NOTE: block->tensor re-quantization may slightly affect accuracy
(equivalent to SGLang's block_quant_to_tensor_quant for CPU).
"""
block_n, block_k = block_size[0], block_size[1]
n, k = weight.shape
# Expand block scales [ceil(N/bn), ceil(K/bk)] -> [N, K]
scale = weight_scale.to(torch.float32)
if scale.shape[0] < n:
scale = scale.repeat_interleave(block_n, dim=0)[:n, :]
if scale.shape[1] < k:
scale = scale.repeat_interleave(block_k, dim=1)[:, :k]
# Dequantize to float32
x_f32 = weight.to(torch.float32) * scale
# Re-quantize per-tensor back to FP8
fp8_max = torch.finfo(weight.dtype).max # 448.0 for e4m3fn
amax = x_f32.abs().amax().clamp(min=1e-12)
quant_scale = fp8_max / amax
x_fp8 = (x_f32 * quant_scale).clamp(-fp8_max, fp8_max).to(weight.dtype)
# dequant_scale = 1 / quant_scale (0-dim tensor for bmm_cpu)
dequant_scale = (amax / fp8_max).to(torch.float32)
return x_fp8, dequant_scale
def _compute_num_kv_splits(max_seq_len: int, num_threads: int) -> int:
"""Mirrors TritonMLAImpl's _compute_num_kv_splits, using the CPU thread
count in place of SM count."""
ideal_splits = 1
while ideal_splits < max(1, max_seq_len // _MIN_WORK_PER_SPLIT):
ideal_splits *= 2
max_splits = num_threads * _SPLIT_OCCUPANCY_MULTIPLIER
return min(ideal_splits, max_splits)
def _expand_block_table(block_table: torch.Tensor, block_size: int) -> torch.Tensor:
"""Adapter: vLLM's block-table paging -> the flat per-(request, position)
physical row index the decode/extend kernels expect. Called once per step
from ``AMXMLAMetadataBuilder.build``, not per layer.
"""
offsets = torch.arange(
block_size, device=block_table.device, dtype=block_table.dtype
)
flat = block_table.unsqueeze(-1) * block_size + offsets
return flat.reshape(block_table.size(0), -1).contiguous()
class AMXMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
# kv_lora_rank(512) + qk_rope_head_dim(64), DeepSeek V2/V3/R1/V3.2.
return [576]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(32)]
@classmethod
def supports_block_size(cls, block_size: int | None) -> bool:
if block_size is None:
return True
return block_size % 32 == 0
@staticmethod
def get_name() -> str:
return "AMX_MLA"
@staticmethod
def get_impl_cls() -> type[AMXMLAImpl]:
return AMXMLAImpl
@staticmethod
def get_builder_cls() -> type[AMXMLAMetadataBuilder]:
return AMXMLAMetadataBuilder
class AMXMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
def build(self, common_prefix_len, common_attn_metadata, fast_build: bool = False):
attn_metadata = super().build(
common_prefix_len, common_attn_metadata, fast_build
)
block_size = self.kv_cache_spec.block_size
if attn_metadata.decode is not None:
# Built once per step and reused by every layer, instead of
# recomputing the same tensor arithmetic in every forward_mqa call.
decode = attn_metadata.decode
decode.req_to_token = _expand_block_table( # type: ignore[attr-defined]
decode.block_table, block_size
)
decode.seq_lens_i64 = decode.seq_lens.to(torch.int64) # type: ignore[attr-defined]
decode.req_pool_indices = torch.arange( # type: ignore[attr-defined]
decode.block_table.size(0),
dtype=torch.int64,
device=decode.block_table.device,
)
decode.num_kv_splits = _compute_num_kv_splits( # type: ignore[attr-defined]
attn_metadata.max_seq_len, current_platform.num_compute_units()
)
if attn_metadata.prefill is not None:
# cpu_seq_lens: total per-request context length (prefix + new
# tokens), the one thing the extend kernel needs that isn't
# already on the shared MLACommonPrefillMetadata.
prefill = attn_metadata.prefill
num_decodes = attn_metadata.num_decodes
num_prefills = attn_metadata.num_prefills
prefill.cpu_seq_lens = common_attn_metadata.seq_lens[ # type: ignore[attr-defined]
num_decodes : num_decodes + num_prefills
].to(torch.int64)
prefill.req_to_token = _expand_block_table( # type: ignore[attr-defined]
prefill.block_table, block_size
).to(torch.int64)
prefill.req_pool_indices = torch.arange( # type: ignore[attr-defined]
prefill.block_table.size(0),
dtype=torch.int64,
device=prefill.block_table.device,
)
query_start_loc_i64 = prefill.query_start_loc.to(torch.int64)
extend_seq_lens = query_start_loc_i64[1:] - query_start_loc_i64[:-1]
prefill.extend_seq_lens = extend_seq_lens # type: ignore[attr-defined]
prefill.extend_start_loc = query_start_loc_i64[:-1] # type: ignore[attr-defined]
prefill.max_len_extend = int(extend_seq_lens.max().item()) # type: ignore[attr-defined]
return attn_metadata
class AMXMLAImpl(MLACommonImpl[MLACommonMetadata]):
# Tells MLAAttention (mla_attention.py) to use this impl's own packed
# W_UK/W_UV + bmm_cpu for the shared decode absorb/de-absorb, mirroring
# is_aiter_triton_fp8_bmm_enabled/is_aiter_triton_fp4_bmm_enabled.
uses_amx_bmm = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"AMXMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and encoder/decoder cross-attention "
"are not implemented for AMXMLAImpl"
)
self._w_uk_packed: torch.Tensor | None = None
self._w_uv_packed: torch.Tensor | None = None
self._w_scale: torch.Tensor | None = (
None # per-tensor dequant scale (FP8 W8A16)
)
def process_weights_after_loading(self, act_dtype: torch.dtype) -> None:
# forward_mha (unlike forward_mqa) receives no `layer` argument, so it
# cannot read the generic layer.W_UK_T/W_UV/._v_up_proj that
# MLAAttention.process_weights_after_loading already computes. This
# impl derives its own copies from self.kv_b_proj (already available
# via the constructor) and VNNI-packs them once, ahead of time, for
# use with bmm_cpu in forward_mha.
#
# kv_b_proj carries `_cpu_skip_gemm_dispatch`, so the CPU FP8 kernels
# leave its weight in the checkpoint [N, K] layout. For block-quant
# FP8 checkpoints, re-quantize per-tensor and keep the BMM in FP8
# (W8A16); everything else goes through the BF16 path.
weight = getattr(self.kv_b_proj, "weight", None)
block_size = getattr(self.kv_b_proj, "weight_block_size", None)
if (
weight is not None
and weight.dtype == torch.float8_e4m3fn
and block_size is not None
):
block_scale = getattr(self.kv_b_proj, "weight_scale_inv", None)
if block_scale is None:
block_scale = self.kv_b_proj.weight_scale
fp8_weight, self._w_scale = _block_quant_to_tensor_quant(
weight, block_scale, block_size
)
# [N, K] -> [K, N] = [kv_lora_rank, heads * (nope + v)]
kv_b_proj_weight = fp8_weight.T.contiguous().view(
self.kv_lora_rank,
self.num_heads,
self.qk_nope_head_dim + self.v_head_dim,
)
else:
kv_b_proj_weight = get_and_maybe_dequant_weights(
self.kv_b_proj, out_dtype=act_dtype
).T
kv_b_proj_weight = kv_b_proj_weight.view(
self.kv_lora_rank,
self.num_heads,
self.qk_nope_head_dim + self.v_head_dim,
)
self._w_scale = None
w_uk, w_uv = kv_b_proj_weight.split(
[self.qk_nope_head_dim, self.v_head_dim], dim=-1
)
# bmm_cpu computes out[b] = mat1[b] @ mat2[b]^T (Linear-weight
# convention: mat2[b] is (OUT, IN)).
# absorb: ql_nope(N,B,L) = q_nope(N,B,P) @ w_uk_for_bmm(N,L,P)^T
# de-absorb: out(N,B,V) = attn_out(N,B,L) @ w_uv_for_bmm(N,V,L)^T
w_uk_for_bmm = w_uk.permute(1, 0, 2).contiguous() # (N, L, P)
w_uv_for_bmm = w_uv.permute(1, 2, 0).contiguous() # (N, V, L)
self._w_uk_packed = torch.ops._C.convert_weight_packed(w_uk_for_bmm)
self._w_uv_packed = torch.ops._C.convert_weight_packed(w_uv_for_bmm)
def do_kv_cache_update(
self,
kv_c_normed: torch.Tensor,
k_pe: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
kv_cache_dtype: str,
k_scale: torch.Tensor,
) -> None:
# Overrides the default (CUDA-only concat_and_cache_mla).
if kv_cache.numel() == 0:
return
assert kv_cache_dtype == "auto", (
"AMXMLAImpl only supports an unquantized (bf16) KV cache; fp8 "
"KV cache for CPU MLA is not yet implemented."
)
ops.amx_mla_concat_and_cache(
kv_c_normed, k_pe.squeeze(1), kv_cache, slot_mapping.flatten()
)
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
# q arrives already absorbed (tensor or (ql_nope, q_pe) tuple) --
# MLAAttention.forward_impl does the Q-absorption bmm generically
# before calling forward_mqa, using layer.W_UK_T. De-absorption is
# likewise done generically afterwards via layer._v_up_proj. Nothing
# left for this impl to do beyond invoking the decode kernel.
if isinstance(q, tuple):
q = torch.cat(q, dim=-1)
assert attn_metadata.decode is not None
num_tokens = q.shape[0]
kv_cache_flat = kv_c_and_k_pe_cache.view(-1, 1, self.head_size)
v_buffer = kv_cache_flat[..., : self.kv_lora_rank]
seq_lens = attn_metadata.decode.seq_lens_i64 # type: ignore[attr-defined]
req_to_token = attn_metadata.decode.req_to_token # type: ignore[attr-defined]
req_pool_indices = attn_metadata.decode.req_pool_indices # type: ignore[attr-defined]
num_kv_splits = attn_metadata.decode.num_kv_splits # type: ignore[attr-defined]
o = torch.zeros(
num_tokens,
self.num_heads,
self.kv_lora_rank,
dtype=q.dtype,
device=q.device,
)
attn_logits = torch.zeros(
num_tokens,
self.num_heads,
num_kv_splits,
self.kv_lora_rank + 1,
dtype=torch.float32,
device=q.device,
)
ops.cpu_mla_decode(
q,
kv_cache_flat,
v_buffer,
o,
None,
None,
None, # loc: only meaningful when key/value are given; we
# already wrote the new K/V via do_kv_cache_update before this.
attn_logits,
req_to_token,
req_pool_indices,
seq_lens,
self.scale,
0.0,
False,
0,
None,
None,
)
return o, None
def forward_mha(
self,
q: torch.Tensor,
kv_c_normed: torch.Tensor,
k_pe: torch.Tensor,
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
k_scale: torch.Tensor,
output: torch.Tensor,
output_scale: torch.Tensor | None = None,
) -> None:
assert output_scale is None, (
"AMXMLAImpl.forward_mha does not support fused output quantization"
)
prefill = attn_metadata.prefill
assert prefill is not None
assert self._w_uk_packed is not None and self._w_uv_packed is not None
num_tokens = q.shape[0]
num_heads = self.num_heads
q_nope, q_pe = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
# Absorb: (N, B, P) x (N, L, P)^T -> (N, B, L)
# bmm_cpu tolerates non-contiguous mat1/out as long as their last dim
# is contiguous, so q_nope's transpose and ql_nope's transposed view
# can be passed directly -- no copy needed for either.
q_nope_t = q_nope.transpose(0, 1)
ql_nope = torch.empty(
num_tokens, num_heads, self.kv_lora_rank, dtype=q.dtype, device=q.device
)
ops.bmm_cpu(
ql_nope.transpose(0, 1), q_nope_t, self._w_uk_packed, True, self._w_scale
)
mqa_q = torch.cat([ql_nope, q_pe], dim=-1)
kv_cache_flat = kv_c_and_k_pe_cache.view(-1, 1, self.head_size)
v_buffer = kv_cache_flat[..., : self.kv_lora_rank]
req_to_token = prefill.req_to_token # type: ignore[attr-defined]
req_pool_indices = prefill.req_pool_indices # type: ignore[attr-defined]
seq_lens = prefill.cpu_seq_lens # type: ignore[attr-defined]
extend_seq_lens = prefill.extend_seq_lens # type: ignore[attr-defined]
extend_start_loc = prefill.extend_start_loc # type: ignore[attr-defined]
max_len_extend = prefill.max_len_extend # type: ignore[attr-defined]
# k_extend/v_extend: the new tokens' own latent K/V, aliased in one
# 576-wide buffer (v_extend is a view of k_extend's first
# kv_lora_rank columns) so the kernel can gather both from one read,
# mirroring the cache's own layout.
k_extend = torch.cat(
[kv_c_normed, k_pe.reshape(num_tokens, self.qk_rope_head_dim)], dim=-1
).unsqueeze(1)
v_extend = k_extend[..., : self.kv_lora_rank]
attn_out = torch.empty(
num_tokens, num_heads, self.kv_lora_rank, dtype=q.dtype, device=q.device
)
ops.cpu_mla_extend(
mqa_q,
k_extend,
v_extend,
attn_out,
kv_cache_flat,
v_buffer,
req_to_token,
req_pool_indices,
seq_lens,
extend_seq_lens,
extend_start_loc,
max_len_extend,
self.scale,
0.0,
False,
0,
None,
None,
None,
)
# De-absorb directly into `output` (view, no extra copy on either side):
# (N, B, L) x (N, V, L)^T -> (N, B, V)
attn_out_t = attn_out.transpose(0, 1)
output_view = output.view(num_tokens, num_heads, self.v_head_dim).transpose(
0, 1
)
ops.bmm_cpu(output_view, attn_out_t, self._w_uv_packed, True, self._w_scale)
@@ -1,232 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Any
import torch
from vllm.model_executor.warmup.jit_warmup import kernel_launcher, zip_inputs
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
LaunchSpec,
TritonWarmupTensor,
VllmTritonJitKernel,
triton_scalar_specialization_rep,
)
from vllm.transformers_utils.deepseek_v4_utils import get_compress_ratios
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import cdiv
_DSPARK_SWA_INDEX_ALIGNMENT = 64
def get_dspark_swa_index_width(
window_size: int,
num_speculative_tokens: int,
) -> int:
"""Return the padded width of non-causal DSpark SWA indices."""
width = max(int(window_size), 0) + max(int(num_speculative_tokens), 0)
return cdiv(width, _DSPARK_SWA_INDEX_ALIGNMENT) * _DSPARK_SWA_INDEX_ALIGNMENT
class CompressedSlotMappingKernel(
VllmTritonJitKernel["CompressedSlotMappingKernel.CompileKey"]
):
TRITON_BLOCK_SIZE = 1024
@dataclass(frozen=True)
class CompileKey:
compress_ratio: int
triton_block_size: int
block_size: int
dcp_world_size: int
cp_interleave: int
@staticmethod
@triton.jit(do_not_specialize=["block_table_stride"])
def kernel(
# [num_tokens]
compressed_slot_mapping_ptr,
# [num_tokens] the tokens' own slots
slot_mapping_ptr,
# [num_reqs + 1]
query_start_loc_ptr,
# [num_reqs]
seq_lens_ptr,
# [num_reqs, max_num_blocks]
block_table_ptr,
block_table_stride,
block_size,
dcp_world_size,
cp_interleave,
COMPRESS_RATIO: tl.constexpr,
PAD_ID: tl.constexpr,
TRITON_BLOCK_SIZE: tl.constexpr,
):
batch_idx = tl.program_id(0)
query_start = tl.load(query_start_loc_ptr + batch_idx)
query_end = tl.load(query_start_loc_ptr + batch_idx + 1)
query_len = query_end - query_start
seq_len = tl.load(seq_lens_ptr + batch_idx)
start_pos = seq_len - query_len
for i in range(0, query_len, TRITON_BLOCK_SIZE):
offset = i + tl.arange(0, TRITON_BLOCK_SIZE)
mask = offset < query_len
pos = start_pos + i + tl.arange(0, TRITON_BLOCK_SIZE)
# A replayed token has a PAD slot (SWA bounded replay: its KV is
# cached already); its compressed KV is cached too, so PAD here.
slot = tl.load(
slot_mapping_ptr + query_start + offset, mask=mask, other=PAD_ID
)
is_valid = ((pos + 1) % COMPRESS_RATIO == 0) & (slot != PAD_ID)
# Under DCP a PAD slot also marks tokens owned by other ranks; the
# interleave is a multiple of COMPRESS_RATIO, so a state lives
# entirely on the rank owning its last token.
local_pos = (
pos // (cp_interleave * dcp_world_size) * cp_interleave
+ pos % cp_interleave
)
pos_after_compress = local_pos // COMPRESS_RATIO
block_ids = pos_after_compress // block_size
block_numbers = tl.load(
block_table_ptr + batch_idx * block_table_stride + block_ids,
mask=mask & is_valid,
)
slot_ids = block_numbers.to(tl.int64) * block_size + (
pos_after_compress % block_size
)
# NOTE
slot_ids = tl.where(is_valid, slot_ids, PAD_ID)
tl.store(
compressed_slot_mapping_ptr + query_start + offset, slot_ids, mask=mask
)
def dispatch( # type: ignore[override]
self,
*,
compress_ratio: int,
block_size: int,
dcp_world_size: int,
cp_interleave: int,
) -> CompileKey:
return self.CompileKey(
compress_ratio=compress_ratio,
triton_block_size=self.TRITON_BLOCK_SIZE,
block_size=triton_scalar_specialization_rep(block_size),
dcp_world_size=triton_scalar_specialization_rep(dcp_world_size),
cp_interleave=triton_scalar_specialization_rep(cp_interleave),
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
hf_text_config = vllm_config.model_config.hf_text_config
configured_ratios = (
*get_compress_ratios(hf_text_config),
getattr(hf_text_config, "index_kpool", 1) or 1,
)
compress_ratios = tuple(
dict.fromkeys(int(ratio) for ratio in configured_ratios if int(ratio) > 1)
)
if not compress_ratios:
return []
parallel_config = vllm_config.parallel_config
return self._trace_dispatch(self.dispatch)(
zip_inputs(
*(
dict(
compress_ratio=ratio,
block_size=vllm_config.cache_config.block_size // ratio,
dcp_world_size=parallel_config.decode_context_parallel_size,
cp_interleave=parallel_config.cp_kv_cache_interleave_size,
)
for ratio in compress_ratios
)
)
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
int32_ptr = TritonWarmupTensor(torch.int32)
return dict(
compressed_slot_mapping=TritonWarmupTensor(torch.int64),
slot_mapping=TritonWarmupTensor(torch.int64),
query_start_loc=int32_ptr,
seq_lens=int32_ptr,
block_table=int32_ptr,
block_size=compile_key.block_size,
compress_ratio=compile_key.compress_ratio,
dcp_world_size=compile_key.dcp_world_size,
cp_interleave=compile_key.cp_interleave,
)
@kernel_launcher
def __call__(
self,
compressed_slot_mapping: torch.Tensor,
slot_mapping: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
compress_ratio: int,
dcp_world_size: int,
cp_interleave: int,
) -> LaunchSpec:
return (block_table.shape[0],), dict(
block_table_stride=block_table.stride(0),
COMPRESS_RATIO=compress_ratio,
PAD_ID=-1,
TRITON_BLOCK_SIZE=self.TRITON_BLOCK_SIZE,
)
def get_compressed_slot_mapping(
num_tokens: int,
slot_mapping: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
compress_ratio: int,
out: torch.Tensor | None = None,
dcp_world_size: int = 1,
cp_interleave: int = 1,
) -> torch.Tensor:
"""Slot mapping for writing the compressed states of ``num_tokens`` tokens.
Every ``compress_ratio`` tokens share one compressed state, written by the
last of them: that token maps to the state's slot, the others to PAD. A
token whose own ``slot_mapping`` entry is PAD maps to PAD too: SWA bounded
replay recomputes tokens whose KV is cached already, and their compressed
states must not be rewritten either.
"""
if out is not None:
# Guard: for padded / invalid sequences.
# Negative positions produce bogus block indices that lead to illegal memory
# accesses inside the block_table load.
# NOTE: Fill -1 to the whole tensor, not just the first `num_tokens`.
out.fill_(-1)
compressed_slot_mapping = out[:num_tokens]
else:
compressed_slot_mapping = torch.full(
(num_tokens,), -1, dtype=torch.int64, device=query_start_loc.device
)
_COMPRESSED_SLOT_MAPPING_KERNEL(
compressed_slot_mapping,
slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size,
compress_ratio,
dcp_world_size,
cp_interleave,
)
return compressed_slot_mapping
_COMPRESSED_SLOT_MAPPING_KERNEL = CompressedSlotMappingKernel()
-220
View File
@@ -1,220 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU MLA backend.
This is a *reference-quality* MLA backend for the CPU platform. It is
intended to make DeepSeek-V2/V3 style models runnable on CPU (for
functional verification, tiny-model smoke tests and CI), not to be
performant. The prefill path is a plain PyTorch SDPA and the decode
path forwards to the existing CPU decode kernel
`torch.ops._C.mla_decode_kvcache` (see csrc/cpu/mla_decode.cpp).
Key design points:
* We inherit the shared MLA scaffolding (`MLACommonBackend`,
`MLACommonImpl`, `MLACommonMetadata`) so that the same
``forward_impl`` in ``MLAAttention`` orchestrates weight-absorbed
decode (MQA) and non-absorbed prefill (MHA) for us.
* The parent ``MLACommonImpl.__init__`` tries to pick a GPU prefill
kernel (flash_attn / flashinfer / cudnn / trtllm) and raises when
none of them are available. On CPU none of them apply, so we
bypass that logic and set the attributes ourselves.
* Chunked prefill and prefix caching are disabled by the CPU platform
when ``use_mla`` is set.
* The CPU decode kernel only supports ``head_dim=576``,
``v_head_dim=512`` and ``block_size=16`` today; the platform layer
forces ``block_size=16`` for MLA models.
"""
from typing import ClassVar
import torch
from vllm import _custom_ops as ops
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonImpl,
MLACommonMetadata,
)
from vllm.v1.attention.backend import (
AttentionLayer,
AttentionType,
MultipleOf,
)
logger = init_logger(__name__)
class CPUMLABackend(MLACommonBackend):
"""Attention backend descriptor for CPU MLA."""
supported_dtypes: ClassVar[list[torch.dtype]] = [
torch.float16,
torch.bfloat16,
torch.float32,
]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto"]
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
# DeepSeek-V2/V3 latent cache size = kv_lora_rank(512)+rope(64)=576.
# The current CPU decode kernel only compiles for this size.
return [576]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [16]
@classmethod
def supports_block_size(cls, block_size: int | None) -> bool:
return block_size is None or block_size == 16
@staticmethod
def get_name() -> str:
return "CPU_MLA"
@staticmethod
def get_impl_cls() -> type["CPUMLAImpl"]:
return CPUMLAImpl
class CPUMLAImpl(MLACommonImpl[MLACommonMetadata]):
"""CPU implementation of MLA attention.
See module docstring for the overall design. This class only
overrides the parts of the parent that would otherwise pull in
CUDA-only dependencies.
"""
# Decode always returns the softmax lse if the parent needs it, but
# CPU decode currently only produces the output tensor. Report False
# so DCP / cross-batch reductions are not requested from us.
can_return_lse_for_decode: bool = False
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA-specific arguments (forwarded from `MLAAttention`).
**mla_args,
) -> None:
# NOTE: We deliberately skip ``MLACommonImpl.__init__`` because it
# tries to pick a GPU prefill kernel and raises on CPU. Instead we
# replicate the attribute setup here and then wire our own hooks.
if kv_sharing_target_layer_name is not None:
raise NotImplementedError("KV sharing is not supported for MLA")
if attn_type != AttentionType.DECODER:
raise NotImplementedError("CPU MLA only supports decoder self-attention.")
unsupported = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported):
raise NotImplementedError(
"CPU MLA does not support alibi_slopes / sliding_window / "
"logits_soft_cap."
)
self.num_heads = num_heads
self.head_size = head_size
self.scale = float(scale)
self.num_kv_heads = num_kv_heads
self.kv_cache_dtype = kv_cache_dtype
self.q_lora_rank = mla_args["q_lora_rank"]
self.kv_lora_rank = mla_args["kv_lora_rank"]
self.qk_nope_head_dim = mla_args["qk_nope_head_dim"]
self.qk_rope_head_dim = mla_args["qk_rope_head_dim"]
self.qk_head_dim = mla_args["qk_head_dim"]
self.v_head_dim = mla_args["v_head_dim"]
self.kv_b_proj = mla_args["kv_b_proj"]
self.indexer = mla_args.get("indexer")
self.q_pad_num_heads = mla_args.get("q_pad_num_heads")
self.supports_quant_query_input = False
# Never take the flashinfer specialisation of ``_concat_k_nope_k_pe``.
self._use_flashinfer_concat_mla_k = False
# We do not need V padding since our SDPA prefill takes k / v with
# matching head dims.
self._pad_v = False
# Distributed / context-parallel bookkeeping expected by the parent.
self.dcp_world_size = 1
self.cp_kv_cache_interleave_size = 1
# ------------------------------------------------------------------
# Decode (MQA)
# ------------------------------------------------------------------
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert attn_metadata.decode is not None
# The parent hands us either a tuple (q_nope, q_pe) or a single
# tensor already concatenated. CPU decode kernel wants a single
# (bs, num_heads, head_dim=kv_lora_rank+rope) contiguous tensor.
if isinstance(q, tuple):
q = torch.cat(q, dim=-1)
q = q.contiguous()
bs, num_heads, _ = q.shape
out = torch.zeros(
bs, num_heads, self.kv_lora_rank, dtype=q.dtype, device=q.device
)
# The CPU kernel is templated on int32 block_tables / seq_lens.
block_table = attn_metadata.decode.block_table.to(torch.int32)
seq_lens = attn_metadata.decode.seq_lens.to(torch.int32)
ops.mla_decode_kvcache_cpu(
out,
q,
kv_c_and_k_pe_cache,
self.scale,
block_table,
seq_lens,
)
# The parent only consumes the LSE when DCP is active, which we
# disable, so returning None here is safe.
return out, None
# ------------------------------------------------------------------
# KV cache write
# ------------------------------------------------------------------
def do_kv_cache_update(
self,
kv_c_normed: torch.Tensor,
k_pe: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
kv_cache_dtype: str,
k_scale: torch.Tensor,
) -> None:
if kv_cache.numel() == 0:
return
k_pe_sq = k_pe.squeeze(1)
kv_lora_rank = kv_c_normed.shape[-1]
pe_dim = k_pe_sq.shape[-1]
flat = kv_cache.view(-1, kv_lora_rank + pe_dim)
slots = slot_mapping.flatten().to(torch.long)
# Only write valid slots. Padding slots are set to -1 by the
# scheduler and must be skipped.
valid_mask = slots >= 0
if not valid_mask.all().item():
slots = slots[valid_mask]
kv_c_normed = kv_c_normed[valid_mask]
k_pe_sq = k_pe_sq[valid_mask]
target_dtype = flat.dtype
flat[slots, :kv_lora_rank] = kv_c_normed.to(target_dtype)
flat[slots, kv_lora_rank:] = k_pe_sq.view(-1, pe_dim).to(target_dtype)
@@ -1,286 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
from typing import ClassVar
import torch
import vllm._custom_ops as ops
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
)
from vllm.platforms.interface import DeviceCapability
from vllm.utils.platform_utils import num_compute_units
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
AttentionType,
MultipleOf,
)
logger = init_logger(__name__)
class CutlassMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
# enable full CUDA Graph support for decode-only capture
_cudagraph_support: ClassVar[AttentionCGSupport] = (
AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
)
class CutlassMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [128]
@staticmethod
def get_name() -> str:
return "CUTLASS_MLA"
@staticmethod
def get_impl_cls() -> type["CutlassMLAImpl"]:
return CutlassMLAImpl
@staticmethod
def get_builder_cls() -> type["CutlassMLAMetadataBuilder"]:
return CutlassMLAMetadataBuilder
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 10
class SM100Workspace:
def __init__(self, initial_workspace_size):
self._workspace_buf = torch.empty(
initial_workspace_size, device="cuda", dtype=torch.uint8
)
self._block_size = 128 # Forced to 128
# Pre-compute sm_count to avoid recomputing it. Use device 0 as a proxy
# (assumes all devices are similar)
self._sm_count = num_compute_units(0)
def get_buf(self):
return self._workspace_buf
def ensure_size(self, attn_metadata: MLACommonMetadata, num_kv_splits: int):
batch_size = attn_metadata.num_reqs
max_seq_len = attn_metadata.max_query_len
workspace_size = ops.sm100_cutlass_mla_get_workspace_size(
max_seq_len * self._block_size,
batch_size,
self._sm_count,
num_kv_splits=num_kv_splits,
)
if self._workspace_buf.shape[0] < workspace_size:
self._workspace_buf.resize_(workspace_size)
g_sm100_workspace = SM100Workspace(128 * 1024 * 1024) # 128MB
MAX_HEADS = 128
class CutlassMLAImpl(MLACommonImpl[MLACommonMetadata]):
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
q_pad_num_heads=MAX_HEADS,
**mla_args,
)
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"CutlassMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"CutlassMLAImpl"
)
# TODO: Currently, num_kv_splits is limited to 16 to avoid hanging
# issues. In case the code hangs, use:
# FORCE_NUM_KV_SPLITS=1
force_num_kv_splits = os.environ.get("FORCE_NUM_KV_SPLITS", None)
if force_num_kv_splits:
logger.debug_once("Forcing num_kv_splits to %d", int(force_num_kv_splits))
self._num_kv_splits = int(force_num_kv_splits)
else:
self._num_kv_splits = -1 # => Auto-detect
# Share workspace buffer across all executions
self._workspace = g_sm100_workspace
def _sm100_cutlass_mla_decode(
self,
q_nope: torch.Tensor,
q_pe: torch.Tensor,
kv_c_and_k_pe_cache: torch.Tensor,
seq_lens: torch.Tensor,
page_table: torch.Tensor,
workspace: torch.Tensor,
sm_scale: float,
num_kv_splits: int,
) -> tuple[torch.Tensor, torch.Tensor]:
assert q_nope.ndim == 3, f"q_nope must be a 3D tensor, but got {q_nope.ndim}"
assert q_pe.ndim == 3, f"q_pe must be a 3D tensor, but got {q_pe.ndim}"
assert kv_c_and_k_pe_cache.ndim == 3, (
"kv_c_and_k_pe_cache must be a 3D tensor, but got {}".format(
kv_c_and_k_pe_cache.ndim
)
)
B_q, H, D_q_nope = q_nope.shape
B_q_2, H_2, D_q_pe = q_pe.shape
assert (B_q == B_q_2) and (H == H_2)
_, PAGE_SIZE, D_ckv = kv_c_and_k_pe_cache.shape
D_latent = 512
D_rope = 64
assert D_q_nope == D_latent
assert D_q_pe == D_rope
assert D_ckv == D_latent + D_rope
MAX_HEADS = 128
assert H <= MAX_HEADS, f"H must be <= {MAX_HEADS}, but got {H}"
assert len(page_table.shape) == 2
B_block_table, block_num = page_table.shape
assert B_block_table == B_q
assert block_num > 0, f"block num must be greater than 0, got {block_num}"
assert block_num % (128 / PAGE_SIZE) == 0
assert q_nope.dtype in (torch.float16, torch.bfloat16, torch.float8_e4m3fn), (
f"q_nope.dtype needs to be fp16 or bf16 or e4m3 but got {q_nope.dtype}."
)
assert q_nope.dtype == q_pe.dtype == kv_c_and_k_pe_cache.dtype
assert seq_lens.dtype == torch.int32, (
f"seq_lens.dtype needs to be int32 but got {seq_lens.dtype}."
)
assert page_table.dtype == torch.int32, (
f"page_table.dtype needs to be int32 but got {page_table.dtype}."
)
dtype = (
torch.bfloat16
if is_quantized_kv_cache(self.kv_cache_dtype)
else q_nope.dtype
)
out = q_nope.new_empty((B_q, MAX_HEADS, D_latent), dtype=dtype)
lse = (
torch.empty((B_q, MAX_HEADS), dtype=torch.float32, device=q_nope.device)
if self.need_to_return_lse_for_decode
else torch.Tensor()
)
ops.sm100_cutlass_mla_decode(
out,
lse,
q_nope,
q_pe,
kv_c_and_k_pe_cache,
seq_lens,
page_table,
workspace,
sm_scale,
num_kv_splits,
)
if H < MAX_HEADS:
# Extract the subsets of the outputs
lse = lse[:, :H] if self.need_to_return_lse_for_decode else lse
out = out[:, :H]
return out, lse
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
if layer._q_scale_float != 1.0 or layer._k_scale_float != 1.0:
raise NotImplementedError(
"CutlassMLAImpl does not support scaling for q and kv_latent yet"
)
if type(q) is tuple:
q_nope, q_pe = q
else:
q_nope, q_pe = torch.split(
q, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
)
# Adjust workspace size (if necessary)
self._workspace.ensure_size(attn_metadata, self._num_kv_splits)
# Run MLA
o, lse = self._sm100_cutlass_mla_decode(
q_nope,
q_pe,
kv_c_and_k_pe_cache,
attn_metadata.decode.seq_lens,
attn_metadata.decode.block_table,
self._workspace.get_buf(),
self.scale,
self._num_kv_splits,
)
return o, (lse if self.need_to_return_lse_for_decode else None)
@@ -1,498 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import ClassVar
import torch
import vllm.envs as envs
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonDecodeMetadata,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
QueryLenSupport,
)
from vllm.platforms.interface import DeviceCapability
from vllm.utils.math_utils import round_up
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
AttentionType,
MultipleOf,
)
from vllm.v1.attention.backends.fa_utils import (
flash_attn_supports_mla,
flash_attn_varlen_func,
get_flash_attn_version,
get_scheduler_metadata,
)
from vllm.v1.kv_cache_interface import AttentionSpec
logger = init_logger(__name__)
class FlashAttnMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(16)]
@staticmethod
def get_name() -> str:
return "FLASH_ATTN_MLA"
@classmethod
def supports_batch_invariance(cls) -> bool:
return True
@staticmethod
def get_builder_cls() -> type["FlashAttnMLAMetadataBuilder"]:
return FlashAttnMLAMetadataBuilder
@staticmethod
def get_impl_cls() -> type["FlashAttnMLAImpl"]:
return FlashAttnMLAImpl
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 9
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
if not flash_attn_supports_mla():
return "FlashAttention MLA not supported on this device"
return None
class XPUFlashAttnMLABackend(FlashAttnMLABackend):
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(64)]
@staticmethod
def get_builder_cls() -> type["XPUFlashAttnMLAMetadataBuilder"]:
return XPUFlashAttnMLAMetadataBuilder
@staticmethod
def get_impl_cls() -> type["XPUFlashAttnMLAImpl"]:
return XPUFlashAttnMLAImpl
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return True
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [576]
@dataclass
class FlashAttnMLADecodeMetadata(MLACommonDecodeMetadata):
query_start_loc: torch.Tensor
max_query_len: int
max_seq_len: int
scheduler_metadata: torch.Tensor | None = None
max_num_splits: int = 0
@dataclass
class FlashAttnMLAMetadata(MLACommonMetadata[FlashAttnMLADecodeMetadata]):
pass
class FlashAttnMLAMetadataBuilder(MLACommonMetadataBuilder[FlashAttnMLAMetadata]):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.VARLEN
reorder_batch_threshold: int = 512 # process small prefills with decode pathway
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
):
interleave_size = vllm_config.parallel_config.cp_kv_cache_interleave_size
super().__init__(
kv_cache_spec,
layer_names,
vllm_config,
device,
FlashAttnMLAMetadata,
supports_dcp_with_varlen=(interleave_size == 1),
)
self.max_num_splits = 0 # No upper bound on the number of splits.
self.fa_aot_schedule = get_flash_attn_version() == 3
self.use_full_cuda_graph = (
self.compilation_config.cudagraph_mode.has_full_cudagraphs()
)
self.max_cudagraph_size = self.compilation_config.max_cudagraph_capture_size
if self.use_full_cuda_graph and self.fa_aot_schedule:
# FA3 scheduler_metadata size: 1 + round_up(batch_size, 4) * 4
# The +1 is for the tile_count_semaphore (synchronization).
# The 4 slots per batch element (num_prepare_batch_vectors) are:
# prepare_varlen + dynamic_split + sort_batches + head_swizzle
# See: https://github.com/vllm-project/flash-attention/blob/5824e6e/hopper/flash_api.cpp#L664-L671 # noqa: E501
max_batch_size = max(
vllm_config.scheduler_config.max_num_seqs,
self.max_cudagraph_size or 0,
)
self.scheduler_metadata = torch.zeros(
1 + round_up(max_batch_size, 4) * 4,
dtype=torch.int32,
device=self.device,
)
# When using cuda graph, we need to set the upper bound of the
# number of splits so that large enough intermediate buffers are
# pre-allocated during capture.
self.max_num_splits = (
vllm_config.attention_config.flash_attn_max_num_splits_for_cuda_graph
)
if envs.VLLM_BATCH_INVARIANT:
self.max_num_splits = 1
def _schedule_decode(
self,
num_reqs,
cu_query_lens,
max_query_len,
seqlens,
max_seq_len,
causal,
max_num_splits,
):
if self.fa_aot_schedule:
return get_scheduler_metadata(
batch_size=num_reqs,
max_seqlen_q=max_query_len,
max_seqlen_k=max_seq_len,
num_heads_q=self.num_heads * self.dcp_world_size,
num_heads_kv=1,
headdim=self.mla_dims.qk_rope_head_dim,
cache_seqlens=seqlens,
qkv_dtype=self.kv_cache_spec.dtype,
headdim_v=self.mla_dims.kv_lora_rank,
page_size=self.page_size,
cu_seqlens_q=cu_query_lens,
causal=causal,
num_splits=max_num_splits,
)
return None
def _build_decode(
self,
block_table_tensor: torch.Tensor,
seq_lens_device: torch.Tensor,
max_seq_len: int,
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
max_query_len: int,
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> FlashAttnMLADecodeMetadata:
# Measured, not the promised bound: _schedule_decode asserts metadata size
# against a persistent buffer.
query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1]
max_query_len = query_lens_cpu.max().item()
# For Flash Attention MLA + full cudagraph
max_num_splits = 0
if (
self.use_full_cuda_graph
and self.max_cudagraph_size is not None
and num_decode_tokens <= self.max_cudagraph_size
):
# NOTE(woosuk): Setting num_splits > 1 may increase the memory
# usage, because the intermediate buffers of size [num_splits,
# num_heads, num_tokens, head_size] are allocated. Therefore,
# we only set num_splits when using cuda graphs.
max_num_splits = self.max_num_splits
if envs.VLLM_BATCH_INVARIANT:
max_num_splits = 1
scheduler_metadata = self._schedule_decode(
num_reqs=seq_lens_device.shape[0],
cu_query_lens=query_start_loc_device,
max_query_len=max_query_len,
seqlens=seq_lens_device,
max_seq_len=max_seq_len,
causal=True,
max_num_splits=max_num_splits,
)
if self.use_full_cuda_graph and scheduler_metadata is not None:
n = scheduler_metadata.shape[0]
# Ensure the persistent buffer is large enough
assert n <= self.scheduler_metadata.shape[0], (
f"Scheduler metadata size {n} exceeds buffer size "
f"{self.scheduler_metadata.shape[0]}"
)
self.scheduler_metadata[:n] = scheduler_metadata
# NOTE(woosuk): We should zero out the rest of the scheduler
# metadata to guarantee the correctness. Otherwise, some thread
# blocks may use the invalid scheduler metadata and overwrite the
# output buffer.
self.scheduler_metadata[n:] = 0
scheduler_metadata = self.scheduler_metadata[:n]
metadata = FlashAttnMLADecodeMetadata(
block_table=block_table_tensor,
seq_lens=seq_lens_device,
query_start_loc=query_start_loc_device,
max_query_len=max_query_len,
max_seq_len=max_seq_len,
scheduler_metadata=scheduler_metadata,
max_num_splits=max_num_splits,
dcp_tot_seq_lens=dcp_tot_seq_lens_device,
)
return metadata
class XPUFlashAttnMLAMetadataBuilder(FlashAttnMLAMetadataBuilder):
_cudagraph_support: ClassVar[AttentionCGSupport] = (
AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
)
query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.SINGLE_ONLY
reorder_batch_threshold: int = 1
def _schedule_decode(
self,
num_reqs,
cu_query_lens,
max_query_len,
seqlens,
max_seq_len,
causal,
max_num_splits,
):
# XPU uses the FA2 varlen interface, which has no AOT scheduler metadata.
return None
class FlashAttnMLAImpl(MLACommonImpl[FlashAttnMLAMetadata]):
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
assert flash_attn_supports_mla(), "FlashAttnMLA is not supported on this device"
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"FlashAttnMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"FlashAttnMLAImpl"
)
if is_quantized_kv_cache(self.kv_cache_dtype):
raise NotImplementedError(
"FlashAttnMLA V1 with FP8 KV cache not yet supported"
)
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashAttnMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
if type(q) is tuple:
q_nope, q_pe = q
else:
q_nope, q_pe = torch.split(
q, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
)
if is_quantized_kv_cache(self.kv_cache_dtype):
raise NotImplementedError("FP8 FlashAttention MLA not yet supported")
kv_c_cache = kv_c_and_k_pe_cache[..., : self.kv_lora_rank]
k_pe_cache = kv_c_and_k_pe_cache[..., self.kv_lora_rank :]
# NOTE(matt): During CUDA graph capture, max_query_len can be 0, but the
# kernel uses this to calculate grid dimensions. Ensure it's at least 1
# to prevent invalid grid configuration during graph capture.
max_seqlen_q = max(attn_metadata.decode.max_query_len, 1)
attn_out = flash_attn_varlen_func(
q=q_pe,
k=k_pe_cache.unsqueeze(-2), # Add head dim of 1
v=kv_c_cache.unsqueeze(-2), # Add head dim of 1
q_v=q_nope,
max_seqlen_q=max_seqlen_q,
cu_seqlens_q=attn_metadata.decode.query_start_loc,
max_seqlen_k=attn_metadata.decode.max_seq_len,
seqused_k=attn_metadata.decode.seq_lens,
block_table=attn_metadata.decode.block_table,
softmax_scale=self.scale,
causal=True,
return_softmax_lse=self.need_to_return_lse_for_decode,
fa_version=3, # only version 3 is supported
scheduler_metadata=attn_metadata.decode.scheduler_metadata,
num_splits=attn_metadata.decode.max_num_splits,
cp_world_size=self.dcp_world_size,
cp_rank=self.dcp_rank,
cp_tot_seqused_k=attn_metadata.decode.dcp_tot_seq_lens,
)
if self.need_to_return_lse_for_decode:
o, lse = attn_out
# FA returns LSE in shape [ H, B ] but DCP wants [ B, H ]
return o, lse.transpose(0, 1) # [ H, B ] -> [ B, H ]
else:
o = attn_out
return o, None
class XPUFlashAttnMLAImpl(FlashAttnMLAImpl):
supports_dcp: bool = False
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
if self.dcp_world_size > 1:
raise NotImplementedError(
"FlashAttnMLA on XPU does not support decode context parallelism"
)
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashAttnMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
num_decodes = attn_metadata.num_decodes
decode_cu_seqlens_q = attn_metadata.query_start_loc[: num_decodes + 1]
cache = kv_c_and_k_pe_cache
if cache.dim() == 3:
cache = cache.unsqueeze(-2)
assert cache.dim() == 4 and cache.size(-2) == 1, (
"kv_c_and_k_pe_cache must be [num_blocks, block_size, "
"(num_heads_kv=1)?, kv_lora_rank+qk_rope_head_dim]"
)
if type(q) is tuple: # noqa: SIM108
q_in = torch.cat(q, dim=-1)
else:
q_in = q
if not q_in.is_contiguous():
q_in = q_in.contiguous()
attn_out = flash_attn_varlen_func(
q_in,
cache,
cache.narrow(-1, 0, self.kv_lora_rank),
max_seqlen_q=1,
cu_seqlens_q=decode_cu_seqlens_q,
max_seqlen_k=attn_metadata.decode.max_seq_len,
seqused_k=attn_metadata.decode.seq_lens,
block_table=attn_metadata.decode.block_table,
softmax_scale=self.scale,
# Single-token paged decode has no future KV to mask; seqused_k
# already restricts each request to its valid KV prefix.
causal=False,
fa_version=2,
return_softmax_lse=self.need_to_return_lse_for_decode,
)
if self.need_to_return_lse_for_decode:
o, lse = attn_out
# FA returns LSE in shape [ H, B ] but DCP wants [ B, H ]
return o, lse.transpose(0, 1) # [ H, B ] -> [ B, H ]
return attn_out, None
@@ -1,422 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import math
from dataclasses import dataclass
from functools import cache
from typing import Any, ClassVar
import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
SparseMLACommonMetadata,
SparseMLACommonMetadataBuilder,
)
from vllm.platforms.interface import DeviceCapability
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionLayer,
MLAAttentionImpl,
MultipleOf,
)
from vllm.v1.attention.backends.fa_utils import flash_attn_supports_mla
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseImpl,
FlashInferMLASparseTRTLLMBackend,
FlashInferMLASparseTRTLLMMetadataBuilder,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
align_blocks_to_rows,
flat_kv_row_view,
)
from vllm.v1.attention.ops.metadata import compute_token_to_req_indices
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.vllm_flash_attn.flash_attn_interface import flash_attn_varlen_func
class FlashAttnMLASparseBackend(AttentionBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(64)]
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
return align_blocks_to_rows(spec)
@staticmethod
def get_name() -> str:
return "FLASH_ATTN_MLA_SPARSE"
@staticmethod
def get_builder_cls() -> type["FlashAttnMLASparseMetadataBuilder"]:
return FlashAttnMLASparseMetadataBuilder
@staticmethod
def get_impl_cls() -> type[MLAAttentionImpl[Any]]:
return FlashAttnMLASparseImpl
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return []
@classmethod
def is_mla(cls) -> bool:
return True
@classmethod
def is_sparse(cls) -> bool:
return True
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 9
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
if kv_cache_dtype not in (None, "auto", "float16", "bfloat16"):
return (
"FlashAttention MLA Sparse currently supports only FP16/BF16 KV cache"
)
if not flash_attn_supports_mla():
return "FlashAttention MLA not supported on this device"
from vllm.config import get_current_vllm_config_or_none
vllm_config = get_current_vllm_config_or_none()
if vllm_config is not None and vllm_config.model_config is not None:
if vllm_config.parallel_config.decode_context_parallel_size > 1:
return "FlashAttention MLA Sparse does not support DCP for now"
hf_text_config = vllm_config.model_config.hf_text_config
if not hasattr(hf_text_config, "index_topk"):
return "FlashAttention MLA Sparse requires model with index_topk"
return None
@dataclass
class FlashAttnMLASparseMetadata(SparseMLACommonMetadata):
pass
class FlashAttnMLASparseMetadataBuilder(
SparseMLACommonMetadataBuilder[FlashAttnMLASparseMetadata]
):
metadata_cls = FlashAttnMLASparseMetadata
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
num_q_heads = self.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
threshold = {16: 128, 32: 128, 64: 256, 128: 256}.get(num_q_heads, 256)
self._init_reorder_batch_threshold(threshold, supports_spec_as_decode=True)
self.supports_draft_decode_metadata_update = self.dcp_world_size == 1
def update_draft_decode_metadata(self, metadata: SparseMLACommonMetadata) -> None:
num_tokens = metadata.num_decode_tokens
if num_tokens == 0:
return
# Everything else is a view of runner buffers; the per-token request
# map is a builder buffer that build() filled for the captured batch.
compute_token_to_req_indices(
metadata.query_start_loc,
metadata.req_id_per_token,
num_tokens,
num_tokens,
)
class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
group_conversion_decode_only: ClassVar[bool] = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
topk_indices_buffer: torch.Tensor | None = None,
indexer: Any | None = None,
**mla_args: Any,
) -> None:
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"FlashAttnMLASparseImpl does not support alibi, sliding window, "
"or logits soft cap."
)
if kv_cache_dtype not in ("auto", "float16", "bfloat16"):
raise NotImplementedError(
"FlashAttnMLASparseImpl currently supports only FP16/BF16 KV cache."
)
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
indexer=indexer,
topk_indices_buffer=topk_indices_buffer,
**mla_args,
)
assert self.topk_indices_buffer is not None, (
"Indexer or topk_indices_buffer required for sparse MLA"
)
self.cu_seqlens_q_buffer = torch.arange(
self.topk_indices_buffer.shape[0] + 1,
dtype=torch.int32,
device=self.topk_indices_buffer.device,
)
self.supports_quant_query_input = False
def _forward_mqa_kernel(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_cache: torch.Tensor,
topk_indices: torch.Tensor,
valid_counts: torch.Tensor,
*,
layer: AttentionLayer,
block_size: int,
is_decode: bool,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if not isinstance(q, tuple):
raise NotImplementedError(
"FlashAttnMLASparseImpl expects split (q_nope, q_rope) input."
)
q_nope, q_rope = q
kv_rows, _ = flat_kv_row_view(kv_cache, block_size)
cu_seqlens_q = self.cu_seqlens_q_buffer[: q_rope.shape[0] + 1]
v_cache = kv_rows[:, : self.kv_lora_rank].unsqueeze(1).unsqueeze(1)
if self.qk_rope_head_dim == 0:
# FA3's QV path requires the 64-wide Q/K specialization. For NoPE
# MLA, zero Q preserves QV-only attention scores while providing a
# valid TMA shape.
_FA3_QV_HEAD_DIM = 64
q_rope = q_nope.new_zeros(*q_nope.shape[:-1], _FA3_QV_HEAD_DIM)
k_cache = v_cache[..., :_FA3_QV_HEAD_DIM]
else:
k_cache = kv_rows[:, self.kv_lora_rank :].unsqueeze(1).unsqueeze(1)
out = flash_attn_varlen_func(
q=q_rope,
k=k_cache,
v=v_cache,
q_v=q_nope,
max_seqlen_q=1,
cu_seqlens_q=cu_seqlens_q,
max_seqlen_k=topk_indices.shape[1],
seqused_k=valid_counts,
block_table=topk_indices,
softmax_scale=self.scale,
causal=True,
fa_version=3,
)
return out, None
def _fa4_cute_mla_available() -> str | None:
"""Reason the FA4 cute-DSL MLA entry point is unusable, or None."""
from vllm.vllm_flash_attn import flash_attn_interface as fa
if not fa.is_fa_version_supported(4):
return f"FA4 unavailable: {fa.fa_version_unsupported_reason(4)}"
try:
from vllm.vllm_flash_attn.cute.interface import _flash_attn_fwd # noqa: F401
except Exception as e: # cute-DSL / cutlass import chain
return f"FA4 cute-DSL entry point failed to import: {e!r}"
return None
class FlashAttnMLASparseFA4Backend(FlashInferMLASparseTRTLLMBackend):
"""FA4 for is_decode kernel calls; trtllm-gen for the rest."""
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
# The qv kernel asserts every descale is None: BF16 KV cache only.
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(64)]
@staticmethod
def get_name() -> str:
return "FLASH_ATTN_MLA_SPARSE_FA4"
@staticmethod
def get_builder_cls() -> type["FlashAttnMLASparseFA4MetadataBuilder"]:
return FlashAttnMLASparseFA4MetadataBuilder
@staticmethod
def get_impl_cls() -> type[MLAAttentionImpl[Any]]:
return FlashAttnMLASparseFA4Impl
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
# 512 latent + 64 RoPE; split back apart for the qv kernel.
return [576]
@classmethod
def supports_combination(cls, *args: Any, **kwargs: Any) -> str | None:
from vllm.config import get_current_vllm_config_or_none
from vllm.utils.flashinfer import has_flashinfer
if not has_flashinfer():
return "FA4 sparse MLA runs its prefill batches on FlashInfer's kernel"
if (reason := _fa4_cute_mla_available()) is not None:
return reason
vllm_config = get_current_vllm_config_or_none()
if vllm_config is None:
return None
if vllm_config.model_config is not None:
hf_config = vllm_config.model_config.hf_text_config
topk = getattr(hf_config, "index_topk", None)
# gather_kv_indices' last dim must be a whole number of n-tiles.
if topk is None or topk % 128 != 0:
return f"FA4 sparse MLA requires index_topk % 128 == 0, got {topk}"
dims = (
getattr(hf_config, "kv_lora_rank", None),
getattr(hf_config, "qk_rope_head_dim", None),
)
if dims != (512, 64):
return (
"FA4 sparse MLA requires (kv_lora_rank, qk_rope_head_dim) "
f"== (512, 64), got {dims}"
)
# Under DCP the query is all-gathered: the kernel sees heads * dcp_size.
dcp_size = vllm_config.parallel_config.decode_context_parallel_size
num_heads = vllm_config.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
# 128 gathered heads take FA's prefill kernel, unvalidated under DCP.
head_counts = (8, 16, 32, 64) if dcp_size > 1 else (8, 16, 32, 64, 128)
if num_heads * dcp_size not in head_counts:
return (
f"FA4 sparse MLA requires {head_counts} gathered query heads, "
f"got num_heads={num_heads} * dcp_size={dcp_size}"
)
return super().supports_combination(*args, **kwargs)
class FlashAttnMLASparseFA4MetadataBuilder(FlashInferMLASparseTRTLLMMetadataBuilder):
"""The trtllm-gen builder, for the prefill lane's DCP workspace pre-size.
Its UNIFORM_BATCH support and varlen decode bound also fit FA4, which runs
one query row per token and bakes the row count into its varlen scalars.
"""
@cache
def _fa4_varlen_scalars(
num_tokens: int, num_kv_rows: int, device: torch.device
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Per-token varlen scalars; never evict, CUDA graphs bake in the pointers."""
cu_seqlens_q = torch.arange(num_tokens + 1, dtype=torch.int32, device=device)
cu_seqlens_k = torch.zeros(num_tokens + 1, dtype=torch.int32, device=device)
seqused_k = torch.full((num_tokens,), num_kv_rows, dtype=torch.int32, device=device)
return cu_seqlens_q, cu_seqlens_k, seqused_k
class FlashAttnMLASparseFA4Impl(FlashInferMLASparseImpl):
# FA4 emits a natural-log LSE; prefill converts trtllm-gen's log2 LSE.
lse_base_on_e: bool = True
def _forward_mqa_kernel(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_cache: torch.Tensor,
topk_indices: torch.Tensor,
valid_counts: torch.Tensor,
*,
layer: AttentionLayer,
block_size: int,
is_decode: bool,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if not is_decode:
out, lse = super()._forward_mqa_kernel(
q,
kv_cache,
topk_indices,
valid_counts,
layer=layer,
block_size=block_size,
is_decode=is_decode,
)
return out, None if lse is None else lse * math.log(2.0)
if isinstance(q, tuple):
ql_nope, q_pe = q
else:
# 16B-aligned halves of the fused query; FA4 reads them in place.
ql_nope, q_pe = q[..., : self.kv_lora_rank], q[..., self.kv_lora_rank :]
kv_rows, _ = flat_kv_row_view(kv_cache, block_size)
num_tokens = q_pe.shape[0]
num_kv_rows = kv_rows.shape[0]
assert self.topk_indices_buffer is not None
cu_seqlens_q, cu_seqlens_k, seqused_k = _fa4_varlen_scalars(
self.topk_indices_buffer.shape[0], num_kv_rows, kv_rows.device
)
# An all-sentinel row yields (0, -inf), the DCP merge identity; no masking.
kernel_out = flash_attn_varlen_func(
q=q_pe,
k=kv_rows[:, self.kv_lora_rank :].unsqueeze(1),
v=kv_rows[:, : self.kv_lora_rank].unsqueeze(1),
q_v=ql_nope,
max_seqlen_q=1,
cu_seqlens_q=cu_seqlens_q[: num_tokens + 1],
max_seqlen_k=num_kv_rows,
cu_seqlens_k=cu_seqlens_k[: num_tokens + 1],
seqused_k=seqused_k[:num_tokens],
gather_kv_indices=topk_indices,
# Part of FA4's compile key: pass it unconditionally.
gather_kv_valid_length=valid_counts,
softmax_scale=self.scale,
# Causality is in the top-k list; causal=True would clamp flat rows.
causal=False,
fa_version=4,
return_softmax_lse=self.need_to_return_lse_for_decode,
)
return kernel_out if self.need_to_return_lse_for_decode else (kernel_out, None)
@@ -1,490 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, ClassVar
import torch
from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla
from flashinfer.utils import (
get_device_sm_count,
get_trtllm_gen_multi_ctas_kv_counter_bytes,
)
from vllm.config import get_current_vllm_config
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonDecodeMetadata,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
QueryLenSupport,
)
from vllm.platforms.interface import DeviceCapability
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
AttentionType,
MultipleOf,
)
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.v1.kv_cache_interface import AttentionSpec
logger = init_logger(__name__)
def _trtllm_gen_mla_decode_supports_num_heads(num_heads: int) -> bool:
"""True if trtllm-gen's MLA decode kernel supports this query head count.
The kernel groups Q heads into CTAs of ``min(num_heads, tileSizeQ)`` and
requires ``num_heads`` divisible by that, else raises "The
numHeadsQ/numHeadsKv is not supported" (flashinfer fmhaKernels.cuh).
``tileSizeQ`` is 8/16 for ``num_heads <= 8``/``<= 32`` (SwapsMmaAb) else 64;
treat ``> 32`` as tile 64 (safe bound). E.g. 96/24 -> False, 48/64/128 -> True.
"""
if num_heads <= 8:
tile = 8
elif num_heads <= 32:
tile = 16
else:
tile = 64
return num_heads % min(num_heads, tile) == 0
def _select_mla_decode_backend(num_heads: int) -> str | None:
"""cute-dsl for head counts trtllm-gen cannot tile, else None (=> auto)."""
if not _trtllm_gen_mla_decode_supports_num_heads(num_heads):
logger.warning_once(
"trtllm-gen MLA decode does not support num_heads=%d "
"(query/kv head ratio); falling back to the cute-dsl backend.",
num_heads,
)
return "cute-dsl"
return None
FLASHINFER_MLA_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024
FLASHINFER_MLA_LSE_WORKSPACE_BUFFER_SIZE = 256 * 1024 * 1024
_fi_workspace: torch.Tensor | None = None
def _get_workspace_buffer(return_lse: bool) -> torch.Tensor:
global _fi_workspace
buffer_size = (
FLASHINFER_MLA_LSE_WORKSPACE_BUFFER_SIZE
if return_lse
else FLASHINFER_MLA_WORKSPACE_BUFFER_SIZE
)
if _fi_workspace is None or _fi_workspace.numel() < buffer_size:
# FlashInfer's CuteDSL MLA-decode tactic requires an int8 workspace;
# the trtllm-gen path views it as uint8, so int8 is safe for all backends.
_fi_workspace = torch.zeros(buffer_size, dtype=torch.int8, device="cuda")
return _fi_workspace
_fi_multi_ctas_kv_counter: torch.Tensor | None = None
def _get_multi_ctas_kv_counter_buffer(
min_bytes: int, device: torch.device
) -> torch.Tensor:
"""Persistent, zero-initialized trtllm-gen multi-CTA-KV counter buffer.
trtllm-gen's multi-CTA-KV MLA decode kernel resets these semaphores to zero
at the end of every launch, so the buffer only needs zeroing once. The
public ``trtllm_batch_decode_with_kv_cache_mla`` entry point builds a fresh
runner per call, so without a caller-owned buffer it re-allocates and
re-zeros this counter on every decode step (a tiny ``FillFunctor<uint8>``
launch right before the FMHA). Owning it here and passing it in removes that
per-step launch. ``min_bytes`` is sized to the worst-case batch so the
buffer is allocated once and never reallocated after CUDA-graph capture.
"""
global _fi_multi_ctas_kv_counter
if (
_fi_multi_ctas_kv_counter is None
or _fi_multi_ctas_kv_counter.numel() < min_bytes
):
_fi_multi_ctas_kv_counter = torch.zeros(
min_bytes, dtype=torch.uint8, device=device
)
return _fi_multi_ctas_kv_counter
@dataclass
class FlashInferMLADecodeMetadata(MLACommonDecodeMetadata):
flattened_block_table: torch.Tensor | None = None
flattened_seq_lens: torch.Tensor | None = None
flattened_row_req: torch.Tensor | None = None
# Row count the flattened tensors were built for (0 = not built), not a query len.
query_len: int = 0
query_start_loc: torch.Tensor | None = None
max_query_len: int = 1
@dataclass
class FlashInferMLAMetadata(MLACommonMetadata[FlashInferMLADecodeMetadata]):
pass
class FlashInferMLAMetadataBuilder(MLACommonMetadataBuilder[FlashInferMLAMetadata]):
# Adaptive verification requires ALWAYS from every builder, matching upstream's
# DeepseekV4FlashMLAMetadataBuilder. The kernels tile ragged queries from the device
# query offsets (flashinfer #3238), so one k+1 graph replays any 1..k+1 mix.
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.VARLEN
# Non-causal DSpark blocks are flattened to single-token rows in forward_mqa.
supports_non_causal_multi_token_decode: ClassVar[bool] = True
supports_non_causal_multi_token_dcp: ClassVar[bool] = True
def __init__(
self,
kv_cache_spec: "AttentionSpec",
layer_names: list[str],
vllm_config: "VllmConfig",
device: torch.device,
) -> None:
parallel_config = vllm_config.parallel_config
dcp_size = parallel_config.decode_context_parallel_size
interleave_size = parallel_config.cp_kv_cache_interleave_size
if dcp_size > 1 and interleave_size != 1:
raise ValueError(
"FlashInfer MLA native DCP requires "
"cp_kv_cache_interleave_size=1; got "
f"{interleave_size}."
)
super().__init__(
kv_cache_spec,
layer_names,
vllm_config,
device,
FlashInferMLAMetadata,
supports_dcp_with_varlen=True,
)
def _build_decode(
self,
block_table_tensor: torch.Tensor,
seq_lens_device: torch.Tensor,
max_seq_len: int,
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
max_query_len: int,
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> FlashInferMLADecodeMetadata:
# Promised bound, not measured: a capture dummy puts one token/req, so
# measuring would bake an undersized graph. Ragged only when max_query_len>1.
return FlashInferMLADecodeMetadata(
block_table=block_table_tensor,
seq_lens=seq_lens_device,
dcp_tot_seq_lens=dcp_tot_seq_lens_device,
query_start_loc=query_start_loc_device,
max_query_len=max_query_len,
)
class FlashInferMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [32, 64]
@staticmethod
def get_name() -> str:
return "FLASHINFER_MLA"
@staticmethod
def get_impl_cls() -> type["FlashInferMLAImpl"]:
return FlashInferMLAImpl
@staticmethod
def get_builder_cls() -> type["FlashInferMLAMetadataBuilder"]:
return FlashInferMLAMetadataBuilder
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 10
@classmethod
def supports_non_causal(cls) -> bool:
return True
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
# FlashInfer MLA kernel requires qk_nope_head_dim in [64, 128, 192]
vllm_config = get_current_vllm_config()
if vllm_config.model_config is not None:
hf_text_config = vllm_config.model_config.hf_text_config
qk_nope_head_dim = getattr(hf_text_config, "qk_nope_head_dim", 1)
if qk_nope_head_dim not in [64, 128, 192]:
return (
"FlashInfer MLA kernel requires qk_nope_head_dim "
f"in [64, 128, 192], but got {qk_nope_head_dim}"
)
return None
class FlashInferMLAImpl(MLACommonImpl[FlashInferMLAMetadata]):
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
# DCP is the only path that consumes LSE. It uses monolithic CuTeDSL,
# whose public LSE contract is natural-log.
lse_base_on_e: bool = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"FlashInferMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"FlashInferMLAImpl"
)
self.bmm1_scale: float | None = None
self.bmm2_scale: float | None = None
# Worst-case decode batch for the persistent trtllm-gen multi-CTA-KV
# counter buffer (see _get_multi_ctas_kv_counter_buffer). Captured here
# (config is in scope during construction) so the byte size can be
# resolved once on the first decode and never grows after CUDA-graph
# capture. The impl has no _vllm_config, hence get_current_vllm_config().
_sched = get_current_vllm_config().scheduler_config
self._mla_counter_max_batch: int = (
_sched.max_num_batched_tokens or _sched.max_num_seqs
)
self._mla_counter_bytes: int | None = None
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashInferMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
if isinstance(q, tuple):
q_nope, q_pe = q
q = torch.cat([q_nope, q_pe], dim=-1)
block_table = attn_metadata.decode.block_table
seq_lens = attn_metadata.decode.seq_lens
# Led by the promised bound (baked into the graph), not
# num_decode_tokens // num_decodes -- that average is a per-request length
# only for uniform batches.
multi_token_decode = (
attn_metadata.decode.max_query_len > 1
or attn_metadata.num_decode_tokens > attn_metadata.num_decodes
)
cum_seq_lens_q: torch.Tensor | None = None
max_q_len: int | None = None
row_req: torch.Tensor | None = None
if not attn_metadata.causal:
# FlashInfer decode has no causal flag. Flatten each non-causal
# query block into independent single-token rows.
q = q.unsqueeze(1)
if multi_token_decode:
block_table, seq_lens, row_req = self._flattened_decode_metadata(
attn_metadata, q.shape[0]
)
elif attn_metadata.decode.max_query_len > 1 and self.dcp_world_size == 1:
# Causal spec decode: keep q compact and let the kernel tile each
# request's length (uniform 1+k and adaptive ragged). Mirrors vllm #52157.
# DCP keeps the uniform reshape below: it needs LSE, which the kernels
# do not return on the ragged path (flashinfer #3238).
cum_seq_lens_q = attn_metadata.decode.query_start_loc
max_q_len = attn_metadata.decode.max_query_len
# trtllm API requires extra dimension q_len_per_request for MTP
elif attn_metadata.num_decode_tokens % attn_metadata.num_decodes != 0:
logger.warning_once(
"""FlashInferMLAImpl got a query of uneven length.
This usually indicates an issue in batch reordering
or incorrect setup in dummy_run."""
)
q = q.unsqueeze(1)
else:
q = q.view(attn_metadata.num_decodes, -1, q.shape[-2], q.shape[-1])
if self.bmm1_scale is None:
self.bmm1_scale = self.scale
if is_quantized_kv_cache(self.kv_cache_dtype):
self.bmm1_scale *= layer._q_scale_float * layer._k_scale_float
if self.bmm2_scale is None:
self.bmm2_scale = 1.0
if is_quantized_kv_cache(self.kv_cache_dtype):
self.bmm2_scale *= layer._k_scale_float
return_lse = self.need_to_return_lse_for_decode
workspace_buffer = _get_workspace_buffer(return_lse)
# Parallel gathers can change the runtime Q heads from TP-local num_heads.
runtime_num_heads = q.shape[-2]
extra_kwargs: dict[str, Any] = {}
decode_backend: str | None
if self.dcp_world_size > 1:
causal_seqlens_kv_global = attn_metadata.decode.dcp_tot_seq_lens
assert causal_seqlens_kv_global is not None
if row_req is not None:
causal_seqlens_kv_global = causal_seqlens_kv_global[row_req]
extra_kwargs.update(
enable_dcp=True,
cp_world=self.dcp_world_size,
cp_rank=self.dcp_rank,
causal_seqlens_kv_global=causal_seqlens_kv_global,
)
decode_backend = "cute-dsl"
else:
# trtllm-gen rejects MLA head counts it can't tile (e.g. 96);
# fall back to cute-dsl for those.
decode_backend = _select_mla_decode_backend(runtime_num_heads)
if cum_seq_lens_q is not None:
# Neither decode backend returns LSE on the ragged path
# (flashinfer #3238); DCP, the only LSE consumer, took the uniform
# branch above, so this only guards a future caller wiring the two.
assert not return_lse, (
"FlashInferMLA ragged decode cannot return LSE; DCP and adaptive "
"variable-length decode are mutually exclusive."
)
extra_kwargs["cum_seq_lens_q"] = cum_seq_lens_q
extra_kwargs["max_q_len"] = max_q_len
if decode_backend:
extra_kwargs["backend"] = decode_backend
elif kv_c_and_k_pe_cache.shape[-2] in (32, 64):
# The auto path can dispatch to trtllm-gen, whose multi-CTA-KV decode
# kernel self-resets its semaphore counter after each launch (so it
# only needs zeroing once). Pass a persistent counter buffer to skip
# the per-step re-allocate + re-zero the public entry point would
# otherwise do. Guarded to configs where a trtllm-gen runner is
# eligible (page/block size in {32, 64}); the arg is rejected when
# only a cute-dsl runner can run.
if self._mla_counter_bytes is None:
self._mla_counter_bytes = get_trtllm_gen_multi_ctas_kv_counter_bytes(
self._mla_counter_max_batch,
runtime_num_heads,
get_device_sm_count(q.device),
)
extra_kwargs["multi_ctas_kv_counter_buffer"] = (
_get_multi_ctas_kv_counter_buffer(self._mla_counter_bytes, q.device)
)
kernel_out = trtllm_batch_decode_with_kv_cache_mla(
query=q,
kv_cache=kv_c_and_k_pe_cache.unsqueeze(1),
workspace_buffer=workspace_buffer,
qk_nope_head_dim=self.qk_nope_head_dim,
kv_lora_rank=self.kv_lora_rank,
qk_rope_head_dim=self.qk_rope_head_dim,
block_tables=block_table,
seq_lens=seq_lens,
max_seq_len=attn_metadata.max_seq_len,
bmm1_scale=self.bmm1_scale,
bmm2_scale=self.bmm2_scale,
return_lse=return_lse,
**extra_kwargs,
)
if return_lse:
o, lse = kernel_out
lse = lse.view(-1, lse.shape[-1])
else:
o, lse = kernel_out, None
# Flatten the output for consistent shape
o = o.view(-1, o.shape[-2], o.shape[-1])
return o, lse
def _flattened_decode_metadata(
self,
attn_metadata: FlashInferMLAMetadata,
num_rows: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Expand per-request decode tensors to one row per query token.
Cached across the layers of a group, which all see the same batch.
"""
decode = attn_metadata.decode
assert decode is not None
if decode.query_len != num_rows:
cu = decode.query_start_loc
assert cu is not None
# searchsorted on the device offsets, not repeat_interleave(uniform_len):
# the latter only lines up for uniform batches and hands ragged rows
# another request's KV (silent garbage).
rows = torch.arange(num_rows, device=cu.device, dtype=cu.dtype)
row_req = torch.searchsorted(cu[1:], rows, right=True).clamp_(
max=decode.block_table.shape[0] - 1
)
decode.flattened_row_req = row_req
decode.flattened_block_table = decode.block_table[row_req]
decode.flattened_seq_lens = decode.seq_lens[row_req]
decode.query_len = num_rows
assert decode.flattened_block_table is not None
assert decode.flattened_seq_lens is not None
assert decode.flattened_row_req is not None
return (
decode.flattened_block_table,
decode.flattened_seq_lens,
decode.flattened_row_req,
)
@@ -1,701 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""FlashInfer sparse MLA attention backend."""
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar
import torch
from vllm import envs
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
SparseMLACommonMetadata,
SparseMLACommonMetadataBuilder,
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionLayer,
AttentionType,
MLAAttentionImpl,
MultipleOf,
max_decode_query_len,
)
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
from vllm.v1.attention.backends.mla.sparse_utils import (
align_blocks_to_rows,
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:
from vllm.model_executor.models.deepseek_v2 import Indexer
logger = init_logger(__name__)
class _FlashInferMLASparseBackendBase(AttentionBackend):
"""Common metadata for concrete FlashInfer sparse MLA backends."""
@staticmethod
def get_name() -> str:
return "FLASHINFER_MLA_SPARSE"
@staticmethod
def get_builder_cls() -> type["FlashInferMLASparseMetadataBuilder"]:
return FlashInferMLASparseMetadataBuilder
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
# 576 = 512 NoPE + 64 RoPE (with-rope layout); 512 = 512 NoPE only
# (no-rope layout, qk_rope_head_dim == 0). Both share D_V = 512 and are
# served by the TRTLLM-GEN sparse MLA kernel.
return [512, 576]
@classmethod
def is_mla(cls) -> bool:
return True
@classmethod
def is_sparse(cls) -> bool:
return True
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
# The kernels read the rows as pages of their kernel block size.
(page,) = cls.get_supported_kernel_block_sizes(spec)
assert isinstance(page, MultipleOf)
return align_blocks_to_rows(spec, page.base)
class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase):
"""FlashInfer sparse MLA backend using the TRTLLM-gen launcher."""
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(32)]
@staticmethod
def get_impl_cls() -> type[MLAAttentionImpl]:
return FlashInferMLASparseImpl
@staticmethod
def get_builder_cls() -> type["FlashInferMLASparseTRTLLMMetadataBuilder"]:
return FlashInferMLASparseTRTLLMMetadataBuilder
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 10
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
from vllm.config import get_current_vllm_config
vllm_config = get_current_vllm_config()
parallel_config = vllm_config.parallel_config
if (
parallel_config.prefill_context_parallel_size > 1
and parallel_config.decode_context_parallel_size > 1
):
return (
f"{cls.get_name()} does not support combined PCP+DCP; "
"use FLASHMLA_SPARSE, which gathers each DCP KV shard before "
"running the rank-local PCP prefill queries"
)
if kv_cache_dtype == "fp8_ds_mla":
return f"{cls.get_name()} SM10 does not support fp8_ds_mla kv-cache dtype"
# FlashInfer MLA sparse SM10 kernel requires qk_nope_head_dim in [128, 192].
if vllm_config.model_config is not None:
hf_text_config = vllm_config.model_config.hf_text_config
qk_nope_head_dim = hf_text_config.qk_nope_head_dim
qk_rope_head_dim = hf_text_config.qk_rope_head_dim
kv_lora_rank = hf_text_config.kv_lora_rank
if qk_rope_head_dim == 0:
# Native no-rope MLA: FlashInfer only ships the one shape
# (nope_mla_dimensions in flashinfer.mla._core).
if qk_nope_head_dim != 256 or kv_lora_rank != 512:
return (
"FlashInfer native no-rope MLA requires "
"qk_nope_head_dim=256 and kv_lora_rank=512, but got "
f"qk_nope_head_dim={qk_nope_head_dim}, "
f"kv_lora_rank={kv_lora_rank}"
)
elif qk_nope_head_dim not in [128, 192]:
return (
"FlashInfer MLA Sparse kernel requires qk_nope_head_dim "
f"in [128, 192], but got {qk_nope_head_dim}"
)
# Check for index_topk which indicates sparse model
if not hasattr(hf_text_config, "index_topk"):
return "FlashInfer MLA Sparse requires model with index_topk config"
return None
class FlashInferMLASparseSM120Backend(_FlashInferMLASparseBackendBase):
"""FlashInfer sparse MLA backend for SM120."""
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"fp8",
"fp8_e4m3",
"fp8_ds_mla",
]
@staticmethod
def get_name() -> str:
return "FLASHINFER_MLA_SPARSE_SM120"
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(64)]
@staticmethod
def get_impl_cls() -> type[MLAAttentionImpl]:
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm120 import (
FlashInferMLASparseSM120Impl,
)
return FlashInferMLASparseSM120Impl
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 12
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
from vllm.config import get_current_vllm_config
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120
if not has_flashinfer_sparse_mla_sm120():
return (
"FLASHINFER_MLA_SPARSE_SM120 requires FlashInfer's "
"sparse MLA decode API"
)
if dtype != torch.bfloat16:
return "dtype not supported"
if kv_cache_dtype not in (
None,
"auto",
"fp8",
"fp8_e4m3",
"fp8_ds_mla",
):
return "kv_cache_dtype not supported"
vllm_config = get_current_vllm_config()
if vllm_config.model_config is not None:
hf_text_config = vllm_config.model_config.hf_text_config
index_topk = getattr(hf_text_config, "index_topk", None)
if index_topk is None:
return (
"FLASHINFER_MLA_SPARSE_SM120 requires a model with "
"index_topk config"
)
if int(index_topk) != 2048:
return (
"FLASHINFER_MLA_SPARSE_SM120 requires index_topk=2048; "
f"got {index_topk}"
)
return None
@dataclass
class FlashInferMLASparseMetadata(SparseMLACommonMetadata):
"""Attention metadata for FlashInfer MLA Sparse backend."""
class FlashInferMLASparseMetadataBuilder(
SparseMLACommonMetadataBuilder[FlashInferMLASparseMetadata]
):
"""Builder for FlashInfer MLA Sparse attention metadata."""
metadata_cls = FlashInferMLASparseMetadata
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
num_q_heads = vllm_config.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
threshold = {8: 128, 16: 128, 32: 128, 64: 256, 128: 1024}.get(
num_q_heads, 1024
)
self._init_reorder_batch_threshold(
threshold,
supports_spec_as_decode=True,
supports_dcp_with_varlen=True,
)
class FlashInferMLASparseTRTLLMMetadataBuilder(FlashInferMLASparseMetadataBuilder):
"""Metadata builder for the SM100 TRT-LLM sparse MLA kernel."""
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
@classmethod
def get_varlen_cudagraph_max_query_len(
cls,
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> int | None:
# Decode uses device request boundaries; prefill metadata is not graph-safe.
return max_decode_query_len(vllm_config)
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
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
# final size here, before the first forward/capture (no lazy regrow).
if self.dcp_world_size > 1:
num_q_heads = vllm_config.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
_get_workspace_buffer(
device,
_required_workspace_bytes(
self.dcp_world_size,
num_q_heads,
vllm_config.scheduler_config.max_num_batched_tokens,
),
)
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
# trtllm-gen carves a softmax-stats slab from the workspace whenever LSE is
# requested (FlashInfer csrc/trtllm_fmha_kernel_launcher.cu, unchanged from
# v0.6.14 through current main):
# sizeof(float2) * num_qo_heads * batch_size * round_up(max_q_len, 256)
# + 1 MiB guard
# forward_mqa always passes q_len == 1, so each (head, token) pair costs
# round_up(1, 256) == 256 slots.
_TRTLLM_GEN_SOFTMAX_STAT_BYTES = 8 # sizeof(float2)
_TRTLLM_GEN_SOFTMAX_SLOTS_PER_TOKEN = 256 # round_up(q_len=1, 256)
_TRTLLM_GEN_SOFTMAX_GUARD_BYTES = 1024 * 1024
# Keep in sync with the VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE default in
# vllm/envs.py.
_DEFAULT_WORKSPACE_BUFFER_SIZE = 394 * 1024 * 1024
def compute_trtllm_sparse_mla_workspace_bytes(
base_workspace_bytes: int,
dcp_world_size: int,
num_heads_per_rank: int,
max_num_batched_tokens: int,
) -> int:
"""Workspace bytes needed by the trtllm-gen sparse MLA decode kernel.
Under DCP the query is all-gathered across the DCP group in the head dim
and the kernel is asked for LSE, so trtllm-gen carves the softmax-stats
slab described above from the workspace before its (batch-independent)
counter and scratch regions. ``base_workspace_bytes`` must stay available
for those regions, so the slab is added on top of it (see #50781).
Without DCP no LSE is requested, no slab is carved, and the base size is
returned unchanged.
"""
if dcp_world_size <= 1:
return base_workspace_bytes
softmax_bytes = (
_TRTLLM_GEN_SOFTMAX_STAT_BYTES
* (num_heads_per_rank * dcp_world_size)
* max_num_batched_tokens
* _TRTLLM_GEN_SOFTMAX_SLOTS_PER_TOKEN
+ _TRTLLM_GEN_SOFTMAX_GUARD_BYTES
)
return base_workspace_bytes + softmax_bytes
def _required_workspace_bytes(
dcp_world_size: int,
num_heads_per_rank: int,
max_num_batched_tokens: int,
) -> int:
"""Resolve the workspace size, honoring an explicit env override."""
computed = compute_trtllm_sparse_mla_workspace_bytes(
_DEFAULT_WORKSPACE_BUFFER_SIZE,
dcp_world_size,
num_heads_per_rank,
max_num_batched_tokens,
)
if not envs.is_set("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE"):
return computed
env_bytes = envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE
if env_bytes < computed:
logger.warning_once(
"VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE=%d is below the %d bytes "
"computed for the sparse MLA workspace with dcp_world_size=%d, "
"%d heads/rank and max_num_batched_tokens=%d. Respecting the "
"override, but the trtllm-gen kernel may crash with a workspace "
"overflow; set VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE=%d or unset "
"it to use the computed size.",
env_bytes,
computed,
dcp_world_size,
num_heads_per_rank,
max_num_batched_tokens,
computed,
)
return env_bytes
def _get_workspace_buffer(
device: torch.device, min_bytes: int | None = None
) -> torch.Tensor:
global _fi_sparse_workspace
required = (
min_bytes
if min_bytes is not None
else envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE
)
if _fi_sparse_workspace is None or _fi_sparse_workspace.numel() < required:
# FlashInfer's CuteDSL MLA-decode tactic requires an int8 workspace;
# the trtllm-gen path views it as uint8, so int8 is safe for all backends.
_fi_sparse_workspace = torch.zeros(
required,
dtype=torch.int8,
device=device,
)
return _fi_sparse_workspace
class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
"""FlashInfer MLA Sparse implementation.
Uses the TRT-LLM MLA kernel with sparse_mla_top_k parameter for
sparse attention computation.
"""
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
lse_base_on_e: bool = False
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
topk_indices_buffer: torch.Tensor | None = None,
indexer: "Indexer | None" = None,
**mla_args,
) -> None:
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"FlashInferMLASparseImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"FlashInferMLASparseImpl"
)
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
indexer=indexer,
topk_indices_buffer=topk_indices_buffer,
**mla_args,
)
self._workspace_buffer: torch.Tensor | None = None
self.bmm1_scale: float | None = None
self.bmm2_scale: float | None = None
# Native no-rope MLA additionally requires a per-query-token active
# top-k length tensor.
self.is_nope_mla = self.qk_rope_head_dim == 0
# fp8 query quantization is required when using fp8 kv_cache,
# as the TRTLLM-GEN sparse MLA kernel requires matching dtypes
# for query and kv_cache (mixed bf16+fp8 is not supported).
self.supports_quant_query_input = True
def _prepare_mqa_kernel(
self,
layer: AttentionLayer,
device: torch.device,
) -> None:
if self._workspace_buffer is None:
self._workspace_buffer = _get_workspace_buffer(device)
if self.bmm1_scale is None:
self.bmm1_scale = self.scale
if is_quantized_kv_cache(self.kv_cache_dtype):
self.bmm1_scale *= layer._q_scale_float * layer._k_scale_float
if self.bmm2_scale is None:
self.bmm2_scale = 1.0
if is_quantized_kv_cache(self.kv_cache_dtype):
self.bmm2_scale *= layer._k_scale_float
def autotune_hisparse_decode(self, layer: AttentionLayer) -> None:
"""Autotune the largest legal HiSparse decode batch."""
assert isinstance(self.index_group, HiSparseMLAIndexGroup)
cache = self.index_group.cache(self.index_group_index)
assert self.topk_indices_buffer is not None
runtime = cache.runtime
kv_cache = runtime.hot.attention_cache
num_tokens = runtime.max_num_reqs
topk_tokens = self.topk_indices_buffer.shape[1]
q_dtype = (
current_platform.fp8_dtype()
if is_quantized_kv_cache(self.kv_cache_dtype)
else kv_cache.dtype
)
q = torch.zeros(
(
num_tokens,
self.num_heads,
self.kv_lora_rank + self.qk_rope_head_dim,
),
dtype=q_dtype,
device=kv_cache.device,
)
topk_indices = (
torch.arange(
topk_tokens,
dtype=torch.int32,
device=kv_cache.device,
)
.expand(num_tokens, -1)
.contiguous()
)
seq_lens = torch.full(
(num_tokens,),
topk_tokens,
dtype=torch.int32,
device=kv_cache.device,
)
self._forward_mqa_kernel(
q,
kv_cache,
topk_indices,
seq_lens,
layer=layer,
block_size=runtime.hot.block_size,
is_decode=True,
)
def _forward_mqa_kernel(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_cache: torch.Tensor,
topk_indices: torch.Tensor,
seq_lens: torch.Tensor,
*,
layer: AttentionLayer,
block_size: int,
is_decode: bool,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if isinstance(q, tuple):
ql_nope, q_pe = q
if q_pe.shape[-1] == 0 and ql_nope.is_contiguous():
q = ql_nope
else:
q = torch.cat(q, dim=-1)
self._prepare_mqa_kernel(layer, q.device)
assert self._workspace_buffer is not None
assert self.bmm1_scale is not None
assert self.bmm2_scale is not None
from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla
kv_rows, block_stride_rows = flat_kv_row_view(
kv_cache.view(q.dtype), block_size
)
# Block sizes and strides have been aligned to 32 rows.
kv_cache = kv_rows.view(
-1, math.gcd(block_stride_rows, block_size, 64), kv_rows.shape[-1]
)
# Single-token sparse decode. trtllm-gen requires the q_len_per_request
# dim, but the sparse attention mask is fully per-token (each query token
# carries its own top-k index row), so unsqueeze is sufficient and
# correct. The MTP/multi-token q_len grouping is a perf-only layout and is
# deferred until MTP is validated end-to-end for this backend.
query = q.unsqueeze(1)
block_tables = topk_indices.unsqueeze(1)
seq_lens_arg = seq_lens
# page_table width = topk buffer width, which kpool widens past
# index_topk (topk_tokens) and rounds up to a multiple of 128. The
# kernel treats sparse_mla_top_k as the page-table *capacity* and bounds
# the active per-query length by ``seq_lens`` (the compacted valid
# count), so the -1 padding slots past seq_lens are never attended to.
# Use the actual buffer width instead of the fixed topk_tokens, which
# mismatches the page_table when index_kpool > 1.
sparse_topk_capacity = topk_indices.shape[1]
extra_kwargs: dict[str, torch.Tensor] = {}
needs_empty_query_guard = self.need_to_return_lse_for_decode or isinstance(
self.index_group, HiSparseMLAIndexGroup
)
if self.is_nope_mla:
# Resident TP queries have nonempty selections. Preserve empty-query
# handling for DCP's local selections and host-backed HiSparse.
topk_lens = seq_lens
if needs_empty_query_guard:
topk_lens = prepare_sparse_mla_safe_lengths(topk_indices, seq_lens)
extra_kwargs["sparse_mla_top_k_lens"] = topk_lens
kernel_out = trtllm_batch_decode_with_kv_cache_mla(
query=query,
kv_cache=kv_cache.unsqueeze(1),
workspace_buffer=self._workspace_buffer,
qk_nope_head_dim=self.qk_nope_head_dim,
kv_lora_rank=self.kv_lora_rank,
qk_rope_head_dim=self.qk_rope_head_dim,
block_tables=block_tables,
seq_lens=seq_lens_arg,
max_seq_len=sparse_topk_capacity,
bmm1_scale=self.bmm1_scale,
bmm2_scale=self.bmm2_scale,
sparse_mla_top_k=sparse_topk_capacity,
return_lse=self.need_to_return_lse_for_decode,
**extra_kwargs,
)
if self.need_to_return_lse_for_decode:
assert isinstance(kernel_out, tuple)
o, lse = kernel_out
else:
assert isinstance(kernel_out, torch.Tensor)
o = kernel_out
lse = None
out = o.view(-1, o.shape[-2], o.shape[-1])
if lse is not None:
lse = self._normalize_lse(lse, out.shape[0], out.shape[1])
if self.is_nope_mla and needs_empty_query_guard:
empty_queries = seq_lens == 0
if lse is not None:
# DCP combine already suppresses outputs with zero LSE weight.
lse.masked_fill_(empty_queries[:, None], float("-inf"))
else:
out.masked_fill_(empty_queries[:, None, None], 0.0)
elif lse is not None:
empty_rows = (topk_indices == -1).all(dim=-1)
out.masked_fill_(empty_rows.view(-1, 1, 1), 0.0)
lse.masked_fill_(empty_rows.view(-1, 1), float("-inf"))
return out, lse
@staticmethod
def _normalize_lse(
lse: torch.Tensor,
num_tokens: int,
num_heads: int,
) -> torch.Tensor:
# FlashInfer returns the decode LSE either as 2D (num_tokens, num_heads)
# or 3D ((num_tokens, num_heads, 1) / (num_tokens, 1, num_heads)).
# Collapse all of these to the (num_tokens, num_heads) the shared DCP
# reducer expects.
if lse.dim() == 3:
if lse.shape[-1] == 1:
lse = lse.squeeze(-1)
elif lse.shape[1] == 1:
lse = lse.squeeze(1)
elif lse.shape[0] * lse.shape[1] == num_tokens:
lse = lse.reshape(num_tokens, lse.shape[-1])
if lse.shape != (num_tokens, num_heads):
raise RuntimeError(
"Unexpected FlashInfer sparse MLA LSE shape: "
f"{tuple(lse.shape)}, expected ({num_tokens}, {num_heads})."
)
return lse
@@ -1,250 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""SM120 implementation variant for ``FLASHINFER_MLA_SPARSE_SM120``."""
from typing import TYPE_CHECKING, cast
import torch
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
)
from vllm.v1.attention.backend import AttentionLayer, AttentionType
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseMetadata,
_get_workspace_buffer,
)
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
)
if TYPE_CHECKING:
from vllm.model_executor.models.deepseek_v2 import Indexer
def _kv_scale_format_for_model(model_type: str | None) -> str:
if model_type is not None and model_type.startswith("glm"):
return "arbitrary_fp32"
return "pow2_fp32"
class FlashInferMLASparseSM120Impl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
"""SM120 FlashInfer sparse-MLA implementation."""
is_sparse = True
supports_dense_mha_prefill = False
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
indexer: "Indexer | None" = None,
**mla_args,
) -> None:
if any([alibi_slopes, sliding_window, logits_soft_cap]):
raise NotImplementedError(
"FLASHINFER_MLA_SPARSE_SM120 does not support alibi_slopes / "
"sliding_window / logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"FLASHINFER_MLA_SPARSE_SM120 only supports decoder self-attention"
)
if kv_cache_dtype != "fp8_ds_mla":
raise NotImplementedError(
"FLASHINFER_MLA_SPARSE_SM120 requires the packed fp8_ds_mla "
f"KV cache layout; got kv_cache_dtype={kv_cache_dtype!r}."
)
topk_indices_buffer = mla_args.pop("topk_indices_buffer", None)
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
indexer=indexer,
topk_indices_buffer=topk_indices_buffer,
**mla_args,
)
from vllm.config import get_current_vllm_config
vllm_config = get_current_vllm_config()
model_type = None
if vllm_config.model_config is not None:
model_type = getattr(
vllm_config.model_config.hf_text_config, "model_type", None
)
self.kv_scale_format = _kv_scale_format_for_model(model_type)
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120
if not has_flashinfer_sparse_mla_sm120():
raise RuntimeError(
"FLASHINFER_MLA_SPARSE_SM120 requires FlashInfer's "
"sparse MLA decode API."
)
assert self.topk_indices_buffer is not None
self.supports_quant_query_input = False
self._workspace_buffer: torch.Tensor | None = None
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashInferMLASparseMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if isinstance(q, tuple):
q = torch.cat(q, dim=-1)
num_actual_toks = q.shape[0]
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[:num_actual_toks]
index_group = self.index_group
if isinstance(index_group, HiSparseMLAIndexGroup):
num_decode_tokens = attn_metadata.num_decode_tokens
physical_kv_cache = index_group.physical_kv_cache(self.index_group_index)
if (
num_decode_tokens == num_actual_toks
or index_group.cache(self.index_group_index).all_context_pages_resident
):
topk_indices_physical = cast(
torch.Tensor,
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=False,
),
)
return (
self._run_mqa_kernel(q, physical_kv_cache, topk_indices_physical),
None,
)
outputs = []
if num_decode_tokens:
topk_indices_physical = cast(
torch.Tensor,
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
block_stride_rows=None,
return_valid_counts=False,
),
)
outputs.append(
self._run_mqa_kernel(
q[:num_decode_tokens],
physical_kv_cache,
topk_indices_physical,
)
)
prefill_cache, block_table, req_ids = index_group.stage_prefill_rows(
self.index_group_index,
kv_c_and_k_pe_cache,
attn_metadata,
)
topk_indices_physical = cast(
torch.Tensor,
triton_convert_req_index_to_global_index(
req_ids,
block_table,
topk_indices[num_decode_tokens:],
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
),
)
outputs.append(
self._run_mqa_kernel(
q[num_decode_tokens:],
prefill_cache,
topk_indices_physical,
)
)
output = torch.cat(outputs) if len(outputs) > 1 else outputs[0]
return output, None
kv_rows, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
topk_indices_physical = cast(
torch.Tensor,
triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[:num_actual_toks],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk_indices.shape[1],
),
)
return (
self._run_mqa_kernel(
q,
# The SM120 kernels are built for 64-row pages only.
kv_rows.view(-1, 64, kv_rows.shape[-1]),
topk_indices_physical,
),
None,
)
def _run_mqa_kernel(
self,
q: torch.Tensor,
kv_cache: torch.Tensor,
topk_indices_physical: torch.Tensor,
) -> torch.Tensor:
num_actual_toks = q.shape[0]
output = q.new_empty(
(num_actual_toks, self.num_heads, self.kv_lora_rank),
dtype=q.dtype,
)
if self._workspace_buffer is None:
self._workspace_buffer = _get_workspace_buffer(q.device)
from vllm.utils.flashinfer import (
flashinfer_trtllm_batch_decode_with_kv_cache_mla,
)
sparse_capacity = topk_indices_physical.shape[1]
out = flashinfer_trtllm_batch_decode_with_kv_cache_mla(
query=q.unsqueeze(1),
kv_cache=kv_cache.view(torch.uint8).unsqueeze(1),
workspace_buffer=self._workspace_buffer,
qk_nope_head_dim=self.qk_nope_head_dim,
kv_lora_rank=self.kv_lora_rank,
qk_rope_head_dim=self.qk_rope_head_dim,
block_tables=topk_indices_physical.unsqueeze(1),
seq_lens=None,
max_seq_len=sparse_capacity,
out=output.unsqueeze(1),
bmm1_scale=self.scale,
bmm2_scale=1.0,
sparse_mla_top_k=sparse_capacity,
kv_scale_format=self.kv_scale_format,
)
return out.squeeze(1)
@@ -1,646 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""FlashInfer sparse MLA backend for SM90 (Hopper) NoPE models.
Wraps FlashInfer's ``BatchMLAPagedAttentionWrapper`` (FA2/FA3 paths), which
as of FlashInfer 0.6.18 supports ``head_dim_kpe=0`` (GLM-5.3-Flash NoPE MLA)
and FP8 E4M3 KV caches on SM90 with in-kernel dequantization: the FP8 cache
is read directly (half the bf16 HBM traffic) and converted to BF16 in shared
memory, while queries stay BF16 (no query quantization).
Sparsity rides the same trick the FA-based sparse backend uses: with
``page_size=1`` the per-token top-k slot indices ARE the page table, so each
query token becomes one varlen batch row whose ``kv_indices`` slice is its
top-k row and whose ``kv_len`` is its valid count. Causality is already
encoded by the indexer's selection, so ``causal=False``.
CUDA-graph handling: ``plan()`` copies its inputs to host unconditionally,
so it must stay outside graph capture. Each metadata builder owns a wrapper,
reserved capture-stable device buffers, and the plan parameters. The wrapper
bakes the per-row ``kv_len`` into its int schedule at plan() time — ``run()``
never reads the device-side buffer. The builder plans (outside capture) from
sync-free host upper bounds and clamps each scheduled work item's ``kv_end``
on device to the exact valid count, so the kernel never reads past a row's
valid prefix (the -1 tail of the converted index buffer) and async scheduling
needs no D2H sync. Per-step content (top-k slots) is written into the
reserved buffers by kernels inside the captured forward, and captured runs
read the refreshed plan buffers on replay.
KV cache format: E4M3 ``[num_blocks, block_size, 512]`` (any block stride)
(uint8 storage) with a per-tensor ``k_scale``; BF16 caches also work. The
per-token x 128-channel-group ``ckv_scale_arr`` layout is supported by the
kernel but not wired yet (it needs a group-quantizing cache-write op).
"""
from dataclasses import dataclass
from typing import Any, ClassVar
import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
)
from vllm.platforms.interface import DeviceCapability
from vllm.triton_utils import tl, triton
from vllm.utils.flashinfer import has_flashinfer_sm90_nope_mla
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionLayer,
CommonAttentionMetadata,
MLAAttentionImpl,
MultipleOf,
)
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseMetadata,
FlashInferMLASparseMetadataBuilder,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
align_blocks_to_rows,
flat_kv_row_view,
triton_convert_req_index_to_global_index,
)
from vllm.v1.kv_cache_interface import AttentionSpec
_FP8_KV_DTYPES = ("fp8", "fp8_e4m3")
_WORKSPACE_BYTES = 128 * 1024 * 1024
# TODO: FlashInfer bakes per-row kv_len into the plan on the host, which
# forces a D2H sync under async scheduling. The plan-info layout constants
# below and the int-workspace clamp in _SM90State work around this by
# planning from sync-free upper bounds; delete them once FlashInfer accepts
# an upper-bound plan() that clamps kv_end internally, or exposes a
# GPU-side plan API (upstream ask:
# https://github.com/flashinfer-ai/flashinfer/issues/5559, see
# vllm-project/vllm#58684).
# FlashInfer MLAPlanInfo layout (scheduler.cuh) field indices.
_PLAN_INFO_LEN = 18
_PI_NUM_BLKS_Y = 1
_PI_Q_INDPTR = 2
_PI_KV_INDPTR = 3
_PI_KV_START = 13
_PI_KV_END = 14
_PI_WORK_INDPTR = 15
# Planned lengths exceed the host upper bound by up to this many tokens so a
# plan stays reusable across draft steps and consecutive decode steps; the
# device-side clamp restores the exact lengths.
_PLAN_SLACK = 32
@triton.jit
def _pack_topk_indices(
slots,
indptr,
indices,
WIDTH: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
cols = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
start = tl.load(indptr + row)
end = tl.load(indptr + row + 1)
mask = (cols < end - start) & (cols < WIDTH)
values = tl.load(slots + row * WIDTH + cols, mask=mask, other=0)
first_slot = tl.load(slots + row * WIDTH)
tl.store(
indices + start + cols,
tl.where(values >= 0, values, tl.maximum(first_slot, 0)),
mask=mask,
)
@triton.jit
def _clamp_work_kv_end(
int_ws,
saved_kv_end,
seq_lens,
query_start_loc,
req_id_per_token,
num_works_idx,
q_indptr_off,
kv_start_off,
kv_end_off,
TOPK: tl.constexpr,
KPOOL: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# Clamp each planned work item to its row's exact valid count, derived
# from the device batch layout exactly as the convert kernel counts it.
works = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = works < tl.load(int_ws + num_works_idx)
row = tl.load(int_ws + q_indptr_off + works, mask=mask, other=0)
req = tl.load(req_id_per_token + row, mask=mask, other=0)
seq_len = tl.load(seq_lens + req, mask=mask, other=0)
query_end = tl.load(query_start_loc + req + 1, mask=mask, other=0)
ctx = seq_len - query_end + row + 1
valid = tl.where(ctx <= TOPK, ctx, TOPK + ctx % KPOOL)
start = tl.load(int_ws + kv_start_off + works, mask=mask, other=0)
end = tl.load(saved_kv_end + works, mask=mask, other=0)
tl.store(
int_ws + kv_end_off + works,
tl.maximum(tl.minimum(end, valid), start),
mask=mask,
)
class FlashInferMLASparseSM90Backend(AttentionBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(64)]
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
return align_blocks_to_rows(spec)
@staticmethod
def get_name() -> str:
return "FLASHINFER_MLA_SPARSE_SM90"
@staticmethod
def get_builder_cls() -> type["FlashInferMLASparseSM90Builder"]:
return FlashInferMLASparseSM90Builder
@staticmethod
def get_impl_cls() -> type[MLAAttentionImpl]:
return FlashInferMLASparseSM90Impl
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
# 512 = ckv 512 + kpe 0 (NoPE); 576 = ckv 512 + kpe 64.
return [512, 576]
@classmethod
def is_mla(cls) -> bool:
return True
@classmethod
def is_sparse(cls) -> bool:
return True
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 9
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
if not has_flashinfer_sm90_nope_mla():
return (
"FLASHINFER_MLA_SPARSE_SM90 requires FlashInfer with SM90 "
"MLA support (ckv_scale_arr in "
"BatchMLAPagedAttentionWrapper.run, FlashInfer >= 0.6.18)"
)
if not use_sparse:
return "FLASHINFER_MLA_SPARSE_SM90 requires sparse MLA"
from vllm.config import get_current_vllm_config
vllm_config = get_current_vllm_config()
if vllm_config.model_config is not None:
hf = vllm_config.model_config.hf_text_config
# The SM90 FA2/FA3 kernel covers ckv=512 with kpe in {0, 64}
# (NoPE models and DeepSeek-style rope MLA alike).
if hf.kv_lora_rank != 512:
return "FLASHINFER_MLA_SPARSE_SM90 requires kv_lora_rank=512"
if hf.qk_rope_head_dim not in (0, 64):
return "FLASHINFER_MLA_SPARSE_SM90 requires qk_rope_head_dim in (0, 64)"
return None
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int,
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
return (num_blocks, block_size, head_size)
class _SM90State:
"""Builder-owned wrapper, capture-stable buffers, and plan parameters.
One instance serves every MLA layer in an attention group because the plan
depends only on the batch shape, not the layer.
"""
def __init__(
self,
device: torch.device,
num_heads: int,
kv_dtype: torch.dtype,
max_tokens: int,
topk_width: int,
kv_lora_rank: int,
qk_rope_head_dim: int,
sm_scale: float,
index_topk: int,
index_kpool: int,
) -> None:
from flashinfer.mla import BatchMLAPagedAttentionWrapper
self.workspace = torch.empty(_WORKSPACE_BYTES, dtype=torch.uint8, device=device)
self.device = device
self.num_heads = num_heads
self.kv_dtype = kv_dtype
self.max_tokens = max_tokens
self.topk_width = topk_width
self.kv_lora_rank = kv_lora_rank
self.qk_rope_head_dim = qk_rope_head_dim
self.sm_scale = sm_scale
self.index_topk = index_topk
self.index_kpool = max(index_kpool, 1)
# Largest valid count the convert kernel can produce for any context.
self.max_valid = min(self.index_topk + self.index_kpool - 1, topk_width)
# User-reserved buffers: with use_cuda_graph=True plan() refreshes
# these in place, so run()'s captured kernels always read them.
self.kv_indices = torch.zeros(
max_tokens * topk_width, dtype=torch.int32, device=device
)
self.kv_len_arr = torch.full(
(max_tokens,), topk_width, dtype=torch.int32, device=device
)
self.kv_indptr = torch.zeros(max_tokens + 1, dtype=torch.int32, device=device)
self.wrapper = BatchMLAPagedAttentionWrapper(
self.workspace,
qo_indptr=torch.zeros(max_tokens + 1, dtype=torch.int32, device=device),
kv_indptr=self.kv_indptr,
kv_indices=self.kv_indices,
kv_len_arr=self.kv_len_arr,
use_cuda_graph=True,
backend="fa3",
)
self._arange_cpu = torch.arange(self.max_tokens + 1, dtype=torch.int32)
self._qo_cpu = torch.empty(self.max_tokens + 1, dtype=torch.int32)
self._kv_cpu = torch.empty(self.max_tokens + 1, dtype=torch.int32)
self._lens_cpu = torch.full(
(self.max_tokens,), self.topk_width, dtype=torch.int32
)
# Planned per-work kv_end of the current plan, restored by each clamp;
# sized on first plan to the planner's work capacity.
self._saved_kv_end = torch.empty(0, dtype=torch.int32, device=device)
self._planned_num_tokens = -1
self._int_ws: torch.Tensor | None = None
self._plan_offsets: tuple[int, int, int, int] | None = None
def plan(
self,
num_tokens: int,
kv_lens: torch.Tensor,
cam: CommonAttentionMetadata | None,
req_id_per_token: torch.Tensor | None,
) -> None:
"""Plan per-row KV lengths (CPU int32, ``[num_tokens]``).
The wrapper bakes kv_len into its int schedule from host values, so
rows past their valid count would send the kernel into the -1 tail of
the converted index buffer. With ``cam`` and ``req_id_per_token``
(device batch layout), ``kv_lens`` only needs to upper-bound the
valid counts: the plan is padded by ``_PLAN_SLACK`` and reused while
the bound still fits, and every call clamps each work item's kv_end
on device to the exact count, so no D2H sync is needed. Without them
the lengths must be exact. Must run outside CUDA graph capture: the
in-place refreshed plan_info/indptr buffers are what captured runs
read.
"""
if torch.cuda.is_current_stream_capturing():
raise RuntimeError(
"FlashInferMLASparseSM90 plan() called inside CUDA graph "
"capture; lengths must be planned host-side before capture."
)
kv_lens = kv_lens.to(torch.int32)
if cam is None or req_id_per_token is None:
self._plan(num_tokens, kv_lens)
self._planned_num_tokens = -1
return
planned = self._lens_cpu[:num_tokens]
if num_tokens != self._planned_num_tokens or not bool(
((planned >= kv_lens) & (planned <= kv_lens + _PLAN_SLACK)).all()
):
self._plan(
num_tokens, torch.clamp(kv_lens + _PLAN_SLACK, max=self.max_valid)
)
self._planned_num_tokens = num_tokens
self._clamp_kv_end(cam, req_id_per_token)
def _plan(self, num_tokens: int, kv_lens: torch.Tensor) -> None:
# CPU staging buffers are filled in place: plan() runs per step
# (once per draft/verify metadata build), so per-call allocations and
# device round trips are on the hot path. Passing CPU tensors lets
# the wrapper's internal .to("cpu") no-op; its reserved-buffer
# copy_ then performs the single H2D transfer per tensor.
# use_cuda_graph=True makes the wrapper copy qo/kv indptr into its
# fixed (max_tokens+1)-sized buffers with exact-size copy_, so the
# indptr must always be full-size. Rows past num_tokens are padded
# empty (qo_indptr flat at num_tokens) — zero-query rows read no q
# and schedule no work. FlashInfer 0.7 requires packed CSR offsets
# matching the exact lengths, including zero-length padded rows.
torch.clamp(self._arange_cpu, max=num_tokens, out=self._qo_cpu)
self._lens_cpu.zero_()
self._lens_cpu[:num_tokens] = kv_lens
self._kv_cpu[0] = 0
torch.cumsum(self._lens_cpu, dim=0, out=self._kv_cpu[1:])
# Only the live prefix of kv_indices: the wrapper snapshots and
# copies whatever is passed.
num_indices = max(int(self._kv_cpu[-1]), 1)
self.wrapper.plan(
self._qo_cpu,
self._kv_cpu,
self.kv_indices[:num_indices],
self._lens_cpu,
self.num_heads,
self.kv_lora_rank, # head_dim_ckv
self.qk_rope_head_dim, # 0 (NoPE) or 64 (rope MLA)
1, # page_size: top-k slots are the page table
False, # causal: encoded by the indexer's selection
self.sm_scale,
q_data_type=torch.bfloat16,
kv_data_type=self.kv_dtype,
)
plan_info = [int(x) for x in self.wrapper._plan_info]
assert len(plan_info) == _PLAN_INFO_LEN, plan_info
# Per-work arrays are laid out back to back at the planner's capacity.
max_works = (plan_info[_PI_KV_INDPTR] - plan_info[_PI_Q_INDPTR]) // 4
if self._saved_kv_end.numel() != max_works:
self._saved_kv_end = torch.empty(
max_works, dtype=torch.int32, device=self.device
)
self._int_ws = self.wrapper._planned_backend._int_workspace_buffer.view(
torch.int32
)
self._plan_offsets = (
plan_info[_PI_WORK_INDPTR] // 4 + plan_info[_PI_NUM_BLKS_Y],
plan_info[_PI_Q_INDPTR] // 4,
plan_info[_PI_KV_START] // 4,
plan_info[_PI_KV_END] // 4,
)
kv_end_off = self._plan_offsets[3]
self._saved_kv_end.copy_(self._int_ws[kv_end_off : kv_end_off + max_works])
def _clamp_kv_end(
self, cam: CommonAttentionMetadata, req_id_per_token: torch.Tensor
) -> None:
assert self._int_ws is not None and self._plan_offsets is not None
block = 1024
_clamp_work_kv_end[(triton.cdiv(self._saved_kv_end.numel(), block),)](
self._int_ws,
self._saved_kv_end,
cam.seq_lens,
cam.query_start_loc,
req_id_per_token,
*self._plan_offsets,
TOPK=self.index_topk,
KPOOL=self.index_kpool,
BLOCK_SIZE=block,
)
def pack_indices(self, topk_slots: torch.Tensor) -> None:
num_tokens, width = topk_slots.shape
_pack_topk_indices[(num_tokens, triton.cdiv(width, 256))](
topk_slots, self.kv_indptr, self.kv_indices, width, 256
)
@dataclass
class FlashInferMLASparseSM90Metadata(FlashInferMLASparseMetadata):
state: _SM90State | None = None
class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
"""Reuse the common sparse metadata (req ids, topk buffer access)."""
metadata_cls = FlashInferMLASparseSM90Metadata
def __init__(
self,
kv_cache_spec: "AttentionSpec",
layer_names: list[str],
vllm_config: "VllmConfig",
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
attention_layer = vllm_config.compilation_config.static_forward_context[
layer_names[0]
]
self._attention_layer = attention_layer
impl = attention_layer.impl
if not isinstance(impl, FlashInferMLASparseSM90Impl):
raise TypeError(
"FlashInferMLASparseSM90Builder requires an SM90 FlashInfer "
f"implementation, got {type(impl).__name__}."
)
topk_indices_buffer = impl.topk_indices_buffer
assert topk_indices_buffer is not None
hf_config = vllm_config.model_config.hf_text_config
assert hf_config.index_topk is not None
# fp8 KV cache is stored as uint8; plan() needs the logical dtype.
kv_plan_dtype = (
torch.float8_e4m3fn
if kv_cache_spec.dtype == torch.uint8
else kv_cache_spec.dtype
)
self.state = _SM90State(
device,
impl.num_heads,
kv_plan_dtype,
vllm_config.scheduler_config.max_num_batched_tokens,
topk_indices_buffer.shape[1],
kv_lora_rank=impl.kv_lora_rank,
qk_rope_head_dim=impl.qk_rope_head_dim,
sm_scale=impl.scale,
index_topk=int(hf_config.index_topk),
index_kpool=int(getattr(hf_config, "index_kpool", 1) or 1),
)
spec_config = vllm_config.speculative_config
self._adaptive_verification = bool(
spec_config is not None and spec_config.enable_adaptive_verification
)
def _kv_lens_host(
self, cam: CommonAttentionMetadata
) -> tuple[int, torch.Tensor, bool]:
"""Host per-row KV lengths for the plan and whether they are exact.
A row for the j-th query token of request i attends
``seq_lens[i] - q_len[i] + j + 1`` tokens. The indexer's selection
then bounds the valid count: contexts up to ``index_topk`` select
everything (valid == context); longer contexts keep the top
``index_topk`` pool-expanded tokens plus the trailing incomplete
pool (valid == ``index_topk + context % index_kpool``). Both match
the count of non -1 entries the convert kernel produces.
With ``seq_lens_cpu_upper_bound`` (optimistic under async spec
decode) returns sync-free upper bounds, which the plan clamps on
device. Otherwise returns exact lengths via a D2H copy.
"""
num_reqs = cam.num_reqs
qsl = cam.query_start_loc_cpu[: num_reqs + 1]
num_rows = int(qsl[-1])
if num_rows == 0:
return 0, torch.zeros(0, dtype=torch.int32), True
state = self.state
sl_host = cam.seq_lens_cpu_upper_bound
if sl_host is None:
ctx = self._row_contexts(qsl, cam.seq_lens[:num_reqs].cpu())
topk, kpool = state.index_topk, state.index_kpool
lens = torch.where(ctx <= topk, ctx, topk + ctx % kpool)
return num_rows, lens.to(torch.int32), True
if self._adaptive_verification:
# The host query split may not match the device one, so bound
# every row by the longest request.
ctx = torch.full((num_rows,), int(sl_host[:num_reqs].max()))
else:
ctx = self._row_contexts(qsl, sl_host[:num_reqs])
return num_rows, torch.clamp(ctx, max=state.max_valid), False
@staticmethod
def _row_contexts(qsl: torch.Tensor, seq_lens: torch.Tensor) -> torch.Tensor:
num_reqs = qsl.shape[0] - 1
q_lens = (qsl[1:] - qsl[:-1]).to(torch.int64)
first_ctx = seq_lens.to(torch.int64) - q_lens + 1
req_of_row = torch.repeat_interleave(
torch.arange(num_reqs, dtype=torch.int64), q_lens
)
rows = torch.arange(int(qsl[-1]), dtype=torch.int64)
return first_ctx[req_of_row] + rows - qsl.to(torch.int64)[req_of_row]
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> FlashInferMLASparseSM90Metadata:
metadata = super().build(common_prefix_len, common_attn_metadata, fast_build)
assert isinstance(metadata, FlashInferMLASparseSM90Metadata)
# Plan outside any CUDA graph capture; captured runs read the
# refreshed buffers.
num_rows, kv_lens, exact = self._kv_lens_host(common_attn_metadata)
# MHA prefills are removed from q before forward_mqa. Plan only the
# decode prefix in that case, using the same routing decision as MLA.
if metadata.num_prefills > 0 and self._attention_layer._use_sparse_mha(
metadata
):
num_rows = metadata.num_decode_tokens
kv_lens = kv_lens[:num_rows]
if exact:
self.state.plan(num_rows, kv_lens, None, None)
else:
self.state.plan(
num_rows, kv_lens, common_attn_metadata, metadata.req_id_per_token
)
metadata.state = self.state
return metadata
class FlashInferMLASparseSM90Impl(SparseMLACommonImpl[FlashInferMLASparseSM90Metadata]):
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
topk_indices_buffer: torch.Tensor | None = None,
indexer: Any | None = None,
**mla_args: Any,
) -> None:
if any([alibi_slopes, sliding_window, logits_soft_cap]):
raise NotImplementedError(
"FlashInferMLASparseSM90Impl does not support alibi, sliding "
"window, or logits soft cap."
)
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
indexer=indexer,
topk_indices_buffer=topk_indices_buffer,
**mla_args,
)
assert self.topk_indices_buffer is not None
self.supports_quant_query_input = False
self.use_fp8_kv_cache = self.kv_cache_dtype in _FP8_KV_DTYPES
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashInferMLASparseSM90Metadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if not isinstance(q, tuple):
raise NotImplementedError(
"FlashInferMLASparseSM90Impl expects split (q_nope, q_rope)."
)
q_nope, q_rope = q
num_tokens = q_rope.shape[0]
# NoPE models hand a zero-width rope tensor through; rope MLA hands
# the real 64-dim part. The kernel takes both as-is.
q_pe = q_rope.reshape(num_tokens, self.num_heads, self.qk_rope_head_dim)
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[:num_tokens]
kv_c_and_k_pe_cache, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
# return_valid_counts=True keeps the compacted-prefix layout: valid
# entries at [0, valid_count), -1 past it — exactly the prefix the
# planned per-row lengths address.
topk_slots, _ = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[:num_tokens],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
state = attn_metadata.state
assert state is not None
# Pack valid prefixes at the offsets refreshed by plan() before replay.
state.pack_indices(topk_slots)
flat = (
kv_c_and_k_pe_cache.view(torch.float8_e4m3fn)
if self.use_fp8_kv_cache
else kv_c_and_k_pe_cache
).reshape(-1, 1, self.head_size)
ckv = flat[..., : self.kv_lora_rank]
kpe = flat[..., self.kv_lora_rank :]
scale_kwargs = (
{"ckv_scale": float(layer._k_scale_float or 1.0), "kpe_scale": 1.0}
if self.use_fp8_kv_cache
else {}
)
out = state.wrapper.run(q_nope, q_pe, ckv, kpe, **scale_kwargs)
return out, None
-352
View File
@@ -1,352 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import ClassVar
import torch
import vllm.envs as envs
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonDecodeMetadata,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
QueryLenSupport,
)
from vllm.platforms.interface import DeviceCapability
from vllm.utils.platform_utils import num_compute_units
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
AttentionType,
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
reshape_attn_output_for_spec_decode,
reshape_query_for_spec_decode,
)
from vllm.v1.attention.ops.flashmla import (
FlashMLASchedMeta,
flash_mla_with_kvcache,
flash_mla_with_kvcache_fp8,
get_mla_metadata,
get_mla_metadata_dense_fp8,
is_flashmla_dense_supported,
)
from vllm.v1.kv_cache_interface import AttentionSpec
logger = init_logger(__name__)
class FlashMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [64]
@staticmethod
def get_name() -> str:
return "FLASHMLA"
@staticmethod
def get_builder_cls() -> type["FlashMLAMetadataBuilder"]:
return FlashMLAMetadataBuilder
@staticmethod
def get_impl_cls() -> type["FlashMLAImpl"]:
return FlashMLAImpl
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major in [9, 10]
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
if use_sparse:
from vllm.v1.attention.ops.flashmla import is_flashmla_sparse_supported
return is_flashmla_sparse_supported()[1]
else:
from vllm.v1.attention.ops.flashmla import is_flashmla_dense_supported
return is_flashmla_dense_supported()[1]
@dataclass
class FlashMLADecodeMetadata(MLACommonDecodeMetadata):
scheduler_metadata: FlashMLASchedMeta
@dataclass
class FlashMLAMetadata(MLACommonMetadata[FlashMLADecodeMetadata]):
pass
class FlashMLAMetadataBuilder(MLACommonMetadataBuilder[FlashMLAMetadata]):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM
reorder_batch_threshold: int = 128 # process small prefills with decode pathway
# ^ TODO(matt): tune this
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
):
super().__init__(
kv_cache_spec, layer_names, vllm_config, device, FlashMLAMetadata
)
self.num_q_heads = vllm_config.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
self.cg_buf_tile_scheduler_metadata = None
self.cg_buf_num_splits = None
self.is_fp8_kvcache = is_quantized_kv_cache(
vllm_config.cache_config.cache_dtype
)
num_sms = num_compute_units(self.device.index)
if self.compilation_config.cudagraph_mode.has_full_cudagraphs():
self.cg_buf_tile_scheduler_metadata = torch.zeros(
# Upper bound on size (<= #SMs, TileSchedulerMetaDataSize)
# TileSchedulerMetaDataSize = 8
(num_sms, 8),
device=self.device,
dtype=torch.int32,
)
self.cg_buf_num_splits = torch.empty(
(vllm_config.scheduler_config.max_num_seqs + 1),
device=self.device,
dtype=torch.int32,
)
def _build_decode(
self,
block_table_tensor: torch.Tensor,
seq_lens_device: torch.Tensor,
max_seq_len: int,
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
max_query_len: int,
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> FlashMLADecodeMetadata:
query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1]
# we use the max but all should be the same due to uniform length requirement
max_query_len = query_lens_cpu.max().item()
num_q_heads = self.num_q_heads
if self.dcp_world_size > 1:
num_q_heads *= self.dcp_world_size
num_q_tokens_per_head_k = max_query_len * num_q_heads // 1
scheduler_metadata, _ = get_mla_metadata(
seq_lens_device,
num_q_tokens_per_head_k,
1, # MQA for the decode path
is_fp8_kvcache=self.is_fp8_kvcache,
)
if self.is_fp8_kvcache:
tile_scheduler_metadata, num_splits = get_mla_metadata_dense_fp8(
seq_lens_device,
num_q_tokens_per_head_k,
1, # MQA for the decode path
)
# Copy FP8 metadata into persistent CUDA graph buffers
if self.compilation_config.cudagraph_mode.has_full_cudagraphs():
assert self.cg_buf_tile_scheduler_metadata is not None
assert self.cg_buf_num_splits is not None
n = tile_scheduler_metadata.size(0)
assert n <= self.cg_buf_tile_scheduler_metadata.size(0)
self.cg_buf_tile_scheduler_metadata[:n].copy_(tile_scheduler_metadata)
tile_scheduler_metadata = self.cg_buf_tile_scheduler_metadata[:n]
n = num_splits.size(0)
assert n <= self.cg_buf_num_splits.size(0)
self.cg_buf_num_splits[:n].copy_(num_splits)
num_splits = self.cg_buf_num_splits[:n]
scheduler_metadata.tile_scheduler_metadata = tile_scheduler_metadata
scheduler_metadata.num_splits = num_splits
return FlashMLADecodeMetadata(
block_table=block_table_tensor,
seq_lens=seq_lens_device,
scheduler_metadata=scheduler_metadata,
dcp_tot_seq_lens=dcp_tot_seq_lens_device,
)
class FlashMLAImpl(MLACommonImpl[FlashMLAMetadata]):
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
is_supported, reason = is_flashmla_dense_supported()
assert is_supported, reason
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"FlashMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"FlashMLAImpl"
)
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
# TODO: (zyongye) decode function for mla here
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
if type(q) is tuple:
q = torch.cat(q, dim=-1)
# mypy assertion: q is now always a tensor
assert isinstance(q, torch.Tensor)
num_decodes = attn_metadata.num_decodes
q = reshape_query_for_spec_decode(q, num_decodes)
scheduler_metadata = attn_metadata.decode.scheduler_metadata
if envs.VLLM_BATCH_INVARIANT and not is_quantized_kv_cache(self.kv_cache_dtype):
device = q.device
dtype = torch.int32
B = q.shape[0]
# block_table shape: [batch_size, max_num_blocks_per_seq]
# The number of blocks per sequence is in the second dimension
topk = attn_metadata.decode.block_table.shape[-1]
B_TOPK = 64
assert topk % B_TOPK == 0, f"topk ({topk}) must be divisible by {B_TOPK}"
end_block_idx = topk // B_TOPK
# Single partition => num_sm_parts = 1
# TileSchedulerMetaDataSize = 8, layout:
# [begin_idx, begin_block_idx, end_idx, end_block_idx,
# begin_n_split_idx, _, _, _]
tile_scheduler_metadata = torch.zeros((1, 8), dtype=dtype, device=device)
tile_scheduler_metadata[0, 0] = 0 # begin_idx
tile_scheduler_metadata[0, 1] = 0 # sched_begin_block_idx
tile_scheduler_metadata[0, 2] = B - 1 # end_idx
tile_scheduler_metadata[0, 3] = end_block_idx
tile_scheduler_metadata[0, 4] = 0 # begin_n_split_idx
# fields [5..7] stay 0
# Non-split path ignores num_splits, but the API requires it:
# zeros of length B+1
num_splits = torch.zeros((B + 1,), dtype=dtype, device=device)
scheduler_metadata.tile_scheduler_metadata = tile_scheduler_metadata
scheduler_metadata.num_splits = num_splits
if is_quantized_kv_cache(self.kv_cache_dtype):
o, lse = flash_mla_with_kvcache_fp8(
q=q,
k_cache=kv_c_and_k_pe_cache.unsqueeze(-2), # Add head dim of 1
block_table=attn_metadata.decode.block_table,
cache_seqlens=attn_metadata.decode.seq_lens,
head_dim_v=self.kv_lora_rank,
tile_scheduler_metadata=scheduler_metadata.tile_scheduler_metadata,
num_splits=scheduler_metadata.num_splits,
softmax_scale=self.scale,
causal=True,
descale_q=layer._q_scale.reshape(1),
descale_k=layer._k_scale.reshape(1),
)
else:
o, lse = flash_mla_with_kvcache(
q=q,
k_cache=kv_c_and_k_pe_cache.unsqueeze(-2), # Add head dim of 1
block_table=attn_metadata.decode.block_table,
cache_seqlens=attn_metadata.decode.seq_lens,
head_dim_v=self.kv_lora_rank,
tile_scheduler_metadata=scheduler_metadata,
softmax_scale=self.scale,
causal=True,
is_fp8_kvcache=False,
)
o = reshape_attn_output_for_spec_decode(o)
if self.need_to_return_lse_for_decode:
# FlashMLA returns LSE as [batch, heads, seq_len]; the DCP reducer
# consumes [tokens, heads]. Flattening matters under spec-decode,
# where seq_len > 1. Only DCP consumes lse, so skip the copy
# otherwise.
num_decodes, q_num_heads, seq_len = lse.shape
lse = (
lse.permute(0, 2, 1)
.reshape(num_decodes * seq_len, q_num_heads)
.contiguous()
)
return o, lse
File diff suppressed because it is too large Load Diff
@@ -1,407 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import torch
from vllm import _custom_ops as ops
from vllm.config import VllmConfig
from vllm.forward_context import in_piecewise_cudagraph
from vllm.utils.torch_utils import current_stream
from vllm.v1.attention.backend import max_decode_query_len
from vllm.v1.attention.backends.mla.sparse_utils import (
triton_convert_req_index_to_global_index,
)
from vllm.v1.hisparse.runtime import (
FP8_DS_MLA_ROW_BYTES,
HiSparseCacheHandle,
HiSparsePrefillStagingPlan,
create_hisparse_cache_handle,
)
def _create_side_stream(device: torch.device) -> torch.Stream:
return torch.Stream(device=device)
def _create_event() -> torch.Event:
return torch.Event()
@dataclass
class SparseMLAIndexGroup:
"""Layers that consume one sparse-indexer result."""
logical_topk_indices: torch.Tensor
physical_topk_indices: torch.Tensor
valid_topk_counts: torch.Tensor
side_stream: torch.Stream
logical_topk_ready: torch.Event
physical_topk_ready: torch.Event
has_indexer: bool
num_layers: int = 0
def register_layer(
self,
vllm_config: VllmConfig | None = None,
*,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> int:
layer_index = self.num_layers
self.num_layers += 1
return layer_index
def set_logical_topk_ready(self, layer_index: int) -> None:
if layer_index != 0 or not self.has_indexer:
return
# In piecewise cudagraph mode the consumer converts on the side stream
# from an eager break; an event recorded inside a captured segment is
# graph-local and any eager wait on it raises cudaErrorInvalidValue.
# The convert side falls back to wait_stream there instead (and never
# touches this event), so skip the record as well.
if in_piecewise_cudagraph():
return
self.logical_topk_ready.record(current_stream())
def prepare_for_batch(self, layer_index: int, attn_metadata: Any | None) -> None:
pass
def gather_fp8_prefill(
self,
layer_index: int,
source_cache: torch.Tensor,
dst: torch.Tensor,
block_table: torch.Tensor,
workspace_starts: torch.Tensor,
batch_size: int,
attn_metadata: Any,
request_start: int,
) -> torch.Event | None:
ops.cp_gather_and_upconvert_fp8_kv_cache(
source_cache,
dst,
block_table,
workspace_starts,
batch_size,
)
return None
def convert_logical_to_physical_topk(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
attn_metadata: Any,
*,
block_stride_rows: int | None,
return_valid_counts: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Convert one index result once for all layers in this group."""
return self._convert_once(
layer_index,
logical_topk_indices,
attn_metadata.req_id_per_token[: logical_topk_indices.shape[0]],
attn_metadata.block_table,
attn_metadata.block_size,
block_stride_rows=block_stride_rows,
return_valid_counts=return_valid_counts,
)
def _convert_once(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
req_id_per_token: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
*,
block_stride_rows: int | None,
return_valid_counts: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
num_tokens = logical_topk_indices.shape[0]
if num_tokens > self.physical_topk_indices.shape[0]:
return triton_convert_req_index_to_global_index(
req_id_per_token,
block_table,
logical_topk_indices,
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=logical_topk_indices.shape[1],
return_valid_counts=return_valid_counts,
)
physical_topk_indices = self.physical_topk_indices[:num_tokens]
valid_topk_counts = self.valid_topk_counts[:num_tokens]
compute_stream = current_stream()
if layer_index == 0:
if self.has_indexer and not in_piecewise_cudagraph():
self.side_stream.wait_event(self.logical_topk_ready)
else:
self.side_stream.wait_stream(compute_stream)
with self.side_stream:
triton_convert_req_index_to_global_index(
req_id_per_token,
block_table,
logical_topk_indices,
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=logical_topk_indices.shape[1],
return_valid_counts=return_valid_counts,
out=physical_topk_indices,
valid_counts_out=(
valid_topk_counts if return_valid_counts else None
),
)
self.physical_topk_ready.record(self.side_stream)
compute_stream.wait_event(self.physical_topk_ready)
if return_valid_counts:
return physical_topk_indices, valid_topk_counts
return physical_topk_indices
@dataclass
class HiSparseMLAIndexGroup(SparseMLAIndexGroup):
"""Sparse index group with per-layer host-backed KV caches."""
caches: list[HiSparseCacheHandle] = field(default_factory=list)
hisparse_group: Any | None = None
prefill_stream: torch.Stream | None = None
prefill_ready_events: list[torch.Event] = field(default_factory=list)
def register_layer(
self,
vllm_config: VllmConfig | None = None,
*,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> int:
assert vllm_config is not None
assert head_size is not None
assert kv_cache_dtype is not None
layer_index = super().register_layer()
if self.prefill_stream is None:
self.prefill_stream = _create_side_stream(self.logical_topk_indices.device)
if kv_cache_dtype == "fp8_ds_mla":
row_width = FP8_DS_MLA_ROW_BYTES
kv_dtype = torch.uint8
else:
from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype
row_width = head_size
kv_dtype = kv_cache_dtype_str_to_dtype(
kv_cache_dtype, vllm_config.model_config
)
cache = create_hisparse_cache_handle(
vllm_config,
self.logical_topk_indices.shape[1],
is_index_group_leader=layer_index == 0,
row_width=row_width,
kv_dtype=kv_dtype,
index_group=self,
)
assert cache is not None
self.caches.append(cache)
cache.index_group_caches = self.caches
self.prefill_ready_events.append(_create_event())
return layer_index
def cache(self, layer_index: int) -> HiSparseCacheHandle:
return self.caches[layer_index]
def physical_kv_cache(self, layer_index: int) -> torch.Tensor:
cache = self.cache(layer_index)
return cache.runtime.hot.attention_cache
def prepare_for_batch(self, layer_index: int, attn_metadata: Any | None) -> None:
if layer_index == 0:
self.cache(0).prepare_group_for_batch(attn_metadata)
def convert_logical_to_physical_topk(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
attn_metadata: Any,
*,
block_stride_rows: int | None,
return_valid_counts: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
cache = self.cache(layer_index)
num_tokens = logical_topk_indices.shape[0]
req_id_per_token = attn_metadata.req_id_per_token[:num_tokens]
if num_tokens > cache.runtime.max_swap_rows or (
cache.all_context_pages_resident
and cache.num_decode_tokens < cache.num_actual_tokens
):
# Prefill-sized batches do not fit the decode residency workspace.
# Non-resident prefills are staged before reaching this path.
assert cache.all_context_pages_resident
leader = self.cache(0)
assert leader.view is not None and leader.block_table is not None
return self._convert_once(
layer_index,
logical_topk_indices,
req_id_per_token,
leader.batch_block_table(),
leader.view.block_size,
block_stride_rows=leader.view.attention_block_stride,
return_valid_counts=return_valid_counts,
)
source_block_table = cache.source_block_table
assert source_block_table is not None
return cache.swap_in(
req_id_per_token,
block_table=source_block_table,
logical_topk_indices=logical_topk_indices,
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
num_valid_rows=attn_metadata.query_start_loc[-1:],
)
def stage_prefill_rows(
self, layer_index: int, kv_cache: torch.Tensor, attn_metadata: Any
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
cache = self.cache(layer_index)
prefill = attn_metadata.prefill
staging_plan = prefill.host_staging_plan if prefill is not None else None
assert staging_plan is not None
resident_cache = None
if cache.view is not None and cache.block_table is not None:
state_indices = cache.runtime.request_state_indices
assert state_indices is not None
staging_plan.ensure_gpu_sources(
cache.block_table,
state_indices[attn_metadata.num_decodes :],
cache.view.block_size,
)
resident_cache = cache.view.cache
staged_cache = cache.runtime.gather_prefill_cache(
kv_cache,
staging_plan,
resident_cache=resident_cache,
)
req_ids = attn_metadata.req_id_per_token[attn_metadata.num_decode_tokens :]
if attn_metadata.num_decodes > 0:
req_ids = req_ids - attn_metadata.num_decodes
return staged_cache, staging_plan.block_table, req_ids
def _prefill_gather_plan(
self, layer_index: int, attn_metadata: Any
) -> HiSparsePrefillStagingPlan:
cache = self.cache(layer_index)
prefill = attn_metadata.prefill
plan = prefill.host_staging_plan if prefill is not None else None
assert plan is not None
assert cache.view is not None and cache.block_table is not None
state_indices = cache.runtime.request_state_indices
assert state_indices is not None
plan.ensure_gpu_sources(
cache.block_table,
state_indices[attn_metadata.num_decodes :],
cache.view.block_size,
)
assert plan.gpu_row_ids is not None
return plan
def gather_fp8_prefill(
self,
layer_index: int,
source_cache: torch.Tensor,
dst: torch.Tensor,
block_table: torch.Tensor,
workspace_starts: torch.Tensor,
batch_size: int,
attn_metadata: Any,
request_start: int,
) -> torch.Event | None:
cache = self.cache(layer_index)
plan = self._prefill_gather_plan(layer_index, attn_metadata)
assert cache.view is not None and plan.gpu_row_ids is not None
row_width = source_cache.shape[-1]
prefill_stream = self.prefill_stream
assert prefill_stream is not None
block_table = plan.block_table[request_start : request_start + batch_size]
prefill_stream.wait_stream(current_stream())
with prefill_stream:
ops.cp_gather_and_upconvert_fp8_kv_cache(
cache.view.cache,
dst,
block_table,
workspace_starts,
batch_size,
host_cache=source_cache.view(-1, row_width),
host_row_ids=plan.row_ids,
device_row_ids=plan.gpu_row_ids,
)
ready = self.prefill_ready_events[layer_index]
ready.record(prefill_stream)
return ready
class SparseMLAIndexGroupBuilder:
"""Assign sparse MLA layers to their index-producing layer."""
def __init__(
self, logical_topk_indices: torch.Tensor, max_decode_rows: int | None = None
) -> None:
self.logical_topk_indices = logical_topk_indices
self.max_decode_rows = (
logical_topk_indices.shape[0]
if max_decode_rows is None
else max_decode_rows
)
self.current_group: SparseMLAIndexGroup | None = None
def register_layer(
self,
is_index_producing_layer: bool,
vllm_config: VllmConfig | None = None,
*,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> tuple[SparseMLAIndexGroup, int]:
if is_index_producing_layer or self.current_group is None:
group_cls = (
HiSparseMLAIndexGroup
if vllm_config is not None
and vllm_config.attention_config.hisparse_config is not None
else SparseMLAIndexGroup
)
workspace_rows = self.max_decode_rows
physical_topk_indices = torch.empty(
(workspace_rows + 1, self.logical_topk_indices.shape[1]),
dtype=self.logical_topk_indices.dtype,
device=self.logical_topk_indices.device,
)
self.current_group = group_cls(
logical_topk_indices=self.logical_topk_indices,
physical_topk_indices=physical_topk_indices,
valid_topk_counts=torch.empty(
workspace_rows + 1,
dtype=torch.int32,
device=self.logical_topk_indices.device,
),
side_stream=_create_side_stream(self.logical_topk_indices.device),
logical_topk_ready=_create_event(),
physical_topk_ready=_create_event(),
has_indexer=is_index_producing_layer,
)
group = self.current_group
group_index = group.register_layer(
vllm_config,
head_size=head_size,
kv_cache_dtype=kv_cache_dtype,
)
return group, group_index
def get_sparse_mla_index_group_max_rows(vllm_config: VllmConfig) -> int:
scheduler_config = vllm_config.scheduler_config
return min(
scheduler_config.max_num_batched_tokens,
scheduler_config.max_num_seqs * max_decode_query_len(vllm_config),
)
File diff suppressed because it is too large Load Diff
@@ -1,140 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""AITER FlashAttention backend for MLA prefill (ROCm).
This backend calls ``aiter.flash_attn_varlen_func`` directly, which natively
supports different q/k and v head dims (qk headdim 192, v headdim 128) without
padding V, and dispatches to the fast ``aiter::fmha_fwd_`` kernel on
gfx942/gfx950 (fp16/bf16).
"""
from typing import TYPE_CHECKING
import torch
import vllm.envs as envs
from vllm.platforms import current_platform
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonPrefillMetadata,
)
from vllm.platforms.interface import DeviceCapability
class AiterFlashAttnPrefillBackend(MLAPrefillBackend):
"""AITER FlashAttention backend for MLA prefill."""
@staticmethod
def get_name() -> str:
return "ROCM_AITER_FA"
@classmethod
def supports_compute_capability(
cls,
device_capability: "DeviceCapability | None",
) -> bool:
if not current_platform.is_rocm():
return False
from vllm.platforms.rocm import on_mi3xx
return on_mi3xx()
@classmethod
def is_available(cls) -> bool:
from vllm._aiter_ops import rocm_aiter_ops
return rocm_aiter_ops.is_enabled()
@classmethod
def validate_configuration(cls, device_capability, selector_config):
invalid_reasons = super().validate_configuration(
device_capability, selector_config
)
if envs.VLLM_BATCH_INVARIANT:
invalid_reasons.append("batch invariance not supported")
return invalid_reasons
def __init__(
self,
num_heads: int,
scale: float,
kv_lora_rank: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
vllm_config: "VllmConfig",
) -> None:
super().__init__(
num_heads=num_heads,
scale=scale,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
vllm_config=vllm_config,
)
from aiter import flash_attn_varlen_func
self.flash_attn_varlen_func = flash_attn_varlen_func
def run_prefill_new_tokens(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
assert output_scale is None, (
"AiterFlashAttnPrefillBackend does not support fused quantized output."
)
result = self.flash_attn_varlen_func(
q=q,
k=k,
v=v,
cu_seqlens_q=self._prefill_metadata.query_start_loc,
cu_seqlens_k=self._prefill_metadata.query_start_loc,
max_seqlen_q=self._prefill_metadata.max_query_len,
max_seqlen_k=self._prefill_metadata.max_query_len,
softmax_scale=self.scale,
causal=True,
return_lse=return_softmax_lse,
out=out,
)
# aiter returns the bare output tensor when return_lse is False, and
# (out, softmax_lse) when it is True.
if return_softmax_lse:
return result[0], result[1]
return result
def run_prefill_context_chunk(
self,
chunk: "MLACommonPrefillMetadata.ContextChunk",
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
assert out is None, (
"AiterFlashAttnPrefillBackend does not report supports_out(), so it "
"is never given a context-chunk `out` to write into."
)
out, lse = self.flash_attn_varlen_func(
q=q,
k=k,
v=v,
cu_seqlens_q=chunk.query_start_loc,
cu_seqlens_k=chunk.cu_seq_lens,
max_seqlen_q=chunk.max_query_len,
max_seqlen_k=chunk.max_seq_len,
softmax_scale=self.scale,
causal=False,
return_lse=True,
)
return out, lse
@@ -1,137 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU MLA prefill backend implemented with dense per-request attention.
This backend is selected on CPU devices, where flash-attn is unavailable. It
computes MLA prefill attention by slicing the ragged (varlen) q/k/v tensors
per request and evaluating dense attention in PyTorch.
"""
from typing import TYPE_CHECKING
import torch
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
if TYPE_CHECKING:
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonPrefillMetadata,
)
class CPUSDPAMLAPrefillBackend(MLAPrefillBackend):
"""MLA prefill backend for CPU using dense PyTorch attention.
flash-attn is not installable on CPU, so this backend provides an
equivalent prefill implementation using per-request dense attention.
"""
@staticmethod
def get_name() -> str:
return "CPU_SDPA_MLA"
@classmethod
def is_available(cls) -> bool:
# SDPA is always available on CPU.
return True
def supports_out(self) -> bool:
return True
def _ragged_sdpa(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q_cu_seq_lens: torch.Tensor,
kv_cu_seq_lens: torch.Tensor,
causal: bool,
return_softmax_lse: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
# q/k/v: [num_tokens, num_heads, head_dim] (ragged, concatenated).
# q_cu_seq_lens/kv_cu_seq_lens: [num_reqs + 1] row offsets for each
# request's query and key/value tokens.
num_reqs = q_cu_seq_lens.numel() - 1
assert num_reqs == kv_cu_seq_lens.numel() - 1
out_chunks: list[torch.Tensor] = []
lse_chunks: list[torch.Tensor] = []
for r in range(num_reqs):
q_start = int(q_cu_seq_lens[r])
q_end = int(q_cu_seq_lens[r + 1])
kv_start = int(kv_cu_seq_lens[r])
kv_end = int(kv_cu_seq_lens[r + 1])
q_r = q[q_start:q_end].transpose(0, 1).float() # [NH, Sq, Hq]
k_r = k[kv_start:kv_end].transpose(0, 1).float() # [NH, Sk, Hq]
v_r = v[kv_start:kv_end].transpose(0, 1).float() # [NH, Sk, Hv]
attn_scores = torch.matmul(q_r, k_r.transpose(-2, -1)) * self.scale
if causal:
causal_mask = torch.ones(
(q_end - q_start, kv_end - kv_start),
dtype=torch.bool,
device=attn_scores.device,
).triu(1)
attn_scores.masked_fill_(causal_mask.unsqueeze(0), float("-inf"))
attn_probs = torch.softmax(attn_scores, dim=-1, dtype=torch.float32)
out_r = torch.matmul(attn_probs, v_r).transpose(0, 1).to(v.dtype)
out_chunks.append(out_r) # [Sq, NH, Hv]
if return_softmax_lse:
lse_chunks.append(torch.logsumexp(attn_scores, dim=-1))
out = torch.cat(out_chunks, dim=0)
if not return_softmax_lse:
return out
lse = torch.cat(lse_chunks, dim=1)
return out, lse
def run_prefill_new_tokens(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
assert output_scale is None, (
"CPU MLA prefill backend does not support fused FP8 output"
)
out_t = self._ragged_sdpa(
q,
k,
v,
self._prefill_metadata.query_start_loc,
self._prefill_metadata.query_start_loc,
causal=True,
return_softmax_lse=return_softmax_lse,
)
if out is not None and not return_softmax_lse:
assert isinstance(out_t, torch.Tensor)
out.copy_(out_t)
return out
return out_t
def run_prefill_context_chunk(
self,
chunk: "MLACommonPrefillMetadata.ContextChunk",
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
assert out is None, "CPU MLA context prefill does not support in-place output"
result = self._ragged_sdpa(
q,
k,
v,
chunk.query_start_loc,
chunk.cu_seq_lens,
causal=False,
return_softmax_lse=True,
)
assert isinstance(result, tuple)
out, lse = result
return out, lse
@@ -1,510 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""FlashAttention backend for MLA prefill."""
import functools
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
import torch
import vllm.envs as envs
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8StaticTensorSym,
)
from vllm.model_executor.warmup.jit_warmup import VllmJitKernel, zip_inputs
from vllm.platforms import current_platform
from vllm.v1.attention.backends.fa_utils import (
compile_flash_attn_varlen_func_from_specs,
get_flash_attn_version,
is_flash_attn_varlen_func_available,
)
from vllm.v1.attention.backends.mla.prefill.base import (
MLADimensions,
MLAPrefillBackend,
)
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonPrefillMetadata,
MLADims,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
if is_flash_attn_varlen_func_available():
from vllm.v1.attention.backends.fa_utils import flash_attn_varlen_func
else:
flash_attn_varlen_func = None # type: ignore[assignment]
FA4_STANDARD_DTYPES = (torch.bfloat16, torch.float16)
# Current vLLM MLA prefill expands K/V to num_heads before FA4, so this plan
# covers qhead_per_kvhead=1. Batch is not a current FA4 MLA-prefill key field.
# Use b1 for compile-only specs because it is the conservative case for
# Split-KV shape heuristics.
# TODO(roberto): FA4 also has direct-GQA and qv/top-k absorbed-MLA paths, but
# vLLM does not use them in this backend yet; they need a separate
# num_kv_heads/qv/top-k-aware warmup plan if wired in later.
FA4_MLA_PREFILL_COMPILE_BATCH_SIZE = 1
FA4_MLA_PREFILL_Q_TILE = 128
FA4_MLA_PREFILL_K_TILE = 128
FA4_MLA_PREFILL_LONG_K_BLOCKS = 32
FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS = 64
FA4_MLA_PREFILL_CAUSAL_OPTIONS = (False, True)
FA4_MLA_PREFILL_LSE_OPTIONS = (False, True)
class FA4MLAPrefillKernel(VllmJitKernel["FA4MLAPrefillKernel.CompileKey"]):
"""FA4 MLA prefill compile-key wrapper used by generic JIT warmup."""
@dataclass(frozen=True)
class CompileKey:
"""High-level FA4 compile-only key used by vLLM warmup.
This is not the CuTeDSL cache key. FA4 owns the selector that maps these
serving inputs to the actual compile-static fields: tile sizes, q_stage,
Split-KV, scheduler choice, layout-presence booleans, dtype/head dims,
arch, and related fields.
"""
q_shape: tuple[int, ...]
k_shape: tuple[int, ...]
v_shape: tuple[int, ...]
q_dtype: torch.dtype
max_seqlen_q: int
max_seqlen_k: int
softmax_scale: float
causal: bool
fa_version: int
v_stride: tuple[int, ...] | None = None
cu_seqlens_q_shape: tuple[int, ...] | None = None
cu_seqlens_k_shape: tuple[int, ...] | None = None
window_size: tuple[int, int] | None = None
return_softmax_lse: bool = False
num_splits: int = 0
@staticmethod
def kernel(
*args: Any,
runtime_kernel: Callable[..., Any] | None = None,
**kwargs: Any,
) -> Any:
kernel = flash_attn_varlen_func if runtime_kernel is None else runtime_kernel
assert kernel is not None
return kernel(*args, **kwargs)
def dispatch( # type: ignore[override]
self,
*,
batch_size: int,
dtype: torch.dtype,
num_heads: int,
mla_dims: "MLADims",
max_seqlen_q: int,
max_seqlen_k: int,
requires_v_padding: bool,
causal: bool,
fa_version: int,
window_size: tuple[int, int] | None = None,
return_lse: bool = False,
num_splits: int = 0,
) -> CompileKey:
return self.CompileKey(
q_shape=(
batch_size * max_seqlen_q,
num_heads,
mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim,
),
k_shape=(
batch_size * max_seqlen_k,
num_heads,
mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim,
),
v_shape=(
batch_size * max_seqlen_k,
num_heads,
(
mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim
if requires_v_padding
else mla_dims.v_head_dim
),
),
q_dtype=dtype,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
softmax_scale=(mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim)
** -0.5,
causal=causal,
fa_version=fa_version,
v_stride=(
None
if requires_v_padding
else (
num_heads * (mla_dims.qk_nope_head_dim + mla_dims.v_head_dim),
mla_dims.qk_nope_head_dim + mla_dims.v_head_dim,
1,
)
),
cu_seqlens_q_shape=(batch_size + 1,),
cu_seqlens_k_shape=(batch_size + 1,),
window_size=window_size,
return_softmax_lse=return_lse,
num_splits=num_splits,
)
def _is_valid_warmup_shape_probe(
self,
*,
max_seqlen_k: int,
num_splits: int,
is_sm90: bool,
qk_head_dim: int,
effective_v_head_dim: int,
) -> bool:
long_k = FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE
very_long_k = FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE
return (
max_seqlen_k < long_k
or (num_splits != 1 and max_seqlen_k == long_k)
or (
num_splits != 1
and max_seqlen_k == very_long_k
and not is_sm90
and qk_head_dim != effective_v_head_dim
)
)
def get_warmup_keys(self, vllm_config: "VllmConfig") -> list[CompileKey]:
from vllm.model_executor.layers.attention.mla_attention import (
get_mla_dims,
)
mla_dims = get_mla_dims(vllm_config.model_config)
qk_head_dim = mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim
fa_version = get_flash_attn_version(head_size=qk_head_dim)
if fa_version != 4:
return []
dtype = vllm_config.model_config.dtype
if dtype not in FA4_STANDARD_DTYPES:
dtype = torch.bfloat16
is_sm90 = current_platform.is_device_capability(90)
is_sm100_family = current_platform.is_device_capability_family(100)
is_sm120 = current_platform.is_device_capability_family(120)
if not (is_sm90 or is_sm100_family or is_sm120):
return []
num_splits = 1 if envs.VLLM_BATCH_INVARIANT else 0
if is_sm120 and num_splits != 1:
return []
num_heads = vllm_config.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
if num_heads <= 0:
return []
requires_v_padding = False
effective_v_head_dim = (
qk_head_dim if requires_v_padding else mla_dims.v_head_dim
)
shape_probes = (
dict(max_seqlen_q=1, max_seqlen_k=FA4_MLA_PREFILL_K_TILE),
dict(
max_seqlen_q=FA4_MLA_PREFILL_Q_TILE + 1,
max_seqlen_k=4 * FA4_MLA_PREFILL_K_TILE,
),
dict(
max_seqlen_q=1,
max_seqlen_k=FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE,
),
dict(
max_seqlen_q=FA4_MLA_PREFILL_Q_TILE + 1,
max_seqlen_k=FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE,
),
dict(
max_seqlen_q=1,
max_seqlen_k=FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS
* FA4_MLA_PREFILL_K_TILE,
),
dict(
max_seqlen_q=FA4_MLA_PREFILL_Q_TILE + 1,
max_seqlen_k=FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS
* FA4_MLA_PREFILL_K_TILE,
),
)
return self._trace_dispatch(self.dispatch)(
zip_inputs(*shape_probes),
batch_size=FA4_MLA_PREFILL_COMPILE_BATCH_SIZE,
dtype=dtype,
num_heads=num_heads,
mla_dims=mla_dims,
requires_v_padding=requires_v_padding,
is_sm90=is_sm90,
qk_head_dim=qk_head_dim,
effective_v_head_dim=effective_v_head_dim,
causal=FA4_MLA_PREFILL_CAUSAL_OPTIONS,
return_lse=FA4_MLA_PREFILL_LSE_OPTIONS,
num_splits=num_splits,
fa_version=fa_version,
_when=self._is_valid_warmup_shape_probe,
)
def compile(self, compile_key: CompileKey) -> None:
assert compile_flash_attn_varlen_func_from_specs is not None
window_size = (
list(compile_key.window_size)
if compile_key.window_size is not None
else None
)
compile_flash_attn_varlen_func_from_specs(
q_shape=compile_key.q_shape,
k_shape=compile_key.k_shape,
v_shape=compile_key.v_shape,
q_dtype=compile_key.q_dtype,
v_stride=compile_key.v_stride,
cu_seqlens_q_shape=compile_key.cu_seqlens_q_shape,
cu_seqlens_k_shape=compile_key.cu_seqlens_k_shape,
max_seqlen_q=compile_key.max_seqlen_q,
max_seqlen_k=compile_key.max_seqlen_k,
softmax_scale=compile_key.softmax_scale,
causal=compile_key.causal,
window_size=window_size,
return_softmax_lse=compile_key.return_softmax_lse,
fa_version=compile_key.fa_version,
num_splits=compile_key.num_splits,
)
def __call__(
self,
*,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
runtime_kernel: Callable[..., Any] | None = None,
**kwargs: Any,
) -> Any:
return self.kernel(
q=q,
k=k,
v=v,
runtime_kernel=runtime_kernel,
**kwargs,
)
class FlashAttnPrefillBackend(MLAPrefillBackend):
"""FlashAttention backend for MLA prefill."""
@staticmethod
def get_name() -> str:
return "FLASH_ATTN"
@classmethod
def is_available(cls) -> bool:
return is_flash_attn_varlen_func_available()
@classmethod
def supports_mla_dimensions(cls, mla_dimensions: MLADimensions) -> bool:
return mla_dimensions in [
MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
MLADimensions(
qk_nope_head_dim=192,
qk_rope_head_dim=64,
v_head_dim=256,
),
MLADimensions(
qk_nope_head_dim=64,
qk_rope_head_dim=64,
v_head_dim=128,
),
# GLM5Next NoPE layout: qk_head_dim 256 + 0 and v_head_dim 256 run
# the same kernels as the (192, 64, 256) DeepSeek-V3.2 layout.
MLADimensions(
qk_nope_head_dim=256,
qk_rope_head_dim=0,
v_head_dim=256,
),
]
def __init__(
self,
num_heads: int,
scale: float,
kv_lora_rank: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
vllm_config: "VllmConfig",
) -> None:
super().__init__(
num_heads=num_heads,
scale=scale,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
vllm_config=vllm_config,
)
# Handle the differences between the flash_attn_varlen from
# flash_attn and the one from vllm_flash_attn
assert flash_attn_varlen_func is not None, (
"FlashAttnPrefillBackend requires flash_attn_varlen_func. "
"Ensure FlashAttnPrefillBackend.is_available() is checked first."
)
qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
self.flash_attn_varlen_func = flash_attn_varlen_func
self.vllm_flash_attn_version = get_flash_attn_version(
head_size=qk_head_dim, head_size_v=v_head_dim
)
if self.vllm_flash_attn_version is not None:
self.flash_attn_varlen_func = functools.partial(
flash_attn_varlen_func, fa_version=self.vllm_flash_attn_version
)
if (
vllm_config.kernel_config.enable_jit_warmup
and self.vllm_flash_attn_version == 4
):
_FA4_MLA_PREFILL_KERNEL.register_warmup()
# Determine if we need to pad V
# For MLA the v head dim is smaller than qk head dim so we pad out
# v with 0s to match the qk head dim for attention backends that do
# not support different headdims.
# FA3 on Hopper (SM90) and FA4 natively handle diff headdims.
device_capability = current_platform.get_device_capability()
self.requires_v_padding = self.vllm_flash_attn_version is None or not (
(
self.vllm_flash_attn_version == 3
and device_capability is not None
and device_capability[0] == 9
)
or self.vllm_flash_attn_version == 4
)
# Track whether we're using vllm's FA or upstream (for ROCm)
self._is_vllm_fa = current_platform.is_cuda() or current_platform.is_xpu()
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
device_capability = current_platform.get_device_capability()
return (
self.vllm_flash_attn_version == 4
and self._is_vllm_fa
and device_capability is not None
and device_capability[0] in (10, 11)
and quant_key == kFp8StaticTensorSym
)
def _flash_attn_varlen_diff_headdims(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool = False,
softmax_scale: float | None = None,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
maybe_padded_v = v
if self.requires_v_padding:
maybe_padded_v = torch.nn.functional.pad(
v, [0, q.shape[-1] - v.shape[-1]], value=0
)
if self._is_vllm_fa:
kwargs["return_softmax_lse"] = return_softmax_lse
kwargs["out"] = out
kwargs["output_scale"] = output_scale
if envs.VLLM_BATCH_INVARIANT:
kwargs["num_splits"] = 1
else:
# ROCm leverages the upstream flash_attn, which takes a parameter
# called "return_attn_probs" instead of return_softmax_lse
kwargs["return_attn_probs"] = return_softmax_lse
assert out is None and output_scale is None
attn_out = _FA4_MLA_PREFILL_KERNEL(
q=q,
k=k,
v=maybe_padded_v,
runtime_kernel=self.flash_attn_varlen_func,
softmax_scale=softmax_scale,
**kwargs,
)
# Unpack the output if there are multiple results
lse = None
if isinstance(attn_out, tuple):
attn_out, lse = attn_out[0], attn_out[1]
# Remain consistent with old `flash_attn_varlen_func` where there
# is only one output tensor if `return_softmax_lse` is False.
if return_softmax_lse:
return attn_out, lse
return attn_out
def supports_out(self) -> bool:
# A padded V produces a qk_head_dim output that cannot be written into
# a v_head_dim `out`; only the unpadded path honors `out`.
return not self.requires_v_padding
def run_prefill_new_tokens(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
return self._flash_attn_varlen_diff_headdims(
q=q,
k=k,
v=v,
cu_seqlens_q=self._prefill_metadata.query_start_loc,
cu_seqlens_k=self._prefill_metadata.query_start_loc,
max_seqlen_q=self._prefill_metadata.max_query_len,
max_seqlen_k=self._prefill_metadata.max_query_len,
softmax_scale=self.scale,
causal=True,
return_softmax_lse=return_softmax_lse,
out=out,
output_scale=output_scale,
)
def run_prefill_context_chunk(
self,
chunk: "MLACommonPrefillMetadata.ContextChunk",
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
return self._flash_attn_varlen_diff_headdims(
q=q,
k=k,
v=v,
cu_seqlens_q=chunk.query_start_loc,
cu_seqlens_k=chunk.cu_seq_lens,
max_seqlen_q=chunk.max_query_len,
max_seqlen_k=chunk.max_seq_len,
softmax_scale=self.scale,
causal=False, # Context is unmasked
return_softmax_lse=True,
out=out,
)
_FA4_MLA_PREFILL_KERNEL = FA4MLAPrefillKernel()
@@ -1,264 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""FlashInfer backend for MLA prefill."""
from typing import TYPE_CHECKING, ClassVar
import torch
import vllm.envs as envs
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.v1.attention.backends.mla.prefill.base import (
MLADimensions,
MLAPrefillBackend,
)
from vllm.v1.attention.backends.utils import (
PerLayerParameters,
get_per_layer_parameters,
infer_global_hyperparameters,
log2_lse_to_ln,
)
from vllm.v1.worker.workspace import current_workspace_manager
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonPrefillMetadata,
)
from vllm.platforms.interface import DeviceCapability
try:
from flashinfer import BatchPrefillWithRaggedKVCacheWrapper
except ImportError:
BatchPrefillWithRaggedKVCacheWrapper = object # type: ignore[misc,assignment]
_DEFAULT_NUM_CHUNKS = 32
class FlashInferPrefillBackend(MLAPrefillBackend):
"""FlashInfer backend for MLA prefill."""
supported_mla_dimensions: ClassVar[list[MLADimensions]] = [
MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
]
@staticmethod
def get_name() -> str:
return "FLASHINFER"
@classmethod
def supports_compute_capability(
cls,
device_capability: "DeviceCapability | None",
) -> bool:
return device_capability is not None and device_capability.major == 10
@classmethod
def is_available(cls) -> bool:
try:
from flashinfer import (
BatchPrefillWithRaggedKVCacheWrapper, # noqa: F401
)
return True
except ImportError:
return False
def __init__(
self,
num_heads: int,
scale: float,
kv_lora_rank: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
vllm_config: "VllmConfig",
) -> None:
super().__init__(
num_heads=num_heads,
scale=scale,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
vllm_config=vllm_config,
)
self._prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None
self._prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = []
self._global_hyperparameters: PerLayerParameters | None = None
self._wrapper_workspace_ptr = 0
self._workspace_spec = (
(envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE,),
torch.uint8,
)
# Reserve capacity without retaining a view: a retained view would pin
# the old buffer when another user grows the shared workspace.
current_workspace_manager().get_simultaneous(self._workspace_spec)
def _ensure_chunks(
self,
num_chunks: int,
workspace_buffer: torch.Tensor,
) -> None:
if len(self._prefill_chunks) < num_chunks:
for _ in range(len(self._prefill_chunks), num_chunks):
self._prefill_chunks.append(
BatchPrefillWithRaggedKVCacheWrapper(
workspace_buffer, "NHD", backend="cutlass"
)
)
def _resolve_global_hyperparameters(self) -> PerLayerParameters:
if self._global_hyperparameters is not None:
return self._global_hyperparameters
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonImpl,
)
from vllm.model_executor.layers.attention_layer_base import (
AttentionLayerBase,
)
# Match any layer with an MLA impl, not just the MLAAttention wrapper:
# fused MLA modules (Kimi-K3's MultiHeadLatentAttention) register a
# different layer type. Keying on impl also excludes linear/KDA layers.
forward_context = self.vllm_config.compilation_config.static_forward_context
layer_names = [
name
for name, layer in forward_context.items()
if isinstance(layer, AttentionLayerBase)
and isinstance(getattr(layer, "impl", None), MLACommonImpl)
]
self._global_hyperparameters = infer_global_hyperparameters(
get_per_layer_parameters(
self.vllm_config,
layer_names,
MLACommonImpl, # type: ignore[type-abstract]
)
)
return self._global_hyperparameters
def prepare_metadata(
self,
prefill_metadata: "MLACommonPrefillMetadata",
) -> None:
global_hyperparameters = self._resolve_global_hyperparameters()
qo_indptr = prefill_metadata.query_start_loc
has_context = prefill_metadata.chunked_context is not None
(workspace_buffer,) = current_workspace_manager().get_simultaneous(
self._workspace_spec
)
if (
self._prefill_main is None
or self._wrapper_workspace_ptr != workspace_buffer.data_ptr()
):
self._prefill_main = BatchPrefillWithRaggedKVCacheWrapper(
workspace_buffer, "NHD", backend="cutlass"
)
self._prefill_chunks = []
self._ensure_chunks(_DEFAULT_NUM_CHUNKS, workspace_buffer)
self._wrapper_workspace_ptr = workspace_buffer.data_ptr()
if has_context:
chunked_context = prefill_metadata.chunked_context
assert chunked_context is not None
self._ensure_chunks(len(chunked_context.chunks), workspace_buffer)
num_qo_heads = self.num_heads
num_kv_heads = num_qo_heads
head_dim_qk = self.qk_nope_head_dim + self.qk_rope_head_dim
head_dim_vo = self.v_head_dim
kv_indptr = qo_indptr.clone()
assert self._prefill_main is not None
# FlashInfer's plan() currently copies GPU indptrs to the CPU.
# This will be fixed by https://github.com/vllm-project/vllm/pull/52657.
with gpu_sync_allowed():
self._prefill_main.plan(
qo_indptr=qo_indptr,
kv_indptr=kv_indptr,
num_qo_heads=num_qo_heads,
num_kv_heads=num_kv_heads,
head_dim_qk=head_dim_qk,
head_dim_vo=head_dim_vo,
causal=True,
sm_scale=global_hyperparameters.sm_scale,
window_left=global_hyperparameters.window_left,
logits_soft_cap=global_hyperparameters.logits_soft_cap,
q_data_type=prefill_metadata.q_data_type,
o_data_type=prefill_metadata.output_dtype,
)
if has_context:
chunked_context = prefill_metadata.chunked_context
assert chunked_context is not None
for chunk in chunked_context.chunks:
with gpu_sync_allowed():
self._prefill_chunks[chunk.index].plan(
qo_indptr=chunk.query_start_loc,
kv_indptr=chunk.cu_seq_lens,
num_qo_heads=num_qo_heads,
num_kv_heads=num_kv_heads,
head_dim_qk=head_dim_qk,
head_dim_vo=head_dim_vo,
causal=False,
sm_scale=global_hyperparameters.sm_scale,
window_left=global_hyperparameters.window_left,
logits_soft_cap=global_hyperparameters.logits_soft_cap,
q_data_type=prefill_metadata.q_data_type,
o_data_type=prefill_metadata.output_dtype,
)
def supports_out(self) -> bool:
# Planned with head_dim_vo == v_head_dim, so the output is unpadded.
return True
def run_prefill_new_tokens(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
assert self._prefill_main is not None
ret = self._prefill_main.run(
q=q,
k=k,
v=v,
out=out,
return_lse=return_softmax_lse,
)
if isinstance(ret, tuple):
# Convert from (q_len, num_heads) to (num_heads, q_len)
return ret[0], log2_lse_to_ln(ret[1].transpose(0, 1))
return ret
def run_prefill_context_chunk(
self,
chunk: "MLACommonPrefillMetadata.ContextChunk",
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
attn_out, lse = self._prefill_chunks[chunk.index].run(
q=q,
k=k,
v=v,
out=out,
return_lse=True,
)
# Convert from (q_len, num_heads) to (num_heads, q_len)
return attn_out, log2_lse_to_ln(lse.transpose(0, 1))
@@ -1,199 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TokenSpeed CuTe DSL backend for MLA prefill."""
from typing import TYPE_CHECKING, ClassVar
import torch
from vllm.v1.attention.backends.mla.prefill.base import (
MLADimensions,
MLAPrefillBackend,
)
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonPrefillMetadata,
)
from vllm.platforms.interface import DeviceCapability
class TokenspeedMLAPrefillBackend(MLAPrefillBackend):
"""TokenSpeed CuTe DSL backend for MLA prefill."""
supported_mla_dimensions: ClassVar[list[MLADimensions]] = [
MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
]
@staticmethod
def get_name() -> str:
return "TOKENSPEED_MLA"
@classmethod
def supports_compute_capability(
cls,
device_capability: "DeviceCapability | None",
) -> bool:
return device_capability is not None and device_capability.major == 10
_INSTALL_HINT = (
"tokenspeed_mla package is not installed. "
"Install it with: `uv pip install tokenspeed-mla`"
)
@classmethod
def is_available(cls) -> bool:
try:
from tokenspeed_mla import (
tokenspeed_mla_prefill, # noqa: F401
)
return True
except ImportError:
return False
@classmethod
def validate_configuration(
cls,
device_capability,
selector_config,
) -> list[str]:
# Replace the generic "required dependencies not available" message
# from the base class with a specific install hint so users know
# exactly which package to install when they explicitly select this
# backend without having tokenspeed_mla installed.
reasons = super().validate_configuration(device_capability, selector_config)
return [
cls._INSTALL_HINT if r == "required dependencies not available" else r
for r in reasons
]
def __init__(
self,
num_heads: int,
scale: float,
kv_lora_rank: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
vllm_config: "VllmConfig",
) -> None:
super().__init__(
num_heads=num_heads,
scale=scale,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
vllm_config=vllm_config,
)
# Pre-JIT BF16 and FP8 prefill kernels. Idempotent — also called from
# TokenspeedMLAImpl.__init__; second call is a no-op.
from tokenspeed_mla import warmup_compile_prefill
for q_dtype in (torch.bfloat16, torch.float8_e4m3fn):
warmup_compile_prefill(
q_dtype=q_dtype,
d_qk=qk_nope_head_dim + qk_rope_head_dim,
d_v=v_head_dim,
enable_pdl=False,
)
def prepare_metadata(
self,
prefill_metadata: "MLACommonPrefillMetadata",
) -> None:
super().prepare_metadata(prefill_metadata)
# Kernel signature requires `seq_lens` but the implementation never reads
# it (per-batch lengths are derived from `cum_seq_lens` diffs); compute
# for parity with trtllm_ragged. cuda-graph padding in
# `query_start_loc` is saturated to `total_num_tokens`
# (gpu_model_runner.py:1905), so trailing diffs are 0 and padded batches
# are kernel no-ops — same reason trtllm passes the padded length as
# batch_size directly.
self._query_seq_lens = (
prefill_metadata.query_start_loc[1:] - prefill_metadata.query_start_loc[:-1]
)
def supports_out(self) -> bool:
# Output head dim is v_head_dim (unpadded); `out` supported since 0.1.8.
return True
def run_prefill_new_tokens(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
from tokenspeed_mla import tokenspeed_mla_prefill
# `v` arrives as the second half of `kv_nope.split(...)` — a
# non-contiguous view of `kv_nope` along dim=-1. The kernel wraps inputs
# via `from_dlpack`, which preserves strides, but the FMHA kernel reads
# `v` assuming contiguous storage and silently produces wrong output on
# a strided view (verified on tokenspeed-mla 0.1.8). Force contiguity.
v = v.contiguous()
ret = tokenspeed_mla_prefill(
query=q,
key=k,
value=v,
seq_lens=self._query_seq_lens,
cum_seq_lens=self._prefill_metadata.query_start_loc,
max_seq_len=self._prefill_metadata.max_query_len,
batch_size=self._query_seq_lens.shape[0],
softmax_scale=self.scale,
is_causal=True,
return_lse=return_softmax_lse,
enable_pdl=False,
out=out,
)
if isinstance(ret, tuple):
# Convert from (q_len, num_heads) to (num_heads, q_len)
return ret[0], ret[1].transpose(0, 1)
return ret
def run_prefill_context_chunk(
self,
chunk: "MLACommonPrefillMetadata.ContextChunk",
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
from tokenspeed_mla import tokenspeed_mla_prefill
# See note in run_prefill_new_tokens — `v` is a split-view of `kv_nope`
# in the generic `_compute_prefill_context` and arrives non-contiguous.
# (K3's fused fp8 K/V pack already hands over a contiguous `v`.)
v = v.contiguous()
attn_out, lse = tokenspeed_mla_prefill(
query=q,
key=k,
value=v,
seq_lens=chunk.seq_lens,
cum_seq_lens=chunk.cu_seq_lens,
max_seq_len=chunk.max_seq_len,
batch_size=chunk.num_requests,
softmax_scale=self.scale,
is_causal=False,
return_lse=True,
cum_seq_lens_q=chunk.query_start_loc,
max_seq_len_q=chunk.max_query_len,
enable_pdl=False,
out=out,
)
# Convert from (q_len, num_heads) to (num_heads, q_len)
return attn_out, lse.transpose(0, 1)
@@ -1,257 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TRT-LLM Ragged backend for MLA prefill."""
from typing import TYPE_CHECKING, ClassVar
import torch
import vllm.envs as envs
from vllm.v1.attention.backends.mla.prefill.base import (
MLADimensions,
MLAPrefillBackend,
)
from vllm.v1.attention.backends.utils import log2_lse_to_ln
from vllm.v1.worker.workspace import current_workspace_manager
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonPrefillMetadata,
)
from vllm.platforms.interface import DeviceCapability
def is_cute_dsl_mla_prefill_supported(
qk_head_dim: int, v_head_dim: int, query_dtype: torch.dtype
) -> bool:
# FlashInfer has no public compatibility API; replace these checks when available.
return (
query_dtype in (torch.float16, torch.bfloat16, torch.float8_e4m3fn)
and (qk_head_dim, v_head_dim) in ((128, 128), (192, 128))
and (qk_head_dim != 192 or query_dtype == torch.float8_e4m3fn)
)
class TrtllmRaggedPrefillBackend(MLAPrefillBackend):
"""TRT-LLM Ragged backend for MLA prefill."""
supported_mla_dimensions: ClassVar[list[MLADimensions]] = [
MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
MLADimensions(
qk_nope_head_dim=192,
qk_rope_head_dim=64,
v_head_dim=256,
),
]
@staticmethod
def get_name() -> str:
return "TRTLLM_RAGGED"
@classmethod
def supports_compute_capability(
cls,
device_capability: "DeviceCapability | None",
) -> bool:
return device_capability is not None and device_capability.major == 10
@classmethod
def is_available(cls) -> bool:
try:
from flashinfer.prefill import (
trtllm_ragged_attention_deepseek, # noqa: F401
)
return True
except ImportError:
return False
def __init__(
self,
num_heads: int,
scale: float,
kv_lora_rank: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
vllm_config: "VllmConfig",
) -> None:
super().__init__(
num_heads=num_heads,
scale=scale,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
vllm_config=vllm_config,
)
self._context_backend = vllm_config.attention_config.trtllm_ragged_backend
self._workspace_spec = (
(envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE,),
torch.uint8,
)
# Reserve capacity without retaining a view: a retained view would pin
# the old buffer when another user grows the shared workspace.
current_workspace_manager().get_simultaneous(self._workspace_spec)
def prepare_metadata(
self,
prefill_metadata: "MLACommonPrefillMetadata",
) -> None:
super().prepare_metadata(prefill_metadata)
(self._workspace_buffer,) = current_workspace_manager().get_simultaneous(
self._workspace_spec
)
self._query_seq_lens = (
prefill_metadata.query_start_loc[1:] - prefill_metadata.query_start_loc[:-1]
)
query_lens_cpu = prefill_metadata.query_lens_cpu
if query_lens_cpu is None:
raise ValueError("TRTLLM ragged prefill requires CPU query lengths")
if query_lens_cpu.device.type != "cpu":
raise ValueError("TRTLLM ragged prefill query lengths must be on CPU")
if query_lens_cpu.ndim != 1 or query_lens_cpu.numel() == 0:
raise ValueError(
"TRTLLM ragged prefill requires a non-empty 1D query-length tensor"
)
min_query_len = int(torch.min(query_lens_cpu).item())
if min_query_len < 0:
raise ValueError("TRTLLM ragged prefill query lengths must be non-negative")
self._has_active_rows = min_query_len > 0
if not self._has_active_rows:
has_mixed_rows = bool(torch.any(query_lens_cpu > 0).item())
if has_mixed_rows:
raise ValueError(
"TRTLLM ragged prefill contains mixed active and empty query "
f"rows: query_lens={query_lens_cpu.tolist()}"
)
def supports_out(self) -> bool:
# Output head dim is v.shape[-1] == v_head_dim, so `out` is unpadded.
return True
def run_prefill_new_tokens(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
return_softmax_lse: bool,
out: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
from flashinfer.prefill import trtllm_ragged_attention_deepseek
if out is None:
out = torch.empty(
q.shape[0],
q.shape[1],
v.shape[2],
device=q.device,
dtype=self._prefill_metadata.output_dtype,
)
if not self._has_active_rows:
out.zero_()
if return_softmax_lse:
lse = torch.empty(
self.num_heads,
q.shape[0],
dtype=torch.float32,
device=q.device,
)
return out, lse.fill_(-float("inf"))
return out
ret = trtllm_ragged_attention_deepseek(
# The kernel reads the query as packed, ignoring its strides
query=q.contiguous(),
key=k,
value=v,
workspace_buffer=self._workspace_buffer,
seq_lens=self._query_seq_lens,
max_q_len=self._prefill_metadata.max_query_len,
max_kv_len=self._prefill_metadata.max_query_len,
bmm1_scale=self.scale,
bmm2_scale=1.0,
o_sf_scale=1.0,
batch_size=self._query_seq_lens.shape[0],
window_left=-1,
cum_seq_lens_q=self._prefill_metadata.query_start_loc,
cum_seq_lens_kv=self._prefill_metadata.query_start_loc,
enable_pdl=False,
is_causal=True,
return_lse=return_softmax_lse,
out=out,
skip_all_rows_active_check=True,
)
if isinstance(ret, tuple):
# Convert from (q_len, num_heads) to (num_heads, q_len)
return ret[0], log2_lse_to_ln(ret[1].transpose(0, 1))
return ret
def run_prefill_context_chunk(
self,
chunk: "MLACommonPrefillMetadata.ContextChunk",
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
from flashinfer.prefill import trtllm_ragged_attention_deepseek
if not chunk.all_rows_active:
raise ValueError(
"TRTLLM ragged context prefill contains an empty query or KV row"
)
if self._context_backend == "cute-dsl":
if not is_cute_dsl_mla_prefill_supported(q.shape[-1], v.shape[-1], q.dtype):
raise ValueError(
"CuTe DSL context prefill does not support "
f"Q/K head dimension {q.shape[-1]}, "
f"V head dimension {v.shape[-1]}, and query dtype {q.dtype}."
)
# Generic MLA supplies V as a projection slice; CuTe requires packed V.
v = v.contiguous()
if out is None:
out = torch.empty(
q.shape[0],
q.shape[1],
v.shape[2],
device=q.device,
dtype=self._prefill_metadata.output_dtype,
)
attn_out, lse = trtllm_ragged_attention_deepseek(
# The kernel reads the query as packed, ignoring its strides
query=q.contiguous(),
key=k,
value=v,
workspace_buffer=self._workspace_buffer,
seq_lens=chunk.seq_lens,
max_q_len=chunk.max_query_len,
max_kv_len=chunk.max_seq_len,
bmm1_scale=self.scale,
bmm2_scale=1.0,
o_sf_scale=1.0,
batch_size=chunk.num_requests,
window_left=-1,
cum_seq_lens_q=chunk.query_start_loc,
cum_seq_lens_kv=chunk.cu_seq_lens,
enable_pdl=False,
is_causal=False,
backend=self._context_backend,
return_lse=True,
out=out,
skip_all_rows_active_check=True,
)
# Convert from (q_len, num_heads) to (num_heads, q_len)
return attn_out, log2_lse_to_ln(lse.transpose(0, 1))
@@ -1,106 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU MLA prefill backend using zentorch SDPA on AMD Zen CPUs.
Subclasses the generic CPU SDPA backend and replaces the per-request attention
with ``zentorch_sdpa``, which fuses the scale, causal mask, softmax and both
matmuls of the base implementation into a single call.
``zentorch_sdpa`` does not return a usable log-sum-exp, so requests that need
one (context chunks, prefix/suffix merge) are delegated to the base backend.
Availability is reported through :meth:`is_available`, so the prefill selector
gates this backend once at selection time rather than per attention call.
"""
import torch
from vllm.model_executor.kernels.linear.zentorch_utils import has_zentorch_op
from vllm.v1.attention.backends.mla.prefill.cpu_sdpa import CPUSDPAMLAPrefillBackend
class ZenCPUSDPAMLAPrefillBackend(CPUSDPAMLAPrefillBackend):
"""MLA prefill backend for AMD Zen CPUs backed by ``zentorch_sdpa``."""
@staticmethod
def get_name() -> str:
return "ZEN_CPU_SDPA_MLA"
@classmethod
def is_available(cls) -> bool:
return has_zentorch_op(["zentorch_sdpa"])
@staticmethod
def _sdpa_layout(
q_r: torch.Tensor,
k_r: torch.Tensor,
v_r: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
"""Convert one request's [S, NH, D] tensors to the [1, NH, S, D] layout.
MLA has ``v_head_dim < qk_head_dim``, which the fused kernel does not
accept, so V is padded up to the query head dim. The original V head
dim is returned so the caller can slice the padding off afterwards.
"""
h_q = q_r.shape[-1]
h_v = v_r.shape[-1]
pad = h_q - h_v
qs = q_r.transpose(0, 1).unsqueeze(0).contiguous()
ks = k_r.transpose(0, 1).unsqueeze(0).contiguous()
vs = v_r.transpose(0, 1).unsqueeze(0).contiguous()
if pad > 0:
vs = torch.nn.functional.pad(vs, (0, pad))
return qs, ks, vs, h_v
def _ragged_sdpa(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q_cu_seq_lens: torch.Tensor,
kv_cu_seq_lens: torch.Tensor,
causal: bool,
return_softmax_lse: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if return_softmax_lse:
# zentorch_sdpa's second return is not a usable LSE, so fall back
# to the base fp32 implementation whenever one is required.
return super()._ragged_sdpa(
q,
k,
v,
q_cu_seq_lens,
kv_cu_seq_lens,
causal,
return_softmax_lse,
)
num_reqs = q_cu_seq_lens.numel() - 1
assert num_reqs == kv_cu_seq_lens.numel() - 1
out_chunks: list[torch.Tensor] = []
for r in range(num_reqs):
q_start = int(q_cu_seq_lens[r])
q_end = int(q_cu_seq_lens[r + 1])
kv_start = int(kv_cu_seq_lens[r])
kv_end = int(kv_cu_seq_lens[r + 1])
qs, ks, vs, h_v = self._sdpa_layout(
q[q_start:q_end],
k[kv_start:kv_end],
v[kv_start:kv_end],
)
attn, _ = torch.ops.zentorch.zentorch_sdpa(
qs,
ks,
vs,
0.0,
causal,
attn_mask=None,
scale=self.scale,
)
out_chunks.append(attn[0].transpose(0, 1)[..., :h_v].to(v.dtype))
return torch.cat(out_chunks, dim=0)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,513 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Indexer metadata for the ROCm paged MXFP4 path.
Extends the dense indexer metadata with what aiter's paged MXFP4 MQA-logits
kernel needs to read the cache in place: each prefill chunk as its requests,
packed through query_start_loc into one launch, and the decode rows as
next_n-row sequences on uniform steps. `RocmMxfp4IndexerMetadataBuilder` plans
this for any model's indexer, and a two-level indexer's candidate blocks once
a subclass sets their size. DeepSeek-V4.1's builder does, and with
``AttentionConfig.indexer_sparse_logits`` adds the per-step state the
candidate consumers share.
"""
import bisect
from dataclasses import dataclass, field, fields
import torch
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.v1.attention.backend import (
AttentionCGSupport,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerMetadata,
DeepseekV32IndexerMetadataBuilder,
DeepseekV32IndexerPrefillChunkMetadata,
DeepseekV41IndexerBackend,
)
from vllm.v1.attention.ops.rocm_paged_mxfp4_indexer import (
build_rocm_mxfp4_decode_schedule,
rocm_mxfp4_consumer_rows,
rocm_mxfp4_decode_schedule_words,
rocm_paged_mxfp4_cache_layout,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec
logger = init_logger(__name__)
# The consumers walk the pool instead of the context once the context is this
# many pools long. Set from kernel timings, not end-to-end runs: the gather
# loads more per key than the dense walk, so it only wins on a large cut.
_GATHER_MIN_CUT_DECODE = 3.0
_GATHER_MIN_CUT_PREFILL = 1.5
@dataclass
class RocmMxfp4PrefillPlan:
"""One prefill chunk as the requests the kernel launches on, all in one
launch: the kernel finds each row's request through query_start_loc, and
a request's rows share its KV tiles."""
requests: list[tuple[int, int, int]]
"""(first row, end row, request) per request with rows in the chunk; rows
count from ``chunk.token_start``, requests index ``chunk.block_table``."""
width: int
"""Logits columns: an upper bound on the chunk's compressed contexts."""
row_ends: torch.Tensor
"""[rows] int32 exclusive compressed key bound of each row."""
context_lens: torch.Tensor
"""[chunk.num_reqs] int32 compressed context of each request."""
query_start_loc: torch.Tensor
"""[chunk.num_reqs + 1] int32 row offsets of the chunk's requests, local to
the chunk."""
first_request: int
"""The step's index of the chunk's first request."""
block_ends: torch.Tensor | None = None
"""[rows] int32 candidate blocks each row sees, for the source's pool."""
use_gather: bool = False
@dataclass
class RocmMxfp4GatherLaunch:
"""Query rows [token_start, token_end) of one request, which the candidate
consumers score against the pool in one launch."""
token_start: int
token_end: int
block_table: torch.Tensor
"""[1, max_blocks] int32, the request's block table row."""
context_len: torch.Tensor
"""[1] int32 compressed context of the request."""
row_ends: torch.Tensor
"""[rows] int32 exclusive compressed key bound of each row."""
pool: tuple[dict, torch.Tensor] | None = None
"""The resolved candidate lists, built by the first consumer layer and
reused by the rest."""
@dataclass
class RocmMxfp4NativeDecode:
"""A decode step whose requests all have next_n query rows, as the
kernel's sequences: a workgroup then walks a KV tile once for up to
next_n rows instead of once per row."""
next_n: int
context_lens: torch.Tensor
"""[requests] int32 compressed context of each request."""
block_table: torch.Tensor
"""[requests, max_blocks] int32, each request's first flattened row."""
def native_decode(
row_lens: torch.Tensor,
row_block_table: torch.Tensor,
query_lens: list[int],
next_n: int,
context_lens: torch.Tensor,
) -> RocmMxfp4NativeDecode | None:
"""The step as next_n-row sequences, or None when a request has fewer rows.
``row_lens`` and ``row_block_table`` are the flattened rows' bounds and
block table, ``query_lens`` the decode requests' query lengths. Trailing
empty requests are cudagraph padding: they keep their next_n rows, with no
context. Only the step's shape decides, so a FULL graph captured on a
uniform batch replays the same launch on a padded one.
"""
num_reqs = len(query_lens)
num_full = next((i for i, n in enumerate(query_lens) if n != next_n), num_reqs)
if (
next_n <= 1
or row_lens.shape[0] != num_reqs * next_n
or any(query_lens[num_full:])
):
return None
return RocmMxfp4NativeDecode(
next_n, context_lens[:num_reqs], row_block_table[::next_n]
)
@dataclass
class RocmMxfp4IndexerMetadata(DeepseekV32IndexerMetadata):
prefill_plans: list[RocmMxfp4PrefillPlan] = field(default_factory=list)
"""Parallel to ``prefill.chunks``."""
decode_row_lens: torch.Tensor | None = None
"""[rows] int32 compressed context of each decode query row."""
decode_block_ends: torch.Tensor | None = None
"""[rows] int32 candidate blocks each decode row sees, for the source's
pool."""
decode_native: RocmMxfp4NativeDecode | None = None
"""The same rows as next_n-row sequences, for the dense launches."""
decode_schedule: torch.Tensor | None = None
"""The dense decode launches' work schedule, built once for the step."""
decode_use_gather: bool = False
"""Whether the candidate consumers gather for the decode rows."""
decode_gather: tuple[dict, torch.Tensor] | None = None
"""The pool the first consumer resolved for the decode rows."""
gather_launches: list[RocmMxfp4GatherLaunch] = field(default_factory=list)
"""The prefill rows of the chunks that gather, as the consumers launch
them."""
def plan_prefill_chunks(
chunks: list[DeepseekV32IndexerPrefillChunkMetadata],
query_start_loc: list[int],
seq_lens_cpu: torch.Tensor,
context_lens: torch.Tensor,
compress_ratio: int,
candidate_block_size: int,
min_gather_width: float | None,
query_start_loc_device: torch.Tensor,
) -> list[RocmMxfp4PrefillPlan]:
"""Split each chunk into its requests.
``query_start_loc`` and ``seq_lens_cpu`` are the step's host copies (the
latter an upper bound), ``context_lens`` the device compressed lengths.
A chunk covers whole requests, or a query slice of one request; either
way it launches once, packed through the chunk's part of the device
``query_start_loc``.
"""
block = candidate_block_size
plans = []
for chunk in chunks:
t0, t1 = chunk.token_start, chunk.token_end
first = bisect.bisect_right(query_start_loc, t0) - 1
requests = []
for req in range(chunk.num_reqs):
lo = max(query_start_loc[first + req], t0) - t0
hi = min(query_start_loc[first + req + 1], t1) - t0
if hi > lo:
requests.append((lo, hi, req))
reqs = slice(first, first + chunk.num_reqs)
packed = torch.clamp(query_start_loc_device[first : reqs.stop + 1], t0, t1)
packed -= t0
width = int(seq_lens_cpu[reqs].max()) // compress_ratio
row_ends = chunk.cu_seqlen_ke - chunk.cu_seqlen_ks
plans.append(
RocmMxfp4PrefillPlan(
requests=requests,
width=width,
row_ends=row_ends,
context_lens=context_lens[reqs],
query_start_loc=packed,
first_request=first,
block_ends=(row_ends + block - 1) // block if block else None,
use_gather=min_gather_width is not None and width >= min_gather_width,
)
)
return plans
def split_prefill_chunks(
context_lens: torch.Tensor,
query_lens: torch.Tensor,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
"""(request slice, query slice) chunks, as the base chunker returns them.
Nothing gathers K here, so the requests' contexts do not add up: a chunk's
logits are [rows, widest compressed context] fp32, at most
``max_logits_bytes``. A request too wide to launch whole is cut on its
query rows.
"""
def max_rows(width: int) -> int:
return max(1, max_logits_bytes // (4 * max(width, 1)))
chunks: list[tuple[slice, slice]] = []
end = 0
while end < len(context_lens):
start, rows, width = end, 0, 0
while end < len(context_lens):
q = int(query_lens[end])
w = max(width, int(context_lens[end]))
if rows and rows + q > max_rows(w):
break
rows, width = rows + q, w
end += 1
step = max_rows(width)
reqs = slice(start + request_offset, end + request_offset)
chunks.extend(
(reqs, slice(lo, min(lo + step, rows))) for lo in range(0, rows, step)
)
return chunks
def plan_gather_launches(
chunks: list[DeepseekV32IndexerPrefillChunkMetadata],
plans: list[RocmMxfp4PrefillPlan],
max_rows: int,
) -> list[RocmMxfp4GatherLaunch]:
"""The candidate consumers' launches over the chunks that gather.
A consumer's logits are [rows, pool] however long the context, so the
dense split, sized for the context, would launch it far more often than
its memory needs. Each request's rows go back together across the chunks
that cut them, then out again at most ``max_rows`` a launch.
"""
# Per request: (first token, [(plan, first row, end row)]), and the chunk
# and request index its block table and context come from.
runs: list[tuple[int, list, DeepseekV32IndexerPrefillChunkMetadata, int]] = []
last: tuple[int, int] | None = None
for chunk, plan in zip(chunks, plans):
if not plan.use_gather:
last = None
continue
for lo, hi, req in plan.requests:
request, t_lo = plan.first_request + req, chunk.token_start + lo
if last != (request, t_lo):
runs.append((t_lo, [], chunk, req))
runs[-1][1].append((plan, lo, hi))
last = (request, chunk.token_start + hi)
launches = []
for token_start, pieces, chunk, req in runs:
ends = [plan.row_ends[lo:hi] for plan, lo, hi in pieces]
row_ends = ends[0] if len(ends) == 1 else torch.cat(ends)
block_table = chunk.block_table[req : req + 1]
context_len = pieces[0][0].context_lens[req : req + 1]
for lo in range(0, row_ends.shape[0], max_rows):
hi = min(lo + max_rows, row_ends.shape[0])
launches.append(
RocmMxfp4GatherLaunch(
token_start + lo,
token_start + hi,
block_table,
context_len,
row_ends[lo:hi],
)
)
return launches
class DeepseekV41RocmMxfp4IndexerBackend(DeepseekV41IndexerBackend):
@staticmethod
def get_name() -> str:
return "DEEPSEEK_V41_ROCM_MXFP4_INDEXER"
@staticmethod
def get_supported_kernel_block_sizes(
kv_cache_spec: KVCacheSpec | None = None,
) -> list[int | MultipleOf]:
# --block-size 128 preferred.
return [64, 128]
@staticmethod
def get_builder_cls() -> type["DeepseekV41RocmMxfp4IndexerMetadataBuilder"]:
return DeepseekV41RocmMxfp4IndexerMetadataBuilder
class RocmMxfp4IndexerMetadataBuilder(DeepseekV32IndexerMetadataBuilder):
"""Dense indexer metadata plus the in-place paged launches' layout.
Requirements are checked here, at engine start.
"""
@classmethod
def get_cudagraph_support(
cls,
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> AttentionCGSupport:
# Decode rows are flattened into persistent buffers, and whether a
# step launches them as next_n-row sequences depends on its shape
# alone (see native_decode).
return AttentionCGSupport.ALWAYS
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
**kwargs,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device, **kwargs)
name = "the ROCm MXFP4 indexer"
if self.dcp_world_size > 1 or self.use_pcp:
raise NotImplementedError(
f"{name} does not support decode/prefill context parallel."
)
hf_config = vllm_config.model_config.hf_text_config
num_heads, head_dim = hf_config.index_n_heads, hf_config.index_head_dim
self.num_heads, self.head_dim = num_heads, head_dim
self.page_entries = kv_cache_spec.block_size // self.compress_ratio
self.cache_layout = rocm_paged_mxfp4_cache_layout(
num_heads, head_dim, self.page_entries
)
# Ragged steps take a row per query token, as do the candidate
# consumers' gathers. Uniform steps also launch the dense layers on
# next_n-row sequences, see native_decode.
self.use_flattening = True
# A two-level (candidate block) indexer's builder sets these.
self.candidate_block_size = 0
self.min_gather_width: float | None = None
self.decode_block_ends_buffer = torch.zeros(
self.arange_buffer.shape[0], dtype=torch.int32, device=device
)
self.context_lens_buffer = torch.zeros(
self.arange_buffer.shape[0], dtype=torch.int32, device=device
)
spec_config = vllm_config.speculative_config
# Adaptive verification replays a FULL graph on drafts reallocated
# across requests, so a step's shape does not fix its query lengths.
adaptive = spec_config is not None and spec_config.enable_adaptive_verification
self.native_next_n = 1 if adaptive else self.num_speculative_tokens + 1
# The indexer's logits width, which the decode schedule sizes slices by.
max_model_len = vllm_config.model_config.max_model_len
self.logits_width = max_model_len // self.compress_ratio
# Every dense layer of this group reads the same rows through the same
# page geometry, so the step builds their schedule once, not per layer.
self.decode_schedule_buffer = torch.empty(
rocm_mxfp4_decode_schedule_words(
num_heads, head_dim, self.page_entries, self.native_next_n
),
dtype=torch.int32,
device=device,
)
def _split_indexer_prefill_chunks( # type: ignore[override]
self,
compressed_seq_lens_cpu: torch.Tensor,
prefill_query_lens_cpu: torch.Tensor,
workspace_size: int,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
return split_prefill_chunks(
compressed_seq_lens_cpu,
prefill_query_lens_cpu,
max_logits_bytes,
request_offset,
)
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> RocmMxfp4IndexerMetadata:
base = super().build(common_prefix_len, common_attn_metadata, fast_build)
metadata = RocmMxfp4IndexerMetadata(
**{f.name: getattr(base, f.name) for f in fields(base)}
)
cm = common_attn_metadata
context_lens = self.context_lens_buffer[: cm.num_reqs]
torch.floor_divide(
cm.seq_lens[: cm.num_reqs], self.compress_ratio, out=context_lens
)
if base.decode is not None:
lengths = base.decode.seq_lens.view(-1)
metadata.decode_row_lens = lengths
block = self.candidate_block_size
if block:
ends = self.decode_block_ends_buffer[: lengths.shape[0]]
torch.add(lengths, block - 1, out=ends)
ends.floor_divide_(block)
metadata.decode_block_ends = ends
query_start_loc = cm.query_start_loc_cpu[: base.num_decodes + 1]
metadata.decode_native = native_decode(
lengths,
base.decode.block_table,
torch.diff(query_start_loc).tolist(),
self.native_next_n,
context_lens,
)
metadata.decode_schedule = build_rocm_mxfp4_decode_schedule(
lengths,
self.num_heads,
self.head_dim,
self.page_entries,
self.decode_schedule_buffer,
self.logits_width,
metadata.decode_native,
)
if base.prefill is not None:
assert cm.seq_lens_cpu_upper_bound is not None
metadata.prefill_plans = plan_prefill_chunks(
base.prefill.chunks,
cm.query_start_loc_cpu.tolist(),
cm.seq_lens_cpu_upper_bound,
context_lens,
self.compress_ratio,
self.candidate_block_size,
self.min_gather_width,
cm.query_start_loc,
)
return metadata
class DeepseekV41RocmMxfp4IndexerMetadataBuilder(RocmMxfp4IndexerMetadataBuilder):
"""DeepSeek-V4.1's two-level indexer: sets the candidate block size the
base plans with and, with ``indexer_sparse_logits``, adds the consumers'
gathers."""
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
**kwargs,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device, **kwargs)
hf_config = vllm_config.model_config.hf_text_config
self.candidate_block_size = getattr(hf_config, "candidate_block_size", 0)
self.num_candidate_cols = 0
if vllm_config.attention_config.indexer_sparse_logits:
prefix = "attention_config.indexer_sparse_logits"
block = self.candidate_block_size
topk_blocks = getattr(hf_config, "candidate_topk_blocks", 0)
layout = self.cache_layout
if block <= 0 or topk_blocks <= 0:
raise ValueError(
f"{prefix} requires a two-level (candidate block) indexer "
"model such as DeepSeek-V4.1."
)
if topk_blocks & (topk_blocks - 1):
raise ValueError(
f"{prefix} on ROCm resolves the candidate pool with a sort "
f"that needs a power-of-two block count, not {topk_blocks}."
)
if self.page_entries % block or block > layout.n_per_tile:
raise ValueError(
f"{prefix} on ROCm needs {block}-entry candidate blocks to "
f"tile a {self.page_entries}-entry indexer page and fit in "
f"one {layout.n_per_tile}-entry shuffle group."
)
self.num_candidate_cols = topk_blocks * block
self.min_gather_width = self.num_candidate_cols * _GATHER_MIN_CUT_PREFILL
self.gather_rows = rocm_mxfp4_consumer_rows(self.num_candidate_cols)
logger.info_once(
"DeepSeek V4.1 indexer: candidate consumers score the %d "
"candidate positions with aiter's paged MXFP4 gather once the "
"context is %.1fx (decode) / %.1fx (prefill) as long.",
self.num_candidate_cols,
_GATHER_MIN_CUT_DECODE,
_GATHER_MIN_CUT_PREFILL,
)
def _gather_pays(self, context: int, cut: float) -> bool:
return self.num_candidate_cols > 0 and context >= cut * self.num_candidate_cols
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> RocmMxfp4IndexerMetadata:
metadata = super().build(common_prefix_len, common_attn_metadata, fast_build)
if metadata.decode is not None:
metadata.decode_use_gather = self._gather_pays(
metadata.max_seq_len // self.compress_ratio, _GATHER_MIN_CUT_DECODE
)
if metadata.prefill is not None and self.num_candidate_cols:
metadata.gather_launches = plan_gather_launches(
metadata.prefill.chunks, metadata.prefill_plans, self.gather_rows
)
return metadata
@@ -1,235 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DeepSeek V4.1 indexer backend for the DeepGEMM sparse MQA-logits path.
Candidate-consuming indexer layers score only the candidate blocks published
by the candidate-source layer (``fp8_fp4_(paged_)sparse_mqa_logits``) instead
of dense logits over the whole context. This backend extends the dense
indexer metadata with the per-row scratch that path needs, so the layer op
allocates nothing per step, and lets all consumer layers of a step share one
candidate expansion and DeepGEMM schedule (they all read the same candidate
blocks). Opt in with ``AttentionConfig.indexer_sparse_logits``.
"""
from dataclasses import dataclass, fields
import torch
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.kernels.attention.dsa.sparse_mqa_logits import (
check_deep_select_layout,
has_deep_select,
pick_sparse_block_kv,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import has_deep_gemm_sparse_mqa
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerMetadata,
DeepseekV32IndexerMetadataBuilder,
DeepseekV41IndexerBackend,
dsa_indexer_uses_fp4,
)
from vllm.v1.kv_cache_interface import AttentionSpec
logger = init_logger(__name__)
@dataclass
class SparseMQARowsMetadata:
"""Per-row state for one sparse-logits call: the decode rows, or one
prefill chunk. Buffers are builder-owned views sized to the rows.
``kernel_metadata`` (the DeepGEMM schedule) is filled by the first
consumer indexer layer of the step together with ``sparse_indices`` /
``end``; later consumer layers reuse all three.
"""
row_ks: torch.Tensor
"""[rows] int32 K-range start per row; zeros for paged decode."""
row_ke: torch.Tensor
"""[rows] int32 K-range end (prefill) or compressed context length."""
sparse_indices: torch.Tensor
"""[rows, num_sparse_blocks] int32 DeepGEMM sparse block ids."""
end: torch.Tensor
"""[rows] int32 valid sparse-column count per row."""
col_indices: torch.Tensor
"""[rows, topk] int32 scratch for the sparse-column top-k."""
block_table: torch.Tensor | None = None
"""Decode only: [rows, pages] per-row page table."""
row_indices: torch.Tensor | None = None
"""Decode only: [rows] row -> request index."""
kernel_metadata: torch.Tensor | None = None
@dataclass
class DeepseekV41SparseIndexerMetadata(DeepseekV32IndexerMetadata):
sparse_block_kv: int = 0
sparse_decode: SparseMQARowsMetadata | None = None
sparse_prefill: list[SparseMQARowsMetadata] | None = None
"""Parallel to ``prefill.chunks``."""
class DeepseekV41SparseIndexerBackend(DeepseekV41IndexerBackend):
@staticmethod
def get_name() -> str:
return "DEEPSEEK_V41_SPARSE_INDEXER"
@staticmethod
def get_builder_cls() -> type["DeepseekV41SparseIndexerMetadataBuilder"]:
return DeepseekV41SparseIndexerMetadataBuilder
class DeepseekV41SparseIndexerMetadataBuilder(DeepseekV32IndexerMetadataBuilder):
"""Dense indexer metadata plus the sparse-logits row scratch.
Every requirement of the sparse kernels is checked here, at engine start,
rather than falling back to the dense path per step.
"""
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
**kwargs,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device, **kwargs)
hf_config = vllm_config.model_config.hf_text_config
candidate_block_size = getattr(hf_config, "candidate_block_size", 0)
candidate_topk_blocks = getattr(hf_config, "candidate_topk_blocks", 0)
topk_tokens = getattr(hf_config, "index_topk", 0)
prefix = "attention_config.indexer_sparse_logits"
if candidate_block_size <= 0 or candidate_topk_blocks <= 0:
raise ValueError(
f"{prefix} requires a two-level (candidate block) indexer model "
"such as DeepSeek-V4.1."
)
if not dsa_indexer_uses_fp4(vllm_config):
raise ValueError(
f"{prefix} requires the MXFP4 indexer cache "
"(attention_config.indexer_kv_dtype='mxfp4'): the sparse kernels "
"take UE8M0-packed granularity-32 scales."
)
if not (
current_platform.is_cuda()
and current_platform.is_device_capability_family(100)
):
raise ValueError(f"{prefix} requires an SM100-class GPU.")
if not has_deep_gemm_sparse_mqa():
raise ValueError(
f"{prefix} requires DeepGEMM >= 2.8 "
"(fp8_fp4_sparse_mqa_logits not found)."
)
if self.dcp_world_size > 1 or self.use_pcp:
raise NotImplementedError(
f"{prefix} is not supported with decode/prefill context parallel."
)
if not self.supports_varlen:
raise ValueError(
f"{prefix} requires the varlen paged MQA logits decode layout."
)
# The top-k runs on the kernels' bf16 logits with DeepSelect; there is
# no fp32 fallback, so the other top-k backends cannot be honored.
topk_backend = vllm_config.kernel_config.sparse_indexer_topk_backend
if not has_deep_select():
raise ValueError(
f"{prefix} requires the DeepSelect top-k extension "
"(vllm._deepselect_C) for this GPU."
)
if topk_backend not in ("auto", "deep_select"):
raise ValueError(
f"{prefix} uses DeepSelect for the top-k; "
f"kernel_config.sparse_indexer_topk_backend='{topk_backend}' "
"is not supported with it."
)
self.sparse_block_kv = pick_sparse_block_kv(candidate_block_size)
if kv_cache_spec.block_size % self.sparse_block_kv != 0:
raise ValueError(
f"{prefix}: indexer cache pages ({kv_cache_spec.block_size} "
f"tokens) must be a multiple of {self.sparse_block_kv} tokens."
)
self.num_sparse_blocks = candidate_topk_blocks * (
candidate_block_size // self.sparse_block_kv
)
num_sparse_cols = self.num_sparse_blocks * self.sparse_block_kv
check_deep_select_layout(num_sparse_cols, topk_tokens)
# Sparse logits are bf16 [rows, num_sparse_cols]; make the prefill
# chunker (which budgets fp32 [rows, seq_len]) size chunks as if every
# row were this wide.
self.min_split_seq_len = (num_sparse_cols * 2 + 3) // 4
# Rows are indexed by batch token (decode rows first, then prefill
# chunks by token range), like ``arange_buffer``.
max_rows = self.arange_buffer.shape[0]
int32 = dict(dtype=torch.int32, device=device)
self.sparse_indices_buffer = torch.zeros(
(max_rows, self.num_sparse_blocks), **int32
)
self.end_buffer = torch.zeros(max_rows, **int32)
self.col_indices_buffer = torch.zeros((max_rows, topk_tokens), **int32)
self.zero_row_ks = torch.zeros(max_rows, **int32)
logger.info_once(
"DeepSeek V4.1 indexer: candidate consumers score only the candidate "
"blocks with DeepGEMM sparse MQA logits (%d sparse blocks of %d "
"tokens per row).",
self.num_sparse_blocks,
self.sparse_block_kv,
)
def _prefill_split_seq_lens(self, seq_lens_cpu: torch.Tensor) -> torch.Tensor:
return seq_lens_cpu.clamp(min=self.min_split_seq_len)
def _rows(self, start: int, end: int, row_ks, row_ke, **kwargs):
return SparseMQARowsMetadata(
row_ks=row_ks,
row_ke=row_ke,
sparse_indices=self.sparse_indices_buffer[start:end],
end=self.end_buffer[start:end],
col_indices=self.col_indices_buffer[start:end],
**kwargs,
)
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> DeepseekV41SparseIndexerMetadata:
base = super().build(common_prefix_len, common_attn_metadata, fast_build)
metadata = DeepseekV41SparseIndexerMetadata(
**{f.name: getattr(base, f.name) for f in fields(base)},
sparse_block_kv=self.sparse_block_kv,
)
if base.decode is not None:
decode = base.decode
rows = decode.seq_lens.shape[0]
# The varlen layout flattens every query to one row, so the base
# decode tensors are already per row.
assert decode.seq_lens.shape[1] == 1 and not decode.requires_padding
assert decode.block_table.shape[0] == rows
metadata.sparse_decode = self._rows(
0,
rows,
row_ks=self.zero_row_ks[:rows],
row_ke=decode.seq_lens.view(-1),
block_table=decode.block_table,
row_indices=(
decode.indices
if decode.indices is not None
else self.arange_buffer[:rows]
),
)
if base.prefill is not None:
metadata.sparse_prefill = [
self._rows(
chunk.token_start,
chunk.token_end,
row_ks=chunk.cu_seqlen_ks,
row_ke=chunk.cu_seqlen_ke,
)
for chunk in base.prefill.chunks
]
return metadata
File diff suppressed because it is too large Load Diff
@@ -1,748 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Utility functions for sparse MLA backends."""
from dataclasses import dataclass, replace
from typing import Any
import numpy as np
import torch
from vllm.config import VllmConfig
from vllm.distributed import get_dcp_group
from vllm.model_executor.warmup.jit_warmup import (
kernel_launcher,
zip_inputs,
)
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
LaunchSpec,
TritonWarmupTensor,
VllmTritonJitKernel,
triton_scalar_specialization_rep,
)
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import cdiv
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.v1.worker.block_table import get_block_table_width
def request_row_bounds(req_idx: np.ndarray) -> np.ndarray:
"""Bounds of the runs of adjacent rows that belong to one request: run
``r`` is rows ``[bounds[r], bounds[r + 1])``.
Under PCP a rank holds two adjacent chunk rows of a split prefill; the
sparse backends give such a run one KV region.
"""
assert req_idx.size > 0
bounds = np.flatnonzero(np.r_[True, req_idx[1:] != req_idx[:-1], True])
assert bounds.size - 1 == np.unique(req_idx).size, (
"rows of one request must be adjacent"
)
return bounds
def align_blocks_to_rows(spec: AttentionSpec, rows: int = 1) -> AttentionSpec:
"""Sparse kernels read the cache as flat rows, viewed as ``rows``-row pages,
so blocks must be whole pages apart."""
return replace(spec, block_stride_alignment=rows * spec.state_content_size_bytes)
def flat_kv_row_view(
kv_cache: torch.Tensor, # [num_blocks, block_size, head_dim]
block_size: int,
) -> tuple[torch.Tensor, int]:
"""Flat [row, head_dim] view of a paged cache and its physical rows per block.
Token offset is ``block_idx * block_stride_rows + offset_in_block``.
When other layers' pages sit between consecutive blocks of this cache,
``block_stride_rows`` exceeds ``block_size``; those in-between rows are never
indexed (`triton_convert_req_index_to_global_index` ensures this).
"""
num_blocks, _, head_dim = kv_cache.shape
assert kv_cache.stride(0) % head_dim == 0, (
"block stride is not a whole number of rows; flat row indexing would "
"silently misaddress"
)
block_stride_rows = kv_cache.stride(0) // head_dim
num_rows = (num_blocks - 1) * block_stride_rows + block_size
rows = kv_cache.as_strided((num_rows, head_dim), (head_dim, 1))
return rows, block_stride_rows
# Kernel with prefill workspace support and valid count tracking
class ConvertReqIndexToGlobalIndexKernel(
VllmTritonJitKernel["ConvertReqIndexToGlobalIndexKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
block_size: int
block_stride_rows: int
block_n: int
has_prefill_workspace: bool
count_valid: bool
single_tile: bool
compact_to_front: bool
dcp_size: int
dcp_rank: int
dcp_interleave: int
num_warps: int
num_topk_tokens: int
block_table_stride: int
@staticmethod
@triton.jit(do_not_specialize=["max_num_blocks_per_req", "workspace_rank_stride"])
def sparse_mla_index_remap_kernel(
req_id_ptr, # int32 [num_tokens]
block_table_ptr, # int32 [num_requests, max_num_blocks_per_req]
token_indices_ptr, # int32 [num_tokens, NUM_TOPK_TOKENS]
out_ptr, # int32 [num_tokens, NUM_TOPK_TOKENS]
valid_count_ptr, # int32 [num_tokens] - output valid count per row
prefill_request_id_ptr, # int32 [num_tokens], -1 for decode, >=0 for prefill
workspace_starts_ptr, # int32 [num_prefill_reqs+1] or nullptr
workspace_rank_stride, # rows per DCP rank of a gathered prefill workspace
# shapes (compile-time where possible)
max_num_blocks_per_req,
BLOCK_SIZE: tl.constexpr,
BLOCK_STRIDE_ROWS: tl.constexpr,
BLOCK_N: tl.constexpr, # tile width along columns
NUM_TOPK_TOKENS: tl.constexpr,
HAS_PREFILL: tl.constexpr,
COUNT_VALID: tl.constexpr, # whether to count valid indices
# BLOCK_N >= NUM_TOPK_TOKENS: one program owns the query, so its count
# is an in-register reduction and needs no atomic.
SINGLE_TILE: tl.constexpr,
# When set, scatter valid slots to a contiguous prefix [0, valid_count) using
# valid_count_ptr as an atomic slot allocator (DCP filtering leaves interior
# -1 gaps; the trtllm-gen sparse kernel reads the first valid_count entries).
# Requires COUNT_VALID; multi-tile output must be pre-filled with -1. The
# prefix is unspecified (only the selected set matters).
COMPACT_TO_FRONT: tl.constexpr,
# DCP de-interleave: with DCP_SIZE == 1 these are an exact no-op
DCP_SIZE: tl.constexpr,
DCP_RANK: tl.constexpr,
DCP_INTERLEAVE: tl.constexpr,
# strides (in elements)
bt_stride0,
bt_stride1,
ti_stride0,
ti_stride1,
out_stride0,
out_stride1,
):
# program_id(0) -> token_id (row)
# program_id(1) -> tile index along columns
token_id = tl.program_id(0)
tile_id = tl.program_id(1)
# Each program covers BLOCK_N consecutive columns
indice_id = tile_id * BLOCK_N + tl.arange(0, BLOCK_N)
# Load request id for this token (no mask: grid is exact)
req = tl.load(req_id_ptr + token_id)
# Load token indices for this tile
ti_ptr = token_indices_ptr + token_id * ti_stride0 + indice_id * ti_stride1
tok = tl.load(ti_ptr, mask=indice_id < NUM_TOPK_TOKENS, other=-1)
# Only token == -1 should propagate as -1
is_invalid_tok = tok < 0
is_prefill = False
if HAS_PREFILL:
prefill_req_id = tl.load(prefill_request_id_ptr + token_id)
is_prefill = prefill_req_id >= 0
# DCP de-interleave the global token id into this rank's local slot.
# Tokens are interleaved in groups of DCP_INTERLEAVE across ranks. With
# DCP_SIZE == 1 (and any interleave) owning_rank == 0 == DCP_RANK (never
# remote) and local_idx == tok, so this reduces to the non-DCP path; with
# DCP_INTERLEAVE == 1 it reduces to plain round-robin (tok % / // DCP_SIZE).
owning_rank = (tok // DCP_INTERLEAVE) % DCP_SIZE
is_remote = owning_rank != DCP_RANK
local_idx = (
tok // (DCP_SIZE * DCP_INTERLEAVE)
) * DCP_INTERLEAVE + tok % DCP_INTERLEAVE
# Compute block id and in-block offset
block_id = local_idx // BLOCK_SIZE
inblock_off = local_idx % BLOCK_SIZE
# Guard block_table access
valid_block = (block_id < max_num_blocks_per_req) & (block_id >= 0)
bt_ptr = block_table_ptr + req * bt_stride0 + block_id * bt_stride1
is_invalid_tok |= ~valid_block | (is_remote & ~is_prefill)
base = tl.load(bt_ptr, mask=valid_block & ~is_prefill & ~is_remote, other=0)
out_val = base * BLOCK_STRIDE_ROWS + inblock_off
# Override with prefill output if prefill is enabled
if HAS_PREFILL:
workspace_start = tl.load(
workspace_starts_ptr + prefill_req_id, mask=is_prefill, other=0
)
# Under DCP the prefill workspace is the all-gather of every rank's
# shard, rank-major. With DCP_SIZE == 1 this is workspace_start + tok.
prefill_out = (
owning_rank * workspace_rank_stride + workspace_start + local_idx
)
out_val = tl.where(is_prefill, prefill_out, out_val)
out_val = tl.where(is_invalid_tok, -1, out_val)
if COMPACT_TO_FRONT:
# Scatter valid slots to a contiguous prefix. A per-tile exclusive prefix
# sum gives each valid lane a distinct local offset; one atomic add of the
# tile's valid count reserves a contiguous base across racing tiles. The
# out buffer is pre-filled with -1, so unwritten tail slots stay -1.
# With no racing tiles the base is 0 and the allocator becomes a store.
is_valid = (~is_invalid_tok).to(tl.int32)
local_offset = tl.cumsum(is_valid) - is_valid
tile_valid_count = tl.sum(is_valid)
if SINGLE_TILE:
base = 0
tl.store(valid_count_ptr + token_id, tile_valid_count)
else:
base = tl.atomic_add(valid_count_ptr + token_id, tile_valid_count)
dest = base + local_offset
out_ptr_dest = out_ptr + token_id * out_stride0 + dest * out_stride1
tl.store(out_ptr_dest, out_val, mask=is_valid == 1)
if SINGLE_TILE:
# This program owns both the compacted prefix and its padding.
# The stores are disjoint, so no separate initialization is needed.
tl.store(
out_ptr + token_id * out_stride0 + indice_id * out_stride1,
-1,
mask=(indice_id >= tile_valid_count)
& (indice_id < NUM_TOPK_TOKENS),
)
else:
# Store results in place (input column == output column).
out_ptr_ij = out_ptr + token_id * out_stride0 + indice_id * out_stride1
tl.store(out_ptr_ij, out_val, mask=indice_id < NUM_TOPK_TOKENS)
# Accumulate the tile's valid count into the row total; a single tile's
# reduction *is* the total.
if COUNT_VALID:
tile_valid_count = tl.sum((~is_invalid_tok).to(tl.int32))
if SINGLE_TILE:
tl.store(valid_count_ptr + token_id, tile_valid_count)
else:
tl.atomic_add(valid_count_ptr + token_id, tile_valid_count)
# Keep the warmup wrapper interface while exposing a descriptive CUDA symbol.
kernel = sparse_mla_index_remap_kernel
def dispatch( # type: ignore[override]
self,
*,
BLOCK_SIZE: int,
BLOCK_STRIDE_ROWS: int,
BLOCK_N: int,
NUM_TOPK_TOKENS: int,
HAS_PREFILL_WORKSPACE: bool,
COUNT_VALID: bool,
COMPACT_TO_FRONT: bool,
DCP_SIZE: int,
DCP_RANK: int,
DCP_INTERLEAVE: int,
max_num_blocks_per_req: int,
) -> CompileKey:
tiling = _remap_tiling(NUM_TOPK_TOKENS, BLOCK_N, COUNT_VALID)
return self.CompileKey(
block_size=BLOCK_SIZE,
block_stride_rows=BLOCK_STRIDE_ROWS,
block_n=tiling[1],
has_prefill_workspace=HAS_PREFILL_WORKSPACE,
count_valid=COUNT_VALID,
single_tile=tiling[0],
compact_to_front=COMPACT_TO_FRONT,
dcp_size=DCP_SIZE,
dcp_rank=DCP_RANK,
dcp_interleave=DCP_INTERLEAVE,
num_warps=tiling[3],
num_topk_tokens=NUM_TOPK_TOKENS,
block_table_stride=triton_scalar_specialization_rep(max_num_blocks_per_req),
)
def get_warmup_keys(
self,
vllm_config: VllmConfig,
*,
block_stride_rows: int,
) -> list[CompileKey]:
block_size = vllm_config.cache_config.block_size
dcp_size = vllm_config.parallel_config.decode_context_parallel_size
dcp_interleave = vllm_config.parallel_config.cp_kv_cache_interleave_size
dcp_rank = get_dcp_group().rank_in_group if dcp_size > 1 else 0
num_topk_tokens = vllm_config.model_config.hf_text_config.index_topk
max_num_blocks = cdiv(
vllm_config.model_config.max_model_len,
block_size * dcp_size,
)
max_num_blocks_per_req = get_block_table_width(max_num_blocks, block_size)
pcp_dcp_combos = []
if (
vllm_config.parallel_config.prefill_context_parallel_size > 1
and dcp_size > 1
):
# PCP + DCP attends prefill rows over a DCP-gathered workspace.
pcp_dcp_combos.append(
dict(
HAS_PREFILL_WORKSPACE=True,
COUNT_VALID=True,
COMPACT_TO_FRONT=True,
DCP_SIZE=dcp_size,
DCP_RANK=dcp_rank,
DCP_INTERLEAVE=dcp_interleave,
)
)
return self._trace_dispatch(self.dispatch)(
zip_inputs(
dict(
HAS_PREFILL_WORKSPACE=False,
COUNT_VALID=False,
COMPACT_TO_FRONT=False,
DCP_SIZE=1,
DCP_RANK=0,
DCP_INTERLEAVE=1,
),
dict(
HAS_PREFILL_WORKSPACE=False,
COUNT_VALID=True,
COMPACT_TO_FRONT=True,
DCP_SIZE=1,
DCP_RANK=0,
DCP_INTERLEAVE=1,
),
dict(
HAS_PREFILL_WORKSPACE=True,
COUNT_VALID=True,
COMPACT_TO_FRONT=True,
DCP_SIZE=1,
DCP_RANK=0,
DCP_INTERLEAVE=1,
),
dict(
HAS_PREFILL_WORKSPACE=False,
COUNT_VALID=True,
COMPACT_TO_FRONT=False,
DCP_SIZE=dcp_size,
DCP_RANK=dcp_rank,
DCP_INTERLEAVE=dcp_interleave,
),
dict(
HAS_PREFILL_WORKSPACE=False,
COUNT_VALID=True,
COMPACT_TO_FRONT=dcp_size > 1,
DCP_SIZE=dcp_size,
DCP_RANK=dcp_rank,
DCP_INTERLEAVE=dcp_interleave,
),
*pcp_dcp_combos,
),
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
BLOCK_N=128,
NUM_TOPK_TOKENS=num_topk_tokens,
max_num_blocks_per_req=max_num_blocks_per_req,
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
int32_ptr = TritonWarmupTensor(torch.int32)
token_shape = (1, compile_key.num_topk_tokens)
token_strides = (16, 1)
return dict(
req_id=int32_ptr,
block_table=TritonWarmupTensor(
torch.int32,
shape=(1, compile_key.block_table_stride),
),
token_indices=TritonWarmupTensor(
torch.int32,
shape=token_shape,
strides=token_strides,
),
out=TritonWarmupTensor(
torch.int32,
shape=token_shape,
strides=token_strides,
),
valid_counts=int32_ptr if compile_key.count_valid else None,
prefill_workspace_request_ids=(
int32_ptr if compile_key.has_prefill_workspace else None
),
prefill_workspace_starts=(
int32_ptr if compile_key.has_prefill_workspace else None
),
max_num_blocks_per_req=1,
workspace_rank_stride=1,
BLOCK_SIZE=compile_key.block_size,
BLOCK_STRIDE_ROWS=compile_key.block_stride_rows,
BLOCK_N=compile_key.block_n,
NUM_TOPK_TOKENS=compile_key.num_topk_tokens,
HAS_PREFILL_WORKSPACE=compile_key.has_prefill_workspace,
COUNT_VALID=compile_key.count_valid,
COMPACT_TO_FRONT=compile_key.compact_to_front,
DCP_SIZE=compile_key.dcp_size,
DCP_RANK=compile_key.dcp_rank,
DCP_INTERLEAVE=compile_key.dcp_interleave,
)
@kernel_launcher
def __call__(
self,
req_id: torch.Tensor,
block_table: torch.Tensor,
token_indices: torch.Tensor,
out: torch.Tensor,
valid_counts: torch.Tensor | None,
prefill_workspace_request_ids: torch.Tensor | None,
prefill_workspace_starts: torch.Tensor | None,
*,
workspace_rank_stride: int,
max_num_blocks_per_req: int,
BLOCK_SIZE: int,
BLOCK_STRIDE_ROWS: int,
BLOCK_N: int,
NUM_TOPK_TOKENS: int,
HAS_PREFILL_WORKSPACE: bool,
COUNT_VALID: bool,
COMPACT_TO_FRONT: bool,
DCP_SIZE: int,
DCP_RANK: int,
DCP_INTERLEAVE: int,
) -> LaunchSpec:
single_tile, block_n, tiles_per_row, num_warps = _remap_tiling(
NUM_TOPK_TOKENS, BLOCK_N, COUNT_VALID
)
# Exact 2D grid: tokens × column tiles
return (req_id.shape[0], tiles_per_row), dict(
valid_count_ptr=valid_counts,
prefill_request_id_ptr=prefill_workspace_request_ids,
workspace_starts_ptr=prefill_workspace_starts,
BLOCK_N=block_n,
HAS_PREFILL=HAS_PREFILL_WORKSPACE,
SINGLE_TILE=single_tile,
# Strides in elements
bt_stride0=block_table.stride(0),
bt_stride1=block_table.stride(1),
ti_stride0=token_indices.stride(0),
ti_stride1=token_indices.stride(1),
out_stride0=out.stride(0),
out_stride1=out.stride(1),
num_warps=num_warps,
)
def _remap_tiling(
NUM_TOPK_TOKENS: int, BLOCK_N: int, count_valid: bool
) -> tuple[bool, int, int, int]:
"""Pick the column tiling for the index remap kernel.
Counting the valid slots per row is the only reason the column tiles have to
talk to each other, so when counting give one program the whole row: the
count becomes an in-register reduction plus a plain store, needing neither
atomics nor a zero-initialized counter. Pad modest non-power-of-two widths
(including GLM's 2176 entries) to one tile; larger widths stay tiled and atomic.
Returns:
(single_tile, block_n, tiles_per_row, num_warps)
"""
padded_width = triton.next_power_of_2(NUM_TOPK_TOKENS)
single_tile = count_valid and (
padded_width == NUM_TOPK_TOKENS or padded_width <= 4096
)
if single_tile:
return True, padded_width, 1, 8
return False, BLOCK_N, NUM_TOPK_TOKENS // BLOCK_N, 4
def triton_convert_req_index_to_global_index(
req_id: torch.Tensor, # int32 [num_tokens]
block_table: torch.Tensor, # int32 [num_requests, max_num_blocks_per_req]
token_indices: torch.Tensor, # int32 [num_tokens, NUM_TOPK_TOKENS]
BLOCK_SIZE: int = 64,
BLOCK_STRIDE_ROWS: int | None = None,
NUM_TOPK_TOKENS: int = 2048,
BLOCK_N: int = 128, # tile width along columns
HAS_PREFILL_WORKSPACE: bool = False,
prefill_workspace_request_ids: torch.Tensor | None = None,
prefill_workspace_starts: torch.Tensor | None = None,
prefill_workspace_rank_stride: int | None = None,
dcp_size: int = 1,
dcp_rank: int = 0,
cp_kv_cache_interleave_size: int = 1,
return_valid_counts: bool = False,
out: torch.Tensor | None = None,
valid_counts_out: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""out[token_id, indice_id] =
block_table[req_id[token_id],
token_indices[token_id, indice_id] // BLOCK_SIZE] * BLOCK_SIZE
+ token_indices[token_id, indice_id] % BLOCK_SIZE
Only when token_indices[token_id, indice_id] == -1 do we output -1.
For safety, we also output -1 if the derived block_id would be
out-of-bounds.
When HAS_PREFILL_WORKSPACE is True, prefill tokens are mapped to workspace offsets
instead of global cache slots. prefill_workspace_request_ids and
prefill_workspace_starts must be provided.
prefill_workspace_request_ids: int32 [num_tokens], -1 for decode else
prefill request index (maps to prefill_workspace_starts)
prefill_workspace_starts: int32 [num_prefills], 0-indexed workspace
starts for each prefill request
When return_valid_counts is True, also returns the count of valid (non -1)
indices per row, computed during the same kernel pass (no extra overhead).
"""
assert req_id.dtype == torch.int32
assert block_table.dtype == torch.int32
assert token_indices.dtype == torch.int32
assert req_id.shape[0] == token_indices.shape[0], (
f"req_id ({req_id.shape[0]}) and token_indices ({token_indices.shape[0]}) "
"must cover the same tokens; the grid is sized by req_id but the output "
"is allocated like token_indices, so a longer req_id writes out of bounds"
)
assert token_indices.shape[1] == NUM_TOPK_TOKENS
assert NUM_TOPK_TOKENS % BLOCK_N == 0, (
f"NUM_TOPK_TOKENS ({NUM_TOPK_TOKENS}) must be divisible by BLOCK_N ({BLOCK_N})"
)
if HAS_PREFILL_WORKSPACE:
assert prefill_workspace_request_ids is not None
assert prefill_workspace_starts is not None
assert prefill_workspace_request_ids.dtype == torch.int32
assert prefill_workspace_starts.dtype == torch.int32
num_tokens = req_id.shape[0]
max_num_blocks_per_req = block_table.shape[1]
single_tile, _, _, _ = _remap_tiling(NUM_TOPK_TOKENS, BLOCK_N, return_valid_counts)
# Ensure contiguous tensors on the same device
req_id_c = req_id.contiguous()
block_table_c = block_table.contiguous()
token_indices_c = token_indices.contiguous()
# Only multi-tile compaction needs separate padding initialization.
if out is None:
out = (
torch.full_like(token_indices_c, -1)
if return_valid_counts and not single_tile
else torch.empty_like(token_indices_c)
)
else:
assert out.dtype == token_indices_c.dtype
assert out.device == token_indices_c.device
assert out.shape == token_indices_c.shape
assert out.is_contiguous()
if return_valid_counts and not single_tile:
out.fill_(-1)
valid_counts: torch.Tensor | None = None
if return_valid_counts:
if valid_counts_out is None:
# Zero-init only matters for the atomic accumulation path.
alloc = torch.empty if single_tile else torch.zeros
valid_counts = alloc(
num_tokens, dtype=torch.int32, device=token_indices.device
)
else:
assert valid_counts_out.dtype == torch.int32
assert valid_counts_out.device == token_indices.device
assert valid_counts_out.shape == (num_tokens,)
assert valid_counts_out.is_contiguous()
valid_counts = valid_counts_out
if not single_tile:
valid_counts.zero_()
# Prepare prefill pointers
if HAS_PREFILL_WORKSPACE:
assert prefill_workspace_request_ids is not None # for mypy
assert prefill_workspace_starts is not None # for mypy
assert prefill_workspace_request_ids.is_contiguous()
assert prefill_workspace_starts.is_contiguous()
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL(
req_id_c,
block_table_c,
token_indices_c,
out,
valid_counts,
prefill_workspace_request_ids,
prefill_workspace_starts,
# shapes / constexprs
workspace_rank_stride=prefill_workspace_rank_stride or 0,
max_num_blocks_per_req=max_num_blocks_per_req,
BLOCK_SIZE=BLOCK_SIZE,
BLOCK_STRIDE_ROWS=(
BLOCK_STRIDE_ROWS if BLOCK_STRIDE_ROWS is not None else BLOCK_SIZE
),
BLOCK_N=BLOCK_N,
NUM_TOPK_TOKENS=NUM_TOPK_TOKENS,
HAS_PREFILL_WORKSPACE=HAS_PREFILL_WORKSPACE,
COUNT_VALID=return_valid_counts,
COMPACT_TO_FRONT=return_valid_counts,
DCP_SIZE=dcp_size,
DCP_RANK=dcp_rank,
DCP_INTERLEAVE=cp_kv_cache_interleave_size,
)
if return_valid_counts:
assert valid_counts is not None
return out, valid_counts
return out
def triton_filter_and_convert_dcp_index(
req_id: torch.Tensor,
block_table: torch.Tensor,
token_indices: torch.Tensor,
dcp_size: int,
dcp_rank: int,
cp_kv_cache_interleave_size: int = 1,
BLOCK_SIZE: int = 64,
BLOCK_STRIDE_ROWS: int | None = None,
NUM_TOPK_TOKENS: int = 2048,
BLOCK_N: int = 128,
return_valid_counts: bool = False,
compact_valid_to_front: bool = True,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Filter global per-request indices to this DCP rank's local slots.
With ``compact_valid_to_front`` (default), the conversion kernel scatters
this rank's owned slots to a contiguous prefix ``[0, valid_count)`` and
leaves the rest ``-1``. DCP filtering marks non-owned slots ``-1`` and so
creates interior gaps; the trtllm-gen sparse kernel reads the first
``valid_count`` entries of each row, so they must be a contiguous prefix.
Compaction is fused into the kernel (atomic slot allocator) rather than a
separate sort/gather pass. Prefix order is unspecified (only the set matters).
"""
assert dcp_size >= 1
assert 0 <= dcp_rank < dcp_size
# Interleave groups must align to KV blocks (globally enforced by
# VllmConfig: block_size % cp_kv_cache_interleave_size == 0); assert the
# local invariant so local_idx // BLOCK_SIZE never straddles a group.
assert BLOCK_SIZE % cp_kv_cache_interleave_size == 0, (
f"BLOCK_SIZE ({BLOCK_SIZE}) must be divisible by "
f"cp_kv_cache_interleave_size ({cp_kv_cache_interleave_size})."
)
assert req_id.dtype == torch.int32
assert block_table.dtype == torch.int32
assert token_indices.dtype == torch.int32
assert token_indices.shape[1] == NUM_TOPK_TOKENS
assert NUM_TOPK_TOKENS % BLOCK_N == 0
if dcp_size == 1:
return triton_convert_req_index_to_global_index(
req_id,
block_table,
token_indices,
BLOCK_SIZE=BLOCK_SIZE,
BLOCK_STRIDE_ROWS=BLOCK_STRIDE_ROWS,
NUM_TOPK_TOKENS=NUM_TOPK_TOKENS,
BLOCK_N=BLOCK_N,
return_valid_counts=return_valid_counts,
)
num_tokens = req_id.shape[0]
max_num_blocks_per_req = block_table.shape[1]
req_id_c = req_id.contiguous()
block_table_c = block_table.contiguous()
token_indices_c = token_indices.contiguous()
# The compaction uses the valid-count buffer as a slot allocator, so it
# requires counting. Only the multi-tile path needs pre-filled padding.
count_valid = return_valid_counts or compact_valid_to_front
# The compaction builds on the counting, so it shares the tiling.
single_tile, _, _, _ = _remap_tiling(NUM_TOPK_TOKENS, BLOCK_N, count_valid)
if compact_valid_to_front and not single_tile:
out = torch.full_like(token_indices_c, -1)
else:
out = torch.empty_like(token_indices_c)
valid_counts: torch.Tensor | None = None
if count_valid:
# Zero-init only matters for the atomic accumulation path.
alloc = torch.empty if single_tile else torch.zeros
valid_counts = alloc(num_tokens, dtype=torch.int32, device=token_indices.device)
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL(
req_id_c,
block_table_c,
token_indices_c,
out,
valid_counts,
# No prefill workspace on the DCP decode path.
None,
None,
workspace_rank_stride=0,
max_num_blocks_per_req=max_num_blocks_per_req,
BLOCK_SIZE=BLOCK_SIZE,
BLOCK_STRIDE_ROWS=(
BLOCK_STRIDE_ROWS if BLOCK_STRIDE_ROWS is not None else BLOCK_SIZE
),
BLOCK_N=BLOCK_N,
NUM_TOPK_TOKENS=NUM_TOPK_TOKENS,
HAS_PREFILL_WORKSPACE=False,
COUNT_VALID=count_valid,
COMPACT_TO_FRONT=compact_valid_to_front,
DCP_SIZE=dcp_size,
DCP_RANK=dcp_rank,
DCP_INTERLEAVE=cp_kv_cache_interleave_size,
)
if return_valid_counts:
assert valid_counts is not None
return out, valid_counts
return out
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL = ConvertReqIndexToGlobalIndexKernel()
@triton.jit(do_not_specialize=["num_tokens"])
def sparse_mla_prepare_safe_lengths_kernel(
indices_ptr,
counts_ptr,
safe_lengths_ptr,
num_tokens,
index_stride0: tl.constexpr,
count_stride: tl.constexpr,
BLOCK: tl.constexpr,
):
token = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
count = tl.load(counts_ptr + token * count_stride, token < num_tokens, other=1)
tl.store(safe_lengths_ptr + token, tl.maximum(count, 1), token < num_tokens)
# TRTLLM's NoPE sparse kernel requires at least one valid KV-cache entry.
tl.store(
indices_ptr + token * index_stride0, 0, (token < num_tokens) & (count == 0)
)
def prepare_sparse_mla_safe_lengths(
physical_indices: torch.Tensor, valid_counts: torch.Tensor
) -> torch.Tensor:
"""Install dummy slots for empty queries and return nonzero kernel lengths.
Preserve the raw counts so empty outputs and LSE can be neutralized later.
"""
num_tokens = valid_counts.numel()
safe_lengths = torch.empty(
(num_tokens,), dtype=valid_counts.dtype, device=valid_counts.device
)
if num_tokens:
sparse_mla_prepare_safe_lengths_kernel[(triton.cdiv(num_tokens, 256),)](
physical_indices,
valid_counts,
safe_lengths,
num_tokens,
physical_indices.stride(0),
valid_counts.stride(0),
BLOCK=256,
)
return safe_lengths
@@ -1,362 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TokenSpeed CuTe DSL MLA decode backend (Blackwell, FP8 KV cache only)."""
from typing import TYPE_CHECKING, ClassVar
import torch
from vllm.config import get_current_vllm_config
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
QueryLenSupport,
)
from vllm.platforms.interface import DeviceCapability
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
AttentionType,
MultipleOf,
)
from vllm.v1.worker.workspace import current_workspace_manager
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.v1.kv_cache_interface import AttentionSpec
logger = init_logger(__name__)
# Workspace upper bound for tokenspeed_mla_decode (per-device, lazy):
# num_sms * num_heads * MAX_Q_LEN * (kv_lora_rank + 1) * sizeof(float32)
# Matches the kernel's `get_workspace_size` formula. MAX_Q_LEN=8 covers up to
# EAGLE3 / MTP-2 spec decoding query lengths; larger q_len fails the kernel's
# own buffer check.
_TOKENSPEED_MAX_Q_LEN = 8
def _get_workspace(
device: torch.device,
num_heads: int,
kv_lora_rank: int,
min_split_kv: int,
max_decode_tokens: int,
) -> torch.Tensor:
from tokenspeed_mla import get_num_sm
# TokenSpeed reduction scratch: B * H * Q * split_kv * (D + 1) * 4 bytes,
# using the effective query layout and FP32 partial outputs plus LSE.
# Automatic splitting lowers split_kv as the batch grows; split_kv=1
# needs no reduction scratch, so an SM-based bound covers all batch sizes.
needed = (
get_num_sm(device) * num_heads * _TOKENSPEED_MAX_Q_LEN * (kv_lora_rank + 1) * 4
)
if min_split_kv > 1:
# A forced floor breaks that bound: reserve for the maximum batch.
# Packed queries pad head rows to 128; reserve one tile per query token.
needed = max(
needed,
max_decode_tokens
* max(num_heads, 128)
* min_split_kv
* (kv_lora_rank + 1)
* 4,
)
logger.info_once(
"TokenSpeed MLA decode workspace: %.2f GiB", needed / (1 << 30)
)
return current_workspace_manager().get_simultaneous(((needed,), torch.int8))[0]
class TokenspeedMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM
# The kernel accepts an explicit causal mask, so a non-causal DSpark
# block can remain fused instead of being flattened to single tokens.
supports_non_causal_multi_token_decode: ClassVar[bool] = True
supports_non_causal_multi_token_dcp: ClassVar[bool] = True
def __init__(
self,
kv_cache_spec: "AttentionSpec",
layer_names: list[str],
vllm_config: "VllmConfig",
device: torch.device,
) -> None:
super().__init__(
kv_cache_spec,
layer_names,
vllm_config,
device,
MLACommonMetadata,
supports_dcp_with_varlen=True,
)
class TokenspeedMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [32, 64]
@staticmethod
def get_name() -> str:
return "TOKENSPEED_MLA"
@staticmethod
def get_impl_cls() -> type["TokenspeedMLAImpl"]:
return TokenspeedMLAImpl
@staticmethod
def get_builder_cls() -> type["TokenspeedMLAMetadataBuilder"]:
return TokenspeedMLAMetadataBuilder
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 10
@classmethod
def supports_non_causal(cls) -> bool:
return True
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: DeviceCapability,
) -> str | None:
# Surface a clear install hint up front rather than letting a raw
# ModuleNotFoundError fire deep inside `forward_mqa` at first request.
try:
import tokenspeed_mla # noqa: F401
except ImportError:
return (
"tokenspeed_mla package is not installed. "
"Install it with: `uv pip install tokenspeed-mla`"
)
# tokenspeed_mla CuTe DSL kernel is shape-specialized for DeepSeek R1
# MLA dimensions (qk_nope=128, qk_rope=64, v=128). Reject anything else.
from vllm.config import get_current_vllm_config
vllm_config = get_current_vllm_config()
if vllm_config.model_config is not None:
hf_text_config = vllm_config.model_config.hf_text_config
qk_nope_head_dim = getattr(hf_text_config, "qk_nope_head_dim", 0)
qk_rope_head_dim = getattr(hf_text_config, "qk_rope_head_dim", 0)
v_head_dim = getattr(hf_text_config, "v_head_dim", 0)
if qk_nope_head_dim != 128 or qk_rope_head_dim != 64 or v_head_dim != 128:
return (
"tokenspeed_mla requires DeepSeek R1 MLA dimensions "
"(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128), "
f"got ({qk_nope_head_dim}, {qk_rope_head_dim}, {v_head_dim})"
)
return None
class TokenspeedMLAImpl(MLACommonImpl[MLACommonMetadata]):
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
supports_mtp_with_cp_non_trivial_interleave_size: bool = True
# tokenspeed_mla_decode returns LSE in log2 units; its own DCP test merges
# partial outputs with exp2(lse).
lse_base_on_e: bool = False
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"TokenspeedMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"TokenspeedMLAImpl"
)
if not is_quantized_kv_cache(self.kv_cache_dtype):
raise NotImplementedError(
"TokenspeedMLAImpl requires an FP8 KV cache "
"(--kv-cache-dtype fp8 or fp8_e4m3); "
f"got kv_cache_dtype={self.kv_cache_dtype!r}."
)
config = get_current_vllm_config()
self._min_split_kv = config.attention_config.tokenspeed_mla_min_split_kv
self._max_decode_tokens = 0
if self._min_split_kv > 1:
spec = config.speculative_config
query_len = 1 + (spec.num_speculative_tokens if spec else 0)
self._max_decode_tokens = max(
min(
config.scheduler_config.max_num_batched_tokens,
config.scheduler_config.max_num_seqs * query_len,
),
config.compilation_config.max_cudagraph_capture_size or 0,
)
self.softmax_scale: float | None = None
self.output_scale: float | None = None
# NIXL resolves interleaving after model construction; retain the config
# rather than caching its initial interleave size.
self._parallel_config = config.parallel_config
# Pre-JIT BF16 and FP8 prefill kernels here too — decode impl always
# runs when tokenspeed is selected, prefill backend may not (user can
# pair with flash_attn / trtllm). Idempotent.
from tokenspeed_mla import warmup_compile_prefill
for q_dtype in (torch.bfloat16, torch.float8_e4m3fn):
warmup_compile_prefill(
q_dtype=q_dtype,
d_qk=self.qk_nope_head_dim + self.qk_rope_head_dim,
d_v=self.v_head_dim,
enable_pdl=False,
)
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
from tokenspeed_mla import tokenspeed_mla_decode
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
if isinstance(q, tuple):
q_nope, q_pe = q
q = torch.cat([q_nope, q_pe], dim=-1)
# supports_quant_query_input=True (set in MLACommonImpl) tells the
# pipeline to concat+FP8-quantize Q upstream via _decode_concat_quant_fp8_op.
# The kernel is shape-specialized for FP8 Q + FP8 KV, so anything else
# here means the upstream quant didn't run and the kernel will produce
# garbage.
assert q.dtype == torch.float8_e4m3fn, (
f"TokenspeedMLAImpl expected FP8 query (supports_quant_query_input=True), "
f"got {q.dtype}. Pipeline isinstance(q, tuple)={isinstance(q, tuple)}, "
f"q_scale={layer._q_scale_float}, k_scale={layer._k_scale_float}."
)
num_decodes = attn_metadata.num_decodes
num_decode_tokens = attn_metadata.num_decode_tokens
block_tables = attn_metadata.decode.block_table
seq_lens = attn_metadata.decode.seq_lens
causal_seqs = attn_metadata.decode.dcp_tot_seq_lens
# tokenspeed_mla_decode expects query shape
# (num_decodes, q_len_per_request, num_heads, head_dim).
if num_decode_tokens % num_decodes != 0:
logger.warning_once(
"""TokenspeedMLAImpl got a query of uneven length.
This usually indicates an issue in batch reordering
or incorrect setup in dummy_run."""
)
q = q.unsqueeze(1)
else:
q = q.view(num_decodes, -1, q.shape[-2], q.shape[-1])
if self.softmax_scale is None:
# FP8 KV cache is mandatory for this backend, so q_scale/k_scale
# always apply. softmax_scale is bmm1; output_scale is bmm2 — both
# required to recover the correct attention output from the FP8
# KV cache (V is stored as V_real/k_scale).
self.softmax_scale = (
self.scale * layer._q_scale_float * layer._k_scale_float
)
self.output_scale = layer._k_scale_float
workspace = _get_workspace(
q.device,
q.shape[-2],
self.kv_lora_rank,
self._min_split_kv,
self._max_decode_tokens,
)
# vLLM kv_c_and_k_pe_cache is already (num_blocks, block_size, head_size).
# tokenspeed_mla_decode wants 3D — pass as-is (no unsqueeze, unlike trtllm).
return_lse = self.need_to_return_lse_for_decode
kernel_out = tokenspeed_mla_decode(
query=q,
kv_cache=kv_c_and_k_pe_cache,
workspace_buffer=workspace,
kv_lora_rank=self.kv_lora_rank,
qk_rope_head_dim=self.qk_rope_head_dim,
block_tables=block_tables,
seq_lens=seq_lens,
max_seq_len=attn_metadata.max_seq_len,
softmax_scale=self.softmax_scale,
output_scale=self.output_scale,
enable_pdl=False,
return_lse=return_lse,
causal_mask=attn_metadata.causal,
causal_seqs=causal_seqs if self.dcp_world_size > 1 else None,
cp_world=self.dcp_world_size,
cp_rank=self.dcp_rank,
cp_interleave_size=self._parallel_config.cp_kv_cache_interleave_size,
min_split_kv=self._min_split_kv,
)
if return_lse:
o, lse = kernel_out
# DCP ranks with no local KV may return undefined outputs (e.g.,
# NaNs). The downstream DCP combine path must mask empty
# shards and ignore their outputs when merging partial attention.
lse = lse.view(-1, lse.shape[-1])
else:
o, lse = kernel_out, None
o = o.view(-1, o.shape[-2], o.shape[-1])
return o, lse
@@ -1,328 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import ClassVar
import torch
import vllm.envs as envs
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBackend,
MLACommonImpl,
MLACommonMetadata,
MLACommonMetadataBuilder,
QueryLenSupport,
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.triton_utils import triton
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionLayer,
AttentionType,
MultipleOf,
)
from vllm.v1.attention.ops.triton_decode_attention import decode_attention_fwd
from vllm.v1.worker.workspace import (
current_workspace_manager,
is_workspace_manager_initialized,
)
logger = init_logger(__name__)
# num_kv_splits selection (shared by forward_mqa and the workspace reservation
# so the two cannot drift). Both are hardware dependent.
_MIN_WORK_PER_SPLIT = 512
_SPLIT_OCCUPANCY_MULTIPLIER = 2
def _compute_num_kv_splits(max_seq_len: int, sm_count: int) -> int:
# Power of 2 to avoid excessive kernel instantiations, capped by an SM-based
# maximum (occupancy multiplier allows multiple blocks per SM
# for latency hiding).
ideal_splits = triton.next_power_of_2(max(1, max_seq_len // _MIN_WORK_PER_SPLIT))
max_splits = sm_count * _SPLIT_OCCUPANCY_MULTIPLIER
return min(ideal_splits, max_splits)
class TritonMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
# forward_mqa flattens a uniform multi-token block to one decode row per
# query token, so causal and non-causal blocks both take the decode path.
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM
supports_non_causal_multi_token_decode: ClassVar[bool] = True
def __init__(self, kv_cache_spec, layer_names, vllm_config, device):
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
# DCP local sequence lengths are not advanced between draft steps.
self.supports_draft_decode_metadata_update = self.dcp_world_size == 1
self._reserve_attn_logits_workspace()
def update_draft_decode_metadata(self, _metadata: MLACommonMetadata) -> None:
pass
def _reserve_attn_logits_workspace(self) -> None:
"""Pre-size the shared workspace for the decode split-KV attn logits.
Reserving at the worst case (max_model_len -> max num_kv_splits,
max_num_seqs decode tokens) before warmup/cudagraph capture means the
per-call ``get_simultaneous`` in ``forward_mqa`` never has to grow the
buffer at runtime (which would raise once the workspace is locked).
"""
if not is_workspace_manager_initialized():
return
# forward_mqa flattens each request's block to query_len decode rows,
# and query_len is bounded by the reorder threshold.
B = (
self.vllm_config.scheduler_config.max_num_seqs
* self.reorder_batch_threshold
)
# DCP all-gathers the query heads before forward_mqa.
q_num_heads = self.num_heads * self.dcp_world_size
max_splits = _compute_num_kv_splits(
self.model_config.max_model_len,
current_platform.num_compute_units(),
)
lse_dim = self.mla_dims.kv_lora_rank + 1
current_workspace_manager().get_simultaneous(
((B, q_num_heads, max_splits, lse_dim), torch.float32),
)
class TritonMLABackend(MLACommonBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return []
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
def supports_block_size(cls, block_size: int | None) -> bool:
if block_size is None:
return True
return block_size % 16 == 0
@staticmethod
def get_name() -> str:
return "TRITON_MLA"
@classmethod
def supports_batch_invariance(cls) -> bool:
return True
@staticmethod
def get_impl_cls() -> type["TritonMLAImpl"]:
return TritonMLAImpl
@staticmethod
def get_builder_cls() -> type["TritonMLAMetadataBuilder"]:
return TritonMLAMetadataBuilder
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return True
@classmethod
def supports_non_causal(cls) -> bool:
# DSpark non-causal blocks are flattened to single-token decode rows in
# TritonMLAImpl.forward_mqa (decode_attention_fwd has no causal flag /
# no intra-block masking). Enables the non-causal AMD MLA path.
return True
class TritonMLAImpl(MLACommonImpl[MLACommonMetadata]):
can_return_lse_for_decode: bool = True
supports_dcp: bool = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
**mla_args,
)
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
if any(unsupported_features):
raise NotImplementedError(
"TritonMLAImpl does not support one of the following: "
"alibi_slopes, sliding_window, logits_soft_cap"
)
if attn_type != AttentionType.DECODER:
raise NotImplementedError(
"Encoder self-attention and "
"encoder/decoder cross-attention "
"are not implemented for "
"TritonMLAImpl"
)
if current_platform.is_cuda():
cap = current_platform.get_device_capability()
cap_str = cap.as_version_str() if cap is not None else "unknown"
dev = current_platform.get_device_name()
if self.kv_cache_dtype.startswith("fp8") and not (
current_platform.has_device_capability(89)
):
suggested = (
"float16" if (cap is None or cap.to_int() < 80) else "bfloat16"
)
raise ValueError(
f"FP8 KV cache is not supported by the Triton MLA backend "
f"on {dev} (compute capability {cap_str}); native FP8 "
f"(fp8e4nv) requires SM89+. Re-run with "
f"--kv-cache-dtype {suggested}."
)
if self.kv_cache_dtype == "bfloat16" and not (
current_platform.has_device_capability(80)
):
raise ValueError(
f"bfloat16 KV cache is not supported by the Triton MLA "
f"backend on {dev} (compute capability {cap_str}); "
f"bfloat16 requires SM80+. Re-run with "
f"--kv-cache-dtype float16."
)
# For FP8 KV cache, we dequantize to BF16 on load inside the
# Triton kernel. Tell the common layer not to quantize queries
# to FP8 — we handle FP8 KV cache with BF16 queries (Mode 1).
if is_quantized_kv_cache(self.kv_cache_dtype):
self.supports_quant_query_input = False
self._sm_count = current_platform.num_compute_units()
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
if type(q) is tuple:
q = torch.cat(q, dim=-1)
assert isinstance(q, torch.Tensor)
B = q.shape[0]
q_num_heads = q.shape[1]
o = torch.zeros(
B, q_num_heads, self.kv_lora_rank, dtype=q.dtype, device=q.device
)
lse = torch.zeros(B, q_num_heads, dtype=q.dtype, device=q.device)
# For batch invariance, use only 1 split to ensure deterministic reduction
if envs.VLLM_BATCH_INVARIANT:
num_kv_splits = 1
else:
num_kv_splits = _compute_num_kv_splits(
attn_metadata.max_seq_len, self._sm_count
)
# NOTE: the +1 stores the LogSumExp (LSE) that the stage2 kernel uses to
# merge partial attention outputs across splits. The scratch is served
# from the shared workspace (reserved at max in the metadata builder), so
# there is no per-call allocation on the decode hot path. Fall back to a
# direct allocation when the workspace manager is not initialized (e.g.
# unit tests without a GPUModelRunner).
logits_shape = (B, q_num_heads, num_kv_splits, self.kv_lora_rank + 1)
if is_workspace_manager_initialized():
(attn_logits,) = current_workspace_manager().get_simultaneous(
(logits_shape, torch.float32),
)
else:
attn_logits = torch.empty(
logits_shape, dtype=torch.float32, device=q.device
)
# Add a head dim of 1
kv_c_and_k_pe_cache = kv_c_and_k_pe_cache.unsqueeze(2)
kv_c_cache = kv_c_and_k_pe_cache[..., : self.kv_lora_rank]
PAGE_SIZE = kv_c_and_k_pe_cache.size(1)
block_table = attn_metadata.decode.block_table
seq_lens = attn_metadata.decode.seq_lens
# decode_attention_fwd has no causal flag: it launches one program per
# row of q and reads that row's KV extent from seq_lens, so intra-block
# causality is expressed as per-row extents. Deriving query_len from the
# tensors the kernel indexes keeps the three row counts in step.
num_decodes = seq_lens.shape[0]
query_len, remainder = divmod(B, num_decodes) if num_decodes else (1, 0)
assert remainder == 0, (
f"non-uniform decode block: {B} query rows over {num_decodes} requests"
)
if query_len > 1:
block_table = block_table.repeat_interleave(query_len, dim=0)
if attn_metadata.causal:
# Per-row extents are offsets off the global sequence length;
# under DCP seq_lens is this rank's local slice instead.
assert self.dcp_world_size == 1, (
"causal multi-token decode is not supported with DCP"
)
# Row t attends the prefix plus block tokens 0..t. Clamp holds
# padding rows at extent 0; the kernel skips them either way
# (split_kv_end == split_kv_start).
offsets = torch.arange(
1 - query_len, 1, device=seq_lens.device, dtype=seq_lens.dtype
)
seq_lens = (seq_lens.unsqueeze(1) + offsets).flatten().clamp(min=0)
else:
# Non-causal draft block: every row sees the same prefix.
seq_lens = seq_lens.repeat_interleave(query_len)
# Run MQA — always pass layer scales. When KV cache is
# BF16 the kernel's `if dtype.is_fp8()` check is a no-op.
decode_attention_fwd(
q,
kv_c_and_k_pe_cache,
kv_c_cache,
o,
lse,
block_table,
seq_lens,
attn_logits,
num_kv_splits,
self.scale,
PAGE_SIZE,
k_scale=layer._k_scale,
v_scale=layer._k_scale,
is_mla=True,
)
return o, lse
@@ -1,282 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar, Optional
import numpy as np
import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import (
get_mla_dims,
)
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SharedTopkIndicesBuffer,
)
from vllm.utils.torch_utils import is_quantized_kv_cache, np_to_pinned_tensor
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionLayer,
AttentionMetadata,
AttentionMetadataBuilder,
CommonAttentionMetadata,
MLAAttentionImpl,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
align_blocks_to_rows,
flat_kv_row_view,
triton_convert_req_index_to_global_index,
)
from vllm.v1.attention.ops.xpu_mla_sparse import triton_bf16_mla_sparse_interface
from vllm.v1.kv_cache_interface import AttentionSpec
if TYPE_CHECKING:
from vllm.model_executor.models.deepseek_v2 import Indexer
logger = init_logger(__name__)
class XPUMLASparseBackend(AttentionBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
]
@staticmethod
def get_name() -> str:
return "XPU_MLA_SPARSE"
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
return align_blocks_to_rows(spec)
@staticmethod
def get_metadata_cls() -> type["XPUMLASparseMetadata"]:
return XPUMLASparseMetadata
@staticmethod
def get_builder_cls() -> type["XPUMLASparseMetadataBuilder"]:
return XPUMLASparseMetadataBuilder
@staticmethod
def get_impl_cls() -> type["XPUMLASparseImpl"]:
return XPUMLASparseImpl
@classmethod
def is_mla(cls) -> bool:
return True
@classmethod
def is_sparse(cls) -> bool:
return True
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [576]
@dataclass
class XPUMLASparseMetadata(AttentionMetadata):
num_reqs: int
max_query_len: int
max_seq_len: int
num_actual_tokens: int # Number of tokens excluding padding.
query_start_loc: torch.Tensor
slot_mapping: torch.Tensor
block_table: torch.Tensor
req_id_per_token: torch.Tensor
block_size: int = 1
topk_tokens: int = 2048
# The shared MLA layer (`mla_attention.py::forward_impl`) reads these
# decode/prefill counts unconditionally for every MLA metadata (it asserts
# `num_decodes`/`num_prefills`/`num_decode_tokens is not None` and uses
# `num_decode_tokens` to split MQA vs dense-MHA tokens). The CUDA sparse
# backends carry them via `SparseMLACommonMetadataBuilder`; this XPU backend
# builds its own metadata and previously omitted them, so a sparse-MLA
# (DeepSeek / GLM DSA) run on XPU crashed with
# `'XPUMLASparseMetadata' object has no attribute 'num_decode_tokens'`.
# This backend serves both prefill and decode through the top-k sparse MQA
# path (see `forward_mqa`), so all tokens are routed as "decode"
# (`num_decode_tokens == num_actual_tokens`, `num_prefills == 0`); that keeps
# the shared layer's `num_mha_tokens` at 0 and never enters the dense-MHA
# prefill branch (which needs prefill-only fields this backend lacks).
num_decodes: int = 0
num_prefills: int = 0
num_decode_tokens: int = 0
@dataclass
class XPUMLASparseMetadataBuilder(AttentionMetadataBuilder[XPUMLASparseMetadata]):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.NEVER
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
):
self.kv_cache_spec = kv_cache_spec
self.model_config = vllm_config.model_config
parallel_config = vllm_config.parallel_config
self.device = device
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
self.num_heads = self.model_config.get_num_attention_heads(parallel_config)
self.mla_dims = get_mla_dims(self.model_config)
self.topk_tokens = vllm_config.model_config.hf_text_config.index_topk
self.topk_tokens_tensor = torch.tensor(
[self.topk_tokens], device=device, dtype=torch.int32
)
self.max_model_len_tensor = torch.tensor(
[self.model_config.max_model_len], device=device, dtype=torch.int32
)
# this is ignored by `flash_mla_with_kvcache` if indices not None
self.dummy_block_table = torch.empty(
(1, 1), dtype=torch.int32, device=self.device
)
self.req_id_per_token_buffer = torch.empty(
(max_num_batched_tokens,),
dtype=torch.int32,
device=device,
)
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> XPUMLASparseMetadata:
num_tokens = common_attn_metadata.num_actual_tokens
starts = np.asarray(common_attn_metadata.query_start_loc_cpu, dtype=np.int32)
seg_lengths = np.diff(starts)
req_id_per_token = np.repeat(
np.arange(seg_lengths.shape[0], dtype=np.int32), seg_lengths
)
# Zero-fill for cudagraphs
self.req_id_per_token_buffer.fill_(0)
self.req_id_per_token_buffer[: req_id_per_token.shape[0]].copy_(
np_to_pinned_tensor(req_id_per_token), non_blocking=True
)
req_id_per_token = self.req_id_per_token_buffer[:num_tokens]
metadata = XPUMLASparseMetadata(
num_reqs=common_attn_metadata.num_reqs,
max_query_len=common_attn_metadata.max_query_len,
max_seq_len=common_attn_metadata.max_seq_len,
num_actual_tokens=common_attn_metadata.num_actual_tokens,
query_start_loc=common_attn_metadata.query_start_loc,
slot_mapping=common_attn_metadata.slot_mapping,
block_table=common_attn_metadata.block_table_tensor,
req_id_per_token=req_id_per_token,
block_size=self.kv_cache_spec.block_size,
topk_tokens=self.topk_tokens,
# Route every token through the sparse MQA path (see the field
# definitions above); this backend has no dense-MHA prefill.
num_decodes=common_attn_metadata.num_reqs,
num_prefills=0,
num_decode_tokens=common_attn_metadata.num_actual_tokens,
)
return metadata
class XPUMLASparseImpl(MLAAttentionImpl[XPUMLASparseMetadata], SharedTopkIndicesBuffer):
is_sparse = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
topk_indices_buffer: torch.Tensor | None = None,
indexer: Optional["Indexer"] = None,
**mla_args,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
self.scale = float(scale)
self.num_kv_heads = num_kv_heads
self.kv_cache_dtype = kv_cache_dtype
self.kv_lora_rank: int = mla_args["kv_lora_rank"]
self.softmax_scale = scale
self.init_topk_indices_buffer(indexer, topk_indices_buffer)
def _forward_bf16_kv(
self,
q: torch.Tensor, # [sq, heads, d_qk]
kv_c_and_k_pe_cache: torch.Tensor, # [blocks, heads, d_qk]
topk_indices: torch.Tensor, # [sq, topk]
attn_metadata: XPUMLASparseMetadata,
) -> torch.Tensor:
num_tokens = q.shape[0]
kv_c_and_k_pe_cache = kv_c_and_k_pe_cache.view(
-1, 1, kv_c_and_k_pe_cache.shape[-1]
)
topk_indices = topk_indices.view(num_tokens, 1, -1)
output, _, _ = triton_bf16_mla_sparse_interface(
q,
kv_c_and_k_pe_cache,
topk_indices,
sm_scale=self.softmax_scale,
)
return output[:, : self.num_heads, :]
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: XPUMLASparseMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
# NOTE(lucas): for the sparse FlashMLA kernels the kernels want to use
# MQA 576/512 approach for both prefill and decode
if is_quantized_kv_cache(self.kv_cache_dtype):
raise NotImplementedError("FP8 kv is not supported with XPU MLA Sparse yet")
# Concatenate q if it's a tuple (ql_nope, q_pe)
if isinstance(q, tuple):
q = torch.cat(q, dim=-1)
num_actual_toks = q.shape[0]
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[:num_actual_toks]
kv_rows, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
topk_indices_global = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token,
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=attn_metadata.topk_tokens,
)
attn_out = self._forward_bf16_kv(q, kv_rows, topk_indices_global, attn_metadata)
return attn_out, None
File diff suppressed because it is too large Load Diff
@@ -1,542 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention layer with PagedAttention and Triton prefix prefill."""
from typing import ClassVar
import torch
from vllm import _custom_ops as ops
from vllm._aiter_ops import IS_AITER_FOUND, rocm_aiter_ops
from vllm.config import get_current_vllm_config_or_none
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
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,
AttentionType,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.rocm_attn import (
RocmAttentionBackend,
RocmAttentionImpl,
RocmAttentionMetadata,
RocmAttentionMetadataBuilder,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
KVQuantMode,
get_kv_quant_mode,
)
logger = init_logger(__name__)
def _kv_connector_enabled() -> bool:
vllm_config = get_current_vllm_config_or_none()
if vllm_config is None:
return False
kv_transfer_config = vllm_config.kv_transfer_config
return kv_transfer_config is not None and kv_transfer_config.is_kv_transfer_instance
class RocmAiterUnifiedAttentionMetadataBuilder(RocmAttentionMetadataBuilder):
def build_for_cudagraph_capture(
self, common_attn_metadata: CommonAttentionMetadata
) -> RocmAttentionMetadata:
attn_metadata = self.build(0, common_attn_metadata)
# Avoid capturing the real maximum sequence length while preserving
# query_start_loc, which unified attention consumes during replay.
attn_metadata.seq_lens.fill_(1)
return attn_metadata
class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
"fp8_e5m2",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
def get_preferred_block_size(cls, default_block_size: int) -> int:
return 64
@classmethod
def supports_block_size(cls, block_size: int | None) -> bool:
if block_size is None:
return True
return block_size % 16 == 0
@classmethod
def supports_head_size(cls, head_size: int) -> bool:
return head_size >= 32
@classmethod
def supports_mm_prefix(cls) -> bool:
# Not implemented
return False
@classmethod
def supports_sink(cls) -> bool:
return True
@classmethod
def supports_non_causal(cls) -> bool:
return False
@classmethod
def supports_kv_connector(cls) -> bool:
return True
forward_includes_kv_cache_update: bool = False
@staticmethod
def get_name() -> str:
return "ROCM_AITER_UNIFIED_ATTN"
@staticmethod
def get_impl_cls() -> type["RocmAiterUnifiedAttentionImpl"]:
return RocmAiterUnifiedAttentionImpl
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
"""Keep K and V packed in the content dim, unlike the native HIP
kernels the base class targets."""
# block_size == 1 is the per-token page-size probe (see
# Platform.get_page_size_bytes); real blocks must be gatherable in
# 16-token units by the ROCm kernel.
if spec.block_size != 1 and spec.block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
return spec
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
# K and V come out of the content dim as transposed views rather than
# copies, so the head dim may sit on either side of the block dim, but
# the layer must stay outermost.
if _kv_connector_enabled():
# Connectors like MoRI assume contiguous blocks
return (KVCacheLayout.LBHNC,)
return (KVCacheLayout.LBHNC, KVCacheLayout.LHBNC)
@staticmethod
def get_builder_cls() -> type["RocmAiterUnifiedAttentionMetadataBuilder"]:
return RocmAiterUnifiedAttentionMetadataBuilder
@classmethod
def supports_attn_type(cls, attn_type: str) -> bool:
"""RocmAiterUnifiedAttention supports all attention types."""
return attn_type in (
AttentionType.DECODER,
AttentionType.ENCODER,
AttentionType.ENCODER_ONLY,
AttentionType.ENCODER_DECODER,
)
class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
def fused_output_quant_supported(self, quant_key: QuantKey):
return quant_key == kFp8StaticTensorSym
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: int | None = None,
sinks: torch.Tensor | None = None,
) -> None:
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
sinks,
)
logger.info_once(
"Using aiter unified attention for RocmAiterUnifiedAttentionImpl"
)
from aiter.ops.triton.unified_attention import unified_attention
from vllm.platforms.rocm import on_gfx11
self.unified_attention = unified_attention
# 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,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: RocmAttentionMetadata,
output: torch.Tensor,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with FlashAttention.
Args:
layer: The attention layer, providing the q/k/v quantization scales.
query: shape = [num_tokens, num_heads, head_size]
key: shape = [num_tokens, num_kv_heads, head_size]
value: shape = [num_tokens, num_kv_heads, head_size]
kv_cache: shape =
[num_blocks, 2, block_size, num_kv_heads, head_size]
attn_metadata: Metadata for attention.
output: Tensor that the attention result is written into.
output_scale: Scale for fused output quantization.
output_block_scale: Block scale for fused output quantization;
not supported by this backend.
Returns:
shape = [num_tokens, num_heads * head_size]
"""
if output_block_scale is not None:
raise NotImplementedError(
"fused block_scale output quantization is not yet supported"
" for RocmAttentionImpl"
)
if attn_metadata is None:
# Profiling run.
return output.fill_(0)
# IMPORTANT!
# NOTE(woosuk): With piece-wise CUDA graphs, this method is executed in
# eager-mode PyTorch. Thus, we need to be careful about any CPU overhead
# in this method. For example, `view` and `slice` (or `[:n]`) operations
# are surprisingly slow even in the case they do not invoke any GPU ops.
# Minimize the PyTorch ops in this method as much as possible.
# Whenever making a change in this method, please benchmark the
# performance to make sure it does not introduce any overhead.
num_actual_tokens = attn_metadata.num_actual_tokens
# Handle encoder attention differently - no KV cache needed
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
# For encoder attention,
# we use direct Q, K, V tensors without caching
return self._forward_encoder_attention(
query[:num_actual_tokens],
key[:num_actual_tokens],
value[:num_actual_tokens],
output[:num_actual_tokens],
attn_metadata,
layer,
)
key_cache, value_cache = self._split_kv_cache(kv_cache)
softmax_scale = self.scale
if is_quantized_kv_cache(self.kv_cache_dtype):
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
max_seqlen_k = attn_metadata.max_seq_len
block_table = attn_metadata.block_table
if attn_metadata.causal:
self.unified_attention(
q=query[:num_actual_tokens],
k=key_cache,
v=value_cache,
out=output[:num_actual_tokens],
cu_seqlens_q=cu_seqlens_q,
max_seqlen_q=max_seqlen_q,
seqused_k=seqused_k,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=True,
alibi_slopes=self.alibi_slopes,
window_size=self.sliding_window,
block_table=block_table,
softcap=self.logits_soft_cap,
q_descale=layer._q_scale if query.dtype == self.fp8_dtype else None,
k_descale=layer._k_scale,
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
# (ENCODER_DECODER, e.g. Whisper) falls back to the vLLM Triton
# unified kernel, which shares this layout and honors the flag.
from vllm.v1.attention.ops.triton_unified_attention import (
unified_attention as triton_unified_attention,
)
descale_shape = (cu_seqlens_q.shape[0] - 1, key_cache.shape[2])
triton_unified_attention(
q=query[:num_actual_tokens],
k=key_cache,
v=value_cache,
out=output[:num_actual_tokens],
cu_seqlens_q=cu_seqlens_q,
max_seqlen_q=max_seqlen_q,
seqused_k=seqused_k,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=attn_metadata.causal,
alibi_slopes=self.alibi_slopes,
window_size=self.sliding_window,
block_table=block_table,
softcap=self.logits_soft_cap,
q_descale=layer._q_scale if query.dtype == self.fp8_dtype else None,
k_descale=layer._k_scale.expand(descale_shape),
v_descale=layer._v_scale.expand(descale_shape),
sinks=self.sinks,
output_scale=output_scale,
)
return output
def do_kv_cache_update(
self,
layer: AttentionLayer,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
):
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
# For encoder attention,
# we use direct Q, K, V tensors without caching
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,
value,
key_cache,
value_cache,
slot_mapping,
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
)
def fused_rope_kvcache_supported(self):
return rocm_aiter_ops.is_enabled()
def fused_qk_norm_rope_kvcache_supported(self):
return rocm_aiter_ops.is_enabled()
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,
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,
):
key_cache, value_cache = self._split_kv_cache(kv_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=self._use_shuffle_kv,
return_kv=False,
)
def do_qk_norm_mrope_kvcache_update(
self,
layer: AttentionLayer,
qkv: torch.Tensor,
q_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,
mrope_section: tuple[int, int, int],
is_interleaved: bool,
rotary_dim: int,
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
key_cache, value_cache = self._split_kv_cache(kv_cache)
rocm_aiter_ops.do_qk_norm_mrope_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,
mrope_section=list(mrope_section),
is_interleaved=is_interleaved,
rms_norm_eps=rms_norm_eps,
q_out=q_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,
rotary_dim=rotary_dim,
)
def do_rope_and_kv_cache_update(
self,
layer: AttentionLayer,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
is_neox: bool,
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
# For encoder attention,
# we use direct Q, K, V tensors without caching
return
key_cache, value_cache = self._split_kv_cache(kv_cache)
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,
value,
positions,
cos_sin_cache,
is_neox,
key_cache,
value_cache,
layer_slot_mapping,
layer._k_scale,
layer._v_scale,
flash_layout,
is_fp8_kv_cache,
)
-612
View File
@@ -1,612 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention layer with PagedAttention and Triton prefix prefill."""
from dataclasses import dataclass, replace
from typing import ClassVar
import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kFp8StaticTensorSym,
)
from vllm.platforms import current_platform
from vllm.utils.torch_utils import get_dtype_size, is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionImpl,
AttentionLayer,
AttentionMetadataBuilder,
AttentionType,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.ops.chunked_prefill_paged_decode import (
chunked_prefill_paged_decode,
has_native_kv_cache_layout,
)
from vllm.v1.attention.ops.paged_attn import PagedAttention
from vllm.v1.attention.ops.triton_reshape_and_cache_flash import (
triton_reshape_and_cache_flash,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
logger = init_logger(__name__)
@dataclass
class RocmAttentionMetadata:
# NOTE(sang): Definition of context_len, query_len, and seq_len.
# |---------- N-1 iteration --------|
# |---------------- N iteration ---------------------|
# |- tokenA -|......................|-- newTokens ---|
# |---------- context_len ----------|
# |-------------------- seq_len ---------------------|
# |-- query_len ---|
num_actual_tokens: int # Number of tokens excluding padding.
max_query_len: int
query_start_loc: torch.Tensor
max_seq_len: int
seq_lens: torch.Tensor
block_table: torch.Tensor
slot_mapping: torch.Tensor
# Optional aot scheduling
scheduler_metadata: torch.Tensor | None = None
# DFlash drafting sets this to False via CommonAttentionMetadata.
causal: bool = True
class RocmAttentionMetadataBuilder(AttentionMetadataBuilder[RocmAttentionMetadata]):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
):
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
self.block_size = kv_cache_spec.block_size
model_config = vllm_config.model_config
self.num_heads_q = model_config.get_num_attention_heads(
vllm_config.parallel_config
)
self.num_heads_kv = model_config.get_num_kv_heads(vllm_config.parallel_config)
self.headdim = model_config.get_head_size()
def build_for_cudagraph_capture(
self, common_attn_metadata: CommonAttentionMetadata
) -> RocmAttentionMetadata:
attn_metadata = self.build(0, common_attn_metadata)
# When doing full graph capture, setting seq_lens to
# max_model_len will cause graph capture to be extremely
# slow, so here we set it to 1.
attn_metadata.seq_lens.fill_(1)
# Zero device query start locations to avoid invalid memory access in
# the prefix prefill kernel during graph capture (#25985).
common_attn_metadata.query_start_loc.zero_()
return attn_metadata
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> RocmAttentionMetadata:
num_actual_tokens = common_attn_metadata.num_actual_tokens
max_query_len = common_attn_metadata.max_query_len
max_seq_len = common_attn_metadata.max_seq_len
query_start_loc = common_attn_metadata.query_start_loc
seq_lens = common_attn_metadata.seq_lens
block_table_tensor = common_attn_metadata.block_table_tensor
slot_mapping = common_attn_metadata.slot_mapping
attn_metadata = RocmAttentionMetadata(
num_actual_tokens=num_actual_tokens,
max_query_len=max_query_len,
query_start_loc=query_start_loc,
max_seq_len=max_seq_len,
seq_lens=seq_lens,
block_table=block_table_tensor,
slot_mapping=slot_mapping,
causal=common_attn_metadata.causal,
)
return attn_metadata
class RocmAttentionBackend(AttentionBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [
torch.float16,
torch.bfloat16,
torch.float32,
]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
"fp8_e5m2",
]
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
# ROCM paged attention native C++ kernel only supports block sizes 16 and 32
# due to shared memory (LDS) constraints on AMD GPUs.
# See csrc/rocm/attention.cu CALL_CUSTOM_LAUNCHER_BLK macro.
# However, vLLM allows support for any multiple of 16 via the Triton path.
# As addressed in PR: https://github.com/vllm-project/vllm/pull/31380,
# non-standard models (like qwen3-next with block_size 544, or qwen3_5
# with 784 and 1056) are dynamically routed to our optimized Triton kernel
# in `do_kv_cache_update`.
return [MultipleOf(16)]
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [32, 64, 80, 96, 128, 160, 192, 224, 256]
@classmethod
def supports_mm_prefix(cls) -> bool:
# Not implemented
return False
@classmethod
def supports_sink(cls) -> bool:
# ROCM custom attention kernel does not support sinks.
# Callink this backend with sinks will cause it to fall back to the Triton
# kernel, which is less efficient than the proper triton backends.
return False
@classmethod
def supports_non_causal(cls) -> bool:
return True
@classmethod
def supports_kv_connector(cls) -> bool:
# ROCM_ATTN uses (2, num_blocks, ...) KV cache layout which is
# incompatible with KV connectors that require blocks-first layout.
return False
forward_includes_kv_cache_update: bool = False
@staticmethod
def get_name() -> str:
return "ROCM_ATTN"
@classmethod
def supports_sliding_window(cls) -> bool:
return True
@staticmethod
def get_impl_cls() -> type["RocmAttentionImpl"]:
return RocmAttentionImpl
@classmethod
def supports_attn_type(cls, attn_type: str) -> bool:
"""ENCODER_DECODER is not supported because
chunked_prefill_paged_decode's prefill kernel (context_attention_fwd)
assumes self-attention semantics: it treats passed K/V as new tokens
to mix with cached K/V. For cross-attention layers the encoder K/V
are already fully cached, so mixing them again produces incorrect
results when max_query_len > 1 (e.g. beam search).
"""
return attn_type in (
AttentionType.DECODER,
AttentionType.ENCODER,
AttentionType.ENCODER_ONLY,
)
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
"""K and V as two head groups so the native HIP kernels address each side
as one contiguous region (x-packed interior applied in split_kv_cache)."""
if spec.state_content_bytes is not None:
return spec
assert spec.head_size == spec.head_size_v, (
"Separate K/V head groups require symmetric K/V head sizes."
)
return replace(
spec,
num_head_slots=2,
state_content_bytes=spec.num_kv_heads
* spec.head_size
* get_dtype_size(spec.dtype),
)
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
# The native HIP kernels hardcode group-contiguous block addressing, so
# they need the K and V groups to span all blocks (H outermost within the layer)
# The Triton fallbacks are stride-aware, so block-interior LBHNC is also
# supported, just without the native kernels.
return (KVCacheLayout.LHBNC, KVCacheLayout.LBHNC)
@staticmethod
def get_builder_cls() -> type["RocmAttentionMetadataBuilder"]:
return RocmAttentionMetadataBuilder
class RocmAttentionImpl(AttentionImpl):
def fused_output_quant_supported(self, quant_key: QuantKey):
return quant_key == kFp8StaticTensorSym
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: int | None = None,
sinks: torch.Tensor | None = None,
) -> None:
self.attn_type = attn_type
self.num_heads = num_heads
self.head_size = head_size
self.scale = float(scale)
self.num_kv_heads = num_kv_heads
if alibi_slopes is not None:
alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
self.alibi_slopes = alibi_slopes
if sliding_window is None:
self.sliding_window = (-1, -1)
elif attn_type in (AttentionType.ENCODER, AttentionType.ENCODER_ONLY):
self.sliding_window = (sliding_window - 1, sliding_window - 1)
else:
self.sliding_window = (sliding_window - 1, 0)
self.kv_cache_dtype = kv_cache_dtype
if logits_soft_cap is None:
# In flash-attn, setting logits_soft_cap as 0 means no soft cap.
logits_soft_cap = 0
self.logits_soft_cap = logits_soft_cap
self.kv_sharing_target_layer_name = kv_sharing_target_layer_name
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
self.fp8_dtype = current_platform.fp8_dtype()
self.sinks = sinks
if sinks is not None:
assert sinks.shape[0] == num_heads, (
"Sinks must have the same number of heads as the number of "
f"heads in the layer. Sinks shape: {sinks.shape}, "
f"num_heads: {num_heads}."
)
self._use_interleaved_v_cache = False
def _forward_encoder_attention(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
output: torch.Tensor,
attn_metadata: RocmAttentionMetadata,
layer: torch.nn.Module,
) -> torch.Tensor:
"""Forward pass for encoder attention without KV cache.
Args:
query: shape = [num_encoder_tokens, num_heads, head_size]
key: shape = [num_encoder_tokens, num_kv_heads, head_size]
value: shape = [num_encoder_tokens, num_kv_heads, head_size]
output: shape = [num_encoder_tokens, num_heads, head_size]
attn_metadata: Encoder attention metadata
layer: The attention layer
"""
# For encoder attention, process FP8 quantization if needed
if is_quantized_kv_cache(self.kv_cache_dtype):
raise NotImplementedError(
"quantization is not supported for encoder attention"
)
# Use encoder-specific metadata for sequence information
query_start_loc = attn_metadata.query_start_loc
seq_lens = attn_metadata.seq_lens
max_query_len = attn_metadata.max_query_len
# Call flash attention directly on Q, K, V tensors
from vllm.v1.attention.ops.triton_prefill_attention import context_attention_fwd
context_attention_fwd(
q=query,
k=key,
v=value,
o=output,
b_start_loc=query_start_loc,
b_seq_len=seq_lens,
max_input_len=max_query_len,
is_causal=False,
softmax_scale=self.scale,
sliding_window_q=self.sliding_window[0],
sliding_window_k=self.sliding_window[1],
sinks=self.sinks,
)
return output
def forward(
self,
layer: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: RocmAttentionMetadata,
output: torch.Tensor,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with FlashAttention.
Args:
layer: The attention layer, providing the q/k/v quantization scales.
query: shape = [num_tokens, num_heads, head_size]
key: shape = [num_tokens, num_kv_heads, head_size]
value: shape = [num_tokens, num_kv_heads, head_size]
kv_cache: logical [num_blocks, 2, block_size, num_kv_heads *
head_size] under LHBNC (physically K/V-group-first)
attn_metadata: Metadata for attention.
output: Tensor that the attention result is written into.
output_scale: Scale for fused output quantization.
output_block_scale: Block scale for fused output quantization;
not supported by this backend.
Returns:
shape = [num_tokens, num_heads * head_size]
"""
if output_block_scale is not None:
raise NotImplementedError(
"fused block_scale output quantization is not yet supported"
" for RocmAttentionImpl"
)
if attn_metadata is None:
# Profiling run.
return output.fill_(0)
# IMPORTANT!
# NOTE(woosuk): With piece-wise CUDA graphs, this method is executed in
# eager-mode PyTorch. Thus, we need to be careful about any CPU overhead
# in this method. For example, `view` and `slice` (or `[:n]`) operations
# are surprisingly slow even in the case they do not invoke any GPU ops.
# Minimize the PyTorch ops in this method as much as possible.
# Whenever making a change in this method, please benchmark the
# performance to make sure it does not introduce any overhead.
num_actual_tokens = attn_metadata.num_actual_tokens
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return self._forward_encoder_attention(
query[:num_actual_tokens],
key[:num_actual_tokens],
value[:num_actual_tokens],
output[:num_actual_tokens],
attn_metadata,
layer,
)
# The bound view is logical [B, 2, N, H*hs]; split_kv_cache expects
# the K/V groups first.
key_cache, value_cache = PagedAttention.split_kv_cache(
kv_cache.transpose(0, 1), self.num_kv_heads, self.head_size
)
if is_quantized_kv_cache(self.kv_cache_dtype):
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
# q_scale only applies to an fp8 query; this path keeps the query
# in full precision, so a non-1.0 q_scale is not applicable here.
if query.dtype == self.fp8_dtype and layer._q_scale_float != 1.0:
raise NotImplementedError(
"A non 1.0 q_scale with an fp8 query is not currently "
"supported by RocmAttentionImpl."
)
cu_seqlens_q = attn_metadata.query_start_loc
seqused_k = attn_metadata.seq_lens
max_seqlen_q = attn_metadata.max_query_len
max_seqlen_k = attn_metadata.max_seq_len
block_table = attn_metadata.block_table
# Compute attention and update output up to `num_actual_tokens`.
chunked_prefill_paged_decode(
query=query[:num_actual_tokens],
key=key[:num_actual_tokens] if key is not None else None,
value=value[:num_actual_tokens] if value is not None else None,
output=output[:num_actual_tokens],
kv_cache_dtype=self.kv_cache_dtype,
key_cache=key_cache,
value_cache=value_cache,
block_table=block_table,
query_start_loc=cu_seqlens_q,
seq_lens=seqused_k,
max_seq_len=max_seqlen_k,
max_query_len=max_seqlen_q,
k_scale=layer._k_scale,
v_scale=layer._v_scale,
alibi_slopes=self.alibi_slopes,
# self.sliding_window[0] is the FlashAttention-style left span (W - 1).
# chunked_prefill_paged_decode expects the full window length W.
sliding_window=1 + self.sliding_window[0],
sm_scale=self.scale,
output_scale=output_scale,
sinks=self.sinks,
use_interleaved_v_cache=self._use_interleaved_v_cache,
causal=attn_metadata.causal,
)
return output
def do_kv_cache_update(
self,
layer: AttentionLayer,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
):
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return
key_cache, value_cache = PagedAttention.split_kv_cache(
kv_cache.transpose(0, 1), self.num_kv_heads, self.head_size
)
# Reshape the input keys and values and store them in the cache.
# Get the actual block_size from value_cache
# value_cache shape: [num_blocks, num_heads, head_size, block_size]
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(
key,
value,
key_cache,
value_cache,
slot_mapping,
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
interleaved_v,
)
else:
# Non-standard blocks and hybrid attention/Mamba layouts need the
# stride-aware Triton writer. The native reshape_and_cache kernel
# assumes contiguous block storage and writes to the wrong hybrid
# cache blocks.
triton_reshape_and_cache_flash(
key,
value,
key_cache,
value_cache,
slot_mapping,
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()
def do_rope_and_kv_cache_update(
self,
layer: AttentionLayer,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
is_neox: bool,
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return
key_cache, value_cache = PagedAttention.split_kv_cache(
kv_cache.transpose(0, 1),
layer.num_kv_heads, # type: ignore[attr-defined]
layer.head_size, # type: ignore[attr-defined]
)
flash_layout = False
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)
rocm_aiter_ops.triton_rope_and_cache(
query,
key,
value,
positions,
cos_sin_cache,
is_neox,
key_cache,
value_cache,
layer_slot_mapping,
layer._k_scale,
layer._v_scale,
flash_layout,
is_fp8_kv_cache,
)
@@ -1,370 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ROCm attention backend for token-major segmented Triton attention."""
import os
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar
import torch
import vllm.envs as envs
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import VllmConfig, get_current_vllm_config
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import AttentionLayer, AttentionType
from vllm.v1.attention.backends.rocm_attn import (
RocmAttentionBackend,
RocmAttentionImpl,
RocmAttentionMetadata,
RocmAttentionMetadataBuilder,
)
from vllm.v1.attention.backends.utils import get_num_attention_heads_from_layers
from vllm.v1.attention.ops.segmented_attention import (
get_segmented_attention_workspace,
segmented_attention,
segmented_attention_workspace_size,
)
from vllm.v1.attention.ops.triton_reshape_and_cache_flash import (
triton_reshape_and_cache_flash,
)
from vllm.v1.kv_cache_interface import AttentionSpec
if TYPE_CHECKING:
from vllm.platforms.interface import DeviceCapability
logger = init_logger(__name__)
def is_rdna() -> bool:
if not current_platform.is_rocm():
return False
from vllm.platforms.rocm import on_gfx1x
return on_gfx1x()
class RocmSegmentedAttentionMetadataBuilder(RocmAttentionMetadataBuilder):
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
):
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
model_config = vllm_config.model_config
self.num_heads_q = get_num_attention_heads_from_layers(
vllm_config, layer_names
) or model_config.get_num_attention_heads(vllm_config.parallel_config)
self.num_heads_kv = kv_cache_spec.num_kv_heads
self.headdim = kv_cache_spec.head_size
class RocmSegmentedAttentionBackend(RocmAttentionBackend):
"""Explicit token-major ROCm backend optimized for segmented prefill."""
supported_dtypes: ClassVar[list[torch.dtype]] = [
torch.float16,
torch.bfloat16,
]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"float16",
"bfloat16",
"fp8",
"fp8_e4m3",
]
@staticmethod
def get_name() -> str:
return "ROCM_SEGMENTED_ATTN"
@staticmethod
def get_impl_cls() -> type["RocmSegmentedAttentionImpl"]:
return RocmSegmentedAttentionImpl
@staticmethod
def get_builder_cls() -> type["RocmSegmentedAttentionMetadataBuilder"]:
return RocmSegmentedAttentionMetadataBuilder
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [64, 128, 256]
@classmethod
def supports_attn_type(cls, attn_type: str) -> bool:
return attn_type == AttentionType.DECODER
@classmethod
def supports_non_causal(cls) -> bool:
return True
@classmethod
def supports_sliding_window(cls) -> bool:
return True
@classmethod
def supports_sink(cls) -> bool:
return True
@classmethod
def supports_mm_prefix(cls) -> bool:
return False
@classmethod
def supports_combination(
cls,
head_size: int,
dtype: torch.dtype,
kv_cache_dtype: CacheDType | None,
block_size: int | None,
use_mla: bool,
has_sink: bool,
use_sparse: bool,
use_mm_prefix: bool,
device_capability: "DeviceCapability",
) -> str | None:
del (
head_size,
dtype,
block_size,
use_mla,
has_sink,
use_sparse,
use_mm_prefix,
device_capability,
)
if not is_rdna():
return "ROCM_SEGMENTED_ATTN requires AMD RDNA GPUs on ROCm"
from vllm.platforms.rocm import on_gfx12x
if kv_cache_dtype in ("fp8", "fp8_e4m3") and not on_gfx12x():
return "FP8 segmented attention requires gfx12"
return None
class RocmSegmentedAttentionImpl(RocmAttentionImpl):
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: int | None = None,
sinks: torch.Tensor | None = None,
) -> None:
if not is_rdna():
raise ValueError("ROCM_SEGMENTED_ATTN requires AMD RDNA GPUs on ROCm")
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
sinks,
)
from vllm.platforms.rocm import on_gfx1x, on_gfx12x
fp8 = kv_cache_dtype in ("fp8", "fp8_e4m3")
arch_supported = on_gfx12x() if fp8 else on_gfx1x()
gqa_ratio_supported = (
num_kv_heads > 0
and num_heads % num_kv_heads == 0
and 1 <= self.num_queries_per_kv <= 16
)
if not (
arch_supported
and attn_type == AttentionType.DECODER
and head_size in (64, 128, 256)
and gqa_ratio_supported
and kv_cache_dtype in ("auto", "float16", "bfloat16", "fp8", "fp8_e4m3")
and alibi_slopes is None
):
raise ValueError(
"ROCM_SEGMENTED_ATTN requires decoder attention on gfx1x "
"(gfx12 for FP8), head size 64, 128 or 256, GQA ratio 1-16, and "
"does not support ALiBi."
)
# Startup tuning and target/draft compilation must share a Triton cache.
cache_dir = os.environ.setdefault(
"TRITON_CACHE_DIR",
str(Path(envs.VLLM_CACHE_ROOT) / "rocm_segmented_attention" / "triton"),
)
Path(cache_dir).mkdir(parents=True, exist_ok=True)
logger.info_once("Using token-major ROCm segmented Triton attention")
self._segmented_attention_warmed_up = False
self._segmented_attention_config: VllmConfig | None = None
def process_weights_after_loading(self, act_dtype: torch.dtype):
super().process_weights_after_loading(act_dtype)
config = get_current_vllm_config()
self._segmented_attention_config = config
def _autotune_enabled(self) -> bool:
config = self._segmented_attention_config
return (
config is not None
and config.kernel_config.enable_rocm_segmented_attn_autotune
)
def _get_workspace(self, device):
config = self._segmented_attention_config
assert config is not None
sizes = segmented_attention_workspace_size(
config.scheduler_config.max_num_seqs,
self.num_heads,
self.num_kv_heads,
self.head_size,
config.model_config.max_model_len,
max_tokens=config.scheduler_config.max_num_batched_tokens,
fp8=self.kv_cache_dtype in ("fp8", "fp8_e4m3"),
autotune=self._autotune_enabled(),
)
return get_segmented_attention_workspace(device, sizes)
def _split_kv_cache(
self,
kv_cache: torch.Tensor,
num_kv_heads: int | None = None,
head_size: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
num_kv_heads = num_kv_heads or self.num_kv_heads
head_size = head_size or self.head_size
return (
kv_cache[:, 0].unflatten(-1, (num_kv_heads, head_size)),
kv_cache[:, 1].unflatten(-1, (num_kv_heads, head_size)),
)
def forward(
self,
layer: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: RocmAttentionMetadata,
output: torch.Tensor,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
if output_block_scale is not None:
raise NotImplementedError(
"fused block_scale output quantization is not supported"
)
# Profile runs allocate the same fixed scratch used during graph replay.
workspace = self._get_workspace(query.device)
if attn_metadata is None:
return output.fill_(0)
num_actual_tokens = attn_metadata.num_actual_tokens
key_cache, value_cache = self._split_kv_cache(kv_cache)
if is_quantized_kv_cache(self.kv_cache_dtype):
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
if query.dtype == self.fp8_dtype and layer._q_scale_float != 1.0:
raise NotImplementedError(
"A non-1.0 q_scale with an FP8 query is not supported"
)
segmented_attention(
query=query[:num_actual_tokens],
key=key[:num_actual_tokens],
value=value[:num_actual_tokens],
output=output[:num_actual_tokens],
kv_cache_dtype=self.kv_cache_dtype,
key_cache=key_cache,
value_cache=value_cache,
block_table=attn_metadata.block_table,
query_start_loc=attn_metadata.query_start_loc,
seq_lens=attn_metadata.seq_lens,
max_seq_len=attn_metadata.max_seq_len,
max_query_len=attn_metadata.max_query_len,
k_scale=layer._k_scale,
v_scale=layer._v_scale,
sm_scale=self.scale,
sliding_window=self.sliding_window[0],
output_scale=output_scale,
sinks=self.sinks,
causal=attn_metadata.causal,
softcap=self.logits_soft_cap,
workspace=workspace,
use_tuned_config=self._autotune_enabled(),
)
return output
def do_kv_cache_update(
self,
layer: AttentionLayer,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
):
key_cache, value_cache = self._split_kv_cache(kv_cache)
if is_quantized_kv_cache(self.kv_cache_dtype):
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
triton_reshape_and_cache_flash(
key,
value,
key_cache,
value_cache,
slot_mapping,
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
)
def do_rope_and_kv_cache_update(
self,
layer: AttentionLayer,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
is_neox: bool,
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
key_cache, value_cache = self._split_kv_cache(
kv_cache,
layer.num_kv_heads, # type: ignore[attr-defined]
layer.head_size, # type: ignore[attr-defined]
)
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)
rocm_aiter_ops.triton_rope_and_cache(
query,
key,
value,
positions,
cos_sin_cache,
is_neox,
key_cache,
value_cache,
layer_slot_mapping,
layer._k_scale,
layer._v_scale,
True,
is_fp8_kv_cache,
)
@@ -1,22 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Triton image-mask and FlashInfer causal attention composite."""
from vllm.v1.attention.backends.composite import (
MMPrefixAttentionRouting,
create_composite_attention_backend,
)
from vllm.v1.attention.backends.flashinfer import FlashInferBackend
from vllm.v1.attention.backends.triton_attn import TritonAttentionBackend
TritonFlashInferBackend = create_composite_attention_backend(
TritonAttentionBackend,
FlashInferBackend,
name="TritonFlashInferBackend",
backend_name="TRITON_FLASHINFER",
module=__name__,
routing_policy=MMPrefixAttentionRouting,
head_sizes=(256, 512),
kernel_block_sizes=(64,),
device_major=10,
)
File diff suppressed because it is too large Load Diff
@@ -1,609 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""UltraQuant 4-bit KV-cache attention backend.
UltraQuant is a 4-bit KV-cache format (FP4 E2M1 codes + UE8M0 power-of-two
per-group-32 scales) with Hadamard-rotated keys. It reuses the TurboQuant
attention scaffolding (forward orchestration, metadata, cache-layout addressing,
CUDA-graph pre-warm) by subclassing, and overrides only the format-specific
seams:
* store -> ultraquant_store (rotate K, pack FP4 + UE8M0 scales)
* decode -> FlyDSL D=256 scaled-MFMA kernel, Triton unified fallback
* continuation -> small chunk: Triton unified; large chunk: dequant + FA
``UltraQuantAttentionBackend`` is a standalone backend with its own identity
(``ULTRAQUANT``) and dtype (``ultraquant_4bit``); the TurboQuant backend/impl
carry no UltraQuant knowledge.
"""
import contextlib
import math
from dataclasses import replace
from typing import Any, ClassVar
import torch
import torch.nn.functional as F
from vllm.config import get_current_vllm_config
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.v1.attention.backend import AttentionType
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
from vllm.v1.attention.backends.turboquant_attn import (
_CONTINUATION_DECODE_THRESHOLD,
_HAS_FLASH_ATTN,
TurboQuantAttentionBackend,
TurboQuantAttentionImpl,
TurboQuantMetadata,
_build_hadamard,
)
from vllm.v1.attention.ops.flydsl_ultraquant_decode import (
flydsl_ultraquant_decode_attention,
is_ultraquant_flydsl_available,
ultraquant_flydsl_decode_eligible,
)
from vllm.v1.attention.ops.ultraquant.format import slot_size
from vllm.v1.attention.ops.ultraquant.triton_unified_attention import (
ultraquant_unified_attention,
)
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.v1.worker.workspace import (
current_workspace_manager,
is_workspace_manager_initialized,
)
logger = init_logger(__name__)
# CK FlashAttention on ROCm has no compiled kernel above head_dim 256 and no
# sinks argument; those cases route through the Triton unified kernel instead.
_CK_MAX_HEAD_DIM = 256
class UltraQuantAttentionBackend(TurboQuantAttentionBackend):
"""Standalone backend for the ``ultraquant_4bit`` KV-cache dtype.
Subclasses :class:`TurboQuantAttentionBackend` for the shared metadata and
cache-layout plumbing, and overrides identity, spec, impl, block size, and
capabilities so no UltraQuant knowledge lives in the TurboQuant backend.
"""
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["ultraquant_4bit"]
# FlyDSL D=256 decode loads query as bf16; fp16 is not supported. Selection
# reads this from the backend class, not from the impl.
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
"""UltraQuant packs K+V into one 4-bit FP4/UE8M0 slot per head."""
if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_ultraquant:
return spec
return replace(spec, state_content_bytes=slot_size(spec.head_size))
@staticmethod
def get_name() -> str:
return "ULTRAQUANT"
@classmethod
def get_preferred_block_size(cls, default_block_size: int) -> int:
# FlyDSL D=256 decode geometry requires a 64-token KV block; pin it so
# the KV-cache manager pages stay dense and splittable into kernel blocks.
return 64
@staticmethod
def get_impl_cls() -> type["UltraQuantAttentionImpl"]:
return UltraQuantAttentionImpl
@classmethod
def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool:
return kv_cache_dtype == "ultraquant_4bit"
@classmethod
def supports_sink(cls) -> bool:
# Decode and continuation prefill route sinks to the Triton unified
# kernel, but first-chunk prefill goes through flash_attn_varlen, which
# takes no sinks argument. Until that path is covered, reject sink
# models at selection rather than returning silently wrong output.
return False
class UltraQuantAttentionImpl(TurboQuantAttentionImpl):
"""UltraQuant 4-bit KV-cache attention (FP4 E2M1 + UE8M0, rotated K).
Overrides the init, on-device setup, store, decode, and prefill/continuation
seams of :class:`TurboQuantAttentionImpl`; the shared ``forward`` /
``do_kv_cache_update`` orchestration and metadata handling are inherited.
"""
# FlyDSL D=256 decode loads query as bf16; fp16 is not supported.
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int | None = None,
alibi_slopes: list[float] | None = None,
sliding_window: int | None = None,
kv_cache_dtype: str = "auto",
logits_soft_cap: float | None = None,
attn_type: str = AttentionType.DECODER,
kv_sharing_target_layer_name: str | None = None,
**kwargs,
):
self.num_heads = num_heads
self.head_size = head_size
self.scale = scale
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
self.num_kv_groups = num_heads // self.num_kv_heads
self.kv_cache_dtype = kv_cache_dtype
self.fa_version = get_flash_attn_version(head_size=head_size)
vllm_config = get_current_vllm_config()
self.max_num_kv_splits = (
vllm_config.attention_config.tq_max_kv_splits_for_cuda_graph
)
self.sliding_window = sliding_window
self.sinks = kwargs.get("sinks")
self._max_model_len = vllm_config.model_config.max_model_len
self._use_ultraquant_flydsl = is_ultraquant_flydsl_available()
# FlyDSL decode eligibility is static per layer config; compute once.
self._flydsl_decode_eligible = ultraquant_flydsl_decode_eligible(
head_size=self.head_size,
num_kv_groups=self.num_kv_groups,
has_sinks=self.sinks is not None,
sliding_window=self.sliding_window,
flydsl_loaded=self._use_ultraquant_flydsl,
)
def _ensure_on_device(self, layer, device):
"""Build the shared Hadamard rotation and pre-warm FlyDSL buffers.
UltraQuant needs no Lloyd-Max centroids, but the inherited forward reads
``layer._tq_centroids``, so an empty tensor is kept on the layer.
"""
if self._use_ultraquant_flydsl:
# CUDA-graph capture safety for the FlyDSL decode path on ROCm:
# pre-allocate index buffers and grow the workspace to its max size
# before capture so replay never lands on stale addresses.
_max_len = self._max_model_len
_already_ok = (
hasattr(self, "_arange_cache")
and self._arange_cache.device.type == str(device).split(":")[0]
and self._arange_cache.shape[0] >= _max_len + 2
)
if not _already_ok:
self._arange_cache = torch.arange(
0, _max_len + 2, device=device, dtype=torch.int32
)
if not hasattr(self, "_cu_2") or self._cu_2.device != torch.device(device):
self._cu_2 = torch.zeros(2, device=device, dtype=torch.int32)
if (
is_workspace_manager_initialized()
and not current_workspace_manager().is_locked()
):
B_max = self._max_capture_batch_size()
D = self.head_size
Hq = self.num_heads
S = self.max_num_kv_splits
_pre_warm_bytes = (
B_max * Hq * (S * (D + 1) + D) * 4 # fp32 mid_o + fp32 lse
+ B_max * Hq * D * 2 # query-dtype output (bf16 = 2 B)
+ 512 # alignment padding
)
with contextlib.suppress(AssertionError):
current_workspace_manager().get_simultaneous(
((_pre_warm_bytes,), torch.uint8)
)
if not hasattr(layer, "_tq_cached"):
D = self.head_size
# Pure Hadamard: orthonormal + symmetric (H = H^T), enabling
# in-kernel butterfly fusion and trivial inverse for continuation.
H = _build_hadamard(D, str(device))
layer._tq_PiT = H
layer._tq_Pi = H
layer._tq_Pi_half = H.to(torch.float16)
# Inherited TurboQuantAttentionImpl.forward reads _tq_centroids
# unconditionally; UltraQuant has no centroid table, so an empty
# tensor satisfies the read.
layer._tq_centroids = torch.empty(0, device=device, dtype=torch.float32)
layer._tq_cached = True
def _store_kv(
self,
key: torch.Tensor, # (N, Hk, D)
value: torch.Tensor, # (N, Hk, D)
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
slot_mapping: torch.Tensor,
layer: Any,
):
"""Rotate K by the Hadamard and pack K+V into FP4/UE8M0 slots."""
from vllm.v1.attention.ops.ultraquant.triton_store import ultraquant_store
ultraquant_store(
key,
value,
kv_cache,
slot_mapping,
PiT=layer._tq_PiT,
)
def _decode_attention(
self,
query: torch.Tensor, # (B, Hq, D)
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
attn_metadata: TurboQuantMetadata,
Pi: torch.Tensor,
centroids: torch.Tensor,
PiT: torch.Tensor | None = None,
layer: torch.nn.Module | None = None,
) -> torch.Tensor:
# Acquire shared decode scratch from the WorkspaceManager (UltraQuant
# only needs the output buffer; the mid_o/lse slots keep the triple
# allocation identical to the base decode for buffer reuse).
B = query.shape[0]
D = self.head_size
S = self.max_num_kv_splits
Hq = self.num_heads
output_buf = None
if is_workspace_manager_initialized():
_mid_o, output_buf, _lse = current_workspace_manager().get_simultaneous(
((B, Hq, S, D + 1), torch.float32),
((B, Hq, D), query.dtype),
((B, Hq), torch.float32),
)
if self._flydsl_decode_eligible:
return flydsl_ultraquant_decode_attention(
query=query,
kv_cache=kv_cache,
block_table=attn_metadata.block_table,
seq_lens=attn_metadata.seq_lens,
scale=self.scale,
PiT=PiT,
max_seq_len=attn_metadata.max_seq_len,
output_buf=output_buf,
buf_holder=layer,
max_num_kv_splits=self.max_num_kv_splits,
sinks=self.sinks,
)
logger.info_once(
"UltraQuant FlyDSL is ineligible for head_size=%s, GQA=%s, "
"sinks=%s, sliding_window=%s; using Triton fallback.",
self.head_size,
self.num_kv_groups,
self.sinks is not None,
self.sliding_window,
)
return ultraquant_unified_attention(
query=query,
kv_cache=kv_cache,
block_table=attn_metadata.block_table,
seq_lens=attn_metadata.seq_lens,
query_start_loc=attn_metadata.query_start_loc,
scale=self.scale,
PiT=PiT,
output=output_buf,
max_query_len=1,
max_seq_len=attn_metadata.max_seq_len,
sinks=self.sinks,
sliding_window=self.sliding_window,
)
def _prefill_attention(
self,
query: torch.Tensor, # (N, Hq, D)
key: torch.Tensor, # (N, Hk, D)
value: torch.Tensor, # (N, Hk, D)
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
attn_metadata: TurboQuantMetadata,
Pi: torch.Tensor,
centroids: torch.Tensor,
PiT: torch.Tensor | None = None,
layer: Any = None,
) -> torch.Tensor:
N, Hq, D = query.shape
# Fast path: flash_attn for first-chunk prefills (all K/V in batch).
# CK cannot serve head dims above 256, so those fall through to the
# per-request unified-attention path below.
if (
_HAS_FLASH_ATTN
and attn_metadata.max_query_len == attn_metadata.max_seq_len
and D <= _CK_MAX_HEAD_DIM
):
return self._flash_attn_varlen(
q=query,
k=key,
v=value,
cu_seqlens_q=attn_metadata.query_start_loc,
cu_seqlens_k=attn_metadata.query_start_loc,
max_seqlen_q=attn_metadata.max_query_len,
max_seqlen_k=attn_metadata.max_query_len,
)
# Continuation or no flash_attn: per-request attention.
Hk = key.shape[1]
use_gqa = Hk < Hq
query_start_loc = attn_metadata.query_start_loc
num_reqs = query_start_loc.shape[0] - 1
output = torch.zeros(N, Hq, D, device=query.device, dtype=query.dtype)
if attn_metadata.query_start_loc_cpu is not None:
qsl = attn_metadata.query_start_loc_cpu.tolist()
else:
qsl = query_start_loc.tolist()
if attn_metadata.seq_lens_cpu is not None:
seq_lens_list = attn_metadata.seq_lens_cpu.tolist()
else:
seq_lens_list = attn_metadata.seq_lens.tolist()
if not hasattr(self, "_cu_2"):
self._cu_2 = torch.zeros(2, device=query.device, dtype=torch.int32)
_max_seq = attn_metadata.max_seq_len
_ac: torch.Tensor | None = getattr(self, "_arange_cache", None)
if _ac is None or _ac.shape[0] <= _max_seq:
_ac = torch.arange(
0, _max_seq + 1, device=query.device, dtype=attn_metadata.seq_lens.dtype
)
self._arange_cache = _ac
_arange_cache: torch.Tensor = _ac
for i in range(num_reqs):
q_start = qsl[i]
q_end = qsl[i + 1]
q_len = q_end - q_start
if q_len <= 0:
continue
seq_len = seq_lens_list[i]
q_seq = query[q_start:q_end] # (q_len, Hq, D)
k_seq = key[q_start:q_end] # (q_len, Hk, D)
v_seq = value[q_start:q_end] # (q_len, Hk, D)
if q_len == seq_len:
# First-chunk prefill: all K/V are in the current batch.
if D > _CK_MAX_HEAD_DIM:
# Head dims CK cannot handle (Gemma 4 global layers,
# D=512). This kernel is generic over head size.
from vllm.v1.attention.ops.triton_unified_attention import (
unified_attention,
)
out = torch.empty_like(q_seq)
cu_single = torch.tensor(
[0, q_len], dtype=torch.int32, device=query.device
)
seq_lens_single = torch.tensor(
[q_len], dtype=torch.int32, device=query.device
)
block_table_single = torch.zeros(
(1, 1), dtype=torch.int32, device=query.device
)
unified_attention(
q=q_seq,
k=k_seq.unsqueeze(0),
v=v_seq.unsqueeze(0),
out=out,
cu_seqlens_q=cu_single,
max_seqlen_q=q_len,
seqused_k=seq_lens_single,
max_seqlen_k=q_len,
softmax_scale=self.scale,
causal=True,
window_size=(-1, -1),
block_table=block_table_single,
softcap=0.0,
q_descale=None,
k_descale=None,
v_descale=None,
sinks=None,
)
elif _HAS_FLASH_ATTN:
self._cu_2[1:2] = q_len
cu = self._cu_2
out = self._flash_attn_varlen(
q=q_seq,
k=k_seq,
v=v_seq,
cu_seqlens_q=cu,
cu_seqlens_k=cu,
max_seqlen_q=q_len,
max_seqlen_k=q_len,
)
else:
q_t = q_seq.transpose(0, 1).contiguous()
k_t = k_seq.transpose(0, 1).contiguous()
v_t = v_seq.transpose(0, 1).contiguous()
out = F.scaled_dot_product_attention(
q_t,
k_t,
v_t,
is_causal=True,
scale=self.scale,
enable_gqa=use_gqa,
).transpose(0, 1)
output[q_start:q_end] = out.to(query.dtype)
else:
# Continuation chunk: prefix already stored (Hadamard-rotated
# FP4) by do_kv_cache_update. Small chunks reuse the Triton
# unified decode-shaped kernel; large chunks dequant the prefix
# once and run a dense flash-attention prefill.
cached_len = seq_len - q_len
if q_len <= _CONTINUATION_DECODE_THRESHOLD:
synth_seq_lens = _arange_cache[cached_len + 1 : seq_len + 1]
synth_bt = attn_metadata.block_table[i : i + 1].expand(q_len, -1)
out = ultraquant_unified_attention(
query=q_seq,
kv_cache=kv_cache,
block_table=synth_bt,
seq_lens=synth_seq_lens,
query_start_loc=_arange_cache[: q_len + 1],
scale=self.scale,
PiT=PiT,
max_query_len=1,
max_seq_len=seq_len,
sinks=self.sinks,
sliding_window=self.sliding_window,
)
else:
out = self._ultraquant_continuation_prefill(
layer=layer,
query=q_seq,
key_chunk=k_seq,
val_chunk=v_seq,
kv_cache=kv_cache,
block_table=attn_metadata.block_table[i : i + 1],
cached_len=cached_len,
seq_len=seq_len,
PiT=PiT,
)
output[q_start:q_end] = out.to(query.dtype)
return output
def _ultraquant_continuation_prefill(
self,
*,
layer: Any,
query: torch.Tensor, # (q_len, Hq, D) unrotated
key_chunk: torch.Tensor, # (q_len, Hk, D) unrotated
val_chunk: torch.Tensor, # (q_len, Hk, D)
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
block_table: torch.Tensor, # (1, max_num_blocks)
cached_len: int,
seq_len: int,
PiT: torch.Tensor, # (D, D) fp32 Hadamard
) -> torch.Tensor:
"""Large continuation chunk: dequant the cached prefix, then flash_attn.
The cache stores K already Hadamard-rotated, so only the current chunk's
K and the queries need rotating. Hadamard is symmetric orthonormal, so
rotating both sides leaves the attention scores unchanged.
"""
from vllm.v1.attention.ops.ultraquant.triton_dequant import (
ultraquant_full_dequant_kv,
)
q_len, Hq, D = query.shape
Hk = key_chunk.shape[1]
device = query.device
qdtype = query.dtype
block_size = kv_cache.shape[1]
alloc_len = math.ceil(cached_len / block_size) * block_size
# Dequant target, shared across layers by the workspace manager so long
# context does not pay one allocation per layer.
buf_shape = (1, Hk, alloc_len, D)
k_buf, v_buf = current_workspace_manager().get_simultaneous(
(buf_shape, qdtype),
(buf_shape, qdtype),
)
ultraquant_full_dequant_kv(
kv_cache=kv_cache,
block_table=block_table,
k_out=k_buf,
v_out=v_buf,
alloc_len=alloc_len,
)
# Layer-cached prefix+chunk concatenation, grown once to worst case.
cap = block_table.shape[1] * block_size
k_full_buf = getattr(layer, "_uq_kfull_buf", None)
if (
k_full_buf is None
or k_full_buf.shape[0] < cap
or k_full_buf.dtype != qdtype
):
k_full_buf = torch.empty(cap, Hk, D, dtype=qdtype, device=device)
layer._uq_kfull_buf = k_full_buf
v_full_buf = getattr(layer, "_uq_vfull_buf", None)
if (
v_full_buf is None
or v_full_buf.shape[0] < cap
or v_full_buf.dtype != qdtype
):
v_full_buf = torch.empty(cap, Hk, D, dtype=qdtype, device=device)
layer._uq_vfull_buf = v_full_buf
k_full = k_full_buf[:seq_len]
v_full = v_full_buf[:seq_len]
k_full[:cached_len] = k_buf[0, :, :cached_len, :].transpose(0, 1)
v_full[:cached_len] = v_buf[0, :, :cached_len, :].transpose(0, 1)
k_full[cached_len:] = (key_chunk.to(torch.float32) @ PiT).to(qdtype)
v_full[cached_len:] = val_chunk
q_rot = (query.to(torch.float32) @ PiT).to(qdtype)
# Unequal q/k lengths with causal=True gives lower-right alignment:
# query i (absolute position cached_len + i) sees keys 0..cached_len+i.
#
# FA2 on ROCm has no sinks parameter, and CK cannot serve head dims
# above 256, so those cases route through the Triton unified kernel.
# Q/K are already in Hadamard-rotated space (q_rot, k_full) so the dot
# products match the original-space attention scores.
if self.sinks is not None or D > _CK_MAX_HEAD_DIM:
from vllm.v1.attention.ops.triton_unified_attention import (
unified_attention,
)
out = torch.empty_like(q_rot)
cu_q = torch.tensor([0, q_len], dtype=torch.int32, device=device)
seqused_k = torch.tensor([seq_len], dtype=torch.int32, device=device)
block_table_single = torch.zeros((1, 1), dtype=torch.int32, device=device)
window = (
(self.sliding_window - 1, 0)
if self.sliding_window and self.sliding_window > 0
else (-1, -1)
)
unified_attention(
q=q_rot,
k=k_full.unsqueeze(0),
v=v_full.unsqueeze(0),
out=out,
cu_seqlens_q=cu_q,
max_seqlen_q=q_len,
seqused_k=seqused_k,
max_seqlen_k=seq_len,
softmax_scale=self.scale,
causal=True,
window_size=window,
block_table=block_table_single,
softcap=0.0,
q_descale=None,
k_descale=None,
v_descale=None,
sinks=self.sinks,
)
return out.to(qdtype)
if _HAS_FLASH_ATTN:
cu_q = torch.tensor([0, q_len], dtype=torch.int32, device=device)
cu_k = torch.tensor([0, seq_len], dtype=torch.int32, device=device)
return self._flash_attn_varlen(
q=q_rot,
k=k_full,
v=v_full,
cu_seqlens_q=cu_q,
cu_seqlens_k=cu_k,
max_seqlen_q=q_len,
max_seqlen_k=seq_len,
)
q_t = q_rot.transpose(0, 1).unsqueeze(0)
k_t = k_full.transpose(0, 1).unsqueeze(0)
v_t = v_full.transpose(0, 1).unsqueeze(0)
if Hq > Hk:
k_t = k_t.expand(1, Hq, -1, -1)
v_t = v_t.expand(1, Hq, -1, -1)
return (
F.scaled_dot_product_attention(
q_t, k_t, v_t, is_causal=True, scale=self.scale
)
.squeeze(0)
.transpose(0, 1)
.to(qdtype)
)
-148
View File
@@ -1,148 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Encoder attention through the zentorch SDPA kernel on Zen CPUs."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from vllm.model_executor.kernels.linear.zentorch_utils import has_zentorch_op
from vllm.v1.attention.backend import AttentionType
if TYPE_CHECKING:
from vllm.v1.attention.backends.cpu_attn import CPUAttentionMetadata
__all__ = ["should_use_zentorch_sdpa", "zentorch_sdpa_attn"]
def should_use_zentorch_sdpa(
attn_type: str,
dtype: torch.dtype,
) -> bool:
"""True when encoder attention should dispatch to zentorch_sdpa.
Full, sliding-window, and ALiBi encoder layers all dispatch. A window is
a single-head [1, 1, S, S] additive mask; ALiBi is a per-query-head
[1, H, S, S] bias. The zentorch_sdpa_attn op builds both.
dtype must match the op's ISA gate (bf16: AVX512-BF16, fp32: AVX512);
fp16 needs AVX512-FP16, which torch exposes no query for, so it stays
native.
"""
if attn_type not in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return False
if not has_zentorch_op(["zentorch_sdpa_attn"]):
return False
if dtype == torch.bfloat16:
return torch.cpu._is_avx512_bf16_supported()
if dtype == torch.float32:
return torch.cpu._is_avx512_supported()
return False
def zentorch_sdpa_attn(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
output: torch.Tensor,
attn_metadata: CPUAttentionMetadata,
scale: float,
sliding_window: int = -1,
alibi_slopes: torch.Tensor | None = None,
) -> torch.Tensor:
"""Run encoder / encoder-only attention with zentorch_sdpa.
Encoder attention reads no KV cache, so the packed
[num_tokens, num_heads, head_size] query/key/value are attended in place
and written straight into `output`.
Args:
query: Query of shape [num_tokens, num_heads, head_size].
key: Key of shape [num_tokens, num_kv_heads, head_size].
value: Value of shape [num_tokens, num_kv_heads, head_size].
output: Pre-allocated output, same shape as `query`.
attn_metadata: Metadata carrying the per-sequence token offsets and
whether attention is causal.
scale: Softmax scale.
sliding_window: Encoder window size, or -1 for full bidirectional
attention. Handed to the op, which masks token i to
[i-(W-1), i+(W-1)].
alibi_slopes: Per-query-head ALiBi slopes, or None. Handed to the op,
which applies them as an additive per-head bias.
Returns:
`output`, filled in place.
"""
# zentorch_sdpa_attn builds the ALiBi mask in query.dtype. A bf16 per-head
# mask is wrong when the query head count is not a power of two, so run
# that path in fp32 and write bf16 back.
if alibi_slopes is not None and query.dtype == torch.bfloat16:
out32 = torch.empty_like(query, dtype=torch.float32)
zentorch_sdpa_attn(
query.float(),
key.float(),
value.float(),
out32,
attn_metadata,
scale,
sliding_window,
alibi_slopes,
)
output.copy_(out32.to(dtype=output.dtype))
return output
# The op counts window tokens on each side of the diagonal; vLLM's window
# includes the diagonal itself.
window = -1 if sliding_window in (None, -1) else sliding_window - 1
# zentorch_sdpa takes no enable_gqa argument but derives the KV head count
# from the key tensor and maps each query head onto its KV head, so GQA/MQA
# needs no expansion here.
query = query.movedim(0, query.dim() - 2)
key = key.movedim(0, key.dim() - 2)
value = value.movedim(0, value.dim() - 2)
start_loc = attn_metadata.query_start_loc.numpy()
seq_lens = start_loc[1:] - start_loc[:-1]
# Encoder sequences are packed along the token dimension. When they all
# have the same length, recover a dense BHSD batch and invoke zentorch_sdpa
# once for the whole scheduler batch instead of once per sequence.
if len(seq_lens) > 0 and (seq_lens == seq_lens[0]).all():
batch_size = len(seq_lens)
seq_len = int(seq_lens[0])
def _packed_hsd_to_bhsd(tensor: torch.Tensor) -> torch.Tensor:
return tensor.unflatten(1, (batch_size, seq_len)).permute(1, 0, 2, 3)
torch.ops.zentorch.zentorch_sdpa_attn(
_packed_hsd_to_bhsd(query),
_packed_hsd_to_bhsd(key),
_packed_hsd_to_bhsd(value),
# The op writes [B, H, S, D]; hand it the matching view of the
# packed buffer so it stores there instead of into a temporary.
output.unflatten(0, (batch_size, seq_len)).permute(0, 2, 1, 3),
scale=scale,
is_causal=attn_metadata.causal,
alibi_slopes=alibi_slopes,
left_window_size=window,
right_window_size=window,
)
return output
for start_q, end_q in zip(start_loc[:-1], start_loc[1:], strict=True):
torch.ops.zentorch.zentorch_sdpa_attn(
query[None, :, start_q:end_q, :],
key[None, :, start_q:end_q, :],
value[None, :, start_q:end_q, :],
output[start_q:end_q, :, :].movedim(0, 1).unsqueeze(0),
scale=scale,
is_causal=attn_metadata.causal,
alibi_slopes=alibi_slopes,
left_window_size=window,
right_window_size=window,
)
return output
@@ -1,105 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Compressed DCP context preparation for ROCm MLA."""
from collections.abc import Callable
import torch
from vllm import _custom_ops as ops
from vllm._aiter_ops import rocm_aiter_ops
from vllm.model_executor.layers.attention.mla_attention import MLACommonPrefillMetadata
def context_row_indices(
chunk: MLACommonPrefillMetadata.ContextChunk, device: torch.device
) -> torch.Tensor:
"""Map compact request-major rows to the padded rank-major AllGather."""
assert chunk.padded_local_seq_lens is not None
assert chunk.local_context_lens_allranks is not None
assert chunk.local_starts is not None
segments = []
offset = 0
for padded, lengths, start in zip(
chunk.padded_local_seq_lens,
chunk.local_context_lens_allranks,
chunk.local_starts,
):
for rank, length in enumerate(lengths):
count = min(max(0, length - start), padded)
if count:
first = rank * chunk.num_local_context_tokens + offset
segments.append(torch.arange(first, first + count, dtype=torch.int32))
offset += padded
rows = torch.cat(segments) if segments else torch.empty(0, dtype=torch.int32)
assert rows.numel() == chunk.num_context_tokens
return rows.to(device=device, non_blocking=True)
def gather_compressed_context(
cache: torch.Tensor,
workspace: torch.Tensor,
block_table: torch.Tensor,
chunk: MLACommonPrefillMetadata.ContextChunk,
gather: Callable[[torch.Tensor, torch.Tensor], object],
cache_dtype: torch.dtype,
) -> torch.Tensor:
"""Gather FP8 bytes, preserving the existing workspace row capacity."""
assert chunk.local_context_lens_allranks is not None
assert workspace.is_contiguous()
rows, width = workspace.shape
fp8_workspace = workspace.view(cache_dtype).view(-1, width)[:rows]
local_rows = chunk.num_local_context_tokens
world_size = len(chunk.local_context_lens_allranks[0])
offset = rows // (world_size + 1)
assert offset * (world_size + 1) == rows
assert local_rows <= offset
local = fp8_workspace[:local_rows]
gathered = fp8_workspace[offset : offset + world_size * local_rows]
assert chunk.padded_local_cu_seq_lens is not None
ops.cp_gather_cache(
cache.view(torch.uint8),
local.view(torch.uint8),
block_table,
chunk.padded_local_cu_seq_lens,
chunk.num_requests,
chunk.starts,
)
gather(gathered.view(torch.uint8), local.view(torch.uint8))
return gathered
def expand_context(
gathered: torch.Tensor,
scale: torch.Tensor,
row_indices: torch.Tensor,
cu_seq_lens: torch.Tensor,
weight: torch.Tensor,
num_heads: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Fuse row reorganization, dequantization, projection and K/V packing."""
k = torch.empty(
(row_indices.numel(), num_heads, qk_nope_head_dim + qk_rope_head_dim),
device=gathered.device,
dtype=weight.dtype,
)
v = torch.empty(
(row_indices.numel(), num_heads, v_head_dim),
device=gathered.device,
dtype=weight.dtype,
)
if row_indices.numel():
rocm_aiter_ops.gather_kv_b_proj(
gathered.unsqueeze(1),
scale,
cu_seq_lens,
row_indices,
cu_seq_lens,
weight,
k,
v,
)
return k, v
File diff suppressed because it is too large Load Diff
@@ -1,676 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Sparse attention indexer on aiter's paged MXFP4 MQA-logits kernel.
gfx950 only. The kernel reads the preshuffled paged indexer K cache in place,
so no layer gathers K into a contiguous buffer, prefill included. Any model
whose indexer supplies the inputs `rocm_mxfp4_sparse_attn_indexer` documents
can run the dense path. DeepSeek-V4.1's two-level indexer adds to it: the
candidate source takes its block maxima from the same walk that writes its
logits, and the candidate consumers can walk the candidate pool instead of
the whole context: the pool is resolved once per step and shared by all of
them.
"""
import functools
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, NamedTuple
import torch
import vllm.envs as envs
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import CUDAGraphMode
from vllm.forward_context import get_forward_context
from vllm.model_executor.kernels.attention.dsa.candidate_blocks import (
apply_candidate_mask,
)
from vllm.triton_utils import tl, triton
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_apply_candidate_mask_strided,
_max_decode_logits_rows,
)
from vllm.v1.worker.workspace import current_workspace_manager
if TYPE_CHECKING:
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerPrefillChunkMetadata,
)
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
RocmMxfp4GatherLaunch,
RocmMxfp4IndexerMetadata,
RocmMxfp4NativeDecode,
RocmMxfp4PrefillPlan,
)
MXFP4_BLOCK_SIZE = 32
@functools.cache
def _aiter():
"""The aiter module with the paged MXFP4 MQA-logits launcher, its schedule
and cache_format."""
from aiter.ops.triton.attention import pa_mqa_logits_mxfp4
return pa_mqa_logits_mxfp4
@functools.cache
def _aiter_topk() -> Callable[..., None]:
"""The aiter per-row top-k."""
from aiter.ops.topk import top_k_per_row_decode
return top_k_per_row_decode
class RocmPagedMxfp4CacheLayout(NamedTuple):
"""The byte order of an indexer K page, as the kernel reads it, and the
shuffle pattern aiter's K cache op writes it with.
A page is cut into runs of ``n_per_tile`` tokens. Inside a run, each token's
packed values are split into ``d_per_tile``-byte chunks along the head
dimension, and the run stores chunk 0 of every token, then chunk 1, and so
on: ``[chunk, token, byte]``. Its e8m0 scales are stored as
``[scale % scale_lanes, token, scale // scale_lanes]``.
"""
n_per_tile: int
d_per_tile: int
scale_lanes: int
# The scale order the kernel reads: aiter's mode 1, a lane's scales innermost.
# cache_format does not report the order or the lane split yet.
_SCALE_ORDER = 1
_WAVE_SIZE = 64
@functools.cache
def rocm_paged_mxfp4_cache_layout(
num_heads: int, head_dim: int, page_entries: int
) -> RocmPagedMxfp4CacheLayout:
"""The K page layout from aiter's ``cache_format``, the only place vLLM
reads it, so a change there cannot reach the writer unchecked.
Raises:
ValueError: aiter rejects the page size, or describes an order this
layout cannot express.
"""
fmt = _aiter().cache_format(num_heads, head_dim, page_entries)
try:
n_per_tile = int(fmt["n_per_tile"])
d_per_tile = int(fmt["d_per_tile"])
scale_order = fmt.get("scale_mode", _SCALE_ORDER)
scale_lanes = int(fmt.get("scale_lanes", _WAVE_SIZE // n_per_tile))
except (KeyError, TypeError, ValueError, ZeroDivisionError) as e:
raise ValueError(f"aiter's cache_format() returned {fmt!r}") from e
if (
scale_order != _SCALE_ORDER
or min(n_per_tile, d_per_tile, scale_lanes) <= 0
or page_entries % n_per_tile
or (head_dim // 2) % d_per_tile
or (head_dim // MXFP4_BLOCK_SIZE) % scale_lanes
):
raise ValueError(
f"aiter's cache_format() returned {fmt!r} for {num_heads} heads of "
f"{head_dim} in {page_entries}-entry pages, a K page order "
"RocmPagedMxfp4CacheLayout cannot express"
)
return RocmPagedMxfp4CacheLayout(n_per_tile, d_per_tile, scale_lanes)
def rocm_mxfp4_decode_schedule_words(
num_heads: int, head_dim: int, page_entries: int, next_n: int = 1
) -> int:
"""int32 words of the largest schedule a decode step can build, flattened or
not. The slice cap can take it past target_wgs, up to SCHED_SLOT_CAP."""
words = 4 * _aiter().SCHED_SLOT_CAP
for rows in {1, next_n}:
config = _aiter().select_config(num_heads, head_dim, rows, page_entries)
words = max(words, 4 * config["target_wgs"])
return words
def build_rocm_mxfp4_decode_schedule(
row_lens: torch.Tensor,
num_heads: int,
head_dim: int,
page_entries: int,
out: torch.Tensor,
logits_width: int,
native: "RocmMxfp4NativeDecode | None" = None,
) -> torch.Tensor | None:
"""Work descriptors that even out a decode step, or None where the static
grid already fills the machine. Depends only on the rows' lengths, the
cache geometry and the logits width, so one serves every layer of a group.
The width sizes the slices, capped the way the static grid caps them."""
if native is None:
return _aiter().build_schedule(
row_lens,
1,
num_heads,
head_dim,
page_entries,
out=out,
max_model_len=logits_width,
)
return _aiter().build_schedule(
native.context_lens,
native.next_n,
num_heads,
head_dim,
page_entries,
out=out,
row_ends=row_lens,
max_model_len=logits_width,
)
def _kv_view(kv_cache: torch.Tensor, head_dim: int) -> torch.Tensor:
"""The indexer cache as [pages, entries, 1, bytes]. The page stride is the
block-major pool's, not the page's own size."""
num_pages, entries, width = kv_cache.shape
assert kv_cache.dtype == torch.uint8
assert width == head_dim // 2 + head_dim // MXFP4_BLOCK_SIZE, width
return torch.as_strided(
kv_cache, (num_pages, entries, 1, width), (kv_cache.stride(0), width, width, 1)
)
def rocm_mxfp4_consumer_rows(num_candidate_cols: int) -> int:
"""Query rows per candidate-consumer launch. Its logits are [rows, pool]
fp32 whatever the context, so the logits budget alone sizes it."""
budget = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
return max(1, budget // (4 * num_candidate_cols))
def reserve_rocm_mxfp4_indexer_workspace(
hidden_states: torch.Tensor,
logits_width: int,
candidate_block_size: int = 0,
gather_block_size: int = 0,
num_candidate_cols: int = 0,
) -> None:
"""Profiling run: claim the decode logits workspace and the peak prefill
logits, block scores included when the layer writes them, candidate lists
when it gathers."""
rows = _max_decode_logits_rows(hidden_states.shape[0])
specs = [((rows, logits_width), torch.float32)]
budget = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
if candidate_block_size:
nblocks = triton.cdiv(logits_width, candidate_block_size)
specs.append(((rows, nblocks), torch.float32))
budget += budget // candidate_block_size
if gather_block_size:
# aiter allocates the candidate lists: each gathered row, 8 B per
# candidate block (int32 slot and position). The first consumer builds
# them and they live until the step ends, across the later layers, so
# one reservation is held for the rest of the forward.
held = get_forward_context().additional_kwargs
if "rocm_mxfp4_candidate_lists" not in held:
held["rocm_mxfp4_candidate_lists"] = torch.empty(
hidden_states.shape[0] * (num_candidate_cols // gather_block_size) * 8,
dtype=torch.uint8,
device=hidden_states.device,
)
current_workspace_manager().get_simultaneous(*specs)
torch.empty(budget, dtype=torch.uint8, device=hidden_states.device)
def _topk(
logits: torch.Tensor, lengths: torch.Tensor, out: torch.Tensor, k: int
) -> None:
"""Top-k over each row's [0, lengths[row]); -1 pads rows shorter than k.
aiter's kernel is faster on the candidate top-k and from 128 rows on; below
that, a wide decode step is faster on vLLM's. Shape alone decides, so a FULL
graph replays the same choice at every context length.
"""
rows, width = logits.shape
if rows == 0:
return
if width >= k and (k >= 2048 or rows >= 128):
_aiter_topk()(
logits,
1,
lengths.reshape(-1),
out,
rows,
logits.stride(0),
logits.stride(1),
k=k,
)
else:
torch.ops._C.top_k_per_row_decode(
logits, 1, lengths, out, rows, logits.stride(0), logits.stride(1), k
)
@triton.jit
def _remap_compact_topk_kernel(
idx_ptr,
idx_stride,
pos_ptr,
pos_stride,
K: tl.constexpr,
BLOCK: tl.constexpr,
PADDED_K: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
cols = tl.arange(0, PADDED_K)
live = cols < K
slot = tl.load(idx_ptr + row * idx_stride + cols, mask=live, other=-1)
hit = slot >= 0
slot = tl.where(hit, slot, 0)
start = tl.load(
pos_ptr + row * pos_stride + slot // BLOCK, mask=live & hit, other=0
)
tl.store(
idx_ptr + row * idx_stride + cols,
tl.where(hit, start + slot % BLOCK, -1).to(tl.int32),
mask=live,
)
def _remap_compact_topk(
indices: torch.Tensor, positions: torch.Tensor, block: int
) -> None:
"""Candidate slots to context positions, in place: slot j sits in pool
block j // block, which starts at positions[j // block]."""
rows, k = indices.shape
if rows == 0:
return
_remap_compact_topk_kernel[(rows,)](
indices,
indices.stride(0),
positions,
positions.stride(0),
K=k,
BLOCK=block,
PADDED_K=triton.next_power_of_2(k),
num_warps=4,
)
@dataclass
class _Layer:
"""One indexer layer's inputs and outputs for this step."""
metadata: "RocmMxfp4IndexerMetadata"
kv: torch.Tensor
q: torch.Tensor
q_scale: torch.Tensor
weights: torch.Tensor
topk_buffer: torch.Tensor
topk_tokens: int
compress_ratio: int
candidates: torch.Tensor | None
block: int
full_graph: bool
@property
def num_heads(self) -> int:
return self.q.shape[1]
@property
def head_dim(self) -> int:
return self.q.shape[2] * 2
def rows(self, lo: int, hi: int, seqs: int = 1) -> tuple[torch.Tensor, ...]:
"""Q, its scales and the weights of token rows [lo, hi), as ``seqs``
sequences of next_n rows each."""
return (
self.q[lo:hi].view(seqs, -1, *self.q.shape[1:]),
self.q_scale[lo:hi].view(seqs, -1, *self.q_scale.shape[1:]),
self.weights[lo:hi],
)
def decode_rows(self, n: int) -> tuple[torch.Tensor, ...]:
"""The first n token rows, one sequence each."""
return (
self.q[:n].unsqueeze(1),
self.q_scale[:n].unsqueeze(1),
self.weights[:n],
)
def _layer(
k_cache_prefix: str,
kv_cache: torch.Tensor,
q_values: torch.Tensor,
q_scale: torch.Tensor,
weights: torch.Tensor,
topk_indices_buffer: torch.Tensor,
topk_tokens: int,
head_dim: int,
compress_ratio: int,
candidate_blocks: torch.Tensor | None,
candidate_block_size: int,
) -> _Layer:
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
RocmMxfp4IndexerMetadata,
)
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
assert isinstance(attn_metadata, dict)
metadata = attn_metadata[k_cache_prefix]
assert isinstance(metadata, RocmMxfp4IndexerMetadata), (
"the ROCm MXFP4 indexer needs RocmMxfp4IndexerMetadataBuilder metadata"
)
kv = _kv_view(kv_cache, head_dim)
num_heads = q_values.shape[1]
return _Layer(
metadata=metadata,
kv=kv,
q=q_values,
# The fused Q kernel returns one int32 per head; the kernel reads the
# four ue8m0 bytes behind it.
q_scale=q_scale.view(torch.uint8).view(q_scale.shape[0], num_heads, -1),
weights=weights,
topk_buffer=topk_indices_buffer,
topk_tokens=topk_tokens,
compress_ratio=compress_ratio,
candidates=candidate_blocks,
block=candidate_block_size,
full_graph=forward_context.cudagraph_runtime_mode == CUDAGraphMode.FULL,
)
def _block_scores(layer: _Layer, scores: torch.Tensor | None) -> dict:
if scores is None:
return {}
return dict(
calc_block_scores=True, block_scores=scores, candidate_block_size=layer.block
)
def _dense_prefill(
layer: _Layer,
chunk: "DeepseekV32IndexerPrefillChunkMetadata",
plan: "RocmMxfp4PrefillPlan",
candidate_write: bool,
) -> None:
pa = _aiter()
t0, t1 = chunk.token_start, chunk.token_end
logits = layer.q.new_empty((t1 - t0, plan.width), dtype=torch.float32)
scores = None
if candidate_write:
nblocks = triton.cdiv(plan.width, layer.block)
scores = layer.q.new_empty((t1 - t0, nblocks), dtype=torch.float32)
# One launch for the chunk: the kernel finds each row's request from
# query_start_loc on its own grid.
pa.paged_mxfp4_mqa_logits(
layer.q[t0:t1],
layer.q_scale[t0:t1],
layer.kv,
layer.weights[t0:t1],
plan.context_lens,
chunk.block_table,
plan.width,
out_logits=logits,
clean_logits=False,
row_ends=plan.row_ends,
query_start_loc=plan.query_start_loc,
**_block_scores(layer, scores),
)
candidates = None if layer.candidates is None else layer.candidates[t0:t1]
if scores is not None:
assert candidates is not None and plan.block_ends is not None
_topk(scores, plan.block_ends, candidates, candidates.shape[1])
elif candidates is not None:
apply_candidate_mask(logits, None, plan.row_ends, candidates, layer.block)
_topk(
logits,
plan.row_ends,
layer.topk_buffer[t0:t1, : layer.topk_tokens],
layer.topk_tokens,
)
def _dense_decode(layer: _Layer, logits_width: int, candidate_write: bool) -> None:
metadata = layer.metadata
lengths = metadata.decode_row_lens
assert metadata.decode is not None and lengths is not None
rows = lengths.shape[0]
specs = [((rows, logits_width), torch.float32)]
if candidate_write:
specs.append(((rows, triton.cdiv(logits_width, layer.block)), torch.float32))
logits, *scores = current_workspace_manager().get_simultaneous(*specs)
native = metadata.decode_native
if native is not None:
# A request's next_n rows go in as one sequence, so a workgroup walks
# each KV tile once for all of them.
q, q_scale, weights = layer.rows(0, rows, native.context_lens.shape[0])
context_lens, block_table, row_ends = (
native.context_lens,
native.block_table,
lengths,
)
else:
q, q_scale, weights = layer.decode_rows(rows)
context_lens, block_table, row_ends = lengths, metadata.decode.block_table, None
assert block_table.shape[0] == rows, "one block-table row per query row"
_aiter().paged_mxfp4_mqa_logits(
q,
q_scale,
layer.kv,
weights,
context_lens,
block_table,
logits_width,
out_logits=logits,
clean_logits=False,
row_ends=row_ends,
schedule=metadata.decode_schedule,
**_block_scores(layer, scores[0] if scores else None),
)
candidates = None if layer.candidates is None else layer.candidates[:rows]
if scores:
assert candidates is not None and metadata.decode_block_ends is not None
_topk(scores[0], metadata.decode_block_ends, candidates, candidates.shape[1])
elif candidates is not None:
_apply_candidate_mask_strided(logits, None, lengths, candidates, layer.block)
_topk(
logits,
lengths,
layer.topk_buffer[:rows, : layer.topk_tokens],
layer.topk_tokens,
)
def _gather_prefill(
layer: _Layer, launch: "RocmMxfp4GatherLaunch", num_cols: int
) -> None:
pa = _aiter()
assert layer.candidates is not None
t0, t1 = launch.token_start, launch.token_end
if launch.pool is None:
launch.pool = pa.build_candidate_gather(
layer.candidates[t0:t1],
launch.row_ends,
launch.block_table.expand(t1 - t0, -1),
layer.kv,
layer.num_heads,
layer.head_dim,
layer.block,
)
gather, slot_ends = launch.pool
compact = layer.q.new_empty((t1 - t0, num_cols), dtype=torch.float32)
q, q_scale, weights = layer.rows(t0, t1)
pa.paged_mxfp4_mqa_logits(
q,
q_scale,
layer.kv,
weights,
launch.context_len,
launch.block_table,
num_cols,
out_logits=compact,
clean_logits=False,
row_ends=slot_ends,
use_gather=True,
candidates=gather,
)
out = layer.topk_buffer[t0:t1, : layer.topk_tokens]
_topk(compact, slot_ends, out, layer.topk_tokens)
_remap_compact_topk(out, gather["positions"], layer.block)
def _gather_decode(layer: _Layer, num_cols: int) -> None:
pa = _aiter()
assert layer.candidates is not None
metadata = layer.metadata
lengths = metadata.decode_row_lens
assert metadata.decode is not None and lengths is not None
block_table = metadata.decode.block_table
rows = lengths.shape[0]
if metadata.decode_gather is None:
metadata.decode_gather = pa.build_candidate_gather(
layer.candidates[:rows],
lengths,
block_table,
layer.kv,
layer.num_heads,
layer.head_dim,
layer.block,
)
gather, slot_ends = metadata.decode_gather
(compact,) = current_workspace_manager().get_simultaneous(
((rows, num_cols), torch.float32)
)
q, q_scale, weights = layer.decode_rows(rows)
pa.paged_mxfp4_mqa_logits(
q,
q_scale,
layer.kv,
weights,
lengths,
block_table,
num_cols,
out_logits=compact,
clean_logits=False,
row_ends=slot_ends,
use_gather=True,
candidates=gather,
)
out = layer.topk_buffer[:rows, : layer.topk_tokens]
_topk(compact, slot_ends, out, layer.topk_tokens)
_remap_compact_topk(out, gather["positions"], layer.block)
@eager_break_during_capture
def rocm_mxfp4_sparse_attn_indexer(
hidden_states: torch.Tensor,
k_cache_prefix: str,
kv_cache: torch.Tensor,
q_values: torch.Tensor,
q_scale: torch.Tensor,
weights: torch.Tensor,
topk_tokens: int,
head_dim: int,
max_model_len: int,
topk_indices_buffer: torch.Tensor,
compress_ratio: int = 1,
candidate_blocks: torch.Tensor | None = None,
candidate_block_size: int = 0,
candidate_write: bool = False,
) -> torch.Tensor:
"""Dense indexer: every layer that scores the whole context, the
candidate source included. With ``candidate_blocks`` and not
``candidate_write`` the scores are masked to the pool first, as the
shared path does.
The model supplies ``q_values`` [T, H, D // 2] packed e2m1, ``q_scale``
holding each head's D // 32 ue8m0 bytes (one int32 per head at D = 128),
fp32 ``weights`` with the softmax and head scales folded in, and
``kv_cache`` pages in `rocm_paged_mxfp4_cache_layout` order for H heads.
"""
if not isinstance(get_forward_context().attn_metadata, dict):
reserve_rocm_mxfp4_indexer_workspace(
hidden_states,
max_model_len,
candidate_block_size if candidate_write else 0,
)
return topk_indices_buffer
layer = _layer(
k_cache_prefix,
kv_cache,
q_values,
q_scale,
weights,
topk_indices_buffer,
topk_tokens,
head_dim,
compress_ratio,
candidate_blocks,
candidate_block_size,
)
metadata = layer.metadata
topk_indices_buffer[: hidden_states.shape[0]] = -1
if metadata.prefill is not None:
for chunk, plan in zip(metadata.prefill.chunks, metadata.prefill_plans):
_dense_prefill(layer, chunk, plan, candidate_write)
if metadata.decode is not None:
_dense_decode(layer, max_model_len, candidate_write)
return topk_indices_buffer
@eager_break_during_capture
def rocm_mxfp4_sparse_mqa_indexer(
hidden_states: torch.Tensor,
k_cache_prefix: str,
kv_cache: torch.Tensor,
q_values: torch.Tensor,
q_scale: torch.Tensor,
weights: torch.Tensor,
topk_tokens: int,
head_dim: int,
max_model_len: int,
topk_indices_buffer: torch.Tensor,
compress_ratio: int,
candidate_blocks: torch.Tensor,
candidate_block_size: int,
num_candidate_cols: int,
) -> torch.Tensor:
"""Candidate consumer: score only the source's pool where the builder's
length gate says it pays, else the dense walk masked to the pool."""
if not isinstance(get_forward_context().attn_metadata, dict):
reserve_rocm_mxfp4_indexer_workspace(
hidden_states,
max(max_model_len, num_candidate_cols),
gather_block_size=candidate_block_size,
num_candidate_cols=num_candidate_cols,
)
return topk_indices_buffer
layer = _layer(
k_cache_prefix,
kv_cache,
q_values,
q_scale,
weights,
topk_indices_buffer,
topk_tokens,
head_dim,
compress_ratio,
candidate_blocks,
candidate_block_size,
)
metadata = layer.metadata
topk_indices_buffer[: hidden_states.shape[0]] = -1
if metadata.prefill is not None:
for chunk, plan in zip(metadata.prefill.chunks, metadata.prefill_plans):
if not plan.use_gather:
_dense_prefill(layer, chunk, plan, candidate_write=False)
for launch in metadata.gather_launches:
_gather_prefill(layer, launch, num_candidate_cols)
if metadata.decode is not None:
# A FULL graph cannot follow the per-step gate; the gather is the side
# that stays flat in the context length.
if metadata.decode_use_gather or layer.full_graph:
_gather_decode(layer, num_candidate_cols)
else:
_dense_decode(layer, max_model_len, candidate_write=False)
return topk_indices_buffer
File diff suppressed because it is too large Load Diff
+8 -1
View File
@@ -121,7 +121,14 @@ def flashinfer_sampler_supported() -> bool:
"VLLM_USE_FLASHINFER_SAMPLER=0."
)
return False
from vllm.v1.attention.backends.flashinfer import FlashInferBackend
try:
from vllm.v1.attention.backends.flashinfer import FlashInferBackend
except ImportError:
logger.info_once(
"FlashInfer top-p/top-k sampling unavailable: "
"the FlashInfer attention backend is not installed."
)
return False
capability = current_platform.get_device_capability()
assert capability is not None
+43 -8
View File
@@ -30,12 +30,8 @@ from vllm.model_executor.models import (
supports_multimodal,
supports_multimodal_embeddings,
)
from vllm.model_executor.models.deepseek_eagle3 import Eagle3DeepseekV2ForCausalLM
from vllm.model_executor.models.interfaces import SupportsMultiModal
from vllm.model_executor.models.laguna_dflash import DFlashLagunaForCausalLM
from vllm.model_executor.models.llama_eagle3 import Eagle3LlamaForCausalLM
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3ForCausalLM
from vllm.model_executor.models.qwen3_eagle3 import Eagle3Qwen3ForCausalLM
from vllm.platforms import current_platform
from vllm.transformers_utils.deepseek_v4_utils import get_compress_ratios
from vllm.utils.torch_utils import PIN_MEMORY, async_tensor_h2d
@@ -67,6 +63,45 @@ from vllm.v1.worker.dp_utils import coordinate_batch_across_dp
from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
from vllm.v1.worker.utils import AttentionGroup
def _eagle3_dsv2_cls() -> type:
try:
from vllm.model_executor.models.deepseek_eagle3 import (
Eagle3DeepseekV2ForCausalLM,
)
except ModuleNotFoundError:
return type("AbsentEagle3DeepseekV2", (), {})
return Eagle3DeepseekV2ForCausalLM
def _dflash_laguna_cls() -> type:
try:
from vllm.model_executor.models.laguna_dflash import (
DFlashLagunaForCausalLM,
)
except ModuleNotFoundError:
return type("AbsentDFlashLaguna", (), {})
return DFlashLagunaForCausalLM
def _eagle3_llama_cls() -> type:
try:
from vllm.model_executor.models.llama_eagle3 import Eagle3LlamaForCausalLM
except ModuleNotFoundError:
return type("AbsentEagle3Llama", (), {})
return Eagle3LlamaForCausalLM
def _eagle3_qwen3_cls() -> type:
try:
from vllm.model_executor.models.qwen3_eagle3 import (
Eagle3Qwen3ForCausalLM,
)
except ModuleNotFoundError:
return type("AbsentEagle3Qwen3", (), {})
return Eagle3Qwen3ForCausalLM
logger = init_logger(__name__)
@@ -539,11 +574,11 @@ class SpecDecodeBaseProposer:
assert isinstance(
model,
(
Eagle3LlamaForCausalLM,
Eagle3DeepseekV2ForCausalLM,
_eagle3_llama_cls(),
_eagle3_dsv2_cls(),
_eagle3_qwen3_cls(),
DFlashQwen3ForCausalLM,
Eagle3Qwen3ForCausalLM,
DFlashLagunaForCausalLM,
_dflash_laguna_cls(),
),
)
target_hidden_states = self.model.combine_hidden_states(
+1 -177
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import argparse
import contextlib
import json
import multiprocessing
import threading
import time
@@ -277,129 +276,6 @@ class APIServerProcessManager:
)
class RustFrontendProcessManager:
"""Manages a single Rust frontend subprocess.
Launches the Rust vllm-rs binary in 'frontend' mode, passing the
HTTP and ZMQ listener file descriptors. Provides the same
interface as APIServerProcessManager for process monitoring.
"""
def __init__(
self,
binary_path: str,
sock: Any,
args: argparse.Namespace,
input_listener: ZmqListener,
output_listener: ZmqListener,
engine_start_index: int,
engine_count: int,
data_parallel_size: int,
stats_update_address: str | None = None,
grpc_sock: Any | None = None,
):
import os
import subprocess
listen_fd = sock.fileno()
input_fd = input_listener.socket.fileno()
output_fd = output_listener.socket.fileno()
inherited_fds = [listen_fd, input_fd, output_fd]
for fd in inherited_fds:
os.set_inheritable(fd, True)
cmd = [
binary_path,
"frontend",
"--listen-fd",
str(listen_fd),
"--input-listener-fd",
str(input_fd),
"--output-listener-fd",
str(output_fd),
"--engine-start-index",
str(engine_start_index),
"--engine-count",
str(engine_count),
"--data-parallel-size",
str(data_parallel_size),
]
if grpc_sock is not None:
grpc_fd = grpc_sock.fileno()
os.set_inheritable(grpc_fd, True)
cmd.extend(["--grpc-listen-fd", str(grpc_fd)])
inherited_fds.append(grpc_fd)
if stats_update_address is not None:
cmd.extend(["--coordinator-address", stats_update_address])
from vllm.entrypoints.serve.utils.api_utils import jsonify_non_default_args
args_dict = jsonify_non_default_args(
args,
exclude={
"api_server_count",
# Python passes the bootstrapped engine range explicitly.
"data_parallel_rank",
"data_parallel_external_lb",
"data_parallel_hybrid_lb",
},
)
# `model_tag` is the positional `vllm serve` model argument. When the
# model is supplied only through `--config`, argparse populates `model`
# while leaving `model_tag` unset. The Rust frontend requires
# `model_tag` in its JSON bootstrap payload, so use the resolved model
# as a fallback.
model_tag = getattr(args, "model_tag", None) or getattr(args, "model", None)
if model_tag is not None:
args_dict["model_tag"] = model_tag
# The Rust `frontend` subcommand parses --args-json via serde_json,
# which bypasses clap and therefore ignores any `#[arg(env = ...)]`
# declarations on SharedRuntimeArgs fields. Forward the env-driven
# values explicitly so VLLM_ENGINE_READY_TIMEOUT_S and
# VLLM_HTTP_TIMEOUT_KEEP_ALIVE behave the same on both Python and Rust
# frontends.
args_dict["engine_ready_timeout_secs"] = envs.VLLM_ENGINE_READY_TIMEOUT_S
args_dict["http_timeout_keep_alive"] = envs.VLLM_HTTP_TIMEOUT_KEEP_ALIVE
args_json = json.dumps(args_dict, sort_keys=True)
cmd.extend(["--args-json", args_json])
# The subprocess needs the real values, but the log must not carry
# credentials such as api_key or hf_token.
from vllm.entrypoints.serve.utils.api_utils import redact_sensitive_args
redacted_json = json.dumps(redact_sensitive_args(args_dict), sort_keys=True)
logger.info("Launching Rust frontend: %s", " ".join(cmd[:-1] + [redacted_json]))
self._listeners = [input_listener, output_listener]
try:
self._proc = subprocess.Popen(cmd, pass_fds=inherited_fds)
except BaseException:
for listener in self._listeners:
listener.cleanup()
raise
else:
input_listener.close()
output_listener.close()
# Create a process wrapper with a sentinel fd for monitoring
self.processes: list[_SubprocessWrapper] = [
_SubprocessWrapper(self._proc, "RustFrontend")
]
self._finalizer = weakref.finalize(
self,
_shutdown_subprocesses_and_cleanup_listeners,
self.processes,
self._listeners,
)
def shutdown(self, timeout: float | None = None) -> None:
if self._finalizer.detach() is not None:
_shutdown_subprocesses_and_cleanup_listeners(
self.processes, self._listeners, timeout=timeout
)
class _SubprocessWrapper:
"""Wraps subprocess.Popen to provide the BaseProcess-like interface
needed by wait_for_completion_or_failure."""
@@ -454,58 +330,6 @@ class _SubprocessWrapper:
self._sentinel_send.close()
def _shutdown_subprocesses(
procs: list[_SubprocessWrapper], timeout: float | None = None
) -> None:
"""Shutdown subprocess wrappers (mirrors the shutdown() function)."""
if timeout is None:
timeout = 0.0
timeout = max(timeout, 5.0)
logger.debug(
"[shutdown] Subprocess manager: start process_count=%d timeout=%ss",
len(procs),
timeout,
)
for proc in procs:
if proc.is_alive():
proc.terminate()
deadline = time.monotonic() + timeout
for proc in procs:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
if proc.is_alive():
proc.join(remaining)
remaining_pids = [
proc.pid for proc in procs if proc.is_alive() and proc.pid is not None
]
if remaining_pids:
logger.warning(
"[shutdown] Subprocess manager: force killing remaining processes count=%d",
len(remaining_pids),
)
for pid in remaining_pids:
kill_process_tree(pid)
logger.debug_once("[shutdown] Subprocess manager: complete")
def _shutdown_subprocesses_and_cleanup_listeners(
procs: list[_SubprocessWrapper],
listeners: list[ZmqListener],
timeout: float | None = None,
) -> None:
try:
_shutdown_subprocesses(procs, timeout=timeout)
finally:
for listener in listeners:
listener.cleanup()
def run_api_server_worker_proc(
listen_address, sock, args, client_config=None, **uvicorn_kwargs
) -> None:
@@ -530,7 +354,7 @@ def run_api_server_worker_proc(
def wait_for_completion_or_failure(
api_server_manager: "APIServerProcessManager | RustFrontendProcessManager",
api_server_manager: "APIServerProcessManager",
engine_manager: Union["CoreEngineProcManager", "CoreEngineActorManager"]
| None = None,
coordinator: "DPCoordinator | None" = None,