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