From 0dc8b29e15ddd9cf14151d17a62380179340ba1a Mon Sep 17 00:00:00 2001 From: fanxingran Date: Thu, 24 Sep 2026 12:46:35 +0800 Subject: [PATCH] [ROCm][DSA] Enable AITER fused FP8 indexer writer (#40710) Co-authored-by: Thomas Wang --- .../ops/attention/dsa/fp8_fused_writer_hip.py | 119 +++++++++++ python/sglang/srt/environ.py | 4 + .../srt/layers/attention/dsa/dsa_indexer.py | 190 ++++++++++++++++-- .../amd/test_fp8_fused_dsa_writer_gfx950.py | 164 +++++++++++++++ .../attention/test_fp8_fused_writer_hip.py | 132 ++++++++++++ 5 files changed, 595 insertions(+), 14 deletions(-) create mode 100644 python/sglang/kernels/ops/attention/dsa/fp8_fused_writer_hip.py create mode 100644 test/registered/amd/test_fp8_fused_dsa_writer_gfx950.py create mode 100644 test/registered/unit/layers/attention/test_fp8_fused_writer_hip.py diff --git a/python/sglang/kernels/ops/attention/dsa/fp8_fused_writer_hip.py b/python/sglang/kernels/ops/attention/dsa/fp8_fused_writer_hip.py new file mode 100644 index 0000000000..fc416dd7c4 --- /dev/null +++ b/python/sglang/kernels/ops/attention/dsa/fp8_fused_writer_hip.py @@ -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, + ) diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py index 4e502e48b9..a4ea55503c 100644 --- a/python/sglang/srt/environ.py +++ b/python/sglang/srt/environ.py @@ -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 diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer.py index b933601c4a..c14c42aa1b 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer.py @@ -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 diff --git a/test/registered/amd/test_fp8_fused_dsa_writer_gfx950.py b/test/registered/amd/test_fp8_fused_dsa_writer_gfx950.py new file mode 100644 index 0000000000..ff10360428 --- /dev/null +++ b/test/registered/amd/test_fp8_fused_dsa_writer_gfx950.py @@ -0,0 +1,164 @@ +"""AITER fused FP8 DSA writer parity on GLM-5.2 geometry.""" + +import unittest + +import torch + +from sglang.kernels.ops.attention.dsa.fp8_fused_writer_hip import ( + aiter_fused_fp8_qk_write, + prepare_aiter_rope_caches, +) +from sglang.kernels.ops.quantization.fp8_kernel import fp8_dtype +from sglang.srt.layers.layernorm import LayerNorm +from sglang.srt.layers.rotary_embedding import get_rope_wrapper +from sglang.test.ci.ci_register import register_amd_ci +from sglang.test.test_utils import CustomTestCase + +register_amd_ci(est_time=60, suite="stage-b-test-1-gpu-small-amd-mi35x") + +HEADS = 32 +HEAD_DIM = 128 +ROPE_DIM = 64 +PAGE_SIZE = 64 + + +def _gfx950() -> bool: + if not torch.cuda.is_available(): + return False + return ( + str(torch.cuda.get_device_properties(0).gcnArchName).split(":")[0] == "gfx950" + ) + + +def _ue8m0_quant(x: torch.Tensor): + """CPU/GPU reference for per-1x128 ue8m0 FP8 used by the fused writer.""" + fp8_max = 224.0 if str(fp8_dtype).endswith("fnuz") else 448.0 + amax = x.detach().float().abs().amax(dim=-1, keepdim=True).clamp_min(1e-4) + scale = torch.exp2(torch.ceil(torch.log2(amax / fp8_max))) + y = (x.float() / scale).clamp(-fp8_max, fp8_max) + return y.to(fp8_dtype), scale.squeeze(-1) + + +@unittest.skipUnless(_gfx950(), "gfx950 only") +class TestFp8FusedDsaWriter(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.norm = LayerNorm(HEAD_DIM, dtype=torch.float32).cuda() + cls.rope = get_rope_wrapper( + ROPE_DIM, + rotary_dim=ROPE_DIM, + max_position=4096, + base=1_000_000, + is_neox_style=False, + device="cuda", + ) + if not (hasattr(cls.rope, "cos_cache") and hasattr(cls.rope, "sin_cache")): + raise unittest.SkipTest("AITER split cos/sin RoPE caches are required") + cls.cos_cache, cls.sin_cache = prepare_aiter_rope_caches( + cls.rope.cos_cache, + cls.rope.sin_cache, + device=torch.device("cuda"), + dtype=torch.bfloat16, + ) + cls.rope.cos_cache = cls.rope.cos_cache.to(device="cuda", dtype=torch.bfloat16) + cls.rope.sin_cache = cls.rope.sin_cache.to(device="cuda", dtype=torch.bfloat16) + + def _inputs(self, tokens: int): + torch.manual_seed(2026 + tokens) + q = torch.randn(tokens, HEADS, HEAD_DIM, dtype=torch.bfloat16, device="cuda") + k = torch.randn(tokens, HEAD_DIM, dtype=torch.bfloat16, device="cuda") + weights = torch.randn(tokens, HEADS, dtype=torch.bfloat16, device="cuda") + positions = torch.arange(tokens, dtype=torch.int64, device="cuda") + slots = torch.arange(tokens, dtype=torch.int64, device="cuda") + pages = max(1, (tokens + PAGE_SIZE - 1) // PAGE_SIZE) + return q, k, weights, positions, slots, pages + + def _cache(self, pages: int, fill: int = 0): + return torch.full( + (pages, PAGE_SIZE, HEAD_DIM + 4), + fill, + dtype=torch.uint8, + device="cuda", + ) + + def _separate_no_hadamard(self, q, k, weights, positions, slots, cache): + q_ref = q.clone() + k_ref = self.norm(k) + q_rope = q_ref[..., :ROPE_DIM] + k_rope = k_ref[..., :ROPE_DIM] + self.rope(positions, q_rope, k_rope) + q_fp8, q_scale = _ue8m0_quant(q_ref) + + from aiter.ops.cache import indexer_k_quant_and_cache + + indexer_k_quant_and_cache( + k_ref, + cache.view(fp8_dtype), + slots, + 128, + "ue8m0", + preshuffle=True, + ) + weights_out = ( + weights.float() * q_scale.squeeze(-1) * (HEAD_DIM**-0.5) * (HEADS**-0.5) + ) + return q_fp8, weights_out + + def _fused(self, q, k, weights, positions, slots, cache): + q_out = torch.empty_like(q, dtype=fp8_dtype) + weights_out = torch.empty_like(weights, dtype=torch.float32) + aiter_fused_fp8_qk_write( + q, + q_out, + weights, + weights_out, + k, + cache.view(fp8_dtype), + slots, + self.norm.weight, + self.norm.bias, + positions, + self.cos_cache, + self.sin_cache, + self.norm.variance_epsilon, + 128, + "ue8m0", + (HEAD_DIM**-0.5) * (HEADS**-0.5), + preshuffle=True, + is_neox=False, + compute_all_q_rope=True, + ) + return q_out, weights_out + + def test_matches_separate_no_hadamard_path(self): + for tokens in (1, 4, 8, 24, 48): + with self.subTest(tokens=tokens): + q, k, weights, positions, slots, pages = self._inputs(tokens) + ref_cache = self._cache(pages) + got_cache = self._cache(pages) + _, ref_weights = self._separate_no_hadamard( + q, k, weights, positions, slots, ref_cache + ) + got_q, got_weights = self._fused( + q, k, weights, positions, slots, got_cache + ) + self.assertTrue(torch.isfinite(got_q.float()).all()) + self.assertTrue(torch.isfinite(got_weights).all()) + torch.testing.assert_close( + got_weights, ref_weights, rtol=2e-2, atol=2e-2 + ) + self.assertTrue(torch.equal(got_cache, ref_cache)) + + def test_negative_slot_computes_q_but_does_not_write_k(self): + q, k, weights, positions, slots, pages = self._inputs(4) + slots.fill_(-1) + cache = self._cache(pages, fill=0xA5) + before = cache.clone() + q_out, weights_out = self._fused(q, k, weights, positions, slots, cache) + self.assertTrue(torch.equal(cache, before)) + self.assertTrue(torch.isfinite(q_out.float()).all()) + self.assertTrue(torch.isfinite(weights_out).all()) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/layers/attention/test_fp8_fused_writer_hip.py b/test/registered/unit/layers/attention/test_fp8_fused_writer_hip.py new file mode 100644 index 0000000000..0149841bb0 --- /dev/null +++ b/test/registered/unit/layers/attention/test_fp8_fused_writer_hip.py @@ -0,0 +1,132 @@ +import sys +import types +import unittest +from unittest.mock import MagicMock, patch + +import torch + +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.test.ci.ci_register import register_amd_ci +from sglang.test.test_utils import CustomTestCase + +register_amd_ci(est_time=2, suite="stage-a-test-cpu-amd") + + +class TestFusedFp8WriterHip(CustomTestCase): + def test_geometry_gate(self): + self.assertTrue(fused_fp8_writer_geometry_supported(128, 64, 128)) + self.assertFalse(fused_fp8_writer_geometry_supported(64, 64, 128)) + self.assertFalse(fused_fp8_writer_geometry_supported(128, 32, 128)) + self.assertFalse(fused_fp8_writer_geometry_supported(128, 64, 64)) + + def test_available_rejects_mi300(self): + with patch( + "sglang.srt.utils.is_gfx95_supported", + return_value=False, + ): + self.assertFalse(aiter_fused_fp8_writer_available()) + + def test_prepare_aiter_rope_caches_squeezes_cpu_tables(self): + cos = torch.randn(128, 1, 1, 32, dtype=torch.float32) + sin = torch.randn(128, 1, 1, 32, dtype=torch.float32) + got_cos, got_sin = prepare_aiter_rope_caches( + cos, sin, device=torch.device("cpu"), dtype=torch.float32 + ) + self.assertEqual(tuple(got_cos.shape), (128, 32)) + self.assertEqual(got_cos.dtype, torch.float32) + self.assertTrue(torch.equal(got_cos, cos.squeeze())) + self.assertTrue(torch.equal(got_sin, sin.squeeze())) + + def _inputs(self): + tokens, heads, dim, page = 2, 32, 128, 64 + return dict( + q=torch.empty(tokens, heads, dim, dtype=torch.bfloat16), + q_out=torch.empty(tokens, heads, dim, dtype=torch.uint8), + weights=torch.empty(tokens, heads, dtype=torch.bfloat16), + weights_out=torch.empty(tokens, heads, dtype=torch.float32), + k=torch.empty(tokens, dim, dtype=torch.bfloat16), + kv_cache=torch.empty(1, page, dim + 4, dtype=torch.uint8), + slot_mapping=torch.arange(tokens, dtype=torch.int64), + norm_weight=torch.ones(dim, dtype=torch.float32), + norm_bias=torch.zeros(dim, dtype=torch.float32), + positions=torch.arange(tokens, dtype=torch.int64), + cos_cache=torch.empty(1024, 32, dtype=torch.bfloat16), + sin_cache=torch.empty(1024, 32, dtype=torch.bfloat16), + ) + + def test_forwards_full_abi(self): + op = MagicMock() + cache_module = types.ModuleType("aiter.ops.cache") + cache_module.indexer_qk_rope_quant_and_cache = op + ops_module = types.ModuleType("aiter.ops") + ops_module.cache = cache_module + aiter_module = types.ModuleType("aiter") + aiter_module.ops = ops_module + + args = self._inputs() + with patch.dict( + sys.modules, + { + "aiter": aiter_module, + "aiter.ops": ops_module, + "aiter.ops.cache": cache_module, + }, + ): + aiter_fused_fp8_qk_write( + **args, + epsilon=1e-6, + quant_block_size=128, + scale_fmt="ue8m0", + weights_scale=0.03125, + preshuffle=True, + is_neox=False, + compute_all_q_rope=True, + ) + + op.assert_called_once() + call = op.call_args + self.assertIs(call.args[0], args["q"]) + self.assertIs(call.args[5], args["kv_cache"]) + self.assertEqual(call.kwargs["preshuffle"], True) + self.assertEqual(call.kwargs["is_neox"], False) + self.assertEqual(call.kwargs["compute_all_q_rope"], True) + + def test_refuses_non_fp32_layernorm(self): + args = self._inputs() + args["norm_weight"] = args["norm_weight"].bfloat16() + with self.assertRaisesRegex(TypeError, "LayerNorm parameters as fp32"): + aiter_fused_fp8_qk_write( + **args, + epsilon=1e-6, + quant_block_size=128, + scale_fmt="ue8m0", + weights_scale=1.0, + preshuffle=True, + is_neox=False, + compute_all_q_rope=True, + ) + + def test_refuses_wrong_geometry(self): + args = self._inputs() + args["cos_cache"] = torch.empty(1024, 16, dtype=torch.bfloat16) + args["sin_cache"] = torch.empty(1024, 16, dtype=torch.bfloat16) + with self.assertRaisesRegex(ValueError, "rope_dim=32"): + aiter_fused_fp8_qk_write( + **args, + epsilon=1e-6, + quant_block_size=128, + scale_fmt="ue8m0", + weights_scale=1.0, + preshuffle=True, + is_neox=False, + compute_all_q_rope=True, + ) + + +if __name__ == "__main__": + unittest.main()