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