[KV Cache] GLM-5.3-Flash: use the generic packed KV layout; CircularBufferSpec tail with speculative ring slots (#57169)
Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai> Signed-off-by: Dakai An <dakaian108@gmail.com> Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: OpenAI Codex <codex@openai.com> Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com>
This commit is contained in:
co-authored by
Yifan Qiao
OpenAI Codex
OpenAI Codex
Lucas Wilkinson
Claude Opus 5.5
Lucas Wilkinson
parent
3766a67a32
commit
02e55d2af3
@@ -297,11 +297,6 @@ def create_composite_attention_backend(
|
||||
)
|
||||
self.routing = routing_policy(layer_names, vllm_config)
|
||||
|
||||
def set_kernel_block_size(self, kernel_block_size):
|
||||
super().set_kernel_block_size(kernel_block_size)
|
||||
for builder in self._builders:
|
||||
builder.set_kernel_block_size(kernel_block_size)
|
||||
|
||||
@classmethod
|
||||
def get_cudagraph_support(cls, vllm_config, kv_cache_spec):
|
||||
return min(
|
||||
|
||||
@@ -95,7 +95,9 @@ class CompressedSlotMappingKernel(
|
||||
block_table_ptr + batch_idx * block_table_stride + block_ids,
|
||||
mask=mask & is_valid,
|
||||
)
|
||||
slot_ids = block_numbers * block_size + pos_after_compress % block_size
|
||||
slot_ids = block_numbers.to(tl.int64) * block_size + (
|
||||
pos_after_compress % block_size
|
||||
)
|
||||
|
||||
# NOTE
|
||||
slot_ids = tl.where(is_valid, slot_ids, PAD_ID)
|
||||
|
||||
@@ -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.index_group import HiSparseMLAIndexGroup
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
align_blocks_to_rows,
|
||||
flat_kv_row_view,
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
@@ -42,7 +43,11 @@ class FlashAttnMLASparseBackend(AttentionBackend):
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
return [64]
|
||||
return [MultipleOf(64)]
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
return align_blocks_to_rows(spec)
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlashInfer sparse MLA attention backend."""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
@@ -30,6 +31,7 @@ from vllm.v1.attention.backend import (
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
align_blocks_to_rows,
|
||||
flat_kv_row_view,
|
||||
prepare_sparse_mla_safe_lengths,
|
||||
triton_convert_req_index_to_global_index,
|
||||
@@ -69,6 +71,13 @@ class _FlashInferMLASparseBackendBase(AttentionBackend):
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
# The kernels read the rows as pages of their kernel block size.
|
||||
(page,) = cls.get_supported_kernel_block_sizes(spec)
|
||||
assert isinstance(page, MultipleOf)
|
||||
return align_blocks_to_rows(spec, page.base)
|
||||
|
||||
|
||||
class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase):
|
||||
"""FlashInfer sparse MLA backend using the TRTLLM-gen launcher."""
|
||||
@@ -84,7 +93,7 @@ class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase):
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
return [32, 64]
|
||||
return [MultipleOf(32)]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[MLAAttentionImpl]:
|
||||
@@ -173,7 +182,7 @@ class FlashInferMLASparseSM120Backend(_FlashInferMLASparseBackendBase):
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
return [64, 256]
|
||||
return [MultipleOf(64)]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[MLAAttentionImpl]:
|
||||
@@ -575,7 +584,7 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
assert prefill_lse is not None
|
||||
return output, torch.cat((decode_lse, prefill_lse))
|
||||
|
||||
_, block_stride_rows = flat_kv_row_view(
|
||||
kv_rows, block_stride_rows = flat_kv_row_view(
|
||||
kv_c_and_k_pe_cache, attn_metadata.block_size
|
||||
)
|
||||
|
||||
@@ -602,7 +611,12 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
|
||||
return self._run_mqa_kernel(
|
||||
q,
|
||||
kv_c_and_k_pe_cache,
|
||||
# Block sizes and strides have been aligned to 32 rows.
|
||||
kv_rows.view(
|
||||
-1,
|
||||
math.gcd(block_stride_rows, attn_metadata.block_size, 64),
|
||||
kv_rows.shape[-1],
|
||||
),
|
||||
topk_indices_physical,
|
||||
seq_lens,
|
||||
)
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
flat_kv_row_view,
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
|
||||
@@ -184,6 +185,9 @@ class FlashInferMLASparseSM120Impl(SparseMLACommonImpl[FlashInferMLASparseMetada
|
||||
output = torch.cat(outputs) if len(outputs) > 1 else outputs[0]
|
||||
return output, None
|
||||
|
||||
kv_rows, block_stride_rows = flat_kv_row_view(
|
||||
kv_c_and_k_pe_cache, attn_metadata.block_size
|
||||
)
|
||||
topk_indices_physical = cast(
|
||||
torch.Tensor,
|
||||
triton_convert_req_index_to_global_index(
|
||||
@@ -191,13 +195,15 @@ class FlashInferMLASparseSM120Impl(SparseMLACommonImpl[FlashInferMLASparseMetada
|
||||
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 (
|
||||
self._run_mqa_kernel(
|
||||
q,
|
||||
kv_c_and_k_pe_cache,
|
||||
# The SM120 kernels are built for 64-row pages only.
|
||||
kv_rows.view(-1, 64, kv_rows.shape[-1]),
|
||||
topk_indices_physical,
|
||||
),
|
||||
None,
|
||||
|
||||
@@ -26,7 +26,7 @@ needs no D2H sync. 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]``
|
||||
KV cache format: E4M3 ``[num_blocks, block_size, 512]`` (any block stride)
|
||||
(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).
|
||||
@@ -57,9 +57,11 @@ from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
FlashInferMLASparseMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
align_blocks_to_rows,
|
||||
flat_kv_row_view,
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
|
||||
_FP8_KV_DTYPES = ("fp8", "fp8_e4m3")
|
||||
_WORKSPACE_BYTES = 128 * 1024 * 1024
|
||||
@@ -99,7 +101,12 @@ def _pack_topk_indices(
|
||||
end = tl.load(indptr + row + 1)
|
||||
mask = (cols < end - start) & (cols < WIDTH)
|
||||
values = tl.load(slots + row * WIDTH + cols, mask=mask, other=0)
|
||||
tl.store(indices + start + cols, tl.maximum(values, 0), mask=mask)
|
||||
first_slot = tl.load(slots + row * WIDTH)
|
||||
tl.store(
|
||||
indices + start + cols,
|
||||
tl.where(values >= 0, values, tl.maximum(first_slot, 0)),
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -149,6 +156,10 @@ class FlashInferMLASparseSM90Backend(AttentionBackend):
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
return [MultipleOf(64)]
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
return align_blocks_to_rows(spec)
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_MLA_SPARSE_SM90"
|
||||
@@ -222,10 +233,6 @@ class FlashInferMLASparseSM90Backend(AttentionBackend):
|
||||
) -> 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.
|
||||
@@ -602,6 +609,9 @@ class FlashInferMLASparseSM90Impl(SparseMLACommonImpl[FlashInferMLASparseSM90Met
|
||||
|
||||
assert self.topk_indices_buffer is not None
|
||||
topk_indices = self.topk_indices_buffer[:num_tokens]
|
||||
kv_c_and_k_pe_cache, block_stride_rows = flat_kv_row_view(
|
||||
kv_c_and_k_pe_cache, attn_metadata.block_size
|
||||
)
|
||||
# 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.
|
||||
@@ -610,6 +620,7 @@ class FlashInferMLASparseSM90Impl(SparseMLACommonImpl[FlashInferMLASparseSM90Met
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
import numpy as np
|
||||
@@ -36,6 +36,7 @@ from vllm.v1.attention.backend import (
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
align_blocks_to_rows,
|
||||
flat_kv_row_view,
|
||||
request_row_bounds,
|
||||
triton_convert_req_index_to_global_index,
|
||||
@@ -53,7 +54,7 @@ from vllm.v1.attention.ops.flashmla import (
|
||||
flash_mla_with_kvcache,
|
||||
get_mla_metadata,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVQuantMode
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -132,6 +133,17 @@ QUANTIZED_DS_MLA_CACHE_FORMATS: frozenset[str] = frozenset(
|
||||
FP8_DS_MLA_ROPE_DIM = 64
|
||||
|
||||
|
||||
def _fp8_kv_pages(
|
||||
kv_cache: torch.Tensor, block_size: int
|
||||
) -> tuple[torch.Tensor, int | None]:
|
||||
"""The cache as the fp8 kernel's 64-token pages, and the block stride in
|
||||
rows when a block spans several pages."""
|
||||
if block_size == 64:
|
||||
return kv_cache, None
|
||||
rows, block_stride_rows = flat_kv_row_view(kv_cache, block_size)
|
||||
return rows.view(-1, 64, rows.shape[-1]), block_stride_rows
|
||||
|
||||
|
||||
class FlashMLASparseBackend(AttentionBackend):
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
@@ -144,7 +156,23 @@ class FlashMLASparseBackend(AttentionBackend):
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
return [64]
|
||||
if (
|
||||
isinstance(kv_cache_spec, AttentionSpec)
|
||||
and kv_cache_spec.kv_quant_mode != KVQuantMode.NONE
|
||||
and current_platform.is_device_capability_family(100)
|
||||
):
|
||||
return [64]
|
||||
return [MultipleOf(64)]
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
# Off SM100 the quantized kernel reads 64-token pages, only needed
|
||||
# when blocks span several.
|
||||
if spec.kv_quant_mode != KVQuantMode.NONE and (
|
||||
not current_platform.is_device_capability_family(100)
|
||||
):
|
||||
return replace(spec, block_stride_alignment=MultipleOf(64))
|
||||
return align_blocks_to_rows(spec)
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
@@ -998,13 +1026,16 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
# and the prefill rows per chunk, against the gathered workspace.
|
||||
lse: torch.Tensor | None = None
|
||||
topk_length: torch.Tensor | None = None
|
||||
kv_pages, block_stride_rows = _fp8_kv_pages(
|
||||
kv_c_and_k_pe_cache, attn_metadata.block_size
|
||||
)
|
||||
if self.pcp_dcp_kv_gather:
|
||||
pass
|
||||
elif num_prefill_tokens == 0 and not uses_host_cache:
|
||||
topk_indices, topk_length = self._convert_logical_to_physical_topk(
|
||||
topk_indices,
|
||||
attn_metadata,
|
||||
block_stride_rows=None,
|
||||
block_stride_rows=block_stride_rows,
|
||||
return_valid_counts=True,
|
||||
)
|
||||
elif num_prefill_tokens > 0:
|
||||
@@ -1013,6 +1044,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
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],
|
||||
HAS_PREFILL_WORKSPACE=has_prefill_workspace,
|
||||
prefill_workspace_request_ids=prefill_request_ids,
|
||||
@@ -1056,7 +1088,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
topk_indices = topk_indices.view(num_decodes, seq_len, -1)
|
||||
attn_out, _ = self._fp8_flash_mla_kernel(
|
||||
q=q,
|
||||
kv_c_and_k_pe_cache=kv_c_and_k_pe_cache,
|
||||
kv_c_and_k_pe_cache=kv_pages,
|
||||
topk_indices=topk_indices,
|
||||
kernel_metadata=fp8_metadata.decode.kernel_metadata,
|
||||
)
|
||||
@@ -1173,6 +1205,9 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
# req_id_per_token covers the whole batch; slice it to the MQA tokens
|
||||
# (q may exclude prefill tokens routed to dense MHA).
|
||||
req_id_per_token = attn_metadata.req_id_per_token[: topk_indices.shape[0]]
|
||||
kv_pages, block_stride_rows = _fp8_kv_pages(
|
||||
kv_c_and_k_pe_cache, attn_metadata.block_size
|
||||
)
|
||||
if self.dcp_world_size > 1:
|
||||
# The indexer emits global token ids; keep this rank's shard and
|
||||
# convert to local slots. compact_valid_to_front=False keeps the
|
||||
@@ -1187,6 +1222,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
dcp_rank=self.dcp_rank,
|
||||
cp_kv_cache_interleave_size=attn_metadata.cp_kv_cache_interleave_size,
|
||||
BLOCK_SIZE=attn_metadata.block_size,
|
||||
BLOCK_STRIDE_ROWS=block_stride_rows,
|
||||
NUM_TOPK_TOKENS=topk_indices.shape[1],
|
||||
compact_valid_to_front=False,
|
||||
)
|
||||
@@ -1202,7 +1238,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
topk_indices = self._convert_logical_to_physical_topk(
|
||||
topk_indices,
|
||||
attn_metadata,
|
||||
block_stride_rows=None,
|
||||
block_stride_rows=block_stride_rows,
|
||||
return_valid_counts=False,
|
||||
)
|
||||
else:
|
||||
@@ -1211,12 +1247,13 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
block_table,
|
||||
topk_indices,
|
||||
BLOCK_SIZE=attn_metadata.block_size,
|
||||
BLOCK_STRIDE_ROWS=block_stride_rows,
|
||||
NUM_TOPK_TOKENS=topk_indices.shape[1],
|
||||
)
|
||||
|
||||
_attn_out, _lse = self._fp8_flash_mla_kernel(
|
||||
q=q.unsqueeze(0), # unsqueeze to add batch_dim: (T, H, D) -> (1, T, H, D)
|
||||
kv_c_and_k_pe_cache=kv_c_and_k_pe_cache,
|
||||
kv_c_and_k_pe_cache=kv_pages,
|
||||
topk_indices=topk_indices.unsqueeze(0), # (T, topk) -> (1, T, topk)
|
||||
kernel_metadata=fp8_metadata,
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ import numpy as np
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
from vllm.distributed import get_dcp_group, get_pcp_group
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.warmup.jit_warmup import kernel_launcher, zip_inputs
|
||||
@@ -22,6 +22,7 @@ from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.deep_gemm import (
|
||||
get_paged_mqa_logits_metadata,
|
||||
get_paged_mqa_page_sizes,
|
||||
has_deep_gemm,
|
||||
native_next_n_supported,
|
||||
)
|
||||
@@ -234,12 +235,25 @@ class DeepseekV32IndexerBackend(AttentionBackend):
|
||||
return DeepseekV32IndexerMetadataBuilder
|
||||
|
||||
|
||||
class Glm5NextIndexerBackend(DeepseekV32IndexerBackend):
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
if kv_cache_spec is not None:
|
||||
# Worker get_kv_cache_spec: runs without the current config.
|
||||
index_kpool = int(kv_cache_spec.tokens_per_state)
|
||||
else:
|
||||
# Platform block-size selection: no spec yet, under the current config.
|
||||
model_config = get_current_vllm_config().model_config
|
||||
index_kpool = model_config.hf_text_config.index_kpool
|
||||
return [index_kpool * n for n in get_paged_mqa_page_sizes()]
|
||||
|
||||
|
||||
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,)
|
||||
return (KVCacheLayout.BLHNC,)
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
@@ -1065,8 +1079,6 @@ 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
|
||||
# DCP not supported yet
|
||||
self.supports_draft_decode_metadata_update = self.dcp_world_size == 1
|
||||
|
||||
@@ -1353,16 +1365,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
dcp_local_seq_lens = common_attn_metadata.dcp_local_seq_lens
|
||||
|
||||
compressed_slot_mapping = slot_mapping
|
||||
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
|
||||
local_slot_mapping = slot_mapping
|
||||
if self.use_pcp:
|
||||
@@ -1378,7 +1381,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
local_slot_mapping,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
indexer_block_table,
|
||||
block_table,
|
||||
self.kv_cache_spec.num_states,
|
||||
self.compress_ratio,
|
||||
out=self.compressed_slot_mapping_buffer,
|
||||
@@ -1497,7 +1500,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
seq_lens,
|
||||
compressed_seq_lens,
|
||||
compressed_seq_lens_cpu,
|
||||
indexer_block_table,
|
||||
block_table,
|
||||
self.compress_ratio,
|
||||
query_slice=query_slice,
|
||||
skip_kv_gather=query_slice.start > 0,
|
||||
@@ -1632,27 +1635,6 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
)
|
||||
)
|
||||
|
||||
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]
|
||||
|
||||
# Flattening always returns a buffer view, including single-token
|
||||
# batches. Keep its address stable across varlen graph replays.
|
||||
seq_lens_is_buffer_view = not use_native or next_n > 1
|
||||
@@ -1741,17 +1723,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
# One query token per request, so the per-token decode block table is
|
||||
# the request block table (at the indexer kernel's page size). build()
|
||||
# may copy it into a builder buffer, so re-derive it for this batch.
|
||||
block_table = metadata.block_table[: metadata.num_decode_tokens]
|
||||
kernel_block_size = self.kernel_block_size
|
||||
if (
|
||||
self.compress_ratio > 1
|
||||
and 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
|
||||
block_table = block_table[:, ::factor] // factor
|
||||
decode.block_table.copy_(block_table)
|
||||
decode.block_table.copy_(metadata.block_table[: metadata.num_decode_tokens])
|
||||
if decode.indices is not None:
|
||||
decode.indices.copy_(self.arange_buffer[: metadata.num_decode_tokens])
|
||||
if decode.per_req_decode_lens is not None:
|
||||
|
||||
@@ -35,6 +35,10 @@ from vllm.v1.attention.backend import (
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
AiterMLAHelper,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
align_blocks_to_rows,
|
||||
flat_kv_row_view,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
rocm_sparse_attn_decode_bf16,
|
||||
@@ -160,6 +164,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
|
||||
# strides (in elements)
|
||||
bt_stride0,
|
||||
@@ -201,9 +206,8 @@ def _convert_req_index_to_global_index_kernel(
|
||||
bt_ptr = block_table_ptr + req * bt_stride0 + block_id * bt_stride1
|
||||
base = tl.load(bt_ptr, mask=valid_block, other=0)
|
||||
|
||||
# # If token == -1 OR block_id OOB, output 0; else base * BLOCK_SIZE + offset
|
||||
out_val = tl.where(
|
||||
is_invalid_tok | (~valid_block), 0, base * BLOCK_SIZE + inblock_off
|
||||
is_invalid_tok | (~valid_block), 0, base * BLOCK_STRIDE_ROWS + inblock_off
|
||||
)
|
||||
out_ptr_ij = out_ptr + seq_start + indice_id
|
||||
out_ptr_ij_mask = (seq_start + indice_id) < seq_end
|
||||
@@ -218,13 +222,14 @@ def triton_convert_req_index_to_global_index(
|
||||
token_indices: torch.Tensor, # int32 [num_tokens, NUM_TOPK_TOKENS]
|
||||
cu_seqlens: torch.Tensor, # int32 [num_tokens + 1]
|
||||
paged_kv_indices: torch.Tensor, # int32 [num_tokens * topk] out_buffer
|
||||
BLOCK_STRIDE_ROWS: int,
|
||||
BLOCK_SIZE: int = 64,
|
||||
NUM_TOPK_TOKENS: int = 2048,
|
||||
BLOCK_N: int = 128, # tile width along columns
|
||||
):
|
||||
"""out[token_id, indice_id] =
|
||||
block_table[req_id[token_id],
|
||||
token_indices[token_id, indice_id] // BLOCK_SIZE] * BLOCK_SIZE
|
||||
token_indices[token_id, indice_id] // BLOCK_SIZE] * BLOCK_STRIDE_ROWS
|
||||
+ token_indices[token_id, indice_id] % BLOCK_SIZE
|
||||
|
||||
Only when token_indices[token_id, indice_id] == -1 do we output -1.
|
||||
@@ -264,6 +269,7 @@ def triton_convert_req_index_to_global_index(
|
||||
# shapes / constexprs
|
||||
max_num_blocks_per_req,
|
||||
BLOCK_SIZE,
|
||||
BLOCK_STRIDE_ROWS,
|
||||
BLOCK_N,
|
||||
# strides
|
||||
bt_stride0,
|
||||
@@ -345,6 +351,10 @@ class ROCMAiterMLASparseBackend(AttentionBackend):
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
|
||||
return [1, MultipleOf(16)]
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
return align_blocks_to_rows(spec)
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "ROCM_AITER_MLA_SPARSE"
|
||||
@@ -371,8 +381,7 @@ class ROCMAiterMLASparseBackend(AttentionBackend):
|
||||
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
|
||||
# Global index conversion assumes contiguous pages within each layer.
|
||||
return (KVCacheLayout.LBNHC, KVCacheLayout.LBHNC)
|
||||
return (KVCacheLayout.LBNHC, KVCacheLayout.LBHNC, KVCacheLayout.BLHNC)
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
@@ -1155,6 +1164,9 @@ class ROCMAiterMLASparseImpl(
|
||||
self.topk_indices_buffer[:num_actual_toks], attn_metadata.topk_tokens
|
||||
)
|
||||
|
||||
kv_c_and_k_pe_cache, block_stride_rows = flat_kv_row_view(
|
||||
kv_c_and_k_pe_cache, attn_metadata.block_size
|
||||
)
|
||||
triton_convert_req_index_to_global_index(
|
||||
attn_metadata.req_id_per_token,
|
||||
attn_metadata.block_table,
|
||||
@@ -1162,6 +1174,7 @@ class ROCMAiterMLASparseImpl(
|
||||
attn_metadata.paged_kv_indptr,
|
||||
attn_metadata.paged_kv_indices,
|
||||
BLOCK_SIZE=attn_metadata.block_size,
|
||||
BLOCK_STRIDE_ROWS=block_stride_rows,
|
||||
NUM_TOPK_TOKENS=attn_metadata.topk_tokens,
|
||||
)
|
||||
|
||||
@@ -1179,5 +1192,5 @@ class ROCMAiterMLASparseImpl(
|
||||
return output, None
|
||||
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self.num_heads, q)
|
||||
return self._forward_mla(
|
||||
layer, mla_padded_q, kv_c_and_k_pe_cache, attn_metadata
|
||||
layer, mla_padded_q, kv_c_and_k_pe_cache.unsqueeze(1), attn_metadata
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Utility functions for sparse MLA backends."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -22,6 +22,7 @@ from vllm.model_executor.warmup.jit_warmup_triton_helper import (
|
||||
)
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.v1.worker.block_table import get_block_table_width
|
||||
|
||||
|
||||
@@ -40,6 +41,12 @@ def request_row_bounds(req_idx: np.ndarray) -> np.ndarray:
|
||||
return bounds
|
||||
|
||||
|
||||
def align_blocks_to_rows(spec: AttentionSpec, rows: int = 1) -> AttentionSpec:
|
||||
"""Sparse kernels read the cache as flat rows, viewed as ``rows``-row pages,
|
||||
so blocks must be whole pages apart."""
|
||||
return replace(spec, block_stride_alignment=rows * spec.state_content_size_bytes)
|
||||
|
||||
|
||||
def flat_kv_row_view(
|
||||
kv_cache: torch.Tensor, # [num_blocks, block_size, head_dim]
|
||||
block_size: int,
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.v1.attention.backend import (
|
||||
MLAAttentionImpl,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
align_blocks_to_rows,
|
||||
flat_kv_row_view,
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
@@ -50,6 +51,10 @@ class XPUMLASparseBackend(AttentionBackend):
|
||||
def get_name() -> str:
|
||||
return "XPU_MLA_SPARSE"
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
return align_blocks_to_rows(spec)
|
||||
|
||||
@staticmethod
|
||||
def get_metadata_cls() -> type["XPUMLASparseMetadata"]:
|
||||
return XPUMLASparseMetadata
|
||||
|
||||
Reference in New Issue
Block a user