Enable DeepSeek V4 and GLM-5.1 on SM120 (#43477)
Signed-off-by: Zihua Wu <13583761+lucifer1004@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Yongye Zhu <zyy1102000@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
Yongye Zhu
parent
3ce15fd574
commit
44d95069e9
@@ -436,7 +436,7 @@ class CommonAttentionMetadata:
|
||||
positions: torch.Tensor | None = None
|
||||
"""(num_actual_tokens,) token positions. Optional; set when the caller
|
||||
has positions available so that builders can pre-compute position-dependent
|
||||
metadata (e.g. C128A topk indices for DeepSeek V4)."""
|
||||
sparse metadata for DeepSeek V4 C128A layers."""
|
||||
|
||||
is_prefilling: torch.Tensor | None = None
|
||||
"""(batch_size,) bool tensor: True if request is still in prefill phase
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlashInfer MLA Sparse Attention Backend.
|
||||
|
||||
This backend uses the FlashInfer TRT-LLM MLA kernel with sparse_mla_top_k
|
||||
for models like DeepSeek-V3.2 that use index-based sparse attention.
|
||||
|
||||
For sparse MLA:
|
||||
- block_tables shape changes from [batch_size, max_num_blocks] (dense)
|
||||
to [batch_size, q_len_per_request, sparse_mla_top_k] (sparse)
|
||||
- The sparse indices represent physical cache slot positions to attend to
|
||||
- sparse_mla_top_k parameter must be set to the topk value
|
||||
"""
|
||||
"""FlashInfer sparse MLA attention backend."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
@@ -52,34 +41,13 @@ logger = init_logger(__name__)
|
||||
FLASHINFER_MLA_SPARSE_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024
|
||||
|
||||
|
||||
class FlashInferMLASparseBackend(AttentionBackend):
|
||||
"""FlashInfer MLA backend with sparse attention support.
|
||||
|
||||
This backend uses the FlashInfer TRT-LLM MLA kernel with sparse_mla_top_k
|
||||
for models like DeepSeek-V3.2 that use index-based sparse attention.
|
||||
"""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"float16",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [32, 64]
|
||||
class _FlashInferMLASparseBackendBase(AttentionBackend):
|
||||
"""Common metadata for concrete FlashInfer sparse MLA backends."""
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_MLA_SPARSE"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["FlashInferMLASparseImpl"]:
|
||||
return FlashInferMLASparseImpl
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["FlashInferMLASparseMetadataBuilder"]:
|
||||
return FlashInferMLASparseMetadataBuilder
|
||||
@@ -96,9 +64,29 @@ class FlashInferMLASparseBackend(AttentionBackend):
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase):
|
||||
"""FlashInfer sparse MLA backend using the TRTLLM-gen launcher."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"float16",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [32, 64]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[SparseMLAAttentionImpl]:
|
||||
return FlashInferMLASparseImpl
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
|
||||
# FlashInfer sparse MLA targets Blackwell (SM 10.x)
|
||||
return capability.major == 10
|
||||
|
||||
@classmethod
|
||||
@@ -114,10 +102,15 @@ class FlashInferMLASparseBackend(AttentionBackend):
|
||||
use_mm_prefix: bool,
|
||||
device_capability: DeviceCapability,
|
||||
) -> str | None:
|
||||
# FlashInfer MLA sparse kernel requires qk_nope_head_dim in [128, 192]
|
||||
from vllm.config import get_current_vllm_config
|
||||
|
||||
vllm_config = get_current_vllm_config()
|
||||
if kv_cache_dtype == "fp8_ds_mla":
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE SM10 does not support fp8_ds_mla kv-cache dtype"
|
||||
)
|
||||
|
||||
# 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)
|
||||
@@ -146,6 +139,102 @@ class FlashInferMLASparseBackend(AttentionBackend):
|
||||
return "HND"
|
||||
|
||||
|
||||
class FlashInferMLASparseSM120Backend(_FlashInferMLASparseBackendBase):
|
||||
"""FlashInfer sparse MLA backend for SM120."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
"fp8_ds_mla",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_MLA_SPARSE_SM120"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
return [64, 256]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[SparseMLAAttentionImpl]:
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm120 import (
|
||||
FlashInferMLASparseSM120Impl,
|
||||
)
|
||||
|
||||
return FlashInferMLASparseSM120Impl
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
|
||||
return capability.major == 12
|
||||
|
||||
@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:
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120
|
||||
|
||||
if not has_flashinfer_sparse_mla_sm120():
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE_SM120 requires FlashInfer's "
|
||||
"sparse MLA decode API"
|
||||
)
|
||||
if dtype != torch.bfloat16:
|
||||
return "dtype not supported"
|
||||
if kv_cache_dtype not in (
|
||||
None,
|
||||
"auto",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
"fp8_ds_mla",
|
||||
):
|
||||
return "kv_cache_dtype not supported"
|
||||
vllm_config = get_current_vllm_config()
|
||||
if vllm_config.model_config is not None:
|
||||
hf_text_config = vllm_config.model_config.hf_text_config
|
||||
index_topk = getattr(hf_text_config, "index_topk", None)
|
||||
if index_topk is None:
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE_SM120 requires a model with "
|
||||
"index_topk config"
|
||||
)
|
||||
if int(index_topk) != 2048:
|
||||
return (
|
||||
"FLASHINFER_MLA_SPARSE_SM120 requires index_topk=2048; "
|
||||
f"got {index_topk}"
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_kv_cache_shape(
|
||||
num_blocks: int,
|
||||
block_size: int,
|
||||
num_kv_heads: int, # assumed to be 1 for MLA
|
||||
head_size: int,
|
||||
cache_dtype_str: str = "auto",
|
||||
) -> tuple[int, ...]:
|
||||
if cache_dtype_str in ("auto", "fp8", "fp8_e4m3", "fp8_ds_mla"):
|
||||
# fp8_ds_mla packed layout: 512 NoPE + 16 scales + 128 RoPE.
|
||||
return (num_blocks, block_size, 656)
|
||||
return (num_blocks, block_size, head_size)
|
||||
|
||||
@classmethod
|
||||
def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None":
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FlashInferMLASparseMetadata(AttentionMetadata):
|
||||
"""Attention metadata for FlashInfer MLA Sparse backend."""
|
||||
@@ -353,6 +442,8 @@ class FlashInferMLASparseImpl(SparseMLAAttentionImpl[FlashInferMLASparseMetadata
|
||||
if is_quantized_kv_cache(self.kv_cache_dtype):
|
||||
self.bmm2_scale *= layer._k_scale_float
|
||||
|
||||
from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla
|
||||
|
||||
o = trtllm_batch_decode_with_kv_cache_mla(
|
||||
query=q.unsqueeze(1),
|
||||
kv_cache=kv_c_and_k_pe_cache.unsqueeze(1),
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""SM120 implementation variant for ``FLASHINFER_MLA_SPARSE_SM120``."""
|
||||
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionLayer,
|
||||
AttentionType,
|
||||
SparseMLAAttentionImpl,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
FlashInferMLASparseMetadata,
|
||||
_get_workspace_buffer,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.models.deepseek_v2 import Indexer
|
||||
|
||||
|
||||
def _kv_scale_format_for_model(model_type: str | None) -> str:
|
||||
if model_type is not None and model_type.startswith("glm"):
|
||||
return "arbitrary_fp32"
|
||||
return "pow2_fp32"
|
||||
|
||||
|
||||
class FlashInferMLASparseSM120Impl(SparseMLAAttentionImpl[FlashInferMLASparseMetadata]):
|
||||
"""SM120 FlashInfer sparse-MLA implementation."""
|
||||
|
||||
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,
|
||||
indexer: "Indexer | None" = None,
|
||||
**mla_args,
|
||||
) -> None:
|
||||
if any([alibi_slopes, sliding_window, logits_soft_cap]):
|
||||
raise NotImplementedError(
|
||||
"FLASHINFER_MLA_SPARSE_SM120 does not support alibi_slopes / "
|
||||
"sliding_window / logits_soft_cap"
|
||||
)
|
||||
if attn_type != AttentionType.DECODER:
|
||||
raise NotImplementedError(
|
||||
"FLASHINFER_MLA_SPARSE_SM120 only supports decoder self-attention"
|
||||
)
|
||||
|
||||
self.num_heads = num_heads
|
||||
self.head_size = head_size
|
||||
self.scale = float(scale)
|
||||
self.num_kv_heads = num_kv_heads
|
||||
self.kv_cache_dtype = kv_cache_dtype
|
||||
if self.kv_cache_dtype != "fp8_ds_mla":
|
||||
raise NotImplementedError(
|
||||
"FLASHINFER_MLA_SPARSE_SM120 requires the packed fp8_ds_mla "
|
||||
f"KV cache layout; got kv_cache_dtype={kv_cache_dtype!r}."
|
||||
)
|
||||
|
||||
self.kv_lora_rank: int = mla_args["kv_lora_rank"]
|
||||
self.qk_nope_head_dim: int = mla_args["qk_nope_head_dim"]
|
||||
self.qk_rope_head_dim: int = mla_args["qk_rope_head_dim"]
|
||||
from vllm.config import get_current_vllm_config
|
||||
|
||||
vllm_config = get_current_vllm_config()
|
||||
model_type = None
|
||||
if vllm_config.model_config is not None:
|
||||
model_type = getattr(
|
||||
vllm_config.model_config.hf_text_config, "model_type", None
|
||||
)
|
||||
self.kv_scale_format = _kv_scale_format_for_model(model_type)
|
||||
|
||||
assert indexer is not None, (
|
||||
"FLASHINFER_MLA_SPARSE_SM120 requires a sparse-MLA indexer "
|
||||
"(model with index_topk in its config)."
|
||||
)
|
||||
self.topk_indices_buffer: torch.Tensor | None = indexer.topk_indices_buffer
|
||||
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120
|
||||
|
||||
if not has_flashinfer_sparse_mla_sm120():
|
||||
raise RuntimeError(
|
||||
"FLASHINFER_MLA_SPARSE_SM120 requires FlashInfer's "
|
||||
"sparse MLA decode API."
|
||||
)
|
||||
assert self.topk_indices_buffer is not None
|
||||
|
||||
self.supports_quant_query_input = False
|
||||
self._workspace_buffer: torch.Tensor | None = None
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
kv_c_and_k_pe_cache: torch.Tensor,
|
||||
attn_metadata: FlashInferMLASparseMetadata,
|
||||
layer: AttentionLayer,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
if isinstance(q, tuple):
|
||||
q = torch.cat(q, dim=-1)
|
||||
|
||||
num_actual_toks = q.shape[0]
|
||||
|
||||
assert self.topk_indices_buffer is not None
|
||||
topk_indices = self.topk_indices_buffer[:num_actual_toks]
|
||||
|
||||
topk_indices_physical = cast(
|
||||
torch.Tensor,
|
||||
triton_convert_req_index_to_global_index(
|
||||
attn_metadata.req_id_per_token[:num_actual_toks],
|
||||
attn_metadata.block_table,
|
||||
topk_indices,
|
||||
BLOCK_SIZE=attn_metadata.block_size,
|
||||
NUM_TOPK_TOKENS=topk_indices.shape[1],
|
||||
),
|
||||
)
|
||||
|
||||
output = q.new_empty(
|
||||
(num_actual_toks, self.num_heads, self.kv_lora_rank),
|
||||
dtype=q.dtype,
|
||||
)
|
||||
|
||||
if self._workspace_buffer is None:
|
||||
self._workspace_buffer = _get_workspace_buffer(q.device)
|
||||
|
||||
from vllm.utils.flashinfer import (
|
||||
flashinfer_trtllm_batch_decode_with_kv_cache_mla,
|
||||
)
|
||||
|
||||
out = flashinfer_trtllm_batch_decode_with_kv_cache_mla(
|
||||
query=q.unsqueeze(1),
|
||||
kv_cache=kv_c_and_k_pe_cache.view(torch.uint8).unsqueeze(1),
|
||||
workspace_buffer=self._workspace_buffer,
|
||||
qk_nope_head_dim=self.qk_nope_head_dim,
|
||||
kv_lora_rank=self.kv_lora_rank,
|
||||
qk_rope_head_dim=self.qk_rope_head_dim,
|
||||
block_tables=topk_indices_physical.unsqueeze(1),
|
||||
seq_lens=None,
|
||||
max_seq_len=attn_metadata.topk_tokens,
|
||||
out=output.unsqueeze(1),
|
||||
bmm1_scale=self.scale,
|
||||
bmm2_scale=1.0,
|
||||
sparse_mla_top_k=attn_metadata.topk_tokens,
|
||||
kv_scale_format=self.kv_scale_format,
|
||||
)
|
||||
return out.squeeze(1), None
|
||||
@@ -74,14 +74,14 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
|
||||
# determines the SWA block size of 64 tokens per block.
|
||||
# TODO(yifan): make SWA block size automatically determined and configurable.
|
||||
self.block_size = 64
|
||||
# uint8: legacy FlashMLA UE8M0 paged layout. bfloat16 / float8_e4m3fn:
|
||||
# FlashInfer contiguous full-cache layout.
|
||||
# uint8: fp8_ds_mla UE8M0 paged layout. bfloat16 / float8_e4m3fn:
|
||||
# contiguous full-cache layout.
|
||||
assert self.dtype in (torch.uint8, torch.bfloat16, torch.float8_e4m3fn)
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
# FlashMLA's UE8M0 paged layout needs 576B alignment; FlashInfer's
|
||||
# contiguous bf16/fp8 cache uses the natural element-size page.
|
||||
is_flashmla = self.cache_config.cache_dtype == "fp8_ds_mla"
|
||||
# fp8_ds_mla's UE8M0 paged layout needs 576B alignment; contiguous
|
||||
# bf16/fp8 cache uses the natural element-size page.
|
||||
uses_fp8_ds_mla_layout = self.cache_config.cache_dtype == "fp8_ds_mla"
|
||||
return SlidingWindowMLASpec(
|
||||
block_size=self.block_size,
|
||||
num_kv_heads=1,
|
||||
@@ -89,7 +89,7 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
|
||||
dtype=self.dtype,
|
||||
sliding_window=self.window_size,
|
||||
cache_dtype_str=self.cache_config.cache_dtype,
|
||||
alignment=576 if is_flashmla else None,
|
||||
alignment=576 if uses_fp8_ds_mla_layout else None,
|
||||
model_version="deepseek_v4",
|
||||
)
|
||||
|
||||
@@ -164,6 +164,11 @@ class DeepseekSparseSWAMetadata:
|
||||
token_to_req_indices: torch.Tensor | None = None # [num_tokens]
|
||||
decode_swa_indices: torch.Tensor | None = None # [num_decode_tokens, window_size]
|
||||
decode_swa_lens: torch.Tensor | None = None # [num_decode_tokens]
|
||||
# Paged-coordinate prefill SWA indices/lens (FP8 paged-direct prefill).
|
||||
prefill_swa_indices: torch.Tensor | None = (
|
||||
None # [num_prefill_tokens, 1, window_size]
|
||||
)
|
||||
prefill_swa_lens: torch.Tensor | None = None # [num_prefill_tokens]
|
||||
|
||||
# Number of decode/prefill requests/tokens (batch is reordered: decodes first)
|
||||
num_decodes: int = 0
|
||||
@@ -343,6 +348,20 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
# Allocated unconditionally — consumer picks paged-direct vs dequant
|
||||
# at call time.
|
||||
self.prefill_swa_indices = torch.zeros(
|
||||
max_tokens,
|
||||
1,
|
||||
self.window_size,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.prefill_swa_lens = torch.zeros(
|
||||
max_tokens,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.is_valid_token = torch.zeros(
|
||||
max_tokens,
|
||||
dtype=torch.bool,
|
||||
@@ -402,6 +421,29 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
self.block_size,
|
||||
token_offset=0,
|
||||
TRITON_BLOCK_SIZE=1024,
|
||||
)
|
||||
|
||||
# Prefill SWA indices live in paged coordinates. `token_offset` lets
|
||||
# the kernel read is_valid_token / token_to_req_indices at absolute
|
||||
# prefill positions while writing output starting at index 0.
|
||||
if num_prefill_tokens > 0:
|
||||
prefill_swa_indices = self.prefill_swa_indices[:num_prefill_tokens]
|
||||
prefill_swa_lens = self.prefill_swa_lens[:num_prefill_tokens]
|
||||
_compute_swa_indices_and_lens_kernel[(num_prefill_tokens,)](
|
||||
prefill_swa_indices,
|
||||
prefill_swa_indices.stride(0),
|
||||
prefill_swa_lens,
|
||||
self.window_size,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
token_to_req_indices,
|
||||
is_valid_token,
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
self.block_size,
|
||||
token_offset=num_decode_tokens,
|
||||
TRITON_BLOCK_SIZE=1024,
|
||||
)
|
||||
|
||||
@@ -431,6 +473,16 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
token_to_req_indices=token_to_req_indices,
|
||||
decode_swa_indices=self.decode_swa_indices[:num_decode_tokens],
|
||||
decode_swa_lens=self.decode_swa_lens[:num_decode_tokens],
|
||||
prefill_swa_indices=(
|
||||
self.prefill_swa_indices[:num_prefill_tokens]
|
||||
if num_prefill_tokens > 0
|
||||
else None
|
||||
),
|
||||
prefill_swa_lens=(
|
||||
self.prefill_swa_lens[:num_prefill_tokens]
|
||||
if num_prefill_tokens > 0
|
||||
else None
|
||||
),
|
||||
block_size=self.block_size,
|
||||
num_decodes=num_decodes,
|
||||
num_prefills=num_prefills,
|
||||
@@ -465,6 +517,7 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
num_decode_tokens == 0
|
||||
or current_platform.is_rocm()
|
||||
or current_platform.is_xpu()
|
||||
or current_platform.is_device_capability_family(120)
|
||||
):
|
||||
return out
|
||||
for layer_type in self._layer_types:
|
||||
@@ -489,7 +542,7 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
Returns a dict of keyword arguments to pass to the
|
||||
DeepseekSparseSWAMetadata constructor.
|
||||
|
||||
Note: C128A topk indices are computed by the FlashMLASparse builder
|
||||
Note: C128A sparse metadata is computed by the FlashMLASparse builder
|
||||
(which owns the C128A block_table), not here.
|
||||
"""
|
||||
result: dict[str, torch.Tensor | int | None] = {}
|
||||
@@ -539,10 +592,14 @@ def _compute_prefill_metadata_kernel(
|
||||
"""Compute prefill gather_lens in a single pass."""
|
||||
offset = tl.arange(0, BLOCK_SIZE)
|
||||
mask = offset < num_prefills
|
||||
# SM12x + Triton 3.6 raises IMA on out-of-bounds address arithmetic for
|
||||
# masked-off lanes even though the load mask gates the actual read, so
|
||||
# clamp the offset. Caller guarantees num_prefills > 0.
|
||||
safe_offset = tl.minimum(offset, num_prefills - 1)
|
||||
|
||||
seq_len = tl.load(seq_lens_ptr + num_decodes + offset, mask=mask)
|
||||
qsl_start = tl.load(query_start_loc_ptr + num_decodes + offset, mask=mask)
|
||||
qsl_end = tl.load(query_start_loc_ptr + num_decodes + offset + 1, mask=mask)
|
||||
seq_len = tl.load(seq_lens_ptr + num_decodes + safe_offset, mask=mask)
|
||||
qsl_start = tl.load(query_start_loc_ptr + num_decodes + safe_offset, mask=mask)
|
||||
qsl_end = tl.load(query_start_loc_ptr + num_decodes + safe_offset + 1, mask=mask)
|
||||
|
||||
query_len = qsl_end - qsl_start
|
||||
prefix_len = seq_len - query_len
|
||||
@@ -551,7 +608,7 @@ def _compute_prefill_metadata_kernel(
|
||||
tl.store(prefill_gather_lens_ptr + offset, gather_len, mask=mask)
|
||||
|
||||
|
||||
@triton.jit
|
||||
@triton.jit(do_not_specialize=["token_offset"])
|
||||
def _compute_swa_indices_and_lens_kernel(
|
||||
swa_indices_ptr,
|
||||
swa_indices_stride,
|
||||
@@ -564,12 +621,14 @@ def _compute_swa_indices_and_lens_kernel(
|
||||
block_table_ptr,
|
||||
block_table_stride,
|
||||
block_size,
|
||||
token_offset,
|
||||
TRITON_BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
token_idx = tl.program_id(0)
|
||||
pid = tl.program_id(0)
|
||||
token_idx = pid + token_offset
|
||||
is_valid = tl.load(is_valid_token_ptr + token_idx)
|
||||
if not is_valid:
|
||||
tl.store(swa_lens_ptr + token_idx, 0)
|
||||
tl.store(swa_lens_ptr + pid, 0)
|
||||
return
|
||||
|
||||
req_idx = tl.load(token_to_req_indices_ptr + token_idx)
|
||||
@@ -586,7 +645,7 @@ def _compute_swa_indices_and_lens_kernel(
|
||||
end_pos = pos + 1
|
||||
|
||||
swa_len = end_pos - start_pos
|
||||
tl.store(swa_lens_ptr + token_idx, swa_len)
|
||||
tl.store(swa_lens_ptr + pid, swa_len)
|
||||
|
||||
for i in range(0, window_size, TRITON_BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, TRITON_BLOCK_SIZE)
|
||||
@@ -602,7 +661,7 @@ def _compute_swa_indices_and_lens_kernel(
|
||||
|
||||
slot_ids = tl.where(offset < swa_len, slot_ids, -1)
|
||||
tl.store(
|
||||
swa_indices_ptr + token_idx * swa_indices_stride + offset,
|
||||
swa_indices_ptr + pid * swa_indices_stride + offset,
|
||||
slot_ids,
|
||||
mask=offset < window_size,
|
||||
)
|
||||
|
||||
@@ -71,7 +71,11 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
)
|
||||
FLASHINFER_MLA_SPARSE = (
|
||||
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse."
|
||||
"FlashInferMLASparseBackend"
|
||||
"FlashInferMLASparseTRTLLMBackend"
|
||||
)
|
||||
FLASHINFER_MLA_SPARSE_SM120 = (
|
||||
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse."
|
||||
"FlashInferMLASparseSM120Backend"
|
||||
)
|
||||
TRITON_MLA = "vllm.v1.attention.backends.mla.triton_mla.TritonMLABackend"
|
||||
CUTLASS_MLA = "vllm.v1.attention.backends.mla.cutlass_mla.CutlassMLABackend"
|
||||
|
||||
@@ -73,7 +73,7 @@ def is_flashmla_sparse_supported() -> tuple[bool, str | None]:
|
||||
):
|
||||
return (
|
||||
False,
|
||||
"FlashMLA Sparse is only supported on Hopper and Blackwell devices.",
|
||||
"FlashMLA Sparse is only supported on Hopper and Blackwell DC devices.",
|
||||
)
|
||||
return True, None
|
||||
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import AbstractContextManager, nullcontext
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm import PoolingParams, SamplingParams
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.core.sched.output import (
|
||||
CachedRequestData,
|
||||
@@ -18,6 +20,134 @@ from vllm.v1.core.sched.output import (
|
||||
from vllm.v1.request import Request
|
||||
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def run_mixed_prefill_decode_warmup(
|
||||
model_runner: GPUModelRunner,
|
||||
worker_execute_model: Callable[[SchedulerOutput], Any],
|
||||
worker_sample_tokens: Callable[[GrammarOutput | None], Any],
|
||||
num_tokens: int,
|
||||
*,
|
||||
mixed_step_context: AbstractContextManager[object] | None = None,
|
||||
req_id_prefix: str = "_v2_mixed_warmup",
|
||||
) -> bool:
|
||||
"""Run a V2 mixed prefill+decode step through normal scheduler inputs."""
|
||||
if model_runner.is_pooling_model or num_tokens < 3:
|
||||
return False
|
||||
|
||||
decode_req_id = f"{req_id_prefix}_decode_"
|
||||
prefill_req_id = f"{req_id_prefix}_prefill_"
|
||||
decode_prompt_len = 2
|
||||
decode_scheduled_tokens = 1
|
||||
prefill_len = num_tokens - decode_scheduled_tokens
|
||||
decode_token_ids = list(range(decode_prompt_len))
|
||||
prefill_token_ids = list(range(prefill_len))
|
||||
|
||||
kv_cache_groups = model_runner.kv_cache_config.kv_cache_groups
|
||||
num_kv_cache_groups = len(kv_cache_groups)
|
||||
group_block_sizes = [g.kv_cache_spec.block_size for g in kv_cache_groups]
|
||||
decode_prefill_block_counts = [
|
||||
cdiv(decode_prompt_len, block_size) for block_size in group_block_sizes
|
||||
]
|
||||
decode_block_counts = [
|
||||
cdiv(decode_prompt_len + decode_scheduled_tokens, block_size)
|
||||
for block_size in group_block_sizes
|
||||
]
|
||||
decode_block_deltas = [
|
||||
decode - prefill
|
||||
for decode, prefill in zip(decode_block_counts, decode_prefill_block_counts)
|
||||
]
|
||||
prefill_block_counts = [
|
||||
cdiv(prefill_len, block_size) for block_size in group_block_sizes
|
||||
]
|
||||
required_blocks = sum(decode_block_counts) + sum(prefill_block_counts)
|
||||
if model_runner.kv_cache_config.num_blocks <= required_blocks:
|
||||
logger.warning(
|
||||
"Skipping V2 mixed prefill+decode warmup because only %d KV blocks "
|
||||
"are available for %d required warmup blocks.",
|
||||
model_runner.kv_cache_config.num_blocks,
|
||||
required_blocks,
|
||||
)
|
||||
return False
|
||||
|
||||
next_block_id = 1
|
||||
|
||||
def _alloc_blocks(num_blocks: int) -> list[int]:
|
||||
nonlocal next_block_id
|
||||
block_ids = list(range(next_block_id, next_block_id + num_blocks))
|
||||
next_block_id += num_blocks
|
||||
return block_ids
|
||||
|
||||
sampling_params = SamplingParams(max_tokens=2, temperature=0.0)
|
||||
|
||||
decode_prefill_output = SchedulerOutput.make_empty()
|
||||
decode_prefill_output.scheduled_new_reqs = [
|
||||
NewRequestData(
|
||||
req_id=decode_req_id,
|
||||
prompt_token_ids=decode_token_ids,
|
||||
mm_features=[],
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
block_ids=tuple(_alloc_blocks(n) for n in decode_prefill_block_counts),
|
||||
num_computed_tokens=0,
|
||||
lora_request=None,
|
||||
prefill_token_ids=decode_token_ids,
|
||||
),
|
||||
]
|
||||
decode_prefill_output.num_scheduled_tokens = {
|
||||
decode_req_id: decode_prompt_len,
|
||||
}
|
||||
decode_prefill_output.total_num_scheduled_tokens = decode_prompt_len
|
||||
decode_prefill_output.num_common_prefix_blocks = [0] * num_kv_cache_groups
|
||||
|
||||
decode_new_blocks = tuple(_alloc_blocks(n) for n in decode_block_deltas)
|
||||
cached_decode_req = CachedRequestData.make_empty()
|
||||
cached_decode_req.req_ids = [decode_req_id]
|
||||
cached_decode_req.num_computed_tokens = [decode_prompt_len]
|
||||
cached_decode_req.num_output_tokens = [1]
|
||||
cached_decode_req.new_block_ids = [
|
||||
decode_new_blocks if any(decode_block_deltas) else None
|
||||
]
|
||||
|
||||
mixed_output = SchedulerOutput.make_empty()
|
||||
mixed_output.scheduled_cached_reqs = cached_decode_req
|
||||
mixed_output.scheduled_new_reqs = [
|
||||
NewRequestData(
|
||||
req_id=prefill_req_id,
|
||||
prompt_token_ids=prefill_token_ids,
|
||||
mm_features=[],
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
block_ids=tuple(_alloc_blocks(n) for n in prefill_block_counts),
|
||||
num_computed_tokens=0,
|
||||
lora_request=None,
|
||||
prefill_token_ids=prefill_token_ids,
|
||||
),
|
||||
]
|
||||
mixed_output.num_scheduled_tokens = {
|
||||
decode_req_id: decode_scheduled_tokens,
|
||||
prefill_req_id: prefill_len,
|
||||
}
|
||||
mixed_output.total_num_scheduled_tokens = num_tokens
|
||||
mixed_output.num_common_prefix_blocks = [0] * num_kv_cache_groups
|
||||
|
||||
cleanup_output = SchedulerOutput.make_empty()
|
||||
cleanup_output.finished_req_ids = {decode_req_id, prefill_req_id}
|
||||
|
||||
context = mixed_step_context or nullcontext()
|
||||
model_runner.kv_connector.set_disabled(True)
|
||||
try:
|
||||
worker_execute_model(decode_prefill_output)
|
||||
worker_sample_tokens(None)
|
||||
with context:
|
||||
worker_execute_model(mixed_output)
|
||||
worker_sample_tokens(None)
|
||||
worker_execute_model(cleanup_output)
|
||||
finally:
|
||||
model_runner.kv_connector.set_disabled(False)
|
||||
return True
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def warmup_kernels(
|
||||
|
||||
Reference in New Issue
Block a user