[ROCm][DSA] Enable AITER fused FP8 indexer writer (#40710)
Co-authored-by: Thomas Wang <thomawan@amd.com>
This commit is contained in:
co-authored by
Thomas Wang
parent
c3685dff42
commit
0dc8b29e15
@@ -0,0 +1,119 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""AITER fused FP8 DSA indexer writer (RoPE, K LayerNorm, quant, cache write)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
|
||||
SUPPORTED_HEAD_DIM = 128
|
||||
SUPPORTED_ROPE_DIM = 64
|
||||
SUPPORTED_QUANT_BLOCK_SIZE = 128
|
||||
|
||||
|
||||
def fused_fp8_writer_geometry_supported(
|
||||
head_dim: int, rope_dim: int, quant_block_size: int
|
||||
) -> bool:
|
||||
return (
|
||||
head_dim == SUPPORTED_HEAD_DIM
|
||||
and rope_dim == SUPPORTED_ROPE_DIM
|
||||
and quant_block_size == SUPPORTED_QUANT_BLOCK_SIZE
|
||||
)
|
||||
|
||||
|
||||
def aiter_fused_fp8_writer_available() -> bool:
|
||||
from sglang.srt.utils import is_gfx95_supported
|
||||
|
||||
# gfx950-only kernel. gfx942 may still import the Python symbol.
|
||||
if not is_gfx95_supported():
|
||||
return False
|
||||
try:
|
||||
from aiter.ops.cache import indexer_qk_rope_quant_and_cache # noqa: F401
|
||||
except (ImportError, AttributeError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def prepare_aiter_rope_caches(
|
||||
cos_cache: torch.Tensor,
|
||||
sin_cache: torch.Tensor,
|
||||
*,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
# AITER RotaryEmbedding stores CPU [max_pos, 1, 1, rotary_dim/2]; the fused
|
||||
# kernel wants device [max_pos, rotary_dim/2].
|
||||
def _prepare(table: torch.Tensor) -> torch.Tensor:
|
||||
prepared = table.squeeze()
|
||||
if prepared.dim() != 2:
|
||||
raise ValueError(
|
||||
"fused FP8 writer expects RoPE table [max_pos, rotary_dim/2], "
|
||||
f"got {tuple(table.shape)}"
|
||||
)
|
||||
return prepared.to(device=device, dtype=dtype).contiguous()
|
||||
|
||||
return _prepare(cos_cache), _prepare(sin_cache)
|
||||
|
||||
|
||||
def aiter_fused_fp8_qk_write(
|
||||
q: torch.Tensor,
|
||||
q_out: torch.Tensor,
|
||||
weights: torch.Tensor,
|
||||
weights_out: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
norm_bias: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_cache: torch.Tensor,
|
||||
sin_cache: torch.Tensor,
|
||||
epsilon: float,
|
||||
quant_block_size: int,
|
||||
scale_fmt: Optional[str],
|
||||
weights_scale: float,
|
||||
*,
|
||||
preshuffle: bool,
|
||||
is_neox: bool,
|
||||
compute_all_q_rope: bool,
|
||||
) -> None:
|
||||
if not fused_fp8_writer_geometry_supported(
|
||||
k.shape[-1], cos_cache.shape[-1] * 2, quant_block_size
|
||||
):
|
||||
raise ValueError(
|
||||
"fused FP8 writer requires "
|
||||
f"head_dim={SUPPORTED_HEAD_DIM}, rope_dim={SUPPORTED_ROPE_DIM}, "
|
||||
f"quant_block_size={SUPPORTED_QUANT_BLOCK_SIZE}; got "
|
||||
f"head_dim={k.shape[-1]}, rope_dim={cos_cache.shape[-1] * 2}, "
|
||||
f"quant_block_size={quant_block_size}"
|
||||
)
|
||||
if norm_weight.dtype != torch.float32 or norm_bias.dtype != torch.float32:
|
||||
raise TypeError(
|
||||
"fused FP8 writer reads LayerNorm parameters as fp32; got "
|
||||
f"{norm_weight.dtype} and {norm_bias.dtype}"
|
||||
)
|
||||
|
||||
from aiter.ops.cache import indexer_qk_rope_quant_and_cache
|
||||
|
||||
indexer_qk_rope_quant_and_cache(
|
||||
q,
|
||||
q_out,
|
||||
weights,
|
||||
weights_out,
|
||||
k,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
norm_weight,
|
||||
norm_bias,
|
||||
positions,
|
||||
cos_cache,
|
||||
sin_cache,
|
||||
epsilon,
|
||||
quant_block_size,
|
||||
scale_fmt,
|
||||
weights_scale,
|
||||
preshuffle=preshuffle,
|
||||
is_neox=is_neox,
|
||||
compute_all_q_rope=compute_all_q_rope,
|
||||
)
|
||||
@@ -1641,6 +1641,10 @@ class Envs:
|
||||
SGLANG_ENABLE_PCG_DSV2_DUAL_STREAM = EnvBool(False)
|
||||
SGLANG_DSA_TOPK_BROADCAST = EnvBool(False)
|
||||
SGLANG_DISABLE_DSA_INDEXER_FUSION = EnvBool(False)
|
||||
# HIP analog of CUDA SGLANG_DISABLE_DSA_INDEXER_FUSION (default on).
|
||||
# Set 1 for the legacy split writer. Omits Hadamard; pre-quant logits match.
|
||||
# Separate from the CUDA flag: that one also packs wk+weights_proj.
|
||||
SGLANG_DISABLE_AITER_FUSED_FP8_DSA_INDEXER = EnvBool(False)
|
||||
# Opt-in perf path for --dsa-prefill-backend flashmla_sparse_q8: fuse the
|
||||
# absorbed q bmm with the nope/rope concat + fp8 cast so q is written
|
||||
# directly in fp8 ("born fp8") and the standalone concat-cast kernel
|
||||
|
||||
@@ -8,6 +8,12 @@ import torch
|
||||
from einops import rearrange
|
||||
|
||||
from sglang.kernels.fused_op import BaseFusedOp
|
||||
from sglang.kernels.ops.attention.dsa.fp8_fused_writer_hip import (
|
||||
aiter_fused_fp8_qk_write,
|
||||
aiter_fused_fp8_writer_available,
|
||||
fused_fp8_writer_geometry_supported,
|
||||
prepare_aiter_rope_caches,
|
||||
)
|
||||
from sglang.kernels.ops.attention.fused_store_index_cache import (
|
||||
can_use_dsa_fused_store,
|
||||
fused_store_index_k_cache,
|
||||
@@ -70,6 +76,7 @@ from sglang.srt.utils import (
|
||||
from sglang.srt.utils.custom_op import register_custom_op
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_FUSED_FP8_WRITER_LOGGED = False
|
||||
|
||||
_is_cuda = is_cuda()
|
||||
_is_hip = is_hip()
|
||||
@@ -249,11 +256,31 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
self.index_topk = index_topk
|
||||
self.q_lora_rank = q_lora_rank
|
||||
self.layer_id = layer_id
|
||||
self.is_neox_style = is_neox_style
|
||||
self.block_size = block_size
|
||||
self.scale_fmt = scale_fmt
|
||||
self.use_dsa_indexer_fusion = (
|
||||
_is_cuda
|
||||
and not envs.SGLANG_DISABLE_DSA_INDEXER_FUSION.get()
|
||||
and not is_neox_style
|
||||
)
|
||||
index_k_uses_rmsnorm = (
|
||||
config is not None
|
||||
and getattr(config, "index_k_norm_type", "layer") == "rms"
|
||||
)
|
||||
aiter_fused_fp8_requested = (
|
||||
_is_hip
|
||||
and _use_aiter
|
||||
and not envs.SGLANG_DISABLE_AITER_FUSED_FP8_DSA_INDEXER.get()
|
||||
)
|
||||
self.use_aiter_fused_fp8_writer = (
|
||||
aiter_fused_fp8_requested
|
||||
and not index_k_uses_rmsnorm
|
||||
and fused_fp8_writer_geometry_supported(
|
||||
self.head_dim, self.rope_head_dim, self.block_size
|
||||
)
|
||||
and aiter_fused_fp8_writer_available()
|
||||
)
|
||||
self.alt_stream = alt_stream
|
||||
self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp()
|
||||
if self.dsa_enable_prefill_cp:
|
||||
@@ -301,14 +328,16 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
params_dtype=torch.bfloat16,
|
||||
prefix=add_prefix("weights_proj", prefix),
|
||||
)
|
||||
if (
|
||||
config is not None
|
||||
and getattr(config, "index_k_norm_type", "layer") == "rms"
|
||||
):
|
||||
if index_k_uses_rmsnorm:
|
||||
self.k_norm = RMSNorm(self.head_dim)
|
||||
else:
|
||||
self.k_norm = LayerNorm(
|
||||
self.head_dim, dtype=torch.bfloat16 if _use_aiter else torch.float32
|
||||
self.head_dim,
|
||||
dtype=(
|
||||
torch.float32
|
||||
if self.use_aiter_fused_fp8_writer
|
||||
else (torch.bfloat16 if _use_aiter else torch.float32)
|
||||
),
|
||||
)
|
||||
self.rotary_emb = get_rope_wrapper(
|
||||
rope_head_dim,
|
||||
@@ -319,8 +348,29 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
is_neox_style=is_neox_style,
|
||||
device=get_device().device,
|
||||
)
|
||||
self.block_size = block_size
|
||||
self.scale_fmt = scale_fmt
|
||||
if self.use_aiter_fused_fp8_writer and not (
|
||||
hasattr(self.rotary_emb, "cos_cache")
|
||||
and hasattr(self.rotary_emb, "sin_cache")
|
||||
):
|
||||
self.use_aiter_fused_fp8_writer = False
|
||||
self.k_norm = LayerNorm(self.head_dim, dtype=torch.bfloat16)
|
||||
if (
|
||||
aiter_fused_fp8_requested
|
||||
and not self.use_aiter_fused_fp8_writer
|
||||
and envs.SGLANG_DISABLE_AITER_FUSED_FP8_DSA_INDEXER.is_set()
|
||||
):
|
||||
logger.warning(
|
||||
"SGLANG_DISABLE_AITER_FUSED_FP8_DSA_INDEXER=0 but unsupported; "
|
||||
"using the legacy ROCm indexer writer"
|
||||
)
|
||||
elif self.use_aiter_fused_fp8_writer:
|
||||
global _FUSED_FP8_WRITER_LOGGED
|
||||
if not _FUSED_FP8_WRITER_LOGGED:
|
||||
logger.info("Enabled AITER fused FP8 DSA indexer writer")
|
||||
_FUSED_FP8_WRITER_LOGGED = True
|
||||
self._fused_fp8_rope_cache_key = None
|
||||
self._fused_fp8_cos_cache = None
|
||||
self._fused_fp8_sin_cache = None
|
||||
self.softmax_scale = self.head_dim**-0.5
|
||||
self.num_init_tokens = self.num_local_tokens = 0
|
||||
if config is not None:
|
||||
@@ -399,10 +449,101 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
kw, _ = self.wk_weights_proj(x)
|
||||
return kw.split([self.head_dim, self.n_heads], dim=-1)
|
||||
|
||||
def _aiter_fused_fp8_active(self, forward_batch: ForwardBatch) -> bool:
|
||||
if not self.use_aiter_fused_fp8_writer:
|
||||
return False
|
||||
if is_cp_active(forward_batch) or forward_batch.attn_cp_metadata is not None:
|
||||
return False
|
||||
# Layer-split needs a no-write fused mode for non-owners; fall back.
|
||||
return not hasattr(get_token_to_kv_pool(), "_is_layer_owned")
|
||||
|
||||
def _aiter_fused_fp8_rope_caches(
|
||||
self, device: torch.device, dtype: torch.dtype
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
key = (str(device), dtype)
|
||||
if self._fused_fp8_rope_cache_key != key:
|
||||
self._fused_fp8_cos_cache, self._fused_fp8_sin_cache = (
|
||||
prepare_aiter_rope_caches(
|
||||
self.rotary_emb.cos_cache,
|
||||
self.rotary_emb.sin_cache,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
)
|
||||
self._fused_fp8_rope_cache_key = key
|
||||
return self._fused_fp8_cos_cache, self._fused_fp8_sin_cache
|
||||
|
||||
def _aiter_fused_fp8_prepare_and_store(
|
||||
self,
|
||||
x: Union[torch.Tensor, Tuple[torch.Tensor, ...]],
|
||||
q_lora: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
forward_batch: ForwardBatch,
|
||||
layer_id: int,
|
||||
*,
|
||||
num_tokens: Optional[int] = None,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
query, _ = self.wq_b(q_lora)
|
||||
query = query.view(-1, self.n_heads, self.head_dim)
|
||||
key, _ = self.wk(x)
|
||||
weights_raw = self._weights_proj_bf16_in_fp32_out(x)
|
||||
|
||||
out_cache_loc = forward_batch.out_cache_loc
|
||||
if num_tokens is not None:
|
||||
query = query[:num_tokens]
|
||||
key = key[:num_tokens]
|
||||
weights_raw = weights_raw[:num_tokens]
|
||||
positions = positions[:num_tokens]
|
||||
out_cache_loc = out_cache_loc[:num_tokens]
|
||||
if out_cache_loc.dtype != torch.int64:
|
||||
out_cache_loc = out_cache_loc.to(torch.int64)
|
||||
if not out_cache_loc.is_contiguous():
|
||||
out_cache_loc = out_cache_loc.contiguous()
|
||||
|
||||
pool = get_token_to_kv_pool()
|
||||
if hasattr(pool, "invalidate_index_buffer_for_layer"):
|
||||
pool.invalidate_index_buffer_for_layer(layer_id)
|
||||
kv_cache = (
|
||||
pool.get_index_k_with_scale_buffer(layer_id=layer_id)
|
||||
.view(-1, pool.page_size, self.head_dim + 4)
|
||||
.view(fp8_dtype)
|
||||
)
|
||||
|
||||
q_fp8 = torch.empty_like(query, dtype=fp8_dtype)
|
||||
weights = torch.empty_like(weights_raw, dtype=torch.float32)
|
||||
cos_cache, sin_cache = self._aiter_fused_fp8_rope_caches(
|
||||
query.device, query.dtype
|
||||
)
|
||||
aiter_fused_fp8_qk_write(
|
||||
query,
|
||||
q_fp8,
|
||||
weights_raw,
|
||||
weights,
|
||||
key,
|
||||
kv_cache,
|
||||
out_cache_loc,
|
||||
self.k_norm.weight,
|
||||
self.k_norm.bias,
|
||||
positions,
|
||||
cos_cache,
|
||||
sin_cache,
|
||||
self.k_norm.variance_epsilon,
|
||||
self.block_size,
|
||||
self.scale_fmt,
|
||||
self.softmax_scale * self.n_heads**-0.5,
|
||||
preshuffle=_use_aiter_preshuffle,
|
||||
is_neox=self.is_neox_style,
|
||||
# Padded graph rows still need Q/gate; only K write is skipped.
|
||||
compute_all_q_rope=True,
|
||||
)
|
||||
return q_fp8, weights.unsqueeze(-1)
|
||||
|
||||
def _maybe_rotate(self, x: torch.Tensor) -> torch.Tensor:
|
||||
# Fusion drops the (logit-preserving) Hadamard rotation; without it the
|
||||
# index-K cache here matches the fused path that decode reads back.
|
||||
return x if self.use_dsa_indexer_fusion else rotate_activation(x)
|
||||
# CUDA and HIP fused writers omit Hadamard; skip it on fallbacks too so
|
||||
# the index-K cache matches the fused path that decode reads back.
|
||||
if self.use_dsa_indexer_fusion or self.use_aiter_fused_fp8_writer:
|
||||
return x
|
||||
return rotate_activation(x)
|
||||
|
||||
def _should_skip_logits_computation(self, forward_batch: ForwardBatch) -> bool:
|
||||
# topk_transform selects every valid page slot when kv_len <= index_topk;
|
||||
@@ -531,6 +672,8 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
*,
|
||||
apply_hadamard: bool = True,
|
||||
):
|
||||
# Non-fusion path only; self.wk does not exist when fusion is on.
|
||||
key, _ = self.wk(x)
|
||||
@@ -547,7 +690,8 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
dummy_q_rope = k_rope
|
||||
_, k_rope = self.rotary_emb(positions, dummy_q_rope, k_rope)
|
||||
self._update_rope_guarded(key[..., : self.rope_head_dim], k_rope)
|
||||
key = rotate_activation(key)
|
||||
if apply_hadamard:
|
||||
key = rotate_activation(key)
|
||||
|
||||
return key
|
||||
|
||||
@@ -1278,9 +1422,19 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
elif not forward_batch.out_cache_loc.is_contiguous():
|
||||
forward_batch.out_cache_loc = forward_batch.out_cache_loc.contiguous()
|
||||
|
||||
# Write the same K representation the decode path reads back: fused
|
||||
# (no-Hadamard) when fusion is on, else the legacy Hadamard path.
|
||||
if self.use_dsa_indexer_fusion:
|
||||
# Keep K in the same no-Hadamard space as the fused Q/K writer.
|
||||
if self._aiter_fused_fp8_active(forward_batch):
|
||||
key = self._get_k_bf16(x, positions, apply_hadamard=False)
|
||||
if num_tokens is not None:
|
||||
key = key[:num_tokens]
|
||||
self._store_index_k_cache(
|
||||
forward_batch=forward_batch,
|
||||
layer_id=layer_id,
|
||||
key=key,
|
||||
act_quant=act_quant,
|
||||
out_cache_loc=out_cache_loc,
|
||||
)
|
||||
elif self.use_dsa_indexer_fusion:
|
||||
key_raw, _ = self._fused_k_weights(x)
|
||||
if num_tokens is not None:
|
||||
assert num_tokens <= key_raw.shape[0]
|
||||
@@ -1502,6 +1656,14 @@ class Indexer(DSANPUIndexerMixin, BaseFusedOp):
|
||||
)
|
||||
|
||||
if (
|
||||
self._aiter_fused_fp8_active(forward_batch)
|
||||
and not in_piecewise_or_breakable_cuda_graph
|
||||
and not weights_proj_lora
|
||||
):
|
||||
q_fp8, weights = self._aiter_fused_fp8_prepare_and_store(
|
||||
x, q_lora, positions, forward_batch, layer_id
|
||||
)
|
||||
elif (
|
||||
self.use_dsa_indexer_fusion
|
||||
and not in_piecewise_or_breakable_cuda_graph
|
||||
and forward_batch.attn_cp_metadata is None
|
||||
|
||||
Reference in New Issue
Block a user