[CK_TILE][FMHA][gfx950] hd256 bf16/fp16 fwd: dispatcher always picks qr before the faster qr_async_trload instance (dead code)

Abierto
#3,781 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
35/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
cpp
Área
performance

Línea de trabajo

Start by reading example/ck_tile/01_fmha/codegen/ops/fmha_fwd.py, especially KernelComponentFactoryGfx950.get_pipelines(), then inspect the generated fmha_fwd_api.cpp branch order using the provided ck_hd256_repro.py order command. The issue reports that the broader qr predicate returns before qr_async_trload; verify this on gfx950 and check the benchmark with force-trload. Done means the trload instance is selected when its constraints hold, with qr still serving cases it does not cover.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Environment

  • GPUs: AMD Instinct MI355X (gfx950, DigitalOcean gpu-mi355x1-288gb-spot, SR-IOV VF) and MI350X (gfx950, gpu-mi350x1-288gb-spot).
  • Container: lmsysorg/sglang:v0.5.20-rocm720-mi35x (sha256:ef84c44150da0f90495953458e7386350ffc50a37b2b9ac6802d9a94c454c6dd).
    • ROCm 7.2.0, hipcc /opt/rocm-7.2.0/bin/hipcc.
    • aiter 0.1.21.dev48 (git 4ad99832823dde2315b361cbd3b54b1c5c12acd5, 2026-08-29).
    • Vendored composable_kernel af9e1d1f1ae347c22feeb08fd2d42645075e0c5d (2026-08-05). torch 2.x ROCm build from the image.
  • Shape: one sequence, causal, 24 query heads / 4 KV heads (GQA 6), head_dim 256, bf16 in/out.
  • PFLOP/s = 4 * T^2/2 * 24 * 256 / time.
  • Error = |out - fp32 reference| on 512-1024 query rows; mean_rel = mean |diff| / mean |ref|.

Description

  • example/ck_tile/01_fmha/codegen/ops/fmha_fwd.py, KernelComponentFactoryGfx950.get_pipelines(), does two things for
    bf16/fp16 (256, 256):
    1. It appends the gfx950-only qr_async_trload pipelines.
    2. It does so after the base gfx9 qr pipelines.
  • The generated fmha_fwd_api.cpp therefore tests the hd256 branches in this order:
    1. qr (sink)
    2. qr padded (sink)
    3. qr (no sink)
    4. qr padded (no sink)
    5. qr_async_trload (sink)
    6. qr_async_trload (no sink)
  • The qr predicate covers every case the trload predicate covers: the same mode, mask, bias, lse, dropout and qscale checks and
    a.hdim_q % 256 == 0. The first qr branch therefore always returns. The trload instances are compiled and linked but unreachable.

Reproducer

# inside the container above, on a gfx950 GPU (modifies aiter's JIT tree in place: use a throwaway container)
python3 ck_hd256_repro.py order                     # prints the hd256 branch order of the generated dispatcher
python3 ck_hd256_repro.py bench 8192 32768          # stock: flash_attn_varlen_func = qr instance
python3 ck_hd256_repro.py force-trload 8192 32768   # move the two trload branches first, ninja-rebuild the module, re-bench
python3 ck_hd256_repro.py restore

force-trload changes only the branch order in the generated fmha_fwd_api.cpp. No kernel code changes.

Expected: on gfx950 the qr_async_trload hd256 instance is used whenever its constraints hold.

Actual: the qr instance is always used.

Measured, full causal (q = kv = T), PFLOP/s

GPU Dispatch 8k 16k 32k 100k 200k
MI355X stock (qr 128x64x32) 0.47 0.53 0.55 - -
MI355X trload forced 0.66 0.67 - 0.77 0.75
MI350X stock (qr) 0.43 - 0.51 0.46 0.44
MI350X trload forced 0.49 - 0.62 0.62 0.61
  • The MI350X rows come from ck_hd256_repro.py bench and force-trload on 2026-10-08.
  • MI355X trload-forced numbers at other lengths: 10k 0.57, 20k 0.72, 40k 0.77.
  • Gain: +15 / +22 / +37 / +41% (MI350X, 8k / 32k / 100k / 200k) and +27-40% (MI355X).
  • Error is unchanged on both GPUs: mean_rel 2.03e-3 vs 2.10e-3 at 8k and 1.79e-3 vs 1.82e-3 at 100k (MI350X, trload vs qr).

Suggested fix: for gfx950, emit the trload branches before the qr branches (or order the API pool by pipeline priority), so that
qr only serves the cases trload does not cover.

ck_hd256_repro.py (167 lines, random tensors only)
#!/usr/bin/env python3
"""Reproducer for three CK-tile / aiter issues with bf16 head_dim-256 causal prefill attention on gfx950 (MI350X / MI355X).
Random tensors only. Run inside lmsysorg/sglang:v0.5.20-rocm720-mi35x (aiter 0.1.21.dev48, CK af9e1d1f, ROCm 7.2) or any aiter
install that has its JIT build tree for mha_varlen_fwd. Subcommands:

  bench            time + check aiter.flash_attn_varlen_func (CK fmha_fwd, group mode) and aiter.mha_batch_prefill_func (CK
                   fmha_batch_prefill, page size 1) against an fp32 reference: 24 q heads / 4 kv heads, hd 256, causal, one sequence.
  order            print the hd256 branch order of the generated fmha_fwd dispatcher (issue A: qr is tested before qr_async_trload
                   with the same predicate, so the gfx950 trload instance is unreachable).
  force-trload     rebuild the JIT module with the dispatcher's hd256 trload branches moved first, then rerun bench (issue A gain).
  bad-tile         add a qr_async_trload instance with tile 64x64x32x256x32x256, 4x1x1 warps, 16x16x32 warp tile (the tile CK lists
                   for gfx1250 bf16 hd256) to the module, select it, rerun bench (issue C: compiles for gfx950, silently wrong output).
  restore          put the original module back.
The rebuilding subcommands modify aiter's JIT tree in place: use a throwaway container. Usage: ck_hd256_repro.py <cmd> [T ...]"""
import json, os, re, shutil, subprocess, sys

MOD = "mha_varlen_fwd_bf16_nlogits_nbias_mask_nlse_ndropout_nskip_nqscale"


def paths():
    import aiter
    root = os.path.dirname(os.path.dirname(aiter.__file__))
    jit = os.path.join(os.path.dirname(aiter.__file__), "jit")
    return root, jit, os.path.join(jit, "build", MOD)


def bench(Ts):
    import torch, aiter
    HQ, HK, D = 24, 4, 256
    S = D ** -0.5
    dev = "cuda"
    for T in Ts:
        g = torch.Generator(device=dev).manual_seed(7)
        q = torch.randn(T, HQ, D, device=dev, generator=g).to(torch.bfloat16)
        k = torch.randn(T, HK, D, device=dev, generator=g).to(torch.bfloat16)
        v = torch.randn(T, HK, D, device=dev, generator=g).to(torch.bfloat16)
        rows = torch.unique(torch.cat([torch.linspace(0, T - 1, 256, device=dev).long(), torch.arange(T - 256, T, device=dev)]))
        kk = k.float().repeat_interleave(HQ // HK, 1).transpose(0, 1)
        vv = v.float().repeat_interleave(HQ // HK, 1).transpose(0, 1)
        R = torch.empty(len(rows), HQ, D, device=dev)
        for s in range(0, len(rows), 64):
            rr = rows[s:s + 64]
            sc = torch.matmul(q[rr].float().transpose(0, 1), kk.transpose(1, 2)) * S
            sc = sc.masked_fill(torch.arange(T, device=dev)[None, :] > rr[:, None], float("-inf"))
            R[s:s + 64] = torch.matmul(torch.softmax(sc, -1), vv).transpose(0, 1)
        cu = torch.tensor([0, T], device=dev, dtype=torch.int32)
        idx = torch.arange(T, device=dev, dtype=torch.int32)
        fns = {"flash_attn_varlen_func (CK fmha_fwd)": lambda: aiter.flash_attn_varlen_func(q, k, v, cu, cu, T, T, softmax_scale=S, causal=True),
               "mha_batch_prefill_func (CK batch_prefill, page 1)": lambda: aiter.mha_batch_prefill_func(q, k, v, cu, cu, idx, T, T, softmax_scale=S, causal=True)}
        for name, fn in fns.items():
            o = fn(); o = o[0] if isinstance(o, (tuple, list)) else o
            torch.cuda.synchronize()
            st, en = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
            ts = []
            for _ in range(3):
                st.record(); fn(); en.record(); torch.cuda.synchronize(); ts.append(st.elapsed_time(en))
            ms = sorted(ts)[1]
            d = (o[rows].float() - R).abs()
            print(json.dumps({"T": T, "fn": name, "AK_D256": os.environ.get("AK_D256"), "ms": round(ms, 3),
                              "pflops": round(4 * T * T / 2 * HQ * D / ms / 1e12, 3), "max_abs": float(d.max()),
                              "mean_rel": float(d.mean() / R.abs().mean())}), flush=True)


def order():
    _, _, B = paths()
    api = open(os.path.join(B, "blob", "fmha_fwd_api.cpp")).read()
    i = api.find("t.hdim_q <= 256 && t.hdim_v <= 256")
    seg = api[i:i + 12000]
    seg = seg[:seg.find("\n            }\n")] if "\n            }\n" in seg else seg
    for n, m in enumerate(re.finditer(r"fmha_fwd_traits_<256, FmhaFwdBf16, true, *(\d+), *(\d+), *(\d+),[^>]*?BlockFmhaPipelineEnum::(\w+)[^;]*?(true|false)>;", seg)):
        print(n, "tile", "x".join(m.group(i) for i in (1, 2, 3)), "pipeline", m.group(4), "sink", m.group(5))
    print("(first matching branch wins; the qr branches' predicate (a.hdim_q % 256 == 0 ...) is identical to the trload branches')")


def _backup():
    _, jit, B = paths()
    os.makedirs("/tmp/ckrepro", exist_ok=True)
    if not os.path.exists("/tmp/ckrepro/orig.so"):
        shutil.copy(os.path.join(jit, MOD + ".so"), "/tmp/ckrepro/orig.so")
        shutil.copy(os.path.join(B, "blob", "fmha_fwd_api.cpp"), "/tmp/ckrepro/orig_api.cpp")
        shutil.copy(os.path.join(B, "build", "build.ninja"), "/tmp/ckrepro/orig_build.ninja")
    root, _, _ = paths()
    meta = os.path.join(root, "aiter_meta")       # the image's ninja file points at aiter_meta/, which the image no longer ships
    if not os.path.exists(meta):
        os.symlink(root, meta)


def _build_install():
    _, jit, B = paths()
    r = subprocess.run(["ninja", "-j", str(os.cpu_count())], cwd=os.path.join(B, "build"), capture_output=True, text=True)
    if r.returncode:
        print(r.stdout[-3000:], r.stderr[-2000:]); sys.exit("build failed")
    shutil.copy(os.path.join(B, "build", MOD + ".so"), os.path.join(jit, MOD + ".so"))


def force_trload():
    _backup()
    _, _, B = paths()
    api = open("/tmp/ckrepro/orig_api.cpp").read()
    i = api.find("            else if(t.hdim_q <= 256 && t.hdim_v <= 256) {\n")  # first occurrence = the gfx950 section
    j = api.find("\n            }\n", i)
    body = api[i:j]
    hdr, rest = body.split("\n", 1)
    branches = re.split(r"\n(?=                (?:else )?if\()", "\n" + rest)
    branches = [b for b in branches if b.strip()]
    tr = [b for b in branches if "QRKSVS_ASYNC_TRLOAD" in b]
    other = [b for b in branches if "QRKSVS_ASYNC_TRLOAD" not in b]
    new = [re.sub(r"^\s*(else )?if\(", "                if(" if n == 0 else "                else if(", b.lstrip("\n"), count=1)
           for n, b in enumerate(tr + other)]
    api = api[:i] + hdr + "\n" + "\n".join(new) + api[j:]
    open(os.path.join(B, "blob", "fmha_fwd_api.cpp"), "w").write(api)
    shutil.copy("/tmp/ckrepro/orig_build.ninja", os.path.join(B, "build", "build.ninja"))
    _build_install()
    print("rebuilt with hd256 qr_async_trload branches first")


def bad_tile():
    _backup()
    _, _, B = paths()
    tpl = os.path.join(B, "blob", "fmha_fwd_d256_bf16_group_b128x64x32x256x32x256_r4x1x1_r4x1x1_w32x32x16_w32x32x16_"
                       "qr_async_trload_vr_pssk_nlogits_nbias_mask_nlse_ndropout_nskip_nqscale_trload_nsink_gfx950.cpp")
    src = open(tpl).read()
    src = src.replace("ck_tile::sequence<128, 64, 32, 256, 32, 256>", "ck_tile::sequence<64, 64, 32, 256, 32, 256>")
    src = src.replace("ck_tile::sequence<32, 32, 16>", "ck_tile::sequence<16, 16, 32>")
    src = src.replace("true,128, 64, 32, 256, 32, 256, true,", "true,64, 64, 32, 256, 32, 256, true,")
    src = src.replace("fmha_fwd_d256_bf16_group_b128x64x32x256x32x256_r4x1x1_r4x1x1_w32x32x16_w32x32x16_qr_async_trload_vr_pssk", "repro_d256_b64x64_w16x16x32")
    name = "repro_d256_b64x64_w16x16x32"
    open(os.path.join(B, "blob", name + ".cpp"), "w").write(src)
    trait = ("fmha_fwd_traits_<256, FmhaFwdBf16, true,64, 64, 32, 256, 32, 256, true, ck_tile::BlockFmhaPipelineEnum::QRKSVS_ASYNC_TRLOAD, "
             "false, ck_tile::SimplifiedGenericAttentionMask<true>, ck_tile::BlockAttentionBiasEnum::NO_BIAS, false, false, "
             "ck_tile::BlockAttentionQuantScaleEnum::NO_SCALE, true, true, false, false, true, false, false>")
    api = open("/tmp/ckrepro/orig_api.cpp").read()
    anchor = "            else if(t.hdim_q <= 256 && t.hdim_v <= 256) {\n"
    i = api.find(anchor) + len(anchor)
    api = api[:i] + ("                if((t.is_group_mode == true) && (t.mask_type != mask_enum::no_mask) && (t.has_lse == false) && (t.has_sink == false) "
                     "&& (t.bias_type == bias_enum::no_bias) && (t.has_dropout == false) && (a.hdim_q == 256) && (a.hdim_v == 256)) {\n"
                     f"                    using trait_ = {trait};\n                    return fmha_fwd_<trait_, ck_tile::gfx950_t>(s, a);\n                }}\n") + api[i:]
    open(os.path.join(B, "blob", "fmha_fwd_api.cpp"), "w").write(api)
    nin = open("/tmp/ckrepro/orig_build.ninja").read()
    obj = name + ".cuda.o"
    nin = nin.replace(f"build {MOD}.so: link ", f"build {MOD}.so: link {obj} ")
    nin = nin.replace("\nbuild fmha_fwd_api.cuda.o:", f"\nbuild {obj}: cuda_compile {os.path.join(B, 'blob', name + '.cpp')}\n\nbuild fmha_fwd_api.cuda.o:", 1)
    open(os.path.join(B, "build", "build.ninja"), "w").write(nin)
    _build_install()
    print("rebuilt with the 64x64 / 16x16x32 hd256 trload instance dispatched first (it compiles without any static_assert)")


def restore():
    _, jit, B = paths()
    shutil.copy("/tmp/ckrepro/orig.so", os.path.join(jit, MOD + ".so"))
    shutil.copy("/tmp/ckrepro/orig_api.cpp", os.path.join(B, "blob", "fmha_fwd_api.cpp"))
    shutil.copy("/tmp/ckrepro/orig_build.ninja", os.path.join(B, "build", "build.ninja"))
    print("restored")


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "bench"
    Ts = [int(x) for x in sys.argv[2:]] or [8192, 32768]
    if cmd == "bench":
        bench(Ts)
    elif cmd == "order":
        order()
    elif cmd in ("force-trload", "bad-tile"):
        (force_trload if cmd == "force-trload" else bad_tile)()
        subprocess.run([sys.executable, __file__, "bench"] + [str(t) for t in Ts])   # fresh process loads the rebuilt module
    elif cmd == "restore":
        restore()

Lenguaje dominante
C++
Estrellas
552
Forks
316
Merge medio
3 d 14 h
PR fusionados (30 d)
2

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de ROCm/composable_kernel

Todos los issues de ROCm/composable_kernel

Issues similares

Más issues de C++

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.