Skip to content

[Triton/Gluon] [Perf] unified_attention: split KV by actual sequence lengths under CUDA graphs (gfx950, head 64, bf16 Q / fp8 KV) - #7088

Open
yuychang wants to merge 3 commits into
ROCm:mainfrom
yuychang:k3/unified-attn-d64-bf16-fp8-kvsplit
Open

yuychang wants to merge 3 commits into
ROCm:mainfrom
yuychang:k3/unified-attn-d64-bf16-fp8-kvsplit

Conversation

@yuychang

@yuychang yuychang commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • On gfx950, split each request's KV range by its real length (seqused_k, read on the GPU).
    • Before: the split followed max_seqlen_k, which a CUDA graph captures as a 1M bound.
  • Scope: Triton 3D kernel, all of the following:
    • bf16 Q, fp8 KV.
    • Head dim 64 (Q/K and V).
    • Up to 4 query heads per KV head.
    • No sliding window.
    • One query block per sequence.
    • A derived per-sequence cap (SPLIT_NUM_SEGMENTS) above 1.
  • Enabled by new keys in the gfx950 JSON config.
    • On by default for every call in that scope, graph or eager.
    • There is no caller flag or env opt-out.
  • Rollback: delete SPLIT_PROGRAMS_PER_CU from the gfx950 kv_split entry.
    • The launcher then keeps the uniform split (covered by test_length_aware_split_scope).
  • Groups above 4 (GPT-OSS TP8 8 Q / 1 KV, TP1 64 Q / 8 KV) keep the uniform split.

Motivation

  • SGLang captures decode/verify graphs with max_seqlen_k = 1M, so every request gets the same segment count.
  • In a skewed batch (one 120K request among short ones) the long request bounds the batch.
    • 280–774 µs on main.
  • The launcher cannot read real lengths on the host without a sync, which a graph forbids.

Changes

  • Kernels compute each sequence's segment count on the GPU from seqused_k (int32 or int64).
    • A flat grid of (sequence, segment) work items per KV head.
      • split_budget + num_seqs - 1 items at most.
    • ITEM_RUN groups an item's KV heads on one XCD.
      • It shrinks for small batches.
  • Partials are slot-major [segment, token, head].
    • The reduce merges exactly the segments each sequence used.
  • compute_segment_params derives SPLIT_NUM_SEGMENTS from SPLIT_SEGMENTS_PER_CU.
    • NUM_SEGMENTS (uniform split) is unchanged.
  • New gfx950 config keys, used only on a length-aware launch:
Entry Key Value Meaning
kv_split D_EQ_64.G_LEQ_4.DT_bf16_fp8 SPLIT_PROGRAMS_PER_CU 4 The opt-in; programs per CU the batch shares
kv_split D_EQ_64.G_LEQ_4.DT_bf16_fp8 SPLIT_SEGMENTS_PER_CU 32 Cap on one sequence's segments
kv_split D_EQ_64.G_LEQ_4.DT_bf16_fp8 SPLIT_SEQ_BLOCK_MIN/MAX 64/256 Sequence block bounds
attn_3d (any, D_LEQ_128.Q_GEQ_4) SPLIT_RUNS_PER_XCD 16 Runs per XCD
attn_3d D_LEQ_128.Q_GEQ_4 SPLIT_BLOCK_M 16 Also set on this entry
reduce SPLIT_SEGMENT_BLOCK_MIN 16 Reduce segment block minimum
  • The kv_split schema gains a G axis (queries per KV head) after D.
  • The uniform split stays for:
    • More than 4 query heads per KV head (not tuned).
    • Other dtypes/head dims and asymmetric heads (32,64)/(64,32) (not tuned).
    • skip_reduce (callers read the uniform layout).
    • Sliding window.
    • More than one query block per sequence.
    • num_seqs >= 2**15 / split_budget + num_seqs >= 2**16 / int32 overflow bounds.
    • The Gluon 3D kernel and Gluon reduce (they read the uniform token-major partials).
  • Merged main ([Triton/Gluon] Window-aware split-KV for sliding-window verify on gfx950 #6889, [Triton/Gluon] [gfx950] unified_attention: split-KV 3D configs for head_size <= 128 keyed on max_seqlen_q #6983): the attn_3d D_LEQ_128.Q_GEQ_4 entry gets two keys.
    • SPLIT_RUNS_PER_XCD: without it, q >= 4 calls fall back to the uniform split (0688eb5a0d).
    • SPLIT_BLOCK_M: 16: BLOCK_M 32 padded q4 blocks to 2x rows.
  • Merged main 4ba20eba9b (b0318b2d5): the only conflict was aiter/ops/triton/attention/unified_attention.py.
  • Merged main 95f38f953 (ae1db9dca): the only conflict was the import block of test_unified_attention.py.
    • functools from this branch, os from main.
    • No kernel or launcher change.
  • Docs: SPLIT_* keys in configs/AGENTS.md, aiter/ops/triton/README.md, Copilot instructions, utils docstring.

Performance (if applicable)

  • Author run, first table (MI355X; bf16 Q / fp8 KV, head 64, page 128, 8 Q / 2 KV heads unless noted):
    • Script bench_ua_split.py (below).
      • One CUDA graph per workload at max_seqlen_k = 1M.
      • 1 GiB write before each of 40 replays (evicts L2 and MALL).
      • Median per round, best of 3 alternating rounds on one GPU.
    • Before = main e4973c4bed.
    • After = 12f033ff57, an early head of this branch that is not in the current history.
      • It predates the group-4 scoping (later tables supersede it for the scoped shapes).
    • Kernel latency only; ROCm version not recorded.
    • Skewed = one 120K request plus seeded 200–3000-token requests.
Hardware Workload/configuration Before (µs) After (µs) Change
MI355X 1×8K, q1, 64 Q / 64 KV heads 40.00 34.82 1.15× faster
MI355X Skewed 32 requests, q4 280.02 51.28 5.46× faster
MI355X Skewed 64 requests, q1 323.96 47.72 6.79× faster
MI355X Skewed 300 requests, q1 774.20 125.14 6.19× faster
MI355X Uniform 64×8K, q4 79.26 69.12 1.15× faster
MI355X Uniform 128×4K, q4 79.22 68.30 1.16× faster
MI355X Uniform 64×64K, q1 236.22 236.26 1.00×
MI355X Uniform 8×2K, q1 16.92 18.96 0.89× (+2.04 µs)
MI355X Uniform 256×2K, q1 44.32 46.88 0.95× (+2.56 µs)
  • Review run at head d507d3c1a vs its merge base 5c1489c24:
    • Later commits: 23037623c test, 6fd883da2 docs, main merges.
    • MI355X (gfx950), ROCm 10.0.0, torch 2.11.0+rocm10.0.0.
    • Same script plus --set gptoss / --bound real (below), best of 3 alternating rounds.
    • Rows with 8 Q / 1 KV or 64 Q / 8 KV heads are group 8 and take the uniform split on both sides.
Hardware Workload/configuration Before (µs) After (µs) Change
MI355X 256×1K, q1, 8 Q / 1 KV heads (GPT-OSS TP8) 22.70 22.64 1.00×
MI355X 256×1K, q1, 8 Q / 1 KV heads, sinks 22.62 22.66 1.00×
MI355X 128×1K, q1, 8 Q / 1 KV heads, sinks 17.28 17.56 0.98×
MI355X 64×2K, q1, 8 Q / 1 KV heads 17.20 17.12 1.00×
MI355X 64×2K, q1, 64 Q / 8 KV heads, sinks (GPT-OSS TP1) 44.88 45.30 0.99×
MI355X Uniform 64×64K, q1, 64 Q / 8 KV heads 1017.61 1013.17 1.00×
  • With max_seqlen_k set to the real maximum instead of 1M, the same rows are 1.00× (0.98–1.00× in all six).
  • Before the group scoping, the same rows measured 0.84–0.99×.
    • 256×1K 8 Q / 1 KV: 22.58 → 26.80 µs (9c02c030a).
  • Trade-off, Kimi shapes (group ≤ 4): short-context decode is 3–12% slower.
    • Cause: each workgroup first scans the batch lengths.
    • At the graph bound: 8×2K q1 is 0.88× and 256×2K q1 0.97×.
    • At the real maximum: 0.92× and 0.94×.
    • The split is not gated by length or batch inside the scope; it applies in eager mode too.
    • The same run on Kimi shapes: skewed64 q1 7.39×, skewed32 q4 5.18×, 64×8K q4 1.14×, 1×8K 64/64 1.18×.
  • SPLIT_BLOCK_M (author, same method, length-aware launch at BLOCK_M 32 → 16):
  • Review-fix re-run at acd39a137 vs b6997bdce: every workload within ±1%, output checksums matched.
  • Merged head b0318b2d5 vs main 4ba20eba9b (its second parent, so the diff is this PR alone):
    • MI355X (gfx950), GPU 0, ROCm 10.0.0, torch 2.11.0+rocm10.0.0, Triton 3.8.0, bench_ua_split.py.
    • 2 alternating rounds, best of 2; speedup at the 1M graph bound (at the real maximum in parentheses).
Hardware Workload/configuration Before (µs) After (µs) Change
MI355X Skewed 32 requests, q4 270.76 53.32 5.08× (5.05×)
MI355X Skewed 64 requests, q1 325.64 44.48 7.32× (7.35×)
MI355X Skewed 300 requests, q1 784.19 126.24 6.21× (6.25×)
MI355X 1×8K, q1, 64 Q / 64 KV heads 36.94 31.32 1.18× (1.17×)
MI355X Uniform 64×8K, q4 79.28 70.08 1.13× (1.15×)
MI355X Uniform 128×4K, q4 79.20 68.72 1.15× (1.16×)
MI355X Uniform 64×64K, q1 233.44 236.02 0.99× (1.00×)
MI355X Uniform 8×2K, q1 13.68 15.14 0.90× (0.93×)
MI355X Uniform 256×2K, q1 41.52 45.36 0.92× (0.92×)
MI355X 256×1K, q1, 8 Q / 1 KV heads (GPT-OSS TP8) 22.68 22.76 1.00× (0.99×)
MI355X 256×1K, q1, 8 Q / 1 KV heads, sinks 22.88 22.72 1.01× (0.99×)
MI355X 128×1K, q1, 8 Q / 1 KV heads, sinks 17.48 17.08 1.02× (1.01×)
MI355X 64×2K, q1, 8 Q / 1 KV heads 17.26 17.18 1.00× (1.01×)
MI355X 64×2K, q1, 64 Q / 8 KV heads, sinks 46.60 46.40 1.00× (1.01×)
  • Values are the 1M graph bound with the real-maximum bound in parentheses.
    • Best of 2 rounds, from the run's 7088-bench.log.
  • Short-context decode (8×2K, 256×2K q1) is 0.90–0.93× at the merged head (+0.9 to +3.8 µs).
Benchmark scripts
  • Run: ./run_bench.sh <gpu> <main-tree> <head-tree> 3 for the Kimi rows at the 1M bound.
  • For the GPT-OSS rows and the real-maximum bound, run bench_ua_split.py directly.
    • Flags: --set gptoss / --bound real.
    • The wrapper does not forward them.
  • bench_ua_split.py:
"""Graph-replay latency of aiter unified_attention (gfx950, bf16 Q / fp8 KV, head 64, page 128).

Captures one CUDA graph per workload with max_seqlen_k = 1M (the bound sglang
captures), evicts L2 before each replay, and prints the median replay time.
Run it once per tree, e.g. with PYTHONPATH pointing at the tree under test:

    PYTHONPATH=/path/to/aiter python bench_ua_split.py --tag head --out head.json
"""

import argparse
import json
import random
import statistics

import torch

from aiter.ops.triton.attention.unified_attention import unified_attention


def fp8_dtype():
    from aiter.ops.triton.utils.types import e4m3_dtype

    return e4m3_dtype


def skewed(n, q, seed=7):
    rng = random.Random(seed)
    return [(q, 120_000)] + [(q, rng.randint(200, 3000)) for _ in range(n - 1)]


WORKLOADS = {
    "1x8K q1 64/64": ([(1, 8192)], (64, 64)),
    "skewed32 q4": (skewed(32, 4), (8, 2)),
    "skewed64 q1": (skewed(64, 1), (8, 2)),
    "skewed300 q1": (skewed(300, 1), (8, 2)),
    "64x8K q4": ([(4, 8192)] * 64, (8, 2)),
    "128x4K q4": ([(4, 4096)] * 128, (8, 2)),
    "64x64K q1": ([(1, 65536)] * 64, (8, 2)),
    "64x64K q1 64/8": ([(1, 65536)] * 64, (64, 8)),
    "8x2K q1": ([(1, 2048)] * 8, (8, 2)),
    "256x2K q1": ([(1, 2048)] * 256, (8, 2)),
}

GPTOSS = {  # (workload, heads, sinks)
    "256x1K q1 8/1": ([(1, 1024)] * 256, (8, 1), False),
    "256x1K q1 8/1 sinks": ([(1, 1024)] * 256, (8, 1), True),
    "128x1K q1 8/1 sinks": ([(1, 1024)] * 128, (8, 1), True),
    "64x2K q1 8/1": ([(1, 2048)] * 64, (8, 1), False),
    "64x2K q1 64/8 sinks": ([(1, 2048)] * 64, (64, 8), True),
}

DRAFT = {  # Kimi-K3 DSpark draft verify at TP8 (#7244)
    f"{n}x{k // 1000}K q4": ([(4, k)] * n, (8, 2))
    for n, k in [
        (1, 350_000),
        (4, 350_000),
        (16, 120_000),
        (32, 120_000),
        (56, 120_000),
        (56, 30_000),
    ]
}


def build(seq_lens, heads, block_size=128, head=64, causal=True, sinks=False, bound="graph"):
    torch.manual_seed(0)
    hq, hk = heads
    qlens = [q for q, _ in seq_lens]
    kvlens = [k for _, k in seq_lens]
    blocks = [(k + block_size - 1) // block_size for k in kvlens]
    nblocks = sum(blocks)
    maxb = max(blocks)
    dt = fp8_dtype()
    q = torch.randn(sum(qlens), hq, head, device="cuda", dtype=torch.bfloat16)
    k = torch.randn(nblocks, block_size, hk, head, device="cuda").to(dt)
    v = torch.randn(nblocks, block_size, hk, head, device="cuda").to(dt)
    perm = torch.randperm(nblocks, device="cuda", dtype=torch.int32)
    bt = torch.zeros(len(seq_lens), maxb, dtype=torch.int32, device="cuda")
    off = 0
    for i, b in enumerate(blocks):
        bt[i, :b] = perm[off : off + b]
        off += b
    cu = torch.tensor([0] + qlens, device="cuda").cumsum(0, dtype=torch.int32)
    seqused = torch.tensor(kvlens, device="cuda", dtype=torch.int32)
    out = torch.empty(sum(qlens), hq, head, device="cuda", dtype=torch.bfloat16)
    one = torch.ones(1, device="cuda", dtype=torch.float32)
    args = dict(
        q=q,
        k=k,
        v=v,
        out=out,
        cu_seqlens_q=cu,
        seqused_k=seqused,
        max_seqlen_q=max(qlens),
        max_seqlen_k=(1 << 20) if bound == "graph" else max(kvlens),
        softmax_scale=head**-0.5,
        causal=causal,
        window_size=(-1, -1),
        block_table=bt,
        softcap=0,
        q_descale=None,
        k_descale=one,
        v_descale=one,
    )
    if sinks:
        args["sinks"] = torch.randn(hq, device="cuda", dtype=torch.bfloat16)
    return args


def bench(args, replays, flush):
    for _ in range(3):
        unified_attention(**args)
    torch.cuda.synchronize()
    g = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g):
        unified_attention(**args)
    times = []
    for _ in range(replays):
        flush.zero_()
        s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(
            enable_timing=True
        )
        s.record()
        g.replay()
        e.record()
        e.synchronize()
        times.append(s.elapsed_time(e) * 1000)
    out = args["out"].float()
    return statistics.median(times), float(out.abs().sum())


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tag", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--replays", type=int, default=40)
    ap.add_argument("--only", nargs="*")
    ap.add_argument("--set", choices=["split", "draft", "gptoss"], default="split")
    ap.add_argument("--non-causal", action="store_true")
    ap.add_argument("--bound", choices=["graph", "real"], default="graph")
    a = ap.parse_args()
    flush = torch.empty(1 << 30, dtype=torch.uint8, device="cuda")  # 1 GiB > L2+MALL
    res = {}
    table = {"split": WORKLOADS, "draft": DRAFT, "gptoss": GPTOSS}[a.set]
    for name, spec in table.items():
        seq_lens, heads = spec[:2]
        sinks = spec[2] if len(spec) > 2 else False
        if a.only and name not in a.only:
            continue
        args = build(seq_lens, heads, causal=not a.non_causal, sinks=sinks, bound=a.bound)
        us, checksum = bench(args, a.replays, flush)
        res[name] = {"us": us, "checksum": checksum}
        print(f"{a.tag:6s} {name:18s} {us:9.2f} us", flush=True)
        del args
        torch.cuda.empty_cache()
    json.dump(res, open(a.out, "w"), indent=1)


if __name__ == "__main__":
    main()
  • run_bench.sh:
#!/usr/bin/env bash
# Alternating main-vs-head rounds on one GPU. usage: run_bench.sh <gpu> <main-tree> <head-tree> [rounds]
G=$1; MAIN=$2; HEAD=$3; R=${4:-3}
D=$(cd "$(dirname "$0")" && pwd)
PY=${PY:-python3}
for r in $(seq 1 $R); do
  for side in main head; do
    T=$MAIN; [[ $side == head ]] && T=$HEAD
    (cd /tmp && HIP_VISIBLE_DEVICES=$G PYTHONPATH=$T AITER_JIT_DIR=/tmp/aiter-jit-bench-$side \
      $PY -I -c "import sys; sys.path.insert(0, '$T'); sys.argv=['b','--tag','$side','--out','$D/bench_${side}_r$r.json']; exec(open('$D/bench_ua_split.py').read())")
  done
done
$PY - "$D" "$R" <<'PY'
import json, sys
d, R = sys.argv[1], int(sys.argv[2])
best = {s: {} for s in ("main", "head")}
for s in best:
    for r in range(1, R + 1):
        for k, v in json.load(open(f"{d}/bench_{s}_r{r}.json")).items():
            best[s][k] = min(best[s].get(k, 1e18), v["us"])
print("| Workload | Main (µs) | Head (µs) | Speedup |\n|---|---:|---:|---:|")
for k in best["main"]:
    m, h = best["main"][k], best["head"][k]
    print(f"| {k} | {m:.2f} | {h:.2f} | {m / h:.2f}× |")
PY

Testing

Revision Selection Result
main e4973c4bed Whole file 2636 passed; 2208 skipped; 0 failed
this PR f732d9af02 Whole file 2649 passed; 2208 skipped; 0 failed
acd39a137 Whole file 2649 passed; 2208 skipped; 0 failed
#7244 on top (e7fcdde3ee) Whole file 2997 passed; 2208 skipped; 0 failed
acd39a137 -k "long_kv or length_aware or graph_replay or split_scope" 13 passed
9c02c030a -k "length_aware or rel_l2" 17 passed, 0 failed
23037623c Whole file, same deselect 2747 passed, 2963 skipped, 0 failed
6fd883da2 -k "length_aware or split_scope or rel_l2 or long_kv" 18 passed (docs-only commit)
merged head b0318b2d5 Whole file, no deselect 2800 passed, 2963 skipped, 0 failed, in two independent runs
cfde66b86 -k "length_aware or split_scope or rel_l2 or long_kv" 18 passed, 0 failed
pushed head ae1db9dca Whole file, no deselect 2812 passed, 2963 skipped, 0 failed (7088-full.log)
pushed head 4456f7450 Whole file 2814 passed, 2963 skipped, 0 failed
  • 23037623c environment: MI355X, ROCm 10.0.0, torch 2.11.0+rocm10.0.0, Triton 3.8.0.
  • b0318b2d5 environment: MI355X, GPU 0, ROCm 10.0.0, torch 2.11.0+rocm10.0.0, Triton 3.8.0.
  • cfde66b86 and later: same host.
  • cfde66b86: with seq_num_segments forced to one segment (copy in /tmp, reverted):
    • -k length_aware fails 12 of 16.
    • The new partials check reports the unwritten slots.
  • 4456f7450: the new sinks (8 Q / 2 KV) and single_8k length-aware cases compare against the reference.
    • single_8k is 1 sequence, 64 Q / 64 KV, shortest ITEM_RUN.
  • Black and Ruff pass.
  • MI250X: not tested.
  • MI300X: not rerun at the merged head.
    • 4efe46133c records the length-aware and long-KV tests passing there (19 cases, gfx950 tables pinned).
    • The opt-in entry exists only for gfx950.
  • Check: explain("kv_split", ...) on gfx950 matches:
    • D_EQ_64.G_LEQ_4.DT_bf16_fp8 for 8 Q / 2 KV and 64 Q / 64 KV.
    • D_LEQ_64 (the entry main uses) for 8 Q / 1 KV and 64 Q / 8 KV.

Documentation

  • Docstrings updated

  • User guide updated

  • Performance guide updated

  • No documentation change is needed, with the reason stated below

  • SPLIT_* keys and the G_LEQ_4 scope are documented in:

    • configs/AGENTS.md.
    • aiter/ops/triton/README.md.
    • The Copilot instructions.
    • The utils docstring.

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

  • None.
  • Latency trade-off inside the scope (short-context decode 3–12% slower): see Performance.

PR Self-Review

Reviewed revision

  • 4456f74506b4db8366cd56cba91b42bcb9ea8e9f
  • b0318b2d5 merges main 4ba20eba9b; see Changes for the one conflict and how it was resolved.
  • cfde66b86 (test only):
    • NaN-fills segm_max in the launch spy.
    • Asserts the slot-major entries the 3D kernel wrote per sequence.
  • ae1db9dca merges main 95f38f953.
    • One conflict: the import block of the test file, both sides kept.
  • 9c02c030a, d8b4be493, ede8629bb only shorten docstrings/comments.
  • c05579a79 documents the SPLIT_* keys.
  • d507d3c1a scopes the opt-in to up to 4 query heads per KV head (config key, test, docs).
  • 23037623c is a test fix.
  • 6fd883da2 adds the group limit to the README, Copilot rule and utils docstring.
  • Kernel and launcher fixes continued through 0688eb5a0d (reduce kernel ca444d6fb5, launcher 0688eb5a0d).
    • d507d3c1a later narrowed the config scope.
    • Since then only tests, docs and main merges.

Behavior and intent

  • In scope, the KV split follows each request's actual seqused_k instead of the captured max_seqlen_k.
  • Before, a graph captured at 1M gave every request the same segment count; one long request bounded the batch.
  • Cost: a per-workgroup scan of seqused_k that makes short uniform decode 3–12% slower (Kimi shapes, group ≤ 4).
  • Review findings (at b6997bdce):
    • Fixed in acd39a137:
      • find_work_item counted empty lanes past num_seqs (before & valid).
      • The Gluon reduce could read slot-major partials (now requires split is None).
      • num_seqs * max_seqlen_k could wrap for a numpy bound (int()).
      • SEQ_BLOCK bounds moved to the gfx950 JSON.
      • Docs say only bf16 Q, head 64 opt in.
    • Measured, not adopted:
      • Clamping segments to the KV tile count (±1% on 9 of 10 workloads).
      • remap_xcd instead of ITEM_RUN (1.3–1.8× slower on 7 of 10).
    • Kept: packed int64 counters and per-program scans instead of a prologue kernel (a prologue adds a launch).
    • Not a defect: a max_seqlen_q below a real query length drops rows; it is the documented upper bound.
    • Resolved in d507d3c1a: GPT-OSS TP8 short decode was 0.84× with the split on for every group.
      • Groups above 4 now keep the uniform split (1.00×).
      • Opting GPT-OSS in later needs its own tuning and end-to-end numbers.

Validation and unverified scope

  • Tests: pytest op_tests/triton_tests/attention/test_unified_attention.py (whole file), one MI355X.
    • Also the -k selection above.
  • Benchmarks: run_bench.sh (attached), one MI355X.
  • End-to-end accuracy through SGLang (Kimi-K3, DSpark draft attention on this path):
    • Command: sgl-eval 0.1.3 run gsm8k --load-preset-from-model-id moonshotai/Kimi-K3.
    • Settings: full 1319, temperature 1.0, top_p 0.95, thinking on, reasoning_effort max.
    • Split on: 97.19%, 97.50%; split off (key removed): 97.27%; 0 truncated, 0 errors.
      • Within noise (stderr ~0.45 pp).
    • Setup: 8× MI355X, Kimi-K3-Quark-MXFP4-AttnFP8, AgentX c16 recipe.
      • TP8/DCP8, DSpark block 4, graphs bs 1–32, simulated acceptance off.
      • SGLang k3-agentx-pr-stack @ 39d944c57d.
      • aiter stack @ f9b5308b2 (this PR at e2355e700, before the review fixes).
  • Unverified:
    • Other architectures.
    • GPT-OSS end-to-end (unchanged by this PR now).
    • The Kimi-K3 end-to-end runs above were at e2355e700, before the group scoping.
      • The group scoping leaves group 4 and group 1 unchanged.
    • Downstream CI.
    • Kimi-K3 GSM8K was not repeated at the merged head b0318b2d5.
  • Out of scope, same on main: the uniform reduce stores NaN for a kv_len 0 row.
  • Shares unified_attention.py, the kernel file and the test file with [Triton/Gluon] [Feature] unified_attention: support causal=False for bidirectional draft verify #7244.

PR-specific question

  • Consumer: only gfx950 Triton kv_split D_EQ_64.G_LEQ_4.DT_bf16_fp8 sets SPLIT_PROGRAMS_PER_CU.
    • Its uniform values equal D_LEQ_64, so the uniform split is unchanged.
  • The attn_3d keys (SPLIT_RUNS_PER_XCD, SPLIT_BLOCK_M) and reduce key are used only on a length-aware launch.
  • Other shapes: guards keep the uniform split.
    • Guards: dtype, head dims, window, skip_reduce, query block, integer bounds.
    • test_length_aware_split_scope checks this and that attn_3d/reduce entries for q = 1, 4, 8 carry their keys.

Changed op tests

  • op_tests/triton_tests/attention/test_unified_attention.py:
    • test_triton_unified_attn_3d_long_kv: actual vs captured KV bound.
    • test_triton_unified_attn_3d_length_aware_split:
      • Cases: skewed, uniform, 300-request, int64 seqused_k, q=8, against ref_paged_attn.
      • Also per-sequence segment counts.
      • Also, from a NaN-filled segm_max, which slot-major partials the 3D kernel wrote.
    • test_triton_unified_attn_3d_length_aware_split_graph_replay: changes seqused_k between graph replays.
    • test_length_aware_split_scope:
      • Excluded calls.
      • Groups 1 and 4 opt in and 8 does not (8 Q / 1 KV and 64 Q / 8 KV).
      • Asymmetric heads, window, integer bounds.
      • Query-block guard (q = 4 and 8 split, q = 9 falls back).
      • Config keys and the entry's SEQ_BLOCK.
    • Not redundant: no existing 3D test covers captured bounds or per-sequence segment allocation.

🤖 Generated with Claude Code

@yuychang
yuychang requested review from a team and a balanced review from Copilot October 28, 2026 09:27
@github-actions github-actions Bot changed the title [Triton] unified_attention: gfx950 kv_split for head-dim-64 bf16-Q / fp8-KV [Triton/Gluon] [Config] unified_attention: gfx950 kv_split for head-dim-64 bf16-Q / fp8-KV Oct 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 7088 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The gfx950 split-count retune needs exact-head CUDA-graph correctness and latency validation because the supplied measurements predate this PR and GPU execution was unavailable during review.

No open issues 🎉

What changed in this PR

This config-only PR tunes unified attention on gfx950 for head dimensions up to 64 with bf16 queries and fp8 KV, targeting long-context decode under CUDA graphs.

Changes:

  • Adds a dtype-specific entry with 128 KV segments and fixed segment and tile sizes of 64.
  • Leaves kernel code unchanged. Reported measurements show faster long-context decode, with a 2.6 µs slowdown for the short-sequence case.
File Description
aiter/​ops/​triton/​configs/​gfx950/​triton/​attention/​unified_attention/​DEFAULT.json Adds the D_LEQ_64.DT_bf16_fp8 KV-split configuration.

Review effort: Balanced

@github-actions github-actions Bot changed the title [Triton/Gluon] [Config] unified_attention: gfx950 kv_split for head-dim-64 bf16-Q / fp8-KV [Triton/Gluon] unified_attention: gfx950 kv_split for head-dim-64 bf16-Q / fp8-KV Oct 28, 2026
@github-actions github-actions Bot removed the Config label Oct 28, 2026
Copilot AI balanced review requested due to automatic review settings October 28, 2026 14:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The long-KV test tolerances can accept zero for small reference values, potentially masking lost split contributions.

1 open issue

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 28, 2026 15:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because a finding that passed the severity filter was omitted from the published review.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@yuychang yuychang changed the title [Triton/Gluon] unified_attention: gfx950 kv_split for head-dim-64 bf16-Q / fp8-KV [Triton/Gluon] [Perf] unified_attention: gfx950 kv_split for head-dim-64 bf16-Q / fp8-KV Oct 28, 2026
@yuychang
yuychang requested a balanced review from Copilot October 28, 2026 16:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The test docstring redundantly repeats setup values and exceeds the documented short-comment limit.

1 open issue

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 28, 2026 16:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The gfx950 default’s reported mixed-length gains come with uniform-batch slowdowns, requiring maintainer judgment supported by target-GPU correctness and latency measurements unavailable in this review.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 28, 2026 17:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The gfx950 tuning’s reported long-context gains come with uniform-batch latency regressions, requiring maintainer judgment on the workload trade-off because GPU correctness and performance results could not be independently reproduced.

No open issues 🎉

Review effort: Balanced

@zufayu
zufayu requested review from a team and Dewei-Wang-sh October 29, 2026 01:03
@yuychang
yuychang force-pushed the k3/unified-attn-d64-bf16-fp8-kvsplit branch from 4948cd3 to be2a245 Compare October 29, 2026 02:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The GPU allocation and slot-major reduction changes require exact-head gfx950 CUDA-graph correctness and base/head latency validation that this source-only review cannot perform.

No open issues 🎉

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The docstring in op_tests/triton_tests/attention/test_unified_attention.py:675 exceeds the project's two-sentence limit and needs shortening.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new GPU work-item mapping and reduction layout require exact-head gfx950 correctness and CUDA-graph replay validation, which this source-only review cannot provide and no supplied report establishes.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new GPU work-item mapping and slot-major reduction require independent exact-head gfx950 correctness, latency, and changing-length graph-replay validation that this source-only review could not perform.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@yuychang

yuychang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

gfx942 (MI300X) validation: validate-kernel-pr PASS.

1149 passed / 0 failed; independent grid 317 pass. The length-aware split is gated off on gfx942 by its config and runs correctly there when the gfx950 tables are pinned; the split and long-KV tests now run on gfx942. Bench latency within ±0.8% of base.

New commits for gfx942: 4efe461.

Reports were generated with the repo's validate-kernel-pr skill on a local head, so repo.head is null and they are not attached as PR evidence.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The packed work-item mapping and slot-major reduction require head-matched gfx950 correctness, graph-replay, and latency validation that the source-only reviews could not perform.

No open issues 🎉

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The packed GPU scheduling and partial-buffer changes require independent exact-head gfx950 correctness and latency validation, especially for length changes during CUDA-graph replay, which this environment cannot perform.

No open issues 🎉

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The packed GPU work-item mapping and slot-major partial layout require exact-head gfx950 correctness and base/head latency checks under graph replay, which this source-only environment cannot provide.

No open issues 🎉

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The length-aware split configuration contract remains undocumented in both required files, including the required SPLIT_* keys and uniform fallback conditions.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new GPU work-item mapping and slot-major reduction require exact-head gfx950 CUDA-graph correctness and latency validation, which this source-only review cannot perform and no head-matched report was supplied to establish.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The gfx950 work-item mapping and slot-major partial layout require independent GPU correctness, graph-replay, and latency validation that this source-only review cannot perform.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The packed GPU mapping and slot-major reduction lack exact-head gfx950 validation for CUDA-graph replay correctness and base-versus-head latency, which static review alone cannot establish.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new GPU work-item mapping and slot-major partial-buffer layout require exact-head gfx950 CUDA-graph correctness and latency validation, but no matching report was supplied and this environment cannot run those checks.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Both sink tests take the uniform split, leaving length-aware sink normalization untested and requiring a targeted case with a dominant sink and an asserted non-None split.

1 open issue

Review effort: Balanced

# the length-aware split does not exclude these inputs
+ [
("skewed", (8, 2), 4, option, torch.int32)
for option in ("shuffled_kv_cache", "softcap", "qq_bias")

@yuychang yuychang Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4456f74 and 622db0c: ("skewed", (8, 2), 4, "sinks", torch.int32) runs the group-4 length-aware split (assert num_segments > 1 and split is not None), and sinks + 10.0 makes segment 0's sink dominant so omitting it moves the 120K-token request by 24.0% and the short requests by >=408% (failing the 2% bound). Verified on MI355X (gfx950): max relative L2 error is 0.28%.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The default-on gfx950 scheduling and partial-buffer layout changes need human review because head-matched graph-replay validation is unavailable and the acknowledged 3–12% short-context cost requires a rollout trade-off assessment.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The dtype gate incorrectly enables the new split for mixed-cache calls, and tests do not cover dominant sinks in the length-aware merge.

2 open issues

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The added sink tests exercise only uniform splitting, leaving sink handling in the new length-aware merge without reference-comparison coverage.

3 open issues

Review effort: Balanced

)

if single_tile:
if LENGTH_AWARE_SPLIT:

@yuychang yuychang Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4456f74 and 622db0c: ("skewed", (8, 2), 4, "sinks", torch.int32) exercises the group-4 LENGTH_AWARE_SPLIT merge in _reduce_segments with a dominant sink (sinks + 10.0, moving the 120K-token request by 24.0% if omitted) and compares against ref_paged_attn. Verified on MI355X (gfx950): max relative L2 error is 0.28%.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The default-on gfx950 work-mapping and partial-buffer changes need maintainer review of graph replay and short-context latency trade-offs because exact-head GPU validation was unavailable.

3 open issues

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The default-on gfx950 scheduling and partial-buffer changes need maintainer review of the short-context latency trade-off and exact-head GPU correctness and performance, as runtime validation was unavailable here.

2 open issues
1 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate a critical overflow edge case in the attention reduction that can silently produce zero outputs for large sequence lengths.

2 open issues

Review effort: Balanced

- Compute per-sequence KV segment counts on GPU from seqused_k (int32/int64) for CUDA-graph-safe split-KV launches.
- Use slot-major partials [segment, token, head] and flat (work item, KV head) grid grouped by ITEM_RUN per XCD.
- Derive SPLIT_NUM_SEGMENTS in compute_segment_params without changing uniform-split NUM_SEGMENTS behavior.
- Guard length-aware split to gfx950 Triton 3D bf16 Q, fp8 KV, head dim 64, G <= 4, single query block, no window.
- Add G axis and length-aware SPLIT_* keys to gfx950 unified_attention DEFAULT.json (D_EQ_64.G_LEQ_4.DT_bf16_fp8).
- Add shared _assert_request_rel_l2 helper checking per-request relative L2 error and zero output for kv_len == 0.
- Add long-KV head-dim-64 bf16-Q/fp8-KV 3D attention test covering both real and 1M captured max_seqlen_k bounds.
- Add length-aware split tests for skewed, uniform, empty-slot, 300-seq, int64, shuffled, softcap, qq_bias, and sinks.
- Add CUDA graph replay test mutating seqused_k across skewed, uniform, and empty-slot batches at the 1M bound.
- Add CPU unit test test_length_aware_split_scope verifying config key guards, G_LEQ_4 scope, and overflow bounds.
- Document G_LEQ_4 scope and SPLIT_* config keys for length-aware KV split in README.md and configs/AGENTS.md.
- Add review rule in aiter-ops-triton.instructions.md flagging incomplete SPLIT_* keys or missing G_LEQ_4 scoping.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The default gfx950 scheduling and partial-buffer changes require maintainer review of graph-replay correctness and the short-context latency trade-off because head-matched GPU validation is unavailable.

2 open issues

Review effort: Balanced

This branch has not been deployed

No deployments
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.

5 participants