[Feat][Perf] Add new warmup infrastructure for JITs (#47451)
Signed-off-by: LopezCastroRoberto <rocastro@redhat.com> Signed-off-by: Roberto L. Castro <38211239+LopezCastroRoberto@users.noreply.github.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
fbfe58133d
commit
7ca017778f
@@ -8,6 +8,14 @@ import vllm.envs as envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed import get_dcp_group, get_pcp_group
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.warmup.jit_warmup import (
|
||||
VllmJitKernel,
|
||||
WarmupIntRange,
|
||||
)
|
||||
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
|
||||
TritonPointerInputVariant,
|
||||
TritonWarmupTensor,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.deep_gemm import (
|
||||
@@ -190,6 +198,211 @@ class DeepseekV32IndexerPrefillChunkMetadata:
|
||||
max_local_total_seq_lens: int = 0
|
||||
|
||||
|
||||
_BUILD_PREFILL_CHUNK_METADATA_INPUT_VARIANTS = (
|
||||
TritonPointerInputVariant.from_alignment(uncompressed_seq_lens=True),
|
||||
TritonPointerInputVariant.from_alignment(uncompressed_seq_lens=False),
|
||||
)
|
||||
|
||||
|
||||
class BuildPrefillChunkMetadataKernel(
|
||||
VllmJitKernel["BuildPrefillChunkMetadataKernel.CompileKey"]
|
||||
):
|
||||
BLOCK_SIZE = 1024
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompileKey:
|
||||
query_slice_start: int
|
||||
query_slice_stop: int
|
||||
DCP_RANK: int
|
||||
DCP_WORLD: int
|
||||
DCP_INTERLEAVE: int
|
||||
BLOCK_SIZE: int
|
||||
COMPRESS_RATIO: int
|
||||
input_variant: TritonPointerInputVariant
|
||||
|
||||
@staticmethod
|
||||
@triton.jit
|
||||
def kernel(
|
||||
# Inputs
|
||||
query_start_loc_ptr,
|
||||
uncompressed_seq_lens_ptr,
|
||||
cu_compressed_seq_lens_ptr,
|
||||
# Row-start base for cu_seq_len_ks/ke: local cumulative lens under DCP,
|
||||
# aliases cu_compressed_seq_lens_ptr otherwise.
|
||||
row_start_cu_compressed_seq_lens_ptr,
|
||||
# Outputs
|
||||
token_to_seq_ptr,
|
||||
cu_compressed_seq_len_ks_ptr,
|
||||
cu_compressed_seq_len_ke_ptr,
|
||||
query_slice_start,
|
||||
query_slice_stop,
|
||||
DCP_RANK,
|
||||
DCP_WORLD,
|
||||
DCP_INTERLEAVE,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
):
|
||||
batch_idx = tl.program_id(0)
|
||||
|
||||
query_start = tl.load(query_start_loc_ptr + batch_idx)
|
||||
query_end = tl.load(query_start_loc_ptr + batch_idx + 1)
|
||||
query_len = query_end - query_start
|
||||
|
||||
seq_start = tl.load(cu_compressed_seq_lens_ptr + batch_idx)
|
||||
seq_end = tl.load(cu_compressed_seq_lens_ptr + batch_idx + 1)
|
||||
compressed_seq_len = seq_end - seq_start
|
||||
|
||||
# Row start for the (possibly localized) cu_seq_len_ks/ke. Equals seq_start
|
||||
# when DCP is disabled (the pointer aliases cu_compressed_seq_lens_ptr).
|
||||
row_start = tl.load(row_start_cu_compressed_seq_lens_ptr + batch_idx)
|
||||
|
||||
uncompressed_seq_len = tl.load(uncompressed_seq_lens_ptr + batch_idx)
|
||||
start_pos = uncompressed_seq_len - query_len
|
||||
|
||||
for i in range(0, query_len, BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, BLOCK_SIZE)
|
||||
abs_pos = query_start + offset
|
||||
mask = (
|
||||
(offset < query_len)
|
||||
& (abs_pos >= query_slice_start)
|
||||
& (abs_pos < query_slice_stop)
|
||||
)
|
||||
out_pos = abs_pos - query_slice_start
|
||||
|
||||
# cu_seq_len_ks: row start in the gathered K buffer.
|
||||
tl.store(cu_compressed_seq_len_ks_ptr + out_pos, row_start, mask=mask)
|
||||
|
||||
# cu_seq_len_ke: row start + per-token context length. Under DCP the
|
||||
# global per-token length is sharded across ranks.
|
||||
global_ctx = start_pos + 1 + offset
|
||||
len_per_token = global_ctx // COMPRESS_RATIO
|
||||
if DCP_WORLD > 1:
|
||||
# Per-rank local context length under interleave-aware DCP, matching
|
||||
# get_dcp_local_seq_lens. K == 1 reduces to (len + world-1-rank)//world.
|
||||
base = (len_per_token // DCP_INTERLEAVE // DCP_WORLD) * DCP_INTERLEAVE
|
||||
remainder = len_per_token - base * DCP_WORLD
|
||||
remainder = tl.minimum(
|
||||
tl.maximum(remainder - DCP_RANK * DCP_INTERLEAVE, 0), DCP_INTERLEAVE
|
||||
)
|
||||
len_per_token = base + remainder
|
||||
tl.store(
|
||||
cu_compressed_seq_len_ke_ptr + out_pos,
|
||||
row_start + len_per_token,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
# Compute token_to_seq
|
||||
for i in range(0, compressed_seq_len, BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offset < compressed_seq_len
|
||||
tl.store(token_to_seq_ptr + seq_start + offset, batch_idx, mask=mask)
|
||||
|
||||
def dispatch( # type: ignore[override]
|
||||
self,
|
||||
*,
|
||||
query_slice_start: int,
|
||||
query_slice_stop: int,
|
||||
DCP_RANK: int,
|
||||
DCP_WORLD: int,
|
||||
DCP_INTERLEAVE: int,
|
||||
BLOCK_SIZE: int,
|
||||
COMPRESS_RATIO: int,
|
||||
input_variant: TritonPointerInputVariant,
|
||||
) -> CompileKey:
|
||||
return self.CompileKey(
|
||||
query_slice_start=query_slice_start,
|
||||
query_slice_stop=query_slice_stop,
|
||||
DCP_RANK=DCP_RANK,
|
||||
DCP_WORLD=DCP_WORLD,
|
||||
DCP_INTERLEAVE=DCP_INTERLEAVE,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
COMPRESS_RATIO=COMPRESS_RATIO,
|
||||
input_variant=input_variant,
|
||||
)
|
||||
|
||||
def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]:
|
||||
max_tokens = max(1, min(vllm_config.scheduler_config.max_num_batched_tokens, 8))
|
||||
hf_config = vllm_config.model_config.hf_config
|
||||
parallel_config = vllm_config.parallel_config
|
||||
dcp_world = parallel_config.decode_context_parallel_size
|
||||
dcp_interleave = parallel_config.cp_kv_cache_interleave_size
|
||||
dcp_rank = get_dcp_group().rank_in_group if dcp_world > 1 else 0
|
||||
compress_ratios = tuple(
|
||||
int(ratio)
|
||||
for ratio in (getattr(hf_config, "compress_ratios", None) or (1,))
|
||||
)
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
query_slice_start=WarmupIntRange(0, 2),
|
||||
query_slice_stop=(1, 2 * max_tokens - 1, 2 * max_tokens),
|
||||
DCP_RANK=dcp_rank,
|
||||
DCP_WORLD=dcp_world,
|
||||
DCP_INTERLEAVE=dcp_interleave,
|
||||
BLOCK_SIZE=self.BLOCK_SIZE,
|
||||
COMPRESS_RATIO=list(compress_ratios),
|
||||
input_variant=_BUILD_PREFILL_CHUNK_METADATA_INPUT_VARIANTS,
|
||||
)
|
||||
|
||||
def compile(self, compile_key: CompileKey) -> None:
|
||||
warmup = getattr(self.kernel, "warmup", None)
|
||||
assert warmup is not None
|
||||
int32_ptr = TritonWarmupTensor(torch.int32)
|
||||
warmup(
|
||||
int32_ptr,
|
||||
compile_key.input_variant.pointer("uncompressed_seq_lens", torch.int32),
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
compile_key.query_slice_start,
|
||||
compile_key.query_slice_stop,
|
||||
compile_key.DCP_RANK,
|
||||
compile_key.DCP_WORLD,
|
||||
compile_key.DCP_INTERLEAVE,
|
||||
BLOCK_SIZE=compile_key.BLOCK_SIZE,
|
||||
COMPRESS_RATIO=compile_key.COMPRESS_RATIO,
|
||||
grid=(1,),
|
||||
)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
uncompressed_seq_lens: torch.Tensor,
|
||||
cu_compressed_seq_lens: torch.Tensor,
|
||||
row_start_cu_compressed_seq_lens: torch.Tensor,
|
||||
token_to_seq: torch.Tensor,
|
||||
cu_compressed_seq_len_ks: torch.Tensor,
|
||||
cu_compressed_seq_len_ke: torch.Tensor,
|
||||
query_slice_start: int,
|
||||
query_slice_stop: int,
|
||||
DCP_RANK: int,
|
||||
DCP_WORLD: int,
|
||||
DCP_INTERLEAVE: int,
|
||||
*,
|
||||
num_reqs: int,
|
||||
COMPRESS_RATIO: int,
|
||||
) -> None:
|
||||
self.kernel[(num_reqs,)](
|
||||
query_start_loc,
|
||||
uncompressed_seq_lens,
|
||||
cu_compressed_seq_lens,
|
||||
row_start_cu_compressed_seq_lens,
|
||||
token_to_seq,
|
||||
cu_compressed_seq_len_ks,
|
||||
cu_compressed_seq_len_ke,
|
||||
query_slice_start,
|
||||
query_slice_stop,
|
||||
DCP_RANK,
|
||||
DCP_WORLD,
|
||||
DCP_INTERLEAVE,
|
||||
BLOCK_SIZE=self.BLOCK_SIZE,
|
||||
COMPRESS_RATIO=COMPRESS_RATIO,
|
||||
)
|
||||
|
||||
|
||||
_BUILD_PREFILL_CHUNK_METADATA_KERNEL = BuildPrefillChunkMetadataKernel()
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeepseekV32IndexerPrefillMetadata:
|
||||
chunks: list[DeepseekV32IndexerPrefillChunkMetadata]
|
||||
@@ -841,7 +1054,7 @@ def build_prefill_chunk_metadata(
|
||||
|
||||
# Under DCP the kernel writes this rank's local row bounds into
|
||||
# cu_seq_len_ks/ke; otherwise local_cu_seq_lens aliases cu_seq_lens.
|
||||
_build_prefill_chunk_metadata_kernel[(num_reqs,)](
|
||||
_BUILD_PREFILL_CHUNK_METADATA_KERNEL(
|
||||
query_start_loc,
|
||||
uncompressed_seq_lens[start_idx:end_idx],
|
||||
cu_seq_lens,
|
||||
@@ -854,7 +1067,7 @@ def build_prefill_chunk_metadata(
|
||||
dcp_rank,
|
||||
dcp_world_size,
|
||||
cp_kv_cache_interleave_size,
|
||||
BLOCK_SIZE=1024,
|
||||
num_reqs=num_reqs,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
)
|
||||
|
||||
@@ -881,80 +1094,3 @@ def build_prefill_chunk_metadata(
|
||||
local_total_seq_lens=local_total_seq_lens,
|
||||
max_local_total_seq_lens=max_local_total_seq_lens,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _build_prefill_chunk_metadata_kernel(
|
||||
# Inputs
|
||||
query_start_loc_ptr,
|
||||
uncompressed_seq_lens_ptr,
|
||||
cu_compressed_seq_lens_ptr,
|
||||
# Row-start base for cu_seq_len_ks/ke: local cumulative lens under DCP,
|
||||
# aliases cu_compressed_seq_lens_ptr otherwise.
|
||||
row_start_cu_compressed_seq_lens_ptr,
|
||||
# Outputs
|
||||
token_to_seq_ptr,
|
||||
cu_compressed_seq_len_ks_ptr,
|
||||
cu_compressed_seq_len_ke_ptr,
|
||||
query_slice_start,
|
||||
query_slice_stop,
|
||||
DCP_RANK,
|
||||
DCP_WORLD,
|
||||
DCP_INTERLEAVE,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
):
|
||||
batch_idx = tl.program_id(0)
|
||||
|
||||
query_start = tl.load(query_start_loc_ptr + batch_idx)
|
||||
query_end = tl.load(query_start_loc_ptr + batch_idx + 1)
|
||||
query_len = query_end - query_start
|
||||
|
||||
seq_start = tl.load(cu_compressed_seq_lens_ptr + batch_idx)
|
||||
seq_end = tl.load(cu_compressed_seq_lens_ptr + batch_idx + 1)
|
||||
compressed_seq_len = seq_end - seq_start
|
||||
|
||||
# Row start for the (possibly localized) cu_seq_len_ks/ke. Equals seq_start
|
||||
# when DCP is disabled (the pointer aliases cu_compressed_seq_lens_ptr).
|
||||
row_start = tl.load(row_start_cu_compressed_seq_lens_ptr + batch_idx)
|
||||
|
||||
uncompressed_seq_len = tl.load(uncompressed_seq_lens_ptr + batch_idx)
|
||||
start_pos = uncompressed_seq_len - query_len
|
||||
|
||||
for i in range(0, query_len, BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, BLOCK_SIZE)
|
||||
abs_pos = query_start + offset
|
||||
mask = (
|
||||
(offset < query_len)
|
||||
& (abs_pos >= query_slice_start)
|
||||
& (abs_pos < query_slice_stop)
|
||||
)
|
||||
out_pos = abs_pos - query_slice_start
|
||||
|
||||
# cu_seq_len_ks: row start in the gathered K buffer.
|
||||
tl.store(cu_compressed_seq_len_ks_ptr + out_pos, row_start, mask=mask)
|
||||
|
||||
# cu_seq_len_ke: row start + per-token context length. Under DCP the
|
||||
# global per-token length is sharded across ranks.
|
||||
global_ctx = start_pos + 1 + offset
|
||||
len_per_token = global_ctx // COMPRESS_RATIO
|
||||
if DCP_WORLD > 1:
|
||||
# Per-rank local context length under interleave-aware DCP, matching
|
||||
# get_dcp_local_seq_lens. K == 1 reduces to (len + world-1-rank)//world.
|
||||
base = (len_per_token // DCP_INTERLEAVE // DCP_WORLD) * DCP_INTERLEAVE
|
||||
remainder = len_per_token - base * DCP_WORLD
|
||||
remainder = tl.minimum(
|
||||
tl.maximum(remainder - DCP_RANK * DCP_INTERLEAVE, 0), DCP_INTERLEAVE
|
||||
)
|
||||
len_per_token = base + remainder
|
||||
tl.store(
|
||||
cu_compressed_seq_len_ke_ptr + out_pos,
|
||||
row_start + len_per_token,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
# Compute token_to_seq
|
||||
for i in range(0, compressed_seq_len, BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offset < compressed_seq_len
|
||||
tl.store(token_to_seq_ptr + seq_start + offset, batch_idx, mask=mask)
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
"""FlashAttention backend for MLA prefill."""
|
||||
|
||||
import functools
|
||||
from typing import TYPE_CHECKING
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
|
||||
@@ -11,14 +13,7 @@ import vllm.envs as envs
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
from vllm.model_executor.warmup.cutedsl_warmup import (
|
||||
CuTeDSLCompileUnit,
|
||||
register_cutedsl_warmup_provider,
|
||||
)
|
||||
from vllm.model_executor.warmup.fa4_cutedsl_config import (
|
||||
FA4MLAPrefillCompileContext,
|
||||
iter_fa4_mla_prefill_compile_requests,
|
||||
)
|
||||
from vllm.model_executor.warmup.jit_warmup import VllmJitKernel
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.fa_utils import (
|
||||
compile_flash_attn_varlen_func_from_specs,
|
||||
@@ -32,6 +27,7 @@ from vllm.v1.attention.backends.mla.prefill.base import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import MLADims
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
|
||||
|
||||
if is_flash_attn_varlen_func_available():
|
||||
@@ -40,6 +36,245 @@ else:
|
||||
flash_attn_varlen_func = None # type: ignore[assignment]
|
||||
|
||||
|
||||
FA4_STANDARD_DTYPES = (torch.bfloat16, torch.float16)
|
||||
|
||||
# Current vLLM MLA prefill expands K/V to num_heads before FA4, so this plan
|
||||
# covers qhead_per_kvhead=1. Batch is not a current FA4 MLA-prefill key field.
|
||||
# Use b1 for compile-only specs because it is the conservative case for
|
||||
# Split-KV shape heuristics.
|
||||
# TODO(roberto): FA4 also has direct-GQA and qv/top-k absorbed-MLA paths, but
|
||||
# vLLM does not use them in this backend yet; they need a separate
|
||||
# num_kv_heads/qv/top-k-aware warmup plan if wired in later.
|
||||
FA4_MLA_PREFILL_COMPILE_BATCH_SIZE = 1
|
||||
FA4_MLA_PREFILL_Q_TILE = 128
|
||||
FA4_MLA_PREFILL_K_TILE = 128
|
||||
FA4_MLA_PREFILL_LONG_K_BLOCKS = 32
|
||||
FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS = 64
|
||||
FA4_MLA_PREFILL_CAUSAL_OPTIONS = (False, True)
|
||||
FA4_MLA_PREFILL_LSE_OPTIONS = (False, True)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _FA4MLAPrefillShapeProbe:
|
||||
max_seqlen_q: int
|
||||
max_seqlen_k: int
|
||||
|
||||
|
||||
class FA4MLAPrefillKernel(VllmJitKernel["FA4MLAPrefillKernel.CompileKey"]):
|
||||
"""FA4 MLA prefill compile-key wrapper used by generic JIT warmup."""
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompileKey:
|
||||
"""High-level FA4 compile-only key used by vLLM warmup.
|
||||
|
||||
This is not the CuTeDSL cache key. FA4 owns the selector that maps these
|
||||
serving inputs to the actual compile-static fields: tile sizes, q_stage,
|
||||
Split-KV, scheduler choice, layout-presence booleans, dtype/head dims,
|
||||
arch, and related fields.
|
||||
"""
|
||||
|
||||
q_shape: tuple[int, ...]
|
||||
k_shape: tuple[int, ...]
|
||||
v_shape: tuple[int, ...]
|
||||
q_dtype: torch.dtype
|
||||
max_seqlen_q: int
|
||||
max_seqlen_k: int
|
||||
softmax_scale: float
|
||||
causal: bool
|
||||
fa_version: int
|
||||
v_stride: tuple[int, ...] | None = None
|
||||
cu_seqlens_q_shape: tuple[int, ...] | None = None
|
||||
cu_seqlens_k_shape: tuple[int, ...] | None = None
|
||||
window_size: tuple[int, int] | None = None
|
||||
return_softmax_lse: bool = False
|
||||
num_splits: int = 0
|
||||
|
||||
def dispatch( # type: ignore[override]
|
||||
self,
|
||||
*,
|
||||
batch_size: int,
|
||||
dtype: torch.dtype,
|
||||
num_heads: int,
|
||||
mla_dims: "MLADims",
|
||||
shape_probe: _FA4MLAPrefillShapeProbe,
|
||||
requires_v_padding: bool,
|
||||
causal: bool,
|
||||
fa_version: int,
|
||||
window_size: tuple[int, int] | None = None,
|
||||
return_lse: bool = False,
|
||||
num_splits: int = 0,
|
||||
) -> CompileKey:
|
||||
return self.CompileKey(
|
||||
q_shape=(
|
||||
batch_size * shape_probe.max_seqlen_q,
|
||||
num_heads,
|
||||
mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim,
|
||||
),
|
||||
k_shape=(
|
||||
batch_size * shape_probe.max_seqlen_k,
|
||||
num_heads,
|
||||
mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim,
|
||||
),
|
||||
v_shape=(
|
||||
batch_size * shape_probe.max_seqlen_k,
|
||||
num_heads,
|
||||
(
|
||||
mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim
|
||||
if requires_v_padding
|
||||
else mla_dims.v_head_dim
|
||||
),
|
||||
),
|
||||
q_dtype=dtype,
|
||||
max_seqlen_q=shape_probe.max_seqlen_q,
|
||||
max_seqlen_k=shape_probe.max_seqlen_k,
|
||||
softmax_scale=(mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim)
|
||||
** -0.5,
|
||||
causal=causal,
|
||||
fa_version=fa_version,
|
||||
v_stride=(
|
||||
None
|
||||
if requires_v_padding
|
||||
else (
|
||||
num_heads * (mla_dims.qk_nope_head_dim + mla_dims.v_head_dim),
|
||||
mla_dims.qk_nope_head_dim + mla_dims.v_head_dim,
|
||||
1,
|
||||
)
|
||||
),
|
||||
cu_seqlens_q_shape=(batch_size + 1,),
|
||||
cu_seqlens_k_shape=(batch_size + 1,),
|
||||
window_size=window_size,
|
||||
return_softmax_lse=return_lse,
|
||||
num_splits=num_splits,
|
||||
)
|
||||
|
||||
def get_warmup_keys(self, vllm_config: "VllmConfig") -> list[CompileKey]:
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
get_mla_dims,
|
||||
)
|
||||
|
||||
mla_dims = get_mla_dims(vllm_config.model_config)
|
||||
qk_head_dim = mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim
|
||||
fa_version = get_flash_attn_version(head_size=qk_head_dim)
|
||||
if fa_version != 4:
|
||||
return []
|
||||
|
||||
dtype = vllm_config.model_config.dtype
|
||||
if dtype not in FA4_STANDARD_DTYPES:
|
||||
dtype = torch.bfloat16
|
||||
|
||||
is_sm90 = current_platform.is_device_capability(90)
|
||||
is_sm100_family = current_platform.is_device_capability_family(100)
|
||||
is_sm120 = current_platform.is_device_capability_family(120)
|
||||
if not (is_sm90 or is_sm100_family or is_sm120):
|
||||
return []
|
||||
|
||||
num_splits = 1 if envs.VLLM_BATCH_INVARIANT else 0
|
||||
if is_sm120 and num_splits != 1:
|
||||
return []
|
||||
|
||||
num_heads = vllm_config.model_config.get_num_attention_heads(
|
||||
vllm_config.parallel_config
|
||||
)
|
||||
if num_heads <= 0:
|
||||
return []
|
||||
|
||||
requires_v_padding = False
|
||||
effective_v_head_dim = (
|
||||
qk_head_dim if requires_v_padding else mla_dims.v_head_dim
|
||||
)
|
||||
shape_probes = [
|
||||
_FA4MLAPrefillShapeProbe(1, FA4_MLA_PREFILL_K_TILE),
|
||||
_FA4MLAPrefillShapeProbe(
|
||||
FA4_MLA_PREFILL_Q_TILE + 1,
|
||||
4 * FA4_MLA_PREFILL_K_TILE,
|
||||
),
|
||||
]
|
||||
if num_splits != 1:
|
||||
shape_probes.extend(
|
||||
(
|
||||
_FA4MLAPrefillShapeProbe(
|
||||
1,
|
||||
FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE,
|
||||
),
|
||||
_FA4MLAPrefillShapeProbe(
|
||||
FA4_MLA_PREFILL_Q_TILE + 1,
|
||||
FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE,
|
||||
),
|
||||
)
|
||||
)
|
||||
if not is_sm90 and qk_head_dim != effective_v_head_dim:
|
||||
shape_probes.extend(
|
||||
(
|
||||
_FA4MLAPrefillShapeProbe(
|
||||
1,
|
||||
FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE,
|
||||
),
|
||||
_FA4MLAPrefillShapeProbe(
|
||||
FA4_MLA_PREFILL_Q_TILE + 1,
|
||||
FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
batch_size=FA4_MLA_PREFILL_COMPILE_BATCH_SIZE,
|
||||
dtype=dtype,
|
||||
num_heads=num_heads,
|
||||
mla_dims=mla_dims,
|
||||
shape_probe=shape_probes,
|
||||
requires_v_padding=requires_v_padding,
|
||||
causal=FA4_MLA_PREFILL_CAUSAL_OPTIONS,
|
||||
return_lse=FA4_MLA_PREFILL_LSE_OPTIONS,
|
||||
num_splits=num_splits,
|
||||
fa_version=fa_version,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def kernel(*args: Any, **kwargs: Any) -> Any:
|
||||
assert flash_attn_varlen_func is not None
|
||||
return flash_attn_varlen_func(*args, **kwargs)
|
||||
|
||||
def compile(self, compile_key: CompileKey) -> None:
|
||||
assert compile_flash_attn_varlen_func_from_specs is not None
|
||||
window_size = (
|
||||
list(compile_key.window_size)
|
||||
if compile_key.window_size is not None
|
||||
else None
|
||||
)
|
||||
compile_flash_attn_varlen_func_from_specs(
|
||||
q_shape=compile_key.q_shape,
|
||||
k_shape=compile_key.k_shape,
|
||||
v_shape=compile_key.v_shape,
|
||||
q_dtype=compile_key.q_dtype,
|
||||
v_stride=compile_key.v_stride,
|
||||
cu_seqlens_q_shape=compile_key.cu_seqlens_q_shape,
|
||||
cu_seqlens_k_shape=compile_key.cu_seqlens_k_shape,
|
||||
max_seqlen_q=compile_key.max_seqlen_q,
|
||||
max_seqlen_k=compile_key.max_seqlen_k,
|
||||
softmax_scale=compile_key.softmax_scale,
|
||||
causal=compile_key.causal,
|
||||
window_size=window_size,
|
||||
return_softmax_lse=compile_key.return_softmax_lse,
|
||||
fa_version=compile_key.fa_version,
|
||||
num_splits=compile_key.num_splits,
|
||||
)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
*,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
runtime_kernel: Callable[..., Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> Any:
|
||||
kernel = self.kernel if runtime_kernel is None else runtime_kernel
|
||||
return kernel(q=q, k=k, v=v, **kwargs)
|
||||
|
||||
|
||||
FA4_MLA_PREFILL_KERNEL = FA4MLAPrefillKernel()
|
||||
|
||||
|
||||
class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
"""FlashAttention backend for MLA prefill."""
|
||||
|
||||
@@ -127,46 +362,6 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
# Track whether we're using vllm's FA or upstream (for ROCm)
|
||||
self._is_vllm_fa = current_platform.is_cuda() or current_platform.is_xpu()
|
||||
if self.vllm_flash_attn_version == 4:
|
||||
register_cutedsl_warmup_provider(self)
|
||||
|
||||
def get_cutedsl_warmup_compile_units(self) -> tuple[CuTeDSLCompileUnit, ...]:
|
||||
if self.vllm_flash_attn_version != 4:
|
||||
return ()
|
||||
if compile_flash_attn_varlen_func_from_specs is None:
|
||||
raise RuntimeError(
|
||||
"FA4 compile-only API is unavailable; CuTeDSL warmup does not "
|
||||
"fall back to synthetic forward passes."
|
||||
)
|
||||
|
||||
dtype = self.vllm_config.model_config.dtype
|
||||
if dtype not in self.supported_dtypes:
|
||||
dtype = torch.bfloat16
|
||||
|
||||
qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
|
||||
ctx = FA4MLAPrefillCompileContext(
|
||||
dtype=dtype,
|
||||
num_heads=self.num_heads,
|
||||
qk_head_dim=qk_head_dim,
|
||||
v_head_dim=self.v_head_dim,
|
||||
kv_nope_head_dim=self.qk_nope_head_dim + self.v_head_dim,
|
||||
requires_v_padding=self.requires_v_padding,
|
||||
scale=self.scale,
|
||||
num_splits=1 if envs.VLLM_BATCH_INVARIANT else 0,
|
||||
fa_version=self.vllm_flash_attn_version,
|
||||
)
|
||||
compile_requests = tuple(iter_fa4_mla_prefill_compile_requests(ctx))
|
||||
if not compile_requests:
|
||||
return ()
|
||||
|
||||
return tuple(
|
||||
CuTeDSLCompileUnit(
|
||||
name="fa4_mla_prefill",
|
||||
key=request.key,
|
||||
compile=request.compile,
|
||||
)
|
||||
for request in compile_requests
|
||||
)
|
||||
|
||||
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
|
||||
device_capability = current_platform.get_device_capability()
|
||||
@@ -207,10 +402,11 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
kwargs["num_splits"] = 1
|
||||
|
||||
attn_out = self.flash_attn_varlen_func(
|
||||
attn_out = FA4_MLA_PREFILL_KERNEL(
|
||||
q=q,
|
||||
k=k,
|
||||
v=maybe_padded_v,
|
||||
runtime_kernel=self.flash_attn_varlen_func,
|
||||
softmax_scale=softmax_scale,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@@ -7,9 +7,14 @@ import torch
|
||||
|
||||
from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.warmup.jit_warmup import (
|
||||
VllmJitKernel,
|
||||
WarmupIntRange,
|
||||
)
|
||||
from vllm.model_executor.warmup.jit_warmup_triton_helper import TritonWarmupTensor
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.math_utils import cdiv, next_power_of_2
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
@@ -279,6 +284,107 @@ class DeepseekSparseSWAMetadata:
|
||||
return chunk_plan
|
||||
|
||||
|
||||
class ComputePrefillMetadataKernel(
|
||||
VllmJitKernel["ComputePrefillMetadataKernel.CompileKey"]
|
||||
):
|
||||
@dataclass(frozen=True)
|
||||
class CompileKey:
|
||||
BLOCK_SIZE: int
|
||||
|
||||
@staticmethod
|
||||
@triton.jit(do_not_specialize=["num_prefills", "num_decodes", "window_size"])
|
||||
def kernel(
|
||||
# Outputs
|
||||
prefill_gather_lens_ptr,
|
||||
# Inputs
|
||||
seq_lens_ptr,
|
||||
query_start_loc_ptr,
|
||||
num_prefills,
|
||||
num_decodes,
|
||||
window_size,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
"""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 + 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
|
||||
gather_len = query_len + tl.minimum(prefix_len, window_size - 1)
|
||||
|
||||
tl.store(prefill_gather_lens_ptr + offset, gather_len, mask=mask)
|
||||
|
||||
def dispatch( # type: ignore[override]
|
||||
self,
|
||||
*,
|
||||
num_prefills: int,
|
||||
) -> CompileKey:
|
||||
return self.CompileKey(
|
||||
BLOCK_SIZE=next_power_of_2(num_prefills),
|
||||
)
|
||||
|
||||
def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]:
|
||||
scheduler_config = vllm_config.scheduler_config
|
||||
max_prefills = max(
|
||||
1,
|
||||
min(
|
||||
scheduler_config.max_num_seqs,
|
||||
scheduler_config.max_num_batched_tokens,
|
||||
),
|
||||
)
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
num_prefills=WarmupIntRange(1, max_prefills + 1),
|
||||
)
|
||||
|
||||
def compile(self, compile_key: CompileKey) -> None:
|
||||
warmup = getattr(self.kernel, "warmup", None)
|
||||
assert warmup is not None
|
||||
int32_ptr = TritonWarmupTensor(torch.int32)
|
||||
warmup(
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
compile_key.BLOCK_SIZE,
|
||||
0,
|
||||
1,
|
||||
BLOCK_SIZE=compile_key.BLOCK_SIZE,
|
||||
grid=(1,),
|
||||
)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
prefill_gather_lens: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
num_prefills: int,
|
||||
num_decodes: int,
|
||||
window_size: int,
|
||||
) -> None:
|
||||
compile_key = self.dispatch(num_prefills=num_prefills)
|
||||
self.kernel[(1,)](
|
||||
prefill_gather_lens,
|
||||
seq_lens,
|
||||
query_start_loc,
|
||||
num_prefills,
|
||||
num_decodes,
|
||||
window_size,
|
||||
BLOCK_SIZE=compile_key.BLOCK_SIZE,
|
||||
)
|
||||
|
||||
|
||||
_COMPUTE_PREFILL_METADATA_KERNEL = ComputePrefillMetadataKernel()
|
||||
|
||||
|
||||
class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
"""Builds metadata for DeepseekV4 SWA cache.
|
||||
|
||||
@@ -602,14 +708,13 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
pfx_gather_lens = torch.empty(
|
||||
num_prefills, dtype=torch.int32, device=seq_lens.device
|
||||
)
|
||||
_compute_prefill_metadata_kernel[(1,)](
|
||||
_COMPUTE_PREFILL_METADATA_KERNEL(
|
||||
pfx_gather_lens,
|
||||
seq_lens,
|
||||
query_start_loc,
|
||||
num_prefills,
|
||||
num_decodes,
|
||||
self.window_size,
|
||||
BLOCK_SIZE=triton.next_power_of_2(num_prefills),
|
||||
)
|
||||
|
||||
result["prefill_seq_lens"] = seq_lens[num_decodes:]
|
||||
@@ -626,37 +731,6 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
return result
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _compute_prefill_metadata_kernel(
|
||||
# Outputs
|
||||
prefill_gather_lens_ptr,
|
||||
# Inputs
|
||||
seq_lens_ptr,
|
||||
query_start_loc_ptr,
|
||||
num_prefills,
|
||||
num_decodes,
|
||||
window_size,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
"""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 + 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
|
||||
gather_len = query_len + tl.minimum(prefix_len, window_size - 1)
|
||||
|
||||
tl.store(prefill_gather_lens_ptr + offset, gather_len, mask=mask)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["token_offset"])
|
||||
def _compute_swa_indices_and_lens_kernel(
|
||||
swa_indices_ptr,
|
||||
|
||||
Reference in New Issue
Block a user