Skip to content

perf(attention): fast fp8 kv decode on rdna3 (gfx11) - #899

Merged
jason-fxz merged 1 commit into
FlashML-org:mainfrom
zihaomu:perf/rdna3-fp8-kv-pr897-followup-20261112
Nov 28, 2026
Merged

jason-fxz merged 1 commit into
FlashML-org:mainfrom
zihaomu:perf/rdna3-fp8-kv-pr897-followup-20261112

Conversation

@zihaomu

@zihaomu zihaomu commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #897 (gfx1201 packed FP8 KV reads); related to #894 and #893.

On RDNA3 (gfx11), fp8_per_token_head KV decode is far slower than BF16 KV: gfx11 has no FP8 converts and no hardware FP32 to BF16 convert, so the generic E4M3 decode runs as integer code, and Triton repeats it for every dot-operand replica. This PR gives gfx11 a dedicated decode reader. With it, FP8 KV decode on a Radeon PRO W7900D is faster than main's FP8 path at every measured context and row count. End to end (batch 1, one row per step) it matches BF16 KV decode at 512 tokens and is 20% faster at 64K, while keeping FP8's KV capacity.

Scope: gfx11 + fp8_per_token_head, decode only. Prefill/extend is unchanged; an in-kernel prefill reader will be a separate PR. RDNA4 (including #897's packed reader), CUDA, BF16 KV and INT8 KV keep their current code (evidence below).

Changes

  • Gate. _use_gfx11_f16_reader(kv_format) sits next to _use_gfx12_fp8_reader in attention.py. It is true for fp8_per_token_head when get_rocm_gfx_arch() starts with gfx11 and FREETOKEN_FORCE_E4M3_EMU is not set.
  • Tile. _kv_tile_gfx11_f16 in kv_rows.py turns each E4M3FN code into the fp16 bit pattern of value/256, ((c & 0x80) << 8) | ((c & 0x7F) << 7).
    • This is exact for every finite code (E4M3 subnormals become fp16 subnormals) and uses integer ops only.
    • A v_mov_b32 inline-asm pin keeps the decode in the load layout, so each byte is decoded once rather than once per WMMA operand replica.
    • kv_row_scale(..., F16=True) restores the 256.
    • Q is cast to fp16, so QK and PV run as v_wmma_f32_16x16x16_f16 with FP32 accumulation.
  • Launch. The reader serves every ROWS <= MAX_DECODE_ROWS. _gfx11_f16_decode_launch(rows * block_h) gives 16-key tiles, 1 stage (the pipeliner cannot predicate the asm pin), and 2 warps up to M = 16, 4 above; these values come from a W7900D sweep over 1/2/4/8 rows.
  • Splits. The minimum split length is 32 instead of 128. decode_kv_split_cap(..., kv_format) allows 8 programs per SM, up to 256 splits, instead of 4 and 64. The Triton backend sizes decode scratch with its KV cache's format.
  • Shared split rule. _max_request_splits(keys, min_split_len) takes the same minimum, so the sliding-window cap matches the kernel; the decode_paged_attention docstring and the _decode_num_splits comment state the rule with L = 128, or 32 for this reader.
  • Tests.
    • test_rocm_kv_decode_preserves_every_finite_fp8_code (the renamed RDNA4 per-code test) gains a gfx11 case comparing all 256 codes bit-for-bit, signed zero and subnormals included. It skips inline on get_rocm_gfx_arch().
    • test_decode_triton_attention_splits_long_requests and test_decode_triton_attention_multi_row_matches_reference now also run with FP8 and INT8 KV against the dequantized reference. On gfx11 the FP8 cases exercise the new reader across head_dim 256/512, GQA 2/6/8, mixed-length batches up to 8,193 keys, 1 to 8 rows per request, sliding windows, sinks and a scratch smaller than the split cap.
    • The existing test_quantized_kv_attention_matches_dequantized_reference decode and decode_rows cases (head_dim 64 to 512) also go through the reader on gfx11.
    • One backend test's FakeKVCache now subclasses the file's _PlainKVStorage, because the backend reads kv_format when sizing decode scratch; production pools define it by default.

Numerics

  • The tile is exact; only operand rounding changes. Q is rounded to fp16 instead of BF16 (finer mantissa; values above 65504 would overflow) and p x scale_v x 256 is rounded to fp16.
  • Greedy outputs therefore can differ from main's FP8 path (hash table below).
  • Task-quality evaluation has not been run.
  • An H100 run of this kernel logic with the gate forced on and a PTX pin (review comment on the previous revision) found its maximum relative error no larger than the current FP8 path's in 47 cases.

Isolation

  • Off gfx11 the gate is false (get_rocm_gfx_arch() is None on CUDA), so host launch parameters, split caps and scratch sizes are unchanged. F16_KV=False and F16=False remove the new branches at compile time.
  • I cross-compiled decode stage 1 on main (a7a8236) and this commit (3422824) with a Triton target override (no launch) and compared the instruction streams. All 20 are identical:
Target Cases Result
gfx1201, D128 1 row: FP8 packed (#897), FP8 generic, INT8, BF16; 4 rows: FP8, INT8, BF16 7/7 identical
gfx1200, D128 same 7 7/7 identical
gfx1100, D256 (non-reader specializations) 1 and 4 rows: FP8 generic, INT8, BF16 6/6 identical
  • Not run on real RDNA4 or NVIDIA hardware for this revision.

Test environment

  • GPU: AMD Radeon PRO W7900D, gfx1100, 48 GiB, PCI 0000:A3:00.0. One GPU is visible via ROCR_VISIBLE_DEVICES; torch.cuda.get_device_properties(0) reports gfx1100 with multi_processor_count=48.
  • CPU: 2x AMD EPYC 9334; Linux 6.8.0-146-generic; amdgpu 6.16.13.
  • Container image sha256:31cc953da2ee8345774f92c8f288dded6a19cbcd59c1ce96051970f48d627d18: ROCm 10.1.0, HIP 7.16.26385, Python 3.13.13, Torch 2.14.0+rocm10.1.0, Triton 3.8.0, Transformers 5.18.0.
  • Checkpoint: Qwen/Qwen3.5-0.8B, BF16, model.safetensors SHA-256 04b1c301231dd422b8860db31311ab2721511346a32cb1e079c4c4e5f1fe4696. It has 24 layers, of which 6 are full attention, with head_dim 256 and 8 query / 2 KV heads (GQA4).

Tests (all on 3422824)

  • pytest tests/kernels/test_triton_attention.py: 142 passed, 2 skipped. The skips are the gfx1201 cases of test_rocm_kv_decode_preserves_every_finite_fp8_code.
  • pytest tests/engine/test_attention_backend_arch.py tests/kvcache/test_kv_cache_rebuild.py tests/kvcache/test_pool_sizing_surface.py tests/attention/test_capture_rows_per_req.py: 62 passed, 4 skipped. The skips are because sgl_kernel / flashinfer are not installed.
  • FREETOKEN_FORCE_E4M3_EMU=1 pytest tests/kernels/test_triton_attention.py -k 'quantized_kv_attention_matches or splits_long_requests or multi_row_matches', with a separate Triton cache: 80 passed. Forced emulation disables the gfx11 reader.

End-to-end A/B (main a7a8236 vs 3422824)

  • Setup: same GPU and image, one service at a time.
  • Requests: exact-length synthetic prompts; 1 warmup and 3 measured requests per point (medians); 128 output tokens, temperature=0, ignore_eos=true, --cache-type naive.
  • Checks: every request was verified for exact prompt tokens, 128 completion tokens and cached_tokens == 0.
  • Metrics: TTFT runs from request start to the first text event; decode tok/s = 127 / (finish event - first text event).
ROCR_VISIBLE_DEVICES=<gpu> python -m freetoken.cli serve --model Qwen/Qwen3.5-0.8B --dtype bfloat16 \
  --attention-backend triton --kv-cache-dtype {auto|fp8_per_token_head} --num-tokens 70000 \
  --max-seq-len-override 65792 --max-prefill-length 2048 --max-running-requests 1 --cuda-graph-max-bs 1 \
  --memory-ratio 0.7 --cache-type naive --text-model-only --enable-cache-report --enable-timings-report \
  --sampling-defaults none --reasoning-parser off --port <port>
python bench_service.py --origin http://127.0.0.1:<port> --prompts prompts --label <label> --repeats 3 --max-tokens 128 --output <label>.json
Context Decode tok/s: BF16 main / FP8 main / FP8 3422824 vs FP8 main vs BF16 TTFT: BF16 / FP8 main / FP8 3422824 E2E: BF16 / FP8 main / FP8 3422824
512 198.8 / 168.7 / 198.3 +17.5% -0.3% 0.031 / 0.031 / 0.031 s 0.670 / 0.784 / 0.671 s
8,192 186.8 / 147.4 / 191.2 +29.7% +2.4% 0.390 / 0.668 / 0.668 s 1.070 / 1.530 / 1.333 s
32,768 160.8 / 92.7 / 176.7 +90.7% +9.9% 2.192 / 7.729 / 7.707 s 2.983 / 9.100 / 8.426 s
65,536 135.8 / 61.6 / 163.1 +164.6% +20.1% 6.113 / 29.370 / 29.454 s 7.047 / 31.432 / 30.232 s
  • TTFT is unchanged from main's FP8 path because prefill is out of scope. Long-context end-to-end time is therefore still dominated by FP8 prefill until the follow-up.
  • KV allocation for 70,000 tokens: BF16 0.80 GiB, FP8 0.41 GiB. Service-reported VRAM: BF16 2.719 GiB, FP8 2.318 GiB (main) and 2.316 GiB (3422824).
  • Greedy output hashes are identical across the three repeats in every run. 3422824 matches BF16 at 512 and 32,768 tokens and matches neither BF16 nor main FP8 at 8,192 and 65,536.

Kernel microbenchmark: decode stage 1+2 per layer (us)

  • Shapes: Qwen3.5-0.8B full attention (8 Q heads, 2 KV heads, D256), contiguous slots, batch 1 with rows query rows.
  • Timing: median of 7 HIP-Graph replay batches.
  • Splits: the backend's split cap for each format.
  • Error: max abs error of 3422824 against the BF16 kernel on the dequantized cache.
Rows Keys BF16 main FP8 main FP8 3422824 Max abs err
1 512 / 8K / 32K / 64K 22.2 / 57.3 / 177.6 / 398.5 86.4 / 248.7 / 900.1 / 1821.7 20.6 / 46.4 / 108.1 / 170.3 <= 4.2e-3
2 512 / 8K / 32K / 64K 23.0 / 62.8 / 203.3 / 458.9 88.6 / 272.1 / 985.4 / 1929.2 22.4 / 54.1 / 119.1 / 187.0 <= 4.4e-3
4 512 / 8K / 32K / 64K 25.2 / 64.1 / 166.3 / 406.6 91.0 / 282.9 / 991.9 / 1937.0 27.0 / 69.6 / 131.7 / 204.4 <= 4.2e-3
8 512 / 8K / 32K / 64K 33.2 / 92.8 / 270.0 / 679.5 110.8 / 326.7 / 1185.2 / 2324.7 23.8 / 86.8 / 197.3 / 338.9 <= 7.8e-3

With 4 rows at 8K keys or fewer, the reader is still 7-9% slower than BF16 KV; everywhere else in this table it is within 2% or faster.

Open questions

  • Gate width. The gate covers all gfx11* (gfx1100/1101/1102 and RDNA3.5 gfx1150/1151), which share the missing converts, but only gfx1100 was measured. It can be narrowed to measured targets.

Scripts

bench_service.py (end-to-end SSE client)
from __future__ import annotations

import argparse
import hashlib
import json
import statistics
import time
import urllib.request
from pathlib import Path


def get_json(url: str, timeout: float = 30) -> dict:
    with urllib.request.urlopen(url, timeout=timeout) as response:
        return json.load(response)


def stream_completion(origin: str, model: str, prompt: str, max_tokens: int) -> dict:
    body = {
        "model": model,
        "prompt": prompt,
        "max_tokens": max_tokens,
        "temperature": 0,
        "ignore_eos": True,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    request = urllib.request.Request(
        f"{origin}/v1/completions",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json"},
    )
    t0 = time.perf_counter()
    first_text = None
    finish = None
    usage = None
    pieces: list[str] = []
    event_count = 0
    with urllib.request.urlopen(request, timeout=1800) as response:
        for raw in response:
            line = raw.strip()
            if not line.startswith(b"data:"):
                continue
            payload = line[5:].strip()
            if payload == b"[DONE]":
                break
            now = time.perf_counter()
            event = json.loads(payload)
            event_count += 1
            if event.get("usage"):
                usage = event["usage"]
            for choice in event.get("choices", []):
                text = choice.get("text") or ""
                if text:
                    if first_text is None:
                        first_text = now
                    pieces.append(text)
                if choice.get("finish_reason") is not None:
                    finish = now
    if usage is None or first_text is None or finish is None:
        raise RuntimeError(
            f"incomplete stream: usage={usage is not None}, "
            f"first_text={first_text}, finish={finish}, events={event_count}"
        )
    completion = int(usage["completion_tokens"])
    decode_s = finish - first_text
    return {
        "prompt_tokens": int(usage["prompt_tokens"]),
        "completion_tokens": completion,
        "cached_tokens": int(
            (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0) or 0
        ),
        "ttft_s": first_text - t0,
        "decode_s": decode_s,
        "decode_tok_s": (completion - 1) / decode_s,
        "e2e_s": finish - t0,
        "events": event_count,
        "text_sha256": hashlib.sha256("".join(pieces).encode()).hexdigest(),
        "text_chars": sum(map(len, pieces)),
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--origin", required=True)
    parser.add_argument("--prompts", required=True)
    parser.add_argument("--label", required=True)
    parser.add_argument("--repeats", type=int, default=3)
    parser.add_argument("--max-tokens", type=int, default=128)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    model = get_json(f"{args.origin}/v1/models")["data"][0]["id"]
    manifest = json.loads((Path(args.prompts) / "manifest.json").read_text())
    rows = []
    for item in manifest:
        target = int(item["tokens"])
        prompt = (Path(args.prompts) / f"prompt-{target}.txt").read_text()
        warm = stream_completion(args.origin, model, prompt, args.max_tokens)
        if warm["prompt_tokens"] != target or warm["completion_tokens"] != args.max_tokens:
            raise RuntimeError(f"warmup usage mismatch at {target}: {warm}")
        print(f"warmup label={args.label} tokens={target} ttft={warm['ttft_s']:.3f}s decode={warm['decode_tok_s']:.2f}", flush=True)
        for repeat in range(1, args.repeats + 1):
            row = stream_completion(args.origin, model, prompt, args.max_tokens)
            if row["prompt_tokens"] != target:
                raise RuntimeError(f"prompt token mismatch: expected {target}, got {row}")
            if row["completion_tokens"] != args.max_tokens:
                raise RuntimeError(f"completion token mismatch: {row}")
            if row["cached_tokens"] != 0:
                raise RuntimeError(f"unexpected prefix cache hit: {row}")
            row.update(label=args.label, target_tokens=target, repeat=repeat)
            rows.append(row)
            print(json.dumps(row, sort_keys=True), flush=True)

    summaries = []
    for target in sorted({r["target_tokens"] for r in rows}):
        subset = [r for r in rows if r["target_tokens"] == target]
        summary = {
            "label": args.label,
            "target_tokens": target,
            "repeats": len(subset),
            "ttft_median_s": statistics.median(r["ttft_s"] for r in subset),
            "decode_tok_s_median": statistics.median(r["decode_tok_s"] for r in subset),
            "e2e_median_s": statistics.median(r["e2e_s"] for r in subset),
            "text_hashes": sorted({r["text_sha256"] for r in subset}),
        }
        summaries.append(summary)
        print("SUMMARY " + json.dumps(summary, sort_keys=True), flush=True)

    stats = get_json(f"{args.origin}/v1/stats")
    Path(args.output).write_text(
        json.dumps({"label": args.label, "model": model, "rows": rows, "summaries": summaries, "stats": stats}, indent=2)
    )


if __name__ == "__main__":
    main()
bench_kernels.py (decode microbenchmark; `--rows` for multi-row)
"""Kernel-level BF16 vs FP8 KV benchmark for Qwen3.5-0.8B full-attention shapes on one GPU."""
from __future__ import annotations

import argparse
import json
import statistics

import torch

from freetoken.kernel.triton.attention import decode_paged_attention, extend_paged_attention
from freetoken.kernel.triton.kv_rows import store_kv_rows
from freetoken.kvcache.format import FP8_PER_TOKEN_HEAD, INT8_PER_TOKEN_HEAD, NONE

QH, KVH, D = 8, 2, 256
CHUNK = 2048
SPLITS = 64


def make_cache(fmt, n, gen):
    k = torch.randn(n, KVH * D, generator=gen, device="cuda").mul_(2.0).to(torch.bfloat16)
    v = torch.randn(n, KVH * D, generator=gen, device="cuda").to(torch.bfloat16)
    if not fmt.quantized:
        return k.view(n, KVH, D), v.view(n, KVH, D), None, None
    kc = torch.empty(n, KVH, D, dtype=fmt.elem_store_dtype, device="cuda")
    vc = torch.empty_like(kc)
    ks = torch.empty(n, KVH, dtype=torch.float32, device="cuda")
    vs = torch.empty_like(ks)
    store_kv_rows(fmt, k, v, torch.arange(n, device="cuda"), kc, vc, ks, vs)
    return kc, vc, ks, vs


def dequant(codes, scale):
    vals = codes.view(torch.float8_e4m3fn).float() if codes.dtype == torch.uint8 else codes.float()
    return (vals * scale[..., None]).to(torch.bfloat16)


def time_graph(fn, iters):
    s = torch.cuda.Stream()
    s.wait_stream(torch.cuda.current_stream())
    with torch.cuda.stream(s):
        for _ in range(3):
            fn()
    torch.cuda.current_stream().wait_stream(s)
    g = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g):
        fn()
    samples = []
    for _ in range(7):
        a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        a.record()
        for _ in range(iters):
            g.replay()
        b.record()
        torch.cuda.synchronize()
        samples.append(a.elapsed_time(b) / iters * 1000.0)
    return statistics.median(samples)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--fmt", choices=["bf16", "fp8", "int8"], required=True)
    ap.add_argument("--decode-ctx", default="512,8192,32768,65536")
    ap.add_argument("--prefix", default="0,8192,32768,63488")
    ap.add_argument("--output", required=True)
    ap.add_argument("--splits", type=int, default=None, help="max_kv_splits for decode (default: kernel cap)")
    ap.add_argument("--min-split-len", type=int, default=None)
    ap.add_argument("--rows", type=int, default=1, help="decode query rows per request (main >= #900)")
    ap.add_argument("--gfx11-cfg", default=None, help="override _gfx11_f16_decode_launch: block_n,stages,warps")
    ap.add_argument("--dec-cfg", default=None, help="override kv_decode_config: block_n,stages,warps")
    args = ap.parse_args()
    fmt = {"fp8": FP8_PER_TOKEN_HEAD, "int8": INT8_PER_TOKEN_HEAD}.get(args.fmt, NONE)
    if args.dec_cfg:
        import freetoken.kernel.triton.attention as attn
        bn, st, wp = map(int, args.dec_cfg.split(","))
        attn.kv_decode_config = lambda *a: (1, bn, st, wp)
    try:
        from freetoken.kernel.triton.attention import decode_kv_split_cap
        cap = decode_kv_split_cap(1, QH, KVH, torch.cuda.current_device(), fmt)
    except TypeError:
        cap = SPLITS
    splits = args.splits or cap
    if args.gfx11_cfg:
        import freetoken.kernel.triton.attention as attn
        cfg = tuple(map(int, args.gfx11_cfg.split(",")))
        attn._gfx11_f16_decode_launch = lambda m: cfg
    R = args.rows
    print(json.dumps({"scratch_splits": splits}), flush=True)
    if args.min_split_len:
        import freetoken.kernel.triton.attention as attn
        attn._MIN_SPLIT_LEN = args.min_split_len
    gen = torch.Generator(device="cuda").manual_seed(0)
    n = 65536 + CHUNK
    kc, vc, ks, vs = make_cache(fmt, n, gen)
    kv_args = dict(kv_format=fmt, k_scale=ks, v_scale=vs)
    ref_args = dict(kv_format=NONE, k_scale=None, v_scale=None)
    if fmt.quantized:
        kr, vr = dequant(kc, ks), dequant(vc, vs)
    rows = []

    for ctx in map(int, filter(None, args.decode_ctx.split(","))):
        q = torch.randn(R, QH, D, generator=gen, device="cuda").to(torch.bfloat16)
        indptr = torch.tensor([0, ctx], dtype=torch.int32, device="cuda")
        indices = torch.arange(ctx, dtype=torch.int32, device="cuda")
        qpos = torch.arange(ctx - R, ctx, dtype=torch.int32, device="cuda")
        logits = torch.empty(R, QH, splits, D, dtype=torch.float32, device="cuda")
        lse = torch.empty(R, QH, splits, dtype=torch.float32, device="cuda")
        rows_kw = {} if R == 1 else dict(qo_indptr=torch.tensor([0, R], dtype=torch.int32, device="cuda"), max_q_len=R)
        out = torch.empty_like(q)

        def run(c=kc, v=vc, kw=kv_args, o=out):
            decode_paged_attention(q, c, v, indptr, indices, qpos, logits, lse, D ** -0.5, out=o,
                                   max_kv_splits=args.splits, **rows_kw, **kw)

        us = time_graph(run, 50)
        err = None
        if fmt.quantized:
            ref = torch.empty_like(q)
            run(kr, vr, ref_args, ref)
            torch.cuda.synchronize()
            err = (out.float() - ref.float()).abs().max().item()
        rows.append({"kernel": "decode", "ctx": ctx, "us": us, "max_err_vs_dequant": err,
                     "splits": args.splits, "dec_cfg": args.dec_cfg, "rows": R, "gfx11_cfg": args.gfx11_cfg})
        print(json.dumps(rows[-1]), flush=True)

    for prefix in map(int, filter(None, args.prefix.split(","))):
        total = prefix + CHUNK
        q = torch.randn(CHUNK, QH, D, generator=gen, device="cuda").to(torch.bfloat16)
        ke = torch.randn(CHUNK, KVH, D, generator=gen, device="cuda").to(torch.bfloat16)
        ve = torch.randn(CHUNK, KVH, D, generator=gen, device="cuda").to(torch.bfloat16)
        qo = torch.tensor([0, CHUNK], dtype=torch.int32, device="cuda")
        kvp = torch.tensor([0, total], dtype=torch.int32, device="cuda")
        idx = torch.arange(total, dtype=torch.int32, device="cuda")
        pl = torch.tensor([prefix], dtype=torch.int32, device="cuda")
        out = torch.empty_like(q)

        def run(c=kc, v=vc, kw=kv_args, o=out):
            extend_paged_attention(q, c, v, qo, kvp, idx, pl, CHUNK, D ** -0.5, out=o, k_extend=ke, v_extend=ve, **kw)

        us = time_graph(run, 5)
        err = None
        if fmt.quantized:
            ref = torch.empty_like(q)
            run(kr, vr, ref_args, ref)
            torch.cuda.synchronize()
            err = (out.float() - ref.float()).abs().max().item()
        rows.append({"kernel": "extend", "prefix": prefix, "us": us, "max_err_vs_dequant": err})
        print(json.dumps(rows[-1]), flush=True)

    with open(args.output, "w") as f:
        json.dump({"fmt": args.fmt, "rows": rows}, f, indent=2)


if __name__ == "__main__":
    main()
xcompile_main.py (ROCm cross-compile isolation check)
"""Cross-compile decode stage 1 (main >= #900 signature) for a ROCm target and hash its instruction stream (no launch)."""
import hashlib
import re
import sys

import torch
import triton.language as tl
from triton.backends.compiler import GPUTarget
from triton.runtime import driver

arch, head_dim = sys.argv[1], int(sys.argv[2])
driver.active.get_current_target = lambda: GPUTarget("hip", arch, 32)
import freetoken.kernel.triton.attention as A  # noqa: E402

fn = A._decode_grouped_stage1_kernel
has_f16 = "F16_KV" in fn.arg_names
H, KVH, D = 8, 2, head_dim
dev = "cuda"
for rows in (1, 4):
    q = torch.zeros(rows, H, D, dtype=torch.bfloat16, device=dev)
    idx = torch.arange(512, dtype=torch.int32, device=dev)
    indptr = torch.tensor([0, 512], dtype=torch.int32, device=dev)
    qo = torch.tensor([0, rows], dtype=torch.int32, device=dev)
    qpos = torch.arange(512 - rows, 512, dtype=torch.int32, device=dev)
    logits = torch.zeros(rows, H, 64, D, device=dev)
    lse = torch.zeros(rows, H, 64, device=dev)
    cases = [("fp8_per_token_head", torch.uint8, 1, 32, 2, 4), ("int8_per_token_head", torch.int8, 1, 32, 2, 4),
             ("none", torch.bfloat16, 1, 32, 3, 4)]
    if rows == 1 and D == 128:
        cases.insert(0, ("fp8_per_token_head", torch.uint8, 4, 64, 1, 4))
    for fmt, dt, pack, bn, st, wp in cases:
        kc = torch.zeros(1024, KVH, D, dtype=dt, device=dev)
        vc = torch.zeros_like(kc)
        ks = torch.zeros(1024, KVH, device=dev)
        vs = torch.zeros_like(ks)
        args = [q, kc, vc, ks, vs, D ** -0.5, indptr, idx, qo, qpos, logits, lse, 64,
                q.stride(0), q.stride(1), kc.stride(0), kc.stride(1), vc.stride(0), vc.stride(1),
                ks.stride(0), vs.stride(0), logits.stride(0), logits.stride(1), logits.stride(2),
                lse.stride(0), lse.stride(1), lse.stride(2)]
        kw = dict(KV_OFFSET_DTYPE=tl.int32, KV_FMT=fmt, KV_PACK=pack, GROUP=4, NUM_Q_HEADS=H, ROWS=rows,
                  BLOCK_D=D, BLOCK_DV=D, BLOCK_N=bn, BLOCK_H=4, VALID_BLOCK_H=4, MIN_BLOCK_KV=32, MIN_SPLIT_LEN=128,
                  MIN_SPLITS=8, D=D, DV=D, SLIDING_WINDOW=0, num_warps=wp, num_stages=st)
        if has_f16:
            kw["F16_KV"] = False
        asm = fn.warmup(*args, grid=(1,), **kw).asm["amdgcn"]
        target = re.search(r"amdgcn-amd-amdhsa--(gfx\w+)", asm).group(1)
        instr = [l.split("//")[0].strip() for l in asm.splitlines()
                 if re.match(r"\s+(v|s|global|buffer|ds|scratch)_[a-z0-9_]+", l)]
        print(f"D={D} rows={rows} {fmt:20s} pack={pack} target={target} instrs={len(instr)} "
              f"sha={hashlib.sha256(chr(10).join(instr).encode()).hexdigest()[:16]}")

@jason-fxz

jason-fxz commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

@zihaomu
Thanks for the detailed write-up and numbers.

Prefill: please drop it from this PR. For prefill we want the E4M3 decode to happen inside the extend kernel, not as an explicit dequantization of the KV cache into a BF16 copy before it. dequant_kv_rows allocates kv_indices.numel() rows of K and V on every layer call, so this transient buffer grows with the batch's total context and is outside the KV memory budget. When spec-decode verify with more than MAX_DECODE_ROWS rows per request is captured in a CUDA graph, the extend path gets capture.page_table.view(-1) as kv_indices, so the buffer is max_bs x max_seq_len rows whatever the real context is. I saw your measurement of an in-kernel fp16 reader in _extend_attend_tile (48.3 ms vs 35.1 ms per chunk at a 62K prefix); work on that in-kernel path can go in a separate PR, and this one can stay decode-only.

Decode looks correct. I ran the decode path on an H100 with the gate forced on and the v_mov_b32 pin replaced by a PTX mov.b32, so this checks the kernel logic and numerics, not gfx11 codegen. I compared it against an fp32 reference on the dequantized rows in 47 cases: head_dim 64/128/256/512, GQA groups 1/4/6/8/16, mixed-length batches and contexts from 1 to 131072 keys, sliding window 128, sinks, V scaled from 1e-4 to 100, and Q or K scaled by 30. In every case the fp16 path's max relative error was at most that of the current fp8 path, and all outputs were finite. All 254 finite E4M3 codes also match torch.float8_e4m3fn bit for bit.

No change on CUDA. On an H100, 01f3b47 and cf44001 give bit-identical decode outputs and the same split caps in 144 configs (bf16 / fp8 / int8 KV, head_dim 64-512, three head layouts, with and without a sliding window, two batch shapes), and the 89 decode kernels they compile have identical PTX.

For the rebase, please follow the structure PR 897 landed with on main:

  • The gfx1201 gate is now _use_gfx12_fp8_reader in attention.py, using get_rocm_gfx_arch(), and kv_rows.py keeps only the tile helpers (the gfx12 tile is the private _kv_tile_gfx12_bf16). The gfx11 gate should be a private predicate next to it, also on get_rocm_gfx_arch(), instead of _gfx11 and kv_f16_reader in kv_rows.py. A name like _use_gfx11_f16_reader also reads as the boolean it is, and the tile can be private as _kv_tile_gfx11_f16.
  • kv_decode_config is gone on main, and decode now serves up to MAX_DECODE_ROWS query rows per request. If the fp16 reader is enabled for more than one row, the decode test should cover that case.
  • The decode_paged_attention docstring still gives the split count as max(ceil(keys / 128), ...), and the comment on _decode_num_splits says it follows the same rule as _max_request_splits. With a minimum split length of 32 on gfx11, both are wrong for this path, and _max_request_splits still uses 128 for the sliding-window cap.
  • The * 256.0 that pairs with kv_tile_f16's / 256 is applied separately to scale_k and scale_v in stage 1. Keeping it in one place, for example in kv_row_scale, keeps the pairing visible.
  • Tests: main's RDNA4 per-code test skips inline on get_rocm_gfx_arch(), so _require_gfx11 is not needed, and the gfx11 per-code check can be a case next to that test rather than a separate function. Once prefill is removed, the combined prefill and decode test needs to become decode-only. It currently covers only head_dim 256, GQA 4 and batch 1.

@jason-fxz
jason-fxz marked this pull request as ready for review November 27, 2026 00:42
gfx11 has no fp8 converts and lowers fp32 -> bf16 to integer RNE code, so the
generic E4M3 decode dominates grouped decode, repeated for every dot-operand
replica. On gfx11 the decode stage reads each E4M3 code as the fp16 bit pattern
of value/256 (exact for every finite code), pins it to the load layout, restores
the 256 in kv_row_scale and runs fp16 WMMA. It uses 16-key single-stage tiles,
a minimum split length of 32 and up to eight programs per SM.
@zihaomu
zihaomu force-pushed the perf/rdna3-fp8-kv-pr897-followup-20261112 branch from cf44001 to 3422824 Compare November 27, 2026 06:02
@zihaomu zihaomu changed the title perf(attention): fast fp8 kv decode and prefill on rdna3 (gfx11) perf(attention): fast fp8 kv decode on rdna3 (gfx11) Nov 27, 2026
@zihaomu

zihaomu commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

@jason-fxz Thanks for the careful review and for running the H100 checks. I reworked the PR on current main (a7a8236, after #897, #900 and #906); it is now one commit, 3422824, and decode-only.

Prefill dropped. dequant_kv_rows and the extend changes are gone; the extend path is exactly main's. The in-kernel prefill reader will be a separate PR.

Structure follows #897 on main.

  • _use_gfx11_f16_reader(kv_format) sits next to _use_gfx12_fp8_reader in attention.py and uses get_rocm_gfx_arch(). kv_f16_reader and _gfx11 are gone.
  • The tile is the private _kv_tile_gfx11_f16 in kv_rows.py, which otherwise keeps only tile helpers.

Multi-row decode. The reader serves every ROWS <= MAX_DECODE_ROWS, not only one row. _gfx11_f16_decode_launch(rows * block_h) gives 16-key tiles, one stage, and 2 warps up to M = 16 (4 above). These values come from a W7900D sweep over 2/4/8 rows.

Split rule.

  • _max_request_splits(keys, min_split_len) takes the minimum split length, so the sliding-window cap uses 32 on this path.
  • The decode_paged_attention docstring now gives max(ceil(keys / L), ...) with L = 128, or 32 for the gfx11 reader.
  • The _decode_num_splits comment names the shared MIN_SPLIT_LEN.

* 256 in one place. The factor is applied in kv_row_scale(..., F16=True), which pairs with the tile's / 256.

Tests.

  • The per-code check is now a parametrized case of the existing test, renamed test_rocm_kv_decode_preserves_every_finite_fp8_code, with an inline get_rocm_gfx_arch() skip. _require_gfx11 is gone.
  • The combined prefill+decode test is removed. Instead, test_decode_triton_attention_splits_long_requests and test_decode_triton_attention_multi_row_matches_reference now also run with FP8 and INT8 KV against the dequantized reference. On gfx11 the FP8 cases go through the new reader. Together these cover:
    • head_dim 256/512;
    • GQA groups 2/6/8;
    • mixed-length batches up to 8,193 keys;
    • 1 to 8 rows per request;
    • sliding windows and sinks;
    • a scratch smaller than the split cap.
  • The existing test_quantized_kv_attention_matches_dequantized_reference decode and decode_rows cases (head_dim 64 to 512, 4/8/16 heads) also run through the reader on gfx11.

Results on W7900D (gfx1100), commit 3422824.

  • tests/kernels/test_triton_attention.py: 142 passed, 2 skipped (the gfx1201 per-code cases).
  • Backend/KV-pool tests: 62 passed, 4 skipped (sgl_kernel / flashinfer not installed).
  • FREETOKEN_FORCE_E4M3_EMU=1 quantized decode cases: 80 passed.
  • Cross-compiled decode stage 1 for gfx1201 and gfx1200 (D128, 1 and 4 rows, including the perf(attention): add packed fp8 kv reads on gfx1201 #897 packed path) and for gfx1100's other formats: all 20 instruction streams are identical to main.
  • End-to-end on Qwen3.5-0.8B: FP8 decode is 17.5% to 165% faster than main's FP8 path and 0.3% slower to 20% faster than BF16 KV.
  • TTFT is unchanged from main FP8 (prefill is no longer in this PR), so long-context end-to-end time stays dominated by FP8 prefill until that follow-up.

The PR description has the full tables. On CUDA the only changes are the default-False F16 constexpr on kv_row_scale and the kv_format argument to decode_kv_split_cap (the gate is false off ROCm). If it is easy to repeat your H100 PTX comparison on the new head, that would close the loop.

@jason-fxz
jason-fxz merged commit 73150e4 into FlashML-org:main Nov 28, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants