[6/N][KV-Cache Layout Refactor] Standardize KV cache layout (#51718)

Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com>
This commit is contained in:
Lucas Wilkinson
2026-08-21 17:47:49 -07:00
committed by GitHub
parent 9ff7041b55
commit 8bdc70ec7b
150 changed files with 4006 additions and 5815 deletions
@@ -45,7 +45,7 @@ def fused_rope_unified_mla_kv_cache_update_impl(
cos_sin_cache,
is_neox,
layer_slot_mapping,
kv_cache,
kv_cache.squeeze(1),
kv_cache_dtype,
kv_cache_scale,
)
+40
View File
@@ -3,6 +3,7 @@
from collections.abc import Callable
from dataclasses import field
from functools import cache
from typing import Any, ClassVar, Literal
from pydantic import Field, field_validator, model_validator
@@ -13,9 +14,28 @@ from vllm.utils.torch_utils import (
is_quantized_kv_cache,
kv_cache_uses_per_token_head_scales,
)
from vllm.v1.kv_cache_layout import KVCacheLayout
logger = init_logger(__name__)
_LAYOUT_COMPAT_ALIASES = {
"NHD": "LBNHC",
"HND": "LBHNC",
}
@cache
def _layout_from_name(layout_name: str) -> KVCacheLayout:
layout_name = _LAYOUT_COMPAT_ALIASES.get(layout_name, layout_name)
try:
return KVCacheLayout[layout_name]
except KeyError:
raise ValueError(
f"Unknown KV cache layout {layout_name!r}. "
f"Valid layouts: {[m.name for m in KVCacheLayout]}"
) from None
CacheDType = Literal[
"auto",
"float16",
@@ -65,6 +85,17 @@ class CacheConfig:
"""Whether block_size was explicitly provided. Derived automatically."""
user_specified_mamba_block_size: bool = field(default=False, init=False)
"""Whether mamba_block_size was explicitly provided. Derived automatically."""
kv_cache_layout: str | None = field(default=None, init=False)
"""Resolved physical KV cache layout name (a ``KVCacheLayout`` member).
``None`` means the layout has not been resolved yet. The engine core
resolves it once (``resolve_kv_cache_layout``) before memory profiling, and
every worker process adopts the resolved name — via the
``set_kv_cache_layout`` RPC, or ``KVCacheConfig.kv_cache_layout`` for
workers spawned after resolution — before the KV cache is allocated. Once
set the value is final and read with ``get_resolved_kv_cache_layout``,
which raises on ``None``. Tests and standalone tools may pre-set a value,
which resolution then honors as-is."""
prefix_match_unit: int | None = Field(default=None, gt=0)
"""The finest token boundary (in tokens) a prefix-cache hit can land on.
@@ -309,3 +340,12 @@ class CacheConfig:
str(cache_dtype),
)
return cache_dtype
def get_resolved_kv_cache_layout(self) -> KVCacheLayout:
if self.kv_cache_layout is None:
raise ValueError(
"KV cache layout has not been resolved yet; it is resolved once "
"by the engine core (resolve_kv_cache_layout) unless explicitly "
"set by the user."
)
return _layout_from_name(self.kv_cache_layout)
@@ -12,7 +12,7 @@ import torch
from vllm.config import (
VllmConfig,
get_current_vllm_config,
get_current_vllm_config_or_none,
get_layers_from_vllm_config,
set_current_vllm_config,
)
@@ -35,20 +35,20 @@ EngineId = str
BlockIds = tuple[list[int], ...] | list[list[int]]
def get_kv_connector_cache_layout():
# NOTE (NickLucche) When running disaggregated PD with NIXL, HND layout is
def get_kv_connector_cache_layout(vllm_config: VllmConfig | None = None):
# NOTE (NickLucche) When running disaggregated PD with NIXL, LBHNC layout is
# used for faster transfer.
vllm_config = get_current_vllm_config()
if vllm_config is None:
vllm_config = get_current_vllm_config_or_none()
if vllm_config is None:
return None
kv_config = vllm_config.kv_transfer_config
if kv_config is not None:
connector_cls = KVConnectorFactory.get_connector_class(kv_config)
required_kvcache_layout = connector_cls.get_required_kvcache_layout(vllm_config)
if required_kvcache_layout is not None:
return required_kvcache_layout
logger.info_once(
"Connectors do not specify a kv cache layout, defaulting to NHD."
)
return "NHD"
return None
class KVOutputAggregator:
@@ -288,11 +288,11 @@ def kv_postprocess_layout_on_receive(cache, indices):
def kv_postprocess_blksize_and_layout_on_receive(cache, indices, block_size_ratio):
"""
Transforms the layout of received KV cache to the local block_size and HND.
Transforms the layout of received KV cache to the local block_size and LBHNC.
(Only works for local blocksize > remote blocksize)
prefill is HND, smaller block_size
decode(local) is NHD, larger block_size
prefill is LBHNC, smaller block_size
decode(local) is LBNHC, larger block_size
"""
blocks_to_update = cache.index_select(0, indices)
@@ -427,48 +427,6 @@ class TransferTopology:
self._engines: dict[tuple[EngineId, int], EngineTransferInfo] = {}
# Figure out whether the first dimension of the cache is K/V
# or num_blocks.
attn_backend = self.attn_backends[0]
if not self.is_mamba:
_MOCK_BLOCK_SIZE = 16
kv_cache_shape: tuple[int, ...] = attn_backend.get_kv_cache_shape(
num_blocks=1,
block_size=_MOCK_BLOCK_SIZE,
num_kv_heads=1,
head_size=1,
)
logger.debug("Test kv_cache_shape: %s", kv_cache_shape)
assert kv_cache_shape[0] == 1, (
"KV cache layout must be blocks-first; expected mocked "
f"num_blocks=1 in leading dim, got shape {kv_cache_shape}."
)
if not self.is_mla:
assert len(kv_cache_shape) == 4, (
"Attention KV cache layout must be standardized as "
"[num_blocks, num_kv_heads, block_size, content_size], "
f"got shape {kv_cache_shape}."
)
self._cross_layers_blocks = False
if self.tensor_shape is not None:
self._cross_layers_blocks = (
len(self.tensor_shape) == len(kv_cache_shape) + 1
)
if self._cross_layers_blocks:
logger.debug("Using cross-layer KV cache")
_MOCK_NUM_LAYERS = 80
kv_cache_shape = (_MOCK_NUM_LAYERS,) + kv_cache_shape
try:
kv_cache_stride_order = attn_backend.get_kv_cache_stride_order(
include_num_layers_dimension=self._cross_layers_blocks
)
except (AttributeError, NotImplementedError):
assert self.tensor_shape is not None
kv_cache_stride_order = tuple(range(len(self.tensor_shape)))
kv_cache_shape = tuple(kv_cache_shape[i] for i in kv_cache_stride_order)
# ============================================================
# Engine registration
# ============================================================
@@ -503,24 +461,6 @@ class TransferTopology:
for key in [k for k in self._engines if k[0] == remote_engine_id]:
del self._engines[key]
# ============================================================
# Layout properties
# ============================================================
@property
def cross_layers_blocks(self) -> bool:
return self._cross_layers_blocks
@property
def virtually_split_kv_in_blocks(self) -> bool:
# Whether to logically split each block into two separately-indexable
# sub-regions. With K and V packed into the content dim, an attention
# block transfers as a single unit — no K/V sub-split is needed. Only
# Mamba still needs this, to index its two state regions (conv/ssm)
# separately. Not applicable to cross-layer blocks (per-layer
# interleaving means a simple half-split does not separate the parts).
return self.is_mamba and not self._cross_layers_blocks
# ============================================================
# Common methods
# ============================================================
@@ -48,7 +48,7 @@ from typing import TYPE_CHECKING, Any, Literal
import torch
from vllm.logger import init_logger
from vllm.v1.attention.backend import AttentionBackend, AttentionMetadata
from vllm.v1.attention.backend import AttentionMetadata
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.outputs import KVConnectorOutput
@@ -182,14 +182,6 @@ class KVConnectorBase_V1(ABC):
"""
return False
@property
def prefer_cross_layer_blocks(self) -> bool:
"""
Indicates whether this connector prefers KV blocks that hold KV data for all
layers, which can speed up KV data transfers. Defaults to False.
"""
return False
@property
def requires_kv_delivery(self) -> bool:
"""Whether this connector hands off KV that must be reliably delivered.
@@ -279,23 +271,6 @@ class KVConnectorBase_V1(ABC):
"""
return
def register_cross_layers_kv_cache(
self, kv_cache: torch.Tensor, attn_backend: type["AttentionBackend"]
):
"""
Initialize with a single KV cache tensor used by all layers.
The first dimension should be num_layers.
This function will only be called for models with uniform layers,
and only if the prefers_cross_layer_blocks is set to True.
Only one of the functions
{register_kv_caches, register_cross_layers_kv_cache} will be called.
Args:
kv_cache: a cross-layers kv cache tensor
attn_backend: The attention backend that corresponds to all layers
"""
return
def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp):
"""
Set the xPU-specific ops for copying KV between host and device.
@@ -129,20 +129,17 @@ class ExampleConnector(KVConnectorBase_V1):
"""Inject the KV cache into the layer.
Args:
dst_kv_cache_layer (torch.Tensor): the destination KV cache
layer. In shape [num_pages, page_size, xxx] for MLA,
[num_pages, 2, page_size, xxx] otherwise.
dst_kv_cache_layer (torch.Tensor): the destination KV cache layer,
a standardized [B, H, N, C] per-layer view (H == 1 for MLA).
src_kv_cache (torch.Tensor): the source KV cache.
slot_mapping (torch.Tensor): the slot mapping. In shape
[num_tokens].
"""
slot_mapping = slot_mapping.to(dst_kv_cache_layer.device, non_blocking=True)
if isinstance(attn_metadata, MLACommonMetadata):
dst_kv_cache_layer_shape = dst_kv_cache_layer.shape
num_pages = dst_kv_cache_layer_shape[0]
page_size = dst_kv_cache_layer_shape[1]
# [B, 1, N, C] -> [B * N, C]; slot_mapping indexes B * N slots.
dst_kv_cache_layer = dst_kv_cache_layer.reshape(
num_pages * page_size, -1
-1, dst_kv_cache_layer.shape[-1]
)
dst_kv_cache_layer[slot_mapping, ...] = src_kv_cache
else:
@@ -225,13 +222,12 @@ class ExampleConnector(KVConnectorBase_V1):
) -> torch.Tensor:
"""Extract the KV cache from the layer.
Assume the shape of the layer is (num_pages, page_size, xxx)
for MLA, and (num_pages, 2, page_size, xxx) otherwise.
The layer is a standardized [B, H, N, C] per-layer view (H == 1 for MLA).
"""
slot_mapping = slot_mapping.to(layer.device, non_blocking=True)
if isinstance(attn_metadata, MLACommonMetadata):
num_pages, page_size = layer.shape[0], layer.shape[1]
return layer.reshape(num_pages * page_size, -1)[slot_mapping, ...]
# [B, 1, N, C] -> [B * N, C]; slot_mapping indexes B * N slots.
return layer.reshape(-1, layer.shape[-1])[slot_mapping, ...]
block_idxs = slot_mapping // self._block_size
offsets = slot_mapping % self._block_size
return layer[block_idxs, :, offsets]
@@ -38,8 +38,10 @@ def extract_from_kv_cache(
num_tokens: int,
) -> torch.Tensor:
"""Extract data from KV cache."""
block_size = kv_cache.shape[1]
return kv_cache[slot_mapping // block_size, slot_mapping % block_size][:num_tokens]
block_size = kv_cache.shape[2]
return kv_cache[slot_mapping // block_size, :, slot_mapping % block_size][
:num_tokens
]
def load_hidden_states(path: str) -> dict[str, torch.Tensor]:
@@ -100,15 +102,6 @@ class ExampleHiddenStatesConnector(KVConnectorBase_V1, SupportsHMA):
Must be used in conjunction with the `extract_hidden_states` spec decoding method.
"""
@property
def prefer_cross_layer_blocks(self) -> bool:
"""
Indicates whether this connector prefers KV blocks that hold KV data for all
layers, which can speed up KV data transfers. Defaults to False.
"""
# Must be False so that drafter kv cache isn't merged with verifier's
return False
@classmethod
def _find_cache_kv_group_id(cls, kv_cache_config: "KVCacheConfig | None") -> int:
"""Index of the KV cache group holding the extracted hidden states.
@@ -310,10 +303,12 @@ class ExampleHiddenStatesConnector(KVConnectorBase_V1, SupportsHMA):
# Block size must match the indexed buffer, else reads hit the wrong
# slots. Raise (not assert) so the check survives `python -O`.
if self._block_size != self._kv_cache.shape[1]:
# Views are [num_blocks, num_heads, block_size, head_size], matching what
# extract_from_kv_cache() indexes.
if self._block_size != self._kv_cache.shape[2]:
raise ValueError(
f"Hidden-states block-size mismatch: derived {self._block_size} "
f"but buffer block size is {self._kv_cache.shape[1]}; read slots "
f"but buffer block size is {self._kv_cache.shape[2]}; read slots "
"would be wrong (likely a hybrid block-size resolution bug)."
)
@@ -605,9 +600,9 @@ class ExampleHiddenStatesConnector(KVConnectorBase_V1, SupportsHMA):
"get_required_kvcache_layout should not be called "
"on the abstract base class"
)
# NHD means we have (num_tokens, num_heads)
# HND means we have (num_heads, num_tokens)
# For now, we only support NHD layout since this keeps the
# LBNHC means we have (num_tokens, num_heads)
# LBHNC means we have (num_heads, num_tokens)
# For now, we only support LBNHC layout since this keeps the
# hidden states for each token together in memory.
# HND is primarily used when sharding heads across devices.
return "NHD"
# LBHNC is primarily used when sharding heads across devices.
return "LBNHC"
@@ -541,35 +541,32 @@ class HF3FSKVConnector(KVConnectorBase_V1):
self._dtype = first_cache.dtype
element_size = first_cache.element_size()
if self._use_mla:
assert len(first_cache.shape) == 3, "MLA format should have 3 dimensions"
# MLA format: [num_blocks, block_size, head_size]
num_blocks, block_size, head_size = first_cache.shape
num_heads = 1
else:
# MHA format: [2, num_blocks, block_size, num_heads, head_size]
_, num_blocks, block_size, num_heads, head_size = first_cache.shape
# Standardized per-layer [B, H, N, C] view; MLA is just H == 1 with the
# latent vector as the content dim.
assert len(first_cache.shape) == 4, (
f"expected a [B, H, N, C] KV cache view, got {tuple(first_cache.shape)}"
)
num_blocks, num_heads, block_size, content_dim = first_cache.shape
cache_strides = first_cache.stride()
assert all(
cache.shape == first_cache.shape and cache.stride() == cache_strides
for cache in self._kv_caches.values()
), "HF3FS requires uniform KV cache shapes and strides."
self._local_total_tokens = num_blocks * block_size
self._local_block_size = block_size
self._num_heads = num_heads
self._content_dim = content_dim
self._kv_cache_strides = cache_strides
if self._use_mla:
layer_block_size = block_size * head_size * element_size
self._bytes_per_page = layer_block_size * len(self._kv_caches)
self._shape_per_page = [
len(self._kv_caches),
block_size,
head_size,
]
else:
layer_block_size = 2 * block_size * num_heads * head_size * element_size
self._bytes_per_page = layer_block_size * len(self._kv_caches)
self._shape_per_page = [
len(self._kv_caches),
2,
block_size,
num_heads * head_size,
]
layer_block_size = num_heads * block_size * content_dim * element_size
self._bytes_per_page = layer_block_size * len(self._kv_caches)
self._shape_per_page = [
len(self._kv_caches),
num_heads,
block_size,
content_dim,
]
self._kvcache_ptrs = torch.tensor(
[cache.data_ptr() for cache in self._kv_caches.values()],
@@ -993,7 +990,10 @@ class HF3FSKVConnector(KVConnectorBase_V1):
self._local_total_tokens,
buffer_tensor,
token_indices,
is_mla=self._use_mla,
self._local_block_size,
self._num_heads,
self._content_dim,
self._kv_cache_strides,
)
else:
gather_scatter_helper.scatter_kv_caches(
@@ -1001,7 +1001,10 @@ class HF3FSKVConnector(KVConnectorBase_V1):
self._local_total_tokens,
buffer_tensor,
token_indices,
is_mla=self._use_mla,
self._local_block_size,
self._num_heads,
self._content_dim,
self._kv_cache_strides,
)
def _compute_prefix_hash(
@@ -12,10 +12,15 @@ def kv_cache_scatter_kernel(
source_ptr,
token_indices_ptr,
num_tokens_in_block,
hidden_size,
total_token_in_kvcache,
num_layers,
is_mla,
tokens_per_block,
block_stride,
head_stride,
token_stride,
content_stride,
num_heads: tl.constexpr,
content_size: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
layer_idx = tl.program_id(0)
@@ -30,39 +35,25 @@ def kv_cache_scatter_kernel(
if token_idx >= total_token_in_kvcache:
return
if is_mla:
# MLA format: source [num_layers, num_tokens_in_block, hidden_size]
# MLA format: target [total_token_in_kvcache, hidden_size] (per layer)
source_offset = (layer_idx * num_tokens_in_block + token_pos) * hidden_size
target_offset = token_idx * hidden_size
for i in range(0, hidden_size, BLOCK_SIZE):
offset = i + tl.arange(0, BLOCK_SIZE)
mask = offset < hidden_size
val = tl.load(source_ptr + source_offset + offset, mask=mask)
tl.store(kv_cache_ptr + target_offset + offset, val, mask=mask)
else:
# MHA format: source [num_layers, 2, num_tokens_in_block, hidden_size]
# MHA format: target [2, total_token_in_kvcache, hidden_size]
source_offset_k = (
layer_idx * num_tokens_in_block * 2 + token_pos
) * hidden_size
source_offset_v = (
layer_idx * num_tokens_in_block * 2 + num_tokens_in_block + token_pos
) * hidden_size
target_offset_k = token_idx * hidden_size
target_offset_v = (total_token_in_kvcache + token_idx) * hidden_size
for i in range(0, hidden_size, BLOCK_SIZE):
offset = i + tl.arange(0, BLOCK_SIZE)
mask = offset < hidden_size
val_k = tl.load(source_ptr + source_offset_k + offset, mask=mask)
val_v = tl.load(source_ptr + source_offset_v + offset, mask=mask)
tl.store(kv_cache_ptr + target_offset_k + offset, val_k, mask=mask)
tl.store(kv_cache_ptr + target_offset_v + offset, val_v, mask=mask)
block_idx = token_idx // tokens_per_block
state_idx = token_idx % tokens_per_block
hidden_size = num_heads * content_size
for i in range(0, hidden_size, BLOCK_SIZE):
offset = i + tl.arange(0, BLOCK_SIZE)
mask = offset < hidden_size
head_idx = offset // content_size
content_idx = offset % content_size
source_offset = (
(layer_idx * num_heads + head_idx) * num_tokens_in_block + token_pos
) * content_size + content_idx
target_offset = (
block_idx * block_stride
+ head_idx * head_stride
+ state_idx * token_stride
+ content_idx * content_stride
)
value = tl.load(source_ptr + source_offset, mask=mask)
tl.store(kv_cache_ptr + target_offset, value, mask=mask)
@triton.jit
@@ -71,10 +62,15 @@ def kv_cache_gather_kernel(
dst_ptr,
token_indices_ptr,
num_tokens_in_block,
hidden_size,
total_token_in_kvcache,
num_layers,
is_mla,
tokens_per_block,
block_stride,
head_stride,
token_stride,
content_stride,
num_heads: tl.constexpr,
content_size: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
layer_idx = tl.program_id(0)
@@ -89,37 +85,25 @@ def kv_cache_gather_kernel(
if token_idx >= total_token_in_kvcache:
return
if is_mla:
# MLA format: source [total_token_in_kvcache, hidden_size] (per layer)
# MLA format: dst [num_layers, num_tokens_in_block, hidden_size]
kvcache_offset = token_idx * hidden_size
dst_offset = (layer_idx * num_tokens_in_block + token_pos) * hidden_size
for i in range(0, hidden_size, BLOCK_SIZE):
offset = i + tl.arange(0, BLOCK_SIZE)
mask = offset < hidden_size
val = tl.load(kv_cache_ptr + kvcache_offset + offset, mask=mask)
tl.store(dst_ptr + dst_offset + offset, val, mask=mask)
else:
# MHA format: source [2, total_token_in_kvcache, hidden_size]
# MHA format: dst [num_layers, 2, num_tokens_in_block, hidden_size]
dst_offset_k = (layer_idx * num_tokens_in_block * 2 + token_pos) * hidden_size
dst_offset_v = (
layer_idx * num_tokens_in_block * 2 + num_tokens_in_block + token_pos
) * hidden_size
kvcache_offset_k = token_idx * hidden_size
kvcache_offset_v = (total_token_in_kvcache + token_idx) * hidden_size
for i in range(0, hidden_size, BLOCK_SIZE):
offset = i + tl.arange(0, BLOCK_SIZE)
mask = offset < hidden_size
val_k = tl.load(kv_cache_ptr + kvcache_offset_k + offset, mask=mask)
val_v = tl.load(kv_cache_ptr + kvcache_offset_v + offset, mask=mask)
tl.store(dst_ptr + dst_offset_k + offset, val_k, mask=mask)
tl.store(dst_ptr + dst_offset_v + offset, val_v, mask=mask)
block_idx = token_idx // tokens_per_block
state_idx = token_idx % tokens_per_block
hidden_size = num_heads * content_size
for i in range(0, hidden_size, BLOCK_SIZE):
offset = i + tl.arange(0, BLOCK_SIZE)
mask = offset < hidden_size
head_idx = offset // content_size
content_idx = offset % content_size
kvcache_offset = (
block_idx * block_stride
+ head_idx * head_stride
+ state_idx * token_stride
+ content_idx * content_stride
)
dst_offset = (
(layer_idx * num_heads + head_idx) * num_tokens_in_block + token_pos
) * content_size + content_idx
value = tl.load(kv_cache_ptr + kvcache_offset, mask=mask)
tl.store(dst_ptr + dst_offset, value, mask=mask)
def scatter_kv_caches(
@@ -127,34 +111,33 @@ def scatter_kv_caches(
total_token_in_kvcache: int,
src_tensor: torch.Tensor,
token_indices: list[int],
is_mla: bool = False,
tokens_per_block: int,
num_heads: int,
content_size: int,
kv_cache_strides: tuple[int, ...],
) -> None:
"""Scatter KV cache data from source tensor to KV cache storage.
Args:
kv_caches_ptrs: Tensor of KV cache pointers (one per layer)
total_token_in_kvcache: Total number of tokens in KV cache
src_tensor: Source tensor containing data to scatter
- MHA format: [num_layers, 2, num_tokens_in_block, hidden_size]
- MLA format: [num_layers, num_tokens_in_block, hidden_size]
src_tensor: Source ``[L, H, N, C]`` tensor containing data to scatter
token_indices: List of token positions to update
is_mla: Whether using MLA model format
tokens_per_block: Number of stored states in each cache block
num_heads: Size of the H axis
content_size: Size of the C axis
kv_cache_strides: Element strides of each ``[B, H, N, C]`` layer view
"""
num_layers = len(kv_caches_ptrs)
num_tokens_in_block = len(token_indices)
if is_mla:
# MLA: src_tensor is [num_layers, num_tokens_in_block, hidden_size]
assert len(src_tensor.shape) == 3, (
f"MLA src_tensor should be 3D, got {src_tensor.shape}"
)
hidden_size = src_tensor.shape[2]
else:
# MHA: src_tensor is [num_layers, 2, num_tokens_in_block, hidden_size]
assert len(src_tensor.shape) == 4, (
f"MHA src_tensor should be 4D, got {src_tensor.shape}"
)
hidden_size = src_tensor.shape[3]
assert src_tensor.shape == (
num_layers,
num_heads,
num_tokens_in_block,
content_size,
)
assert len(kv_cache_strides) == 4
device = src_tensor.device
token_indices_tensor = torch.tensor(
@@ -169,10 +152,12 @@ def scatter_kv_caches(
src_tensor,
token_indices_tensor,
num_tokens_in_block,
hidden_size,
total_token_in_kvcache,
num_layers,
is_mla,
tokens_per_block,
*kv_cache_strides,
num_heads=num_heads,
content_size=content_size,
BLOCK_SIZE=BLOCK_SIZE,
)
@@ -182,49 +167,33 @@ def gather_kv_caches(
total_token_in_kvcache: int,
dst_tensor: torch.Tensor,
token_indices: list[int],
is_mla: bool = False,
tokens_per_block: int,
num_heads: int,
content_size: int,
kv_cache_strides: tuple[int, ...],
) -> None:
"""Gather KV cache data from KV cache storage to destination tensor.
Args:
kv_caches_ptrs: Tensor of KV cache pointers (one per layer)
total_token_in_kvcache: Total number of tokens in KV cache
dst_tensor: Destination tensor to store gathered data
- MHA format: [num_layers, 2, num_tokens_in_block, hidden_size]
- MLA format: [num_layers, num_tokens_in_block, hidden_size]
dst_tensor: Destination ``[L, H, N, C]`` tensor
token_indices: List of token positions to gather
is_mla: Whether using MLA model format
tokens_per_block: Number of stored states in each cache block
num_heads: Size of the H axis
content_size: Size of the C axis
kv_cache_strides: Element strides of each ``[B, H, N, C]`` layer view
"""
num_layers = kv_caches_ptrs.shape[0]
num_tokens_in_block = len(token_indices)
if is_mla:
# MLA: dst_tensor is [num_layers, num_tokens_in_block, hidden_size]
assert len(dst_tensor.shape) == 3, (
f"MLA dst_tensor should be 3D, got {dst_tensor.shape}"
)
assert dst_tensor.shape[0] == num_layers, (
f"Layer count mismatch: {dst_tensor.shape[0]} vs {num_layers}"
)
assert dst_tensor.shape[1] == num_tokens_in_block, (
f"Token count mismatch: {dst_tensor.shape[1]} vs {num_tokens_in_block}"
)
hidden_size = dst_tensor.shape[2]
else:
# MHA: dst_tensor is [num_layers, 2, num_tokens_in_block, hidden_size]
assert len(dst_tensor.shape) == 4, (
f"MHA dst_tensor should be 4D, got {dst_tensor.shape}"
)
assert dst_tensor.shape[0] == num_layers, (
f"Layer count mismatch: {dst_tensor.shape[0]} vs {num_layers}"
)
assert dst_tensor.shape[1] == 2, (
f"MHA should have 2 (K,V) components, got {dst_tensor.shape[1]}"
)
assert dst_tensor.shape[2] == num_tokens_in_block, (
f"Token count mismatch: {dst_tensor.shape[2]} vs {num_tokens_in_block}"
)
hidden_size = dst_tensor.shape[3]
assert dst_tensor.shape == (
num_layers,
num_heads,
num_tokens_in_block,
content_size,
)
assert len(kv_cache_strides) == 4
device = dst_tensor.device
token_indices_tensor = torch.tensor(
@@ -239,10 +208,12 @@ def gather_kv_caches(
dst_tensor,
token_indices_tensor,
num_tokens_in_block,
hidden_size,
total_token_in_kvcache,
num_layers,
is_mla,
tokens_per_block,
*kv_cache_strides,
num_heads=num_heads,
content_size=content_size,
BLOCK_SIZE=BLOCK_SIZE,
)
@@ -49,15 +49,15 @@ from vllm.model_executor.models.utils import extract_layer_index
from vllm.platforms import current_platform
from vllm.utils.math_utils import cdiv
from vllm.utils.network_utils import get_ip, make_zmq_path, make_zmq_socket
from vllm.utils.torch_utils import is_non_overlapping_and_dense
from vllm.v1.attention.backend import AttentionMetadata
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID, get_kv_cache_layout
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import (
AttentionSpec,
FullAttentionSpec,
KVCacheSpec,
MambaSpec,
MLAAttentionSpec,
SlidingWindowMLASpec,
SlidingWindowSpec,
)
from vllm.v1.request import RequestStatus
@@ -122,9 +122,7 @@ def _expand_transfer_regions(
kv_block_lens: list[int],
layer_names: list[str],
layer_indices: list[int],
is_kv_layout_blocks_first: bool,
group_indices: list[int] | None = None,
split_kv_regions: list[bool] | None = None,
) -> list[TransferRegion]:
"""Expand registered KV tensors into the regions transferred by Mooncake."""
assert (
@@ -146,13 +144,6 @@ def _expand_transfer_regions(
"Mooncake transfer regions require matching group metadata lengths, "
f"got group_indices={len(group_indices)}, layer_names={len(layer_names)}."
)
if split_kv_regions is None:
split_kv_regions = [is_kv_layout_blocks_first] * len(layer_names)
assert len(split_kv_regions) == len(layer_names), (
"Mooncake transfer regions require matching split metadata, "
f"got split_kv_regions={len(split_kv_regions)}, "
f"layer_names={len(layer_names)}."
)
regions: list[TransferRegion] = []
for (
base_addr,
@@ -161,7 +152,6 @@ def _expand_transfer_regions(
layer_name,
layer_index,
group_index,
split_kv_region,
) in zip(
base_addrs,
block_lens,
@@ -169,7 +159,6 @@ def _expand_transfer_regions(
layer_names,
layer_indices,
group_indices,
split_kv_regions,
):
regions.append(
TransferRegion(
@@ -181,17 +170,6 @@ def _expand_transfer_regions(
group_index=group_index,
)
)
if split_kv_region:
regions.append(
TransferRegion(
layer_name=layer_name,
layer_index=layer_index,
base_addr=base_addr + kv_block_len,
block_len=block_len,
kv_block_len=kv_block_len,
group_index=group_index,
)
)
return regions
@@ -506,10 +484,10 @@ class MooncakeConnector(KVConnectorBase_V1, SupportsHMA):
if vllm_config.model_config.use_mla:
return None
logger.info_once(
"MooncakeConnector setting KV cache layout to HND for "
"MooncakeConnector setting KV cache layout to LBHNC for "
"heterogeneous TP-safe KV transfer."
)
return "HND"
return "LBHNC"
############################################################
# Scheduler Side Methods
@@ -1023,12 +1001,10 @@ class MooncakeConnectorWorker:
self._sync_block_size_with_kernel()
self.attn_backends = get_current_attn_backends(vllm_config)
self.kv_cache_layout = get_kv_cache_layout()
logger.debug(
"Detected attention backends %s",
[backend.get_name() for backend in self.attn_backends],
)
logger.debug("Detected kv cache layout %s", self.kv_cache_layout)
self._tp_size: dict[EngineId, int] = {self.engine_id: self.tp_size}
self._layer_specs: dict[str, KVCacheSpec] = {}
@@ -1665,7 +1641,7 @@ class MooncakeConnectorWorker:
self.registered_layer_indices = []
self.registered_group_indices = []
for layer_name, cache_or_caches in kv_caches.items():
for layer_name, cache in kv_caches.items():
layer_index = extract_layer_index(layer_name)
layer_spec = self._layer_specs.get(layer_name)
if layer_spec is None:
@@ -1674,34 +1650,30 @@ class MooncakeConnectorWorker:
layer_name,
)
continue
if isinstance(layer_spec, MambaSpec):
conv, _ = cache_or_caches
cache_list = [conv]
# One raw page tensor per layer; for Mamba that page holds all the
# recurrent states, unpacked only when binding the cache for execution.
self._log_debug_cache_registration(layer_name, cache)
block_is_contiguous = is_non_overlapping_and_dense(cache[0])
if not block_is_contiguous:
# Non-block-compact layouts scatter a block across per-head
# regions; each region's blocks are contiguous.
region_caches = [cache[:, head] for head in range(cache.shape[1])]
assert all(
is_non_overlapping_and_dense(region[0]) for region in region_caches
)
else:
# K and V are packed into one blocks-first tensor per layer,
# so each layer registers as a single region.
cache_list = [cache_or_caches]
region_caches = [cache]
logger.debug(
"registering layer %s with %d cache tensor(s)",
layer_name,
len(cache_list),
)
for cache in cache_list:
self._log_debug_cache_registration(layer_name, cache)
base_addr = cache.data_ptr()
block_len = cache.stride(0) * cache.element_size()
for region_cache in region_caches:
base_addr = region_cache.data_ptr()
block_len = region_cache.stride(0) * region_cache.element_size()
region_base_addresses.append(base_addr)
if isinstance(layer_spec, (MLAAttentionSpec, SlidingWindowMLASpec)):
kv_block_len = layer_spec.page_size_bytes
elif self.transfer_topo.virtually_split_kv_in_blocks and not isinstance(
layer_spec, MambaSpec
):
kv_block_len = block_len // 2
else:
kv_block_len = block_len
kv_block_len = (
layer_spec.page_size_bytes
if isinstance(layer_spec, AttentionSpec) and block_is_contiguous
else block_len
)
self.block_len_per_layer.append(block_len)
self.kv_block_len_per_layer.append(kv_block_len)
self.registered_layer_names.append(layer_name)
@@ -1709,12 +1681,12 @@ class MooncakeConnectorWorker:
self.registered_group_indices.append(
self._layer_group_indices[layer_name]
)
storage = cache.untyped_storage()
storage_addr = storage.data_ptr()
if storage_addr not in seen_storage_ptrs:
seen_storage_ptrs.add(storage_addr)
kv_data_ptrs.append(storage_addr)
kv_data_lens.append(storage.nbytes())
storage = cache.untyped_storage()
storage_addr = storage.data_ptr()
if storage_addr not in seen_storage_ptrs:
seen_storage_ptrs.add(storage_addr)
kv_data_ptrs.append(storage_addr)
kv_data_lens.append(storage.nbytes())
self.kv_caches_base_addr = region_base_addresses
self.seen_base_addresses = kv_data_ptrs
@@ -2055,24 +2027,13 @@ class MooncakeConnectorWorker:
self._layer_group_indices.get(layer_name, 0)
for layer_name in layer_names
]
split_kv_regions = None
if self.transfer_topo.virtually_split_kv_in_blocks:
split_kv_regions = [
not isinstance(
self._layer_specs[layer_name],
(MambaSpec, MLAAttentionSpec, SlidingWindowMLASpec),
)
for layer_name in layer_names
]
return _expand_transfer_regions(
base_addrs=base_addrs,
block_lens=block_lens,
kv_block_lens=kv_block_lens,
layer_names=layer_names,
layer_indices=layer_indices,
is_kv_layout_blocks_first=self.transfer_topo.virtually_split_kv_in_blocks,
group_indices=group_indices,
split_kv_regions=split_kv_regions,
)
def _get_sender_transfer_plan(
@@ -89,14 +89,6 @@ class MooncakeStoreKVEvents(KVConnectorKVEvents):
class MooncakeStoreConnector(KVConnectorBase_V1, SupportsHMA):
"""KV connector using MooncakeDistributedStore as shared KV pool."""
@property
def prefer_cross_layer_blocks(self) -> bool:
extra_config = self._kv_transfer_config.kv_connector_extra_config
return (
str(extra_config.get("enable_cross_layers_blocks", "False")).lower()
== "true"
)
@staticmethod
def _validate_kv_cache_config(
vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
@@ -290,16 +282,6 @@ class MooncakeStoreConnector(KVConnectorBase_V1, SupportsHMA):
assert self.connector_worker is not None
self.connector_worker.register_kv_caches(kv_caches)
def register_cross_layers_kv_cache(
self, kv_cache: torch.Tensor, attn_backend: type
):
assert self.connector_worker is not None
assert (
self._kv_cache_config is not None
and len(self._kv_cache_config.kv_cache_groups) == 1
), "Cross-layer KV cache does not supported with hybrid models"
self.connector_worker.register_cross_layers_kv_caches(kv_cache)
def start_load_kv(self, forward_context: ForwardContext, **kwargs: Any) -> None:
# No-op: loads are issued in get_finished() for compute overlap.
pass
@@ -58,6 +58,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.protocol import
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv
from vllm.utils.network_utils import get_ip, make_zmq_socket
from vllm.utils.torch_utils import is_non_overlapping_and_dense
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from vllm.v1.core.kv_cache_utils import (
BlockHash,
@@ -72,6 +73,7 @@ from vllm.v1.kv_cache_interface import (
MLAAttentionSpec,
SlidingWindowMLASpec,
UniformTypeKVCacheSpecs,
group_kernel_blocks,
)
from .metrics import MooncakeStoreConnectorStats
@@ -1617,18 +1619,9 @@ class MooncakeStoreWorker:
for g_idx, db in enumerate(self.token_dbs)
)
def register_cross_layers_kv_caches(self, kv_cache: torch.Tensor) -> None:
"""Register a cross-layers KV cache tensor.
Wraps the unified tensor in a single-entry dict so that the
existing stride-based logic in register_kv_caches() produces
the correct single-segment result (block_len = page_size * num_layers).
"""
self.register_kv_caches({"__cross_layer__": kv_cache})
def register_kv_caches(
self,
kv_caches: dict[str, torch.Tensor | list[torch.Tensor]],
kv_caches: dict[str, torch.Tensor],
) -> None:
"""Register KV cache tensors and start transfer threads."""
if self._capacity_only:
@@ -1637,58 +1630,62 @@ class MooncakeStoreWorker:
logger.warning("No KV caches to offload.")
return
# Resolve each entry to a representative tensor for storage
# deduplication. For attention layers the value is already a tensor;
# for Mamba layers it is a list of tensors that all share the same
# underlying raw storage, so we take the first one.
def _repr_tensor(v: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
assert isinstance(v, torch.Tensor | list)
return v if isinstance(v, torch.Tensor) else v[0]
assert self.cache_config.num_gpu_blocks is not None
self.num_blocks = self.cache_config.num_gpu_blocks
seen_ptrs: set[int] = set()
seen_storage_ptrs: set[int] = set()
seen_region_ptrs: set[int] = set()
addrs: list[int] = []
block_lens: list[int] = []
for value in kv_caches.values():
cache = _repr_tensor(value)
for cache in kv_caches.values():
cache = group_kernel_blocks(cache, self.num_blocks)
cache_storage = cache.untyped_storage()
base_addr = cache_storage.data_ptr()
if base_addr in seen_ptrs:
continue
seen_ptrs.add(base_addr)
region_len = cache_storage.nbytes()
ret = self.store.register_buffer(base_addr, region_len)
if ret != 0:
logger.error(
"register_buffer failed for addr %#x len %d: %d",
base_addr,
region_len,
ret,
)
if base_addr not in seen_storage_ptrs:
seen_storage_ptrs.add(base_addr)
ret = self.store.register_buffer(base_addr, region_len)
if ret != 0:
logger.error(
"register_buffer failed for addr %#x len %d: %d",
base_addr,
region_len,
ret,
)
# Detect layout via stride: a dim whose byte-stride exceeds
# page_size_bytes is an outer segment dim (e.g. the K/V dim of
# FlashAttn's (2, num_blocks, ...)). FlashInfer/MLA's blocks-
# outermost layout has no such dim and yields a single segment.
el = cache.element_size()
page_size_bytes = region_len // self.num_blocks
outer_dims = [
d for d in range(cache.ndim) if cache.stride(d) * el > page_size_bytes
]
if not outer_dims:
# Blocks-first layout (FlashInfer / MLA): one segment.
if not is_non_overlapping_and_dense(cache[0]):
# A block is scattered across per-head regions; each region's
# blocks are contiguous.
for head_idx in range(cache.shape[1]):
head_cache = cache[:, head_idx]
assert is_non_overlapping_and_dense(head_cache[0])
region_addr = head_cache.data_ptr()
if region_addr in seen_region_ptrs:
continue
seen_region_ptrs.add(region_addr)
addrs.append(region_addr)
block_lens.append(head_cache.stride(0) * head_cache.element_size())
elif cache.stride(0) * cache.element_size() * self.num_blocks == region_len:
# The block stride spans the whole per-block window
# (block-outermost and packed layouts, and single-layer
# tensors), which may hold other layers' pages at higher
# offsets. Register the storage once as one whole-window
# region; per-layer regions would copy overlapping windows and
# run past the storage for offset layers.
if base_addr in seen_region_ptrs:
continue
seen_region_ptrs.add(base_addr)
addrs.append(base_addr)
block_lens.append(page_size_bytes)
block_lens.append(region_len // self.num_blocks)
else:
# K/V-first layout (FlashAttn / ROCm): split segments.
seg_stride = cache.stride(outer_dims[0]) * el
for idx in range(cache.shape[outer_dims[0]]):
addrs.append(base_addr + idx * seg_stride)
block_lens.append(seg_stride // self.num_blocks)
region_addr = cache.data_ptr()
if region_addr in seen_region_ptrs:
continue
seen_region_ptrs.add(region_addr)
addrs.append(region_addr)
block_lens.append(cache.stride(0) * cache.element_size())
logger.info(
"Registered KV caches: num_groups=%d, num_segments=%d, num_blocks=%d",
@@ -57,11 +57,6 @@ def is_mla_cache_layer(
return isinstance(spec, (MLAAttentionSpec, SlidingWindowMLASpec))
def _content_packed_dim(spec: AttentionSpec) -> int:
head_size_v = getattr(spec, "head_size_v", spec.head_size)
return spec.head_size + head_size_v
def _spec_dim_matches(value: int, expected: int | None) -> bool:
return expected is None or value == expected
@@ -110,23 +105,6 @@ def get_layer_transfer_geometry(
spec = layer_to_spec[layer_name]
is_mla_cache = is_mla_cache_layer(layer_to_spec, layer_name)
if is_mla_cache and len(shape) == 3:
num_blocks, block_size, latent_dim = shape
slot_size_bytes = latent_dim * element_size
block_len = block_size * slot_size_bytes
return LayerTransferGeometry(
num_blocks=num_blocks,
block_size=block_size,
block_len=block_len,
slot_size_bytes=slot_size_bytes,
block_stride=stride[0],
local_kv_stride=None,
remote_kv_stride=None,
transfers_per_block=1,
regions_per_block=1,
split_kv_regions=False,
)
if not is_mla_cache and len(shape) == 5 and shape[0] == 2:
_, num_blocks = shape[:2]
kernel_blocks_per_block = 1
@@ -230,19 +208,19 @@ def get_layer_transfer_geometry(
)
if (
not is_mla_cache
and isinstance(spec, AttentionSpec)
isinstance(spec, AttentionSpec)
and len(shape) == 4
and shape[1] == spec.num_kv_heads
and shape[2] == spec.block_size
and shape[3] == _content_packed_dim(spec)
and shape[1] == spec.num_heads
and shape[2] == spec.num_states
and shape[3] * element_size == spec.state_content_size_bytes
):
num_blocks, num_kv_heads, block_size, packed_dim = shape
slot_size_bytes = num_kv_heads * packed_dim * element_size
block_len = block_size * slot_size_bytes
# Standardized per-layer [B, H, N, C] view (MLA is just H == 1).
num_blocks, num_heads, num_states, content_dim = shape
slot_size_bytes = num_heads * content_dim * element_size
block_len = num_states * slot_size_bytes
return LayerTransferGeometry(
num_blocks=num_blocks,
block_size=block_size,
block_size=spec.block_size,
block_len=block_len,
slot_size_bytes=slot_size_bytes,
block_stride=stride[0],
@@ -267,6 +245,16 @@ def iter_layer_registration_regions(
) -> list[tuple[torch.Tensor, int]]:
geometry = get_layer_transfer_geometry(layer_name, kv_cache, layer_to_spec)
region_len = geometry.num_blocks * geometry.regions_per_block * geometry.block_len
if geometry.regions_per_block == 1:
# With padded or interleaved pages the block stride exceeds the
# meaningful block_len; register the strided span. The span ends with
# the last block's meaningful bytes, not a whole stride, so it never
# runs past the backing allocation of a strided layer view.
block_stride_bytes = geometry.block_stride * kv_cache.element_size()
region_len = max(
region_len,
(geometry.num_blocks - 1) * block_stride_bytes + geometry.block_len,
)
if geometry.split_kv_regions:
return [(cache, region_len) for cache in kv_cache]
return [(kv_cache, region_len)]
@@ -27,7 +27,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
PromMetricT,
)
from vllm.logger import init_logger
from vllm.v1.attention.backend import AttentionBackend, AttentionMetadata
from vllm.v1.attention.backend import AttentionMetadata
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.outputs import KVConnectorOutput
@@ -209,12 +209,6 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
c.supports_divergent_local_hybrid_hits for c in self._connectors
)
@property
def prefer_cross_layer_blocks(self) -> bool:
if not self._connectors:
return False
return all(c.prefer_cross_layer_blocks for c in self._connectors)
@property
def requires_kv_delivery(self) -> bool:
return any(c.requires_kv_delivery for c in self._connectors)
@@ -245,13 +239,6 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
)
return ret
def register_cross_layers_kv_cache(
self, kv_cache: torch.Tensor, attn_backend: type[AttentionBackend]
):
# Register on all connectors
for c in self._connectors:
c.register_cross_layers_kv_cache(kv_cache, attn_backend)
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
for c in self._connectors:
c.register_kv_caches(kv_caches)
@@ -71,9 +71,9 @@ from vllm.platforms import current_platform
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.network_utils import make_zmq_path
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.attention.backends.utils import get_kv_cache_layout
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheLayout,
MambaSpec,
MLAAttentionSpec,
SlidingWindowMLASpec,
@@ -89,6 +89,13 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
def _share_storage_and_block_stride(caches: list[torch.Tensor]) -> bool:
"""Return whether all views share storage and a block stride."""
block_strides = {cache.stride(0) * cache.element_size() for cache in caches}
storage_ptrs = {cache.untyped_storage().data_ptr() for cache in caches}
return len(block_strides) == len(storage_ptrs) == 1
class NixlBaseConnectorWorker:
"""Base implementation of Worker side methods shared by pull and push."""
@@ -302,7 +309,6 @@ class NixlBaseConnectorWorker:
for group in kv_cache_config.kv_cache_groups
for layer in group.layer_names
}
self.hma_group_size = len(kv_cache_config.kv_cache_tensors)
# ---- Model state (derived from model config) ----
mamba_ssm_size = (0, 0)
@@ -523,7 +529,9 @@ class NixlBaseConnectorWorker:
self.attn_backends = get_current_attn_backends(vllm_config)
self.backend_name = self.attn_backends[0].get_name()
self.kv_cache_layout = get_kv_cache_layout()
self.kv_cache_layout = (
vllm_config.cache_config.get_resolved_kv_cache_layout().name
)
self.host_buffer_kv_cache_layout = self.kv_cache_layout
logger.info(
"Detected attention backend(s) %s",
@@ -558,6 +566,11 @@ class NixlBaseConnectorWorker:
# This is not used for SSM layers, which use the counterpart `mamba_ssm_size`.
self.block_len_per_layer = list[int]()
# Per-region block stride in bytes. Taken from the registered tensor's
# stride(0) so it stays correct under layouts that interleave layers
# within a block (BLHNC/BHLNC), where stride > block_len.
self.block_stride_per_layer = list[int]()
# Per-engine TP mappings. Generated during handshake.
self.tp_mappings: dict[EngineId, TPMapping] = {}
@@ -788,16 +801,16 @@ class NixlBaseConnectorWorker:
if not self.use_mla:
assert kv_cache.ndim == 4
if self.kv_cache_layout == "NHD":
if self.kv_cache_layout == "LBNHC":
if self.kv_transfer_config.enable_permute_local_kv:
logger.info_once(
"'enable_permute_local_kv' flag is enabled while "
"device KV Layout is NHD. Init host buffer with"
" HND to better support Decode/Prefill TP_ratio > 1."
"device KV Layout is LBNHC. Init host buffer with"
" LBHNC to better support Decode/Prefill TP_ratio > 1."
)
# Since NHD will not support Decode/Prefill TP_ratio > 1,
# Since LBNHC will not support Decode/Prefill TP_ratio > 1,
# we can leverage host_buffer for permute.
self.host_buffer_kv_cache_layout = "HND"
self.host_buffer_kv_cache_layout = "LBHNC"
else:
# Packed KV layout is logical (B, H, N, 2*D). Allocate
# (B, N, H, 2*D) and view it as logical (B, H, N, 2*D)
@@ -969,120 +982,9 @@ class NixlBaseConnectorWorker:
fut.add_done_callback(request_ready)
def register_cross_layers_kv_caches(self, kv_cache: torch.Tensor) -> None:
"""Register a cross-layers KV cache tensor with NIXL.
`use_uniform_kv_cache()` guarantees a single KV cache group whose
layers all share the same `AttentionSpec`, so any layer name from
`_layer_specs` yields the correct per-layer spec for `page_size_bytes`.
"""
first_layer = next(iter(self._layer_specs))
# Forwarding a real layer name rather than a synthetic key
self.register_kv_caches({first_layer: kv_cache})
def _register_packed_kv_cache(
self,
storage: torch.UntypedStorage,
) -> None:
"""Register a packed KV cache as a single NIXL region.
The packed allocation interleaves all layers per block, so each
block_stride-byte chunk is one logical block. We register 1
NIXL region and create 1 descriptor per block.
"""
self.transfer_topo = TransferTopology(
tp_rank=self.tp_rank,
tp_size=self.world_size,
block_size=self.block_size,
engine_id=self.engine_id,
is_mla=self.use_mla,
total_num_kv_heads=self.model_config.get_total_num_kv_heads(),
attn_backends=self.attn_backends,
tensor_shape=None,
is_mamba=self._has_mamba,
)
self.compat_hash = compute_nixl_compatibility_hash(
self.vllm_config,
self.backend_name,
self.transfer_topo.cross_layers_blocks,
transfer_mode=self._TRANSFER_MODE,
)
total_size = storage.nbytes()
block_stride = total_size // self.num_blocks
base_addr = storage.data_ptr()
device_id = storage.device.index
assert device_id is not None
logger.info(
"Registering packed KV cache: total_size=%s, block_stride=%s, "
"num_blocks=%s, num_regions=1",
total_size,
block_stride,
self.num_blocks,
)
self.device_id = device_id
caches_data = [(base_addr, total_size, self.device_id, "")]
self.block_len_per_layer = [block_stride]
self.num_regions = 1
self.num_descs = self.num_blocks
self.kv_caches_base_addr[self.engine_id][self.tp_rank] = [base_addr]
descs = self.nixl_wrapper.get_reg_descs(caches_data, self.nixl_memory_type)
self.nixl_wrapper.register_memory(descs, backends=self.nixl_backends)
self._registered_descs.append(descs)
self.dst_num_blocks[self.engine_id] = self.num_blocks
self.src_xfer_handles_by_block_size[self.block_size], (self.src_blocks_data) = (
self.register_local_xfer_handler(self.block_size)
)
agent_metadata = NixlAgentMetadata(
engine_id=self.engine_id,
agent_metadata=self.nixl_wrapper.get_agent_metadata(),
device_id=self.device_id,
kv_caches_base_addr=(
self.kv_caches_base_addr[self.engine_id][self.tp_rank]
),
num_blocks=self.num_blocks,
block_lens=self.block_len_per_layer,
kv_cache_layout=self.kv_cache_layout,
block_size=self.block_size,
ssm_sizes=self._mamba_ssm_size,
attn_backend_name=self.backend_name,
physical_blocks_per_logical_kv_block=(
self._physical_blocks_per_logical_kv_block
),
dcp_size=self.dcp_size,
pcp_size=self.pcp_size,
)
assert self.compat_hash is not None
encoder = msgspec.msgpack.Encoder()
self.xfer_handshake_metadata = NixlHandshakePayload(
compatibility_hash=self.compat_hash,
agent_metadata_bytes=encoder.encode(agent_metadata),
)
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
"""Register the KV Cache data in nixl."""
# Detect packed allocation: all tensors are strided views into the
# same backing storage (different data_ptr but same storage).
# This happens with DSv4-style contiguous per-block packing.
if len(kv_caches) > 1 and not self._has_mamba:
storage = next(iter(kv_caches.values())).untyped_storage()
storage_ptrs = {
cache.untyped_storage().data_ptr() for cache in kv_caches.values()
}
data_ptrs = {cache.data_ptr() for cache in kv_caches.values()}
if len(storage_ptrs) == 1 and len(data_ptrs) > 1:
self._register_packed_kv_cache(storage)
self.device_kv_caches = kv_caches
return
self.transfer_topo = TransferTopology(
tp_rank=self.tp_rank,
tp_size=self.world_size,
@@ -1100,7 +1002,6 @@ class NixlBaseConnectorWorker:
self.compat_hash = compute_nixl_compatibility_hash(
self.vllm_config,
self.backend_name,
self.transfer_topo.cross_layers_blocks,
transfer_mode=self._TRANSFER_MODE,
)
@@ -1127,14 +1028,14 @@ class NixlBaseConnectorWorker:
)
caches_data = []
# With hybrid allocator, layers can share a kv cache tensor
seen_storage_addresses: set[int] = set()
seen_base_addresses: list[int] = []
packed_storage = _share_storage_and_block_stride(list(xfer_buffers.values()))
# K and V are packed into the content dim, so each attention layer is a
# single NIXL region whose block transfers as one unit. Mamba layers instead
# register separate conv/ssm sub-regions (see `_build_mamba_local`).
tensor_size_bytes = None
for layer_name, cache in xfer_buffers.items():
# NOTE (NickLucche) Hybrid SSM mamba/FA physical page_size may differ when
# kernel requires a specific block size. This leads to SSM and FA layers
@@ -1159,55 +1060,98 @@ class NixlBaseConnectorWorker:
else layer_spec.page_size_bytes
// self._physical_blocks_per_logical_kv_block
)
if self.transfer_topo._cross_layers_blocks:
# When cross-layers blocks are used, multiply by number of layers
physical_page_size = physical_page_size * len(
self.kv_cache_config.kv_cache_tensors
)
num_blocks = (
self._logical_num_blocks
if isinstance(layer_spec, MambaSpec)
else self.num_blocks
)
# `page_size` accounts for physical blocks, st KVCache is always
# [`num_blocks` * `page_size`]
curr_tensor_size_bytes = num_blocks * physical_page_size
base_addr = cache.data_ptr()
is_mla_region = isinstance(
layer_spec, (MLAAttentionSpec, SlidingWindowMLASpec)
)
if base_addr in seen_base_addresses:
# NOTE (NickLucche) HMA employs memory pooling to share tensors
# across groups. This results in skipping all tensors but the ones
# pointed to by group0. Also, generally we will have more blocks
# per tensor but fewer regions.
# A shared tensor may back both SSM and attention layers (e.g.
# KDA+MLA in KimiLinear); the region's FA view is MLA whichever
# layer registered it first.
idx = seen_base_addresses.index(base_addr)
self._region_is_mla[idx] |= is_mla_region
logger.debug("Skipping %s because it's already seen", layer_name)
continue
logger.debug(
"Registering layer %s with cache shape: %s", layer_name, cache.shape
)
seen_base_addresses.append(base_addr)
# Only record non-Mamba page sizes.
if isinstance(layer_spec, MambaSpec):
self.block_len_per_layer.append(
physical_page_size // self._physical_blocks_per_logical_kv_block
)
else:
self.block_len_per_layer.append(physical_page_size)
self._region_is_mla.append(is_mla_region)
storage = cache.untyped_storage()
storage_addr = storage.data_ptr()
# Memory registration follows allocations, while transfer regions follow
# logical layers (or contiguous head segments). This keeps strided
# cross-layer views inside their registered allocation.
if storage_addr not in seen_storage_addresses:
seen_storage_addresses.add(storage_addr)
self.device_id = max(cache.get_device(), 0)
caches_data.append((storage_addr, storage.nbytes(), self.device_id, ""))
if not is_mla_region:
if tensor_size_bytes is None:
tensor_size_bytes = curr_tensor_size_bytes
assert tensor_size_bytes == curr_tensor_size_bytes, (
"All non-MLA kv cache tensors must have the same size"
is_mla_region = isinstance(
layer_spec, (MLAAttentionSpec, SlidingWindowMLASpec)
)
if isinstance(layer_spec, MambaSpec):
region_specs = [
(
cache.data_ptr(),
physical_page_size
// self._physical_blocks_per_logical_kv_block,
physical_page_size
// self._physical_blocks_per_logical_kv_block,
)
]
else:
if cache.ndim == 1:
# Flat byte view: HMA tensors shared between layer types carry
# no block dimension, so stride(0) is 1 byte. Blocks abut, so
# the stride is the page size.
block_stride = physical_page_size
else:
block_stride = cache.stride(0) * cache.element_size()
storage_is_block_major = num_blocks * block_stride == storage.nbytes()
# A layer whose [H, N, C] interior is dense addresses its own page
# as one chunk, so it can own a region. When it does not, or when
# every layer is packed into this one storage, the block's whole
# row is the only contiguous unit.
hnc_contiguous = (
cache.ndim == 4
and cache.stride(2) == cache.shape[3]
and cache.stride(1) == cache.shape[2] * cache.shape[3]
)
if storage_is_block_major and (
(packed_storage and is_mla_region) or not hnc_contiguous
):
# TODO(Lucas): handle TP slicing for packed_storage; for now
# restrict to MLA (DSv4) where kv is replicated.
storage_block_len = storage.nbytes() // num_blocks
region_specs = [
(storage_addr, storage_block_len, storage_block_len)
]
elif storage_is_block_major:
region_specs = [
(cache.data_ptr(), physical_page_size, block_stride)
]
else:
segment_bytes = num_blocks * block_stride
assert cache.nbytes % segment_bytes == 0
num_segments = cache.nbytes // segment_bytes
region_block_len = (
block_stride if num_segments > 1 else physical_page_size
)
region_specs = [
(
cache.data_ptr() + segment_idx * segment_bytes,
region_block_len,
block_stride,
)
for segment_idx in range(num_segments)
]
for base_addr, block_len, block_stride in region_specs:
if base_addr in seen_base_addresses:
if is_mla_region:
# Dual-purpose HMA tensor: an MLA layer shares a region
# that a non-MLA layer registered first. MLA is not
# head-sharded, so the region must be flagged MLA.
idx = seen_base_addresses.index(base_addr)
self._region_is_mla[idx] = True
continue
seen_base_addresses.append(base_addr)
self.block_len_per_layer.append(block_len)
self.block_stride_per_layer.append(block_stride)
self._region_is_mla.append(is_mla_region)
# When there's a mismatch between kbs<>bs, we rely on HMA to ensure
# caches are either [NB, PS] or [NB*r, PS/r] where r is bs/kbs.
@@ -1228,11 +1172,6 @@ class NixlBaseConnectorWorker:
f"kv_cache_layout={self.kv_cache_layout}"
)
# Need to make sure the device ID is non-negative for NIXL,
# Torch uses -1 to indicate CPU tensors.
self.device_id = max(cache.get_device(), 0)
caches_data.append((base_addr, curr_tensor_size_bytes, self.device_id, ""))
logger.debug(
"Different block lengths collected: %s", set(self.block_len_per_layer)
)
@@ -1240,10 +1179,11 @@ class NixlBaseConnectorWorker:
len(self.block_len_per_layer)
== len(seen_base_addresses)
== len(self._region_is_mla)
== len(self.block_stride_per_layer)
)
self.kv_caches_base_addr[self.engine_id][self.tp_rank] = seen_base_addresses
self.num_regions = len(caches_data)
self.num_regions = len(seen_base_addresses)
if self.pp_size > 1:
start_layer, end_layer = self.model_config.get_layers_start_end_indices(
@@ -1293,6 +1233,7 @@ class NixlBaseConnectorWorker:
kv_caches_base_addr=self.kv_caches_base_addr[self.engine_id][self.tp_rank],
num_blocks=self.num_blocks,
block_lens=self.block_len_per_layer,
block_strides=self.block_stride_per_layer,
kv_cache_layout=self.kv_cache_layout
if not self.use_host_buffer
else self.host_buffer_kv_cache_layout,
@@ -1431,10 +1372,9 @@ class NixlBaseConnectorWorker:
block_arange = np.arange(num_blocks, dtype=np.uint64)
parts: list[np.ndarray] = []
for i, base_addr in enumerate(base_addresses):
# K/V are packed into the content dim, so the whole block transfers
# as one unit: desc length equals the block stride.
block_len = self.block_len_per_layer[i] // block_size_ratio
addrs = base_addr + block_arange * block_len
block_stride = self.block_stride_per_layer[i] // block_size_ratio
addrs = base_addr + block_arange * block_stride
parts.append(self._stack_descs(addrs, block_len, device_id))
return np.concatenate(parts)
@@ -1476,7 +1416,7 @@ class NixlBaseConnectorWorker:
)
local_block_len = local_block_len // num_reads
page_size = nixl_agent_meta.block_lens[i]
page_size = nixl_agent_meta.block_strides[i]
addrs = base_addr + rank_offset + block_arange * page_size
parts.append(self._stack_descs(addrs, local_block_len, device_id))
return np.concatenate(parts)
@@ -1560,7 +1500,7 @@ class NixlBaseConnectorWorker:
tp_ratio = 4 // 2 = 2
Considering the KV Caches, if P-Worker_i has cache size [2, num_blocksP, kv_heads, block_size, head_dim]
then D-Worker_j has [2, num_blocksD, kv_heads//tp_ratio, block_size, head_dim]. Mind the "HND" layout format.
then D-Worker_j has [2, num_blocksD, kv_heads//tp_ratio, block_size, head_dim]. Mind the "LBHNC" layout format.
Assuming num_blocksD >= num_blocksP, D-Worker0 reads from P-Worker0 by preparing the kv_heads//tp_ratio
first heads from all the slots of all the blocks. D-Worker1 will do the same, but reading the second split
along the kv_heads dimension, and so forth until "tp_ratio" D TP workers have pulled from P-Worker0.
@@ -1600,6 +1540,7 @@ class NixlBaseConnectorWorker:
start:end
]
nixl_agent_meta.block_lens = nixl_agent_meta.block_lens[start:end]
nixl_agent_meta.block_strides = nixl_agent_meta.block_strides[start:end]
### Register remote engine in TransferTopology (idempotent).
assert self.transfer_topo is not None
@@ -1790,10 +1731,10 @@ class NixlBaseConnectorWorker:
if not self.use_mla and nixl_agent_meta.kv_cache_layout != kv_cache_layout:
if (
self.kv_transfer_config.enable_permute_local_kv
and nixl_agent_meta.kv_cache_layout == "HND"
and nixl_agent_meta.kv_cache_layout == "LBHNC"
):
logger.info(
"Remote is HND and local is NHD, enabled additional permute "
"Remote is LBHNC and local is LBNHC, enabled additional permute "
"on local device KV."
)
assert not self._is_hma_required, (
@@ -1823,18 +1764,18 @@ class NixlBaseConnectorWorker:
self.enable_heterogeneous_attn_post_process = True
# Heterogeneous TP requires head-splitting, which only works with
# HND layout. MLA and replicated-KV cases don't split on heads.
# Mamba doesn't support heterogeneous TP.
# block-contiguous layouts (e.g. LBHNC). MLA and replicated-KV cases
# don't split on heads. Mamba doesn't support heterogeneous TP.
if (
abs(tp_ratio) != 1
and not self.use_mla
and not self.transfer_topo.is_kv_replicated(remote_engine_id)
and kv_cache_layout != "HND"
and not KVCacheLayout[kv_cache_layout].is_block_contiguous
and not self.enable_permute_local_kv
):
raise RuntimeError(
"Heterogeneous TP head-dimension splitting requires contiguous heads. "
"Use HND layout on the prefill side."
"Use a block-contiguous layout (e.g. LBHNC) on the prefill side."
)
# Per-region block_len validation enforcing the P/D invariant.
@@ -19,7 +19,6 @@ import torch
from vllm.config import VllmConfig
from vllm.distributed.kv_transfer.kv_connector.utils import (
EngineId,
get_current_attn_backend,
)
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
CopyBlocksOp,
@@ -56,10 +55,8 @@ from vllm.distributed.kv_transfer.kv_connector.v1.nixl.stats import (
)
from vllm.forward_context import ForwardContext
from vllm.logger import init_logger
from vllm.v1.attention.backend import AttentionBackend, AttentionMetadata
from vllm.v1.attention.backends.utils import get_kv_cache_layout
from vllm.v1.attention.backend import AttentionMetadata
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import MambaSpec
from vllm.v1.outputs import KVConnectorOutput
if TYPE_CHECKING:
@@ -83,36 +80,6 @@ class NixlBaseConnector(KVConnectorBase_V1, SupportsHMA):
def supports_divergent_local_hybrid_hits(self) -> bool:
return True
@property
def prefer_cross_layer_blocks(self) -> bool:
if any(
[
isinstance(group.kv_cache_spec, MambaSpec)
for group in self.kv_cache_config.kv_cache_groups
]
):
# Hybrid SSM models do not yet support cross-layer layout
return False
backend = get_current_attn_backend(self._vllm_config)
if backend.get_name() not in (
"FLASH_ATTN",
"FLASHINFER",
"TRITON_ATTN",
):
return False
# For now there is no benefit to run cross layers when backend
# does not support on HND
if get_kv_cache_layout() != "HND":
return False
extra_config = self.kv_transfer_config.kv_connector_extra_config
return (
str(extra_config.get("enable_cross_layers_blocks", "False")).lower()
== "true"
)
def __init__(
self,
vllm_config: VllmConfig,
@@ -179,9 +146,10 @@ class NixlBaseConnector(KVConnectorBase_V1, SupportsHMA):
# which fallback to the default behavior.
return None
logger.info_once(
"NixlConnector setting KV cache layout to HND for better xfer performance."
"NixlConnector setting KV cache layout to LBHNC for "
"better xfer performance."
)
return "HND"
return "LBHNC"
############################################################
# Scheduler Side Methods
@@ -266,12 +234,6 @@ class NixlBaseConnector(KVConnectorBase_V1, SupportsHMA):
assert self.connector_worker is not None
self.connector_worker.register_kv_caches(kv_caches)
def register_cross_layers_kv_cache(
self, kv_cache: torch.Tensor, attn_backend: type[AttentionBackend]
):
assert self.connector_worker is not None
self.connector_worker.register_cross_layers_kv_caches(kv_cache)
def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp):
assert self.connector_worker is not None
self.connector_worker.set_host_xfer_buffer_ops(copy_operation)
@@ -44,8 +44,9 @@ PUSH_REG_NOTIF_PREFIX = b"PUSH_REG:"
# 6: Validate EAGLE/MTP speculative configuration compatibility
# 7: Include NIXL transfer mode (push vs pull) in the compatibility hash
# 8: Add dcp_size and pcp_size to NixlAgentMetadata
# 9: Add block_strides
#
NIXL_CONNECTOR_VERSION: int = 8
NIXL_CONNECTOR_VERSION: int = 9
@dataclass
@@ -56,6 +57,7 @@ class NixlAgentMetadata:
device_id: int
num_blocks: int
block_lens: list[int]
block_strides: list[int]
kv_cache_layout: str
block_size: int
ssm_sizes: tuple[int, int]
@@ -129,7 +131,6 @@ def _get_speculative_compatibility_factors(
def compute_nixl_compatibility_hash(
vllm_config: VllmConfig,
attn_backend_name: str,
cross_layers_blocks: bool,
transfer_mode: str = "pull",
) -> str:
"""
@@ -180,7 +181,6 @@ def compute_nixl_compatibility_hash(
# Attention backend and KV cache dtype affect memory layout
"attn_backend_name": attn_backend_name,
"cache_dtype": str(cache_config.cache_dtype),
"cross_layers_blocks": cross_layers_blocks,
"is_hma_enabled": is_hma_enabled,
"speculative_config": _get_speculative_compatibility_factors(vllm_config),
# push (WRITE) and pull (READ) connectors are protocol-incompatible
@@ -17,6 +17,7 @@ import torch
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheConfig,
KVCacheLayout,
KVCacheSpec,
MambaSpec,
MLAAttentionSpec,
@@ -31,13 +32,16 @@ if TYPE_CHECKING:
CANONICAL_FORMAT_VERSION = 1
def canonical_format_id() -> str:
def canonical_format_id(kv_cache_layout: str) -> str:
"""Identity of the canonical byte format, for namespacing persisted KV.
Canonical pages keep the worker's KV layout family, so the id couples the
format version with that family; consumers must match it exactly."""
from vllm.v1.attention.backends.utils import get_kv_cache_layout
return f"v{CANONICAL_FORMAT_VERSION}-{get_kv_cache_layout().lower()}"
format version with that family; consumers must match it exactly. The family
keeps its historical NHD/HND spelling so ids stay stable for KV persisted
before the layout enum existed."""
layout = KVCacheLayout[kv_cache_layout]
legacy = {KVCacheLayout.LBNHC: "nhd", KVCacheLayout.LBHNC: "hnd"}
family = legacy.get(layout, layout.name.lower())
return f"v{CANONICAL_FORMAT_VERSION}-{family}"
@dataclass(frozen=True)
@@ -278,7 +282,7 @@ def _layer_mapping(
if isinstance(spec, MLAAttentionSpec):
# TP-replicated latent; CP shards its tokens across the DCP groups
if (
spec.compress_ratio != 1
spec.tokens_per_state != 1
or page % bs
or ctx.tp_size % ctx.dcp_size
or spec.kv_quant_mode.is_per_token_head
@@ -20,12 +20,7 @@ from vllm.v1.kv_offload.config import (
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheTensor
def is_kv_cache_tensor_packed(kv_cache_tensor: "KVCacheTensor") -> bool:
"""Return whether a KV cache tensor uses a packed block stride."""
return bool(kv_cache_tensor.block_stride)
from vllm.v1.kv_cache_interface import KVCacheConfig
def build_offloading_config(
@@ -96,18 +91,10 @@ def build_offloading_config(
blocks_per_chunk = tokens_per_chunk_int // tokens_per_block
worker_kv_bytes_per_block = 0
if kv_cache_config.num_blocks > 0:
packed_tensors = tuple(
is_kv_cache_tensor_packed(tensor)
for tensor in kv_cache_config.kv_cache_tensors
)
is_packed = any(packed_tensors)
assert not is_packed or all(packed_tensors)
total_gpu_kv_bytes = (
kv_cache_config.kv_cache_tensors[0].size
if is_packed
else sum(tensor.size for tensor in kv_cache_config.kv_cache_tensors)
)
if kv_cache_config.num_blocks > 0 and kv_cache_config.kv_cache_tensors:
# Every KVCacheTensor describes placement within the same backing allocation,
# so its size is the total, not a per-tensor share.
total_gpu_kv_bytes = kv_cache_config.kv_cache_tensors[0].size
worker_kv_bytes_per_block = total_gpu_kv_bytes // kv_cache_config.num_blocks
single_group_spec = (
@@ -164,7 +151,7 @@ def build_offloading_config(
if isinstance(single_group_spec, FullAttentionSpec):
if type(single_group_spec) is MLAAttentionSpec:
spec_certifiable = (
single_group_spec.compress_ratio == 1
single_group_spec.tokens_per_state == 1
and single_group_spec.real_page_size_bytes
% single_group_spec.block_size
== 0
@@ -219,4 +206,5 @@ def build_offloading_config(
),
replicated_layout=replicated_layout,
canonical_layout=canonical_layout,
kv_cache_layout=vllm_config.cache_config.kv_cache_layout,
)
@@ -14,16 +14,13 @@ from vllm.distributed.kv_transfer.kv_connector.v1.offloading.common import (
OffloadingWorkerMetadata,
ReqId,
)
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.config import (
is_kv_cache_tensor_packed,
)
from vllm.logger import init_logger
from vllm.v1.attention.backend import AttentionBackend
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheConfig,
MambaSpec,
UniformTypeKVCacheSpecs,
group_kernel_blocks,
)
from vllm.v1.kv_offload.base import (
CanonicalKVCacheRef,
@@ -73,16 +70,6 @@ class OffloadingConnectorWorker:
self.vllm_config, kv_cache_config, kv_caches
)
# Packed layouts (e.g. DSv4) set block_stride > 0; their tensors use
# stride(0) as the manager-block stride (equals total_num_bytes_per_block).
# General (non-packed) layouts size the tensor at page_size_bytes per
# manager block, so page_size_bytes is the correct offloading stride.
layer_is_packed: dict[str, bool] = {
ln: is_kv_cache_tensor_packed(kv_tensor)
for kv_tensor in kv_cache_config.kv_cache_tensors
for ln in kv_tensor.shared_by
}
# layer_name -> (num_blocks, page_size_bytes) tensor
tensors_per_block: dict[str, tuple[torch.Tensor, ...]] = {}
# layer_name -> size of (un-padded) page in bytes
@@ -100,63 +87,52 @@ class OffloadingConnectorWorker:
layer_kv_cache_spec = per_layer_specs.get(
layer_name, group_kv_cache_spec
)
if isinstance(layer_kv_cache_spec, AttentionSpec):
layer_kv_cache = kv_caches[layer_name]
assert isinstance(layer_kv_cache, torch.Tensor)
ref = group_kernel_blocks(kv_caches[layer_name], num_blocks)
page = layer_kv_cache_spec.page_size_bytes
elem_size = ref.element_size()
byte_offset = ref.storage_offset() * elem_size
# Packed layouts (e.g. DSv4) interleave layers per block, so the
# attention tensor's stride(0) (the manager-block stride) exceeds
# page_size_bytes; other layouts have stride(0) == page_size_bytes.
block_stride_bytes = (
ref.stride(0) * elem_size
if isinstance(layer_kv_cache_spec, AttentionSpec)
else page
)
tensors_per_block[layer_name] = (
torch.tensor([], dtype=torch.int8, device=ref.device).set_(
ref.untyped_storage(),
byte_offset,
(num_blocks, page),
(block_stride_bytes, 1),
),
)
page_size_bytes[layer_name] = page
page = layer_kv_cache_spec.page_size_bytes
elem_size = layer_kv_cache.element_size()
byte_offset = layer_kv_cache.storage_offset() * elem_size
block_stride_bytes = (
layer_kv_cache.stride(0) * elem_size
if layer_is_packed[layer_name]
else page
)
raw = torch.empty(
0,
dtype=torch.int8,
device=layer_kv_cache.device,
).set_(layer_kv_cache.untyped_storage())
tensors_per_block[layer_name] = (
torch.as_strided(
raw,
(num_blocks, page),
(block_stride_bytes, 1),
byte_offset,
),
)
page_size_bytes[layer_name] = layer_kv_cache_spec.page_size_bytes
if isinstance(layer_kv_cache_spec, AttentionSpec):
unpadded_page_size_bytes[layer_name] = (
layer_kv_cache_spec.unpadded_page_size_bytes
)
elif isinstance(layer_kv_cache_spec, MambaSpec):
layer_kv_cache = kv_caches[layer_name]
assert layer_kv_cache.dtype == torch.int8
tensors_per_block[layer_name] = (
layer_kv_cache.view(
num_blocks, layer_kv_cache_spec.page_size_bytes
),
)
page_size_bytes[layer_name] = layer_kv_cache_spec.page_size_bytes
unpadded_page_size_bytes[layer_name] = replace(
layer_kv_cache_spec, page_size_padded=None
).page_size_bytes
else:
raise NotImplementedError
packed_kv_cache_tensor = next(
# Packed layouts (e.g. DSv4) interleave all layers within each manager
# block: a layer view's block stride exceeds its page size. Offload the
# whole packed block as a single transfer region.
packed_layer_name = next(
(
t
for t in kv_cache_config.kv_cache_tensors
if is_kv_cache_tensor_packed(t) and t.shared_by
layer_name
for layer_name, (tensor,) in tensors_per_block.items()
if tensor.stride(0) != tensor.shape[1]
),
None,
)
if packed_kv_cache_tensor is not None:
(tensor,) = tensors_per_block[packed_kv_cache_tensor.shared_by[0]]
if packed_layer_name is not None:
(tensor,) = tensors_per_block[packed_layer_name]
block_stride = tensor.stride(0)
packed_tensor = tensor.as_strided(
(num_blocks, block_stride),
@@ -176,29 +152,16 @@ class OffloadingConnectorWorker:
block_tensors: list[CanonicalKVCacheTensor] = []
block_data_refs: dict[str, list[CanonicalKVCacheRef]] = defaultdict(list)
for kv_cache_tensor in kv_cache_config.kv_cache_tensors:
# Filter to layers that were actually processed above.
# Packed KV allocation emits KVCacheTensor entries for
# every (tuple_idx, page_size) slot; slots where no group has a
# layer at that index produce an empty shared_by (reserved memory
# with no corresponding model layer).
tensor_layer_names = [
n for n in kv_cache_tensor.shared_by if n in tensors_per_block
]
if not tensor_layer_names:
continue
# Layers that alias the same bytes (cache groups overlay each other) share
# one transfer region: exactly the views with equal address and strides.
aliased_layers: dict[tuple[int, tuple[int, ...]], list[str]] = defaultdict(list)
for layer_name, layer_tensors in tensors_per_block.items():
view = layer_tensors[0]
aliased_layers[(view.data_ptr(), view.stride())].append(layer_name)
# verify all layers in the group reference the exact same tensors
for tensor_layer_names in aliased_layers.values():
assert len({len(tensors_per_block[n]) for n in tensor_layer_names}) == 1
assert (
len({tensors_per_block[n][0].data_ptr() for n in tensor_layer_names})
== 1
)
assert (
len({tensors_per_block[n][0].stride() for n in tensor_layer_names}) == 1
)
# pick the first layer to represent the group
first_layer_name = tensor_layer_names[0]
for tensor in tensors_per_block[first_layer_name]:
block_tensors.append(
@@ -242,53 +205,6 @@ class OffloadingConnectorWorker:
self._init_worker(canonical_kv_caches)
def register_cross_layers_kv_cache(
self, kv_cache: torch.Tensor, attn_backend: type[AttentionBackend]
):
# verify that num_blocks is at physical position 0 in the cross-layers
# tensor layout.
test_shape = attn_backend.get_kv_cache_shape(
num_blocks=1234, block_size=16, num_kv_heads=1, head_size=256
)
num_blocks_logical_dim = test_shape.index(1234) + 1
physical_to_logical = attn_backend.get_kv_cache_stride_order(
include_num_layers_dimension=True
)
num_blocks_physical_dim = physical_to_logical.index(num_blocks_logical_dim)
assert num_blocks_physical_dim == 0
kv_cache_groups = self.kv_cache_config.kv_cache_groups
assert len(kv_cache_groups) == 1
kv_cache_spec = kv_cache_groups[0].kv_cache_spec
num_layers = len(kv_cache_groups[0].layer_names)
page_size_bytes = kv_cache_spec.page_size_bytes * num_layers
assert kv_cache.storage_offset() == 0
storage = kv_cache.untyped_storage()
assert len(storage) % page_size_bytes == 0
num_blocks = len(storage) // page_size_bytes
tensor = (
torch.tensor(
[],
dtype=torch.int8,
device=kv_cache.device,
)
.set_(storage)
.view(num_blocks, page_size_bytes)
)
kv_cache_tensor = CanonicalKVCacheTensor(
tensor=tensor, page_size_bytes=page_size_bytes
)
# in cross layers layout, there's currently only a single group
kv_cache_data_ref = CanonicalKVCacheRef(
tensor_idx=0, page_size_bytes=page_size_bytes
)
canonical_kv_caches = CanonicalKVCaches(
tensors=[kv_cache_tensor], group_data_refs=[[kv_cache_data_ref]]
)
self._init_worker(canonical_kv_caches)
def handle_preemptions(self, kv_connector_metadata: OffloadingConnectorMetadata):
assert self.worker is not None
@@ -37,7 +37,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.offloading.worker import (
OffloadingConnectorWorker,
)
from vllm.forward_context import ForwardContext
from vllm.v1.attention.backend import AttentionBackend, AttentionMetadata
from vllm.v1.attention.backend import AttentionMetadata
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import KVCacheConfig
@@ -47,11 +47,6 @@ from vllm.v1.request import Request
class OffloadingConnector(KVConnectorBase_V1, SupportsHMA):
@property
def prefer_cross_layer_blocks(self) -> bool:
# Cross-layer slabs have no per-layer refs to certify canonical mappings
return not self._canonical_layout
@property
def requires_kv_delivery(self) -> bool:
# Runs as kv_both, but is a best-effort cache: a dropped save is just a
@@ -91,12 +86,6 @@ class OffloadingConnector(KVConnectorBase_V1, SupportsHMA):
assert self.connector_worker is not None
self.connector_worker.register_kv_caches(kv_caches)
def register_cross_layers_kv_cache(
self, kv_cache: torch.Tensor, attn_backend: type[AttentionBackend]
):
assert self.connector_worker is not None
self.connector_worker.register_cross_layers_kv_cache(kv_cache, attn_backend)
def handle_preemptions(self, kv_connector_metadata: KVConnectorMetadata):
assert self.connector_worker is not None
assert isinstance(kv_connector_metadata, OffloadingConnectorMetadata)
@@ -196,7 +185,7 @@ class OffloadingConnector(KVConnectorBase_V1, SupportsHMA):
@classmethod
def get_required_kvcache_layout(cls, vllm_config: VllmConfig) -> str | None:
return "HND"
return "LBHNC"
def reset_cache(self) -> bool | None:
assert self.connector_scheduler is not None
+13 -6
View File
@@ -242,7 +242,10 @@ if TYPE_CHECKING:
VLLM_MQ_MAX_CHUNK_BYTES_MB: int = 16
VLLM_EXECUTE_MODEL_TIMEOUT_SECONDS: int = 300
VLLM_WORKER_SHUTDOWN_TIMEOUT_SECONDS: int = 5
VLLM_KV_CACHE_LAYOUT: Literal["NHD", "HND"] | None = None
VLLM_KV_CACHE_LAYOUT: (
Literal["LBNHC", "LBHNC", "LHBNC", "NHD", "HND", "BLHNC", "BLNHC", "BHLNC"]
| None
) = None
VLLM_SSM_CONV_STATE_LAYOUT: Literal["SD", "DS"] | None = None
VLLM_COMPUTE_NANS_IN_LOGITS: bool = False
VLLM_RAISE_ON_LOGIT_NANS: bool = False
@@ -1784,18 +1787,22 @@ environment_variables: dict[str, Callable[[], Any]] = {
),
# KV Cache layout used throughout vllm.
# Some common values are:
# - NHD
# - HND
# Where N=num_blocks, H=num_heads and D=head_size. The default value will
# - LBNHC
# - LBHNC
# Where N=num_states, H=num_heads and C=state_content. The default value will
# leave the layout choice to the backend. Mind that backends may only
# implement and support a subset of all possible layouts.
# LHBNC hoists the head dim outside the block dim; backends must opt in via
# AttentionBackend.supported_kv_cache_layouts().
"VLLM_KV_CACHE_LAYOUT": env_with_choices(
"VLLM_KV_CACHE_LAYOUT", None, ["NHD", "HND"]
"VLLM_KV_CACHE_LAYOUT",
None,
["LBNHC", "LBHNC", "LHBNC", "NHD", "HND", "BLHNC", "BLNHC", "BHLNC"],
),
# SSM conv state layout used for Mamba models.
# - SD: (state_len, dim) — dim contiguous (default)
# - DS: (dim, state_len) — TP-sharded dim on dim1,
# consistent with SSM temporal state and HND KV cache layout.
# consistent with SSM temporal state and LBHNC KV cache layout.
"VLLM_SSM_CONV_STATE_LAYOUT": env_with_choices(
"VLLM_SSM_CONV_STATE_LAYOUT", None, ["SD", "DS"]
),
@@ -649,6 +649,10 @@ class MLAAttention(nn.Module, AttentionLayerBase):
compile_native=True,
)
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
@property
def chunked_prefill_workspace_size(self) -> int:
if self._chunked_prefill_workspace_size is None:
@@ -1451,27 +1455,6 @@ class MLACommonBackend(AttentionBackend):
def get_builder_cls() -> type["MLACommonMetadataBuilder"]:
return MLACommonMetadataBuilder
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int, # assumed to be 1 for MLA
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
return (num_blocks, block_size, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
# Default to identity permutation to signal cross-layer allocation
# is unsupported. Each MLA backend must opt in to support cross-layer
# allocation by overriding this method.
return (0, 1, 2, 3)
return (0, 1, 2)
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [320, 576]
+15 -12
View File
@@ -61,16 +61,16 @@ def hpc_rope_norm_forward(
return
attn_layer = forward_context.no_compile_layers[layer_name]
# bind_kv_cache stores the per-layer KV cache as a single 5D tensor
# (num_blocks, 2, block_size, num_kv_heads, head_size), so use it directly.
# bind_kv_cache stores the per-layer KV cache as a single tensor
# (num_blocks, num_kv_heads, block_size, 2 * head_size), so use it directly.
kv_cache = attn_layer.kv_cache
if kv_cache.numel() == 0:
output.zero_()
return
assert kv_cache.dim() == 5, (
f"Expected kv_cache to have 5 dims, got {tuple(kv_cache.shape)}"
assert kv_cache.dim() == 4, (
f"Expected kv_cache to have 4 dims, got {tuple(kv_cache.shape)}"
)
rope_norm = _hpc_rope_norm_instances[layer_name]
@@ -295,6 +295,9 @@ class HpcRopeNorm(CustomOp, HpcModule):
"""
import hpc
# (B, H, N, 2*hs) -> two (B, N, H, hs) K/V views, as in HpcAttentionImpl.
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_dim, dim=-1)
num_actual_tokens = attn_metadata.num_actual_tokens
num_prefill_reqs = attn_metadata.num_prefills
num_decode_reqs = attn_metadata.num_decodes
@@ -333,8 +336,8 @@ class HpcRopeNorm(CustomOp, HpcModule):
if self.use_fp8:
_, q_scale, split_k_flag = hpc.rope_norm_store_kv_fp8(
key_cache=kv_cache[:, 0],
value_cache=kv_cache[:, 1],
key_cache=key_cache,
value_cache=value_cache,
qkv=qkv_prefill,
cos_sin=self.cos_sin_cache,
num_seqlen_per_req=seq_lens_prefill,
@@ -353,8 +356,8 @@ class HpcRopeNorm(CustomOp, HpcModule):
attn_metadata.hpc_prefill_q_scale = q_scale
else:
hpc.rope_norm_store_kv(
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
qkv_prefill,
self.cos_sin_cache,
seq_lens_prefill,
@@ -379,8 +382,8 @@ class HpcRopeNorm(CustomOp, HpcModule):
if self.use_fp8:
_, q_scale, split_k_flag = hpc.rope_norm_store_kv_fp8(
key_cache=kv_cache[:, 0],
value_cache=kv_cache[:, 1],
key_cache=key_cache,
value_cache=value_cache,
qkv=qkv_decode,
cos_sin=self.cos_sin_cache,
num_seqlen_per_req=num_seq_kvcache,
@@ -401,8 +404,8 @@ class HpcRopeNorm(CustomOp, HpcModule):
attn_metadata.hpc_split_k_flag = split_k_flag
else:
hpc.rope_norm_store_kv(
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
qkv_decode,
self.cos_sin_cache,
num_seq_kvcache,
@@ -645,6 +645,11 @@ class DeepseekV32IndexerCache(torch.nn.Module, AttentionLayerBase):
raise ValueError(f"Duplicate layer name: {prefix}")
compilation_config.static_forward_context[prefix] = self
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]: the indexer kernels and
# kv_cache_as_quant_view index a 3-D block-major cache.
self.kv_cache = kv_cache.squeeze(1)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
return MLAAttentionSpec(
block_size=self.cache_config.block_size,
@@ -80,14 +80,14 @@ def dummy_attention(layer_name, _placeholder):
def basic_cache(
to_cache: torch.Tensor, # shape: [seq_len, num_heads, head_size]
kv_cache: torch.Tensor, # shape: [num_blocks, block_size, num_heads, head_size]
kv_cache: torch.Tensor, # shape: [num_blocks, num_heads, block_size, head_size]
slot_mapping: torch.Tensor, # shape: [seq_len]
):
# Padding slots are -1; redirect them to the null block (block 0, never
# allocated to a request) so the scatter stays branch-free and sync-free.
block_size = kv_cache.shape[1]
block_size = kv_cache.shape[2]
slot_mapping = slot_mapping.clamp_min(0)
kv_cache[slot_mapping // block_size, slot_mapping % block_size] = to_cache
kv_cache[slot_mapping // block_size, :, slot_mapping % block_size] = to_cache
######### CacheOnlyAttentionBackend ########
@@ -123,18 +123,6 @@ class CacheOnlyAttentionBackend(AttentionBackend):
def get_impl_cls() -> type["CacheOnlyAttentionImpl"]:
return CacheOnlyAttentionImpl
@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, ...]:
# We set `num_kv_heads = num_hidden_layers` and `head_size = hidden_size`
# We also don't use a k/v (2) dim
return (num_blocks, block_size, num_kv_heads, head_size)
@staticmethod
def get_builder_cls() -> type["CacheOnlyAttentionMetadataBuilder"]:
return CacheOnlyAttentionMetadataBuilder
+6 -22
View File
@@ -5,6 +5,7 @@ import functools
import logging
import math
from dataclasses import replace
from fractions import Fraction
from functools import partial
import torch
@@ -128,14 +129,10 @@ def create_whisper_attention_backend_with_block_pooling(
vllm_config: VllmConfig,
device: torch.device,
):
assert kv_cache_spec.num_kv_heads % block_pool_size == 0
# Scale pooled-unit quantities back to unpooled (encoder-token)
# units for the underlying attention metadata: the KV cache spec
# counts blocks in pooled units, but the kernel runs on the
# `block_pool_size`x-expanded sequence built below.
spec_overrides = dict(
kv_cache_spec = replace(
kv_cache_spec,
block_size=kv_cache_spec.block_size * block_pool_size,
num_kv_heads=kv_cache_spec.num_kv_heads // block_pool_size,
tokens_per_state=1,
)
if isinstance(kv_cache_spec, SlidingWindowSpec):
# The manager keeps `sliding_window` in pooled units; the kernel
@@ -143,8 +140,7 @@ def create_whisper_attention_backend_with_block_pooling(
# unpooled units (`get_kv_cache_spec` sizes the pooled window so
# this window always stays resident).
assert sliding_window is not None
spec_overrides["sliding_window"] = sliding_window
kv_cache_spec = replace(kv_cache_spec, **spec_overrides)
kv_cache_spec = replace(kv_cache_spec, sliding_window=sliding_window)
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
# Override model_config-derived values with the actual
# encoder values from kv_cache_spec
@@ -261,18 +257,6 @@ def create_whisper_attention_backend_with_block_pooling(
overrides={
"get_builder_cls": lambda: WhisperCausalAttentionWithBlockPoolingBuilder,
"get_impl_cls": lambda: WhisperCausalAttentionWithBlockPoolingImpl,
"get_kv_cache_shape": lambda num_blocks,
block_size,
num_kv_heads,
head_size,
cache_dtype_str: underlying_attn_backend.get_kv_cache_shape(
num_blocks,
# we stretch each block by `block_pool_size`
block_size * block_pool_size,
num_kv_heads // block_pool_size,
head_size,
cache_dtype_str,
),
"forward_includes_kv_cache_update": True,
},
)
@@ -341,7 +325,7 @@ class WhisperCausalAttentionWithBlockPooling(Attention):
assert isinstance(kv_cache_spec, AttentionSpec)
kv_cache_spec = replace(
kv_cache_spec,
num_kv_heads=self.block_pool_size * kv_cache_spec.num_kv_heads,
tokens_per_state=Fraction(1, self.block_pool_size),
)
if isinstance(kv_cache_spec, SlidingWindowSpec):
# The manager counts blocks in pooled units, so express the window in
+20 -4
View File
@@ -653,7 +653,8 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# per-tensor fp8 writes a separately-allocated fp8 q and quantizes the
# KV row.
block_size = swa_metadata.block_size
swa_kv_cache_3d = swa_kv_cache.view(-1, block_size, self.head_dim)
assert swa_kv_cache.shape[1:] == (block_size, self.head_dim)
swa_kv_cache_3d = swa_kv_cache
if cache_dtype == torch.bfloat16:
torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert(
q,
@@ -684,6 +685,17 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
)
return q_fp8
def _global_topk_output_buffers(
self, topk_indices: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor] | None:
if self.compress_ratio != 4 or self.eager_scratch_pool is None:
return None
return self.eager_scratch_pool.global_topk_outputs(topk_indices)
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
def get_attn_backend(self) -> type[AttentionBackend]:
return self.backend_cls
@@ -701,7 +713,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
num_kv_heads=1,
head_size=self.head_dim,
dtype=torch.uint8 if uses_fp8_ds_mla_layout else self.kv_cache_torch_dtype,
compress_ratio=self.compress_ratio,
tokens_per_state=self.compress_ratio,
cache_dtype_str=self.kv_cache_dtype,
alignment=576 if uses_fp8_ds_mla_layout else 512,
model_version="deepseek_v4",
@@ -733,16 +745,20 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
raise ValueError(f"Duplicate layer name: {prefix}")
compilation_config.static_forward_context[prefix] = self
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
# head_dim already carries the fp8 scale padding
# compress_ratio=1 for V3.2, >1 for DeepseekV4; both use the same cache layout.
# tokens_per_state=1 for V3.2, >1 for DeepseekV4; same cache layout.
uses_fp8_ds_mla_layout = vllm_config.cache_config.cache_dtype == "fp8_ds_mla"
return MLAAttentionSpec(
block_size=self.cache_config.block_size,
num_kv_heads=1,
head_size=self.head_dim,
dtype=self.dtype,
compress_ratio=self.compress_ratio,
tokens_per_state=self.compress_ratio,
# 576B for FlashMLA packing; 512B for FlashInfer sparse (#44577).
alignment=576 if uses_fp8_ds_mla_layout else 512,
)
+4 -19
View File
@@ -75,25 +75,6 @@ class CompressorBackend(AttentionBackend):
def get_builder_cls() -> type["CompressorMetadataBuilder"]:
return CompressorMetadataBuilder
@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, ...]:
assert num_kv_heads == 1
return (num_blocks, block_size, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (0, 1, 2, 3)
return (0, 1, 2)
@dataclass
class CompressorMetadata:
@@ -185,6 +166,10 @@ class CompressorStateCache(torch.nn.Module, AttentionLayerBase):
else:
raise ValueError(f"Invalid compress ratio: {compress_ratio}")
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
# fp8_ds_mla is the UE8M0 paged layout and needs 576B alignment. Plain
# full-cache rows share state pages with contiguous KV pages, so padding
@@ -22,7 +22,6 @@ from vllm.models.deepseek_v4.sparse_mla import (
DeepseekV4FlashMLAMetadata,
DeepseekV4SparseMLABackend,
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.flashinfer import flashinfer_trtllm_batch_decode_sparse_mla_dsv4
from vllm.v1.attention.backend import MultipleOf
@@ -165,26 +164,6 @@ class DeepseekV4FlashInferMLASparseBackend(DeepseekV4SparseMLABackend):
return None
return "FLASHINFER_MLA_SPARSE_DSV4 requires SM10x or SM12x"
@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, ...]:
device_capability = current_platform.get_device_capability()
if device_capability is not None and device_capability.major == 12:
return DeepseekV4SparseMLABackend.get_kv_cache_shape(
num_blocks,
block_size,
num_kv_heads,
head_size,
cache_dtype_str,
)
assert num_kv_heads == 1
return (num_blocks, block_size, head_size)
class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
"""FlashInfer TRTLLM-gen sparse MLA attention layer for SM100 DeepSeek V4."""
+3 -18
View File
@@ -88,21 +88,6 @@ class DeepseekV4SparseMLABackend(AttentionBackend):
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major in [9, 10]
@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, ...]:
if cache_dtype_str == "fp8_ds_mla":
# DeepseekV4 main MLA: 584B per token (448 NoPE + 128 RoPE + 8 fp8 scale).
# head_size passed in is the semantic head_dim (512).
return (num_blocks, block_size, 584)
else:
return (num_blocks, block_size, head_size)
@dataclass
class DeepseekV4FlashMLAMetadata(AttentionMetadata):
@@ -151,8 +136,8 @@ class DeepseekV4SparseMLAMetadataBuilder(
(max_num_batched_tokens,), dtype=torch.int32, device=device
)
assert hasattr(self.kv_cache_spec, "compress_ratio")
self.compress_ratio = self.kv_cache_spec.compress_ratio
assert isinstance(self.kv_cache_spec.tokens_per_state, int)
self.compress_ratio = self.kv_cache_spec.tokens_per_state
# Pre-allocate compressed slot mapping buffer for CUDA graph address
# stability when compress_ratio > 1.
@@ -206,7 +191,7 @@ class DeepseekV4SparseMLAMetadataBuilder(
cm.query_start_loc,
cm.seq_lens,
cm.block_table_tensor.clamp_(min=0),
int(self.kv_cache_spec.storage_block_size),
int(self.kv_cache_spec.num_states),
self.compress_ratio,
out=self.compressed_slot_mapping_buffer,
)
-26
View File
@@ -107,32 +107,6 @@ class InklingSconvBackend(AttentionBackend):
def get_name() -> str:
return "INKLING_SCONV_SWA"
@classmethod
def indexes_kv_by_block_stride(cls) -> bool:
# num_blocks is the outermost dim (HND, see get_kv_cache_shape), so the
# padded conv page is read through a strided view.
return True
@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, ...]:
# HND, num-blocks-first, head-major: [num_blocks, H, N, D].
return (num_blocks, num_kv_heads, block_size, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# Identity: physical layout == logical [num_blocks, H, N, D].
if include_num_layers_dimension:
return (0, 1, 2, 3, 4)
return (0, 1, 2, 3)
@staticmethod
def get_impl_cls():
raise NotImplementedError(
@@ -107,32 +107,6 @@ class InklingSconvBackend(AttentionBackend):
def get_name() -> str:
return "INKLING_SCONV_SWA"
@classmethod
def indexes_kv_by_block_stride(cls) -> bool:
# num_blocks is the outermost dim (HND, see get_kv_cache_shape), so the
# padded conv page is read through a strided view.
return True
@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, ...]:
# HND, num-blocks-first, head-major: [num_blocks, H, N, D].
return (num_blocks, num_kv_heads, block_size, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# Identity: physical layout == logical [num_blocks, H, N, D].
if include_num_layers_dimension:
return (0, 1, 2, 3, 4)
return (0, 1, 2, 3)
@staticmethod
def get_impl_cls():
raise NotImplementedError(
+4
View File
@@ -384,6 +384,10 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
# ------------------------------------------------------------------
# AttentionLayerBase interface
# ------------------------------------------------------------------
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
def get_attn_backend(self) -> type[AttentionBackend]:
return self.attn_backend
+8
View File
@@ -728,6 +728,12 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec | None:
# Main GQA K/V cache. Block size may change after load, refresh it.
# AITER sparse PA wants K and V as two separate head groups
# (H folded into the content dim).
sparse_pa = self.use_aiter_sparse_pa
kv_bytes = (
self.num_kv_heads * self.head_dim * self.kv_cache_torch_dtype.itemsize
)
return FullAttentionSpec(
block_size=vllm_config.cache_config.block_size,
num_kv_heads=self.num_kv_heads,
@@ -735,6 +741,8 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
head_size_v=self.head_dim,
dtype=self.kv_cache_torch_dtype,
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
num_head_slots=2 if sparse_pa else None,
state_content_bytes=kv_bytes if sparse_pa else None,
)
def _ensure_aiter_sparse_pa_kv_cache(self) -> None:
+4 -19
View File
@@ -97,25 +97,6 @@ class MiniMaxM3IndexerBackend(AttentionBackend):
def is_sparse(cls) -> bool:
return True
@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)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
# M3 does not use cross-layer (per-layer-stacked) KV blocks.
raise NotImplementedError
return (0, 1, 2)
class MiniMaxM3IndexerCache(nn.Module, AttentionLayerBase):
"""Side KV cache for the indexer's per-token index keys (key-only).
@@ -156,6 +137,10 @@ class MiniMaxM3IndexerCache(nn.Module, AttentionLayerBase):
raise ValueError(f"Duplicate layer name: {prefix}")
compilation_config.static_forward_context[prefix] = self
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
# Key-only: MLAAttentionSpec budgets one vector/token (not 2x for K+V).
return MLAAttentionSpec(
@@ -51,10 +51,13 @@ from vllm.v1.attention.backend import (
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
get_kv_cache_layout,
split_decodes_and_prefills,
)
from vllm.v1.kv_cache_interface import AttentionSpec, is_quantized_kv_cache
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
is_quantized_kv_cache,
)
logger = init_logger(__name__)
@@ -112,47 +115,13 @@ class MiniMaxM3SparseBackend(AttentionBackend):
def is_sparse(cls) -> bool:
return True
@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, ...]:
if minimax_m3_use_aiter_sparse_pa(num_kv_heads):
# AITER's assembly paged-attention kernels require independently
# contiguous K and V storage. Keep that specialized layout behind
# the shuffle flag while every other implementation uses the
# packed-content contract introduced by #44455.
return (num_blocks, 2, block_size, num_kv_heads, head_size)
# K and V are packed into the content dim: logical (B, H, N, 2*hs).
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# `stride_order` indicates the permutation that gets us from
# `get_kv_cache_shape` (logical (B, H, N, 2*hs)) to the actual memory
# layout we want.
if include_num_layers_dimension:
raise NotImplementedError # no cross-layer KV blocks in M3
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
# AITER sparse PA unbinds K and V as separate contiguous regions, which
# requires the head dimension to sit outside the block dimension.
if _minimax_m3_aiter_sparse_pa_requested():
# The AITER page-16 sparse PA path reinterprets the K and V slices
# as separate SHUFFLE caches. Keep K/V physically separated so
# kv_cache[:, 0] and kv_cache[:, 1] are contiguous byte ranges.
return (1, 0, 2, 3, 4)
cache_layout = get_kv_cache_layout()
if cache_layout == "NHD":
# (num_blocks, block_size, num_kv_heads, 2*head_size)
stride_order = (0, 2, 1, 3)
elif cache_layout == "HND":
# (num_blocks, num_kv_heads, block_size, 2*head_size)
stride_order = (0, 1, 2, 3)
else:
raise ValueError(f"Unknown cache layout format {cache_layout}.")
return stride_order
return (KVCacheLayout.LHBNC,)
return super().supported_kv_cache_layouts()
@dataclass
+15
View File
@@ -117,6 +117,21 @@ def is_strictly_contiguous(t: torch.Tensor) -> bool:
return True
def is_non_overlapping_and_dense(t: torch.Tensor) -> bool:
"""Check if the tensor's elements cover one gapless, non-overlapping byte
range, in any dimension order (i.e. a permuted view of a contiguous
tensor); ``is_contiguous()`` additionally requires row-major order.
"""
expected_stride = 1
for size, stride in sorted(zip(t.shape, t.stride()), key=lambda p: p[1]):
if size == 1:
continue
if stride != expected_stride:
return False
expected_stride *= size
return True
def canonicalize_singleton_dim_strides(t: torch.Tensor) -> torch.Tensor:
"""Fix degenerate strides on size=1 dimensions for CUDA TMA compatibility.
+10 -98
View File
@@ -23,10 +23,14 @@ if TYPE_CHECKING:
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
from vllm.platforms.interface import DeviceCapability
from vllm.v1.attention.backends.utils import KVCacheLayoutType
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec, KVQuantMode
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
KVCacheSpec,
KVQuantMode,
)
from vllm.v1.kv_cache_interface import get_kv_quant_mode
from vllm.v1.kv_cache_interface import KVCacheLayout, get_kv_quant_mode
class AttentionType(str, Enum):
@@ -84,68 +88,6 @@ class AttentionBackend(ABC):
def get_builder_cls(): # -> Type["AttentionMetadataBuilder"]:
raise NotImplementedError
@staticmethod
@abstractmethod
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, ...]:
raise NotImplementedError
@classmethod
def get_kv_cache_block_dim(
cls,
block_size: int,
num_kv_heads: int,
head_size: int,
cache_dtype_str: str = "auto",
) -> int:
"""Discover which tensor dim is the block index, since different
backends lay out dims differently."""
_S = 1234567
shape = cls.get_kv_cache_shape(
_S,
block_size,
num_kv_heads,
head_size,
cache_dtype_str=cache_dtype_str,
)
return shape.index(_S)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
"""
Get the physical (memory layout) ordering of the kv cache dimensions.
Standard attention backends pack K and V into the content dim, giving
the logical shape [num_blocks, num_heads, block_size, 2 * head_size].
e.g. if get_kv_cache_stride_order returns (0, 2, 1, 3) then the physical
ordering of dimensions is
[num_blocks, block_size, num_heads, 2 * head_size].
If this function is unimplemented / raises NotImplementedError,
the physical layout of the KV cache will match the logical shape.
Args:
include_num_layers_dimension: if True, includes an additional
num_layers dimension, which is assumed to be prepended
to the logical KV cache shape.
With the above example, a return value (1, 0, 3, 2, 4)
corresponds to
[num_blocks, num_layers, block_size, num_heads, 2 * head_size].
If an additional dimension is NOT included in the returned
tuple, the physical layout will not include a layers dimension.
Returns:
A tuple of ints which is a permutation of range(len(shape)).
"""
raise NotImplementedError
@classmethod
def full_cls_name(cls) -> tuple[str, str]:
return (cls.__module__, cls.__qualname__)
@@ -215,38 +157,6 @@ class AttentionBackend(ABC):
return min(s.base if isinstance(s, MultipleOf) else s for s in supported_sizes)
@classmethod
def indexes_kv_by_block_stride(cls) -> bool:
"""Whether the backend reads KV pages by the runtime block stride.
True when ``num_blocks`` is the outermost physical dimension of the KV
cache, so the backend tolerates a non-contiguous block dim. This gates
page size padding and cross-layer uniform KV layout.
Returns:
True if the backend's physical KV layout is num-blocks-first. False
otherwise, including when the backend does not define a layered
stride order.
"""
try:
kv_cache_stride_order = cls.get_kv_cache_stride_order(
include_num_layers_dimension=False
)
layered_kv_cache_stride_order = cls.get_kv_cache_stride_order(
include_num_layers_dimension=True
)
except (AttributeError, NotImplementedError):
return False
# Check that attention backend includes a layers dimension.
if len(layered_kv_cache_stride_order) != len(kv_cache_stride_order) + 1:
return False
# stride_order[0] == 0 means num_layers stays first in physical
# layout (identity permutation), so indexing by block stride is
# not supported.
return layered_kv_cache_stride_order[0] != 0
@classmethod
def is_mla(cls) -> bool:
return False
@@ -438,7 +348,9 @@ class AttentionBackend(ABC):
return invalid_reasons
@classmethod
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
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."""
return None
@classmethod
+6 -15
View File
@@ -30,13 +30,13 @@ from vllm.v1.attention.backend import (
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
KVCacheLayoutType,
get_num_attention_heads_from_layers,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
CrossAttentionSpec,
EncoderOnlyAttentionSpec,
KVCacheLayout,
)
logger = init_logger(__name__)
@@ -65,6 +65,11 @@ class CPUAttentionBackend(AttentionBackend):
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"
@@ -96,20 +101,6 @@ class CPUAttentionBackend(AttentionBackend):
def get_builder_cls() -> type["CPUAttentionMetadataBuilder"]:
return CPUAttentionMetadataBuilder
@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, num_kv_heads, block_size, 2 * head_size
@classmethod
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
return "HND"
@staticmethod
def use_cascade_attention(*args, **kwargs) -> bool:
return False
+5 -44
View File
@@ -33,7 +33,6 @@ from vllm.v1.attention.backends.fa_utils import (
from vllm.v1.attention.backends.utils import (
fill_mm_prefix_query_ranges,
get_dcp_local_seq_lens,
get_num_attention_heads_from_layers,
)
from vllm.v1.attention.ops.dcp import (
cp_lse_ag_out_rs,
@@ -65,7 +64,6 @@ from vllm.v1.attention.backend import (
AttentionMetadataBuilder,
CommonAttentionMetadata,
)
from vllm.v1.attention.backends.utils import get_kv_cache_layout
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec
from vllm.v1.worker.cp_utils import (
run_split_fa2_dcp_context_attention,
@@ -138,43 +136,6 @@ class FlashAttentionBackend(AttentionBackend):
def get_builder_cls() -> type["FlashAttentionMetadataBuilder"]:
return FlashAttentionMetadataBuilder
@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, ...]:
if block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
# K and V are packed into the content dim: logical (B, H, N, 2*D).
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# `stride_order` indicates the permutation that gets us from
# `get_kv_cache_shape` (logical (B, H, N, 2*D)) to the actual memory
# layout we want.
cache_layout = get_kv_cache_layout()
if cache_layout == "NHD" and include_num_layers_dimension:
# (num_blocks, num_layers, block_size, num_kv_heads, 2*head_size)
return (1, 0, 3, 2, 4)
elif cache_layout == "NHD":
# (num_blocks, block_size, num_kv_heads, 2*head_size)
stride_order = (0, 2, 1, 3)
elif cache_layout == "HND" and include_num_layers_dimension:
# (num_blocks, num_kv_heads, num_layers, block_size, 2*head_size)
return (1, 2, 0, 3, 4)
elif cache_layout == "HND":
# (num_blocks, num_kv_heads, block_size, 2*head_size)
stride_order = (0, 1, 2, 3)
else:
raise ValueError(f"Unknown cache layout format {cache_layout}.")
return stride_order
@classmethod
def supports_head_size(cls, head_size: int) -> bool:
if head_size % 8 != 0:
@@ -436,12 +397,12 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
self.compilation_config = vllm_config.compilation_config
self.attention_config = vllm_config.attention_config
self.num_heads_q = get_num_attention_heads_from_layers(
vllm_config, layer_names
) or self.model_config.get_num_attention_heads(self.parallel_config)
self.num_heads_kv = kv_cache_spec.num_kv_heads
self.num_heads_q = self.model_config.get_num_attention_heads(
self.parallel_config
)
self.num_heads_kv = self.model_config.get_num_kv_heads(self.parallel_config)
self.kv_cache_dtype = kv_cache_spec.dtype
self.headdim = kv_cache_spec.head_size
self.headdim = self.model_config.get_head_size()
self.block_size = kv_cache_spec.block_size
self.max_num_splits = 0 # No upper bound on the number of splits.
@@ -21,7 +21,6 @@ from vllm.v1.attention.ops.triton_reshape_and_cache_flash import (
if is_flash_attn_varlen_func_available():
from vllm.v1.attention.backends.fa_utils import flash_attn_varlen_func
from vllm.v1.attention.backends.utils import get_kv_cache_layout
from .flash_attn import (
FlashAttentionBackend,
@@ -73,49 +72,6 @@ class FlashAttentionDiffKVBackend(FlashAttentionBackend):
def get_impl_cls() -> type["FlashAttentionImpl"]:
return FlashAttentionDiffKVImpl
@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, ...]:
if block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
# Logical (blocks-first, head-major) layout: K and V (with their
# different head sizes) packed in the content dim.
return (
num_blocks,
num_kv_heads,
block_size,
head_size + FlashAttentionDiffKVBackend.head_size_v,
)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# `stride_order` indicates the permutation that gets us from
# `get_kv_cache_shape` (logical (B, H, N, C_k+C_v)) to the actual
# memory layout we want.
cache_layout = get_kv_cache_layout()
if cache_layout == "NHD" and include_num_layers_dimension:
# (num_blocks, num_layers, block_size, num_kv_heads, C_k+C_v)
return (1, 0, 3, 2, 4)
elif cache_layout == "NHD":
# (num_blocks, block_size, num_kv_heads, C_k+C_v)
stride_order = (0, 2, 1, 3)
elif cache_layout == "HND" and include_num_layers_dimension:
# (num_blocks, num_kv_heads, num_layers, block_size, C_k+C_v)
return (1, 2, 0, 3, 4)
elif cache_layout == "HND":
# (num_blocks, num_kv_heads, block_size, C_k+C_v)
stride_order = (0, 1, 2, 3)
else:
raise ValueError(f"Unknown cache layout format {cache_layout}.")
return stride_order
class FlashAttentionDiffKVImpl(FlashAttentionImpl):
vllm_flash_attn_version: int | None
+36 -61
View File
@@ -67,9 +67,8 @@ from vllm.v1.attention.backend import (
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
KVCacheLayoutType,
get_dcp_local_seq_lens,
get_kv_cache_layout,
get_flashinfer_layout_string,
get_num_attention_heads_from_layers,
get_per_layer_parameters,
infer_global_hyperparameters,
@@ -83,6 +82,7 @@ from vllm.v1.attention.ops.dcp import (
from vllm.v1.attention.ops.merge_attn_states import merge_attn_states
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
KVCacheSpec,
KVQuantMode,
UniformTypeKVCacheSpecs,
@@ -282,6 +282,7 @@ def trtllm_prefill_attn_kvfp8_dequant(
class BatchDCPPrefillWrapper:
def __init__(
self,
kv_layout: str,
workspace_buffer: torch.Tensor | None = None,
dcp_a2a: bool = False,
):
@@ -289,9 +290,7 @@ class BatchDCPPrefillWrapper:
self._dcp_combine = partial(dcp_a2a_lse_reduce, is_lse_base_on_e=False)
else:
self._dcp_combine = partial(cp_lse_ag_out_rs, is_lse_base_on_e=False)
self._context = BatchPrefillWithPagedKVCacheWrapper(
workspace_buffer, get_kv_cache_layout()
)
self._context = BatchPrefillWithPagedKVCacheWrapper(workspace_buffer, kv_layout)
self._new_tokens = BatchPrefillWithRaggedKVCacheWrapper(workspace_buffer)
def plan(
@@ -467,44 +466,6 @@ class FlashInferBackend(AttentionBackend):
def get_builder_cls() -> type["FlashInferMetadataBuilder"]:
return FlashInferMetadataBuilder
@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, ...]:
if cache_dtype_str.startswith("nvfp4"):
full_dim = nvfp4_kv_cache_full_dim(head_size)
return (num_blocks, 2 * num_kv_heads, block_size, full_dim)
# Pack K and V in the content dim (B, H, N, 2*hs).
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# `stride_order` indicates the permutation that gets us from
# `get_kv_cache_shape` (logical (B, H, N, 2*hs)) to the actual memory
# layout we want.
cache_layout = get_kv_cache_layout()
if cache_layout == "NHD" and include_num_layers_dimension:
# (num_blocks, num_layers, block_size, num_kv_heads, 2*head_size)
return (1, 0, 3, 2, 4)
elif cache_layout == "NHD":
# (num_blocks, block_size, num_kv_heads, 2*head_size)
stride_order = (0, 2, 1, 3)
elif cache_layout == "HND" and include_num_layers_dimension:
# (num_blocks, num_kv_heads, num_layers, block_size, 2*head_size)
return (1, 2, 0, 3, 4)
elif cache_layout == "HND":
# (num_blocks, num_kv_heads, block_size, 2*head_size)
stride_order = (0, 1, 2, 3)
else:
raise ValueError(f"Unknown cache layout format {cache_layout}.")
return stride_order
@staticmethod
def get_dtype_for_flashinfer(kv_cache_dtype: str) -> torch.dtype:
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
@@ -563,11 +524,13 @@ class FlashInferBackend(AttentionBackend):
) and supports_trtllm_attention(is_prefill=True)
@classmethod
def get_required_kv_cache_layout(cls) -> KVCacheLayoutType | None:
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
capability = current_platform.get_device_capability()
if capability is not None and capability.major == 10:
return "HND"
return None
# The trtllm-gen kernels consume head-major block interiors; the L/B
# nesting outside the block is immaterial to them.
return (KVCacheLayout.LBHNC, KVCacheLayout.BLHNC)
return super().supported_kv_cache_layouts()
forward_includes_kv_cache_update: bool = False
@@ -945,6 +908,10 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self.paged_kv_indices = self._make_buffer(max_num_pages)
self.paged_kv_last_page_len = self._make_buffer(max_num_reqs)
@property
def kv_cache_layout(self) -> KVCacheLayout:
return self.cache_config.get_resolved_kv_cache_layout()
# Keep SM90 prefill/decode Q dtype selection in one place.
def get_q_data_type(self, is_prefill: bool) -> torch.dtype:
# The user sets --attention-config.disable_flashinfer_q_quantization
@@ -1155,7 +1122,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self._noncausal_prefill_wrapper = (
BatchAttentionWithAttentionSinkWrapper(
self._get_workspace_buffer(),
get_kv_cache_layout(),
get_flashinfer_layout_string(self.kv_cache_layout),
backend="auto",
q_data_type=self.q_data_type_prefill,
kv_data_type=self.kv_cache_dtype,
@@ -1168,7 +1135,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self._noncausal_prefill_wrapper = (
BatchPrefillWithPagedKVCacheWrapper(
self._get_workspace_buffer(),
get_kv_cache_layout(),
get_flashinfer_layout_string(self.kv_cache_layout),
backend="auto",
)
)
@@ -1177,6 +1144,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
if self._prefill_wrapper is None:
if self.use_dcp:
self._prefill_wrapper = BatchDCPPrefillWrapper(
kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
workspace_buffer=self._get_workspace_buffer(),
dcp_a2a=self.dcp_a2a,
)
@@ -1185,7 +1153,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
assert not self.is_kvcache_nvfp4
self._prefill_wrapper = BatchAttentionWithAttentionSinkWrapper(
self._get_workspace_buffer(),
get_kv_cache_layout(),
get_flashinfer_layout_string(self.kv_cache_layout),
backend="auto",
q_data_type=self.q_data_type_prefill,
kv_data_type=self.kv_cache_dtype,
@@ -1199,7 +1167,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
self._prefill_wrapper = BatchPrefillWithPagedKVCacheWrapper(
self._get_workspace_buffer(),
get_kv_cache_layout(),
get_flashinfer_layout_string(self.kv_cache_layout),
backend=backend,
)
assert self._prefill_wrapper is not None
@@ -1225,7 +1193,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
decode_wrapper = BatchDecodeWithPagedKVCacheWrapper(
self._get_workspace_buffer(),
get_kv_cache_layout(),
get_flashinfer_layout_string(self.kv_cache_layout),
use_cuda_graph=use_cudagraph,
paged_kv_indptr_buffer=paged_kv_indptr,
paged_kv_indices_buffer=paged_kv_indices,
@@ -1248,7 +1216,9 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
def _get_cascade_wrapper(self):
if self._cascade_wrapper is None:
self._cascade_wrapper = MultiLevelCascadeAttentionWrapper(
2, self._get_workspace_buffer(), get_kv_cache_layout()
2,
self._get_workspace_buffer(),
get_flashinfer_layout_string(self.kv_cache_layout),
)
return self._cascade_wrapper
@@ -1813,6 +1783,8 @@ class FlashInferImpl(AttentionImpl):
num_heads, num_kv_heads, is_prefill=False
)
vllm_config = get_current_vllm_config_or_none()
# The layout is resolved after model construction, so read it lazily.
self.cache_config = vllm_config.cache_config if vllm_config else None
# Query pre-quantization needs a single dtype for the whole query tensor.
# SM90 XQA needs BF16/FP16-Q for decode and FP8 for prefill,
# so only enable this for SM100 trtllm-gen where both use FP8-Q.
@@ -1848,6 +1820,11 @@ class FlashInferImpl(AttentionImpl):
else:
self.dcp_combine = partial(cp_lse_ag_out_rs, is_lse_base_on_e=False)
@property
def kv_cache_layout(self) -> KVCacheLayout:
assert self.cache_config is not None
return self.cache_config.get_resolved_kv_cache_layout()
def fused_output_quant_supported(self, quant_key: QuantKey):
# XQA does not support FP8/NVFP4 output, so require trtllm-gen
# (SM100+) here. Without that we cannot fuse the output quant.
@@ -1919,9 +1896,7 @@ class FlashInferImpl(AttentionImpl):
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: KV cache tensor with different possible shapes:
- NHD: [num_blocks, 2, block_size, num_kv_heads, head_size]
- HND: [num_blocks, 2, num_kv_heads, block_size, head_size]
kv_cache: [num_blocks, num_kv_heads, block_size, 2*head_size]
attn_metadata: Metadata for attention.
Returns:
shape = [num_tokens, num_heads * head_size]
@@ -2019,7 +1994,7 @@ class FlashInferImpl(AttentionImpl):
if attn_metadata.use_cascade:
# Cascade attention (rare case).
assert attn_metadata.cascade_wrapper is not None
stride_order = FlashInferBackend.get_kv_cache_stride_order()
stride_order = self.kv_cache_layout.layer_view_order
if self.is_kvcache_nvfp4:
kv_cache_views = tuple(
cache.permute(*stride_order)
@@ -2039,7 +2014,7 @@ class FlashInferImpl(AttentionImpl):
num_decode_tokens = attn_metadata.num_decode_tokens
num_prefill_tokens = attn_metadata.num_prefill_tokens
stride_order = FlashInferBackend.get_kv_cache_stride_order()
stride_order = self.kv_cache_layout.layer_view_order
kv_cache_permute = kv_cache.permute(*stride_order) # HND and contiguous
# Fix degenerate strides on any size-1 dimension (e.g. num_kv_heads=1
# with TP=8). PyTorch permits non-canonical strides on size-1 dims;
@@ -2195,7 +2170,7 @@ class FlashInferImpl(AttentionImpl):
seq_lens_prefill = attn_metadata.prefill.seq_lens
# This path needs to be enabled with VLLM_KV_CACHE_LAYOUT = HND
assert get_kv_cache_layout() == "HND"
assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
assert is_strictly_contiguous(prefill_query)
assert is_strictly_contiguous(workspace_buffer)
assert is_strictly_contiguous(block_tables_prefill)
@@ -2380,7 +2355,7 @@ class FlashInferImpl(AttentionImpl):
# trtllm-gen needs HND layout on SM100. XQA is selected
# separately on SM90 and does not use this SM100 layout gate.
if decode_with_trtllm_gen:
assert get_kv_cache_layout() == "HND"
assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
else:
assert decode_with_xqa
assert is_strictly_contiguous(decode_query)
@@ -2426,7 +2401,7 @@ class FlashInferImpl(AttentionImpl):
window_left=self.window_left,
out=output[:num_decode_tokens],
sinks=self.sinks,
kv_layout=get_kv_cache_layout(),
kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
q_len_per_req=q_len_per_req,
mask=attn_metadata.decode.mask,
q_cu_seq_lens=attn_metadata.decode.q_cu_seq_lens,
@@ -2499,7 +2474,7 @@ class FlashInferImpl(AttentionImpl):
sinks=self.sinks,
o_sf_scale=self.o_sf_scale,
out=out,
kv_layout=get_kv_cache_layout(),
kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
backend=attn_metadata.decode.kernel.value,
q_len_per_req=q_len_per_req,
kv_cache_sf=(
+11 -20
View File
@@ -43,7 +43,11 @@ from vllm.v1.attention.backend import (
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.kv_cache_interface import AttentionSpec, EncoderOnlyAttentionSpec
from vllm.v1.kv_cache_interface import (
AttentionSpec,
EncoderOnlyAttentionSpec,
KVCacheLayout,
)
logger = init_logger(__name__)
@@ -118,6 +122,12 @@ class FlexAttentionBackend(AttentionBackend):
def supports_batch_invariance(cls) -> bool:
return True
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
# Flex flattens the (B, N) block/token axes into a single token dim, which
# only LBNHC's strides allow as a zero-copy view of the layer cache.
return (KVCacheLayout.LBNHC,)
@classmethod
def supports_mm_prefix(cls) -> bool:
"""FlexAttention supports full attention for image tokens."""
@@ -127,25 +137,6 @@ class FlexAttentionBackend(AttentionBackend):
def get_impl_cls() -> type["FlexAttentionImpl"]:
return FlexAttentionImpl
@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, ...]:
# K and V are packed into the content dim: logical (B, H, N, 2*hs).
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 3, 2, 4)
return (0, 2, 1, 3)
@staticmethod
def get_builder_cls() -> type["FlexAttentionMetadataBuilder"]:
return FlexAttentionMetadataBuilder
+19 -34
View File
@@ -30,10 +30,9 @@ from vllm.v1.attention.backend import (
MultipleOf,
)
from vllm.v1.attention.backends.utils import (
KVCacheLayoutType,
split_decodes_and_prefills,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout, KVCacheSpec
logger = init_logger(__name__)
@@ -265,7 +264,7 @@ class HpcAttnMetadataBuilder(AttentionMetadataBuilder[HpcAttnMetadata]):
class HpcAttentionBackend(AttentionBackend):
"""HPC attention backend (pure attention, no RoPE/Norm).
KV cache layout: NHD (num_blocks, 2, block_size, num_kv_heads, head_size).
KV cache layout: LBNHC (num_blocks, num_kv_heads, block_size, 2 * head_size).
"""
accept_output_buffer: bool = True
@@ -298,24 +297,6 @@ class HpcAttentionBackend(AttentionBackend):
def get_builder_cls() -> type["HpcAttnMetadataBuilder"]:
return HpcAttnMetadataBuilder
@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, 2, block_size, num_kv_heads, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 2, 3, 4, 5)
return (0, 1, 2, 3, 4)
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [128]
@@ -331,8 +312,8 @@ class HpcAttentionBackend(AttentionBackend):
return kv_cache_dtype in cls.supported_kv_cache_dtypes
@classmethod
def get_required_kv_cache_layout(cls) -> KVCacheLayoutType | None:
return "NHD"
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
return (KVCacheLayout.LBNHC,)
class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
@@ -452,6 +433,9 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
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
@@ -466,8 +450,8 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
torch.ops._C_cache_ops.reshape_and_cache_flash(
key,
value,
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
attn_metadata.slot_mapping,
self.kv_cache_dtype,
layer._k_scale,
@@ -485,7 +469,8 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
f" (layer={getattr(layer, 'layer_name', '?')})"
)
torch_dtype = _get_fp8_dtype_for_kv_cache(self.kv_cache_dtype)
kv_cache = kv_cache.view(torch_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)
@@ -508,8 +493,8 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
if self.use_fp8:
hpc.attention_with_kvcache_prefill_fp8(
q_prefill,
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
hpc_prefill_q_scale,
k_scale,
v_scale,
@@ -523,8 +508,8 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
else:
hpc.attention_with_kvcache_prefill_bf16(
q_prefill,
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
cu_seqlens_prefill,
block_table_prefill,
seq_lens_prefill,
@@ -545,8 +530,8 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
if self.use_fp8:
hpc.attention_decode_fp8(
q_decode,
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
block_table_decode,
num_seq_kvcache,
hpc_decode_q_scale,
@@ -575,8 +560,8 @@ class HpcAttentionImpl(AttentionImpl[HpcAttnMetadata]):
)
hpc.attention_decode_bf16(
q_decode,
kv_cache[:, 0],
kv_cache[:, 1],
key_cache,
value_cache,
block_table_decode,
num_seq_kvcache,
mtp=mtp,
@@ -49,14 +49,6 @@ class CutlassMLABackend(MLACommonBackend):
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [128]
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 2, 3)
return (0, 1, 2)
@staticmethod
def get_name() -> str:
return "CUTLASS_MLA"
@@ -52,14 +52,6 @@ class FlashAttnMLABackend(MLACommonBackend):
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [MultipleOf(16)]
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 2, 3)
return (0, 1, 2)
@staticmethod
def get_name() -> str:
return "FLASH_ATTN_MLA"
@@ -24,6 +24,7 @@ from vllm.v1.attention.backend import (
)
from vllm.v1.attention.backends.fa_utils import flash_attn_supports_mla
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
)
from vllm.v1.kv_cache_interface import AttentionSpec
@@ -103,16 +104,6 @@ class FlashAttnMLASparseBackend(AttentionBackend):
return "FlashAttention MLA Sparse requires model with index_topk"
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)
@dataclass
class FlashAttnMLASparseMetadata(AttentionMetadata):
@@ -223,11 +214,15 @@ class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
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, valid_counts = 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_valid_counts=True,
)
@@ -235,13 +230,8 @@ class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
cu_seqlens_q = torch.arange(
0, num_actual_toks + 1, dtype=torch.int32, device=q_rope.device
)
kv_cache = kv_c_and_k_pe_cache.view(
-1, attn_metadata.block_size, self.head_size
)
k_cache = kv_cache[:, :, self.kv_lora_rank :].view(
-1, 1, 1, self.qk_rope_head_dim
)
v_cache = kv_cache[:, :, : self.kv_lora_rank].view(-1, 1, 1, self.kv_lora_rank)
k_cache = kv_rows[:, self.kv_lora_rank :].unsqueeze(1).unsqueeze(1)
v_cache = kv_rows[:, : self.kv_lora_rank].unsqueeze(1).unsqueeze(1)
out = flash_attn_varlen_func(
q=q_rope,
@@ -28,7 +28,6 @@ from vllm.v1.attention.backend import (
AttentionType,
MultipleOf,
)
from vllm.v1.attention.backends.utils import KVCacheLayoutType
logger = init_logger(__name__)
@@ -133,14 +132,6 @@ class FlashInferMLABackend(MLACommonBackend):
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [32, 64]
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 2, 3)
return (0, 1, 2)
@staticmethod
def get_name() -> str:
return "FLASHINFER_MLA"
@@ -194,10 +185,6 @@ class FlashInferMLABackend(MLACommonBackend):
)
return None
@classmethod
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
return "HND"
class FlashInferMLAImpl(MLACommonImpl[MLACommonMetadata]):
can_return_lse_for_decode: bool = True
@@ -31,7 +31,6 @@ from vllm.v1.attention.backends.mla.sparse_utils import (
triton_convert_req_index_to_global_index,
triton_filter_and_convert_dcp_index,
)
from vllm.v1.attention.backends.utils import KVCacheLayoutType
from vllm.v1.kv_cache_interface import AttentionSpec
if TYPE_CHECKING:
@@ -123,20 +122,6 @@ class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase):
return "FlashInfer MLA Sparse requires model with index_topk config"
return None
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int, # assumed to be 1 for MLA
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
return (num_blocks, block_size, head_size)
@classmethod
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
return "HND"
class FlashInferMLASparseSM120Backend(_FlashInferMLASparseBackendBase):
"""FlashInfer sparse MLA backend for SM120."""
@@ -216,23 +201,6 @@ class FlashInferMLASparseSM120Backend(_FlashInferMLASparseBackendBase):
)
return None
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int, # assumed to be 1 for MLA
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
if cache_dtype_str in ("auto", "fp8", "fp8_e4m3", "fp8_ds_mla"):
# fp8_ds_mla packed layout: 512 NoPE + 16 scales + 128 RoPE.
return (num_blocks, block_size, 656)
return (num_blocks, block_size, head_size)
@classmethod
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
return None
@dataclass
class FlashInferMLASparseMetadata(AttentionMetadata):
@@ -58,14 +58,6 @@ class FlashMLABackend(MLACommonBackend):
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [64]
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 2, 3)
return (0, 1, 2)
@staticmethod
def get_name() -> str:
return "FLASHMLA"
@@ -27,6 +27,7 @@ from vllm.v1.attention.backend import (
MultipleOf,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
triton_filter_and_convert_dcp_index,
)
@@ -128,20 +129,6 @@ class FlashMLASparseBackend(AttentionBackend):
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major in [9, 10]
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int, # assumed to be 1 for MLA
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
if cache_dtype_str == "fp8_ds_mla":
# V3.2 main MLA: 656-byte custom storage format. See module docstring.
return (num_blocks, block_size, 656)
else:
return (num_blocks, block_size, head_size)
@dataclass
class FlashMLASparseMetadata(AttentionMetadata):
@@ -643,18 +630,22 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
# Convert per-request indices to global slots (decode) or workspace
# offsets (prefill). req_id_per_token covers the whole batch; slice it
# to the MQA tokens (q may exclude prefill tokens routed to dense MHA).
kv_rows, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
topk_indices, topk_length = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
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,
)
return self._bf16_flash_mla_kernel(
q,
kv_c_and_k_pe_cache,
kv_rows,
topk_indices,
topk_length,
)
+13 -26
View File
@@ -36,7 +36,7 @@ from vllm.v1.attention.backends.utils import (
get_dcp_local_seq_lens,
split_decodes_and_prefills,
)
from vllm.v1.kv_cache_interface import KVCacheSpec, MLAAttentionSpec
from vllm.v1.kv_cache_interface import KVCacheLayout, KVCacheSpec, MLAAttentionSpec
logger = init_logger(__name__)
@@ -179,34 +179,18 @@ class DeepseekV32IndexerBackend(AttentionBackend):
def get_builder_cls() -> type["DeepseekV32IndexerMetadataBuilder"]:
return DeepseekV32IndexerMetadataBuilder
@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, ...]:
assert num_kv_heads == 1
return (num_blocks, block_size, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
# DeepseekV32Indexer kernels do not support cross-layer
# KV cache layout. Identity permutation keeps num_layers
# first, signaling incompatibility.
return (0, 1, 2, 3)
return (0, 1, 2)
class DeepseekV4IndexerBackend(DeepseekV32IndexerBackend):
@staticmethod
def get_name() -> str:
return "DEEPSEEK_V4_INDEXER"
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
# DeepSeek-V4 packs the indexer pages beside the MLA latent pages inside
# each block, so the layer dim must sit inside the block dim.
return (KVCacheLayout.BLHNC, KVCacheLayout.BLNHC)
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [256]
@@ -638,7 +622,10 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
self.compress_ratio = 1
# Get compress_ratio for DeepseekV4 support
if isinstance(self.kv_cache_spec, MLAAttentionSpec):
self.compress_ratio = self.kv_cache_spec.compress_ratio
# MLA compression is a whole number of tokens per state (fractions
# are whisper block pooling and never reach MLA).
assert isinstance(self.kv_cache_spec.tokens_per_state, int)
self.compress_ratio = self.kv_cache_spec.tokens_per_state
if self.dcp_world_size > 1 and self.compress_ratio > 1:
raise NotImplementedError(
"DCP is not supported with sparse indexer KV compression "
@@ -885,7 +872,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
query_start_loc,
seq_lens,
block_table,
self.kv_cache_spec.storage_block_size,
self.kv_cache_spec.num_states,
self.compress_ratio,
out=self.compressed_slot_mapping_buffer,
)
@@ -1053,7 +1040,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
if current_platform.is_cuda() and has_deep_gemm():
metadata = get_paged_mqa_logits_metadata(
seq_lens,
self.kv_cache_spec.storage_block_size,
self.kv_cache_spec.num_states,
self.num_sms,
indices=decode_indices,
)
@@ -293,16 +293,6 @@ class ROCMAiterMLASparseBackend(AttentionBackend):
def get_impl_cls() -> type["ROCMAiterMLASparseImpl"]:
return ROCMAiterMLASparseImpl
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int, # assumed to be 1 for MLA
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
return (num_blocks, block_size, head_size)
@classmethod
def is_mla(cls) -> bool:
return True
+6 -25
View File
@@ -89,6 +89,10 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
# contiguous full-cache layout.
assert self.dtype in (torch.uint8, torch.bfloat16, torch.float8_e4m3fn)
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
# [B, H=1, N, C] -> [B, N, C]
self.kv_cache = kv_cache.squeeze(1)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
# fp8_ds_mla's UE8M0 paged layout needs 576B alignment; contiguous
# bf16/fp8 cache uses the natural element-size page.
@@ -141,30 +145,6 @@ class DeepseekSparseSWABackend(AttentionBackend):
return DeepseekV4ROCMAiterSparseSWAMetadataBuilder
return DeepseekSparseSWAMetadataBuilder
@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, ...]:
assert num_kv_heads == 1
if cache_dtype_str == "fp8_ds_mla":
# DeepseekV4 SWA: 584B per token (448 NoPE + 128 RoPE + 8 fp8 scale).
# head_size passed in is the semantic head_dim (512).
return (num_blocks, block_size, 584)
else:
return (num_blocks, block_size, head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (0, 1, 2, 3)
return (0, 1, 2)
@dataclass
class DeepseekSparseSWAMetadata:
@@ -417,7 +397,8 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
assert isinstance(self.kv_cache_spec, SlidingWindowMLASpec | MLAAttentionSpec)
mla_spec = cast(SlidingWindowMLASpec | MLAAttentionSpec, self.kv_cache_spec)
self.head_size = mla_spec.head_size # Already considered quantization.
self.compress_ratio = mla_spec.compress_ratio
assert isinstance(mla_spec.tokens_per_state, int)
self.compress_ratio = mla_spec.tokens_per_state
self.block_size = mla_spec.block_size
self.max_model_len = self.vllm_config.model_config.max_model_len
self.max_num_batched_tokens = (
+27 -1
View File
@@ -7,6 +7,28 @@ import torch
from vllm.triton_utils import tl, triton
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
@triton.jit
def _convert_req_index_to_global_index_kernel(
@@ -20,6 +42,7 @@ def _convert_req_index_to_global_index_kernel(
# shapes (compile-time where possible)
max_num_blocks_per_req: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
BLOCK_STRIDE_ROWS: tl.constexpr,
BLOCK_N: tl.constexpr, # tile width along columns
HAS_PREFILL: tl.constexpr,
COUNT_VALID: tl.constexpr, # whether to count valid indices
@@ -86,7 +109,7 @@ def _convert_req_index_to_global_index_kernel(
bt_ptr = block_table_ptr + req * bt_stride0 + block_id * bt_stride1
is_invalid_tok |= ~valid_block | is_remote
base = tl.load(bt_ptr, mask=valid_block & ~is_prefill & ~is_remote, other=0)
out_val = base * BLOCK_SIZE + inblock_off
out_val = base * BLOCK_STRIDE_ROWS + inblock_off
# Override with prefill output if prefill is enabled
if HAS_PREFILL:
@@ -156,6 +179,7 @@ def triton_convert_req_index_to_global_index(
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,
@@ -249,6 +273,7 @@ def triton_convert_req_index_to_global_index(
# shapes / constexprs
max_num_blocks_per_req,
BLOCK_SIZE,
BLOCK_STRIDE_ROWS if BLOCK_STRIDE_ROWS is not None else BLOCK_SIZE,
block_n,
HAS_PREFILL_WORKSPACE,
return_valid_counts,
@@ -365,6 +390,7 @@ def triton_filter_and_convert_dcp_index(
None,
max_num_blocks_per_req,
BLOCK_SIZE,
BLOCK_SIZE, # dense caches on the DCP path
block_n,
False, # HAS_PREFILL
count_valid,
@@ -23,7 +23,6 @@ from vllm.v1.attention.backend import (
AttentionType,
MultipleOf,
)
from vllm.v1.attention.backends.utils import KVCacheLayoutType
if TYPE_CHECKING:
from vllm.config import VllmConfig
@@ -152,10 +151,6 @@ class TokenspeedMLABackend(MLACommonBackend):
)
return None
@classmethod
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
return "HND"
class TokenspeedMLAImpl(MLACommonImpl[MLACommonMetadata]):
can_return_lse_for_decode: bool = True
@@ -121,14 +121,6 @@ class TritonMLABackend(MLACommonBackend):
return True
return block_size % 16 == 0
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
if include_num_layers_dimension:
return (1, 0, 2, 3)
return (0, 1, 2)
@staticmethod
def get_name() -> str:
return "TRITON_MLA"
@@ -23,7 +23,8 @@ from vllm.v1.attention.backend import (
CommonAttentionMetadata,
MLAAttentionImpl,
)
from vllm.v1.attention.backends.mla.flashmla_sparse import (
from vllm.v1.attention.backends.mla.sparse_utils import (
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
@@ -66,16 +67,6 @@ class XPUMLASparseBackend(AttentionBackend):
def is_sparse(cls) -> bool:
return True
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int, # assumed to be 1 for MLA
head_size: int,
cache_dtype_str: str = "auto",
) -> tuple[int, ...]:
return (num_blocks, block_size, head_size)
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
return [576]
@@ -249,16 +240,18 @@ class XPUMLASparseImpl(MLAAttentionImpl[XPUMLASparseMetadata]):
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_c_and_k_pe_cache, topk_indices_global, attn_metadata
)
attn_out = self._forward_bf16_kv(q, kv_rows, topk_indices_global, attn_metadata)
return attn_out, None
+16 -12
View File
@@ -31,7 +31,7 @@ from vllm.v1.attention.backends.utils import (
split_decodes_prefills_and_extends,
)
from vllm.v1.attention.ops.merge_attn_states import merge_attn_states
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
_PARTITION_SIZE_ROCM = 256
_CP_TOKENS_PER_ITER_ROCM = 32 * 1024
@@ -761,18 +761,22 @@ class AiterFlashAttentionBackend(AttentionBackend):
def get_builder_cls() -> type["AiterFlashAttentionMetadataBuilder"]:
return AiterFlashAttentionMetadataBuilder
@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, ...]:
if block_size % 16 != 0:
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
"""Validate the block size the ROCm gather kernels require."""
# 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.")
# K and V are packed into the content dim: logical (B, H, N, 2*hs).
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
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.
return (KVCacheLayout.LBHNC, KVCacheLayout.LHBNC)
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
@@ -22,6 +22,7 @@ from vllm.v1.attention.backends.rocm_attn import (
RocmAttentionMetadata,
RocmAttentionMetadataBuilder,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
logger = init_logger(__name__)
@@ -77,18 +78,23 @@ class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
def get_impl_cls() -> type["RocmAiterUnifiedAttentionImpl"]:
return RocmAiterUnifiedAttentionImpl
@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, ...]:
if block_size % 16 != 0:
@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.")
# K and V are packed into the content dim: logical (B, H, N, 2*hs).
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
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.
return (KVCacheLayout.LBHNC, KVCacheLayout.LHBNC)
@staticmethod
def use_cascade_attention(*args, **kwargs) -> bool:
+34 -19
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention layer with PagedAttention and Triton prefix prefill."""
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import ClassVar
import torch
@@ -16,7 +16,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8StaticTensorSym,
)
from vllm.platforms import current_platform
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.utils.torch_utils import get_dtype_size, is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
@@ -35,7 +35,7 @@ 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
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
logger = init_logger(__name__)
@@ -241,17 +241,30 @@ class RocmAttentionBackend(AttentionBackend):
AttentionType.ENCODER_ONLY,
)
@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, ...]:
if block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
return (2, num_blocks, block_size, num_kv_heads, head_size)
@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 use_cascade_attention(*args, **kwargs) -> bool:
@@ -380,8 +393,8 @@ class RocmAttentionImpl(AttentionImpl):
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 =
[2, num_blocks, block_size, 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.
Returns:
shape = [num_tokens, num_heads * head_size]
@@ -419,8 +432,10 @@ class RocmAttentionImpl(AttentionImpl):
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, self.num_kv_heads, self.head_size
kv_cache.transpose(0, 1), self.num_kv_heads, self.head_size
)
if is_quantized_kv_cache(self.kv_cache_dtype):
@@ -477,7 +492,7 @@ class RocmAttentionImpl(AttentionImpl):
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return
key_cache, value_cache = PagedAttention.split_kv_cache(
kv_cache, self.num_kv_heads, self.head_size
kv_cache.transpose(0, 1), self.num_kv_heads, self.head_size
)
# Reshape the input keys and values and store them in the cache.
@@ -532,7 +547,7 @@ class RocmAttentionImpl(AttentionImpl):
if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER):
return
key_cache, value_cache = PagedAttention.split_kv_cache(
kv_cache,
kv_cache.transpose(0, 1),
layer.num_kv_heads, # type: ignore[attr-defined]
layer.head_size, # type: ignore[attr-defined]
)
-58
View File
@@ -32,7 +32,6 @@ from vllm.v1.attention.backend import (
)
from vllm.v1.attention.backends.utils import (
compute_mm_prefix_range_tensor,
get_kv_cache_layout,
get_num_attention_heads_from_layers,
)
from vllm.v1.attention.ops.triton_prefill_attention import context_attention_fwd
@@ -45,7 +44,6 @@ from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVQuantMode,
get_kv_quant_mode,
kv_cache_uses_per_token_head_scales,
)
logger = init_logger(__name__)
@@ -337,62 +335,6 @@ class TritonAttentionBackend(AttentionBackend):
def get_impl_cls() -> type["TritonAttentionImpl"]:
return TritonAttentionImpl
@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, ...]:
if block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
# K and V are packed into the content dim: logical (B, H, N, 2*hs).
if kv_cache_uses_per_token_head_scales(cache_dtype_str):
# Pad the head dim by sizeof(float32)/sizeof(cache_dtype) so the
# per-(token, head) scale fits inline after the quantized data;
# the backend extracts data[:head_size] and scale[head_size:] via
# typed views (see _ensure_scale_caches). INT4 packs two values
# per byte, so the data occupies only head_size // 2 bytes.
from vllm.utils.torch_utils import (
STR_DTYPE_TO_TORCH_DTYPE,
get_dtype_size,
)
cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype_str]
scale_pad = get_dtype_size(torch.float32) // get_dtype_size(cache_dtype)
if get_kv_quant_mode(cache_dtype_str) == KVQuantMode.INT4_PER_TOKEN_HEAD:
data_head_size = head_size // 2
else:
data_head_size = head_size
padded_hs = data_head_size + scale_pad
return (num_blocks, num_kv_heads, block_size, 2 * padded_hs)
return (num_blocks, num_kv_heads, block_size, 2 * head_size)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# `stride_order` indicates the permutation that gets us from
# `get_kv_cache_shape` (logical (B, H, N, 2*hs)) to the actual memory
# layout we want.
cache_layout = get_kv_cache_layout()
if cache_layout == "NHD" and include_num_layers_dimension:
# (num_blocks, num_layers, block_size, num_kv_heads, 2*head_size)
return (1, 0, 3, 2, 4)
elif cache_layout == "NHD":
# (num_blocks, block_size, num_kv_heads, 2*head_size)
stride_order = (0, 2, 1, 3)
elif cache_layout == "HND" and include_num_layers_dimension:
# (num_blocks, num_kv_heads, num_layers, block_size, 2*head_size)
return (1, 2, 0, 3, 4)
elif cache_layout == "HND":
# (num_blocks, num_kv_heads, block_size, 2*head_size)
stride_order = (0, 1, 2, 3)
else:
raise ValueError(f"Unknown cache layout: {cache_layout}")
return stride_order
@staticmethod
def use_cascade_attention(*args, **kwargs) -> bool:
return False
@@ -23,7 +23,6 @@ from vllm.v1.attention.backends.triton_attn import (
TritonAttentionMetadata,
TritonAttentionMetadataBuilder,
)
from vllm.v1.attention.backends.utils import get_kv_cache_layout
from vllm.v1.attention.ops.triton_reshape_and_cache_flash import (
triton_reshape_and_cache_flash_diffkv,
)
@@ -93,48 +92,6 @@ class TritonAttentionDiffKVBackend(TritonAttentionBackend):
def get_builder_cls() -> type["TritonAttentionDiffKVMetadataBuilder"]:
return TritonAttentionDiffKVMetadataBuilder
@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, ...]:
if block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
# Logical (blocks-first, head-major) layout: K and V (with their
# different head sizes) packed in the content dim.
return (
num_blocks,
num_kv_heads,
block_size,
head_size + TritonAttentionDiffKVBackend.head_size_v,
)
@staticmethod
def get_kv_cache_stride_order(
include_num_layers_dimension: bool = False,
) -> tuple[int, ...]:
# `stride_order` indicates the permutation that gets us from
# `get_kv_cache_shape` (logical (B, H, N, C_k+C_v)) to the actual
# memory layout we want.
cache_layout = get_kv_cache_layout()
if cache_layout == "NHD" and include_num_layers_dimension:
# (num_blocks, num_layers, block_size, num_kv_heads, C_k+C_v)
return (1, 0, 3, 2, 4)
elif cache_layout == "NHD":
# (num_blocks, block_size, num_kv_heads, C_k+C_v)
return (0, 2, 1, 3)
elif cache_layout == "HND" and include_num_layers_dimension:
# (num_blocks, num_kv_heads, num_layers, block_size, C_k+C_v)
return (1, 2, 0, 3, 4)
elif cache_layout == "HND":
# (num_blocks, num_kv_heads, block_size, C_k+C_v)
return (0, 1, 2, 3)
else:
raise ValueError(f"Unknown cache layout format {cache_layout}.")
@classmethod
def supports_head_size(cls, head_size: int) -> bool:
# DiffKV K head sizes (e.g. 192 for MiMo-V2.5) need to be allowed.
+5 -34
View File
@@ -64,7 +64,7 @@ from vllm.v1.attention.ops.triton_turboquant_decode import (
triton_turboquant_decode_attention,
)
from vllm.v1.attention.ops.triton_turboquant_store import triton_turboquant_store
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
from vllm.v1.worker.workspace import (
current_workspace_manager,
is_workspace_manager_initialized,
@@ -156,6 +156,10 @@ class TurboQuantAttentionBackend(AttentionBackend):
def get_name() -> str:
return "TURBOQUANT"
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
return (KVCacheLayout.LBNHC,)
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [16, 32, 64, 128]
@@ -176,39 +180,6 @@ class TurboQuantAttentionBackend(AttentionBackend):
def get_builder_cls() -> type["TurboQuantMetadataBuilder"]:
return TurboQuantMetadataBuilder
@staticmethod
def get_kv_cache_shape(
num_blocks: int,
block_size: int,
num_kv_heads: int,
head_size: int,
cache_dtype_str: str = "turboquant_4bit_nc",
) -> tuple[int, ...]:
"""Combined K+V cache shape — no leading 2 dimension.
Standard attention backends use (2, num_blocks, block_size, num_kv_heads,
head_dim) with a leading 2 to separate K and V. TurboQuant packs K+V
into a single interleaved slot per head per position. The logical
(blocks-first, head-major) shape is:
(num_blocks, num_kv_heads, block_size, slot_size_aligned)
Each slot = [key_packed | value_packed | padding].
This is safe because TQ has its own get_kv_cache_shape override and
never shares cache tensors with other backends. Layers that fall back
to native dtype via kv_cache_dtype_skip_layers get their own
standard-shaped cache allocation.
head_size is the model's real head_dim. slot_size_aligned is computed
from the TQ config to ensure correct cache allocation for all head dims.
"""
from vllm.model_executor.layers.quantization.turboquant.config import (
TurboQuantConfig,
)
tq_config = TurboQuantConfig.from_cache_dtype(cache_dtype_str, head_size)
return (num_blocks, num_kv_heads, block_size, tq_config.slot_size_aligned)
@classmethod
def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool:
if kv_cache_dtype is None:
+152 -44
View File
@@ -1,26 +1,24 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
import math
from collections.abc import Callable
from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field, fields, make_dataclass
from typing import (
TYPE_CHECKING,
Any,
Literal,
Protocol,
cast,
get_args,
)
import numpy as np
import torch
from typing_extensions import runtime_checkable
from vllm.config import VllmConfig, get_layers_from_vllm_config
from vllm.config import CacheConfig, VllmConfig, get_layers_from_vllm_config
from vllm.config.cache import _layout_from_name
from vllm.utils.math_utils import cdiv
from vllm.utils.torch_utils import PIN_MEMORY, async_tensor_h2d, np_to_pinned_tensor
from vllm.v1.kv_cache_interface import KVCacheSpec, MambaSpec
from vllm.v1.kv_cache_interface import KVCacheLayout, KVCacheSpec, MambaSpec
if TYPE_CHECKING:
from vllm.v1.core.sched.output import SchedulerOutput
@@ -41,8 +39,6 @@ from vllm.v1.attention.backend import (
)
logger = init_logger(__name__)
KVCacheLayoutType = Literal["NHD", "HND"]
_KV_CACHE_LAYOUT_OVERRIDE: KVCacheLayoutType | None = None
PAD_SLOT_ID = -1
NULL_BLOCK_ID = 0
@@ -155,44 +151,159 @@ def fill_mm_prefix_query_ranges(
return num_actual_tokens
def is_valid_kv_cache_layout(value: str) -> bool:
return value in get_args(KVCacheLayoutType)
_FLASHINFER_LAYOUT_NAMES = {
"LBNHC": "NHD",
"LBHNC": "HND",
"BLHNC": "HND",
"BLNHC": "NHD",
"BHLNC": "HND",
}
@functools.lru_cache
def get_kv_cache_layout():
# Format specified by the code.
global _KV_CACHE_LAYOUT_OVERRIDE
def get_flashinfer_layout_string(layout: KVCacheLayout) -> str:
"""Return the layout name in FlashInfer's convention (NHD/HND)."""
assert layout.name in _FLASHINFER_LAYOUT_NAMES, (
f"KV cache layout {layout.name} has no FlashInfer equivalent; FlashInfer "
"rejects it in supported_kv_cache_layouts"
)
return _FLASHINFER_LAYOUT_NAMES[layout.name]
cache_layout: Literal["NHD", "HND"] | None = None
if _KV_CACHE_LAYOUT_OVERRIDE is not None:
cache_layout = _KV_CACHE_LAYOUT_OVERRIDE
logger.debug_once(
"`_KV_CACHE_LAYOUT_OVERRIDE` variable detected. "
"Setting KV cache layout to %s.",
cache_layout,
# Preference order when no backend declares a supported set; LBNHC (NHD)
# first to match main's default.
_DEFAULT_LAYOUT_PREFERENCE = (
KVCacheLayout.LBNHC,
KVCacheLayout.LBHNC,
KVCacheLayout.BLNHC,
KVCacheLayout.BLHNC,
KVCacheLayout.BHLNC,
KVCacheLayout.LHBNC,
)
def _layout_names(layouts: Iterable[KVCacheLayout]) -> list[str]:
return [layout.name for layout in layouts]
def get_supported_kv_cache_layouts(
backends: Iterable[type[AttentionBackend]],
) -> list[KVCacheLayout]:
"""Layouts every one of the worker's backends supports, most preferred first.
Every backend declares the layouts its kernels support, most preferred first
(``supported_kv_cache_layouts``), or None when any layout works; workers where
nothing declares follow the default preference. Identical declarations keep
their order; otherwise the layout the most backends put first wins, ties
keeping the enum order. An empty intersection is a hard error.
"""
supported_layouts_lists: list[Sequence[KVCacheLayout]] = [
layouts
for backend in backends
if (layouts := backend.supported_kv_cache_layouts()) is not None
] or [_DEFAULT_LAYOUT_PREFERENCE]
first = supported_layouts_lists[0]
if all(layouts == first for layouts in supported_layouts_lists[1:]):
return list(first)
priorities: dict[KVCacheLayout, int] = defaultdict(int)
for preferred_layout, *_ in supported_layouts_lists:
priorities[preferred_layout] += 1
supported_layouts = set.intersection(*map(set, supported_layouts_lists))
candidates = sorted(
(layout for layout in KVCacheLayout if layout in supported_layouts),
key=lambda layout: priorities[layout],
reverse=True,
)
if not candidates:
raise ValueError(
"No KV cache layout satisfies every supported set: "
f"{list(map(_layout_names, supported_layouts_lists))}."
)
return cache_layout
return candidates
# Format specified by the user.
cache_layout = envs.VLLM_KV_CACHE_LAYOUT
# When neither the user nor the override specified a layout, get default
if cache_layout is None:
cache_layout = get_kv_connector_cache_layout()
def record_kv_cache_layout(cache_config: CacheConfig, layout_name: str) -> None:
"""Adopt a layout resolved elsewhere (the engine core) in this process."""
layout = _layout_from_name(layout_name)
existing = cache_config.kv_cache_layout
if existing is not None and existing != layout.name:
raise ValueError(
f"KV cache layout is already resolved to {existing}; "
f"cannot change it to {layout.name}."
)
cache_config.kv_cache_layout = layout.name
def resolve_kv_cache_layout(
vllm_config: VllmConfig,
supported_layouts: list[list[str]],
kv_cache_specs: Iterable[KVCacheSpec] | None = None,
) -> KVCacheLayout:
"""Resolve one KV cache layout for the whole model.
Runs once in the engine core. Every worker reports the layouts its backends
support, most preferred first (``get_supported_kv_cache_layouts``); all
ranks run the same backends, so their lists must agree. Specs mixing HNC
shapes narrow the candidates to block-compact layouts. An explicit
``VLLM_KV_CACHE_LAYOUT`` must be one of the candidates or resolution fails,
with the legacy ``NHD``/``HND`` names as aliases for ``LBNHC``/``LBHNC``; the
connector's preference is used when compatible and dropped with a warning
otherwise. A layout already present on ``cache_config`` wins outright, and
the result is recorded there (see ``CacheConfig.kv_cache_layout``); it
reaches workers through the ``set_kv_cache_layout`` RPC and
``KVCacheConfig.kv_cache_layout``.
"""
cache_config = vllm_config.cache_config
if cache_config.kv_cache_layout is not None:
return cache_config.get_resolved_kv_cache_layout()
assert supported_layouts and all(supported_layouts), (
"No worker reported supported KV cache layouts."
)
assert all(names == supported_layouts[0] for names in supported_layouts[1:]), (
f"Workers disagree on supported KV cache layouts: {supported_layouts}."
)
candidates = [_layout_from_name(name) for name in supported_layouts[0]]
# A block-compact layout means the block is densely packed in memory, so any mix of
# specs can re-interpret HNC with different sizes as long as the total number of
# bytes is the same. If not block-compact, each spec must agree on HNC to alias
# the same page (this aliasing is done by the Hybrid Memory Allocator, HMA).
hnc_shapes = {
(spec.num_heads, spec.num_states, spec.page_size_bytes)
for spec in kv_cache_specs or ()
}
if len(hnc_shapes) > 1:
candidates = [m for m in candidates if m.is_block_compact]
if not candidates:
raise ValueError(
"Specs with mixed HNC shapes need a block-compact layout, but "
f"none is in every supported set: {supported_layouts}."
)
if (requested := envs.VLLM_KV_CACHE_LAYOUT) is not None:
layout = _layout_from_name(requested)
if layout not in candidates:
raise ValueError(
f"VLLM_KV_CACHE_LAYOUT={requested} does not satisfy every "
f"supported set; valid layouts: {_layout_names(candidates)}."
)
elif (connector := get_kv_connector_cache_layout(vllm_config)) is not None:
layout = _layout_from_name(connector)
if layout not in candidates:
logger.warning_once(
f"KV connector cache layout {connector} does not satisfy every "
f"supported set; valid layouts: {_layout_names(candidates)}. "
f"Using {candidates[0].name} instead."
)
layout = candidates[0]
else:
assert is_valid_kv_cache_layout(cache_layout)
logger.info_once(
"`VLLM_KV_CACHE_LAYOUT` environment variable "
"detected. Setting KV cache layout to %s.",
cache_layout,
)
return cache_layout
layout = candidates[0]
def set_kv_cache_layout(cache_layout: KVCacheLayoutType | None):
global _KV_CACHE_LAYOUT_OVERRIDE
_KV_CACHE_LAYOUT_OVERRIDE = cache_layout
get_kv_cache_layout.cache_clear()
logger.info_once("Using %s KV cache layout.", layout.name)
cache_config.kv_cache_layout = layout.name
return layout
@dataclass
@@ -264,10 +375,7 @@ def get_num_attention_heads_from_layers(
)
if not attn_layers:
return None
heads = {
cast(Any, getattr(layer, "impl", layer)).num_heads
for layer in attn_layers.values()
}
heads = {layer.impl.num_heads for layer in attn_layers.values()}
assert len(heads) == 1, (
f"All layers in one attention group must share num_heads; "
f"got {heads} for {layer_names}."
+2 -16
View File
@@ -8,7 +8,6 @@ import torch
import vllm.envs as envs
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm.v1.attention.backend import AttentionBackend, AttentionType
from vllm.v1.attention.backends.registry import (
@@ -18,8 +17,6 @@ from vllm.v1.attention.backends.registry import (
if TYPE_CHECKING:
from vllm.v1.kv_cache_interface import KVCacheSpecKind
logger = init_logger(__name__)
class AttentionSelectorConfig(NamedTuple):
head_size: int
@@ -185,6 +182,8 @@ def get_attn_backend(
)
backend = attention_config.backend_per_kind.get(kind.value, backend)
# The KV cache layout is resolved across all of the model's backends at once
# in get_kv_cache_spec(); a single selection cannot see its peers.
return _cached_get_attn_backend(
backend=backend,
attn_selector_config=attn_selector_config,
@@ -210,19 +209,6 @@ def _cached_get_attn_backend(
f"Invalid attention backend for {current_platform.device_name}"
)
backend = resolve_obj_by_qualname(attention_cls)
# Adjust kv cache layout if the selected backend requires a specific one
required_layout = backend.get_required_kv_cache_layout()
if required_layout is not None:
from vllm.v1.attention.backends.utils import set_kv_cache_layout
set_kv_cache_layout(required_layout)
logger.info_once(
"Using %s KV cache layout for %s backend.",
required_layout,
backend.get_name(),
)
return backend
+141 -217
View File
@@ -10,7 +10,7 @@ from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, replace
from functools import partial
from typing import Any, NamedTuple, NewType, TypeAlias, cast, overload
from typing import Any, NamedTuple, NewType, TypeAlias, overload
from vllm import envs
from vllm.config import VllmConfig
@@ -26,6 +26,7 @@ from vllm.v1.kv_cache_interface import (
HiddenStateCacheSpec,
KVCacheConfig,
KVCacheGroupSpec,
KVCacheLayout,
KVCacheSpec,
KVCacheTensor,
MambaSpec,
@@ -33,6 +34,7 @@ from vllm.v1.kv_cache_interface import (
SlidingWindowMLASpec,
SlidingWindowSpec,
UniformTypeKVCacheSpecs,
compute_layout_strides,
replace_as,
)
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
@@ -897,7 +899,7 @@ def check_enough_kv_cache_memory(
# of the specs since grouping may unify them in-place.
groups = get_kv_cache_groups(vllm_config, dict(kv_cache_spec))
check_memory = (
available_memory - _pool_bytes_per_block(vllm_config, groups)
available_memory - _pool_bytes_per_block(groups)
if groups
else available_memory
)
@@ -999,45 +1001,14 @@ def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int:
return num_blocks
def _pool_bytes_per_block(
vllm_config: VllmConfig, kv_cache_groups: list[KVCacheGroupSpec]
) -> int:
def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int:
"""
Bytes consumed by one block in the worker's shared KV cache pool, mirroring
the divisor used by `get_kv_cache_config_from_groups` to convert
`available_memory` into `num_blocks`. Used to compute the effective KV cache
capacity once `num_gpu_blocks_override` is applied.
"""
if len(kv_cache_groups) == 1 and isinstance(
kv_cache_groups[0].kv_cache_spec, UniformTypeKVCacheSpecs
):
return kv_cache_groups[0].kv_cache_spec.page_size_bytes
if _use_packed_kv_cache_config(vllm_config, kv_cache_groups):
block_stride, _ = _get_packed_kv_cache_layout(kv_cache_groups)
return block_stride
group_size = max(len(g.layer_names) for g in kv_cache_groups)
page_size = get_uniform_page_size([g.kv_cache_spec for g in kv_cache_groups])
return page_size * group_size
def get_num_blocks(
vllm_config: VllmConfig,
num_layers: int,
available_memory: int,
page_size: int,
) -> int:
"""
Get the number of kv cache blocks.
Args:
vllm_config: The global VllmConfig
num_layers: The number of layers
available_memory: Memory available for KV cache in bytes.
page_size: The page size of the KV cache.
"""
num_blocks = int(available_memory // page_size // num_layers)
num_blocks = max(num_blocks, 0)
return may_override_num_blocks(vllm_config, num_blocks)
return _get_kv_cache_bytes_per_block(kv_cache_groups)
def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int:
@@ -1092,11 +1063,14 @@ def unify_kv_cache_spec_page_size(
size by increasing the block size of layers with smaller page size. Two
cases cannot be unified by block size alone and pad their physical page to
the maximum instead: Mamba layers, whose page size comes from state shapes
and is independent of block size; and attention layers whose page does not
evenly divide the maximum and whose backend opts in via
``AttentionSpec.indexes_kv_by_block_stride`` (the padded page is read through
a strided view, which not every backend handles). Raise NotImplementedError
if failed to unify the page size.
and is independent of block size; and non-MLA attention layers whose page
does not evenly divide the maximum (the padded page is read through a
strided view). MLA is excluded because sparse MLA indexes the cache in
whole token rows (see ``flat_kv_row_view``), so its block stride can only
be padded by its own row-aligned ``alignment``, not to an arbitrary page
size. Raise NotImplementedError if failed to unify the page size;
``get_kv_cache_groups`` catches it to try the full-allocation fallback
(e.g. MLA next to an incompatible sliding-window draft).
Args:
kv_cache_spec: The KVCacheSpec of each attention layer in the model
@@ -1130,18 +1104,15 @@ def unify_kv_cache_spec_page_size(
ratio = max_page_size // layer_page_size
new_block_size = layer_spec.block_size * ratio
new_spec = replace(layer_spec, block_size=new_block_size)
elif (
isinstance(layer_spec, AttentionSpec)
and layer_spec.indexes_kv_by_block_stride
elif isinstance(layer_spec, AttentionSpec) and not isinstance(
layer_spec, MLAAttentionSpec
):
new_spec = replace(layer_spec, page_size_padded=max_page_size)
else:
raise NotImplementedError(
f"Layer {layer_name}: page size is not divisible by the "
"maximum page size and cannot be padded. Padding is only "
"supported for attention layers whose backend indexes KV "
"pages by the block stride (indexes_kv_by_block_stride is "
"True)."
"supported for non-MLA attention layers."
)
assert new_spec.page_size_bytes == max_page_size
new_kv_cache_spec[layer_name] = new_spec
@@ -1296,83 +1267,64 @@ def _get_kv_cache_groups_uniform_page_size(
return create_kv_cache_group_specs(kv_cache_spec, grouped_layers)
def _get_packed_kv_cache_layout(
def _get_per_layer_spec(
group: KVCacheGroupSpec,
layer_name: str,
) -> KVCacheSpec:
spec = group.kv_cache_spec
if isinstance(spec, UniformTypeKVCacheSpecs):
return spec.kv_cache_specs[layer_name]
return spec
def _get_kv_cache_bytes_per_block(
kv_cache_groups: list[KVCacheGroupSpec],
) -> tuple[int, dict[int, list[str]]]:
"""Lay out each cache group densely in one shared block slab.
A block ID is owned by one cache group at a time, so layouts from different
groups may overlap. Layers within a group remain disjoint.
"""
layers_by_offset: dict[int, list[str]] = defaultdict(list)
block_stride = 0
for group in kv_cache_groups:
spec = group.kv_cache_spec
byte_offset = 0
for layer_name in group.layer_names:
if isinstance(spec, UniformTypeKVCacheSpecs):
page_size = spec.kv_cache_specs[layer_name].page_size_bytes
else:
page_size = spec.page_size_bytes
layers_by_offset[byte_offset].append(layer_name)
byte_offset += page_size
block_stride = max(block_stride, byte_offset)
assert block_stride > 0
return block_stride, layers_by_offset
def _use_packed_kv_cache_config(
vllm_config: VllmConfig,
kv_cache_groups: list[KVCacheGroupSpec],
) -> bool:
is_dsv4 = all(
isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs)
) -> int:
"""Return the largest cache group's bytes per block."""
bytes_per_block = max(
sum(
_get_per_layer_spec(group, layer_name).page_size_bytes
for layer_name in group.layer_names
)
for group in kv_cache_groups
)
kv_transfer_config = vllm_config.kv_transfer_config
extra_config = (
kv_transfer_config.kv_connector_extra_config
if kv_transfer_config is not None
else {}
)
# NOTE: enable_cross_layers_blocks is an experimental API and subject to change with
# https://github.com/vllm-project/vllm/issues/42082
enable_cross_layers = (
str(extra_config.get("enable_cross_layers_blocks", "False")).lower() == "true"
)
return is_dsv4 or (enable_cross_layers and len(kv_cache_groups) > 1)
assert bytes_per_block > 0
return bytes_per_block
def _get_kv_cache_config_packed(
vllm_config: VllmConfig,
def validate_kv_cache_layout(
layout: KVCacheLayout,
kv_cache_groups: list[KVCacheGroupSpec],
available_memory: int,
) -> tuple[int, list[KVCacheTensor]]:
"""Plan a packed per-block KV cache tensor layout.
) -> None:
"""Validate that the resolved layout can express this model's packing.
Cache groups use dense, overlapping layouts within one block slab. Each
emitted tensor aliases the same physical backing allocation.
The layout was chosen once in the engine core from the backends' supported
sets; a backend whose model packs pages side by side (e.g. the DeepSeek-V4
indexer) declares block-outermost layouts there, so an inexpressible
layout reaching this point is an error.
"""
block_stride, layers_by_offset = _get_packed_kv_cache_layout(kv_cache_groups)
page_sizes = {
_get_per_layer_spec(group, layer_name).page_size_bytes
for group in kv_cache_groups
for layer_name in group.layer_names
}
if len(page_sizes) == 1:
# A rectangular layer dim exists; every layout can express it.
return
num_blocks = available_memory // block_stride
num_blocks = may_override_num_blocks(vllm_config, num_blocks)
total_size = block_stride * num_blocks
kv_cache_tensors: list[KVCacheTensor] = []
for byte_offset in sorted(layers_by_offset):
kv_cache_tensors.append(
KVCacheTensor(
size=total_size,
shared_by=layers_by_offset[byte_offset],
offset=byte_offset,
block_stride=block_stride,
)
# Mixed page sizes pack pages side by side within a block, which needs each page
# to be one contiguous chunk inside its block (a block-compact layout) and, with
# multiple KV cache groups, the layer dim inside the block dim.
if not layout.is_block_compact or (
len(kv_cache_groups) > 1 and layout.is_layer_compact
):
raise ValueError(
f"KV cache layout {layout.name} cannot express this model's "
f"mixed page sizes ({sorted(page_sizes)}); a backend should "
"declare block-outermost supported layouts (e.g. BLHNC), or "
"set VLLM_KV_CACHE_LAYOUT=BLHNC."
)
return num_blocks, kv_cache_tensors
def get_kv_cache_config_from_groups(
vllm_config: VllmConfig,
@@ -1402,58 +1354,60 @@ def get_kv_cache_config_from_groups(
),
)
# Determine how model runners should initialize the KV cache tensors.
if len(kv_cache_groups) == 1 and isinstance(
kv_cache_groups[0].kv_cache_spec, UniformTypeKVCacheSpecs
):
# Special case: all layers have the same type of KV cache but with
# different hidden sizes. Allocate different amount of memory for each
# layer based on its hidden size.
num_blocks = (
available_memory // kv_cache_groups[0].kv_cache_spec.page_size_bytes
)
num_blocks = may_override_num_blocks(vllm_config, num_blocks)
per_layer_specs = kv_cache_groups[0].kv_cache_spec.kv_cache_specs
kv_cache_tensors = [
KVCacheTensor(
size=per_layer_specs[layer_name].page_size_bytes * num_blocks,
shared_by=[layer_name],
)
for layer_name in kv_cache_groups[0].layer_names
]
elif _use_packed_kv_cache_config(vllm_config, kv_cache_groups):
# DeepSeek V4 uses the packed layout by default. Other multi-group
# layouts can opt in with --enable-cross-layers.
num_blocks, kv_cache_tensors = _get_kv_cache_config_packed(
vllm_config, kv_cache_groups, available_memory
)
else:
# General case:
# We will have group_size memory pools, each is shared by one layer from
# each group. As layers of different groups have different block table,
# they will use different parts of the shared Tensor.
# The memory layout for 3 groups (full.0, full.1), (sw.0, sw.2),
# (sw.1, padding) will be: (group_size = 2)
# full.0, sw.0, sw.1: share a Tensor with size=available_memory//2
# full.1, sw.2: share another Tensor with size=available_memory//2
group_size = max(len(group.layer_names) for group in kv_cache_groups)
layout = vllm_config.cache_config.get_resolved_kv_cache_layout()
validate_kv_cache_layout(layout, kv_cache_groups)
bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups)
interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None
page_size = get_uniform_page_size(
[group.kv_cache_spec for group in kv_cache_groups]
)
assert group_size > 0, "group_size must be greater than 0"
num_blocks = get_num_blocks(
vllm_config, group_size, available_memory, page_size
)
kv_cache_tensors = []
for i in range(group_size):
shared_by = []
for j in range(len(kv_cache_groups)):
if i < len(kv_cache_groups[j].layer_names):
shared_by.append(kv_cache_groups[j].layer_names[i])
kv_cache_tensors.append(
KVCacheTensor(size=page_size * num_blocks, shared_by=shared_by)
num_blocks = available_memory // bytes_per_block
num_blocks = may_override_num_blocks(vllm_config, num_blocks)
size = bytes_per_block * num_blocks
# Groups alias from byte 0. Spec regions are laid out differently:
#
# block-outer (the same packing repeats for every block):
# group 0: | blk 0 [ A | B | pad ] | blk 1 [ A | B | pad ] | ...
# group 1: | blk 0 [ C | D ] | blk 1 [ C | D ] | ...
# |<--- bytes_per_block -->|
#
# layer-outer (only supported for uniform page sizes or single-group models):
# group 0: | A [ blk 0 | blk 1 | ... ] | B [ blk 0 | blk 1 | ... ] |
# group 1: | C [ blk 0 | blk 1 | ... ] | D [ blk 0 | blk 1 | ... ] |
kv_cache_tensors = []
for group in kv_cache_groups:
group_spec = group.kv_cache_spec
layers_by_spec: defaultdict[KVCacheSpec, list[str]] = defaultdict(list)
if isinstance(group_spec, UniformTypeKVCacheSpecs):
for layer_name, spec in group_spec.kv_cache_specs.items():
layers_by_spec[spec].append(layer_name)
elif group.layer_names:
layers_by_spec[group_spec].extend(group.layer_names)
byte_offset = 0
for spec, layer_names in layers_by_spec.items():
layer_stride, block_stride, _, _, _ = compute_layout_strides(
spec,
num_blocks,
len(layer_names),
layout,
fixed_strides=(None, interleaved_block_stride, None, None, None),
)
offset = (
byte_offset
* max(layer_stride, spec.page_size_bytes)
// spec.page_size_bytes
)
kv_cache_tensors.append(
KVCacheTensor(
size=size,
layers=layer_names,
layer_stride=layer_stride,
block_stride=block_stride,
offset=offset,
)
)
byte_offset += len(layer_names) * spec.page_size_bytes
return KVCacheConfig(
num_blocks=num_blocks,
@@ -1941,57 +1895,26 @@ def _max_memory_usage_bytes_from_groups(
This correctly accounts for padding in hybrid models. For example, if a
model has 8 full attention layers and 9 sliding window layers, they will
be padded to 9 full + 9 sliding window for uniform group sizes.
Each group independently claims blocks from the shared pool, so a request consumes
the sum of the per-group block counts, i.e. ``bytes_per_block * total_blocks``.
"""
if not kv_cache_groups:
return 0
if len(kv_cache_groups) == 1 and isinstance(
kv_cache_groups[0].kv_cache_spec, UniformTypeKVCacheSpecs
):
# UniformTypeKVCacheSpecs special case (single group, per-layer specs)
per_layer_specs = kv_cache_groups[0].kv_cache_spec.kv_cache_specs
return sum(
spec.max_memory_usage_bytes(vllm_config)
for spec in per_layer_specs.values()
)
elif all(
isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs)
for group in kv_cache_groups
):
# Special case (only DeepseekV4 for now): all groups are
# UniformTypeKVCacheSpecs.
# They must already be page_size aligned and share a common padded
# layer-tuple layout. Even groups with fewer actual tuples still reserve
# the global number of tuple slots in the shared tensor layout.
full_mla_spec = cast(UniformTypeKVCacheSpecs, kv_cache_groups[0].kv_cache_spec)
layer_tuple_bytes = sum(full_mla_spec.get_page_sizes())
num_layer_tuples = max(
cast(UniformTypeKVCacheSpecs, group.kv_cache_spec).get_num_layer_tuples()
for group in kv_cache_groups
)
total_max_mem_usage_bytes = 0
for group in kv_cache_groups:
group_spec = cast(UniformTypeKVCacheSpecs, group.kv_cache_spec)
g_max_mem_usage_pages = group_spec.max_memory_usage_pages(vllm_config)
g_max_mem_usage_page_bytes = (
num_layer_tuples * g_max_mem_usage_pages * layer_tuple_bytes
bytes_per_block = _pool_bytes_per_block(kv_cache_groups)
total_blocks = 0
for group in kv_cache_groups:
spec = group.kv_cache_spec
if isinstance(spec, UniformTypeKVCacheSpecs):
total_blocks += spec.max_memory_usage_pages(vllm_config)
else:
total_blocks += cdiv(
spec.max_memory_usage_bytes(vllm_config),
spec.page_size_bytes,
)
total_max_mem_usage_bytes += g_max_mem_usage_page_bytes
return total_max_mem_usage_bytes
# General case: group_size pools, each shared by one layer per group
# Memory = group_size * page_size * blocks_for_max_len
group_size = max(len(group.layer_names) for group in kv_cache_groups)
page_size = get_uniform_page_size(
[group.kv_cache_spec for group in kv_cache_groups]
)
blocks_needed = sum(
cdiv(group.kv_cache_spec.max_memory_usage_bytes(vllm_config), page_size)
for group in kv_cache_groups
)
return group_size * page_size * blocks_needed
return bytes_per_block * total_blocks
def _estimate_max_model_len_from_groups(
@@ -2228,7 +2151,7 @@ def get_kv_cache_configs(
if not groups:
adjusted_memory.append(avail_mem)
continue
bytes_per_block = _pool_bytes_per_block(vllm_config, groups)
bytes_per_block = _pool_bytes_per_block(groups)
logger.info(
"Overriding num_gpu_blocks=%d with num_gpu_blocks_override=%d",
avail_mem // bytes_per_block,
@@ -2241,7 +2164,7 @@ def get_kv_cache_configs(
# the capacity check both plan against usable blocks. Allocation below
# still uses the full memory.
check_memory = [
avail_mem - _pool_bytes_per_block(vllm_config, groups) if groups else avail_mem
avail_mem - _pool_bytes_per_block(groups) if groups else avail_mem
for groups, avail_mem in zip(projected_groups_per_worker, available_memory)
]
@@ -2278,14 +2201,15 @@ def get_kv_cache_configs(
min_num_blocks = min(
kv_cache_config.num_blocks for kv_cache_config in kv_cache_configs
)
for kv_cache_config in kv_cache_configs:
num_blocks_old = kv_cache_config.num_blocks
kv_cache_config.num_blocks = min_num_blocks
# Shrink tensor size proportionally
for tensor in kv_cache_config.kv_cache_tensors:
assert tensor.size % num_blocks_old == 0
tensor.size = tensor.size // num_blocks_old * min_num_blocks
for i, kv_cache_config in enumerate(kv_cache_configs):
if kv_cache_config.num_blocks == min_num_blocks:
continue
# Re-plan with exactly the memory the smallest rank can afford, so
# strides and offsets stay consistent with the shrunken allocation.
groups = kv_cache_config.kv_cache_groups
kv_cache_configs[i] = get_kv_cache_config_from_groups(
vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups)
)
return kv_cache_configs
+14
View File
@@ -44,6 +44,7 @@ from vllm.utils.gc_utils import (
from vllm.utils.hashing import get_hash_fn_by_name
from vllm.utils.network_utils import make_zmq_socket
from vllm.utils.system_utils import decorate_logs, set_process_title
from vllm.v1.attention.backends.utils import resolve_kv_cache_layout
from vllm.v1.core.kv_cache_utils import (
BlockHash,
generate_scheduler_kv_cache_config,
@@ -281,6 +282,17 @@ class EngineCore:
)
vllm_config.cache_config.enable_prefix_caching = False
# Resolve the KV cache layout before memory profiling: workers that
# capture full cudagraphs initialize a minimal KV cache during it.
# Attention-free models resolve the default so layout reads never precede
# resolution.
layout = resolve_kv_cache_layout(
vllm_config,
self.model_executor.get_supported_kv_cache_layouts(),
[s for specs in kv_cache_specs for s in specs.values()],
)
self.model_executor.set_kv_cache_layout(layout.name)
has_kv_cache = any(kv_cache_spec for kv_cache_spec in kv_cache_specs)
if has_kv_cache:
if envs.VLLM_ELASTIC_EP_SCALE_UP_LAUNCH:
@@ -307,6 +319,8 @@ class EngineCore:
kv_cache_configs = get_kv_cache_configs(
vllm_config, kv_cache_specs, available_gpu_memory
)
for kv_cache_config in kv_cache_configs:
kv_cache_config.kv_cache_layout = vllm_config.cache_config.kv_cache_layout
# If auto-fit reduced max_model_len, sync the new value to workers.
# This is needed because workers were spawned before memory profiling
+8
View File
@@ -151,6 +151,14 @@ class Executor(ABC):
def get_kv_cache_specs(self) -> list[dict[str, KVCacheSpec]]:
return self.collective_rpc("get_kv_cache_spec")
def get_supported_kv_cache_layouts(self) -> list[list[str]]:
"""Layouts each worker's backends support, most preferred first."""
return self.collective_rpc("get_supported_kv_cache_layouts")
def set_kv_cache_layout(self, layout_name: str) -> None:
"""Publish the resolved KV cache layout to the workers."""
self.collective_rpc("set_kv_cache_layout", args=(layout_name,))
@overload
def collective_rpc(
self,
+202 -40
View File
@@ -8,6 +8,7 @@ from collections import Counter
from collections.abc import Collection
from dataclasses import dataclass, fields, replace
from enum import Enum, IntEnum
from fractions import Fraction
from math import prod
from typing import TYPE_CHECKING, TypeVar
@@ -18,6 +19,7 @@ from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.torch_utils import get_dtype_size
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.kv_cache_layout import _DIM_B, _DIM_L, KVCacheLayout
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
if TYPE_CHECKING:
@@ -147,6 +149,18 @@ class KVCacheSpec:
# number of tokens in a block
block_size: int
@property
def num_heads(self) -> int:
raise NotImplementedError
@property
def tokens_per_state(self) -> int | Fraction:
raise NotImplementedError
@property
def state_content_size_bytes(self) -> int:
raise NotImplementedError
@property
def page_size_bytes(self) -> int:
"""
@@ -158,8 +172,13 @@ class KVCacheSpec:
raise NotImplementedError
@property
def storage_block_size(self) -> int:
return self.block_size
def num_states(self) -> int:
return self.get_num_kernel_states(self.block_size)
def get_num_kernel_states(self, kernel_block_size: int) -> int:
if self.tokens_per_state > 0:
return kernel_block_size // self.tokens_per_state
return 1
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
"""
@@ -214,6 +233,143 @@ class KVCacheSpec:
)
def group_kernel_blocks(cache: torch.Tensor, num_blocks: int) -> torch.Tensor:
"""View a kernel-block-granular layer cache with manager blocks as dim 0.
Kernel block splitting subdivides each manager block into uniformly strided
kernel blocks, so grouping is a pure view: ``(num_blocks * ratio, ...)``
"""
if cache.shape[0] == num_blocks:
return cache
assert cache.shape[0] % num_blocks == 0
return cache.unflatten(0, (num_blocks, -1))
def compute_layer_kv_cache_shape_bytes(
spec: KVCacheSpec,
num_blocks: int,
kernel_block_size: int | None = None,
) -> tuple[int, ...]:
"""Return the 4D logical shape ``(B, H, N, C)`` where C is in bytes."""
bs = kernel_block_size if kernel_block_size is not None else spec.block_size
assert spec.block_size % bs == 0, (
f"Kernel block size {bs} must divide KV cache block size {spec.block_size}."
)
blocks_per_page = spec.block_size // bs
return (
num_blocks * blocks_per_page,
spec.num_heads,
spec.get_num_kernel_states(bs),
spec.state_content_size_bytes,
)
def compute_layout_strides(
spec: KVCacheSpec,
num_blocks: int,
num_layers: int,
layout: KVCacheLayout,
kernel_block_size: int | None = None,
fixed_strides: tuple[int | None, ...] = (None,) * 5,
) -> tuple[int, ...]:
"""Byte strides in logical ``[L, B, H, N, C]`` axis order."""
assert len(fixed_strides) == 5
assert all(stride is None or stride > 0 for stride in fixed_strides)
shape = (
num_layers,
*compute_layer_kv_cache_shape_bytes(spec, num_blocks, kernel_block_size),
)
order = layout.stride_order
padded_page_size = getattr(spec, "page_size_padded", None)
if padded_page_size is not None:
assert kernel_block_size is None or kernel_block_size == spec.block_size, (
"Padded KV pages do not support kernel block splitting."
)
page_grid_end = max(order.index(_DIM_L), order.index(_DIM_B)) + 1
page_grid_shape = tuple(shape[dim] for dim in order[:page_grid_end])
assert prod(page_grid_shape) == num_layers * num_blocks, (
"Page padding requires dimensions outside the page tail to be L, B, "
f"or singleton; got {layout.name} with shape {shape}."
)
strides = [0] * 5
current_stride = 1
for physical_idx, dim in reversed(tuple(enumerate(order))):
if padded_page_size is not None and physical_idx == page_grid_end - 1:
current_stride = max(current_stride, padded_page_size)
assert current_stride % padded_page_size == 0
strides[dim] = fixed_strides[dim] or current_stride
current_stride = strides[dim] * shape[dim]
return tuple(strides)
def create_kv_cache_views(
raw: torch.Tensor,
spec: KVCacheSpec,
num_blocks: int,
layout: KVCacheLayout,
kv_cache_tensor: KVCacheTensor,
kernel_block_size: int | None = None,
) -> list[torch.Tensor]:
"""View a flat int8 buffer as one 4D ``[B, H, N, C]`` view per layer.
Block ``b`` of layer ``l`` starts at the tensor offset plus its layer and
block stride contributions.
"""
num_layers = len(kv_cache_tensor.layers)
layer_stride = kv_cache_tensor.layer_stride
block_stride = kv_cache_tensor.block_stride
shape_bytes = compute_layer_kv_cache_shape_bytes(
spec, num_blocks, kernel_block_size
)
ratio = shape_bytes[0] // num_blocks
if ratio > 1:
# Kernel blocks subdivide a manager block into `ratio` equal pieces, so
# they sit a constant stride apart only if a block is one dense page: no
# padding at its end, and no other layer's page before the next block.
dense_page_size = prod(compute_layer_kv_cache_shape_bytes(spec, 1)[1:])
if block_stride != dense_page_size:
raise ValueError(
f"The resolved KV cache layout ({layout.name}) does not store "
"blocks as dense, unpadded pages (block stride "
f"{block_stride} != page {dense_page_size}), so a manager "
f"block cannot be split into {ratio} kernel blocks of "
f"{kernel_block_size} tokens. Reduce --block-size to "
f"{kernel_block_size} or set VLLM_KV_CACHE_LAYOUT to a "
"layer-compact layout (e.g. LBNHC)."
)
assert block_stride % ratio == 0, (
f"Block stride {block_stride} must divide into {ratio} equal kernel blocks."
)
block_stride //= ratio
logical_shape = (num_layers, *shape_bytes)
strides = compute_layout_strides(
spec,
num_blocks,
num_layers,
layout,
kernel_block_size,
fixed_strides=(layer_stride, block_stride, None, None, None),
)
dtype = getattr(spec, "dtype", None)
view_5d = torch.as_strided(
raw,
size=logical_shape,
stride=strides,
storage_offset=raw.storage_offset() + kv_cache_tensor.offset,
)
views = []
for layer_idx in range(num_layers):
cache_logical = view_5d[layer_idx]
if dtype is not None:
cache_logical = cache_logical.view(dtype)
views.append(cache_logical)
return views
@dataclass(frozen=True, kw_only=True)
class AttentionSpec(KVCacheSpec):
num_kv_heads: int
@@ -222,13 +378,16 @@ class AttentionSpec(KVCacheSpec):
head_size_v: int = None # type: ignore[assignment]
kv_quant_mode: KVQuantMode = KVQuantMode.NONE
page_size_padded: int | None = None
indexes_kv_by_block_stride: bool = False
num_head_slots: int | None = None
"""H of the logical ``[B, H, N, C]`` page when packing diverges from one
slot per KV head. None means one slot per KV head. Published by the backend.
"""
state_content_bytes: int | None = None
"""C in bytes when packed; None means dense K/V content."""
tokens_per_state: int | Fraction = 1
"""Tokens covered by one stored state. Ints > 1 compress multiple tokens
into one state (DSv4 sparse MLA); fractions < 1 store multiple states per
token (Whisper block pooling: ``Fraction(1, block_pool_size)``)."""
def __post_init__(self):
if self.head_size_v is None:
@@ -249,7 +408,7 @@ class AttentionSpec(KVCacheSpec):
@property
def unpadded_page_size_bytes(self) -> int:
return self.num_heads * self.storage_block_size * self.state_content_size_bytes
return self.num_heads * self.num_states * self.state_content_size_bytes
@property
def page_size_bytes(self) -> int:
@@ -345,9 +504,9 @@ class FullAttentionSpec(AttentionSpec):
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
page_size_padded=specs[0].page_size_padded,
indexes_kv_by_block_stride=specs[0].indexes_kv_by_block_stride,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
tokens_per_state=specs[0].tokens_per_state,
sliding_window=cls.merge_window_sizes(sliding_window),
attention_chunk_size=cls.merge_window_sizes(attention_chunk_size),
# If any layer in the group is non-causal, treat the group as
@@ -384,7 +543,6 @@ class MLAAttentionSpec(FullAttentionSpec):
cache_dtype_str: str | None = None
# DeepseekV4 only fields. Non-DeepseekV4 MLA models leave these at defaults.
alignment: int | None = None # Default to None for no padding.
compress_ratio: int = 1 # Default to 1 for no compression.
model_version: str | None = None
# Marks draft groups that flatten a non-causal query block into decode rows.
non_causal_multi_token_decode: bool = False
@@ -395,28 +553,21 @@ class MLAAttentionSpec(FullAttentionSpec):
super().__post_init__()
_apply_alignment_padding(self)
@property
def storage_block_size(self) -> int:
return self.block_size // self.compress_ratio
@classmethod
def merge(cls, specs: list[Self]) -> Self:
assert all(isinstance(spec, MLAAttentionSpec) for spec in specs), (
"All attention layers in the same KV cache group must be MLAAttentionSpec."
)
cache_dtype_str_set = set(spec.cache_dtype_str for spec in specs)
compress_ratio_set = set(spec.compress_ratio for spec in specs)
tokens_per_state_set = set(spec.tokens_per_state for spec in specs)
model_version_set = set(spec.model_version for spec in specs)
block_stride_set = set(spec.indexes_kv_by_block_stride for spec in specs)
assert (
len(cache_dtype_str_set) == 1
and len(compress_ratio_set) == 1
and len(tokens_per_state_set) == 1
and len(model_version_set) == 1
and len(block_stride_set) == 1
), (
"All attention layers in the same KV cache group must use the same "
"quantization method, compress ratio, model version, and KV block "
"stride indexing."
"quantization method, tokens per state, and model version."
)
merged_spec = cls(
block_size=specs[0].block_size,
@@ -427,9 +578,8 @@ class MLAAttentionSpec(FullAttentionSpec):
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
indexes_kv_by_block_stride=block_stride_set.pop(),
cache_dtype_str=cache_dtype_str_set.pop(),
compress_ratio=compress_ratio_set.pop(),
tokens_per_state=tokens_per_state_set.pop(),
model_version=model_version_set.pop(),
non_causal_multi_token_decode=any(
spec.non_causal_multi_token_decode for spec in specs
@@ -483,9 +633,9 @@ class RSWASpec(FullAttentionSpec):
dtype=base.dtype,
kv_quant_mode=base.kv_quant_mode,
page_size_padded=base.page_size_padded,
indexes_kv_by_block_stride=base.indexes_kv_by_block_stride,
num_head_slots=base.num_head_slots,
state_content_bytes=base.state_content_bytes,
tokens_per_state=base.tokens_per_state,
sliding_window=base.sliding_window,
attention_chunk_size=base.attention_chunk_size,
non_causal=base.non_causal,
@@ -598,8 +748,8 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
cache_dtype_str: str | None = None
# DeepseekV4-only: see MLAAttentionSpec.model_version.
alignment: int | None = None # Default to None for no padding.
compress_ratio: int = 1
model_version: str | None = None
# MLA stores a single latent vector per state; there is no separate V.
head_size_v: int = 0
@@ -610,10 +760,6 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
super().__post_init__()
_apply_alignment_padding(self)
@property
def storage_block_size(self) -> int:
return self.block_size // self.compress_ratio
@classmethod
def merge(cls, specs: list[Self]) -> Self:
assert all(isinstance(spec, SlidingWindowMLASpec) for spec in specs), (
@@ -621,22 +767,20 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
"SlidingWindowMLASpec."
)
cache_dtype_str_set = set(spec.cache_dtype_str for spec in specs)
compress_ratio_set = set(spec.compress_ratio for spec in specs)
tokens_per_state_set = set(spec.tokens_per_state for spec in specs)
model_version_set = set(spec.model_version for spec in specs)
sliding_window_set = set(spec.sliding_window for spec in specs)
block_stride_set = set(spec.indexes_kv_by_block_stride for spec in specs)
extra_retained_set = set(spec.extra_retained_tokens for spec in specs)
assert (
len(cache_dtype_str_set) == 1
and len(compress_ratio_set) == 1
and len(tokens_per_state_set) == 1
and len(model_version_set) == 1
and len(sliding_window_set) == 1
and len(block_stride_set) == 1
and len(extra_retained_set) == 1
), (
"All attention layers in the same KV cache group must use the same "
"quantization method, compress ratio, model version, sliding "
"window size, KV block stride indexing, and retained token count."
"quantization method, tokens per state, model version, sliding "
"window size, and retained token count."
)
return cls(
block_size=specs[0].block_size,
@@ -646,11 +790,10 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
indexes_kv_by_block_stride=block_stride_set.pop(),
sliding_window=sliding_window_set.pop(),
extra_retained_tokens=extra_retained_set.pop(),
cache_dtype_str=cache_dtype_str_set.pop(),
compress_ratio=compress_ratio_set.pop(),
tokens_per_state=tokens_per_state_set.pop(),
model_version=model_version_set.pop(),
)
@@ -672,6 +815,15 @@ class MambaSpec(KVCacheSpec):
mamba_type: MambaAttentionBackendEnum = MambaAttentionBackendEnum.MAMBA2
mamba_cache_mode: str = "none"
num_speculative_blocks: int = 0
num_heads: int = 1
tokens_per_state: int = -1
@property
def state_content_size_bytes(self) -> int:
return sum(
prod(shape) * get_dtype_size(dtype)
for (shape, dtype) in zip(self.shapes, self.dtypes)
)
@property
def page_size_bytes(self) -> int:
@@ -771,7 +923,6 @@ class SinkFullAttentionSpec(FullAttentionSpec):
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
page_size_padded=specs[0].page_size_padded,
indexes_kv_by_block_stride=specs[0].indexes_kv_by_block_stride,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
sliding_window=cls.merge_window_sizes(sliding_window),
@@ -857,9 +1008,6 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
return None
# NOTE: below util functions are only used by DeepseekV4 for now.
def get_page_sizes(self) -> list[int]:
return list(set(spec.page_size_bytes for spec in self.kv_cache_specs.values()))
def get_num_layer_tuples(self) -> int:
return Counter(
spec.page_size_bytes for spec in self.kv_cache_specs.values()
@@ -929,12 +1077,24 @@ def get_kv_cache_spec_sliding_window(kv_cache_spec: KVCacheSpec) -> int | None:
class KVCacheTensor:
"""
A class for specifying how the workers should initialize the KV cache.
Placement of a set of same-shaped layers in the KV cache allocation.
Layer ``layers[l]``'s page for block ``b`` starts at
``offset + l * layer_stride + b * block_stride`` bytes into the backing
allocation of ``size`` bytes. Layer-outermost layouts give each layer a
contiguous region (``layer_stride = page * num_blocks``,
``block_stride = page``); block-outermost layouts make each block a
block of all layers' pages (``layer_stride = page``, ``block_stride`` =
the packed block). Tensors whose address ranges overlap
alias the same bytes: cache groups overlay each other, which is sound
because a block ID is owned by one group at a time.
"""
size: int # size of the KV cache tensor in bytes
shared_by: list[str] # layer names that share the same KV cache tensor
offset: int = 0 # byte offset of this layer within a contiguous block
block_stride: int = 0 # total bytes per block in a packed layout (0 = not packed)
size: int # total size of the backing allocation in bytes
layers: list[str] # layer names in L order
layer_stride: int
block_stride: int
offset: int = 0 # byte offset of layers[0]'s block 0
@dataclass
@@ -972,6 +1132,8 @@ class KVCacheConfig:
"""
prefix_cache_retention_interval: int | None = None
"""Resolved retention policy for local prefix-cache checkpoints."""
kv_cache_layout: str | None = None
"""The KV cache layout resolved by the engine core, adopted by all workers."""
@property
def has_mamba_layers(self) -> bool:
+58
View File
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Physical KV cache layout descriptor.
A leaf module so ``vllm.config`` can import the enum without pulling in the
full KV cache interface.
"""
from enum import Enum
# Logical dim indices in the 5D stride permutation [L, B, H, N, C] (see: RFC #42082).
_DIM_L, _DIM_B, _DIM_H, _DIM_N, _DIM_C = 0, 1, 2, 3, 4
class KVCacheLayout(Enum):
"""Physical layout descriptor for a KV cache group.
The logical shape is always [L, B, H, N, <content>] (RFC #42082).
Each member's value is a stride permutation that maps logical axes
to physical (memory) order.
"""
LBHNC = (0, 1, 2, 3, 4) # [L, B, H, N, C] (identity)
LBNHC = (0, 1, 3, 2, 4) # [L, B, N, H, C]
LHBNC = (0, 2, 1, 3, 4) # [L, H, B, N, C]
BLHNC = (1, 0, 2, 3, 4) # [B, L, H, N, C]
BLNHC = (1, 0, 3, 2, 4) # [B, L, N, H, C]
BHLNC = (1, 2, 0, 3, 4) # [B, H, L, N, C]
@property
def stride_order(self) -> tuple[int, ...]:
return self.value
@property
def layer_view_order(self) -> tuple[int, ...]:
"""Physical axis order of a logical 4D per-layer cache view."""
return tuple(i - 1 for i in self.value if i != _DIM_L)
@property
def is_layer_compact(self) -> bool:
"""True when the layer is compact; i.e. the L dimension is outermost."""
return self.value[_DIM_L] == 0
@property
def is_block_contiguous(self) -> bool:
"""True when [H, N, C] is contiguous within a block."""
return self.value[-3:] == (_DIM_H, _DIM_N, _DIM_C)
@property
def is_block_compact(self) -> bool:
"""True when each page's [H, N, C] bytes form one contiguous run; i.e.
the L and B dimensions are outermost."""
return set(self.value[:2]) == {_DIM_L, _DIM_B}
@property
def is_block_outermost(self) -> bool:
"""True when B is the outermost physical dimension."""
return self.value[0] == _DIM_B
+2 -4
View File
@@ -445,10 +445,8 @@ class CanonicalKVCacheTensor:
"""
A canonicalized KV cache tensor whose first dimension is num_blocks.
For attention backends where the raw tensor has num_blocks at a
non-leading physical dimension (e.g. FlashAttention's
(2, num_blocks, ...) layout), the tensor is split so that each
resulting CanonicalKVCacheTensor starts with (num_blocks, ...).
With standardized layouts (RFC #42082) num_blocks is always the leading
logical dimension.
"""
# The KV cache tensor with shape (num_blocks, ...)
+2
View File
@@ -84,3 +84,5 @@ class OffloadingConfig:
# True when the canonical per-layer host byte layout was requested via
# kv_connector_extra_config; certified per-layer at worker registration.
canonical_layout: bool = False
# Resolved KVCacheLayout name of the worker KV cache.
kv_cache_layout: str | None = None
+4 -1
View File
@@ -94,7 +94,10 @@ class FileMapper:
for group in config.groups
]
parallel = config.parallel
canonical_format = canonical_format_id() if config.canonical_layout else None
canonical_format = None
if config.canonical_layout:
assert config.kv_cache_layout is not None
canonical_format = canonical_format_id(config.kv_cache_layout)
return cls(
root_dir=root_dir,
model_name=config.model.name,
+6 -9
View File
@@ -194,22 +194,19 @@ class SimpleCPUOffloadScheduler:
assert len(gpu_config.kv_cache_tensors) > 0
is_packed = any(t.block_stride for t in gpu_config.kv_cache_tensors)
assert not is_packed or all(t.block_stride for t in gpu_config.kv_cache_tensors)
gpu_total_bytes = (
gpu_config.kv_cache_tensors[0].size
if is_packed
else sum(t.size for t in gpu_config.kv_cache_tensors)
)
# Every KVCacheTensor describes placement within the same backing allocation,
# so its size is the total GPU KV cache size.
gpu_total_bytes = gpu_config.kv_cache_tensors[0].size
num_gpu_blocks = gpu_config.num_blocks
num_cpu_blocks = max(1, num_gpu_blocks * cpu_capacity_bytes // gpu_total_bytes)
# Create CPU kv_cache_tensors mirroring GPU by scaling size proportionally.
cpu_tensors = [
KVCacheTensor(
size=t.size // num_gpu_blocks * num_cpu_blocks,
shared_by=list(t.shared_by),
offset=t.offset,
layers=list(t.layers),
layer_stride=t.layer_stride,
block_stride=t.block_stride,
offset=t.offset,
)
for t in gpu_config.kv_cache_tensors
]
+20 -44
View File
@@ -95,57 +95,33 @@ class SimpleCPUOffloadWorker:
logger.warning("No KV caches to offload.")
return
# Resolve each entry to a representative tensor for storage
# deduplication. For attention layers the value is already a tensor;
# for Mamba layers it is a list of tensors that all share the same
# underlying raw storage, so we take the first one.
def _repr_tensor(v: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
assert isinstance(v, torch.Tensor | list)
return v if isinstance(v, torch.Tensor) else v[0]
any_tensor = _repr_tensor(next(iter(kv_caches.values())))
self.device = any_tensor.device
self.device = next(iter(kv_caches.values())).device
assert self.kv_cache_config is not None
num_blocks = self.kv_cache_config.num_blocks
# Deduplicate: multiple layers may share the same backing storage.
seen_ptrs: dict[int, tuple[str, torch.Tensor]] = {}
for name, value in kv_caches.items():
tensor = _repr_tensor(value)
ptr = tensor.untyped_storage().data_ptr()
if ptr not in seen_ptrs:
seen_ptrs[ptr] = (name, tensor)
# Build [num_blocks, block_bytes] int8 views from each unique
# storage so that stride(0) gives block_bytes for the copy op.
#
# The physical layout varies across attention backends:
# FlashAttn/ROCm: (2, num_blocks, ...) -> K/V outermost, 2 segments
# FlashInfer/MLA: (num_blocks, ...) -> blocks outermost, 1 segment
# We derive page_size_bytes = storage.nbytes() // num_blocks, then
# classify dims: any dim whose byte-stride exceeds page_size_bytes
# must be an outer segment dim (e.g. the K/V dim of size 2). A less
# hacky way is to update the interface with the layout.
# The DMA backend copies whole blocks as base + block_id * stride(0),
# so view each unique allocation as [num_blocks, block_bytes].
unique_gpu_caches: dict[str, torch.Tensor] = {}
for name, tensor in seen_ptrs.values():
seen: set[tuple[torch.device, int]] = set()
for name, tensor in kv_caches.items():
storage = tensor.untyped_storage()
raw = torch.empty(0, dtype=torch.int8, device=self.device).set_(
storage, 0, (storage.nbytes(),)
key = (tensor.device, storage.data_ptr())
if key in seen:
continue
seen.add(key)
physical_per_block, remainder = divmod(tensor.shape[0], num_blocks)
assert remainder == 0, (
f"KV cache {name!r} has {tensor.shape[0]} physical blocks, which "
f"is not divisible by {num_blocks} scheduler blocks"
)
el = tensor.element_size()
page_size_bytes = storage.nbytes() // num_blocks
outer_dims = [
d for d in range(tensor.ndim) if tensor.stride(d) * el > page_size_bytes
]
if not outer_dims:
unique_gpu_caches[name] = raw.view(num_blocks, -1)
else:
seg_stride = tensor.stride(outer_dims[0]) * el
for idx in range(tensor.shape[outer_dims[0]]):
offset = idx * seg_stride
chunk = raw[offset : offset + seg_stride]
unique_gpu_caches[f"{name}.{idx}"] = chunk.view(num_blocks, -1)
block_bytes = tensor.stride(0) * tensor.element_size() * physical_per_block
raw = torch.empty(0, dtype=torch.int8, device=tensor.device).set_(storage)
regions = raw.view(-1, num_blocks, block_bytes)
for idx, region in enumerate(regions):
key_name = name if len(regions) == 1 else f"{name}.{idx}"
unique_gpu_caches[key_name] = region
# Compute per-tensor bytes_per_block. Tensors may have different
# page_size_bytes (e.g., UniformTypeKVCacheSpecs with varying head_size).
+12 -380
View File
@@ -1,22 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass, replace
from math import prod
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, cast
import torch
from vllm.config import (
VllmConfig,
get_layers_from_vllm_config,
set_current_vllm_config,
)
from vllm.logger import init_logger
from vllm.config import VllmConfig, get_layers_from_vllm_config
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.multimodal.inputs import MultiModalFeatureSpec
from vllm.utils.torch_utils import get_dtype_size
from vllm.v1.attention.backend import (
AttentionCGSupport,
CommonAttentionMetadata,
@@ -25,20 +18,17 @@ from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheConfig,
KVCacheSpec,
KVQuantMode,
MambaSpec,
UniformTypeKVCacheSpecs,
)
from vllm.v1.worker.gpu.model_states.interface import ModelSpecificAttnMetadata
from vllm.v1.worker.utils import (
AttentionGroup,
add_kv_sharing_layers_to_kv_cache_groups,
allocate_kv_cache,
bind_kv_cache,
prepare_kernel_block_sizes,
)
logger = init_logger(__name__)
@dataclass(frozen=True)
class AttentionCGSupportInfo:
@@ -69,13 +59,7 @@ def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
# Skip modules that don't need KV cache (eg encoder-only attention)
if spec := attn_module.get_kv_cache_spec(vllm_config):
if isinstance(spec, AttentionSpec):
backend = attn_module.get_attn_backend()
# indexes_kv_by_block_stride() -> get_kv_cache_stride_order() ->
# get_kv_cache_layout() needs the current vLLM config.
with set_current_vllm_config(vllm_config):
indexes = backend.indexes_kv_by_block_stride()
spec = replace(spec, indexes_kv_by_block_stride=indexes)
spec = backend.customize_spec(spec)
spec = attn_module.get_attn_backend().customize_spec(spec)
kv_cache_spec[layer_name] = spec
return kv_cache_spec
@@ -197,374 +181,22 @@ def get_query_lens_mismatch_unsupported_backend(
return None
def _allocate_kv_cache(
kv_cache_config: KVCacheConfig, shared_layers: dict[str, str], device: torch.device
):
kv_cache_raw_tensors: dict[str, torch.Tensor] = {}
packed_backing: torch.Tensor | None = None
for kv_cache_tensor in kv_cache_config.kv_cache_tensors:
if kv_cache_tensor.block_stride > 0:
# Allocate once; all packed tensors alias the same backing.
if packed_backing is None:
packed_backing = torch.zeros(
kv_cache_tensor.size, dtype=torch.int8, device=device
)
tensor = packed_backing
else:
tensor = torch.zeros(kv_cache_tensor.size, dtype=torch.int8, device=device)
for layer_name in kv_cache_tensor.shared_by:
kv_cache_raw_tensors[layer_name] = tensor
layer_names = set()
for group in kv_cache_config.kv_cache_groups:
for layer_name in group.layer_names:
layer_names.add(layer_name)
assert layer_names == (kv_cache_raw_tensors.keys() | shared_layers.keys()), (
"Some layers are not correctly initialized"
)
return kv_cache_raw_tensors
def _kv_first_layers_sharing_pool_with_mamba(
attn_groups: Sequence[AttentionGroup],
kernel_block_sizes: list[int],
cache_dtype: str,
kv_cache_config: "KVCacheConfig | None",
) -> set[str]:
"""KV-first attention layers that share an allocation with Mamba state.
Mamba addresses its state by page, so these layers have to lay their blocks
out page by page as well; otherwise block ids from the two groups resolve
to overlapping bytes.
"""
if kv_cache_config is None:
return set()
kv_first_layers: set[str] = set()
mamba_layers: set[str] = set()
for group in attn_groups:
kv_cache_spec = group.kv_cache_spec
if isinstance(kv_cache_spec, MambaSpec):
mamba_layers.update(group.layer_names)
continue
if not isinstance(kv_cache_spec, AttentionSpec):
continue
if group.kv_cache_group_id >= len(kernel_block_sizes):
continue
block_dim = group.backend.get_kv_cache_block_dim(
kernel_block_sizes[group.kv_cache_group_id],
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=cache_dtype,
)
if block_dim != 0:
kv_first_layers.update(group.layer_names)
page_aligned: set[str] = set()
for kv_tensor in kv_cache_config.kv_cache_tensors:
if mamba_layers.isdisjoint(kv_tensor.shared_by):
continue
page_aligned.update(kv_first_layers.intersection(kv_tensor.shared_by))
return page_aligned
def _reshape_attention_kv_cache(
kv_raw_tensor: torch.Tensor,
kv_cache_spec: AttentionSpec,
kv_cache_shape: tuple[int, ...],
kv_cache_stride_order: tuple[int, ...],
num_blocks: int,
packing: tuple[int, int] | None,
page_aligned_blocks: bool = False,
) -> torch.Tensor:
permuted_kv_cache_shape = tuple(kv_cache_shape[i] for i in kv_cache_stride_order)
inv_order = [
kv_cache_stride_order.index(i) for i in range(len(kv_cache_stride_order))
]
dtype = kv_cache_spec.dtype
if packing is not None:
offset, block_stride = packing
assert inv_order[0] == 0
page_bytes = prod(kv_cache_shape[1:]) * get_dtype_size(dtype)
kv_cache = (
kv_raw_tensor.view(-1, block_stride)[:, offset : offset + page_bytes]
.view(dtype)
.view(permuted_kv_cache_shape)
)
elif kv_cache_spec.page_size_padded is not None:
# Use a strided view to skip the padding between physical pages.
#
# Only num-blocks-first layouts are supported (the block dimension is
# dim 0 of the unpermuted shape). kv-first layouts such as ROCm's
# ``(2, num_blocks, ...)`` are intentionally not supported here. For a
# num-blocks-first layout the only stride that must change is the block
# stride: every other (contiguous) stride already steps within the
# unpadded region of a page, so no further adjustment is needed.
assert kv_cache_shape[0] == num_blocks, (
"Padded KV pages require a num-blocks-first KV cache layout (got "
f"shape {kv_cache_shape} with num_blocks={num_blocks}); "
"kv-first layouts are not supported."
)
dtype_size = get_dtype_size(kv_cache_spec.dtype)
page_stride = kv_cache_spec.page_size_bytes // dtype_size
num_blocks_dim = inv_order[0]
strides = list(torch.empty(permuted_kv_cache_shape, device="meta").stride())
strides[num_blocks_dim] = page_stride
kv_cache = torch.as_strided(
kv_raw_tensor.view(dtype),
size=permuted_kv_cache_shape,
stride=tuple(strides),
)
elif page_aligned_blocks:
# A KV-first layout such as ROCm's ``(2, num_blocks, ...)`` puts block
# ``b``'s K and V in two far-apart halves of the allocation, so block
# ``b`` does not cover page ``b``. Mamba layers sharing the allocation
# do address their state by page, so the two would resolve the same
# bytes. Build the view page-first instead, then swap the dims back.
assert kv_cache_shape[1] == num_blocks and kv_cache_stride_order == tuple(
range(len(kv_cache_shape))
), (
"Page-aligned KV blocks expect a default-strided (kv, num_blocks, "
f"...) layout, got shape {kv_cache_shape} with stride order "
f"{kv_cache_stride_order} and num_blocks={num_blocks}."
)
kv_cache = (
kv_raw_tensor.view(dtype)
.view(num_blocks, kv_cache_shape[0], *kv_cache_shape[2:])
.transpose(0, 1)
)
else:
# No padding — safe to use a contiguous view.
kv_cache = kv_raw_tensor.view(dtype).view(permuted_kv_cache_shape)
return kv_cache.permute(*inv_order)
def _reshape_kv_cache(
attn_groups: Sequence[AttentionGroup],
kv_cache_raw_tensors: dict[str, torch.Tensor],
cache_dtype: str,
kernel_block_sizes: list[int],
shared_kv_cache_layers: dict[str, str],
kv_cache_config: "KVCacheConfig | None" = None,
) -> dict[str, Any]:
kv_caches: dict[str, Any] = {}
has_attn = False
layer_packing: dict[str, tuple[int, int]] = {}
if kv_cache_config is not None:
for kv_tensor in kv_cache_config.kv_cache_tensors:
if kv_tensor.block_stride > 0:
for ln in kv_tensor.shared_by:
layer_packing[ln] = (kv_tensor.offset, kv_tensor.block_stride)
page_aligned_layers = _kv_first_layers_sharing_pool_with_mamba(
attn_groups, kernel_block_sizes, cache_dtype, kv_cache_config
)
for group in attn_groups:
if group.kv_cache_group_id >= len(kernel_block_sizes):
continue
kv_cache_spec = group.kv_cache_spec
if kv_cache_spec.storage_block_size != kv_cache_spec.block_size:
# use storage_block_size as the kernel block size for groups
# that apply a compression on block size (eg. DeepSeek V4).
kernel_block_size = kv_cache_spec.storage_block_size
else:
kernel_block_size = kernel_block_sizes[group.kv_cache_group_id]
for layer_name in group.layer_names:
if layer_name in shared_kv_cache_layers:
# Shared layer — tensor will be aliased to its target later.
continue
kv_raw_tensor = kv_cache_raw_tensors[layer_name]
packing = layer_packing.get(layer_name)
if packing is not None:
_, blk_stride = packing
num_blocks = kv_raw_tensor.numel() // blk_stride
else:
assert kv_raw_tensor.numel() % kv_cache_spec.page_size_bytes == 0
num_blocks = kv_raw_tensor.numel() // kv_cache_spec.page_size_bytes
if isinstance(kv_cache_spec, AttentionSpec):
has_attn = True
# Use storage_block_size: it equals block_size for uncompressed
# specs but is smaller for compressed ones (DeepSeek V4), which
# store block_size tokens in block_size // compress_ratio slots.
num_blocks_per_kv_block = (
kv_cache_spec.storage_block_size // kernel_block_size
)
kernel_num_blocks = num_blocks * num_blocks_per_kv_block
# Skipped layers (--kv-cache-dtype-skip-layers) keep the
# unquantized shape; only the quantized primary uses the
# quantized cache dtype's (possibly packed) layout.
layer_cache_dtype = (
"auto"
if kv_cache_spec.kv_quant_mode == KVQuantMode.NONE
else cache_dtype
)
kv_cache_shape = group.backend.get_kv_cache_shape(
kernel_num_blocks,
kernel_block_size,
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=layer_cache_dtype,
)
# FIXME(woosuk): Add kv_cache_stride_order to all attention backends.
try:
kv_cache_stride_order = group.backend.get_kv_cache_stride_order()
assert len(kv_cache_stride_order) == len(kv_cache_shape)
except (AttributeError, NotImplementedError):
kv_cache_stride_order = tuple(range(len(kv_cache_shape)))
kv_caches[layer_name] = _reshape_attention_kv_cache(
kv_raw_tensor,
kv_cache_spec,
kv_cache_shape,
kv_cache_stride_order,
kernel_num_blocks,
packing,
page_aligned_blocks=layer_name in page_aligned_layers,
)
elif isinstance(kv_cache_spec, MambaSpec):
page_size_bytes = kv_cache_spec.page_size_bytes
# Hold a single contiguous [num_blocks, 1, 1, page_size_bytes]
# int8 page view per layer; the layer's bind_kv_cache unpacks
# each block's bytes into its conv/ssm state views. Keeping
# one tensor per layer lets the KV connector register it
# without special-casing Mamba.
kv_caches[layer_name] = kv_raw_tensor[
: num_blocks * page_size_bytes
].view(num_blocks, 1, 1, page_size_bytes)
else:
raise NotImplementedError(
f"Unsupported KV cache spec type: {type(kv_cache_spec)}"
)
if has_attn and kv_cache_config is not None:
_align_mixed_attention_kv_cache_views(
attn_groups=attn_groups,
kv_caches=kv_caches,
kernel_block_sizes=kernel_block_sizes,
cache_dtype=cache_dtype,
kv_cache_config=kv_cache_config,
page_aligned_layers=page_aligned_layers,
)
# Map any sharing layers to their target layer's KV cache.
for layer_name, target_layer_name in shared_kv_cache_layers.items():
kv_caches[layer_name] = kv_caches[target_layer_name]
return kv_caches
def _align_mixed_attention_kv_cache_views(
attn_groups: Iterable[AttentionGroup],
kv_caches: dict[str, Any],
kernel_block_sizes: list[int],
cache_dtype: str,
kv_cache_config: KVCacheConfig,
page_aligned_layers: set[str],
) -> None:
"""Align shared attention KV views when backends disagree on layout.
Encoder-decoder models can share one raw allocation between decoder
self-attention (K/V-first ROCM_ATTN, block dim 1) and cross-attention
(blocks-first backends, block dim 0). Keep the physical storage in the
K/V-first layout expected by ROCM_ATTN, and restride the blocks-first
logical views so block IDs address the same bytes.
"""
block_dims_by_layer: dict[str, int] = {}
for group in attn_groups:
kv_cache_spec = group.kv_cache_spec
if not isinstance(kv_cache_spec, AttentionSpec):
continue
if group.kv_cache_group_id >= len(kernel_block_sizes):
continue
block_dim = group.backend.get_kv_cache_block_dim(
kernel_block_sizes[group.kv_cache_group_id],
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=cache_dtype,
)
for layer_name in group.layer_names:
if layer_name in kv_caches:
block_dims_by_layer[layer_name] = block_dim
for kv_tensor in kv_cache_config.kv_cache_tensors:
if kv_tensor.block_stride > 0:
continue
if not page_aligned_layers.isdisjoint(kv_tensor.shared_by):
# These KV-first views already address blocks by page, just like
# blocks-first views, so they must not be restrided onto the
# unaligned KV-first storage layout.
continue
shared_block_dims = {
block_dims_by_layer[layer_name]
for layer_name in kv_tensor.shared_by
if layer_name in block_dims_by_layer
}
if 0 not in shared_block_dims or 1 not in shared_block_dims:
continue
for layer_name in kv_tensor.shared_by:
if block_dims_by_layer.get(layer_name) == 0:
_restride_blocks_first_kv_cache_to_kv_first_storage(
kv_caches[layer_name]
)
def _restride_blocks_first_kv_cache_to_kv_first_storage(
kv_cache: torch.Tensor,
) -> None:
assert kv_cache.ndim >= 3
assert kv_cache.shape[1] == 2
page_size = kv_cache.shape[2:].numel()
num_blocks = kv_cache.shape[0]
expected_tail_stride = torch.empty(kv_cache.shape[2:]).stride()
if kv_cache.stride()[2:] != expected_tail_stride:
logger.warning_once(
"Skipping mixed KV-cache layout alignment for a non-NHD "
"blocks-first attention view with stride %s.",
kv_cache.stride(),
)
return
kv_cache.as_strided_(
size=kv_cache.shape,
stride=(page_size, num_blocks * page_size, *expected_tail_stride),
)
def init_kv_cache(
runner_kv_caches: list[torch.Tensor | list[torch.Tensor]],
forward_context: dict[str, Any],
kv_cache_config: KVCacheConfig,
attn_groups: list[list[AttentionGroup]],
device: torch.device,
cache_dtype: str,
kernel_block_sizes: list[int],
vllm_config: VllmConfig,
) -> dict[str, Any]:
shared_kv_cache_layers = get_shared_kv_cache_layers(vllm_config)
kv_cache_raw_tensors = _allocate_kv_cache(
kv_cache_config, shared_kv_cache_layers, device
)
flattened_attn_groups = list(group for groups in attn_groups for group in groups)
kv_caches = _reshape_kv_cache(
attn_groups=flattened_attn_groups,
kv_cache_raw_tensors=kv_cache_raw_tensors,
kernel_block_sizes=kernel_block_sizes,
cache_dtype=cache_dtype,
shared_kv_cache_layers=shared_kv_cache_layers,
kv_cache_config=kv_cache_config,
kv_caches = allocate_kv_cache(
kv_cache_config,
device,
vllm_config.cache_config.get_resolved_kv_cache_layout(),
kernel_block_sizes,
)
for layer_name, target in get_shared_kv_cache_layers(vllm_config).items():
kv_caches[layer_name] = kv_caches[target]
# Dual-attention models (e.g. LongCat-Flash) put two Attention modules per
# decoder layer, so a layer name carries two integers (layer + module index).
num_attn_module = (
-2
View File
@@ -51,8 +51,6 @@ class ActiveKVConnector(KVConnector):
self.vllm_config = vllm_config
self.kv_connector = get_kv_transfer_group()
# Register kv caches with KV Connector if applicable.
# TODO: support cross_layers_kv_cache
# (see https://github.com/vllm-project/vllm/pull/27743)
self.kv_connector.register_kv_caches(kv_caches_dict)
self.kv_connector.set_host_xfer_buffer_ops(copy_kv_blocks)
-3
View File
@@ -618,9 +618,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.kv_caches,
self.compilation_config.static_forward_context,
self.kv_cache_config,
self.attn_groups,
self.device,
self.cache_config.cache_dtype,
self.kernel_block_sizes,
self.vllm_config,
)
@@ -632,7 +630,6 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.device,
attn_groups_iter=(g for groups in self.attn_groups for g in groups),
kernel_block_sizes=self.kernel_block_sizes,
cache_dtype=self.cache_config.cache_dtype,
static_forward_context=self.compilation_config.static_forward_context,
)
@@ -1,6 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import copy
from collections.abc import Mapping
from typing import Any
@@ -104,12 +103,13 @@ class DFlashSpeculator(DraftModelSpeculator):
@property
def attn_vllm_config(self) -> VllmConfig:
# The draft's attention differs from the target's in causality.
config = copy.copy(super().attn_vllm_config)
config.attention_config = replace(
self.vllm_config.attention_config,
use_non_causal=self.requires_non_causal,
return replace(
self.vllm_config,
attention_config=replace(
self.vllm_config.attention_config,
use_non_causal=self.requires_non_causal,
),
)
return config
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
wants_full = cudagraph_mode.decode_mode() == CUDAGraphMode.FULL
+12 -268
View File
@@ -42,7 +42,9 @@ from vllm.config.model import PROCESSED_LOGPROBS_MODES
from vllm.distributed.ec_transfer import get_ec_transfer, has_ec_transfer
from vllm.distributed.eplb.eplb_state import EplbState
from vllm.distributed.kv_transfer import get_kv_transfer_group, has_kv_transfer_group
from vllm.distributed.kv_transfer.kv_connector.utils import copy_kv_blocks
from vllm.distributed.kv_transfer.kv_connector.utils import (
copy_kv_blocks,
)
from vllm.distributed.parallel_state import (
GraphCaptureContext,
get_dcp_group,
@@ -164,8 +166,6 @@ from vllm.v1.kv_cache_interface import (
KVCacheGroupSpec,
KVCacheSpec,
KVCacheSpecKind,
KVQuantMode,
MambaSpec,
SlidingWindowSpec,
UniformTypeKVCacheSpecs,
get_kv_cache_spec_kind,
@@ -221,7 +221,6 @@ from vllm.v1.worker.cp_utils import (
)
from vllm.v1.worker.dp_utils import coordinate_batch_across_dp
from vllm.v1.worker.ec_connector_model_runner_mixin import ECConnectorModelRunnerMixin
from vllm.v1.worker.gpu.attn_utils import _reshape_attention_kv_cache
from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
from vllm.v1.worker.gpu_ubatch_wrapper import UBatchWrapper
from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin
@@ -243,6 +242,7 @@ from .utils import (
AttentionGroup,
KVBlockZeroer,
add_kv_sharing_layers_to_kv_cache_groups,
allocate_kv_cache,
bind_kv_cache,
copy_kv_cache_blocks_inplace,
prepare_kernel_block_sizes,
@@ -612,9 +612,6 @@ class GPUModelRunner(
# self.model: nn.Module # Set after load_model
# Initialize in initialize_kv_cache
self.kv_caches: list[torch.Tensor] = []
# Initialize in initialize_kv_cache_tensors
self.cross_layers_kv_cache: torch.Tensor | None = None
self.cross_layers_attn_backend: type[AttentionBackend] | None = None
# indexes: [kv_cache_group_id][attn_group]
self.attn_groups: list[list[AttentionGroup]] = []
# self.kv_cache_config: KVCacheConfig
@@ -1200,7 +1197,6 @@ class GPUModelRunner(
self.device,
attn_groups_iter=self._kv_cache_spec_attn_group_iterator(),
kernel_block_sizes=self._kernel_block_sizes,
cache_dtype=self.cache_config.cache_dtype,
runner_only_attn_layers=self.runner_only_attn_layers,
static_forward_context=self.compilation_config.static_forward_context,
)
@@ -6707,9 +6703,6 @@ class GPUModelRunner(
for i in range(len(self.kv_caches)):
self.kv_caches[i] = None # type: ignore
self.kv_caches.clear()
if hasattr(self, "cross_layers_kv_cache"):
self.cross_layers_kv_cache = None
self.cross_layers_attn_backend = None
if hasattr(self, "attn_groups"):
self.attn_groups.clear()
if hasattr(self, "kv_cache_config"):
@@ -7441,49 +7434,6 @@ class GPUModelRunner(
f"!= kv_cache kernel_block_sizes {kernel_block_sizes}"
)
def _allocate_kv_cache_tensors(
self, kv_cache_config: KVCacheConfig
) -> dict[str, torch.Tensor]:
"""
Initializes the KV cache buffer with the correct size. The buffer needs
to be reshaped to the desired shape before being used by the models.
Args:
kv_cache_config: The KV cache config
Returns:
dict[str, torch.Tensor]: A map between layer names to their
corresponding memory buffer for KV cache.
"""
kv_cache_raw_tensors: dict[str, torch.Tensor] = {}
packed_backing: torch.Tensor | None = None
for kv_cache_tensor in kv_cache_config.kv_cache_tensors:
if kv_cache_tensor.block_stride > 0:
# Allocate once; all packed tensors alias the same backing.
if packed_backing is None:
packed_backing = torch.zeros(
kv_cache_tensor.size,
dtype=torch.int8,
device=self.device,
)
tensor = packed_backing
else:
tensor = torch.zeros(
kv_cache_tensor.size, dtype=torch.int8, device=self.device
)
for layer_name in kv_cache_tensor.shared_by:
kv_cache_raw_tensors[layer_name] = tensor
layer_names = set()
for group in kv_cache_config.kv_cache_groups:
for layer_name in group.layer_names:
if layer_name in self.runner_only_attn_layers:
continue
layer_names.add(layer_name)
assert layer_names == set(kv_cache_raw_tensors.keys()), (
"Some layers are not correctly initialized"
)
return kv_cache_raw_tensors
def _attn_group_iterator(self) -> Iterator[AttentionGroup]:
return itertools.chain.from_iterable(self.attn_groups)
@@ -7493,183 +7443,6 @@ class GPUModelRunner(
for attn_groups in self.attn_groups:
yield from attn_groups
def _reshape_kv_cache_tensors(
self,
kv_cache_raw_tensors: dict[str, torch.Tensor],
kernel_block_sizes: list[int],
) -> dict[str, torch.Tensor]:
"""
Reshape the KV cache tensors to the desired shape and dtype.
Args:
kv_cache_raw_tensors: The KV cache buffer of each layer, with
correct size but uninitialized shape.
kernel_block_sizes: The kernel block sizes for each KV cache group.
Returns:
Dict[str, torch.Tensor]: A map between layer names to their
corresponding memory buffer for KV cache.
"""
kv_caches: dict[str, torch.Tensor] = {}
has_attn, has_mamba = False, False
# Map layer names to (offset, block_stride) within the packed
# backing tensor so we can create strided views per layer.
layer_packing: dict[str, tuple[int, int]] = {}
for kv_tensor in self.kv_cache_config.kv_cache_tensors:
if kv_tensor.block_stride > 0:
for ln in kv_tensor.shared_by:
layer_packing[ln] = (kv_tensor.offset, kv_tensor.block_stride)
for group in self._kv_cache_spec_attn_group_iterator():
kv_cache_spec = group.kv_cache_spec
attn_backend = group.backend
if group.kv_cache_group_id == len(kernel_block_sizes):
# There may be a last group for layers without kv cache.
continue
kernel_block_size = kernel_block_sizes[group.kv_cache_group_id]
for layer_name in group.layer_names:
if layer_name in self.runner_only_attn_layers:
continue
raw_tensor = kv_cache_raw_tensors[layer_name]
packing = layer_packing.get(layer_name)
if packing is not None:
_, blk_stride = packing
num_blocks = raw_tensor.numel() // blk_stride
else:
assert raw_tensor.numel() % kv_cache_spec.page_size_bytes == 0
num_blocks = raw_tensor.numel() // kv_cache_spec.page_size_bytes
if isinstance(kv_cache_spec, AttentionSpec):
has_attn = True
num_blocks_per_kv_block = (
kv_cache_spec.block_size // kernel_block_size
)
kernel_num_blocks = num_blocks * num_blocks_per_kv_block
# For MLA with compression, storage_block_size != block_size
if kv_cache_spec.storage_block_size != kv_cache_spec.block_size:
shape_block_size = kv_cache_spec.storage_block_size
else:
shape_block_size = kernel_block_size
# Skipped layers (--kv-cache-dtype-skip-layers) need
# the unquantized shape.
layer_cache_dtype_str = (
"auto"
if kv_cache_spec.kv_quant_mode == KVQuantMode.NONE
else getattr(
kv_cache_spec,
"cache_dtype_str",
None,
)
or self.cache_config.cache_dtype
)
kv_cache_shape = attn_backend.get_kv_cache_shape(
kernel_num_blocks,
shape_block_size,
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=layer_cache_dtype_str,
)
try:
kv_cache_stride_order = attn_backend.get_kv_cache_stride_order()
assert len(kv_cache_stride_order) == len(kv_cache_shape)
except (AttributeError, NotImplementedError):
kv_cache_stride_order = tuple(range(len(kv_cache_shape)))
raw_tensor = kv_cache_raw_tensors[layer_name]
kv_caches[layer_name] = _reshape_attention_kv_cache(
raw_tensor,
kv_cache_spec,
kv_cache_shape,
kv_cache_stride_order,
kernel_num_blocks,
packing,
)
elif isinstance(kv_cache_spec, MambaSpec):
has_mamba = True
raw_tensor = kv_cache_raw_tensors[layer_name]
page_size_bytes = kv_cache_spec.page_size_bytes
# Hold a single contiguous [num_blocks, 1, 1, page_size_bytes]
# int8 page view per layer; the layer's bind_kv_cache unpacks
# each block's bytes into its conv/ssm state views. Keeping
# one tensor per layer lets the KV connector register it
# without special-casing Mamba.
kv_caches[layer_name] = raw_tensor[
: num_blocks * page_size_bytes
].view(num_blocks, 1, 1, page_size_bytes)
else:
raise NotImplementedError
# Reconcile divergent KV layouts to blocks-first. Triggered by hybrid
# attention/mamba models, and by encoder-decoder models whose shared
# decoder/cross-attention allocation mixes K/V-first and blocks-first
# backends (see _has_mixed_attention_kv_layout).
if has_attn and (
has_mamba or self._has_mixed_attention_kv_layout(kernel_block_sizes)
):
self._update_hybrid_attention_mamba_layout(kv_caches, kernel_block_sizes)
return kv_caches
def _has_mixed_attention_kv_layout(self, kernel_block_sizes: list[int]) -> bool:
"""Whether attention groups disagree on the physical KV cache layout.
Encoder-decoder models (e.g. Whisper) share one raw KV allocation
between a decoder self-attention layer (K/V-first ROCM_ATTN, block dim
1) and a cross-attention layer (blocks-first, block dim 0). Mixed block
dims mean a block ID maps to different bytes per layer, so the shared
buffer must be normalized to a single (blocks-first) layout.
"""
block_dims: set[int] = set()
for group in self._kv_cache_spec_attn_group_iterator():
kv_cache_spec = group.kv_cache_spec
if not isinstance(kv_cache_spec, AttentionSpec):
continue
if group.kv_cache_group_id == len(kernel_block_sizes):
continue
block_dims.add(
group.backend.get_kv_cache_block_dim(
kernel_block_sizes[group.kv_cache_group_id],
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=self.cache_config.cache_dtype,
)
)
return len(block_dims) > 1
def _update_hybrid_attention_mamba_layout(
self, kv_caches: dict[str, torch.Tensor], kernel_block_sizes: list[int]
) -> None:
"""
Update the layout of attention layers from (2, num_blocks, ...) to
(num_blocks, 2, ...).
Args:
kv_caches: The KV cache buffer of each layer.
kernel_block_sizes: The kernel block sizes for each KV cache group.
"""
for group in self._kv_cache_spec_attn_group_iterator():
kv_cache_spec = group.kv_cache_spec
if not isinstance(kv_cache_spec, AttentionSpec):
continue
block_dim = group.backend.get_kv_cache_block_dim(
kernel_block_sizes[group.kv_cache_group_id],
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=self.cache_config.cache_dtype,
)
# block_dim: 0 means (num_blocks, 2, ...); 1 means (2, num_blocks, ...).
if block_dim == 0:
continue
assert block_dim == 1
for layer_name in group.layer_names:
kv_cache = kv_caches[layer_name]
hidden_size = kv_cache.shape[2:].numel()
kv_cache.as_strided_(
size=kv_cache.shape,
stride=(hidden_size, 2 * hidden_size, *kv_cache.stride()[2:]),
)
def initialize_kv_cache_tensors(
self, kv_cache_config: KVCacheConfig, kernel_block_sizes: list[int]
) -> dict[str, torch.Tensor]:
@@ -7685,29 +7458,12 @@ class GPUModelRunner(
corresponding memory buffer for KV cache.
"""
# Try creating KV caches optimized for kv-connector transfers
cache_dtype = self.cache_config.cache_dtype
if self.use_uniform_kv_cache(self.attn_groups):
kv_caches, cross_layers_kv_cache, attn_backend = (
self.allocate_uniform_kv_caches(
kv_cache_config,
self.attn_groups,
cache_dtype,
self.device,
kernel_block_sizes,
)
)
self.cross_layers_kv_cache = cross_layers_kv_cache
self.cross_layers_attn_backend = attn_backend
else:
# Fallback to the general case
# Initialize the memory buffer for KV cache
kv_cache_raw_tensors = self._allocate_kv_cache_tensors(kv_cache_config)
# Change the memory buffer to the desired shape
kv_caches = self._reshape_kv_cache_tensors(
kv_cache_raw_tensors, kernel_block_sizes
)
kv_caches = allocate_kv_cache(
kv_cache_config,
self.device,
self.cache_config.get_resolved_kv_cache_layout(),
kernel_block_sizes,
)
# Set up cross-layer KV cache sharing
for layer_name, target_layer_name in self.shared_kv_cache_layers.items():
@@ -7803,13 +7559,7 @@ class GPUModelRunner(
if has_kv_transfer_group() and not is_profiling:
kv_transfer_group = get_kv_transfer_group()
if self.cross_layers_kv_cache is not None:
assert self.cross_layers_attn_backend is not None
kv_transfer_group.register_cross_layers_kv_cache(
self.cross_layers_kv_cache, self.cross_layers_attn_backend
)
else:
kv_transfer_group.register_kv_caches(kv_caches)
kv_transfer_group.register_kv_caches(kv_caches)
kv_transfer_group.set_host_xfer_buffer_ops(copy_kv_blocks)
def get_routed_experts(
@@ -7922,13 +7672,7 @@ class GPUModelRunner(
# Skip modules that don't need KV cache (eg encoder-only attention)
if spec := attn_module.get_kv_cache_spec(self.vllm_config):
if isinstance(spec, AttentionSpec):
backend = attn_module.get_attn_backend()
# indexes_kv_by_block_stride() -> get_kv_cache_stride_order()
# -> get_kv_cache_layout() needs the current vLLM config.
with set_current_vllm_config(self.vllm_config):
indexes = backend.indexes_kv_by_block_stride()
spec = replace(spec, indexes_kv_by_block_stride=indexes)
spec = backend.customize_spec(spec)
spec = attn_module.get_attn_backend().customize_spec(spec)
kv_cache_spec[layer_name] = spec
return kv_cache_spec
+6
View File
@@ -68,6 +68,7 @@ from vllm.utils.gpu_sync_debug import enable_gpu_sync_check, with_gpu_sync_check
from vllm.utils.mem_constants import GiB_bytes
from vllm.utils.mem_utils import MemorySnapshot, format_gib, memory_profiling
from vllm.utils.torch_utils import set_random_seed, set_torch_threads_for_runtime
from vllm.v1.attention.backends.utils import record_kv_cache_layout
from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec
from vllm.v1.outputs import (
@@ -669,6 +670,11 @@ class Worker(WorkerBase):
# so that it's available to the warmup stage.
self.cache_config.num_gpu_blocks = kv_cache_config.num_blocks
# Adopt the engine core's layout; workers spawned after resolution
# (e.g. elastic EP scale-up) only see it through the config.
if kv_cache_config.kv_cache_layout is not None:
record_kv_cache_layout(self.cache_config, kv_cache_config.kv_cache_layout)
# Init kv cache connector here, because it requires
# `kv_cache_config`.
# NOTE(Kuntai): This need to be done before `initialize_kv_cache`,
@@ -8,27 +8,18 @@ from collections.abc import Generator
from contextlib import AbstractContextManager, contextmanager, nullcontext
from typing import TYPE_CHECKING
import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.distributed.kv_transfer import get_kv_transfer_group, has_kv_transfer_group
from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBase
from vllm.forward_context import get_forward_context, set_forward_context
from vllm.logger import init_logger
from vllm.v1.attention.backend import AttentionBackend
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheConfig
from vllm.v1.outputs import (
KVConnectorOutput,
ModelRunnerOutput,
)
from vllm.v1.worker.utils import AttentionGroup
if TYPE_CHECKING:
from vllm.v1.core.sched.output import SchedulerOutput
logger = init_logger(__name__)
# Defined as a kv connector functionality mixin for ModelRunner (GPU, TPU)
class KVConnectorModelRunnerMixin:
@@ -110,146 +101,3 @@ class KVConnectorModelRunnerMixin:
if not defer_finalize:
kv_connector.clear_connector_metadata()
@staticmethod
def use_uniform_kv_cache(
attn_groups: list[list[AttentionGroup]],
) -> bool:
"""
Determines whether a uniform KV layout should be used.
A uniform layout means all layers KV caches will share the same
underlying tensor, where for a given block number, the respective
KV data for all layers will be contiguous.
This will allow efficient KV transfer of per-block KV data for all
layers at once.
Note this layout will only be applied given 3 conditions:
1. The KV Cache config contains just a single group where all layers
have the same page size.
2. A KV connector is configured, and the KV connector instance prefers
to use this layout (prefer_cross_layer_blocks() returns True)
3. The attention backend indexes KV by the block stride
(kv_cache_spec.indexes_kv_by_block_stride), i.e. num_blocks is the
outermost physical dim so per-block all-layers data is contiguous.
Note that the actual placement of the num_layers dimensions
in the unified layers tensors will be determined by the attention
backend.
Thus, the layers KV data may still not be contiguous per block
if the attention backend does not support it.
Args:
attn_groups: The list of attention groups for this model
Returns:
True if we should use a uniform KV cache layout.
"""
if not has_kv_transfer_group():
return False
if not get_kv_transfer_group().prefer_cross_layer_blocks:
return False
if len(attn_groups) != 1 or len(attn_groups[0]) != 1:
return False
attn_group = attn_groups[0][0]
kv_cache_spec = attn_group.kv_cache_spec
if not isinstance(kv_cache_spec, AttentionSpec):
return False
# Per-token-head quant carves inline-scale views that assume per-layer
# contiguous KV buffers; the cross-layer layout breaks this and corrupts KV.
if kv_cache_spec.kv_quant_mode.is_per_token_head:
return False
return kv_cache_spec.indexes_kv_by_block_stride
@staticmethod
def allocate_uniform_kv_caches(
kv_cache_config: KVCacheConfig,
attn_groups: list[list[AttentionGroup]],
cache_dtype: CacheDType,
device: torch.device,
kernel_block_sizes: list[int],
) -> tuple[dict[str, torch.Tensor], torch.Tensor, type[AttentionBackend]]:
"""
Initializes and reshapes KV caches for the simple case where all
layers have the same layout.
This function assumes use_uniform_kv_cache() returned True.
Args:
kv_cache_config: The KV cache config
attn_groups: The list of attention groups for this model
cache_dtype: The KV cache dtype
device: The torch device to allocate on.
kernel_block_sizes: The kernel block sizes for each KV cache group.
Returns:
A tuple (kv_caches, cross_layers_kv_cache, attn_backend) where:
kv_caches is a dict mapping between layer names to their
corresponding memory buffer for KV cache.
cross_layers_kv_cache is the cross layers kv cache tensor
attn_backend is the attention backend matching this tensor
"""
attn_group = attn_groups[0][0]
kv_cache_spec = attn_group.kv_cache_spec
assert isinstance(kv_cache_spec, AttentionSpec)
tensor_sizes = set(
kv_cache_tensor.size for kv_cache_tensor in kv_cache_config.kv_cache_tensors
)
assert len(tensor_sizes) == 1
tensor_size = tensor_sizes.pop()
page_size = kv_cache_spec.page_size_bytes
assert tensor_size % page_size == 0
num_blocks = tensor_size // page_size
num_layers = len(kv_cache_config.kv_cache_tensors)
total_size = tensor_size * num_layers
assert len(kernel_block_sizes) == 1
kernel_block_size = kernel_block_sizes[0]
num_blocks_per_kv_block = kv_cache_spec.block_size // kernel_block_size
kernel_num_blocks = num_blocks * num_blocks_per_kv_block
attn_backend = attn_group.backend
kv_cache_shape = attn_backend.get_kv_cache_shape(
kernel_num_blocks,
kernel_block_size,
kv_cache_spec.num_kv_heads,
kv_cache_spec.head_size,
cache_dtype_str=cache_dtype,
)
# prepend a num_layers dimension into the shape
kv_cache_shape = (num_layers,) + kv_cache_shape
try:
kv_cache_stride_order = attn_backend.get_kv_cache_stride_order(
include_num_layers_dimension=True
)
assert len(kv_cache_stride_order) == len(kv_cache_shape)
except (AttributeError, NotImplementedError):
kv_cache_stride_order = tuple(range(len(kv_cache_shape)))
kv_cache_shape = tuple(kv_cache_shape[i] for i in kv_cache_stride_order)
logger.info("Allocating a cross layer KV cache of shape %s", kv_cache_shape)
# allocate one contiguous buffer for all layers
cross_layers_kv_cache = (
torch.zeros(total_size, dtype=torch.int8, device=device)
.view(kv_cache_spec.dtype)
.view(kv_cache_shape)
)
# Maintain original KV shape view.
inv_order = [
kv_cache_stride_order.index(i) for i in range(len(kv_cache_stride_order))
]
permuted_kv_cache = cross_layers_kv_cache.permute(*inv_order)
kv_caches = {}
for i, kv_cache_tensor in enumerate(kv_cache_config.kv_cache_tensors):
tensor = permuted_kv_cache[i]
for layer_name in kv_cache_tensor.shared_by:
kv_caches[layer_name] = tensor
return kv_caches, cross_layers_kv_cache, attn_backend
+118 -52
View File
@@ -30,9 +30,11 @@ from vllm.v1.kv_cache_interface import (
EncoderOnlyAttentionSpec,
KVCacheConfig,
KVCacheGroupSpec,
KVCacheLayout,
KVCacheSpec,
MambaSpec,
UniformTypeKVCacheSpecs,
create_kv_cache_views,
)
from vllm.v1.worker.block_table import get_block_table_width
@@ -61,10 +63,10 @@ def _zero_kv_blocks_kernel(
):
"""Zero KV cache blocks across all segments in a single launch.
Each segment is a contiguous region of one block's data. For backends
where blocks are outermost (block_dim=0) there is one segment per
buffer. For backends where K/V is outermost (block_dim=1) there are
two segments per buffer (one for K, one for V).
Each segment is a contiguous region of one block's data. Layer-compact
layouts have one segment per layer buffer; dimensions physically outside
the block dim (separate head groups under LHBNC) and virtual block splits
each get their own segment.
Segments may have different block strides and page sizes (e.g. packed
KV views or models with multiple KV cache groups like MLA + DSA
@@ -110,7 +112,6 @@ class KVBlockZeroer:
device: torch.device,
attn_groups_iter: Iterable["AttentionGroup"],
kernel_block_sizes: list[int],
cache_dtype: str,
static_forward_context: dict[str, Any],
runner_only_attn_layers: set[str] | None = None,
) -> None:
@@ -119,6 +120,12 @@ class KVBlockZeroer:
Each entry is the absolute byte address of a segment start on the
GPU, so segments in different CUDA allocations work correctly.
Per-layer views are standardized ``[B, H, N, C]`` with blocks at dim 0; dims
physically outside B (separate head groups under LHBNC) each get their own
segment. A segment's page spans everything inside its block, so under BHLNC it
also covers the block's other layers -- safe, since block IDs are global pool
indices and a newly allocated block owns its whole tile.
Block IDs from the scheduler reference logical blocks whose size
may differ from the kernel block size (virtual block splitting).
Each virtual block is represented as an independent segment so its
@@ -133,7 +140,10 @@ class KVBlockZeroer:
if runner_only_attn_layers is None:
runner_only_attn_layers = set()
seen_ptrs: set[int] = set()
# Overlaid layers (packed layouts) share a base address but may have
# different page sizes; keep the widest span per address so newly
# allocated blocks are fully zeroed for every overlaying group.
seen_ptrs: dict[int, int] = {}
seg_addrs: list[int] = []
seg_block_strides: list[int] = []
seg_page_sizes: list[int] = []
@@ -147,12 +157,6 @@ class KVBlockZeroer:
kernel_bs = kernel_block_sizes[group.kv_cache_group_id]
assert spec.block_size % kernel_bs == 0
ratio = spec.block_size // kernel_bs
block_dim = group.backend.get_kv_cache_block_dim(
kernel_bs,
spec.num_kv_heads,
spec.head_size,
cache_dtype_str=cache_dtype,
)
for layer_name in group.layer_names:
if layer_name in runner_only_attn_layers:
@@ -161,23 +165,18 @@ class KVBlockZeroer:
if not isinstance(kv, torch.Tensor):
continue
dp = kv.data_ptr()
if dp in seen_ptrs:
continue
seen_ptrs.add(dp)
el = kv.element_size()
block_stride_bytes = kv.stride(block_dim) * el
block_stride_bytes = kv.stride(0) * el
assert block_stride_bytes % 4 == 0
assert kv.shape[block_dim] % ratio == 0
assert kv.shape[0] % ratio == 0
outer_dims = [
d
for d in range(block_dim)
for d in range(1, kv.ndim)
if kv.stride(d) * el > block_stride_bytes
]
outer_strides = [kv.stride(d) * el for d in outer_dims]
inner_dims = [
d for d in range(kv.ndim) if d != block_dim and d not in outer_dims
]
inner_dims = [d for d in range(1, kv.ndim) if d not in outer_dims]
kernel_page_bytes = el + sum(
(kv.shape[d] - 1) * kv.stride(d) * el for d in inner_dims
)
@@ -187,9 +186,18 @@ class KVBlockZeroer:
off_bytes = sum(i * s for i, s in zip(outer, outer_strides))
assert (dp + off_bytes) % 4 == 0
for virtual_index in range(ratio):
seg_addrs.append(
dp + off_bytes + virtual_index * block_stride_bytes
)
addr = dp + off_bytes + virtual_index * block_stride_bytes
if (idx := seen_ptrs.get(addr)) is not None:
assert (
seg_block_strides[idx]
== logical_block_stride_bytes // 4
)
seg_page_sizes[idx] = max(
seg_page_sizes[idx], kernel_page_bytes // 4
)
continue
seen_ptrs[addr] = len(seg_addrs)
seg_addrs.append(addr)
seg_block_strides.append(logical_block_stride_bytes // 4)
seg_page_sizes.append(kernel_page_bytes // 4)
@@ -367,6 +375,54 @@ def select_common_block_size(
raise ValueError(f"No common block size for {kv_manager_block_size}. ")
def allocate_kv_cache(
kv_cache_config: KVCacheConfig,
device: torch.device,
layout: KVCacheLayout,
kernel_block_sizes: list[int] | None = None,
) -> dict[str, torch.Tensor]:
"""Allocate the KV cache and view it as ``[B, H, N, C]`` per layer.
Every KVCacheTensor places its layers in the same backing allocation: layer ``l`` of
block ``b`` starts at ``offset + l * layer_stride + b * block_stride``. Cache
groups overlay each other, so tensors may address the same bytes.
"""
if not kv_cache_config.kv_cache_tensors:
return {}
sizes = {tensor.size for tensor in kv_cache_config.kv_cache_tensors}
assert len(sizes) == 1, "KV cache tensors must share one backing allocation."
buf = torch.zeros(sizes.pop(), dtype=torch.int8, device=device)
kv_caches: dict[str, torch.Tensor] = {}
for tensor in kv_cache_config.kv_cache_tensors:
layer_name = tensor.layers[0]
group_id, group = next(
(group_id, group)
for group_id, group in enumerate(kv_cache_config.kv_cache_groups)
if layer_name in group.layer_names
)
spec = group.kv_cache_spec
if isinstance(spec, UniformTypeKVCacheSpecs):
spec = spec.kv_cache_specs[layer_name]
num_blocks = kv_cache_config.num_blocks
kernel_block_size = None
if kernel_block_sizes is not None and group_id < len(kernel_block_sizes):
kernel_block_size = kernel_block_sizes[group_id]
views = create_kv_cache_views(
buf,
spec,
num_blocks,
layout,
tensor,
kernel_block_size=kernel_block_size,
)
kv_caches.update(zip(tensor.layers, views))
return kv_caches
def prepare_kernel_block_sizes(
kv_cache_config: KVCacheConfig, attn_groups: list[list[AttentionGroup]]
) -> list[int]:
@@ -551,42 +607,52 @@ def bind_kv_cache(
def copy_kv_cache_blocks_inplace(
kv_caches: Iterable[torch.Tensor | list[torch.Tensor]],
kv_caches: Iterable[torch.Tensor],
num_blocks: int,
kv_cache_block_copies: Sequence[KVCacheBlockCopy],
) -> None:
if not kv_cache_block_copies:
return
storage_tensors: list[torch.Tensor] = []
seen_storage: set[int] = set()
for entry in kv_caches:
# Mamba layers hold a list of state tensors; attention layers a single
# tensor. Both alias the shared block-major backing storage.
tensors = entry if isinstance(entry, (list, tuple)) else (entry,)
for tensor in tensors:
ptr = tensor.untyped_storage().data_ptr()
if ptr in seen_storage:
continue
seen_storage.add(ptr)
storage_tensors.append(tensor)
if not storage_tensors:
return
device = storage_tensors[0].device
indices_np = np.array(kv_cache_block_copies, dtype=np.int64)
indices = async_tensor_h2d(indices_np, device=device)
src_indices, dst_indices = indices.unbind(dim=1)
indices: torch.Tensor | None = None
seen: set[tuple[torch.device, int]] = set()
copied_storages: set[tuple[torch.device, int]] = set()
for cache in kv_caches:
# Layers sharing KV (cross-layer sharing) alias the same view; copy it
# once. data_ptr distinguishes per-layer views of a shared allocation.
key = (cache.device, cache.data_ptr())
if key in seen:
continue
seen.add(key)
for tensor in storage_tensors:
assert tensor.device == device
blocks = torch.empty(0, dtype=torch.uint8, device=device)
blocks.set_(tensor.untyped_storage())
# Block-major backing storage: block i owns the contiguous byte range
# [i * page_size, (i + 1) * page_size).
assert blocks.numel() % num_blocks == 0
blocks = blocks.view(num_blocks, -1)
blocks[dst_indices] = blocks[src_indices]
if indices is None:
indices = async_tensor_h2d(indices_np, device=cache.device)
assert cache.device == indices.device
src, dst = indices.unbind(dim=1)
kernel_blocks_per_block, remainder = divmod(cache.shape[0], num_blocks)
assert remainder == 0, (
f"{cache.shape[0]} kernel blocks not divisible by "
f"{num_blocks} scheduler blocks"
)
storage = cache.untyped_storage()
storage_key = (cache.device, storage.data_ptr())
scheduler_block_stride = (
cache.stride(0) * cache.element_size() * kernel_blocks_per_block
)
if storage.nbytes() == num_blocks * scheduler_block_stride:
if storage_key in copied_storages:
continue
copied_storages.add(storage_key)
blocks = torch.empty(0, dtype=torch.uint8, device=cache.device)
blocks.set_(storage)
blocks = blocks.view(num_blocks, -1)
else:
# Fold virtual block splitting into the shape so that dim 0 counts
# scheduler blocks; unflatten of dim 0 is always a view.
blocks = cache.unflatten(0, (num_blocks, kernel_blocks_per_block))
blocks[dst] = blocks[src]
def is_uniform_query_len(num_reqs: int, num_tokens: int, max_query_len: int) -> bool:
+14
View File
@@ -9,12 +9,17 @@ import torch.nn as nn
import vllm.ir
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.distributed.kv_transfer.kv_connector.utils import get_current_attn_backends
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.tracing import instrument
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm.utils.system_utils import update_environment_variables
from vllm.v1.attention.backends.utils import (
get_supported_kv_cache_layouts,
record_kv_cache_layout,
)
from vllm.v1.kv_cache_interface import KVCacheSpec
if TYPE_CHECKING:
@@ -99,6 +104,15 @@ class WorkerBase:
"""Get specifications for KV cache implementation."""
raise NotImplementedError
def get_supported_kv_cache_layouts(self) -> list[str]:
"""Layout names every attention backend supports, most preferred first."""
backends = get_current_attn_backends(self.vllm_config)
return [layout.name for layout in get_supported_kv_cache_layouts(backends)]
def set_kv_cache_layout(self, kv_cache_layout: str) -> None:
"""Adopt the KV cache layout resolved by the engine core."""
record_kv_cache_layout(self.vllm_config.cache_config, kv_cache_layout)
def compile_or_warm_up_model(self) -> CompilationTimes:
"""Prepare model for execution through compilation/warmup.