[6/N][KV-Cache Layout Refactor] Standardize KV cache layout (#51718)
Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com>
This commit is contained in:
@@ -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 = (
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user