Add pydocstyle to the ruff rules (#52136)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Signed-off-by: Harry Mellor <hej.mellor@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Harry Mellor
2026-09-16 16:44:29 +00:00
committed by GitHub
co-authored by Claude Opus 5
parent 804e5377aa
commit 8c1557a79c
2002 changed files with 15024 additions and 14269 deletions
+20 -29
View File
@@ -34,8 +34,7 @@ from vllm.v1.kv_cache_interface import KVCacheLayout, get_kv_quant_mode
class AttentionType(str, Enum):
"""
Attention type.
"""Attention type.
Use string to be compatible with `torch.compile`.
"""
@@ -366,7 +365,8 @@ class AttentionBackend(ABC):
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
"""Layouts this backend's kernels can consume, most preferred first, or
None when the kernels consume any layout and express no preference."""
None when the kernels consume any layout and express no preference.
"""
return None
@classmethod
@@ -383,8 +383,7 @@ T = TypeVar("T", bound=AttentionMetadata)
@dataclass
class CommonAttentionMetadata:
"""
Per-batch attention metadata, shared across layers and backends.
"""Per-batch attention metadata, shared across layers and backends.
AttentionMetadataBuilder instances use it to construct per-layer metadata.
For many of the tensors we keep both GPU and CPU versions.
@@ -559,7 +558,8 @@ M = TypeVar("M")
class AttentionCGSupport(Enum):
"""Constants for the cudagraph support of the attention backend
Here we do not consider the cascade attention, as currently
it is never cudagraph supported."""
it is never cudagraph supported.
"""
ALWAYS = 3
"""Cudagraph always supported; supports mixed-prefill-decode"""
@@ -655,8 +655,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> M:
"""
Central method that builds attention metadata.
"""Central method that builds attention metadata.
Some builders (MLA) require reorder_batch to be called prior to build.
Args:
@@ -665,6 +664,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
fast_build: The meta-data will prioritize speed of building over
then speed at execution. Can be used for spec-decode where the
result of a build call may only be used for few layers/iters.
"""
raise NotImplementedError
@@ -674,8 +674,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
blk_table: torch.Tensor,
slot_mapping: torch.Tensor,
) -> M:
"""
Update the block table for the attention metadata.
"""Update the block table for the attention metadata.
Faster when theres multiple kv-cache groups that create virtually the
same metadata but just with different block tables.
@@ -686,8 +685,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
def build_for_cudagraph_capture(
self, common_attn_metadata: CommonAttentionMetadata
) -> M:
"""
Build attention metadata for CUDA graph capture. Uses build by default.
"""Build attention metadata for CUDA graph capture. Uses build by default.
Subclasses that override this method should call self.build or
super().build_for_cudagraph_capture.
"""
@@ -700,8 +698,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
common_attn_metadata: CommonAttentionMetadata,
draft_index: int,
) -> M:
"""
Build attention metadata for draft model. Uses build by default.
"""Build attention metadata for draft model. Uses build by default.
Args:
common_attn_metadata: The common attention metadata.
@@ -710,6 +707,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
draft attempt for the i-th token.
For tree-based attention, this index instead refers to the
draft attempt for the i-th level in the tree of tokens.
"""
return self.build(
common_prefix_len=0,
@@ -910,8 +908,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
raise NotImplementedError
def fused_output_quant_supported(self, quant_key: "QuantKey") -> bool:
"""
Does this attention implementation support fused output quantization.
"""Does this attention implementation support fused output quantization.
This is used by the AttnFusionPass to only fuse output quantization
onto implementations that support it.
@@ -920,20 +917,19 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
Returns:
is fusion supported for this type of quantization
"""
return False
def fused_qk_norm_rope_kvcache_supported(self):
"""
Does this attention implementation support fused QKNorm+RoPE+KVCache fusion.
"""Does this attention implementation support fused QKNorm+RoPE+KVCache fusion.
This is used by the QkNormRopeKvCachePattern to only fuse the QKNorm ops
with the RoPE ops and the KV cache update for implementations that support it.
"""
return False
def fused_rope_kvcache_supported(self):
"""
Does this attention implementation support RoPE+KVCache fusion.
"""Does this attention implementation support RoPE+KVCache fusion.
This is used by the RopeKVCacheFusionPass to only fuse the RoPE ops
with the KV cache update for implementations that support it.
"""
@@ -954,8 +950,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
"""
If `fused_qk_norm_rope_kvcache_supported` returns True, this method
"""If `fused_qk_norm_rope_kvcache_supported` returns True, this method
will be called by the fused custom op. Applies QK-norm + RoPE and
writes K/V to the KV cache. Results are written to the pre-allocated
q_out and k_out tensors; V is split from QKV at the graph level.
@@ -974,8 +969,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
kv_cache: torch.Tensor,
layer_slot_mapping: torch.Tensor,
):
"""
If `fused_rope_kvcache_supported` returns True, this method will be called
"""If `fused_rope_kvcache_supported` returns True, this method will be called
by torch.ops.vllm.fused_rope_and_unified_kv_cache_update
to perform the inplace RoPE and KV cache update.
"""
@@ -1040,8 +1034,7 @@ class MLAAttentionImpl(AttentionImplBase[T], Generic[T]):
raise NotImplementedError
def fused_output_quant_supported(self, quant_key: "QuantKey"):
"""
Does this attention implementation support fused output quantization.
"""Does this attention implementation support fused output quantization.
Since MLA quantization is done manually in forward_impl (common code),
all MLA backends support it by default.
"""
@@ -1080,9 +1073,7 @@ def subclass_attention_backend(
attention_backend_cls: type[AttentionBackend],
builder_cls: type[AttentionMetadataBuilder[M]],
) -> type[AttentionBackend]:
"""
Return a new subclass where `get_builder_cls` returns `builder_cls`.
"""
"""Return a new subclass where `get_builder_cls` returns `builder_cls`."""
name: str = name_prefix + attention_backend_cls.__name__ # type: ignore
return type(
+10 -1
View File
@@ -84,7 +84,8 @@ class CPUAttentionBackend(AttentionBackend):
@classmethod
def supports_attn_type(cls, attn_type: str) -> bool:
"""CPU attention supports decoder,
encoder-only and encoder-decoder attention."""
encoder-only and encoder-decoder attention.
"""
return attn_type in (
AttentionType.DECODER,
AttentionType.ENCODER,
@@ -349,14 +350,22 @@ class CPUAttentionBackendImpl(AttentionImpl):
"""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(
+1
View File
@@ -357,6 +357,7 @@ def is_flash_attn_varlen_func_available() -> bool:
Returns:
bool: True if a working flash_attn_varlen_func implementation is available.
"""
if current_platform.is_cuda() or current_platform.is_xpu():
# CUDA and XPU always have flash_attn_varlen_func available
+10 -2
View File
@@ -766,8 +766,7 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> FlashAttentionMetadata:
"""
fast_build disables AOT scheduling, used when there will be few
"""fast_build disables AOT scheduling, used when there will be few
iterations i.e. spec-decode
"""
num_reqs = common_attn_metadata.num_reqs
@@ -1178,17 +1177,25 @@ class FlashAttentionImpl(AttentionImpl):
"""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, 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]
NOTE: FP8 quantization, flash-attn expect the size of
{q,k,v}_descale to be (num_sequences, num_kv_heads).
We use torch's .expand() to avoid duplicating values
"""
assert self.vllm_flash_attn_version is not None, (
"FlashAttention version not detected."
@@ -1665,6 +1672,7 @@ class FlashAttentionImpl(AttentionImpl):
output: shape = [num_encoder_tokens, num_heads, head_size]
attn_metadata: Encoder attention metadata
layer: The attention layer
"""
assert self.vllm_flash_attn_version is not None, (
"FlashAttention version not detected."
@@ -131,17 +131,25 @@ class FlashAttentionDiffKVImpl(FlashAttentionImpl):
"""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_v]
kv_cache: shape =
[num_blocks, block_size, num_kv_heads, head_size + head_size_v]
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_v]
NOTE: FP8 quantization, flash-attn expect the size of
{q,k,v}_descale to be (num_sequences, num_kv_heads).
We use torch's .expand() to avoid duplicating values
"""
assert self.vllm_flash_attn_version is not None, (
"FlashAttention version not detected."
+12 -6
View File
@@ -398,7 +398,8 @@ class FlashInferBackend(AttentionBackend):
@classmethod
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
"""NVFP4 stores K and V as separate per-head slots of packed fp4 data
plus fp8 block scales."""
plus fp8 block scales.
"""
if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4:
return spec
hs_k = nvfp4_kv_cache_full_dim(spec.head_size)
@@ -1253,9 +1254,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
num_reqs: int,
page_size: int,
) -> torch.Tensor:
"""
Compute paged_kv_indptr, paged_kv_indices, paged_kv_last_page_len for FlashInfer
attention.
"""Compute paged_kv_indptr, paged_kv_indices and paged_kv_last_page_len.
Results are stored in self.paged_kv_indptr,
self.paged_kv_indices, self.paged_kv_last_page_len buffers.
@@ -1964,6 +1963,7 @@ class FlashInferImpl(AttentionImpl):
"""Forward pass with FlashInfer.
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], or None for a
KV-sharing decoder layer.
@@ -1971,8 +1971,15 @@ class FlashInferImpl(AttentionImpl):
KV-sharing decoder layer.
kv_cache: [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. Enables the
attention+quantization fusion path when provided.
output_block_scale: Block scale for fused output quantization,
required for nvfp4 output and rejected for fp8 output.
Returns:
shape = [num_tokens, num_heads * head_size]
"""
if attn_metadata is None:
# Profiling run.
@@ -2638,8 +2645,7 @@ def fast_plan_decode(
fixed_split_size: int = -1,
disable_split_kv: bool = False,
) -> None:
"""
A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for
"""A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for
cudagraph capture/replay, while the no cudagraph version turns back
to the original plan.
using original plan after passing host-side buffers:
+14 -7
View File
@@ -165,8 +165,7 @@ def physical_to_logical_mapping(
block_size: int,
total_blocks: int,
) -> torch.Tensor:
"""
Creates an inverse mapping from physical block locations to logical indices.
"""Creates an inverse mapping from physical block locations to logical indices.
The original block_table maps from logical blocks to physical locations:
@@ -239,6 +238,7 @@ def physical_to_logical_mapping(
A tensor of shape [max_reqs, total_blocks] where each entry
physical_to_logical[req_id, physical_block] contains the logical
block index for that physical block, or -1 if unused.
"""
max_reqs, max_num_blocks = block_table.shape
device = block_table.device
@@ -275,8 +275,7 @@ def unique_static_unsorted(
ignored_val: int = 0, # value to ignore
pad_val: int = -1, # sentinel for unused slots
) -> torch.Tensor:
"""
- Keeps the first occurrence of each non-zero value while preserving order,
"""- Keeps the first occurrence of each non-zero value while preserving order,
then left-packs those uniques and fills the rest with `pad_val`.
- Returns (packed, keep_mask) with the *same shape* as `x`.
- Requires that all values be in the range [0, M]
@@ -286,6 +285,7 @@ def unique_static_unsorted(
Example:
x =[3, 1, 0, 1, 2], M=3, ignored_val=0 => [3, 1, 2, -1, -1]
"""
if not (-1 <= pad_val <= M):
raise ValueError("`pad_val` must lie in [-1, M]")
@@ -349,6 +349,7 @@ class BlockSparsityHint(NamedTuple):
hint_fn: (q_block_idx [num_tokens, 1], kv_block_idx [1, num_kv_blocks],
block_size int) -> bool Tensor [num_tokens, num_kv_blocks].
Returns True for block pairs that may contain non-masked elements.
"""
hint_fn: _block_sparsity_hint_signature
@@ -435,6 +436,7 @@ class FlexAttentionMetadata:
Returns:
tuple of (is_valid, logical_q_idx, logical_kv_idx)
"""
# Map query indices to corresponding request indices
q_req = request_lookup[q_idx]
@@ -512,7 +514,6 @@ class FlexAttentionMetadata:
Note that the sliding window mask here is bidirectional, we need
to mask it with the bidirectional/causal mask for encoder/decoder.
"""
if self.sliding_window is None:
raise ValueError("sliding_window must be set for sliding window attention")
@@ -540,7 +541,6 @@ class FlexAttentionMetadata:
def get_prefix_lm_mask_mod(self) -> _mask_mod_signature:
"""Creates the prefix LM mask_mod function for FlexAttention."""
assert self.doc_ids is not None
request_lookup = self.doc_ids
@@ -587,7 +587,6 @@ class FlexAttentionMetadata:
far-away generated tokens that fall outside the window and outside the
prefix.
"""
assert self.doc_ids is not None
assert self.rswa_prefix_lens is not None
assert self.rswa_window is not None
@@ -1291,14 +1290,22 @@ class FlexAttentionImpl(AttentionImpl):
"""Forward pass with FLexAttention.
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(
+1 -2
View File
@@ -524,8 +524,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
def build_for_cudagraph_capture(
self, common_attn_metadata: CommonAttentionMetadata
):
"""
This method builds the metadata for full cudagraph capture.
"""This method builds the metadata for full cudagraph capture.
Currently, only decode is supported for full cudagraphs with Mamba.
"""
m = common_attn_metadata
+1 -2
View File
@@ -23,8 +23,7 @@ def compute_varlen_chunk_metadata(
query_start_loc: torch.Tensor,
chunk_size: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Build chunk-aligned, variable-length metadata used by Mamba2 SSD kernels.
"""Build chunk-aligned, variable-length metadata used by Mamba2 SSD kernels.
Given per-sequence cumulative token starts `query_start_loc` of shape [B+1]
and a physical `chunk_size`, returns three tensors on the same device:
+6 -13
View File
@@ -227,8 +227,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
def build_for_cudagraph_capture(
self, common_attn_metadata: CommonAttentionMetadata
) -> M:
"""
This method builds the metadata for full cudagraph capture.
"""This method builds the metadata for full cudagraph capture.
Currently, only decode is supported for full cudagraphs with Mamba.
"""
m = common_attn_metadata
@@ -276,8 +275,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
**kwargs: Any,
) -> M:
"""
Default build implementation for Mamba-like attention backends.
"""Default build implementation for Mamba-like attention backends.
Subclasses (e.g., Mamba2) can override to add additional metadata.
"""
return self._compute_common_metadata(
@@ -294,8 +292,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
num_computed_tokens_p_cpu: torch.Tensor,
query_start_loc_p_cpu: torch.Tensor,
) -> tuple[list[int], list[int], list[int]]:
"""
Compute chunk-specific metadata for Mamba models.
"""Compute chunk-specific metadata for Mamba models.
The code below carefully constructs the chunks such that:
1. Chunks contain tokens from a *single* sequence only.
@@ -382,8 +379,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
common: M,
common_attn_metadata: CommonAttentionMetadata,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Compute chunk metadata and return as device tensors.
"""Compute chunk metadata and return as device tensors.
Returns (cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p).
"""
num_prefills = common.num_prefills
@@ -463,9 +459,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
prev_last_scheduled_idx: torch.Tensor | None = None,
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
) -> M:
"""
Compute metadata common to both Mamba1 and Mamba2.
"""
"""Compute metadata common to both Mamba1 and Mamba2."""
num_reqs = common_attn_metadata.num_reqs
# Treat multi-token queries as decode requests when
@@ -752,8 +746,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
self,
metadata: M,
) -> M:
"""
Update the metadata for cudagraph capture.
"""Update the metadata for cudagraph capture.
Currently, only decode is supported for full cudagraphs with Mamba.
"""
state_indices_tensor_d = metadata.state_indices_tensor_d
+2 -1
View File
@@ -63,7 +63,8 @@ _SPLIT_OCCUPANCY_MULTIPLIER = 2
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."""
count in place of SM count.
"""
ideal_splits = 1
while ideal_splits < max(1, max_seq_len // _MIN_WORK_PER_SPLIT):
ideal_splits *= 2
@@ -437,7 +437,6 @@ class FlashMLASparseMetadataBuilder(
be the full batch or only decodes when prefills use dense MHA. This avoids
the BF16 prefill kernel's head-padding overhead at high TP.
"""
scheduler_metadata, _ = get_mla_metadata()
return FlashMLASparseMetadata.FP8KernelMetadata(
scheduler_metadata=scheduler_metadata,
@@ -848,7 +847,8 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
prefill_meta: "FlashMLASparseMetadata.FP8SeparatePrefillDecode.Prefill",
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""All-gather this rank's upconverted KV shard so the chunk's rows attend
the whole context, and map their top-k onto the rank-major result."""
the whole context, and map their top-k onto the rank-major result.
"""
shard_rows = int(chunk.chunk_tot_seqlen)
assert self.gathered_kv_workspace is not None
gathered_kv = self.gathered_kv_workspace[: self.dcp_world_size * shard_rows]
+2 -1
View File
@@ -1118,7 +1118,8 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
def _prefill_split_seq_lens(self, seq_lens_cpu: torch.Tensor) -> torch.Tensor:
"""Per-request KV lengths the prefill chunker budgets logits with;
subclasses whose logits rows are wider than the context override."""
subclasses whose logits rows are wider than the context override.
"""
return seq_lens_cpu
@staticmethod
@@ -24,7 +24,7 @@ if TYPE_CHECKING:
class AiterFlashAttnPrefillBackend(MLAPrefillBackend):
"""AITER FlashAttention backend for MLA prefill"""
"""AITER FlashAttention backend for MLA prefill."""
@staticmethod
def get_name() -> str:
@@ -70,7 +70,8 @@ class MLAPrefillBackend(ABC):
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
"""Whether `run_prefill_new_tokens` can write quantized output
directly (fused) for the given quant key, skipping the post-quant
pass. Overridden by backends that support it."""
pass. Overridden by backends that support it.
"""
return False
def supports_out(self) -> bool:
@@ -65,6 +65,7 @@ class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
Raises:
ValueError: If Backend.CUSTOM is used without being registered
"""
path = _MLA_PREFILL_OVERRIDES.get(self, self.value)
if not path:
@@ -85,6 +86,7 @@ class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
Raises:
ImportError: If the backend class cannot be imported
ValueError: If CUSTOM is used without being registered
"""
return resolve_obj_by_qualname(self.get_path())
@@ -130,6 +132,7 @@ def register_mla_prefill_backend(
MLAPrefillBackendEnum.CUSTOM,
"my.module.MyCustomPrefillBackend"
)
"""
def decorator(cls: type) -> type:
@@ -57,6 +57,7 @@ def _get_mla_prefill_backend_priorities(
Returns:
List of backends in priority order (highest priority first).
"""
from vllm.platforms import current_platform
@@ -104,6 +105,7 @@ def get_mla_prefill_backend(
Returns:
The selected prefill backend class.
"""
from vllm.platforms import current_platform
@@ -173,6 +175,7 @@ def _auto_select_mla_prefill_backend(
Returns:
The selected prefill backend class.
"""
priorities = _get_mla_prefill_backend_priorities(
device_capability,
@@ -710,6 +710,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
attn_out_dtype: Dtype of the attention output buffer, used to size
the padded-head output scratch (small head counts only).
device: Target device for the buffers.
"""
from aiter import get_ps_metadata_info_v1
@@ -1328,8 +1329,7 @@ def _expand_page_indices_kernel(
class AiterMLAHelper:
"""
AITER MLA persistent (asm) decode requires a multiple of 16 heads. Unaligned
"""AITER MLA persistent (asm) decode requires a multiple of 16 heads. Unaligned
head counts through 128 are padded to the next multiple of 16 by tiling the
query heads and slicing to the padded size. Native H24 AITER builds bypass
that padding. Small divisors of 16 retain the existing repeat_interleave and
@@ -167,8 +167,7 @@ def triton_convert_req_index_to_global_index(
NUM_TOPK_TOKENS: int = 2048,
BLOCK_N: int = 128, # tile width along columns
):
"""
out[token_id, indice_id] =
"""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
@@ -426,6 +426,7 @@ def _remap_tiling(
Returns:
(single_tile, block_n, tiles_per_row, num_warps)
"""
single_tile = (
count_valid and triton.next_power_of_2(NUM_TOPK_TOKENS) == NUM_TOPK_TOKENS
@@ -454,8 +455,7 @@ def triton_convert_req_index_to_global_index(
out: torch.Tensor | None = None,
valid_counts_out: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""
out[token_id, indice_id] =
"""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
+9 -1
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention backend registry"""
"""Attention backend registry."""
from collections.abc import Callable
from enum import Enum, EnumMeta
@@ -161,6 +161,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
Raises:
ValueError: If Backend.CUSTOM is used without being registered
"""
path = _ATTN_OVERRIDES.get(self, self.value)
if not path:
@@ -181,6 +182,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
Raises:
ImportError: If the backend class cannot be imported
ValueError: If Backend.CUSTOM is used without being registered
"""
return resolve_obj_by_qualname(self.get_path())
@@ -189,6 +191,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
Returns:
True if the backend has a registered override
"""
return self in _ATTN_OVERRIDES
@@ -224,6 +227,7 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
Raises:
ValueError: If Backend.CUSTOM is used without being registered
"""
path = _MAMBA_ATTN_OVERRIDES.get(self, self.value)
if not path:
@@ -244,6 +248,7 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
Raises:
ImportError: If the backend class cannot be imported
ValueError: If Backend.CUSTOM is used without being registered
"""
return resolve_obj_by_qualname(self.get_path())
@@ -252,6 +257,7 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
Returns:
True if the backend has a registered override
"""
return self in _MAMBA_ATTN_OVERRIDES
@@ -275,6 +281,7 @@ def register_backend(
backend: The AttentionBackendEnum member to register
class_path: Optional class path. If not provided and used as
decorator, will be auto-generated from the class.
is_mamba: Whether the backend is a Mamba attention backend.
Returns:
Decorator function if class_path is None, otherwise a no-op
@@ -300,6 +307,7 @@ def register_backend(
AttentionBackendEnum.CUSTOM,
"my.module.MyCustomBackend"
)
"""
def decorator(cls: type) -> type:
+9 -2
View File
@@ -770,8 +770,7 @@ class AiterFlashAttentionMetadataBuilder(
common_attn_metadata: CommonAttentionMetadata,
draft_index: int,
) -> AiterFlashAttentionMetadata:
"""
Build attention metadata for draft model without CPU-GPU sync.
"""Build attention metadata for draft model without CPU-GPU sync.
During EAGLE drafting all requests are uniform decodes, so we can
skip split_decodes_prefills_and_extends() and avoid all .cpu() /
@@ -1189,17 +1188,25 @@ class AiterFlashAttentionImpl(AttentionImpl):
"""Forward pass with AiterFlashAttention.
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; 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]
NOTE: FP8 quantization, flash-attn expect the size of
{q,k,v}_descale to be (num_sequences, num_kv_heads).
We use torch's .expand() to avoid duplicating values
"""
if output_scale is not None or output_block_scale is not None:
raise NotImplementedError(
@@ -110,7 +110,8 @@ class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
@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."""
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.
@@ -207,14 +208,21 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
"""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(
+10 -1
View File
@@ -244,7 +244,8 @@ class RocmAttentionBackend(AttentionBackend):
@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)."""
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, (
@@ -344,6 +345,7 @@ class RocmAttentionImpl(AttentionImpl):
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):
@@ -390,14 +392,21 @@ class RocmAttentionImpl(AttentionImpl):
"""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(
+10 -1
View File
@@ -275,7 +275,8 @@ class TritonAttentionBackend(AttentionBackend):
@classmethod
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
"""Per-token-head modes pack inline fp32 scales after each head's
data, so the content is (data + one scale) per K/V side."""
data, so the content is (data + one scale) per K/V side.
"""
mode = spec.kv_quant_mode
if spec.state_content_bytes is not None or not mode.is_per_token_head:
return spec
@@ -557,14 +558,21 @@ class TritonAttentionImpl(AttentionImpl):
"""Forward pass with Paged Attention impl. in Triton.
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.
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(
@@ -724,6 +732,7 @@ class TritonAttentionImpl(AttentionImpl):
output: shape = [num_encoder_tokens, num_heads, head_size]
attn_metadata: Encoder attention metadata
layer: The attention layer
"""
# Quantized KV cache is not supported for encoder attention.
if is_quantized_kv_cache(self.kv_cache_dtype):
+15 -22
View File
@@ -324,8 +324,7 @@ def resolve_kv_cache_layout(
@dataclass
class PerLayerParameters:
"""
Currently, FlashInfer backend only support models in which all layers share
"""Currently, FlashInfer backend only support models in which all layers share
the same values for the following hyperparameters. Should not be used for
trtllm-gen backend since it supports different values for the following
hyperparameters.
@@ -343,11 +342,9 @@ class PerLayerParameters:
def get_per_layer_parameters(
vllm_config: VllmConfig, layer_names: list[str], cls_: type["AttentionImpl"]
) -> dict[str, PerLayerParameters]:
"""
Scan layers in `layer_names` and determine some hyperparameters
"""Scan layers in `layer_names` and determine some hyperparameters
to use during `plan`.
"""
layers = get_layers_from_vllm_config(
vllm_config,
AttentionLayerBase, # type: ignore[type-abstract]
@@ -405,8 +402,7 @@ def get_num_attention_heads_from_layers(
def infer_global_hyperparameters(
per_layer_params: dict[str, PerLayerParameters],
) -> PerLayerParameters:
"""
Currently, FlashInfer backend other than trtllm-gen
"""Currently, FlashInfer backend other than trtllm-gen
only support models in which all layers share
the same values for the following hyperparameters:
- `window_left`
@@ -416,7 +412,6 @@ def infer_global_hyperparameters(
So this function asserts that all layers share the same values for these
hyperparameters and returns the global values.
"""
assert len(per_layer_params) > 0, "No attention layers found in the model."
param_sets = list(per_layer_params.values())
@@ -710,8 +705,7 @@ def split_decodes_prefills_and_extends(
common_attn_metadata: CommonAttentionMetadata,
decode_threshold: int = 1,
) -> tuple[int, int, int, int, int, int]:
"""
Assuming a reordered batch, finds the boundary between prefill and decode
"""Assuming a reordered batch, finds the boundary between prefill and decode
requests.
Args:
@@ -726,6 +720,7 @@ def split_decodes_prefills_and_extends(
num_decode_tokens: The number of tokens in the decode requests.
num_extend_tokens: The number of tokens in the extend requests.
num_prefill_tokens: The number of tokens in the prefill requests.
"""
max_query_len = common_attn_metadata.max_query_len
num_reqs = common_attn_metadata.num_reqs
@@ -784,8 +779,7 @@ def split_decodes_and_prefills(
require_uniform: bool = False,
treat_short_extends_as_decodes: bool = True,
) -> tuple[int, int, int, int]:
"""
Assuming a reordered batch, finds the boundary between prefill and decode
"""Assuming a reordered batch, finds the boundary between prefill and decode
requests.
The batch is expected to be ordered as:
@@ -807,6 +801,7 @@ def split_decodes_and_prefills(
num_prefills: The number of prefill requests.
num_decode_tokens: The number of tokens in the decode requests.
num_prefill_tokens: The number of tokens in the prefill requests.
"""
max_query_len = common_attn_metadata.max_query_len
num_reqs = common_attn_metadata.num_reqs
@@ -855,16 +850,17 @@ def split_decodes_and_prefills(
def split_prefill_chunks(
seq_lens_cpu: torch.Tensor, workspace_size: int, request_offset: int = 0
) -> list[tuple[int, int]]:
"""
Split the prefill requests into chunks such that the total sequence length
"""Split the prefill requests into chunks such that the total sequence length
of each chunk is less than or equal to the workspace size.
Args:
seq_lens_cpu: The sequence lengths of the prefill requests on CPU.
workspace_size: The maximum workspace size (in tokens) per chunk.
request_offset: The offset to add to the request indices.
Returns:
A list of tuples of (reqs_start, reqs_end) representing chunk boundaries.
"""
chunk_bounds = []
i, n = 0, len(seq_lens_cpu)
@@ -884,8 +880,7 @@ def reorder_batch_to_split_decodes_and_prefills(
scheduler_output: "SchedulerOutput",
decode_threshold: int = 1,
) -> bool:
"""
Reorders the batch to split into prefill and decode requests; places all
"""Reorders the batch to split into prefill and decode requests; places all
requests with <= decode_threshold tokens at the front of the batch.
The batch is reordered into 4 regions:
@@ -896,6 +891,7 @@ def reorder_batch_to_split_decodes_and_prefills(
Returns:
True if the batch was modified, False otherwise.
"""
num_reqs = len(input_batch.req_ids)
num_scheduled_tokens = [
@@ -960,8 +956,7 @@ def reorder_batch_to_split_decodes_and_prefills(
def reshape_query_for_spec_decode(query: torch.Tensor, batch_size: int) -> torch.Tensor:
"""
Reshapes the query tensor for the specified batch size, so that
"""Reshapes the query tensor for the specified batch size, so that
it has shape (batch_size, seq_len, num_heads, head_dim).
"""
assert query.dim() == 3, f"query must be 3D, got {query.dim()}D"
@@ -976,8 +971,7 @@ def reshape_query_for_spec_decode(query: torch.Tensor, batch_size: int) -> torch
def reshape_attn_output_for_spec_decode(attn_output: torch.Tensor) -> torch.Tensor:
"""
Reshapes the attention output tensor, so that
"""Reshapes the attention output tensor, so that
the batch_size and seq_len dimensions are combined.
"""
if attn_output.dim() == 3:
@@ -1143,8 +1137,7 @@ def mamba_get_block_table_tensor(
kv_cache_spec: KVCacheSpec,
mamba_cache_mode: str,
) -> torch.Tensor:
"""
Get the block table tensor for mamba kernels from the input
"""Get the block table tensor for mamba kernels from the input
common_attn_metadata.block_table_tensor given different mamba cache modes.
- "all": input (#requests, cdiv(max_model_len, block_size)
+3 -3
View File
@@ -178,6 +178,7 @@ def pack_seq_triton(
Returns:
packed: [B, Lmax, ...] — packed tensor.
"""
is_uint8 = x.dtype == torch.uint8
if is_uint8:
@@ -334,8 +335,7 @@ def unpack_seq_triton(
block_t: int = 64,
block_d: int = 64,
) -> torch.Tensor:
"""
Unpack a packed decode query tensor back to the original format.
"""Unpack a packed decode query tensor back to the original format.
Efficient Triton implementation.
Args:
@@ -346,8 +346,8 @@ def unpack_seq_triton(
Returns:
unpacked_tensor: [N, ...] where N = sum(lengths)
"""
"""
# Handle multi-dimensional input by reshaping to (B, Lmax, -1)
original_shape = packed_tensor.shape
if len(original_shape) > 3:
+21 -12
View File
@@ -133,8 +133,7 @@ class CorrectAttnCPOutKernel(VllmTritonJitKernel["CorrectAttnCPOutKernel.Compile
N_ROUNDED: tl.constexpr,
IS_BASE_E: tl.constexpr,
):
"""
Apply the all-gathered lses to correct each local rank's attention
"""Apply the all-gathered lses to correct each local rank's attention
output. we still need perform a cross-rank reduction to obtain the
final attention output.
@@ -147,6 +146,17 @@ class CorrectAttnCPOutKernel(VllmTritonJitKernel["CorrectAttnCPOutKernel.Compile
Pointer to output tensor of shape [ B, H, D ]
vlse_ptr (triton.PointerType):
Pointer to output tensor of shape [ B, H ]
outputs_stride_B (int): Batch stride of ``outputs_ptr``
outputs_stride_H (int): Head stride of ``outputs_ptr``
outputs_stride_D (int): Head-dim stride of ``outputs_ptr``
lses_stride_N (int): Rank stride of ``lses_ptr``
lses_stride_B (int): Batch stride of ``lses_ptr``
lses_stride_H (int): Head stride of ``lses_ptr``
lse_idx (int): Index of this rank's lse within the all-gathered tensor
HEAD_DIM: Head dimension, as a constexpr
N_ROUNDED: Rank count rounded to a power of two, as a constexpr
IS_BASE_E: Whether the lses are natural-log based, as a constexpr
"""
batch_idx = tl.program_id(axis=0).to(tl.int64)
head_idx = tl.program_id(axis=1).to(tl.int64)
@@ -376,9 +386,11 @@ def correct_attn_out(
lses: Tensor of shape [ N, B, H ]
cp_rank: Current rank in the context-parallel group
ctx: Triton context to avoid recompilation
is_lse_base_on_e: Whether the lses use base e rather than base 2
Returns:
Tuple of (out, lse) with corrected attention and final log-sum-exp.
"""
if ctx is None:
ctx = CPTritonContext()
@@ -431,8 +443,7 @@ def _cp_lse_common(
seq_lens: torch.Tensor | None = None,
query_start_loc: torch.Tensor | None = None,
):
"""
cp_attn_out: [ B, H, D ]
"""cp_attn_out: [ B, H, D ]
cp_attn_lse: [ B, H ]
"""
if cp_group.world_size == 1:
@@ -466,8 +477,7 @@ def cp_lse_ag_out_rs(
seq_lens: torch.Tensor | None = None,
query_start_loc: torch.Tensor | None = None,
):
"""
cp_attn_out: [ B, H, D ]
"""cp_attn_out: [ B, H, D ]
cp_attn_lse: [ B, H ]
"""
out, lse = _cp_lse_common(
@@ -499,8 +509,7 @@ def cp_lse_ag_out_ar(
seq_lens: torch.Tensor | None = None,
query_start_loc: torch.Tensor | None = None,
):
"""
cp_attn_out: [ B, H, D ]
"""cp_attn_out: [ B, H, D ]
cp_attn_lse: [ B, H ]
"""
out, lse = _cp_lse_common(
@@ -528,8 +537,7 @@ def _lse_weighted_combine(
return_lse: bool = False,
is_lse_base_on_e: bool = True,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""
CPU reference implementation for LSE-weighted combination.
"""CPU reference implementation for LSE-weighted combination.
This is a pure PyTorch implementation used for testing and validation.
@@ -545,6 +553,7 @@ def _lse_weighted_combine(
Returns:
Combined output [B, H, D], and optionally global LSE [B, H]
"""
N, B, H, D = outputs.shape
@@ -936,8 +945,7 @@ def dcp_a2a_lse_reduce(
seq_lens: torch.Tensor | None = None,
query_start_loc: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""
Combine partial attention outputs across DCP ranks using All-to-All.
"""Combine partial attention outputs across DCP ranks using All-to-All.
The output and LSE are packed into a single output-dtype buffer, sent
with one All-to-All, then unpacked and combined with exact LSE weighting.
@@ -955,6 +963,7 @@ def dcp_a2a_lse_reduce(
Returns:
Combined output [B, H/N, D] (head-scattered)
If return_lse=True, also returns global_lse [B, H/N]
"""
world_size = cp_group.world_size
+2 -6
View File
@@ -49,9 +49,7 @@ def _is_flashmla_available() -> tuple[bool, str | None]:
def is_flashmla_dense_supported() -> tuple[bool, str | None]:
"""
Return: is_supported_flag, unsupported_reason (optional).
"""
"""Return: is_supported_flag, unsupported_reason (optional)."""
is_available, maybe_reason = _is_flashmla_available()
if not is_available:
return False, maybe_reason
@@ -61,9 +59,7 @@ def is_flashmla_dense_supported() -> tuple[bool, str | None]:
def is_flashmla_sparse_supported() -> tuple[bool, str | None]:
"""
Return: is_supported_flag, unsupported_reason (optional).
"""
"""Return: is_supported_flag, unsupported_reason (optional)."""
is_available, maybe_reason = _is_flashmla_available()
if not is_available:
return False, maybe_reason
+1 -1
View File
@@ -106,8 +106,8 @@ def merge_attn_states(
are treated as having context.
output_scale: Optional scalar tensor for FP8 static quantization.
When provided, output must be FP8 dtype.
"""
"""
# Both the CUDA and Triton kernels derive the suffix head stride from
# prefix_output, so suffix_output must share the same head stride.
assert prefix_output.stride(1) == suffix_output.stride(1), (
@@ -654,6 +654,7 @@ def rocm_fp8_paged_mqa_logits(
Returns:
Logits tensor of shape [B * next_n, max_model_len], dtype
`torch.float32`.
"""
from vllm._aiter_ops import rocm_aiter_ops
@@ -737,6 +738,7 @@ def fp8_mqa_logits_torch(
Returns:
Logits tensor of shape [M, N], dtype `torch.float32`.
"""
k_fp8, scale = kv
seq_len_kv = k_fp8.shape[0]
@@ -805,8 +807,8 @@ def rocm_fp8_mqa_logits(
Returns:
Logits tensor of shape [M, N], dtype `torch.float32`.
"""
"""
from vllm._aiter_ops import rocm_aiter_ops
k_fp8, scale = kv
@@ -24,8 +24,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
Memory-efficient attention for decoding.
"""Memory-efficient attention for decoding.
It supports page size >= 1.
"""
@@ -19,8 +19,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
Memory-efficient attention for prefill.
"""Memory-efficient attention for prefill.
It supports page size = 1.
"""
@@ -229,8 +228,7 @@ def context_attention_fwd(
sinks: torch.Tensor | None = None,
sinks_bias_key0: bool = False,
):
"""
q, k, v: [b * s, head, head_dim]
"""q, k, v: [b * s, head, head_dim]
b_start_loc: [b]
b_seq_len: [b]
out: [b * s, head, head_dim]
@@ -45,7 +45,8 @@ def _store_quantized_value(
BLOCK_GRP: tl.constexpr,
):
"""Uniform quantization of values to VQB bits, pack, and store with
scale/zero in the per-block SoA metadata region (Opt#3 layout)."""
scale/zero in the per-block SoA metadata region (Opt#3 layout).
"""
if VQB == 3:
val_vec = tl.load(Value_ptr + base + d_offs, mask=d_mask, other=0.0).to(
tl.float32
+2 -4
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
This file contains ops for ViT attention to be compatible with torch.compile
"""This file contains ops for ViT attention to be compatible with torch.compile
as there are operations here not supported by torch.compile (for instance,
`.item()` in flash attention)
@@ -238,8 +237,7 @@ def apply_sdpa(
scale: float | None = None,
enable_gqa: bool = False,
) -> torch.Tensor:
"""
Input shape:
"""Input shape:
(batch_size x seq_len x num_heads x head_size)
"""
q, k, v = (einops.rearrange(x, "b s h d -> b h s d") for x in [q, k, v])
+7 -2
View File
@@ -185,15 +185,20 @@ def triton_bf16_mla_sparse_interface(
d_v: int = 512,
block_dpe: int = 64,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
out : [num_tokens, num_heads_q, d_v]
"""Out : [num_tokens, num_heads_q, d_v]
max_logits : [num_tokens, num_heads_q]
lse : logsumexp, [num_tokens, num_heads_q]
Args:
q: Query tensor, [num_tokens, num_heads_q, dim_qk].
kv: Latent KV cache tensor.
indices: Sparse KV indices selected for each query token.
sm_scale: Softmax scale applied to the QK product.
d_v: Size of the value dimension.
block_dpe: Size of positional embedding portion of dim_qk.
Set to 0 when q/kv contain only the nope latent (e.g. DSv4
prefill where RoPE is not split out).
"""
num_tokens, num_heads_q, dim_qk = q.shape
_, num_heads_kv, _ = kv.shape
+1 -1
View File
@@ -85,6 +85,7 @@ def get_attn_spec_kind(
Returns:
The ``KVCacheSpecKind`` the layer maps to.
"""
from vllm.v1.kv_cache_interface import KVCacheSpecKind
@@ -115,7 +116,6 @@ def get_attn_backend(
has_sliding_window: bool = False,
) -> type[AttentionBackend]:
"""Selects which attention backend to use and lazily imports it."""
if kv_cache_dtype is not None:
valid_cache_dtypes = get_args(CacheDType)
assert kv_cache_dtype in valid_cache_dtypes, (