[ROCm][CI] Add attention-sink support to ROCm AITER sparse MLA (#54404)
Signed-off-by: Andreas Karatzas <Andreas.Karatzas@amd.com> Signed-off-by: Andreas Karatzas <akaratza@amd.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
OpenAI Codex
parent
392db567b2
commit
e476556189
@@ -624,6 +624,110 @@ def _rocm_aiter_mla_decode_fwd_impl(
|
||||
)
|
||||
|
||||
|
||||
def _rocm_aiter_mla_decode_fwd_lse_impl(
|
||||
q: torch.Tensor,
|
||||
kv_buffer: torch.Tensor,
|
||||
o: torch.Tensor,
|
||||
qo_indptr: torch.Tensor,
|
||||
max_seqlen_qo: int,
|
||||
kv_indptr: torch.Tensor | None = None,
|
||||
kv_indices: torch.Tensor | None = None,
|
||||
kv_last_page_lens: torch.Tensor | None = None,
|
||||
sm_scale: float = 1.0,
|
||||
logit_cap: float = 0.0,
|
||||
q_scale: torch.Tensor | None = None,
|
||||
kv_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Run non-persistent AITER MLA decode and return natural-log LSE.
|
||||
|
||||
gfx942 persistent MLA kernels do not provide an LSE code object. Keeping
|
||||
this as a separate op makes that constraint structural: callers that need
|
||||
LSE cannot accidentally forward persistent work metadata.
|
||||
"""
|
||||
from aiter.mla import get_meta_param, mla_decode_fwd
|
||||
|
||||
kwargs: dict[str, float | int | torch.Tensor | None | bool] = {
|
||||
"sm_scale": sm_scale,
|
||||
"logit_cap": logit_cap,
|
||||
"return_lse": True,
|
||||
}
|
||||
if _check_aiter_mla_fp8_support():
|
||||
kwargs["q_scale"] = q_scale
|
||||
kwargs["kv_scale"] = kv_scale
|
||||
|
||||
if (
|
||||
q.dtype == torch.bfloat16
|
||||
and kv_buffer.dtype == torch.bfloat16
|
||||
and q.shape[1] == 32
|
||||
):
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
if on_gfx950():
|
||||
# The gfx950 H32 BF16 kernel mishandles ragged tails with split KV.
|
||||
# Its single-split path returns correct output and natural-log LSE.
|
||||
kwargs["num_kv_splits"] = 1
|
||||
kwargs["num_kv_splits_indptr"] = torch.arange(
|
||||
qo_indptr.shape[0], dtype=torch.int32, device=q.device
|
||||
)
|
||||
|
||||
if q.dtype == FP8_DTYPE:
|
||||
assert kv_indices is not None
|
||||
num_kv_splits, num_kv_splits_indptr = get_meta_param(
|
||||
None,
|
||||
qo_indptr.shape[0] - 1,
|
||||
kv_indices.numel(),
|
||||
q.shape[1],
|
||||
max_seqlen_qo,
|
||||
q.dtype,
|
||||
)
|
||||
if num_kv_splits == 1:
|
||||
# gfx942's one-split FP8 asm writes the final output directly but
|
||||
# does not write either LSE buffer. Force the normal split reducer,
|
||||
# which produces both the same output and an accurate natural LSE.
|
||||
num_kv_splits = 2
|
||||
num_kv_splits_indptr = torch.arange(
|
||||
0,
|
||||
(qo_indptr.shape[0]) * num_kv_splits,
|
||||
num_kv_splits,
|
||||
dtype=torch.int32,
|
||||
device=q.device,
|
||||
)
|
||||
kwargs["num_kv_splits"] = num_kv_splits
|
||||
kwargs["num_kv_splits_indptr"] = num_kv_splits_indptr
|
||||
|
||||
_, final_lse = mla_decode_fwd(
|
||||
q,
|
||||
kv_buffer.view(-1, 1, 1, q.shape[-1]),
|
||||
o,
|
||||
qo_indptr,
|
||||
kv_indptr,
|
||||
kv_indices,
|
||||
kv_last_page_lens,
|
||||
max_seqlen_qo,
|
||||
**kwargs,
|
||||
)
|
||||
if final_lse is None:
|
||||
raise RuntimeError("AITER MLA decode did not return the requested LSE")
|
||||
return final_lse
|
||||
|
||||
|
||||
def _rocm_aiter_mla_decode_fwd_lse_fake(
|
||||
q: torch.Tensor,
|
||||
kv_buffer: torch.Tensor,
|
||||
o: torch.Tensor,
|
||||
qo_indptr: torch.Tensor,
|
||||
max_seqlen_qo: int,
|
||||
kv_indptr: torch.Tensor | None = None,
|
||||
kv_indices: torch.Tensor | None = None,
|
||||
kv_last_page_lens: torch.Tensor | None = None,
|
||||
sm_scale: float = 1.0,
|
||||
logit_cap: float = 0.0,
|
||||
q_scale: torch.Tensor | None = None,
|
||||
kv_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty(q.shape[:-1], dtype=torch.float32, device=q.device)
|
||||
|
||||
|
||||
def _rocm_aiter_w8a8_gemm_impl(
|
||||
A: torch.Tensor,
|
||||
B: torch.Tensor,
|
||||
@@ -2170,6 +2274,13 @@ class rocm_aiter_ops:
|
||||
mutates_args=["o"],
|
||||
)
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="rocm_aiter_mla_decode_fwd_lse",
|
||||
op_func=_rocm_aiter_mla_decode_fwd_lse_impl,
|
||||
mutates_args=["o"],
|
||||
fake_impl=_rocm_aiter_mla_decode_fwd_lse_fake,
|
||||
)
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="rocm_aiter_w8a8_gemm",
|
||||
op_func=_rocm_aiter_w8a8_gemm_impl,
|
||||
@@ -2756,6 +2867,37 @@ class rocm_aiter_ops:
|
||||
reduce_partial_map=reduce_partial_map,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def mla_decode_fwd_lse(
|
||||
q: torch.Tensor,
|
||||
kv_buffer: torch.Tensor,
|
||||
o: torch.Tensor,
|
||||
sm_scale: float,
|
||||
qo_indptr: torch.Tensor,
|
||||
max_seqlen_qo: int,
|
||||
kv_indptr: torch.Tensor | None = None,
|
||||
kv_indices: torch.Tensor | None = None,
|
||||
kv_last_page_lens: torch.Tensor | None = None,
|
||||
logit_cap: float = 0.0,
|
||||
q_scale: torch.Tensor | None = None,
|
||||
kv_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Run MLA decode without persistent metadata and return its LSE."""
|
||||
return torch.ops.vllm.rocm_aiter_mla_decode_fwd_lse(
|
||||
q,
|
||||
kv_buffer.view(-1, 1, 1, q.shape[-1]),
|
||||
o,
|
||||
qo_indptr,
|
||||
max_seqlen_qo,
|
||||
kv_indptr,
|
||||
kv_indices,
|
||||
kv_last_page_lens,
|
||||
sm_scale=sm_scale,
|
||||
logit_cap=logit_cap,
|
||||
q_scale=q_scale,
|
||||
kv_scale=kv_scale,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def per_tensor_quant(
|
||||
x: torch.Tensor,
|
||||
|
||||
@@ -226,6 +226,13 @@ class AttentionBackend(ABC):
|
||||
except NotImplementedError:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def supports_dcp(cls) -> bool:
|
||||
try:
|
||||
return cls.get_impl_cls().supports_dcp
|
||||
except NotImplementedError:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def supports_non_causal_dcp(cls) -> bool:
|
||||
builder_cls = cls.get_builder_cls()
|
||||
@@ -324,6 +331,8 @@ class AttentionBackend(ABC):
|
||||
invalid_reasons.append("KV connector not supported")
|
||||
if use_pcp and not cls.supports_pcp():
|
||||
invalid_reasons.append("PCP not supported")
|
||||
if use_dcp and not cls.supports_dcp():
|
||||
invalid_reasons.append("DCP not supported")
|
||||
if (
|
||||
use_adaptive_verification
|
||||
and not cls.supports_device_cpu_query_lens_mismatch()
|
||||
|
||||
@@ -35,7 +35,7 @@ from vllm.v1.attention.backends.utils import split_decodes_and_prefills
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
rocm_sparse_attn_prefill,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -350,6 +350,17 @@ class ROCMAiterMLASparseBackend(AttentionBackend):
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
|
||||
# Global index conversion assumes contiguous pages within each layer.
|
||||
return (KVCacheLayout.LBNHC, KVCacheLayout.LBHNC)
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
from vllm.platforms.rocm import on_mi3xx
|
||||
|
||||
return on_mi3xx()
|
||||
|
||||
|
||||
@dataclass
|
||||
class ROCMAiterMLASparseMetadata(AttentionMetadata):
|
||||
@@ -418,6 +429,14 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
self.num_heads = self.model_config.get_num_attention_heads(parallel_config)
|
||||
self.mla_dims = get_mla_dims(self.model_config)
|
||||
self.topk_tokens = vllm_config.model_config.hf_config.index_topk
|
||||
attention_context = vllm_config.compilation_config.static_forward_context
|
||||
# Sink decode must use AITER's nonpersistent path. In particular,
|
||||
# gfx942 has no persistent+LSE kernel, and its metadata heuristic
|
||||
# terminates for HY-V4's TP1 H64 shape.
|
||||
self._use_persistent_metadata = all(
|
||||
getattr(attention_context[name].impl, "sinks", None) is None
|
||||
for name in layer_names
|
||||
)
|
||||
# Bounds the KV-split heuristic (see `_sparse_decode_max_split`).
|
||||
self._num_compute_units = current_platform.num_compute_units()
|
||||
self.max_model_len_tensor = torch.tensor(
|
||||
@@ -591,14 +610,13 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
paged_kv_indices = self.paged_kv_indices[: num_tokens * self.topk_tokens]
|
||||
|
||||
# ----- Compute persistent MLA metadata -----
|
||||
# The aiter sparse decode kernel uses qseqlen=1 (each query token is
|
||||
# treated as its own batch entry), so persistent metadata can always
|
||||
# be precomputed here. The kernel switches to the persistent
|
||||
# work-stealing path automatically when work_meta_data is non-None.
|
||||
# The output is a deterministic function of the per-request query and
|
||||
# context lengths (both clamped to topk_tokens, past which per-token KV
|
||||
# length saturates) and num_heads; fingerprint those CPU-side and skip
|
||||
# the launch when nothing changed.
|
||||
# The AITER sparse decode kernel uses qseqlen=1 (each query token is
|
||||
# treated as its own batch entry). Build its persistent work metadata
|
||||
# only when AITER is selected and no layer needs the nonpersistent LSE
|
||||
# path for attention sinks. The output is a deterministic function of
|
||||
# the per-request query and context lengths (both clamped to
|
||||
# topk_tokens, past which per-token KV length saturates) and num_heads;
|
||||
# fingerprint those CPU-side and skip the launch when nothing changed.
|
||||
head_size = self.mla_dims.kv_lora_rank + self.mla_dims.qk_rope_head_dim
|
||||
use_triton_sparse = _use_rocm_sparse_triton(
|
||||
kv_cache_dtype=self.kv_cache_dtype,
|
||||
@@ -615,7 +633,7 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
reduce_indptr = None
|
||||
reduce_final_map = None
|
||||
reduce_partial_map = None
|
||||
if not use_triton_sparse:
|
||||
if self._use_persistent_metadata and not use_triton_sparse:
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
clamped_seq_lens = np.minimum(
|
||||
common_attn_metadata.seq_lens_cpu[:num_reqs].numpy(),
|
||||
@@ -729,6 +747,7 @@ def reference_mla_sparse_prefill(
|
||||
class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
is_sparse = True
|
||||
supports_dense_mha_prefill = False
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -753,6 +772,20 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
self.head_size = head_size
|
||||
self.scale = float(scale)
|
||||
self.num_kv_heads = num_kv_heads
|
||||
sinks = mla_args.pop("sinks", None)
|
||||
if sinks is not None:
|
||||
if sinks.dtype != torch.float32:
|
||||
raise ValueError(
|
||||
f"ROCm AITER MLA sinks must be float32, got {sinks.dtype}"
|
||||
)
|
||||
if sinks.ndim != 1 or sinks.numel() != num_heads:
|
||||
raise ValueError(
|
||||
"ROCm AITER MLA sinks must have shape "
|
||||
f"({num_heads},), got {tuple(sinks.shape)}"
|
||||
)
|
||||
if not sinks.is_contiguous():
|
||||
raise ValueError("ROCm AITER MLA sinks must be contiguous")
|
||||
self.sinks: torch.Tensor | None = sinks
|
||||
self.kv_cache_dtype = kv_cache_dtype
|
||||
self.kv_lora_rank: int = mla_args["kv_lora_rank"]
|
||||
self.softmax_scale = scale
|
||||
@@ -776,16 +809,31 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
q: torch.Tensor, # [sq, heads, d_qk]
|
||||
kv_c_and_k_pe_cache: torch.Tensor, # [blocks, heads, d_qk]
|
||||
attn_metadata: ROCMAiterMLASparseMetadata,
|
||||
) -> torch.Tensor:
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
num_tokens = q.shape[0]
|
||||
mla_num_heads = AiterMLAHelper.get_actual_mla_num_heads(self.num_heads)
|
||||
output = torch.empty(
|
||||
[num_tokens, mla_num_heads, self.kv_lora_rank],
|
||||
dtype=attn_metadata.attn_out_dtype,
|
||||
device=q.device,
|
||||
base_mla_num_heads = AiterMLAHelper.get_actual_mla_num_heads(self.num_heads)
|
||||
mla_num_heads = base_mla_num_heads
|
||||
need_lse = self.sinks is not None
|
||||
from vllm.platforms.rocm import on_gfx942
|
||||
|
||||
# Keep sink attention available for dtypes/head shapes without an
|
||||
# AITER return-LSE kernel. Sink layers never need persistent metadata.
|
||||
triton_sink_fallback = (
|
||||
need_lse
|
||||
and q.dtype == kv_c_and_k_pe_cache.dtype
|
||||
and (
|
||||
q.dtype == torch.float16
|
||||
or (
|
||||
q.dtype == torch.bfloat16
|
||||
and (
|
||||
mla_num_heads > 128
|
||||
or (on_gfx942() and 32 < mla_num_heads <= 64)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if _use_rocm_sparse_triton(
|
||||
if triton_sink_fallback or _use_rocm_sparse_triton(
|
||||
kv_cache_dtype=self.kv_cache_dtype,
|
||||
head_size=q.shape[-1],
|
||||
kv_lora_rank=self.kv_lora_rank,
|
||||
@@ -794,6 +842,18 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
num_decode_tokens=attn_metadata.num_decode_tokens,
|
||||
max_query_len=attn_metadata.max_query_len,
|
||||
):
|
||||
output = torch.empty(
|
||||
[num_tokens, q.shape[1], self.kv_lora_rank],
|
||||
dtype=attn_metadata.attn_out_dtype,
|
||||
device=q.device,
|
||||
)
|
||||
triton_sinks = None
|
||||
if self.sinks is not None:
|
||||
triton_sinks = AiterMLAHelper.get_mla_padded_q(
|
||||
self.num_heads,
|
||||
self.sinks.reshape(1, self.num_heads, 1),
|
||||
q.shape[1],
|
||||
).reshape(-1)
|
||||
rocm_sparse_attn_prefill(
|
||||
q=q,
|
||||
kv=kv_c_and_k_pe_cache.view(-1, 1, q.shape[-1]),
|
||||
@@ -803,44 +863,149 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
head_dim=q.shape[-1],
|
||||
nope_head_dim=self.kv_lora_rank,
|
||||
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
|
||||
attn_sink=None,
|
||||
attn_sink=triton_sinks,
|
||||
output=output,
|
||||
ragged_indices=attn_metadata.paged_kv_indices,
|
||||
ragged_indptr=attn_metadata.paged_kv_indptr,
|
||||
)
|
||||
return AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
|
||||
output = AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
|
||||
return output, None
|
||||
|
||||
# Build kwargs and forward the persistent MLA metadata when it has
|
||||
# been computed. The aiter mla_decode_fwd switches to its
|
||||
# work-stealing persistent kernel path when work_meta_data is given.
|
||||
mla_kwargs: dict = dict(
|
||||
q_scale=layer._q_scale,
|
||||
kv_scale=layer._k_scale,
|
||||
# AITER's nonpersistent return-LSE dispatch has discrete head kernels.
|
||||
supported_head_buckets: tuple[int, ...] | None = None
|
||||
head_dtype_name = ""
|
||||
if need_lse:
|
||||
if (
|
||||
q.dtype == torch.bfloat16
|
||||
and kv_c_and_k_pe_cache.dtype == torch.bfloat16
|
||||
):
|
||||
supported_head_buckets = (16, 32, 64, 128)
|
||||
head_dtype_name = "BF16"
|
||||
elif (
|
||||
q.dtype == current_platform.fp8_dtype()
|
||||
and kv_c_and_k_pe_cache.dtype == current_platform.fp8_dtype()
|
||||
):
|
||||
supported_head_buckets = (16, 128)
|
||||
head_dtype_name = "FP8"
|
||||
else:
|
||||
raise ValueError(
|
||||
"ROCm AITER MLA attention sinks require query and KV to "
|
||||
"both use BF16 or both use FP8, got "
|
||||
f"query={q.dtype}, KV={kv_c_and_k_pe_cache.dtype}"
|
||||
)
|
||||
|
||||
if supported_head_buckets is not None:
|
||||
from vllm.platforms.rocm import on_mi3xx
|
||||
|
||||
if on_mi3xx():
|
||||
supported_heads = next(
|
||||
(
|
||||
heads
|
||||
for heads in supported_head_buckets
|
||||
if heads >= mla_num_heads
|
||||
),
|
||||
None,
|
||||
)
|
||||
if supported_heads is None:
|
||||
raise ValueError(
|
||||
"ROCm AITER MLA attention sinks support at most 128 "
|
||||
f"padded local {head_dtype_name} heads; increase "
|
||||
"tensor_parallel_size"
|
||||
)
|
||||
if supported_heads != mla_num_heads:
|
||||
q = AiterMLAHelper.get_mla_padded_q(
|
||||
mla_num_heads, q, supported_heads
|
||||
)
|
||||
mla_num_heads = supported_heads
|
||||
output = torch.empty(
|
||||
[num_tokens, mla_num_heads, self.kv_lora_rank],
|
||||
dtype=attn_metadata.attn_out_dtype,
|
||||
device=q.device,
|
||||
)
|
||||
if attn_metadata.work_meta_data is not None:
|
||||
mla_kwargs.update(
|
||||
work_meta_data=attn_metadata.work_meta_data,
|
||||
work_indptr=attn_metadata.work_indptr,
|
||||
work_info_set=attn_metadata.work_info_set,
|
||||
reduce_indptr=attn_metadata.reduce_indptr,
|
||||
reduce_final_map=attn_metadata.reduce_final_map,
|
||||
reduce_partial_map=attn_metadata.reduce_partial_map,
|
||||
|
||||
if need_lse:
|
||||
# gfx942 has no persistent MLA code object that writes final LSE.
|
||||
# The split-KV path consumes the same ragged indices and is exact.
|
||||
lse = rocm_aiter_ops.mla_decode_fwd_lse(
|
||||
q,
|
||||
kv_c_and_k_pe_cache,
|
||||
output,
|
||||
self.scale,
|
||||
attn_metadata.qo_indptr,
|
||||
1,
|
||||
attn_metadata.paged_kv_indptr,
|
||||
attn_metadata.paged_kv_indices,
|
||||
attn_metadata.paged_kv_last_page_len,
|
||||
q_scale=layer._q_scale,
|
||||
kv_scale=layer._k_scale,
|
||||
)
|
||||
else:
|
||||
# Preserve the persistent work-stealing fast path for models that
|
||||
# do not use sinks.
|
||||
mla_kwargs: dict = dict(
|
||||
q_scale=layer._q_scale,
|
||||
kv_scale=layer._k_scale,
|
||||
)
|
||||
if attn_metadata.work_meta_data is not None:
|
||||
mla_kwargs.update(
|
||||
work_meta_data=attn_metadata.work_meta_data,
|
||||
work_indptr=attn_metadata.work_indptr,
|
||||
work_info_set=attn_metadata.work_info_set,
|
||||
reduce_indptr=attn_metadata.reduce_indptr,
|
||||
reduce_final_map=attn_metadata.reduce_final_map,
|
||||
reduce_partial_map=attn_metadata.reduce_partial_map,
|
||||
)
|
||||
|
||||
rocm_aiter_ops.mla_decode_fwd(
|
||||
q,
|
||||
kv_c_and_k_pe_cache,
|
||||
output,
|
||||
self.scale,
|
||||
attn_metadata.qo_indptr,
|
||||
1,
|
||||
attn_metadata.paged_kv_indptr,
|
||||
attn_metadata.paged_kv_indices,
|
||||
attn_metadata.paged_kv_last_page_len,
|
||||
**mla_kwargs,
|
||||
)
|
||||
rocm_aiter_ops.mla_decode_fwd(
|
||||
q,
|
||||
kv_c_and_k_pe_cache,
|
||||
output,
|
||||
self.scale,
|
||||
attn_metadata.qo_indptr,
|
||||
1,
|
||||
attn_metadata.paged_kv_indptr,
|
||||
attn_metadata.paged_kv_indices,
|
||||
attn_metadata.paged_kv_last_page_len,
|
||||
**mla_kwargs,
|
||||
)
|
||||
lse = None
|
||||
|
||||
return AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
|
||||
if mla_num_heads != base_mla_num_heads:
|
||||
if mla_num_heads % base_mla_num_heads == 0:
|
||||
head_stride = mla_num_heads // base_mla_num_heads
|
||||
output = output[:, ::head_stride]
|
||||
if lse is not None:
|
||||
lse = lse[:, ::head_stride]
|
||||
else:
|
||||
output = output[:, :base_mla_num_heads]
|
||||
if lse is not None:
|
||||
lse = lse[:, :base_mla_num_heads]
|
||||
|
||||
output = AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
|
||||
if lse is not None:
|
||||
lse = AiterMLAHelper.get_mla_unpadded_o(
|
||||
self.num_heads, lse.unsqueeze(-1)
|
||||
).squeeze(-1)
|
||||
|
||||
if self.sinks is not None:
|
||||
assert lse is not None
|
||||
# Empty ragged rows have only sink mass and no value contribution.
|
||||
# AITER can return NaN output/LSE for those rows; do not multiply it
|
||||
# by a zero normalization factor and propagate the NaN.
|
||||
has_keys = (
|
||||
attn_metadata.paged_kv_indptr[1:] > attn_metadata.paged_kv_indptr[:-1]
|
||||
).unsqueeze(-1)
|
||||
lse = torch.where(has_keys, lse, float("-inf"))
|
||||
sink_lse = torch.logaddexp(lse, self.sinks)
|
||||
sink_scale = torch.exp(lse - sink_lse)
|
||||
output = torch.where(
|
||||
has_keys.unsqueeze(-1),
|
||||
output.float() * sink_scale.unsqueeze(-1),
|
||||
0.0,
|
||||
).to(output.dtype)
|
||||
lse = sink_lse
|
||||
|
||||
return output, lse
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
@@ -863,6 +1028,8 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
q = self.q_concat_buffer[: ql_nope.shape[0]]
|
||||
if q_pe.shape[-1] == 0:
|
||||
q.copy_(ql_nope)
|
||||
elif q.dtype == torch.float16:
|
||||
torch.cat((ql_nope, q_pe), dim=-1, out=q)
|
||||
else:
|
||||
ops.concat_mla_q(ql_nope, q_pe, q)
|
||||
|
||||
@@ -892,7 +1059,6 @@ class ROCMAiterMLASparseImpl(MLAAttentionImpl[ROCMAiterMLASparseMetadata]):
|
||||
q, _ = ops.scaled_fp8_quant(q.view(q.shape[0], -1), layer._q_scale)
|
||||
q = q.view(original_q_shape)
|
||||
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self.num_heads, q)
|
||||
attn_out = self._forward_mla(
|
||||
return self._forward_mla(
|
||||
layer, mla_padded_q, kv_c_and_k_pe_cache, attn_metadata
|
||||
)
|
||||
return attn_out, None
|
||||
|
||||
@@ -2610,7 +2610,7 @@ def _rocm_sparse_attn_prefill_ragged_triton(
|
||||
block_d = triton.next_power_of_2(head_dim)
|
||||
block_k = 16 if head_dim >= 256 else 32
|
||||
num_warps = 4
|
||||
out = torch.empty_like(q, dtype=torch.bfloat16)
|
||||
out = torch.empty_like(q)
|
||||
_sparse_attn_prefill_ragged_kernel[(num_queries, triton.cdiv(num_heads, block_h))](
|
||||
q,
|
||||
kv,
|
||||
@@ -3195,7 +3195,7 @@ def rocm_sparse_attn_prefill(
|
||||
rope_head_dim=rope_head_dim,
|
||||
topk_length=topk_length,
|
||||
)
|
||||
output.copy_(output_chunk.to(output.dtype))
|
||||
output.copy_(output_chunk[..., : output.shape[-1]].to(output.dtype))
|
||||
|
||||
|
||||
def rocm_sparse_attn_decode(
|
||||
|
||||
Reference in New Issue
Block a user