[Model] add GLM-5.3-Flash support (#53906)
This commit is contained in:
@@ -610,6 +610,10 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
self.layer_names = layer_names
|
||||
self.vllm_config = vllm_config
|
||||
self.device = device
|
||||
self.kernel_block_size: int | None = None
|
||||
|
||||
def set_kernel_block_size(self, kernel_block_size: int) -> None:
|
||||
self.kernel_block_size = kernel_block_size
|
||||
|
||||
@classmethod
|
||||
def get_cudagraph_support(
|
||||
|
||||
@@ -54,7 +54,10 @@ class _FlashInferMLASparseBackendBase(AttentionBackend):
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
return [576]
|
||||
# 576 = 512 NoPE + 64 RoPE (with-rope layout); 512 = 512 NoPE only
|
||||
# (no-rope layout, qk_rope_head_dim == 0). Both share D_V = 512 and are
|
||||
# served by the TRTLLM-GEN sparse MLA kernel.
|
||||
return [512, 576]
|
||||
|
||||
@classmethod
|
||||
def is_mla(cls) -> bool:
|
||||
@@ -117,8 +120,20 @@ class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase):
|
||||
# FlashInfer MLA sparse SM10 kernel requires qk_nope_head_dim in [128, 192].
|
||||
if vllm_config.model_config is not None:
|
||||
hf_text_config = vllm_config.model_config.hf_text_config
|
||||
qk_nope_head_dim = getattr(hf_text_config, "qk_nope_head_dim", 1)
|
||||
if qk_nope_head_dim not in [128, 192]:
|
||||
qk_nope_head_dim = hf_text_config.qk_nope_head_dim
|
||||
qk_rope_head_dim = hf_text_config.qk_rope_head_dim
|
||||
kv_lora_rank = hf_text_config.kv_lora_rank
|
||||
if qk_rope_head_dim == 0:
|
||||
# Native no-rope MLA: FlashInfer only ships the one shape
|
||||
# (nope_mla_dimensions in flashinfer.mla._core).
|
||||
if qk_nope_head_dim != 256 or kv_lora_rank != 512:
|
||||
return (
|
||||
"FlashInfer native no-rope MLA requires "
|
||||
"qk_nope_head_dim=256 and kv_lora_rank=512, but got "
|
||||
f"qk_nope_head_dim={qk_nope_head_dim}, "
|
||||
f"kv_lora_rank={kv_lora_rank}"
|
||||
)
|
||||
elif qk_nope_head_dim not in [128, 192]:
|
||||
return (
|
||||
"FlashInfer MLA Sparse kernel requires qk_nope_head_dim "
|
||||
f"in [128, 192], but got {qk_nope_head_dim}"
|
||||
@@ -358,6 +373,10 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
self.bmm1_scale: float | None = None
|
||||
self.bmm2_scale: float | None = None
|
||||
|
||||
# Native no-rope MLA additionally requires a per-query-token active
|
||||
# top-k length tensor.
|
||||
self.is_nope_mla = self.qk_rope_head_dim == 0
|
||||
|
||||
# fp8 query quantization is required when using fp8 kv_cache,
|
||||
# as the TRTLLM-GEN sparse MLA kernel requires matching dtypes
|
||||
# for query and kv_cache (mixed bf16+fp8 is not supported).
|
||||
@@ -429,6 +448,31 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
block_tables = topk_indices_physical.unsqueeze(1)
|
||||
seq_lens_arg = seq_lens
|
||||
|
||||
# page_table width = topk buffer width, which kpool widens past
|
||||
# index_topk (topk_tokens) and rounds up to a multiple of 128. The
|
||||
# kernel treats sparse_mla_top_k as the page-table *capacity* and bounds
|
||||
# the active per-query length by ``seq_lens`` (the compacted valid
|
||||
# count), so the -1 padding slots past seq_lens are never attended to.
|
||||
# Use the actual buffer width instead of the fixed topk_tokens, which
|
||||
# mismatches the page_table when index_kpool > 1.
|
||||
sparse_topk_capacity = topk_indices_physical.shape[1]
|
||||
|
||||
extra_kwargs: dict[str, torch.Tensor] = {}
|
||||
empty_rows: torch.Tensor | None = None
|
||||
if self.is_nope_mla:
|
||||
# The native no-rope kernel takes the active top-k length per query
|
||||
# token (``seq_lens`` here is already the compacted per-token valid
|
||||
# count, int32) and rejects zero-length rows. Point empty rows at a
|
||||
# single valid dummy slot with length 1 and zero their output after
|
||||
# the launch. ``triton_convert_req_index_to_global_index`` packs the
|
||||
# valid indices into a contiguous prefix, which is what the kernel
|
||||
# requires of the page table.
|
||||
empty_rows = seq_lens == 0
|
||||
topk_indices_physical[:, 0] = topk_indices_physical[:, 0].masked_fill(
|
||||
empty_rows, 0
|
||||
)
|
||||
extra_kwargs["sparse_mla_top_k_lens"] = seq_lens.clamp(min=1)
|
||||
|
||||
kernel_out = trtllm_batch_decode_with_kv_cache_mla(
|
||||
query=query,
|
||||
kv_cache=kv_c_and_k_pe_cache.unsqueeze(1),
|
||||
@@ -438,11 +482,12 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
qk_rope_head_dim=self.qk_rope_head_dim,
|
||||
block_tables=block_tables,
|
||||
seq_lens=seq_lens_arg,
|
||||
max_seq_len=attn_metadata.topk_tokens,
|
||||
max_seq_len=sparse_topk_capacity,
|
||||
bmm1_scale=self.bmm1_scale,
|
||||
bmm2_scale=self.bmm2_scale,
|
||||
sparse_mla_top_k=attn_metadata.topk_tokens,
|
||||
sparse_mla_top_k=sparse_topk_capacity,
|
||||
return_lse=self.need_to_return_lse_for_decode,
|
||||
**extra_kwargs,
|
||||
)
|
||||
if self.need_to_return_lse_for_decode:
|
||||
assert isinstance(kernel_out, tuple)
|
||||
@@ -455,9 +500,12 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
out = o.view(-1, o.shape[-2], o.shape[-1])
|
||||
if lse is not None:
|
||||
lse = self._normalize_lse(lse, out.shape[0], out.shape[1])
|
||||
if empty_rows is None and lse is not None:
|
||||
empty_rows = (topk_indices_physical == -1).all(dim=-1)
|
||||
if empty_rows is not None:
|
||||
out.masked_fill_(empty_rows.view(-1, 1, 1), 0.0)
|
||||
lse.masked_fill_(empty_rows.view(-1, 1), float("-inf"))
|
||||
if lse is not None:
|
||||
lse.masked_fill_(empty_rows.view(-1, 1), float("-inf"))
|
||||
return out, lse
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlashInfer sparse MLA backend for SM90 (Hopper) NoPE models.
|
||||
|
||||
Wraps FlashInfer's ``BatchMLAPagedAttentionWrapper`` (FA2/FA3 paths), which
|
||||
as of FlashInfer 0.6.18 supports ``head_dim_kpe=0`` (GLM-5.3-Flash NoPE MLA)
|
||||
and FP8 E4M3 KV caches on SM90 with in-kernel dequantization: the FP8 cache
|
||||
is read directly (half the bf16 HBM traffic) and converted to BF16 in shared
|
||||
memory, while queries stay BF16 (no query quantization).
|
||||
|
||||
Sparsity rides the same trick the FA-based sparse backend uses: with
|
||||
``page_size=1`` the per-token top-k slot indices ARE the page table, so each
|
||||
query token becomes one varlen batch row whose ``kv_indices`` slice is its
|
||||
top-k row and whose ``kv_len`` is its valid count. Causality is already
|
||||
encoded by the indexer's selection, so ``causal=False``.
|
||||
|
||||
CUDA-graph handling: ``plan()`` copies its inputs to host unconditionally,
|
||||
so it must stay outside graph capture. Each metadata builder owns a wrapper,
|
||||
reserved capture-stable device buffers, and the plan parameters. The wrapper
|
||||
bakes the per-row ``kv_len`` into its int schedule
|
||||
at plan() time — ``run()`` never reads the device-side buffer — so the
|
||||
metadata builder replans every step (outside capture) with exact host-side
|
||||
lengths derived from the batch's sequence lengths; a full-width schedule
|
||||
would send the kernel past each row's valid count into the -1 tail of the
|
||||
converted index buffer (illegal address). Per-step content (top-k slots)
|
||||
is written into the reserved buffers by kernels inside the captured
|
||||
forward, and captured runs read the refreshed plan buffers on replay.
|
||||
|
||||
KV cache format: plain contiguous E4M3 ``[num_blocks, block_size, 512]``
|
||||
(uint8 storage) with a per-tensor ``k_scale``; BF16 caches also work. The
|
||||
per-token x 128-channel-group ``ckv_scale_arr`` layout is supported by the
|
||||
kernel but not wired yet (it needs a group-quantizing cache-write op).
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.model_executor.layers.attention.sparse_mla_attention import (
|
||||
SparseMLACommonImpl,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.utils.flashinfer import has_flashinfer_sm90_nope_mla
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionLayer,
|
||||
CommonAttentionMetadata,
|
||||
MLAAttentionImpl,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
FlashInferMLASparseMetadata,
|
||||
FlashInferMLASparseMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
|
||||
|
||||
_FP8_KV_DTYPES = ("fp8", "fp8_e4m3")
|
||||
_WORKSPACE_BYTES = 128 * 1024 * 1024
|
||||
|
||||
|
||||
class FlashInferMLASparseSM90Backend(AttentionBackend):
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [MultipleOf(64)]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_MLA_SPARSE_SM90"
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["FlashInferMLASparseSM90Builder"]:
|
||||
return FlashInferMLASparseSM90Builder
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[MLAAttentionImpl]:
|
||||
return FlashInferMLASparseSM90Impl
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
# 512 = ckv 512 + kpe 0 (NoPE); 576 = ckv 512 + kpe 64.
|
||||
return [512, 576]
|
||||
|
||||
@classmethod
|
||||
def is_mla(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
|
||||
return capability.major == 9
|
||||
|
||||
@classmethod
|
||||
def supports_combination(
|
||||
cls,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
kv_cache_dtype: CacheDType | None,
|
||||
block_size: int | None,
|
||||
use_mla: bool,
|
||||
has_sink: bool,
|
||||
use_sparse: bool,
|
||||
use_mm_prefix: bool,
|
||||
device_capability: DeviceCapability,
|
||||
) -> str | None:
|
||||
if not has_flashinfer_sm90_nope_mla():
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE_SM90 requires FlashInfer with SM90 "
|
||||
"MLA support (ckv_scale_arr in "
|
||||
"BatchMLAPagedAttentionWrapper.run, FlashInfer >= 0.6.18)"
|
||||
)
|
||||
if not use_sparse:
|
||||
return "FLASHINFER_MLA_SPARSE_SM90 requires sparse MLA"
|
||||
from vllm.config import get_current_vllm_config
|
||||
|
||||
vllm_config = get_current_vllm_config()
|
||||
if vllm_config.model_config is not None:
|
||||
hf = vllm_config.model_config.hf_text_config
|
||||
# The SM90 FA2/FA3 kernel covers ckv=512 with kpe in {0, 64}
|
||||
# (NoPE models and DeepSeek-style rope MLA alike).
|
||||
if hf.kv_lora_rank != 512:
|
||||
return "FLASHINFER_MLA_SPARSE_SM90 requires kv_lora_rank=512"
|
||||
if hf.qk_rope_head_dim not in (0, 64):
|
||||
return "FLASHINFER_MLA_SPARSE_SM90 requires qk_rope_head_dim in (0, 64)"
|
||||
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)
|
||||
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
|
||||
return (KVCacheLayout.LBHNC,)
|
||||
|
||||
|
||||
class _SM90State:
|
||||
"""Builder-owned wrapper, capture-stable buffers, and plan parameters.
|
||||
|
||||
One instance serves every MLA layer in an attention group because the plan
|
||||
depends only on the batch shape, not the layer.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
device: torch.device,
|
||||
num_heads: int,
|
||||
kv_dtype: torch.dtype,
|
||||
max_tokens: int,
|
||||
topk_width: int,
|
||||
kv_lora_rank: int,
|
||||
qk_rope_head_dim: int,
|
||||
sm_scale: float,
|
||||
) -> None:
|
||||
from flashinfer.mla import BatchMLAPagedAttentionWrapper
|
||||
|
||||
self.workspace = torch.empty(_WORKSPACE_BYTES, dtype=torch.uint8, device=device)
|
||||
self.device = device
|
||||
self.num_heads = num_heads
|
||||
self.kv_dtype = kv_dtype
|
||||
self.max_tokens = max_tokens
|
||||
self.topk_width = topk_width
|
||||
self.kv_lora_rank = kv_lora_rank
|
||||
self.qk_rope_head_dim = qk_rope_head_dim
|
||||
self.sm_scale = sm_scale
|
||||
# User-reserved buffers: with use_cuda_graph=True plan() refreshes
|
||||
# these in place, so run()'s captured kernels always read them.
|
||||
self.kv_indices = torch.zeros(
|
||||
max_tokens * topk_width, dtype=torch.int32, device=device
|
||||
)
|
||||
self.kv_len_arr = torch.full(
|
||||
(max_tokens,), topk_width, dtype=torch.int32, device=device
|
||||
)
|
||||
self.wrapper = BatchMLAPagedAttentionWrapper(
|
||||
self.workspace,
|
||||
qo_indptr=torch.zeros(max_tokens + 1, dtype=torch.int32, device=device),
|
||||
kv_indptr=torch.zeros(max_tokens + 1, dtype=torch.int32, device=device),
|
||||
kv_indices=self.kv_indices,
|
||||
kv_len_arr=self.kv_len_arr,
|
||||
use_cuda_graph=True,
|
||||
backend="fa3",
|
||||
)
|
||||
self._arange_cpu = torch.arange(self.max_tokens + 1, dtype=torch.int32)
|
||||
self._qo_cpu = torch.empty(self.max_tokens + 1, dtype=torch.int32)
|
||||
self._kv_cpu = torch.empty(self.max_tokens + 1, dtype=torch.int32)
|
||||
self._lens_cpu = torch.full(
|
||||
(self.max_tokens,), self.topk_width, dtype=torch.int32
|
||||
)
|
||||
|
||||
def plan(self, num_tokens: int, kv_lens: torch.Tensor) -> None:
|
||||
"""Replan with exact per-row KV lengths (CPU int32, ``[num_tokens]``).
|
||||
|
||||
The wrapper bakes kv_len into its int schedule from host values;
|
||||
run() never reads the device kv_len_arr buffer. Scheduling with the
|
||||
full buffer width while kv_indices rows carry a -1 tail past each
|
||||
row's valid count makes the kernel compute ``-1 * ckv_stride_page``
|
||||
(illegal address), so the lengths must be exact at plan time and
|
||||
replanned every step as contexts grow. Must run outside CUDA graph
|
||||
capture: the in-place refreshed plan_info/indptr buffers are what
|
||||
captured runs read.
|
||||
"""
|
||||
if torch.cuda.is_current_stream_capturing():
|
||||
raise RuntimeError(
|
||||
"FlashInferMLASparseSM90 plan() called inside CUDA graph "
|
||||
"capture; lengths must be planned host-side before capture."
|
||||
)
|
||||
# CPU staging buffers are filled in place: plan() runs per step
|
||||
# (once per draft/verify metadata build), so per-call allocations and
|
||||
# device round trips are on the hot path. Passing CPU tensors lets
|
||||
# the wrapper's internal .to("cpu") no-op; its reserved-buffer
|
||||
# copy_ then performs the single H2D transfer per tensor.
|
||||
# use_cuda_graph=True makes the wrapper copy qo/kv indptr into its
|
||||
# fixed (max_tokens+1)-sized buffers with exact-size copy_, so the
|
||||
# indptr must always be full-size. Rows past num_tokens are padded
|
||||
# empty (qo_indptr flat at num_tokens) — zero-query rows read no q
|
||||
# and schedule no work. Padded rows keep the full width lens; the
|
||||
# value is never dereferenced.
|
||||
torch.clamp(self._arange_cpu, max=num_tokens, out=self._qo_cpu)
|
||||
torch.mul(self._qo_cpu, self.topk_width, out=self._kv_cpu)
|
||||
self._lens_cpu.fill_(self.topk_width)
|
||||
self._lens_cpu[:num_tokens] = kv_lens.to(torch.int32)
|
||||
self.wrapper.plan(
|
||||
self._qo_cpu,
|
||||
self._kv_cpu,
|
||||
self.kv_indices,
|
||||
self._lens_cpu,
|
||||
self.num_heads,
|
||||
self.kv_lora_rank, # head_dim_ckv
|
||||
self.qk_rope_head_dim, # 0 (NoPE) or 64 (rope MLA)
|
||||
1, # page_size: top-k slots are the page table
|
||||
False, # causal: encoded by the indexer's selection
|
||||
self.sm_scale,
|
||||
q_data_type=torch.bfloat16,
|
||||
kv_data_type=self.kv_dtype,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FlashInferMLASparseSM90Metadata(FlashInferMLASparseMetadata):
|
||||
state: _SM90State | None = None
|
||||
|
||||
|
||||
class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
|
||||
"""Reuse the common sparse metadata (req ids, topk buffer access)."""
|
||||
|
||||
metadata_cls = FlashInferMLASparseSM90Metadata
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: "AttentionSpec",
|
||||
layer_names: list[str],
|
||||
vllm_config: "VllmConfig",
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
attention_layer = vllm_config.compilation_config.static_forward_context[
|
||||
layer_names[0]
|
||||
]
|
||||
impl = attention_layer.impl
|
||||
if not isinstance(impl, FlashInferMLASparseSM90Impl):
|
||||
raise TypeError(
|
||||
"FlashInferMLASparseSM90Builder requires an SM90 FlashInfer "
|
||||
f"implementation, got {type(impl).__name__}."
|
||||
)
|
||||
topk_indices_buffer = impl.topk_indices_buffer
|
||||
assert topk_indices_buffer is not None
|
||||
self.state = _SM90State(
|
||||
device,
|
||||
impl.num_heads,
|
||||
kv_cache_spec.dtype,
|
||||
vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
topk_indices_buffer.shape[1],
|
||||
kv_lora_rank=impl.kv_lora_rank,
|
||||
qk_rope_head_dim=impl.qk_rope_head_dim,
|
||||
sm_scale=impl.scale,
|
||||
)
|
||||
# seq_lens_cpu_upper_bound is optimistic on decode rows under async
|
||||
# spec decode, so the fast sync-free path is only safe without it;
|
||||
# under async scheduling the exact (device) positions are used at
|
||||
# the cost of one D2H sync per metadata build.
|
||||
self._async_scheduling = bool(vllm_config.scheduler_config.async_scheduling)
|
||||
hf_config = vllm_config.model_config.hf_text_config
|
||||
assert hf_config.index_topk is not None
|
||||
self._index_topk = int(hf_config.index_topk)
|
||||
self._index_kpool = int(kv_cache_spec.tokens_per_state)
|
||||
|
||||
def _kv_lens_host(self, cam: CommonAttentionMetadata) -> tuple[int, torch.Tensor]:
|
||||
"""Exact per-row KV lengths, host-side (the flashinfer wrapper bakes
|
||||
them into its schedule at plan time; there is no device-side path).
|
||||
|
||||
A row for the j-th query token of request i attends
|
||||
``seq_lens[i] - q_len[i] + j + 1`` tokens. The indexer's selection
|
||||
then bounds the valid count: contexts up to ``index_topk`` select
|
||||
everything (valid == context); longer contexts keep the top
|
||||
``index_topk`` pool-expanded tokens plus the trailing incomplete
|
||||
pool (valid == ``index_topk + context % index_kpool``). Both match
|
||||
the count of non -1 entries the convert kernel produces.
|
||||
"""
|
||||
num_reqs = cam.num_reqs
|
||||
qsl = cam.query_start_loc_cpu[: num_reqs + 1]
|
||||
num_rows = int(qsl[-1])
|
||||
if num_rows == 0:
|
||||
return 0, torch.zeros(0, dtype=torch.int32)
|
||||
# Row context == position + 1. Without async scheduling the
|
||||
# maintained host upper bound is exact, giving a sync-free path;
|
||||
# under async scheduling it is optimistic on decode rows, so fall
|
||||
# back to the exact device positions (one D2H sync per build). The
|
||||
# seq_lens derivation equals position + 1 because positions are
|
||||
# contiguous per request.
|
||||
sl_host = cam.seq_lens_cpu_upper_bound
|
||||
positions = cam.positions
|
||||
if not self._async_scheduling and sl_host is not None:
|
||||
seq_lens = sl_host[:num_reqs].to(torch.int32)
|
||||
q_lens = qsl[1:] - qsl[:-1]
|
||||
first_pos = seq_lens - q_lens
|
||||
req_of_row = torch.repeat_interleave(
|
||||
torch.arange(num_reqs, dtype=torch.int64), q_lens.to(torch.int64)
|
||||
)
|
||||
rows = torch.arange(num_rows, dtype=torch.int32)
|
||||
ctx = (
|
||||
first_pos.to(torch.int64)[req_of_row]
|
||||
+ rows.to(torch.int64)
|
||||
- qsl.to(torch.int64)[req_of_row]
|
||||
+ 1
|
||||
)
|
||||
elif positions is not None and num_rows <= positions.shape[0]:
|
||||
ctx = positions[:num_rows].cpu().to(torch.int64) + 1
|
||||
else:
|
||||
seq_lens = cam.seq_lens[:num_reqs].cpu().to(torch.int32)
|
||||
q_lens = qsl[1:] - qsl[:-1]
|
||||
first_pos = seq_lens - q_lens
|
||||
req_of_row = torch.repeat_interleave(
|
||||
torch.arange(num_reqs, dtype=torch.int64), q_lens.to(torch.int64)
|
||||
)
|
||||
rows = torch.arange(num_rows, dtype=torch.int32)
|
||||
ctx = (
|
||||
first_pos.to(torch.int64)[req_of_row]
|
||||
+ rows.to(torch.int64)
|
||||
- qsl.to(torch.int64)[req_of_row]
|
||||
+ 1
|
||||
)
|
||||
topk = self._index_topk
|
||||
kpool = max(self._index_kpool, 1)
|
||||
lens = torch.where(ctx <= topk, ctx, topk + ctx % kpool)
|
||||
return num_rows, lens.to(torch.int32)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> FlashInferMLASparseSM90Metadata:
|
||||
metadata = super().build(common_prefix_len, common_attn_metadata, fast_build)
|
||||
assert isinstance(metadata, FlashInferMLASparseSM90Metadata)
|
||||
# Replan every step outside any CUDA graph capture with this step's
|
||||
# exact per-row lengths; captured runs read the refreshed buffers.
|
||||
num_rows, kv_lens = self._kv_lens_host(common_attn_metadata)
|
||||
self.state.plan(num_rows, kv_lens)
|
||||
metadata.state = self.state
|
||||
return metadata
|
||||
|
||||
|
||||
class FlashInferMLASparseSM90Impl(SparseMLACommonImpl[FlashInferMLASparseSM90Metadata]):
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
scale: float,
|
||||
num_kv_heads: int,
|
||||
alibi_slopes: list[float] | None,
|
||||
sliding_window: int | None,
|
||||
kv_cache_dtype: str,
|
||||
logits_soft_cap: float | None,
|
||||
attn_type: str,
|
||||
kv_sharing_target_layer_name: str | None,
|
||||
topk_indices_buffer: torch.Tensor | None = None,
|
||||
indexer: Any | None = None,
|
||||
**mla_args: Any,
|
||||
) -> None:
|
||||
if any([alibi_slopes, sliding_window, logits_soft_cap]):
|
||||
raise NotImplementedError(
|
||||
"FlashInferMLASparseSM90Impl does not support alibi, sliding "
|
||||
"window, or logits soft cap."
|
||||
)
|
||||
super().__init__(
|
||||
num_heads,
|
||||
head_size,
|
||||
scale,
|
||||
num_kv_heads,
|
||||
alibi_slopes,
|
||||
sliding_window,
|
||||
kv_cache_dtype,
|
||||
logits_soft_cap,
|
||||
attn_type,
|
||||
kv_sharing_target_layer_name,
|
||||
indexer=indexer,
|
||||
topk_indices_buffer=topk_indices_buffer,
|
||||
**mla_args,
|
||||
)
|
||||
assert self.topk_indices_buffer is not None
|
||||
self.supports_quant_query_input = False
|
||||
self.use_fp8_kv_cache = self.kv_cache_dtype in _FP8_KV_DTYPES
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
kv_c_and_k_pe_cache: torch.Tensor,
|
||||
attn_metadata: FlashInferMLASparseSM90Metadata,
|
||||
layer: AttentionLayer,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
if not isinstance(q, tuple):
|
||||
raise NotImplementedError(
|
||||
"FlashInferMLASparseSM90Impl expects split (q_nope, q_rope)."
|
||||
)
|
||||
q_nope, q_rope = q
|
||||
num_tokens = q_rope.shape[0]
|
||||
# NoPE models hand a zero-width rope tensor through; rope MLA hands
|
||||
# the real 64-dim part. The kernel takes both as-is.
|
||||
q_pe = q_rope.reshape(num_tokens, self.num_heads, self.qk_rope_head_dim)
|
||||
|
||||
assert self.topk_indices_buffer is not None
|
||||
topk_indices = self.topk_indices_buffer[:num_tokens]
|
||||
# return_valid_counts=True keeps the compacted-prefix layout: valid
|
||||
# entries at [0, valid_count), -1 past it — exactly the prefix the
|
||||
# planned per-row lengths address.
|
||||
topk_slots, _ = triton_convert_req_index_to_global_index(
|
||||
attn_metadata.req_id_per_token[:num_tokens],
|
||||
attn_metadata.block_table,
|
||||
topk_indices,
|
||||
BLOCK_SIZE=attn_metadata.block_size,
|
||||
NUM_TOPK_TOKENS=topk_indices.shape[1],
|
||||
return_valid_counts=True,
|
||||
)
|
||||
state = attn_metadata.state
|
||||
assert state is not None
|
||||
# Refresh top-k rows in graph and clamp masked tails to a valid slot;
|
||||
# per-row lengths are already baked into the host-side plan.
|
||||
width = topk_slots.shape[1]
|
||||
state.kv_indices[: num_tokens * width].copy_(
|
||||
topk_slots.reshape(-1).clamp_(min=0).to(torch.int32)
|
||||
)
|
||||
|
||||
flat = (
|
||||
kv_c_and_k_pe_cache.view(torch.float8_e4m3fn)
|
||||
if self.use_fp8_kv_cache
|
||||
else kv_c_and_k_pe_cache
|
||||
).reshape(-1, 1, self.head_size)
|
||||
ckv = flat[..., : self.kv_lora_rank]
|
||||
kpe = flat[..., self.kv_lora_rank :]
|
||||
|
||||
scale_kwargs = (
|
||||
{"ckv_scale": float(layer._k_scale_float or 1.0), "kpe_scale": 1.0}
|
||||
if self.use_fp8_kv_cache
|
||||
else {}
|
||||
)
|
||||
out = state.wrapper.run(q_nope, q_pe, ckv, kpe, **scale_kwargs)
|
||||
return out, None
|
||||
@@ -37,7 +37,12 @@ from vllm.v1.attention.backends.utils import (
|
||||
get_dcp_local_seq_lens,
|
||||
split_decodes_and_prefills,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import KVCacheLayout, KVCacheSpec, MLAAttentionSpec
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MLAAttentionSpec,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -252,6 +257,30 @@ class DeepseekV32IndexerBackend(AttentionBackend):
|
||||
return DeepseekV32IndexerMetadataBuilder
|
||||
|
||||
|
||||
class KpoolTailBackend(DeepseekV32IndexerBackend):
|
||||
"""Storage-only backend for the GLM-5.3-Flash kpool tail cache."""
|
||||
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
|
||||
return (KVCacheLayout.LBHNC,)
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "KPOOL_TAIL"
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [MultipleOf(1)]
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["KpoolTailMetadataBuilder"]: # type: ignore[override]
|
||||
return KpoolTailMetadataBuilder
|
||||
|
||||
|
||||
class DeepseekV4IndexerBackend(DeepseekV32IndexerBackend):
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
@@ -419,6 +448,9 @@ class BuildPrefillChunkMetadataKernel(
|
||||
)
|
||||
)
|
||||
)
|
||||
index_kpool = getattr(hf_config, "index_kpool", None)
|
||||
if index_kpool and index_kpool > 1 and index_kpool not in compress_ratios:
|
||||
compress_ratios = compress_ratios + (index_kpool,)
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
# Cover Triton's divisible, exact-one, and generic i32 classes.
|
||||
query_slice_start=(0, 1, 2),
|
||||
@@ -483,6 +515,7 @@ class BuildPrefillChunkMetadataKernel(
|
||||
@dataclass
|
||||
class DeepseekV32IndexerPrefillMetadata:
|
||||
chunks: list[DeepseekV32IndexerPrefillChunkMetadata]
|
||||
max_prefill_seq_len: int = -1
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -497,6 +530,9 @@ class DeepSeekV32IndexerDecodeMetadata:
|
||||
requires_padding: bool
|
||||
schedule_metadata: torch.Tensor
|
||||
global_seq_lens: torch.Tensor | None = None
|
||||
per_req_decode_lens: torch.Tensor | None = None
|
||||
decode_is_uniform: bool = True
|
||||
write_max_decode_len: int = 0
|
||||
indices: torch.Tensor | None = None
|
||||
|
||||
|
||||
@@ -519,6 +555,90 @@ class DeepseekV32IndexerMetadata:
|
||||
prefill: DeepseekV32IndexerPrefillMetadata | None = None
|
||||
|
||||
|
||||
def compute_kpool_tail_slot_mapping(
|
||||
slot_mapping: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
num_actual_tokens: int,
|
||||
num_reqs: int,
|
||||
kpool: int,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Map every token to its request's one circular tail block."""
|
||||
if out is None:
|
||||
out = slot_mapping.clone()
|
||||
else:
|
||||
assert out.shape == slot_mapping.shape
|
||||
out.copy_(slot_mapping)
|
||||
if num_actual_tokens == 0:
|
||||
return out
|
||||
tokens = torch.arange(num_actual_tokens, device=slot_mapping.device)
|
||||
req = torch.searchsorted(query_start_loc, tokens, right=True) - 1
|
||||
req = req.clamp_(min=0, max=num_reqs - 1)
|
||||
own_block = block_table[:num_reqs, 0].index_select(0, req).to(torch.int64)
|
||||
pos = positions[:num_actual_tokens].to(torch.int64)
|
||||
out[:num_actual_tokens] = own_block * kpool + torch.remainder(pos, kpool)
|
||||
return out
|
||||
|
||||
|
||||
class KpoolTailMetadataBuilder(AttentionMetadataBuilder):
|
||||
"""Build only the circular slot mapping needed by the storage-only tail."""
|
||||
|
||||
_cudagraph_support = AttentionCGSupport.ALWAYS
|
||||
supports_update_block_table = False
|
||||
reorder_batch_threshold = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: AttentionSpec,
|
||||
layer_names: list[str],
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
):
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
self.slot_mapping_buffer = torch.empty(
|
||||
vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> DeepseekV32IndexerMetadata:
|
||||
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
|
||||
split_decodes_and_prefills(common_attn_metadata)
|
||||
)
|
||||
slot_mapping = common_attn_metadata.slot_mapping
|
||||
positions = common_attn_metadata.positions
|
||||
if positions is not None:
|
||||
slot_mapping_buffer = self.slot_mapping_buffer[
|
||||
: slot_mapping.numel()
|
||||
].view_as(slot_mapping)
|
||||
slot_mapping = compute_kpool_tail_slot_mapping(
|
||||
slot_mapping,
|
||||
common_attn_metadata.block_table_tensor,
|
||||
common_attn_metadata.query_start_loc,
|
||||
positions,
|
||||
common_attn_metadata.num_actual_tokens,
|
||||
common_attn_metadata.num_reqs,
|
||||
self.kv_cache_spec.block_size,
|
||||
out=slot_mapping_buffer,
|
||||
)
|
||||
return DeepseekV32IndexerMetadata(
|
||||
seq_lens=common_attn_metadata.seq_lens,
|
||||
max_seq_len=common_attn_metadata.max_seq_len,
|
||||
slot_mapping=slot_mapping,
|
||||
num_decodes=num_decodes,
|
||||
num_decode_tokens=num_decode_tokens,
|
||||
num_prefills=num_prefills,
|
||||
num_prefill_tokens=num_prefill_tokens,
|
||||
)
|
||||
|
||||
|
||||
def get_max_prefill_buffer_size(vllm_config: VllmConfig):
|
||||
max_model_len = vllm_config.model_config.max_model_len
|
||||
# NOTE(Chen): 40 is a magic number for controlling the prefill buffer size.
|
||||
@@ -640,6 +760,11 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.per_req_decode_lens_buffer = torch.zeros(
|
||||
(scheduler_config.max_num_batched_tokens,),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
# Shared workspace for decode seq_lens. Native MTP views this as
|
||||
# (B, max_decode_len) at runtime, keeping context_lens contiguous even
|
||||
# when max_decode_len is smaller than next_n.
|
||||
@@ -707,6 +832,8 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.indexer_decode_block_table_buffer: torch.Tensor | None = None
|
||||
self._max_num_batched_tokens = scheduler_config.max_num_batched_tokens
|
||||
|
||||
def _dcp_localize_decode_seq_lens(
|
||||
self,
|
||||
@@ -921,7 +1048,16 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
|
||||
compressed_slot_mapping = slot_mapping
|
||||
compressed_seq_lens = seq_lens
|
||||
indexer_block_table = block_table
|
||||
if self.compress_ratio > 1:
|
||||
kernel_block_size = self.kernel_block_size
|
||||
if (
|
||||
kernel_block_size is not None
|
||||
and self.kv_cache_spec.block_size != kernel_block_size
|
||||
and self.kv_cache_spec.block_size % kernel_block_size == 0
|
||||
):
|
||||
factor = self.kv_cache_spec.block_size // kernel_block_size
|
||||
indexer_block_table = (block_table[:, ::factor] // factor).contiguous()
|
||||
padded_num_tokens = num_tokens
|
||||
if self.pcp_world_size > 1:
|
||||
padded_num_tokens = slot_mapping.shape[0] // self.pcp_world_size
|
||||
@@ -929,7 +1065,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
num_tokens,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
block_table,
|
||||
indexer_block_table,
|
||||
self.kv_cache_spec.num_states,
|
||||
self.compress_ratio,
|
||||
out=self.compressed_slot_mapping_buffer,
|
||||
@@ -979,7 +1115,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
seq_lens,
|
||||
compressed_seq_lens,
|
||||
compressed_seq_lens_cpu,
|
||||
common_attn_metadata.block_table_tensor,
|
||||
indexer_block_table,
|
||||
self.compress_ratio,
|
||||
query_slice=query_slice,
|
||||
skip_kv_gather=query_slice.start > 0,
|
||||
@@ -990,7 +1126,14 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
# Skip when total_seq_lens is 0 (i.e., no compressed token).
|
||||
if metadata is not None:
|
||||
chunks.append(metadata)
|
||||
prefill_metadata = DeepseekV32IndexerPrefillMetadata(chunks)
|
||||
prefill_metadata = DeepseekV32IndexerPrefillMetadata(
|
||||
chunks,
|
||||
max_prefill_seq_len=(
|
||||
int(seq_lens_cpu[num_decodes:].max().item())
|
||||
if num_prefills > 0
|
||||
else 0
|
||||
),
|
||||
)
|
||||
|
||||
decode_metadata = None
|
||||
if num_decodes > 0:
|
||||
@@ -999,6 +1142,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
out=self.decode_lens_buffer[:num_decodes],
|
||||
)
|
||||
decode_lens = self.decode_lens_buffer[:num_decodes]
|
||||
self.per_req_decode_lens_buffer[:num_decodes].copy_(decode_lens)
|
||||
decode_lens_cpu = torch.diff(
|
||||
common_attn_metadata.query_start_loc_cpu[: num_decodes + 1]
|
||||
)
|
||||
@@ -1018,6 +1162,8 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
block_table = common_attn_metadata.block_table_tensor[:num_decodes, ...]
|
||||
|
||||
max_decode_len = int(decode_lens_cpu.max().item())
|
||||
min_decode_len = int(decode_lens_cpu.min().item())
|
||||
write_is_uniform = min_decode_len == max_decode_len
|
||||
next_n = 1 + self.num_speculative_tokens
|
||||
# The kernel sees max_decode_len Q rows, not the configured next_n,
|
||||
# so legality is per-step: on SM90 a uniformly 3-deep batch has no
|
||||
@@ -1064,7 +1210,30 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
)
|
||||
)
|
||||
|
||||
seq_lens_is_buffer_view = not use_native or next_n > 1
|
||||
if self.compress_ratio > 1:
|
||||
kernel_block_size = self.kernel_block_size
|
||||
if (
|
||||
kernel_block_size is not None
|
||||
and self.kv_cache_spec.block_size != kernel_block_size
|
||||
and self.kv_cache_spec.block_size % kernel_block_size == 0
|
||||
):
|
||||
factor = self.kv_cache_spec.block_size // kernel_block_size
|
||||
compressed = block_table[:, ::factor] // factor
|
||||
rows, cols = compressed.shape
|
||||
if self.indexer_decode_block_table_buffer is None:
|
||||
self.indexer_decode_block_table_buffer = torch.zeros(
|
||||
(self._max_num_batched_tokens, cols),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.indexer_decode_block_table_buffer[:rows, :cols].copy_(
|
||||
compressed
|
||||
)
|
||||
block_table = self.indexer_decode_block_table_buffer[:rows, :cols]
|
||||
|
||||
seq_lens_is_buffer_view = (use_native and next_n > 1) or (
|
||||
not use_native and max_decode_len > 1
|
||||
)
|
||||
|
||||
# DCP: localize the now-expanded per-token global bounds to this
|
||||
# rank's owned KV. Done here (after expansion) so each token's global
|
||||
@@ -1113,6 +1282,9 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
schedule_metadata=schedule_metadata,
|
||||
indices=decode_indices,
|
||||
global_seq_lens=global_seq_lens_for_decode,
|
||||
per_req_decode_lens=self.per_req_decode_lens_buffer[:num_decodes],
|
||||
decode_is_uniform=write_is_uniform,
|
||||
write_max_decode_len=max_decode_len,
|
||||
)
|
||||
|
||||
attn_metadata = DeepseekV32IndexerMetadata(
|
||||
|
||||
@@ -881,7 +881,11 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
rows. A DCP rank holds ``1/dcp_world_size`` of the sequence, so the
|
||||
request's block table is always wider than the pages a row can reach.
|
||||
"""
|
||||
pages_per_block = self.kernel_block_size // self._segmented_page_size
|
||||
kernel_block_size = self.kernel_block_size
|
||||
page_size = self._segmented_page_size
|
||||
assert kernel_block_size is not None
|
||||
assert page_size is not None
|
||||
pages_per_block = kernel_block_size // page_size
|
||||
max_local_pages = row_block_table.shape[1]
|
||||
max_local_blocks = cdiv(max_local_pages, pages_per_block)
|
||||
assert max_local_blocks <= block_table.shape[1], (
|
||||
|
||||
@@ -32,6 +32,9 @@ from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
AiterMLAHelper,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
rocm_sparse_attn_prefill,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
@@ -40,6 +43,51 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _use_rocm_sparse_triton(
|
||||
*,
|
||||
kv_cache_dtype: str,
|
||||
head_size: int,
|
||||
kv_lora_rank: int,
|
||||
num_prefills: int,
|
||||
num_decodes: int,
|
||||
num_decode_tokens: int,
|
||||
max_query_len: int,
|
||||
) -> bool:
|
||||
"""Select the rope-free BF16 path not supported by AITER sparse MLA."""
|
||||
plain_decode = num_decode_tokens == num_decodes
|
||||
return (
|
||||
not kv_cache_dtype.startswith("fp8")
|
||||
and head_size == kv_lora_rank
|
||||
and plain_decode
|
||||
and (num_prefills > 0 or (num_decodes > 0 and max_query_len == 1))
|
||||
)
|
||||
|
||||
|
||||
def fit_kpool_indices_to_aiter(
|
||||
token_indices: torch.Tensor, topk_tokens: int
|
||||
) -> torch.Tensor:
|
||||
"""Keep the live kpool tail while fitting AITER's fixed top-k width."""
|
||||
if token_indices.shape[1] < topk_tokens:
|
||||
raise ValueError("token_indices width must be at least topk_tokens")
|
||||
if token_indices.shape[1] == topk_tokens:
|
||||
return token_indices
|
||||
|
||||
history = token_indices[:, :topk_tokens]
|
||||
tail = token_indices[:, topk_tokens:]
|
||||
valid_history = (history >= 0).sum(dim=1)
|
||||
valid_tail = (tail >= 0).sum(dim=1)
|
||||
keep_history = torch.minimum(valid_history, topk_tokens - valid_tail)
|
||||
|
||||
columns = torch.arange(topk_tokens, device=token_indices.device).unsqueeze(0)
|
||||
tail_offsets = columns - keep_history.unsqueeze(1)
|
||||
tail_values = torch.gather(
|
||||
tail, 1, tail_offsets.clamp(min=0, max=tail.shape[1] - 1)
|
||||
)
|
||||
output = torch.where(columns < keep_history.unsqueeze(1), history, tail_values)
|
||||
valid_output = columns < (keep_history + valid_tail).unsqueeze(1)
|
||||
return torch.where(valid_output, output, -1)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _convert_req_index_to_global_index_kernel(
|
||||
req_id_ptr, # int32 [num_tokens]
|
||||
@@ -359,6 +407,7 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
self.kv_cache_spec = kv_cache_spec
|
||||
self.model_config = vllm_config.model_config
|
||||
self.model_dtype = vllm_config.model_config.dtype
|
||||
self.kv_cache_dtype = vllm_config.cache_config.cache_dtype
|
||||
parallel_config = vllm_config.parallel_config
|
||||
self.device = device
|
||||
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
@@ -550,53 +599,74 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
# context lengths (both clamped to topk_tokens, past which per-token KV
|
||||
# length saturates) and num_heads; fingerprint those CPU-side and skip
|
||||
# the launch when nothing changed.
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
clamped_seq_lens = np.minimum(
|
||||
common_attn_metadata.seq_lens_cpu[:num_reqs].numpy(),
|
||||
self.topk_tokens,
|
||||
head_size = self.mla_dims.kv_lora_rank + self.mla_dims.qk_rope_head_dim
|
||||
use_triton_sparse = _use_rocm_sparse_triton(
|
||||
kv_cache_dtype=self.kv_cache_dtype,
|
||||
head_size=head_size,
|
||||
kv_lora_rank=self.mla_dims.kv_lora_rank,
|
||||
num_prefills=num_prefills,
|
||||
num_decodes=num_decodes,
|
||||
num_decode_tokens=num_decode_tokens,
|
||||
max_query_len=common_attn_metadata.max_query_len,
|
||||
)
|
||||
clamped_context_lens = np.minimum(
|
||||
common_attn_metadata.seq_lens_cpu[:num_reqs].numpy() - seg_lengths,
|
||||
self.topk_tokens,
|
||||
)
|
||||
metadata_key = (
|
||||
num_tokens,
|
||||
int(common_attn_metadata.max_query_len),
|
||||
self._num_attention_heads,
|
||||
clamped_seq_lens.tobytes(),
|
||||
clamped_context_lens.tobytes(),
|
||||
seg_lengths.tobytes(),
|
||||
)
|
||||
if metadata_key != self._prev_metadata_key:
|
||||
from aiter import get_mla_metadata_v1
|
||||
|
||||
max_split_per_batch = self._sparse_decode_max_split(
|
||||
int(common_attn_metadata.max_seq_len)
|
||||
work_meta_data = None
|
||||
work_indptr = None
|
||||
work_info_set = None
|
||||
reduce_indptr = None
|
||||
reduce_final_map = None
|
||||
reduce_partial_map = None
|
||||
if not use_triton_sparse:
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
clamped_seq_lens = np.minimum(
|
||||
common_attn_metadata.seq_lens_cpu[:num_reqs].numpy(),
|
||||
self.topk_tokens,
|
||||
)
|
||||
get_mla_metadata_v1(
|
||||
qo_indptr,
|
||||
paged_kv_indptr,
|
||||
paged_kv_last_page_len,
|
||||
clamped_context_lens = np.minimum(
|
||||
common_attn_metadata.seq_lens_cpu[:num_reqs].numpy() - seg_lengths,
|
||||
self.topk_tokens,
|
||||
)
|
||||
metadata_key = (
|
||||
num_tokens,
|
||||
int(common_attn_metadata.max_query_len),
|
||||
self._num_attention_heads,
|
||||
1,
|
||||
True,
|
||||
self._mla_work_meta_data,
|
||||
self._mla_work_info_set,
|
||||
self._mla_work_indptr,
|
||||
self._mla_reduce_indptr,
|
||||
self._mla_reduce_final_map,
|
||||
self._mla_reduce_partial_map,
|
||||
page_size=1,
|
||||
kv_granularity=16,
|
||||
max_seqlen_qo=1,
|
||||
uni_seqlen_qo=1,
|
||||
fast_mode=True,
|
||||
max_split_per_batch=max_split_per_batch,
|
||||
clamped_seq_lens.tobytes(),
|
||||
clamped_context_lens.tobytes(),
|
||||
seg_lengths.tobytes(),
|
||||
)
|
||||
# The persistent metadata buffers are read by graph replay. Order
|
||||
# the async metadata write before the graph-captured decode kernel.
|
||||
torch.cuda.current_stream(self.device).synchronize()
|
||||
self._prev_metadata_key = metadata_key
|
||||
if metadata_key != self._prev_metadata_key:
|
||||
from aiter import get_mla_metadata_v1
|
||||
|
||||
max_split_per_batch = self._sparse_decode_max_split(
|
||||
int(common_attn_metadata.max_seq_len)
|
||||
)
|
||||
get_mla_metadata_v1(
|
||||
qo_indptr,
|
||||
paged_kv_indptr,
|
||||
paged_kv_last_page_len,
|
||||
self._num_attention_heads,
|
||||
1,
|
||||
True,
|
||||
self._mla_work_meta_data,
|
||||
self._mla_work_info_set,
|
||||
self._mla_work_indptr,
|
||||
self._mla_reduce_indptr,
|
||||
self._mla_reduce_final_map,
|
||||
self._mla_reduce_partial_map,
|
||||
page_size=1,
|
||||
kv_granularity=16,
|
||||
max_seqlen_qo=1,
|
||||
uni_seqlen_qo=1,
|
||||
fast_mode=True,
|
||||
max_split_per_batch=max_split_per_batch,
|
||||
)
|
||||
torch.cuda.current_stream(self.device).synchronize()
|
||||
self._prev_metadata_key = metadata_key
|
||||
work_meta_data = self._mla_work_meta_data
|
||||
work_indptr = self._mla_work_indptr
|
||||
work_info_set = self._mla_work_info_set
|
||||
reduce_indptr = self._mla_reduce_indptr
|
||||
reduce_final_map = self._mla_reduce_final_map
|
||||
reduce_partial_map = self._mla_reduce_partial_map
|
||||
|
||||
metadata = ROCMAiterMLASparseMetadata(
|
||||
num_reqs=common_attn_metadata.num_reqs,
|
||||
@@ -617,12 +687,12 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
paged_kv_last_page_len=paged_kv_last_page_len,
|
||||
paged_kv_indices=paged_kv_indices,
|
||||
paged_kv_indptr=paged_kv_indptr,
|
||||
work_meta_data=self._mla_work_meta_data,
|
||||
work_indptr=self._mla_work_indptr,
|
||||
work_info_set=self._mla_work_info_set,
|
||||
reduce_indptr=self._mla_reduce_indptr,
|
||||
reduce_final_map=self._mla_reduce_final_map,
|
||||
reduce_partial_map=self._mla_reduce_partial_map,
|
||||
work_meta_data=work_meta_data,
|
||||
work_indptr=work_indptr,
|
||||
work_info_set=work_info_set,
|
||||
reduce_indptr=reduce_indptr,
|
||||
reduce_final_map=reduce_final_map,
|
||||
reduce_partial_map=reduce_partial_map,
|
||||
)
|
||||
return metadata
|
||||
|
||||
@@ -715,6 +785,31 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
device=q.device,
|
||||
)
|
||||
|
||||
if _use_rocm_sparse_triton(
|
||||
kv_cache_dtype=self.kv_cache_dtype,
|
||||
head_size=q.shape[-1],
|
||||
kv_lora_rank=self.kv_lora_rank,
|
||||
num_prefills=attn_metadata.num_prefills,
|
||||
num_decodes=attn_metadata.num_decodes,
|
||||
num_decode_tokens=attn_metadata.num_decode_tokens,
|
||||
max_query_len=attn_metadata.max_query_len,
|
||||
):
|
||||
rocm_sparse_attn_prefill(
|
||||
q=q,
|
||||
kv=kv_c_and_k_pe_cache.view(-1, 1, q.shape[-1]),
|
||||
indices=None,
|
||||
topk_length=None,
|
||||
scale=self.scale,
|
||||
head_dim=q.shape[-1],
|
||||
nope_head_dim=self.kv_lora_rank,
|
||||
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
|
||||
attn_sink=None,
|
||||
output=output,
|
||||
ragged_indices=attn_metadata.paged_kv_indices,
|
||||
ragged_indptr=attn_metadata.paged_kv_indptr,
|
||||
)
|
||||
return AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
|
||||
|
||||
# Build kwargs and forward the persistent MLA metadata when it has
|
||||
# been computed. The aiter mla_decode_fwd switches to its
|
||||
# work-stealing persistent kernel path when work_meta_data is given.
|
||||
@@ -766,13 +861,18 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
)
|
||||
else:
|
||||
q = self.q_concat_buffer[: ql_nope.shape[0]]
|
||||
ops.concat_mla_q(ql_nope, q_pe, q)
|
||||
if q_pe.shape[-1] == 0:
|
||||
q.copy_(ql_nope)
|
||||
else:
|
||||
ops.concat_mla_q(ql_nope, q_pe, q)
|
||||
|
||||
num_actual_toks = attn_metadata.num_actual_tokens
|
||||
|
||||
# Get topk indices
|
||||
assert self.topk_indices_buffer is not None
|
||||
topk_indices = self.topk_indices_buffer[:num_actual_toks]
|
||||
topk_indices = fit_kpool_indices_to_aiter(
|
||||
self.topk_indices_buffer[:num_actual_toks], attn_metadata.topk_tokens
|
||||
)
|
||||
|
||||
triton_convert_req_index_to_global_index(
|
||||
attn_metadata.req_id_per_token,
|
||||
@@ -795,5 +895,4 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
attn_out = self._forward_mla(
|
||||
layer, mla_padded_q, kv_c_and_k_pe_cache, attn_metadata
|
||||
)
|
||||
|
||||
return attn_out, None
|
||||
|
||||
@@ -251,7 +251,7 @@ class ConvertReqIndexToGlobalIndexKernel(
|
||||
dict(
|
||||
HAS_PREFILL_WORKSPACE=False,
|
||||
COUNT_VALID=True,
|
||||
COMPACT_TO_FRONT=False,
|
||||
COMPACT_TO_FRONT=True,
|
||||
DCP_SIZE=1,
|
||||
DCP_RANK=0,
|
||||
DCP_INTERLEAVE=1,
|
||||
@@ -259,7 +259,7 @@ class ConvertReqIndexToGlobalIndexKernel(
|
||||
dict(
|
||||
HAS_PREFILL_WORKSPACE=True,
|
||||
COUNT_VALID=True,
|
||||
COMPACT_TO_FRONT=False,
|
||||
COMPACT_TO_FRONT=True,
|
||||
DCP_SIZE=1,
|
||||
DCP_RANK=0,
|
||||
DCP_INTERLEAVE=1,
|
||||
@@ -458,7 +458,14 @@ def triton_convert_req_index_to_global_index(
|
||||
req_id_c = req_id.contiguous()
|
||||
block_table_c = block_table.contiguous()
|
||||
token_indices_c = token_indices.contiguous()
|
||||
out = torch.empty_like(token_indices_c)
|
||||
# When return_valid_counts, the kernel scatters valid entries to a
|
||||
# contiguous prefix [0, valid_count) and leaves the tail unwritten, so
|
||||
# pre-fill -1 there. flash_mla_sparse_fwd then bounds attention to
|
||||
# [:topk_length] == exactly the valid set (no dropped tokens).
|
||||
if return_valid_counts:
|
||||
out = torch.full_like(token_indices_c, -1)
|
||||
else:
|
||||
out = torch.empty_like(token_indices_c)
|
||||
|
||||
valid_counts: torch.Tensor | None = None
|
||||
if return_valid_counts:
|
||||
@@ -491,7 +498,7 @@ def triton_convert_req_index_to_global_index(
|
||||
NUM_TOPK_TOKENS=NUM_TOPK_TOKENS,
|
||||
HAS_PREFILL_WORKSPACE=HAS_PREFILL_WORKSPACE,
|
||||
COUNT_VALID=return_valid_counts,
|
||||
COMPACT_TO_FRONT=False,
|
||||
COMPACT_TO_FRONT=return_valid_counts,
|
||||
# DCP disabled (no-op de-interleave)
|
||||
DCP_SIZE=1,
|
||||
DCP_RANK=0,
|
||||
|
||||
@@ -77,6 +77,10 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse."
|
||||
"FlashInferMLASparseSM120Backend"
|
||||
)
|
||||
FLASHINFER_MLA_SPARSE_SM90 = (
|
||||
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm90."
|
||||
"FlashInferMLASparseSM90Backend"
|
||||
)
|
||||
TRITON_MLA = "vllm.v1.attention.backends.mla.triton_mla.TritonMLABackend"
|
||||
CUTLASS_MLA = "vllm.v1.attention.backends.mla.cutlass_mla.CutlassMLABackend"
|
||||
FLASHMLA = "vllm.v1.attention.backends.mla.flashmla.FlashMLABackend"
|
||||
|
||||
@@ -909,6 +909,7 @@ def rocm_aiter_sparse_attn_indexer(
|
||||
has_decode = layer_attn_metadata.num_decodes > 0
|
||||
has_prefill = layer_attn_metadata.num_prefills > 0
|
||||
num_decode_tokens = layer_attn_metadata.num_decode_tokens
|
||||
topk_indices_buffer[: hidden_states.shape[0]] = -1
|
||||
|
||||
# during speculative decoding, k may be padded to the CUDA graph batch
|
||||
# size while slot_mapping only covers actual tokens.
|
||||
@@ -1251,15 +1252,31 @@ _DSV4_SPARSE_NOPE_DIM = 448
|
||||
_DSV4_SPARSE_ROPE_DIM = 64
|
||||
|
||||
|
||||
def _validate_sparse_dims(
|
||||
head_dim: int,
|
||||
nope_head_dim: int,
|
||||
rope_head_dim: int,
|
||||
op_name: str,
|
||||
) -> None:
|
||||
assert head_dim > 0, f"{op_name} expected a positive head_dim, got {head_dim}"
|
||||
assert nope_head_dim > 0, (
|
||||
f"{op_name} expected a positive NoPE dimension, got {nope_head_dim}"
|
||||
)
|
||||
assert rope_head_dim >= 0, (
|
||||
f"{op_name} expected a non-negative RoPE dimension, got {rope_head_dim}"
|
||||
)
|
||||
assert head_dim == nope_head_dim + rope_head_dim, (
|
||||
f"{op_name} expected head_dim={nope_head_dim + rope_head_dim}, got {head_dim}"
|
||||
)
|
||||
|
||||
|
||||
def _validate_dsv4_sparse_dims(
|
||||
head_dim: int,
|
||||
nope_head_dim: int,
|
||||
rope_head_dim: int,
|
||||
op_name: str,
|
||||
) -> None:
|
||||
assert head_dim == nope_head_dim + rope_head_dim, (
|
||||
f"{op_name} expected head_dim={nope_head_dim + rope_head_dim}, got {head_dim}"
|
||||
)
|
||||
_validate_sparse_dims(head_dim, nope_head_dim, rope_head_dim, op_name)
|
||||
assert (
|
||||
nope_head_dim == _DSV4_SPARSE_NOPE_DIM
|
||||
and rope_head_dim == _DSV4_SPARSE_ROPE_DIM
|
||||
@@ -1351,6 +1368,12 @@ def _as_int32_contiguous_1d(x: torch.Tensor) -> torch.Tensor:
|
||||
return x.to(torch.int32).contiguous()
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _sparse_kv_row_offset(slot, stride):
|
||||
# A global token slot fits in int32, but its byte/element offset may not.
|
||||
return slot.to(tl.int64) * stride
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _sparse_attn_prefill_ragged_kernel(
|
||||
q_ptr,
|
||||
@@ -1414,7 +1437,7 @@ def _sparse_attn_prefill_ragged_kernel(
|
||||
|
||||
kv = tl.load(
|
||||
kv_ptr
|
||||
+ safe_slot[:, None] * kv_stride_n
|
||||
+ _sparse_kv_row_offset(safe_slot[:, None], kv_stride_n)
|
||||
+ dim_offsets[None, :] * kv_stride_d,
|
||||
mask=valid[:, None] & dim_mask[None, :],
|
||||
other=0.0,
|
||||
@@ -2573,7 +2596,7 @@ def _rocm_sparse_attn_prefill_ragged_triton(
|
||||
assert indptr.numel() == num_queries + 1, (
|
||||
f"expected indptr shape [{num_queries + 1}], got {indptr.shape}"
|
||||
)
|
||||
_validate_dsv4_sparse_dims(
|
||||
_validate_sparse_dims(
|
||||
head_dim,
|
||||
nope_head_dim,
|
||||
rope_head_dim,
|
||||
@@ -3125,7 +3148,7 @@ def _rocm_sparse_attn_decode_triton(
|
||||
def rocm_sparse_attn_prefill(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
indices: torch.Tensor | None,
|
||||
topk_length: torch.Tensor | None,
|
||||
scale: float,
|
||||
head_dim: int,
|
||||
@@ -3139,7 +3162,7 @@ def rocm_sparse_attn_prefill(
|
||||
assert kv.ndim == 3 and kv.shape[1] == 1, (
|
||||
f"ROCm Triton sparse prefill expects kv=[skv,1,d], got {kv.shape}"
|
||||
)
|
||||
_validate_dsv4_sparse_dims(
|
||||
_validate_sparse_dims(
|
||||
head_dim,
|
||||
nope_head_dim,
|
||||
rope_head_dim,
|
||||
@@ -3157,6 +3180,7 @@ def rocm_sparse_attn_prefill(
|
||||
rope_head_dim=rope_head_dim,
|
||||
)
|
||||
else:
|
||||
assert indices is not None
|
||||
indices_2d = indices.reshape(indices.shape[0], -1)
|
||||
output_chunk = _rocm_sparse_attn_prefill_triton(
|
||||
q=q,
|
||||
|
||||
@@ -599,6 +599,9 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
# can be a multiple of hash_block_size.
|
||||
self.hash_block_size = hash_block_size
|
||||
self.dcp_world_size = dcp_world_size
|
||||
# Only groups that participate in prefix caching must satisfy the
|
||||
# divisibility constraint; groups that opt out (e.g. GLM-5.3-Flash kpool
|
||||
# tail, block_size=kpool) are scratch buffers and excluded.
|
||||
group_block_sizes = [
|
||||
manager.block_size
|
||||
for manager, group in zip(
|
||||
@@ -679,6 +682,11 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
"""
|
||||
self.attention_groups: list[SpecGroup] = []
|
||||
for i, g in enumerate(self.kv_cache_config.kv_cache_groups):
|
||||
# Skip groups that opt out of prefix caching (e.g. GLM-5.3-Flash
|
||||
# kpool tail): their blocks are per-request scratch, never
|
||||
# shareable, so they must not participate in hit lookup (their
|
||||
# manager-level hooks already no-op). Their slot in the per-group
|
||||
# hit tuple stays empty.
|
||||
if not g.kv_cache_spec.prefix_cacheable:
|
||||
continue
|
||||
manager_cls = self.single_type_managers[i].__class__
|
||||
|
||||
@@ -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, overload
|
||||
from typing import Any, NamedTuple, NewType, TypeAlias, cast, overload
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config import VllmConfig
|
||||
@@ -24,6 +24,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
ChunkedLocalAttentionSpec,
|
||||
FullAttentionSpec,
|
||||
HiddenStateCacheSpec,
|
||||
KpoolTailSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
@@ -1132,6 +1133,205 @@ def _get_kv_cache_groups_uniform_type(
|
||||
return [KVCacheGroupSpec(list(spec.kv_cache_specs.keys()), spec)]
|
||||
|
||||
|
||||
def _pp_balanced_mamba_group_count(
|
||||
vllm_config: VllmConfig,
|
||||
mamba_layer_names: list[str],
|
||||
mla_layer_names: list[str],
|
||||
) -> int | None:
|
||||
"""Return a Mamba group count whose PP projections fit the MLA slots."""
|
||||
num_groups = cdiv(len(mamba_layer_names), len(mla_layer_names))
|
||||
pp_size = vllm_config.parallel_config.pipeline_parallel_size
|
||||
if pp_size == 1:
|
||||
return num_groups
|
||||
|
||||
from vllm.distributed.utils import get_pp_indices
|
||||
from vllm.model_executor.models.utils import extract_layer_index
|
||||
|
||||
total_layers = vllm_config.model_config.get_total_num_hidden_layers()
|
||||
mamba_indices = [extract_layer_index(name) for name in mamba_layer_names]
|
||||
mla_indices = [extract_layer_index(name) for name in mla_layer_names]
|
||||
for rank in range(pp_size):
|
||||
start, end = get_pp_indices(total_layers, rank, pp_size)
|
||||
num_mamba = sum(start <= index < end for index in mamba_indices)
|
||||
num_mla = sum(start <= index < end for index in mla_indices)
|
||||
if not num_mamba:
|
||||
continue
|
||||
if not num_mla:
|
||||
return None
|
||||
num_groups = max(num_groups, cdiv(num_mamba, num_mla))
|
||||
return num_groups
|
||||
|
||||
|
||||
def _get_kv_cache_groups_glm5_next(
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec] | None:
|
||||
"""Build GLM-5.3-Flash groups with Mamba/MLA and tail/indexer aliasing."""
|
||||
mamba_specs = {
|
||||
name: spec
|
||||
for name, spec in kv_cache_spec.items()
|
||||
if isinstance(spec, MambaSpec)
|
||||
}
|
||||
tail_specs = {
|
||||
name: spec
|
||||
for name, spec in kv_cache_spec.items()
|
||||
if isinstance(spec, KpoolTailSpec)
|
||||
}
|
||||
attn_specs = {
|
||||
name: spec
|
||||
for name, spec in kv_cache_spec.items()
|
||||
if not isinstance(spec, (MambaSpec, KpoolTailSpec))
|
||||
}
|
||||
if not mamba_specs or not all(
|
||||
type(spec) is MLAAttentionSpec for spec in attn_specs.values()
|
||||
):
|
||||
return None
|
||||
|
||||
mla_specs = cast(dict[str, MLAAttentionSpec], attn_specs)
|
||||
idx_pages = {
|
||||
spec.page_size_bytes for spec in mla_specs.values() if spec.tokens_per_state > 1
|
||||
}
|
||||
if not idx_pages:
|
||||
return None
|
||||
|
||||
assert all(spec.page_size_padded is None for spec in mla_specs.values())
|
||||
assert len(idx_pages) == 1
|
||||
mla_names = [name for name, spec in mla_specs.items() if spec.tokens_per_state == 1]
|
||||
mla_pages = {mla_specs[name].page_size_bytes for name in mla_names}
|
||||
assert len(mla_pages) == 1
|
||||
mla_page = mla_pages.pop()
|
||||
uniform_spec = UniformTypeKVCacheSpecs.from_specs(attn_specs)
|
||||
assert uniform_spec is not None
|
||||
|
||||
tail_group: KVCacheGroupSpec | None = None
|
||||
if tail_specs:
|
||||
idx_page = next(iter(idx_pages))
|
||||
padded_tail_specs: dict[str, KVCacheSpec] = {
|
||||
name: replace(spec, page_size_padded=idx_page)
|
||||
for name, spec in tail_specs.items()
|
||||
}
|
||||
tail_uniform = UniformTypeKVCacheSpecs.from_specs(padded_tail_specs)
|
||||
assert tail_uniform is not None
|
||||
tail_group = KVCacheGroupSpec(list(padded_tail_specs), tail_uniform)
|
||||
|
||||
any_mamba = next(iter(mamba_specs.values()))
|
||||
assert all(spec == any_mamba for spec in mamba_specs.values())
|
||||
if any_mamba.real_page_size_bytes > mla_page:
|
||||
raise ValueError(
|
||||
f"the mamba state page ({any_mamba.real_page_size_bytes} bytes) "
|
||||
f"does not fit the MLA page ({mla_page} bytes); increase tensor "
|
||||
"parallelism or use a wider KV cache dtype"
|
||||
)
|
||||
padded_specs: dict[str, KVCacheSpec] = {
|
||||
name: replace(any_mamba, page_size_padded=mla_page) for name in mamba_specs
|
||||
}
|
||||
num_groups = _pp_balanced_mamba_group_count(
|
||||
vllm_config, list(mamba_specs), mla_names
|
||||
)
|
||||
if num_groups is None:
|
||||
raise ValueError(
|
||||
"a pipeline stage has mamba layers but no MLA layer to share "
|
||||
"slots with; realign the stage boundaries (VLLM_PP_LAYER_PARTITION)"
|
||||
)
|
||||
mamba_grouped_names: list[list[str]] = [[] for _ in range(num_groups)]
|
||||
for index, name in enumerate(mamba_specs):
|
||||
mamba_grouped_names[index % num_groups].append(name)
|
||||
|
||||
return (
|
||||
[KVCacheGroupSpec(list(attn_specs), uniform_spec)]
|
||||
+ ([tail_group] if tail_group is not None else [])
|
||||
+ create_kv_cache_group_specs(padded_specs, mamba_grouped_names)
|
||||
)
|
||||
|
||||
|
||||
def _glm5_next_tensor_layout(
|
||||
kv_cache_groups: list[KVCacheGroupSpec],
|
||||
) -> (
|
||||
tuple[
|
||||
KVCacheGroupSpec,
|
||||
list[KVCacheGroupSpec],
|
||||
list[str],
|
||||
list[str],
|
||||
int,
|
||||
int,
|
||||
list[str],
|
||||
int,
|
||||
]
|
||||
| None
|
||||
):
|
||||
"""Recognize the GLM-5.3-Flash grouping after optional PP projection."""
|
||||
uniform_groups = [
|
||||
group
|
||||
for group in kv_cache_groups
|
||||
if isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs)
|
||||
]
|
||||
mamba_groups = [
|
||||
group for group in kv_cache_groups if isinstance(group.kv_cache_spec, MambaSpec)
|
||||
]
|
||||
attn_group: KVCacheGroupSpec | None = None
|
||||
tail_group: KVCacheGroupSpec | None = None
|
||||
for group in uniform_groups:
|
||||
inner = cast(UniformTypeKVCacheSpecs, group.kv_cache_spec).kv_cache_specs
|
||||
if all(type(spec) is MLAAttentionSpec for spec in inner.values()):
|
||||
attn_group = group
|
||||
elif all(isinstance(spec, KpoolTailSpec) for spec in inner.values()):
|
||||
tail_group = group
|
||||
if attn_group is None or not mamba_groups:
|
||||
return None
|
||||
if len(uniform_groups) + len(mamba_groups) != len(kv_cache_groups):
|
||||
return None
|
||||
|
||||
attn_uniform = cast(UniformTypeKVCacheSpecs, attn_group.kv_cache_spec)
|
||||
mla_inner = cast(dict[str, MLAAttentionSpec], attn_uniform.kv_cache_specs)
|
||||
if not all(
|
||||
type(spec) is MLAAttentionSpec and spec.page_size_padded is None
|
||||
for spec in mla_inner.values()
|
||||
):
|
||||
return None
|
||||
mla_names = [
|
||||
name for name in attn_group.layer_names if mla_inner[name].tokens_per_state == 1
|
||||
]
|
||||
idx_names = [
|
||||
name for name in attn_group.layer_names if mla_inner[name].tokens_per_state > 1
|
||||
]
|
||||
mla_pages = {mla_inner[name].page_size_bytes for name in mla_names}
|
||||
idx_pages = {mla_inner[name].page_size_bytes for name in idx_names}
|
||||
if len(mla_pages) != 1 or len(idx_pages) != 1:
|
||||
return None
|
||||
mla_page = mla_pages.pop()
|
||||
idx_page = idx_pages.pop()
|
||||
if any(group.kv_cache_spec.page_size_bytes != mla_page for group in mamba_groups):
|
||||
return None
|
||||
|
||||
tail_names: list[str] = []
|
||||
tail_page = 0
|
||||
if tail_group is not None:
|
||||
tail_names = list(tail_group.layer_names)
|
||||
tail_inner = cast(
|
||||
UniformTypeKVCacheSpecs, tail_group.kv_cache_spec
|
||||
).kv_cache_specs
|
||||
tail_pages = {
|
||||
cast(KpoolTailSpec, spec).unpadded_page_size_bytes
|
||||
for spec in tail_inner.values()
|
||||
}
|
||||
if len(tail_pages) != 1 or len(tail_names) != len(idx_names):
|
||||
return None
|
||||
tail_page = tail_pages.pop()
|
||||
if tail_page > idx_page:
|
||||
return None
|
||||
|
||||
return (
|
||||
attn_group,
|
||||
mamba_groups,
|
||||
mla_names,
|
||||
idx_names,
|
||||
mla_page,
|
||||
idx_page,
|
||||
tail_names,
|
||||
tail_page,
|
||||
)
|
||||
|
||||
|
||||
def unify_kv_cache_spec_page_size(
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> dict[str, KVCacheSpec]:
|
||||
@@ -1359,6 +1559,10 @@ def _get_kv_cache_bytes_per_block(
|
||||
kv_cache_groups: list[KVCacheGroupSpec],
|
||||
) -> int:
|
||||
"""Return the largest cache group's bytes per block."""
|
||||
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
|
||||
_, _, mla_names, idx_names, mla_page, idx_page, _, _ = glm5_layout
|
||||
return len(mla_names) * mla_page + len(idx_names) * idx_page
|
||||
|
||||
bytes_per_block = max(
|
||||
sum(
|
||||
_get_per_layer_spec(group, layer_name).page_size_bytes
|
||||
@@ -1432,6 +1636,69 @@ def get_kv_cache_config_from_groups(
|
||||
),
|
||||
)
|
||||
|
||||
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
|
||||
(
|
||||
attn_group,
|
||||
mamba_groups,
|
||||
mla_names,
|
||||
idx_names,
|
||||
mla_page,
|
||||
idx_page,
|
||||
tail_names,
|
||||
_,
|
||||
) = glm5_layout
|
||||
bytes_per_block = len(mla_names) * mla_page + len(idx_names) * idx_page
|
||||
num_blocks = may_override_num_blocks(
|
||||
vllm_config, available_memory // bytes_per_block
|
||||
)
|
||||
size = bytes_per_block * num_blocks
|
||||
attn_specs = cast(
|
||||
UniformTypeKVCacheSpecs, attn_group.kv_cache_spec
|
||||
).kv_cache_specs
|
||||
|
||||
kv_cache_tensors: list[KVCacheTensor] = []
|
||||
|
||||
def add_tensor(layer_name: str, spec: KVCacheSpec, offset: int) -> None:
|
||||
kv_cache_tensors.append(
|
||||
KVCacheTensor(
|
||||
size=size,
|
||||
layers=[layer_name],
|
||||
layer_stride=spec.page_size_bytes * num_blocks,
|
||||
block_stride=spec.page_size_bytes,
|
||||
offset=offset,
|
||||
)
|
||||
)
|
||||
|
||||
for index, mla_name in enumerate(mla_names):
|
||||
offset = index * mla_page * num_blocks
|
||||
add_tensor(mla_name, attn_specs[mla_name], offset)
|
||||
for group in mamba_groups:
|
||||
if index < len(group.layer_names):
|
||||
add_tensor(group.layer_names[index], group.kv_cache_spec, offset)
|
||||
|
||||
idx_base = len(mla_names) * mla_page * num_blocks
|
||||
for index, idx_name in enumerate(idx_names):
|
||||
offset = idx_base + index * idx_page * num_blocks
|
||||
add_tensor(idx_name, attn_specs[idx_name], offset)
|
||||
if tail_names:
|
||||
tail_name = tail_names[index]
|
||||
tail_group = next(
|
||||
group for group in kv_cache_groups if tail_name in group.layer_names
|
||||
)
|
||||
tail_specs = cast(
|
||||
UniformTypeKVCacheSpecs, tail_group.kv_cache_spec
|
||||
).kv_cache_specs
|
||||
add_tensor(tail_name, tail_specs[tail_name], offset)
|
||||
|
||||
return KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=kv_cache_tensors,
|
||||
kv_cache_groups=kv_cache_groups,
|
||||
prefix_cache_retention_interval=(
|
||||
vllm_config.cache_config.prefix_cache_retention_interval
|
||||
),
|
||||
)
|
||||
|
||||
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)
|
||||
@@ -1941,6 +2208,9 @@ def get_kv_cache_groups(
|
||||
# full attention, or all layers are sliding window attention with the
|
||||
# same window size). Put all layers into one group.
|
||||
return _get_kv_cache_groups_uniform_type(uniform_spec)
|
||||
elif glm5_groups := _get_kv_cache_groups_glm5_next(vllm_config, kv_cache_spec):
|
||||
return glm5_groups
|
||||
|
||||
# Hidden-state layers use their own block table and must not be absorbed
|
||||
# into a compatible attention bucket.
|
||||
hidden_specs = {
|
||||
@@ -2065,6 +2335,30 @@ def _max_memory_usage_bytes_from_groups(
|
||||
if not kv_cache_groups:
|
||||
return 0
|
||||
|
||||
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
|
||||
(
|
||||
attn_group,
|
||||
mamba_groups,
|
||||
mla_names,
|
||||
idx_names,
|
||||
mla_page,
|
||||
idx_page,
|
||||
tail_names,
|
||||
_,
|
||||
) = glm5_layout
|
||||
uniform_spec = cast(UniformTypeKVCacheSpecs, attn_group.kv_cache_spec)
|
||||
total_blocks = uniform_spec.max_memory_usage_pages(vllm_config)
|
||||
total_blocks += sum(
|
||||
cdiv(
|
||||
group.kv_cache_spec.max_memory_usage_bytes(vllm_config),
|
||||
group.kv_cache_spec.page_size_bytes,
|
||||
)
|
||||
for group in mamba_groups
|
||||
)
|
||||
if tail_names:
|
||||
total_blocks += 1
|
||||
return total_blocks * (len(mla_names) * mla_page + len(idx_names) * idx_page)
|
||||
|
||||
bytes_per_block = _pool_bytes_per_block(kv_cache_groups)
|
||||
total_blocks = 0
|
||||
for group in kv_cache_groups:
|
||||
|
||||
@@ -6,6 +6,7 @@ from collections import defaultdict
|
||||
from collections.abc import Sequence
|
||||
from typing import ClassVar
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.core.block_pool import BlockPool
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
@@ -22,6 +23,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
CrossAttentionSpec,
|
||||
FullAttentionSpec,
|
||||
HiddenStateCacheSpec,
|
||||
KpoolTailSpec,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
@@ -33,6 +35,8 @@ from vllm.v1.kv_cache_interface import (
|
||||
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
|
||||
from vllm.v1.request import Request
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SingleTypeKVCacheManager(ABC):
|
||||
"""
|
||||
@@ -1210,6 +1214,10 @@ class CircularBufferManager(FullAttentionManager):
|
||||
return 0
|
||||
|
||||
|
||||
class KpoolTailManager(CircularBufferManager):
|
||||
"""One-block circular scratch manager for ``KpoolTailSpec``."""
|
||||
|
||||
|
||||
class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
def __init__(self, kv_cache_spec: ChunkedLocalAttentionSpec, **kwargs) -> None:
|
||||
super().__init__(kv_cache_spec, **kwargs)
|
||||
@@ -2085,6 +2093,11 @@ def register_all_kvcache_specs(vllm_config):
|
||||
SlidingWindowManager,
|
||||
uniform_type_base_spec=SlidingWindowMLASpec,
|
||||
)
|
||||
KVCacheSpecRegistry.register(
|
||||
KpoolTailSpec,
|
||||
KpoolTailManager,
|
||||
uniform_type_base_spec=KpoolTailSpec,
|
||||
)
|
||||
|
||||
KVCacheSpecRegistry.register(
|
||||
MambaSpec, MambaManager, uniform_type_base_spec=MambaSpec
|
||||
|
||||
+12
-1
@@ -333,8 +333,19 @@ class EngineCore:
|
||||
vllm_config.cache_config.num_gpu_blocks = scheduler_kv_cache_config.num_blocks
|
||||
kv_cache_groups = scheduler_kv_cache_config.kv_cache_groups
|
||||
if kv_cache_groups:
|
||||
# Exclude groups that opt out of prefix caching (e.g. GLM-5.3-Flash
|
||||
# kpool tail, a 1-block/req scratch buffer with block_size=kpool):
|
||||
# their small block_size would otherwise drag the global block_size
|
||||
# below the real allocator block size and desync it from mamba.
|
||||
participating = [
|
||||
g.kv_cache_spec.block_size
|
||||
for g in kv_cache_groups
|
||||
if g.kv_cache_spec.prefix_cacheable
|
||||
]
|
||||
vllm_config.cache_config.block_size = min(
|
||||
g.kv_cache_spec.block_size for g in kv_cache_groups
|
||||
participating
|
||||
if participating
|
||||
else [g.kv_cache_spec.block_size for g in kv_cache_groups]
|
||||
)
|
||||
update_kv_cache_capacity(vllm_config, scheduler_kv_cache_config)
|
||||
|
||||
|
||||
@@ -158,6 +158,7 @@ class KVCacheSpec:
|
||||
|
||||
@property
|
||||
def prefix_cacheable(self) -> bool:
|
||||
"""Whether this spec's group participates in prefix caching."""
|
||||
return True
|
||||
|
||||
@property
|
||||
@@ -555,6 +556,8 @@ class MLAAttentionSpec(FullAttentionSpec):
|
||||
# DeepseekV4 only fields. Non-DeepseekV4 MLA models leave these at defaults.
|
||||
alignment: int | None = None # Default to None for no padding.
|
||||
model_version: str | None = None
|
||||
storage_block_size: int | None = None
|
||||
"""Token width used to view storage when it differs from the kernel block."""
|
||||
# Marks draft groups that flatten a non-causal query block into decode rows.
|
||||
non_causal_multi_token_decode: bool = False
|
||||
# MLA stores a single latent vector per state; there is no separate V.
|
||||
@@ -572,13 +575,16 @@ class MLAAttentionSpec(FullAttentionSpec):
|
||||
cache_dtype_str_set = set(spec.cache_dtype_str 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)
|
||||
storage_block_size_set = set(spec.storage_block_size for spec in specs)
|
||||
assert (
|
||||
len(cache_dtype_str_set) == 1
|
||||
and len(tokens_per_state_set) == 1
|
||||
and len(model_version_set) == 1
|
||||
and len(storage_block_size_set) == 1
|
||||
), (
|
||||
"All attention layers in the same KV cache group must use the same "
|
||||
"quantization method, tokens per state, and model version."
|
||||
"quantization method, tokens per state, model version, and storage "
|
||||
"block size."
|
||||
)
|
||||
non_causal_mtd_set = {spec.non_causal_multi_token_decode for spec in specs}
|
||||
assert len(non_causal_mtd_set) == 1, (
|
||||
@@ -597,6 +603,7 @@ class MLAAttentionSpec(FullAttentionSpec):
|
||||
cache_dtype_str=cache_dtype_str_set.pop(),
|
||||
tokens_per_state=tokens_per_state_set.pop(),
|
||||
model_version=model_version_set.pop(),
|
||||
storage_block_size=storage_block_size_set.pop(),
|
||||
non_causal_multi_token_decode=non_causal_mtd_set.pop(),
|
||||
)
|
||||
for spec in specs:
|
||||
@@ -853,6 +860,28 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class KpoolTailSpec(SlidingWindowSpec):
|
||||
"""One-block circular scratch cache for a kpool indexer's raw tail."""
|
||||
|
||||
def max_admission_blocks_per_request(
|
||||
self, max_in_flight_tokens: int, max_model_len: int
|
||||
) -> int:
|
||||
return 1
|
||||
|
||||
def max_num_blocks_per_req(self, vllm_config: VllmConfig, max_len: int) -> int:
|
||||
return 1
|
||||
|
||||
def is_uniform_with_collection(
|
||||
self, kv_cache_specs: dict[str, KVCacheSpec]
|
||||
) -> bool:
|
||||
return all(isinstance(spec, KpoolTailSpec) for spec in kv_cache_specs.values())
|
||||
|
||||
@property
|
||||
def prefix_cacheable(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MambaSpec(KVCacheSpec):
|
||||
shapes: tuple[tuple[int, ...], ...]
|
||||
@@ -875,6 +904,10 @@ class MambaSpec(KVCacheSpec):
|
||||
for (shape, dtype) in zip(self.shapes, self.dtypes)
|
||||
)
|
||||
|
||||
@property
|
||||
def real_page_size_bytes(self) -> int:
|
||||
return self.state_content_size_bytes
|
||||
|
||||
@property
|
||||
def page_size_bytes(self) -> int:
|
||||
page_size = sum(
|
||||
|
||||
@@ -1021,6 +1021,7 @@ class SpecDecodeBaseProposer:
|
||||
{
|
||||
"DeepSeekMTPModel",
|
||||
"DeepseekV32MTPModel",
|
||||
"Glm5NextMTPModel",
|
||||
"KimiK3MTPModel",
|
||||
}.intersection(architectures)
|
||||
)
|
||||
|
||||
@@ -696,6 +696,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
attn_groups_iter=(g for groups in self.attn_groups for g in groups),
|
||||
kernel_block_sizes=self.kernel_block_sizes,
|
||||
static_forward_context=self.compilation_config.static_forward_context,
|
||||
num_blocks=self.kv_cache_config.num_blocks,
|
||||
)
|
||||
|
||||
@torch.inference_mode()
|
||||
|
||||
@@ -322,6 +322,7 @@ class MambaHybridModelState(DefaultModelState):
|
||||
kv_cache_config=kv_cache_config,
|
||||
seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
|
||||
dcp_local_seq_lens=input_batch.dcp_local_seq_lens,
|
||||
positions=input_batch.positions,
|
||||
model_specific_attn_metadata=mamba_attn_metadata,
|
||||
for_cudagraph_capture=for_capture,
|
||||
rswa_prefix_lens=input_batch.prompt_lens,
|
||||
|
||||
@@ -1160,6 +1160,7 @@ class GPUModelRunner(
|
||||
kernel_block_sizes=self._kernel_block_sizes,
|
||||
runner_only_attn_layers=self.runner_only_attn_layers,
|
||||
static_forward_context=self.compilation_config.static_forward_context,
|
||||
num_blocks=self.kv_cache_config.num_blocks,
|
||||
)
|
||||
|
||||
def _zero_block_ids(self, block_ids: list[int]) -> None:
|
||||
|
||||
+26
-7
@@ -35,6 +35,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
create_kv_cache_views,
|
||||
)
|
||||
@@ -115,6 +116,7 @@ class KVBlockZeroer:
|
||||
attn_groups_iter: Iterable["AttentionGroup"],
|
||||
kernel_block_sizes: list[int],
|
||||
static_forward_context: dict[str, Any],
|
||||
num_blocks: int,
|
||||
runner_only_attn_layers: set[str] | None = None,
|
||||
) -> None:
|
||||
"""Precompute the absolute-address table for the Triton zeroing kernel.
|
||||
@@ -158,8 +160,6 @@ class KVBlockZeroer:
|
||||
continue
|
||||
kernel_bs = kernel_block_sizes[group.kv_cache_group_id]
|
||||
assert spec.block_size % kernel_bs == 0
|
||||
ratio = spec.block_size // kernel_bs
|
||||
|
||||
for layer_name in group.layer_names:
|
||||
if layer_name in runner_only_attn_layers:
|
||||
continue
|
||||
@@ -168,6 +168,12 @@ class KVBlockZeroer:
|
||||
continue
|
||||
dp = kv.data_ptr()
|
||||
|
||||
assert kv.shape[0] % num_blocks == 0, (
|
||||
f"{layer_name}: {kv.shape[0]} kernel blocks is not a "
|
||||
f"multiple of {num_blocks} logical blocks"
|
||||
)
|
||||
ratio = kv.shape[0] // num_blocks
|
||||
|
||||
el = kv.element_size()
|
||||
block_stride_bytes = kv.stride(0) * el
|
||||
assert block_stride_bytes % 4 == 0
|
||||
@@ -267,11 +273,19 @@ class AttentionGroup:
|
||||
kernel_block_size: int | None = None,
|
||||
num_metadata_builders: int = 1,
|
||||
):
|
||||
kv_cache_spec_builder = (
|
||||
self.kv_cache_spec.copy_with_new_block_size(kernel_block_size)
|
||||
if kernel_block_size is not None
|
||||
else self.kv_cache_spec
|
||||
)
|
||||
if kernel_block_size is None:
|
||||
kv_cache_spec_builder = self.kv_cache_spec
|
||||
elif (
|
||||
isinstance(self.kv_cache_spec, MLAAttentionSpec)
|
||||
and self.kv_cache_spec.storage_block_size is not None
|
||||
):
|
||||
kv_cache_spec_builder = self.kv_cache_spec.copy_with_new_block_size(
|
||||
self.kv_cache_spec.storage_block_size
|
||||
)
|
||||
else:
|
||||
kv_cache_spec_builder = self.kv_cache_spec.copy_with_new_block_size(
|
||||
kernel_block_size
|
||||
)
|
||||
builder_cls = self.backend.get_builder_cls()
|
||||
builder_kwargs = {}
|
||||
if builder_cls.requires_block_table_width:
|
||||
@@ -291,6 +305,9 @@ class AttentionGroup:
|
||||
)
|
||||
for _ in range(num_metadata_builders)
|
||||
]
|
||||
if kernel_block_size is not None:
|
||||
for builder in self.metadata_builders:
|
||||
builder.set_kernel_block_size(kernel_block_size)
|
||||
|
||||
def get_metadata_builder(self, ubatch_id: int = 0) -> AttentionMetadataBuilder:
|
||||
assert len(self.metadata_builders) > ubatch_id
|
||||
@@ -427,6 +444,8 @@ def allocate_kv_cache(
|
||||
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]
|
||||
if isinstance(spec, MLAAttentionSpec) and spec.storage_block_size is not None:
|
||||
kernel_block_size = spec.storage_block_size
|
||||
|
||||
views = create_kv_cache_views(
|
||||
buf,
|
||||
|
||||
Reference in New Issue
Block a user