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
+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)