Prhub

#36758 [AMD] Qwen3.5 ASM FMHA chunked-prefill context attention

原始 PR 作者 zijiecode 合并时间 2026-08-28 14:37 文件变更 1 提交数 3 评论 4 代码增减 +103 / -0

执行摘要

gfx950 ASM FMHA 加速 Qwen3.5 分块预填充

在 MI355X 上,Qwen3.5 长输入(70k prompt、chunked prefill)的 prefill attention 大部分时间花在 aiter 的 ck_tile paged mha_batch_prefill 上,该内核在 head_dim 256、fp8 KV、16k chunk 下只达到 FP8 峰值约 15% 的利用率;paging 不是瓶颈(连续 KV 一样慢,fp8 仅比 bf16 快 1.2 倍)。而 gfx950 ASM 内核 fmha_fwd_hd256_fp8_causal_group(已用于无前缀首 chunk)同样形状快 3.5 倍,唯一障碍是它需要连续 varlen K/V,而 KV cache 是 paged 的。实测 gather 70k tokens 的 fp8 KV(约 72 MB)只要约 18 µs,相对注意力本身的数毫秒可忽略,因此值得 gather 后调用 ASM 内核。

推荐精读。核心亮点有三:一是用实测数据论证 paged→contiguous 的 gather 开销可忽略,从而把连续布局 ASM 内核复用到 paged cache;二是对 fp8 用 uint8 view 绕过 index_select 不支持的限制;三是通过 clamp 和多级越界检查构建安全回退,避免 speculative/mixed batch 导致崩溃。设计思路对类似「内核要求连续布局、但缓存是分页」的场景有迁移价值。

讨论亮点

Review 中有两条主要意见,均由作者在 commit af392342 中解决:

  • yichiche 建议不要使用默认开启的 SGLANG_AITER_ASM_CONTEXT_PREFILL 环境变量开关;zijiecode 回应已移除该 toggle,分支直接由 is_gfx95_supported() 门控。
  • yichiche 建议把 is_gfx95_supported() 移到分支条件的首位以明确 ASM 内核仅用于 gfx950;zijiecode 回应已完成,is_gfx95_supported() 现在是分支的第一个条件。
    最终两位 reviewer(yichiche、HaiShaw)均 APPROVED。

实现拆解

  1. 新增 ASM context-prefill 分支:在 aiter_backend.py::forward_extend 中原有无前缀 ASM 分支之前,按 is_gfx95_supported()、extend 模式、存在 prefix、head_dim 256、fp8 KV cache、无 sliding window/sink/softcap、非 vectorized_5d 布局等条件,为带前缀的 context chunk 建立旁路。
  2. 页元数据展开与一致性保护:将页粒度的 kv_indptr/kv_indices 展开成 per-token 的 pool slot 和页内偏移;先用 pages_per_seq * page clamp seq_lens,再逐级检查 page_slot 和 tok_idx 是否越界,任何不一致都会记录 warning 并回退到原 paged 路径,保证最坏情况只是回到旧速度。
  3. fp8 KV 连续化 gather:因为 index_select 不支持 fp8,将 K/V cache 按 uint8 view 做字节级 index_select,再恢复原 dtype 并 reshape 为 varlen 布局。
  4. 调用 ASM varlen 内核:以 gather 后的连续 K/V 和展开的 cu_k 调用 flash_attn_varlen_fp8_pertensor_func,使用右下角 causal mask,输出 reshape 后返回。
  5. 配套验证:PR 提供了 GSM8K 5-shot 准确率(92.8%,1224/1319)与 MI355X 端到端 benchmark(E2E 提升 24.6%-28.5%,TPOT 提升 28.2%),但未新增单元测试文件。
文件 模块 状态 重要度
python/sglang/srt/layers/attention/aiter_backend.py 注意力后端 modified 6.98

关键符号

forward_extend

关键源码片段

python/sglang/srt/layers/attention/aiter_backend.py core-logic

核心改动文件:在 forward_extend 中为带前缀的 context-chunk prefill 新增 gfx950 ASM FMHA 分支,包含 paged 元数据展开、fp8 gather、安全回退逻辑,是性能提升的唯一来源。

# 有前缀的 context-chunk prefill 走 gfx950 ASM fp8 varlen fmha。
# ck_tile paged batch_prefill 在该形状下只有约 15% FP8 MFU,
# 而 ASM 内核快约 3.5 倍;gather 成本约 20 µs,可忽略。
if (
    is_gfx95_supported()
    and forward_batch.forward_mode.is_extend()
    and forward_batch.extend_prefix_lens_cpu is not None
    and any(forward_batch.extend_prefix_lens_cpu)
    and window_size == (-1, -1)
    and sinks is None
    and self.logits_soft_cap == 0.0
    and layer.qk_head_dim == 256
    and layer.v_head_dim == 256
    and self.kv_cache_dtype == fp8_dtype
    and not self.kv_cache_is_vectorized_5d
    and self.forward_metadata.max_kv_len is not None
):
    bs = forward_batch.batch_size
    k_cache, v_cache = self.token_to_kv_pool.get_kv_buffer(layer.layer_id)
    page = self.page_size
    kv_indptr = self.forward_metadata.kv_indptr[: bs + 1]
    kv_pages = self.forward_metadata.kv_indices
    seq_lens = forward_batch.seq_lens[:bs].to(torch.long)
​
    # kvlen 不能超过 kv_indices 实际拥有的页数:plain extend 的元数据
    # 是页粒度的,但 mixed/spec batch 可能和 seq_lens 不一致,直接
    # gather 会越界。先按页数 clamp,再做一致性检查,失败则回退。
    pages_per_seq = (kv_indptr[1 : bs + 1] - kv_indptr[:bs]).to(torch.long)
    kvlen_cap = pages_per_seq * page
    seq_lens = torch.minimum(seq_lens, kvlen_cap)
    total_k = int(seq_lens.sum().item())
    cu_k = torch.zeros(bs + 1, dtype=torch.long, device=q.device)
    torch.cumsum(seq_lens, 0, out=cu_k[1:])
​
    # 把页粒度元数据展开成 per-token 的 pool slot 与页内偏移
    seq_ids = torch.repeat_interleave(torch.arange(bs, device=q.device), seq_lens)
    pos_in_seq = torch.arange(total_k, device=q.device) - cu_k[seq_ids]
    page_slot = kv_indptr[seq_ids].to(torch.long) + pos_in_seq // page
    asm_cp_ok = bool(int(page_slot.max().item()) < kv_pages.numel())
    if not asm_cp_ok:
        logger.warning(
            "[asm-context-prefill] metadata mismatch, falling back:"
            " mode=%s bs=%s page_slot_max=%s kv_pages=%s seq_lens=%s"
            " kv_indptr=%s",
            forward_batch.forward_mode,
            bs,
            int(page_slot.max().item()),
            kv_pages.numel(),
            seq_lens.tolist(),
            kv_indptr.tolist(),
        )
    if asm_cp_ok:
        tok_idx = kv_pages[page_slot].to(torch.long) * page + pos_in_seq % page
        asm_cp_ok = int(tok_idx.max().item()) < (
            self.token_to_kv_pool.get_key_buffer(layer.layer_id).shape[0]
        )
​
    if asm_cp_ok:
        hk = layer.tp_k_head_num * layer.qk_head_dim
        hv = layer.tp_v_head_num * layer.v_head_dim
        # fp8 没有 index_select,先按 uint8 view 再按字节 gather
        k_gather = (
            k_cache.view(-1, hk)
            .view(torch.uint8)
            .index_select(0, tok_idx)
            .view(k_cache.dtype)
            .view(-1, layer.tp_k_head_num, layer.qk_head_dim)
        )
        v_gather = (
            v_cache.view(-1, hv)
            .view(torch.uint8)
            .index_select(0, tok_idx)
            .view(v_cache.dtype)
            .view(-1, layer.tp_v_head_num, layer.v_head_dim)
        )
        # 后续调用 flash_attn_varlen_fp8_pertensor_func,
        # 以 cu_k 作为 cu_seqlens_k,右下角 causal mask。

评论区精华

移除默认开启的 SGLANG_AITER_ASM_CONTEXT_PREFILL 环境变量开关 设计

yichiche 建议不要使用默认开启的全局变量开关,既然默认打开就不需要 env toggle。zijiecode 回复已在 commit af392342 中移除该 toggle,分支直接由 is_gfx95_supported() 门控。

结论:env toggle 被删除,改为无条件检查 is_gfx95_supported()。 · 已解决

将 is_gfx95_supported() 移到分支条件首部 设计

yichiche 建议把 is_gfx95_supported() 移到分支条件中,以明确该 ASM 路径仅用于 gfx950。zijiecode 回复已在 af392342 中完成,is_gfx95_supported() 现在是分支的第一个条件。

结论:is_gfx95_supported() 成为分支第一条件。 · 已解决

风险与影响

  1. 静默截断风险:在 aiter_backend.py 新分支中,seq_lens 被 clamp 到 pages_per_seq * page 后,即使元数据与真实长度不一致,只要 page_slot/tok_idx 不越界,分支仍会继续执行,可能静默忽略部分 prefix KV 而不会回退。对 plain extend 通常无影响,但 mixed/speculative batch 中可能出现注意力长度被截断。
  2. 缺少单元测试:PR 未新增测试文件,主要依赖 GSM8K 和 benchmark 验证,回归风险由 CI 承担,但覆盖范围有限。
  3. 紧耦合 gfx950:分支条件包含 is_gfx95_supported(),未来其他 GPU 或 head_dim 形状可能误入或漏入,需要维护者注意条件收敛。

影响范围集中在 AMD MI355X(gfx950)上、使用 aiter attention 后端且配置为 fp8 KV、head_dim 256、chunked prefill 的模型(典型如 Qwen3.5)。这些场景下 E2E 延迟降低约 25-28%,TTFT 降低约 23-26%,TPOT 也有副作用改善。对其他硬件、其他 attention 后端、非 fp8 KV 场景无影响。代码复杂度小幅上升,但保护机制完整,最坏情况回退到旧路径。

无新增单元测试 元数据 clamp 可能静默截断 prefix 仅 gfx950 + head_dim 256 生效

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论