[Attention] Abstract the MLA prefill backends and eliminate cuDNN (#32623)
Signed-off-by: Matthew Bonanni <mbonanni@redhat.com> Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: Michael Goin <mgoin64@gmail.com> Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Michael Goin
Lucas Wilkinson
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
51295793a2
commit
f3fef12350
@@ -0,0 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
from vllm.v1.attention.backends.mla.prefill.registry import MLAPrefillBackendEnum
|
||||
from vllm.v1.attention.backends.mla.prefill.selector import get_mla_prefill_backend
|
||||
|
||||
__all__ = [
|
||||
"MLAPrefillBackend",
|
||||
"MLAPrefillBackendEnum",
|
||||
"get_mla_prefill_backend",
|
||||
]
|
||||
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Abstract base class for MLA prefill backends."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
import torch
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonPrefillMetadata,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.mla.prefill.selector import (
|
||||
MLAPrefillSelectorConfig,
|
||||
)
|
||||
|
||||
|
||||
class MLAPrefillBackend(ABC):
|
||||
"""Abstract base class for MLA prefill backends."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [
|
||||
torch.float16,
|
||||
torch.bfloat16,
|
||||
]
|
||||
requires_r1_mla_dimensions: ClassVar[bool] = False
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def get_name() -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_dtype(cls, dtype: torch.dtype) -> bool:
|
||||
return dtype in cls.supported_dtypes
|
||||
|
||||
@classmethod
|
||||
def is_available(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def validate_configuration(
|
||||
cls,
|
||||
device_capability: "DeviceCapability",
|
||||
selector_config: "MLAPrefillSelectorConfig",
|
||||
) -> list[str]:
|
||||
invalid_reasons: list[str] = []
|
||||
|
||||
if not cls.supports_compute_capability(device_capability):
|
||||
invalid_reasons.append(
|
||||
f"compute capability {device_capability.major}."
|
||||
f"{device_capability.minor} not supported"
|
||||
)
|
||||
|
||||
if not cls.supports_dtype(selector_config.dtype):
|
||||
invalid_reasons.append(f"dtype {selector_config.dtype} not supported")
|
||||
|
||||
if not cls.is_available():
|
||||
invalid_reasons.append("required dependencies not available")
|
||||
|
||||
if cls.requires_r1_mla_dimensions and not selector_config.is_r1_compatible:
|
||||
invalid_reasons.append(
|
||||
"model does not have DeepSeek R1 MLA dimensions "
|
||||
"(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128)"
|
||||
)
|
||||
|
||||
return invalid_reasons
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
scale: float,
|
||||
kv_lora_rank: int,
|
||||
qk_nope_head_dim: int,
|
||||
qk_rope_head_dim: int,
|
||||
v_head_dim: int,
|
||||
vllm_config: "VllmConfig",
|
||||
device: torch.device,
|
||||
layer_names: list[str] | None = None,
|
||||
) -> None:
|
||||
self.num_heads = num_heads
|
||||
self.scale = scale
|
||||
self.kv_lora_rank = kv_lora_rank
|
||||
self.qk_nope_head_dim = qk_nope_head_dim
|
||||
self.qk_rope_head_dim = qk_rope_head_dim
|
||||
self.v_head_dim = v_head_dim
|
||||
self.vllm_config = vllm_config
|
||||
self.device = device
|
||||
self.layer_names = layer_names
|
||||
|
||||
def prepare_metadata( # noqa: B027
|
||||
self,
|
||||
prefill_metadata: "MLACommonPrefillMetadata",
|
||||
) -> None:
|
||||
"""Prepare backend-specific metadata before the forward pass.
|
||||
|
||||
Called by the metadata builder after constructing the prefill metadata.
|
||||
"""
|
||||
self._prefill_metadata = prefill_metadata
|
||||
|
||||
@abstractmethod
|
||||
def run_prefill_new_tokens(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,180 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlashAttention backend for MLA prefill."""
|
||||
|
||||
import functools
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.fa_utils import (
|
||||
get_flash_attn_version,
|
||||
is_flash_attn_varlen_func_available,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
if is_flash_attn_varlen_func_available():
|
||||
from vllm.v1.attention.backends.fa_utils import flash_attn_varlen_func
|
||||
else:
|
||||
flash_attn_varlen_func = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
"""FlashAttention backend for MLA prefill."""
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASH_ATTN"
|
||||
|
||||
@classmethod
|
||||
def is_available(cls) -> bool:
|
||||
return is_flash_attn_varlen_func_available()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
scale: float,
|
||||
kv_lora_rank: int,
|
||||
qk_nope_head_dim: int,
|
||||
qk_rope_head_dim: int,
|
||||
v_head_dim: int,
|
||||
vllm_config: "VllmConfig",
|
||||
device: torch.device,
|
||||
layer_names: list[str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
num_heads=num_heads,
|
||||
scale=scale,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=vllm_config,
|
||||
device=device,
|
||||
layer_names=layer_names,
|
||||
)
|
||||
|
||||
# Handle the differences between the flash_attn_varlen from
|
||||
# flash_attn and the one from vllm_flash_attn
|
||||
assert flash_attn_varlen_func is not None, (
|
||||
"FlashAttnPrefillBackend requires flash_attn_varlen_func. "
|
||||
"Ensure FlashAttnPrefillBackend.is_available() is checked first."
|
||||
)
|
||||
qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
||||
self.flash_attn_varlen_func = flash_attn_varlen_func
|
||||
self.vllm_flash_attn_version = get_flash_attn_version(head_size=qk_head_dim)
|
||||
if self.vllm_flash_attn_version is not None:
|
||||
self.flash_attn_varlen_func = functools.partial(
|
||||
flash_attn_varlen_func, fa_version=self.vllm_flash_attn_version
|
||||
)
|
||||
|
||||
# Determine if we need to pad V
|
||||
# For MLA the v head dim is smaller than qk head dim so we pad out
|
||||
# v with 0s to match the qk head dim for attention backends that do
|
||||
# not support different headdims.
|
||||
# FA3 on Hopper (SM90) and FA4 natively handle diff headdims.
|
||||
device_capability = current_platform.get_device_capability()
|
||||
self.requires_v_padding = self.vllm_flash_attn_version is None or not (
|
||||
(
|
||||
self.vllm_flash_attn_version == 3
|
||||
and device_capability is not None
|
||||
and device_capability[0] == 9
|
||||
)
|
||||
or self.vllm_flash_attn_version == 4
|
||||
)
|
||||
|
||||
# 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()
|
||||
|
||||
def _flash_attn_varlen_diff_headdims(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool = False,
|
||||
softmax_scale: float | None = None,
|
||||
**kwargs,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
maybe_padded_v = v
|
||||
if self.requires_v_padding:
|
||||
maybe_padded_v = torch.nn.functional.pad(
|
||||
v, [0, q.shape[-1] - v.shape[-1]], value=0
|
||||
)
|
||||
|
||||
if self._is_vllm_fa:
|
||||
kwargs["return_softmax_lse"] = return_softmax_lse
|
||||
else:
|
||||
# ROCm leverages the upstream flash_attn, which takes a parameter
|
||||
# called "return_attn_probs" instead of return_softmax_lse
|
||||
kwargs["return_attn_probs"] = return_softmax_lse
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
kwargs["num_splits"] = 1
|
||||
|
||||
attn_out = self.flash_attn_varlen_func(
|
||||
q=q,
|
||||
k=k,
|
||||
v=maybe_padded_v,
|
||||
softmax_scale=softmax_scale,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
# Unpack the output if there are multiple results
|
||||
lse = None
|
||||
if isinstance(attn_out, tuple):
|
||||
attn_out, lse = attn_out[0], attn_out[1]
|
||||
|
||||
# Unpad output back to v_head_dim if we padded V
|
||||
if self.requires_v_padding:
|
||||
attn_out = attn_out[..., : v.shape[-1]]
|
||||
|
||||
# Remain consistent with old `flash_attn_varlen_func` where there
|
||||
# is only one output tensor if `return_softmax_lse` is False.
|
||||
if return_softmax_lse:
|
||||
return attn_out, lse
|
||||
return attn_out
|
||||
|
||||
def run_prefill_new_tokens(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
return self._flash_attn_varlen_diff_headdims(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
cu_seqlens_q=self._prefill_metadata.query_start_loc,
|
||||
cu_seqlens_k=self._prefill_metadata.query_start_loc,
|
||||
max_seqlen_q=self._prefill_metadata.max_query_len,
|
||||
max_seqlen_k=self._prefill_metadata.max_query_len,
|
||||
softmax_scale=self.scale,
|
||||
causal=True,
|
||||
return_softmax_lse=return_softmax_lse,
|
||||
)
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert self._prefill_metadata.chunked_context is not None
|
||||
return self._flash_attn_varlen_diff_headdims(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
cu_seqlens_q=self._prefill_metadata.query_start_loc,
|
||||
cu_seqlens_k=self._prefill_metadata.chunked_context.cu_seq_lens[chunk_idx],
|
||||
max_seqlen_q=self._prefill_metadata.max_query_len,
|
||||
max_seqlen_k=self._prefill_metadata.chunked_context.max_seq_lens[chunk_idx],
|
||||
softmax_scale=self.scale,
|
||||
causal=False, # Context is unmasked
|
||||
return_softmax_lse=True,
|
||||
)
|
||||
@@ -0,0 +1,211 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlashInfer backend for MLA prefill."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
from vllm.v1.attention.backends.utils import (
|
||||
get_per_layer_parameters,
|
||||
infer_global_hyperparameters,
|
||||
)
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonPrefillMetadata,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
try:
|
||||
from flashinfer import BatchPrefillWithRaggedKVCacheWrapper
|
||||
except ImportError:
|
||||
BatchPrefillWithRaggedKVCacheWrapper = object # type: ignore[misc,assignment]
|
||||
|
||||
_DEFAULT_NUM_CHUNKS = 32
|
||||
|
||||
|
||||
class FlashInferPrefillBackend(MLAPrefillBackend):
|
||||
"""FlashInfer backend for MLA prefill."""
|
||||
|
||||
requires_r1_mla_dimensions = True
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER"
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
return device_capability.major == 10
|
||||
|
||||
@classmethod
|
||||
def is_available(cls) -> bool:
|
||||
try:
|
||||
from flashinfer import (
|
||||
BatchPrefillWithRaggedKVCacheWrapper, # noqa: F401
|
||||
)
|
||||
|
||||
return True
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
scale: float,
|
||||
kv_lora_rank: int,
|
||||
qk_nope_head_dim: int,
|
||||
qk_rope_head_dim: int,
|
||||
v_head_dim: int,
|
||||
vllm_config: "VllmConfig",
|
||||
device: torch.device,
|
||||
layer_names: list[str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
num_heads=num_heads,
|
||||
scale=scale,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=vllm_config,
|
||||
device=device,
|
||||
layer_names=layer_names,
|
||||
)
|
||||
|
||||
self._prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None
|
||||
self._prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = []
|
||||
if layer_names is None:
|
||||
raise ValueError(
|
||||
"FlashInferPrefillBackend requires layer_names to "
|
||||
"initialize global hyperparameters."
|
||||
)
|
||||
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonImpl,
|
||||
)
|
||||
|
||||
self._global_hyperparameters = infer_global_hyperparameters(
|
||||
get_per_layer_parameters(vllm_config, layer_names, MLACommonImpl) # type: ignore[type-abstract]
|
||||
)
|
||||
|
||||
def _ensure_chunks(
|
||||
self,
|
||||
num_chunks: int,
|
||||
workspace_buffer: torch.Tensor,
|
||||
) -> None:
|
||||
if len(self._prefill_chunks) < num_chunks:
|
||||
for _ in range(len(self._prefill_chunks), num_chunks):
|
||||
self._prefill_chunks.append(
|
||||
BatchPrefillWithRaggedKVCacheWrapper(
|
||||
workspace_buffer, "NHD", backend="cutlass"
|
||||
)
|
||||
)
|
||||
|
||||
def prepare_metadata(
|
||||
self,
|
||||
prefill_metadata: "MLACommonPrefillMetadata",
|
||||
) -> None:
|
||||
qo_indptr = prefill_metadata.query_start_loc
|
||||
has_context = prefill_metadata.chunked_context is not None
|
||||
(workspace_buffer,) = current_workspace_manager().get_simultaneous(
|
||||
((envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE,), torch.uint8),
|
||||
)
|
||||
|
||||
if self._prefill_main is None:
|
||||
self._prefill_main = BatchPrefillWithRaggedKVCacheWrapper(
|
||||
workspace_buffer, "NHD", backend="cutlass"
|
||||
)
|
||||
self._ensure_chunks(_DEFAULT_NUM_CHUNKS, workspace_buffer)
|
||||
|
||||
if has_context:
|
||||
chunked_context = prefill_metadata.chunked_context
|
||||
assert chunked_context is not None
|
||||
num_chunks = chunked_context.cu_seq_lens.shape[0]
|
||||
self._ensure_chunks(num_chunks, workspace_buffer)
|
||||
|
||||
num_qo_heads = self.num_heads
|
||||
num_kv_heads = num_qo_heads
|
||||
|
||||
head_dim_qk = self.qk_nope_head_dim + self.qk_rope_head_dim
|
||||
head_dim_vo = self.v_head_dim
|
||||
kv_indptr = qo_indptr.clone()
|
||||
|
||||
assert self._prefill_main is not None
|
||||
self._prefill_main.plan(
|
||||
qo_indptr=qo_indptr,
|
||||
kv_indptr=kv_indptr,
|
||||
num_qo_heads=num_qo_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_dim_qk=head_dim_qk,
|
||||
head_dim_vo=head_dim_vo,
|
||||
causal=True,
|
||||
sm_scale=self._global_hyperparameters.sm_scale,
|
||||
window_left=self._global_hyperparameters.window_left,
|
||||
logits_soft_cap=self._global_hyperparameters.logits_soft_cap,
|
||||
q_data_type=prefill_metadata.q_data_type,
|
||||
o_data_type=prefill_metadata.output_dtype,
|
||||
)
|
||||
|
||||
if has_context:
|
||||
chunked_context = prefill_metadata.chunked_context
|
||||
assert chunked_context is not None
|
||||
for i in range(num_chunks):
|
||||
kv_indptr_chunk = chunked_context.cu_seq_lens[i]
|
||||
|
||||
self._prefill_chunks[i].plan(
|
||||
qo_indptr=qo_indptr,
|
||||
kv_indptr=kv_indptr_chunk,
|
||||
num_qo_heads=num_qo_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_dim_qk=head_dim_qk,
|
||||
head_dim_vo=head_dim_vo,
|
||||
causal=False,
|
||||
sm_scale=self._global_hyperparameters.sm_scale,
|
||||
window_left=self._global_hyperparameters.window_left,
|
||||
logits_soft_cap=self._global_hyperparameters.logits_soft_cap,
|
||||
q_data_type=prefill_metadata.q_data_type,
|
||||
o_data_type=prefill_metadata.output_dtype,
|
||||
)
|
||||
|
||||
def run_prefill_new_tokens(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
assert self._prefill_main is not None
|
||||
|
||||
ret = self._prefill_main.run(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
return_lse=return_softmax_lse,
|
||||
)
|
||||
|
||||
if isinstance(ret, tuple):
|
||||
# Convert from (q_len, num_heads) to (num_heads, q_len)
|
||||
return ret[0], ret[1].transpose(0, 1).contiguous()
|
||||
return ret
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
attn_out, lse = self._prefill_chunks[chunk_idx].run(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
return_lse=True,
|
||||
)
|
||||
|
||||
# Convert from (q_len, num_heads) to (num_heads, q_len)
|
||||
return attn_out, lse.transpose(0, 1).contiguous()
|
||||
@@ -0,0 +1,53 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Registry for MLA prefill backends.
|
||||
|
||||
This module provides an enumeration of all available MLA prefill backends
|
||||
and utilities for loading them.
|
||||
"""
|
||||
|
||||
from enum import Enum, EnumMeta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
|
||||
|
||||
class _MLAPrefillBackendEnumMeta(EnumMeta):
|
||||
"""Metaclass for MLAPrefillBackendEnum to provide better error messages."""
|
||||
|
||||
def __getitem__(cls, name: str):
|
||||
try:
|
||||
return super().__getitem__(name)
|
||||
except KeyError:
|
||||
members = cls.__members__.keys()
|
||||
valid_backends = ", ".join(members)
|
||||
raise ValueError(
|
||||
f"Unknown MLA prefill backend: '{name}'. "
|
||||
f"Valid options are: {valid_backends}"
|
||||
) from None
|
||||
|
||||
|
||||
class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
|
||||
"""Enumeration of all supported MLA prefill backends."""
|
||||
|
||||
FLASH_ATTN = (
|
||||
"vllm.v1.attention.backends.mla.prefill.flash_attn.FlashAttnPrefillBackend"
|
||||
)
|
||||
FLASHINFER = (
|
||||
"vllm.v1.attention.backends.mla.prefill.flashinfer.FlashInferPrefillBackend"
|
||||
)
|
||||
TRTLLM_RAGGED = (
|
||||
"vllm.v1.attention.backends.mla.prefill.trtllm_ragged."
|
||||
"TrtllmRaggedPrefillBackend"
|
||||
)
|
||||
|
||||
def get_path(self) -> str:
|
||||
"""Get the fully qualified class path for this backend."""
|
||||
return self.value
|
||||
|
||||
def get_class(self) -> "type[MLAPrefillBackend]":
|
||||
"""Lazy load and return the backend class."""
|
||||
return resolve_obj_by_qualname(self.get_path())
|
||||
@@ -0,0 +1,183 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Selector for MLA prefill backends.
|
||||
|
||||
This module provides functions for selecting the appropriate MLA prefill
|
||||
backend based on device capabilities and configuration.
|
||||
"""
|
||||
|
||||
from functools import cache
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.mla.prefill.registry import MLAPrefillBackendEnum
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class MLAPrefillSelectorConfig(NamedTuple):
|
||||
"""Hashable configuration for MLA prefill backend selection.
|
||||
|
||||
This is analogous to AttentionSelectorConfig and contains model-specific
|
||||
configuration needed to select an MLA prefill backend, extracted from
|
||||
VllmConfig into a hashable form for caching.
|
||||
"""
|
||||
|
||||
dtype: torch.dtype
|
||||
is_r1_compatible: bool
|
||||
|
||||
|
||||
def is_deepseek_r1_mla_compatible(vllm_config: "VllmConfig") -> bool:
|
||||
"""Check if model has DeepSeek R1 compatible MLA dimensions.
|
||||
|
||||
DeepSeek R1 MLA dimensions are:
|
||||
- qk_nope_head_dim = 128
|
||||
- qk_rope_head_dim = 64
|
||||
- v_head_dim = 128
|
||||
"""
|
||||
if vllm_config.model_config is None:
|
||||
return False
|
||||
hf_text_config = vllm_config.model_config.hf_text_config
|
||||
qk_nope_head_dim = getattr(hf_text_config, "qk_nope_head_dim", 1)
|
||||
qk_rope_head_dim = getattr(hf_text_config, "qk_rope_head_dim", 1)
|
||||
v_head_dim = getattr(hf_text_config, "v_head_dim", 1)
|
||||
return qk_nope_head_dim == 128 and qk_rope_head_dim == 64 and v_head_dim == 128
|
||||
|
||||
|
||||
def _get_mla_prefill_backend_priorities(
|
||||
device_capability: DeviceCapability,
|
||||
) -> list[MLAPrefillBackendEnum]:
|
||||
"""Get MLA prefill backend priorities based on device capability.
|
||||
|
||||
Args:
|
||||
device_capability: The device's compute capability.
|
||||
|
||||
Returns:
|
||||
List of backends in priority order (highest priority first).
|
||||
"""
|
||||
if device_capability.major == 10: # Blackwell
|
||||
return [
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
MLAPrefillBackendEnum.FLASHINFER,
|
||||
]
|
||||
else: # Hopper (SM90) and older
|
||||
return [
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
]
|
||||
|
||||
|
||||
def get_mla_prefill_backend(
|
||||
vllm_config: "VllmConfig",
|
||||
) -> "type[MLAPrefillBackend]":
|
||||
"""Select the MLA prefill backend based on configuration and device.
|
||||
|
||||
This function first checks for explicit user preferences via
|
||||
mla_prefill_backend in AttentionConfig, then falls back to automatic
|
||||
priority-based selection.
|
||||
|
||||
Args:
|
||||
vllm_config: The vLLM configuration.
|
||||
|
||||
Returns:
|
||||
The selected prefill backend class.
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
device_capability = current_platform.get_device_capability()
|
||||
if device_capability is None:
|
||||
logger.info_once(
|
||||
"Device capability not available, using FlashAttention MLA prefill backend."
|
||||
)
|
||||
return MLAPrefillBackendEnum.FLASH_ATTN.get_class()
|
||||
|
||||
attention_config = vllm_config.attention_config
|
||||
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=vllm_config.model_config.dtype,
|
||||
is_r1_compatible=is_deepseek_r1_mla_compatible(vllm_config),
|
||||
)
|
||||
|
||||
if attention_config.mla_prefill_backend is not None:
|
||||
selected_backend = attention_config.mla_prefill_backend
|
||||
backend_cls: type[MLAPrefillBackend] | None = None
|
||||
try:
|
||||
backend_cls = selected_backend.get_class()
|
||||
invalid_reasons = backend_cls.validate_configuration(
|
||||
device_capability, selector_config
|
||||
)
|
||||
except ImportError:
|
||||
invalid_reasons = ["ImportError"]
|
||||
if invalid_reasons:
|
||||
raise ValueError(
|
||||
f"Selected MLA prefill backend {selected_backend.name} "
|
||||
f"is not valid for this configuration. "
|
||||
f"Reason: {invalid_reasons}"
|
||||
)
|
||||
assert backend_cls is not None
|
||||
logger.info("Using %s MLA prefill backend.", selected_backend.name)
|
||||
return backend_cls
|
||||
|
||||
return _auto_select_mla_prefill_backend(
|
||||
device_capability,
|
||||
selector_config,
|
||||
)
|
||||
|
||||
|
||||
@cache
|
||||
def _auto_select_mla_prefill_backend(
|
||||
device_capability: DeviceCapability,
|
||||
selector_config: MLAPrefillSelectorConfig,
|
||||
) -> "type[MLAPrefillBackend]":
|
||||
"""Auto-select the best available MLA prefill backend.
|
||||
|
||||
Args:
|
||||
device_capability: The device's compute capability.
|
||||
selector_config: Hashable configuration for backend selection.
|
||||
|
||||
Returns:
|
||||
The selected prefill backend class.
|
||||
"""
|
||||
priorities = _get_mla_prefill_backend_priorities(device_capability)
|
||||
all_invalid_reasons: dict[str, list[str]] = {}
|
||||
|
||||
for backend_enum in priorities:
|
||||
backend_cls: type[MLAPrefillBackend] | None = None
|
||||
try:
|
||||
backend_cls = backend_enum.get_class()
|
||||
invalid_reasons = backend_cls.validate_configuration(
|
||||
device_capability, selector_config
|
||||
)
|
||||
except ImportError:
|
||||
invalid_reasons = ["ImportError"]
|
||||
if not invalid_reasons:
|
||||
assert backend_cls is not None
|
||||
logger.info_once("Using %s MLA prefill backend.", backend_enum.name)
|
||||
return backend_cls
|
||||
all_invalid_reasons[backend_enum.name] = invalid_reasons
|
||||
|
||||
reasons_str = (
|
||||
"{"
|
||||
+ ", ".join(
|
||||
f"{name}: [{', '.join(reasons)}]"
|
||||
for name, reasons in all_invalid_reasons.items()
|
||||
)
|
||||
+ "}"
|
||||
)
|
||||
config_str = repr(selector_config)
|
||||
logger.debug_once(
|
||||
"Some MLA prefill backends are not valid with %s. Reasons: %s.",
|
||||
config_str,
|
||||
reasons_str,
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
f"No valid MLA prefill backend found with {config_str}. Reasons: {reasons_str}."
|
||||
)
|
||||
@@ -0,0 +1,178 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""TRT-LLM Ragged backend for MLA prefill."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonPrefillMetadata,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
|
||||
class TrtllmRaggedPrefillBackend(MLAPrefillBackend):
|
||||
"""TRT-LLM Ragged backend for MLA prefill."""
|
||||
|
||||
requires_r1_mla_dimensions = True
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "TRTLLM_RAGGED"
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
return device_capability.major == 10
|
||||
|
||||
@classmethod
|
||||
def is_available(cls) -> bool:
|
||||
try:
|
||||
from flashinfer.prefill import (
|
||||
trtllm_ragged_attention_deepseek, # noqa: F401
|
||||
)
|
||||
|
||||
return True
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
scale: float,
|
||||
kv_lora_rank: int,
|
||||
qk_nope_head_dim: int,
|
||||
qk_rope_head_dim: int,
|
||||
v_head_dim: int,
|
||||
vllm_config: "VllmConfig",
|
||||
device: torch.device,
|
||||
layer_names: list[str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
num_heads=num_heads,
|
||||
scale=scale,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=vllm_config,
|
||||
device=device,
|
||||
layer_names=layer_names,
|
||||
)
|
||||
|
||||
def _get_workspace_buffer(self) -> torch.Tensor:
|
||||
(workspace_buffer,) = current_workspace_manager().get_simultaneous(
|
||||
(
|
||||
(envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE,),
|
||||
torch.uint8,
|
||||
),
|
||||
)
|
||||
return workspace_buffer
|
||||
|
||||
def prepare_metadata(
|
||||
self,
|
||||
prefill_metadata: "MLACommonPrefillMetadata",
|
||||
) -> None:
|
||||
super().prepare_metadata(prefill_metadata)
|
||||
self._query_seq_lens = (
|
||||
prefill_metadata.query_start_loc[1:] - prefill_metadata.query_start_loc[:-1]
|
||||
)
|
||||
|
||||
def run_prefill_new_tokens(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
from flashinfer.prefill import trtllm_ragged_attention_deepseek
|
||||
|
||||
workspace_buffer = self._get_workspace_buffer()
|
||||
out = torch.empty(
|
||||
q.shape[0],
|
||||
q.shape[1],
|
||||
v.shape[2],
|
||||
device=q.device,
|
||||
dtype=self._prefill_metadata.output_dtype,
|
||||
)
|
||||
|
||||
ret = trtllm_ragged_attention_deepseek(
|
||||
query=q,
|
||||
key=k,
|
||||
value=v,
|
||||
workspace_buffer=workspace_buffer,
|
||||
seq_lens=self._query_seq_lens,
|
||||
max_q_len=self._prefill_metadata.max_query_len,
|
||||
max_kv_len=self._prefill_metadata.max_query_len,
|
||||
bmm1_scale=self.scale,
|
||||
bmm2_scale=1.0,
|
||||
o_sf_scale=1.0,
|
||||
batch_size=self._query_seq_lens.shape[0],
|
||||
window_left=-1,
|
||||
cum_seq_lens_q=self._prefill_metadata.query_start_loc,
|
||||
cum_seq_lens_kv=self._prefill_metadata.query_start_loc,
|
||||
enable_pdl=False,
|
||||
is_causal=True,
|
||||
return_lse=return_softmax_lse,
|
||||
out=out,
|
||||
)
|
||||
|
||||
if isinstance(ret, tuple):
|
||||
# Convert from (q_len, num_heads) to (num_heads, q_len)
|
||||
return ret[0], ret[1].transpose(0, 1).contiguous()
|
||||
return ret
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
from flashinfer.prefill import trtllm_ragged_attention_deepseek
|
||||
|
||||
assert self._prefill_metadata.chunked_context is not None
|
||||
assert self._prefill_metadata.chunked_context.seq_lens[chunk_idx] is not None
|
||||
workspace_buffer = self._get_workspace_buffer()
|
||||
|
||||
out = torch.empty(
|
||||
q.shape[0],
|
||||
q.shape[1],
|
||||
v.shape[2],
|
||||
device=q.device,
|
||||
dtype=self._prefill_metadata.output_dtype,
|
||||
)
|
||||
|
||||
attn_out, lse = trtllm_ragged_attention_deepseek(
|
||||
query=q,
|
||||
key=k,
|
||||
value=v,
|
||||
workspace_buffer=workspace_buffer,
|
||||
seq_lens=self._prefill_metadata.chunked_context.seq_lens[chunk_idx],
|
||||
max_q_len=self._prefill_metadata.max_query_len,
|
||||
max_kv_len=self._prefill_metadata.chunked_context.max_seq_lens[chunk_idx],
|
||||
bmm1_scale=self.scale,
|
||||
bmm2_scale=1.0,
|
||||
o_sf_scale=1.0,
|
||||
batch_size=self._prefill_metadata.chunked_context.seq_lens[chunk_idx].shape[
|
||||
0
|
||||
],
|
||||
window_left=-1,
|
||||
cum_seq_lens_q=self._prefill_metadata.query_start_loc,
|
||||
cum_seq_lens_kv=self._prefill_metadata.chunked_context.cu_seq_lens[
|
||||
chunk_idx
|
||||
],
|
||||
enable_pdl=False,
|
||||
is_causal=False,
|
||||
return_lse=True,
|
||||
out=out,
|
||||
)
|
||||
|
||||
# Convert from (q_len, num_heads) to (num_heads, q_len)
|
||||
return attn_out, lse.transpose(0, 1).contiguous()
|
||||
@@ -123,18 +123,6 @@ class TritonMLAImpl(MLACommonImpl[MLACommonMetadata]):
|
||||
|
||||
self._sm_count = current_platform.num_compute_units()
|
||||
|
||||
def _flash_attn_varlen_diff_headdims(
|
||||
self, q, k, v, return_softmax_lse=False, softmax_scale=None, **kwargs
|
||||
):
|
||||
return super()._flash_attn_varlen_diff_headdims(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
return_softmax_lse=return_softmax_lse,
|
||||
softmax_scale=softmax_scale,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
|
||||
Reference in New Issue
Block a user