feat: MLA prefill enable FA4 fp8 output (#43050)
Signed-off-by: Carl You <4531192+carlyou@users.noreply.github.com>
This commit is contained in:
@@ -687,7 +687,23 @@ class MLAAttention(nn.Module, AttentionLayerBase):
|
||||
num_mqa_tokens = attn_metadata.num_decode_tokens
|
||||
num_mha_tokens = q.size(0) - num_mqa_tokens
|
||||
|
||||
mha_use_quant_output = (
|
||||
quant_key is not None
|
||||
and self.prefill_backend.supports_quant_output(quant_key)
|
||||
and attn_metadata is not None
|
||||
and attn_metadata.prefill is not None
|
||||
and attn_metadata.prefill.chunked_context is None
|
||||
and self.impl.dcp_world_size <= 1
|
||||
)
|
||||
|
||||
if num_mha_tokens > 0:
|
||||
if mha_use_quant_output:
|
||||
mha_output = quant_output
|
||||
mha_output_scale = output_scale
|
||||
else:
|
||||
mha_output = output
|
||||
mha_output_scale = None
|
||||
|
||||
self.impl.forward_mha( # type: ignore[attr-defined]
|
||||
q[num_mqa_tokens:],
|
||||
k_c_normed[num_mqa_tokens:],
|
||||
@@ -695,7 +711,8 @@ class MLAAttention(nn.Module, AttentionLayerBase):
|
||||
kv_cache,
|
||||
attn_metadata,
|
||||
self._k_scale,
|
||||
output=output[num_mqa_tokens:],
|
||||
output=mha_output[num_mqa_tokens:num_actual_toks],
|
||||
output_scale=mha_output_scale,
|
||||
)
|
||||
|
||||
if num_mqa_tokens > 0:
|
||||
@@ -794,13 +811,15 @@ class MLAAttention(nn.Module, AttentionLayerBase):
|
||||
self._v_up_proj(attn_out, out=mqa_output_slice)
|
||||
|
||||
if quant_key is not None:
|
||||
# Quantize the BF16 computation result into the quantized output
|
||||
actual = output[:num_actual_toks]
|
||||
quant_idx = num_mqa_tokens if mha_use_quant_output else num_actual_toks
|
||||
if quant_idx == 0:
|
||||
return quant_output
|
||||
actual = output[:quant_idx]
|
||||
if quant_key == kNvfp4Dynamic:
|
||||
# NVFP4: two FP4 values packed into one uint8
|
||||
assert output_block_scale is not None
|
||||
fp4_data, fp4_scales = ops.scaled_fp4_quant(actual, output_scale)
|
||||
quant_output[:num_actual_toks].copy_(fp4_data)
|
||||
quant_output[:quant_idx].copy_(fp4_data)
|
||||
output_block_scale[: fp4_scales.shape[0]].copy_(fp4_scales)
|
||||
elif quant_key in (kFp8Dynamic128Sym, kFp8Dynamic64Sym):
|
||||
# Per-group FP8
|
||||
@@ -812,8 +831,8 @@ class MLAAttention(nn.Module, AttentionLayerBase):
|
||||
finfo = torch.finfo(_FP8_DTYPE)
|
||||
torch.ops._C.per_token_group_fp8_quant(
|
||||
actual,
|
||||
quant_output[:num_actual_toks],
|
||||
output_block_scale[:num_actual_toks],
|
||||
quant_output[:quant_idx],
|
||||
output_block_scale[:quant_idx],
|
||||
quant_group_size,
|
||||
1e-10, # eps
|
||||
finfo.min,
|
||||
@@ -825,7 +844,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
|
||||
elif quant_key == kFp8StaticTensorSym:
|
||||
# Static FP8 quantization
|
||||
fp8_data, _ = self._quant_fp8_op(actual, output_scale)
|
||||
quant_output[:num_actual_toks].copy_(fp8_data)
|
||||
quant_output[:quant_idx].copy_(fp8_data)
|
||||
else:
|
||||
raise ValueError(f"Unsupported quant_key: {quant_key}")
|
||||
return quant_output
|
||||
@@ -2254,6 +2273,7 @@ class MLACommonImpl(MLAAttentionImpl[M], Generic[M]):
|
||||
attn_metadata: MLACommonMetadata,
|
||||
k_scale: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
assert attn_metadata.prefill is not None
|
||||
assert self.dcp_world_size != -1
|
||||
@@ -2267,6 +2287,9 @@ class MLACommonImpl(MLAAttentionImpl[M], Generic[M]):
|
||||
q = q.to(prefill_metadata.q_data_type)
|
||||
|
||||
has_context = prefill_metadata.chunked_context is not None
|
||||
assert output_scale is None or not has_context, (
|
||||
"Fused FP8 output is only wired for the non-chunked-context path"
|
||||
)
|
||||
|
||||
kv_nope = self.kv_b_proj(kv_c_normed)[0].view(
|
||||
-1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim
|
||||
@@ -2283,6 +2306,12 @@ class MLACommonImpl(MLAAttentionImpl[M], Generic[M]):
|
||||
k=k,
|
||||
v=v,
|
||||
return_softmax_lse=has_context,
|
||||
out=(
|
||||
output.view(-1, self.num_heads, self.v_head_dim)
|
||||
if output_scale is not None
|
||||
else None
|
||||
),
|
||||
output_scale=output_scale,
|
||||
)
|
||||
|
||||
if has_context:
|
||||
@@ -2312,7 +2341,8 @@ class MLACommonImpl(MLAAttentionImpl[M], Generic[M]):
|
||||
suffix_lse=suffix_lse,
|
||||
prefill_tokens_with_context=prefill_metadata.chunked_context.prefill_tokens_with_context,
|
||||
)
|
||||
else:
|
||||
elif output_scale is None:
|
||||
# With output_scale set, backend already wrote into `output` in place.
|
||||
assert isinstance(output_prefill, torch.Tensor)
|
||||
output_prefill = output_prefill.flatten(start_dim=-2)
|
||||
output.copy_(output_prefill)
|
||||
|
||||
@@ -899,6 +899,7 @@ class MLAAttentionImpl(AttentionImplBase[T], Generic[T]):
|
||||
attn_metadata: T,
|
||||
k_scale: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""MHA-style prefill forward pass."""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -12,6 +12,7 @@ if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonPrefillMetadata,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.mla.prefill.selector import (
|
||||
MLAPrefillSelectorConfig,
|
||||
@@ -44,6 +45,12 @@ class MLAPrefillBackend(ABC):
|
||||
def is_available(cls) -> bool:
|
||||
return True
|
||||
|
||||
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
|
||||
"""Whether `run_prefill_new_tokens` can write quantized output
|
||||
directly (fused) for the given quant key, skipping the post-quant
|
||||
pass. Overridden by backends that support it."""
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def validate_configuration(
|
||||
cls,
|
||||
@@ -107,6 +114,8 @@ class MLAPrefillBackend(ABC):
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
out: torch.Tensor | None = None,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ from typing import TYPE_CHECKING
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.fa_utils import (
|
||||
get_flash_attn_version,
|
||||
@@ -17,6 +20,7 @@ from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
|
||||
|
||||
if is_flash_attn_varlen_func_available():
|
||||
from vllm.v1.attention.backends.fa_utils import flash_attn_varlen_func
|
||||
@@ -87,6 +91,16 @@ 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()
|
||||
|
||||
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
|
||||
device_capability = current_platform.get_device_capability()
|
||||
return (
|
||||
self.vllm_flash_attn_version == 4
|
||||
and self._is_vllm_fa
|
||||
and device_capability is not None
|
||||
and device_capability[0] in (10, 11)
|
||||
and quant_key == kFp8StaticTensorSym
|
||||
)
|
||||
|
||||
def _flash_attn_varlen_diff_headdims(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
@@ -94,6 +108,8 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool = False,
|
||||
softmax_scale: float | None = None,
|
||||
out: torch.Tensor | None = None,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
maybe_padded_v = v
|
||||
@@ -104,10 +120,13 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
if self._is_vllm_fa:
|
||||
kwargs["return_softmax_lse"] = return_softmax_lse
|
||||
kwargs["out"] = out
|
||||
kwargs["output_scale"] = output_scale
|
||||
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
|
||||
assert out is None and output_scale is None
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
kwargs["num_splits"] = 1
|
||||
|
||||
@@ -140,6 +159,8 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
out: torch.Tensor | None = None,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
return self._flash_attn_varlen_diff_headdims(
|
||||
q=q,
|
||||
@@ -152,6 +173,8 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
softmax_scale=self.scale,
|
||||
causal=True,
|
||||
return_softmax_lse=return_softmax_lse,
|
||||
out=out,
|
||||
output_scale=output_scale,
|
||||
)
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
|
||||
@@ -188,6 +188,8 @@ class FlashInferPrefillBackend(MLAPrefillBackend):
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
out: torch.Tensor | None = None,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
assert self._prefill_main is not None
|
||||
|
||||
|
||||
@@ -115,6 +115,8 @@ class TokenspeedMLAPrefillBackend(MLAPrefillBackend):
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
out: torch.Tensor | None = None,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
from tokenspeed_mla import tokenspeed_mla_prefill
|
||||
|
||||
|
||||
@@ -83,6 +83,8 @@ class TrtllmRaggedPrefillBackend(MLAPrefillBackend):
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
return_softmax_lse: bool,
|
||||
out: torch.Tensor | None = None,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
from flashinfer.prefill import trtllm_ragged_attention_deepseek
|
||||
|
||||
|
||||
@@ -841,6 +841,7 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
attn_metadata: MLACommonMetadata,
|
||||
k_scale: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Dispatch prefill to the FP8 ASM kernel when available.
|
||||
|
||||
@@ -866,6 +867,7 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
attn_metadata,
|
||||
k_scale,
|
||||
output,
|
||||
output_scale,
|
||||
)
|
||||
|
||||
assert attn_metadata.prefill is not None
|
||||
@@ -881,8 +883,13 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
attn_metadata,
|
||||
k_scale,
|
||||
output,
|
||||
output_scale,
|
||||
)
|
||||
|
||||
assert output_scale is None, (
|
||||
"fused FP8 output not supported by the AITER FP8 MLA prefill path"
|
||||
)
|
||||
|
||||
kv_nope = self.kv_b_proj(kv_c_normed)[0].view(
|
||||
-1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim
|
||||
)
|
||||
|
||||
@@ -200,6 +200,8 @@ def flash_attn_varlen_func(
|
||||
k_descale=None,
|
||||
v_descale=None,
|
||||
num_splits: int = 0,
|
||||
# FA4 Only
|
||||
output_scale=None,
|
||||
# Version selector
|
||||
fa_version: int = DEFAULT_FA_VERSION,
|
||||
s_aux=None,
|
||||
@@ -273,6 +275,11 @@ def flash_attn_varlen_func(
|
||||
"seqused_k must be provided if block_table is provided"
|
||||
)
|
||||
|
||||
assert output_scale is None or fa_version == 4, (
|
||||
f"Fused FP8 output (output_scale) is only supported by FA4, "
|
||||
f"got fa_version={fa_version}"
|
||||
)
|
||||
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** (-0.5)
|
||||
# custom op does not support non-tuple input
|
||||
@@ -403,6 +410,7 @@ def flash_attn_varlen_func(
|
||||
learnable_sink=s_aux,
|
||||
mask_mod=mask_mod,
|
||||
aux_tensors=aux_tensors,
|
||||
output_scale=output_scale,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unsupported FA version: {fa_version}")
|
||||
|
||||
Reference in New Issue
Block a user