Repository navigation
[FlyDSL] pa_decode: peel the last KV tile so only it carries the V tail mask - #7197
Conversation
…il mask Only a sequence's last tile reads rows past its context, and the task guard guarantees part_start < part_end, so the tile loop now runs [part_start, part_end - 1) without the V tail mask and the task's last tile is peeled to carry it. Single-tile plans keep the masked tile. The runtime mask branch was also a basic-block boundary that kept the scheduler from sinking page64/128 V loads next to their PV MFMAs; the unmasked tiles place sched_barrier(0) there to keep the loads early. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: fsx950223 <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
PR description changed |
MiniMax-M3
|
| Case | #7079 table plan | ATOM plan |
|---|---|---|
| FP8 sparse verify 3×4 = 12 rows | 6.74 → 6.82 µs, +1.31% (8/9) | 6.74 → 6.82 µs, +1.13% (8/9) |
| FP8 sparse decode 4 rows | 6.60 → 6.68 µs, +1.09% (8/9) | 6.62 → 6.66 µs, +0.67% (8/9) |
| FP8 sparse prefill 8192 rows | 427.11 → 431.11 µs, +0.94% (9/9) | 426.22 → 429.96 µs, +0.88% (9/9) |
| FP8 dense decode bs32 8K | 16.75 → 16.89 µs, +0.84% (8/9) | 16.81 → 16.95 µs, +0.83% (6/9) |
| FP8 sparse decode 64 rows (borderline) | 9.77 → 9.88 µs, +1.11% (7/9) | 9.81 → 9.86 µs, +0.49% (5/9) |
The largest wins are on BF16 page16 sparse:
- Decode: 64 rows −17%, 128 rows −19% (ATOM, 4 partitions), 256 rows −8%.
- Prefill: 1024 rows −10%, 4096 rows −3.7%.
- Also BF16 dense verify bs3×4 220K −3.5%, and FP8 sparse decode 128 / 256 rows −3.0% / −4.7%.
In the cached code objects, the BF16 page16 tile kernel drops from 275 VGPRs + 19 AGPRs to 184 VGPRs. That should take it from 1 to 2 waves per SIMD at 256 threads per workgroup. No other M3 tile kernel crosses an occupancy step. Every tile kernel's .text grows by 36–69%, because the tile body is now emitted twice.
Correctness. 60 of 64 outputs are bit-identical to base. The other 4 cases are FP8 dense verify bs8×4 32K and bs3×4 220K, each under both plans. They differ by 1 BF16 ulp in at most 5 of 65,536 elements, and their relative L2 error against an FP32 reference is unchanged (0.0378 and 0.0384). Every output is finite, and each tree is bit-stable across rounds.
Method
- Trees. Base is
mainat 8fd8934, the merge target when I measured. Head is base plus this PR's diff; itspipeline.pyis byte-identical to 553002c's. The two trees differ only in that file, use separateFLYDSL_RUNTIME_CACHE_DIRs, and report differentimplementation_cache_tag()values at runtime. - Timing. Same as [FlyDSL] Merge gfx1250 PA decode partitions in the tile kernel and speed up dense decode #7079: a run's time is the minimum over five 10-call CUDA graphs with 5 replays each, covering the tile kernel plus the reducer and excluding planning and compilation. I ran 3 rounds, rotating the order of base, head and the base re-run, and report the median. One addition: 30 ms of untimed replays per case before the five graphs, because without them clocks were still ramping during the first graph.
- Shapes.
- Common: H16 / KV1 / D128, softmax scale 1/√128, BF16 query and output, no sinks or sliding window.
- FP8 KV: OCP e4m3fn with per-token FP32 K/V scales of shape
[N, 1, page]. Cache layouts are K[N, 1, D/x, page, x]and V[N, 1, page/x, D, x]. - Dense: page128 with one sequence per request; 8K = 8192, 32K = 32768 and 220K = 225,280 tokens. Verify uses 4 causal query tokens.
- Sparse: page16, gathered from a 4096-page pool. Each row picks 16 distinct random 128-token blocks, and prefill row i sees min(i + 1, 2048) tokens.
- Q/K/V are drawn from N(0, 1). The 8192-row plan passes
max_batch_size=8192.
- ATOM pattern.
- Sparse:
max_partitions = get_recommended_splits(rows, 1)withmax_context_length=2048. That gives 8 partitions for 4, 12 and 64 rows, 4 for 128 rows, 2 for 256 rows, and 1 for prefill. - Dense: block tables padded to 256K tokens, with no
max_context_length.
- Sparse:
- Environment. MI355X (gfx950, 256 CUs), one GPU that stayed idle throughout, held under a lock for the whole run. FlyDSL v0.4.1.dev994 (888d7d80), PyTorch 2.10.0+rocm7.2.4, HIP 7.2.53211.
All 64 cases (median of 3 rounds)
"Tasks (multi-tile)" is the number of planned tasks, with the number covering more than one 256-token tile in parentheses. "A/A" is the base tree's re-run against base.
| Case | Plan | Base µs | Head µs | Head vs base | A/A | Tasks (multi-tile) | Partition cap |
|---|---|---|---|---|---|---|---|
| FP8 dense decode bs1 8K | table | 7.19 | 7.22 | +0.34% | +0.33% | 32 (0) | 256 |
| FP8 dense decode bs4 8K | table | 7.47 | 7.42 | −0.70% | −0.75% | 128 (0) | 256 |
| FP8 dense decode bs8 8K | table | 7.82 | 7.80 | −0.20% | +0.15% | 256 (0) | 256 |
| FP8 dense decode bs32 8K | table | 16.73 | 16.84 | +0.62% | +0.31% | 512 (512) | 256 |
| FP8 dense decode bs4 32K | table | 11.12 | 11.16 | +0.32% | +0.04% | 512 (0) | 256 |
| FP8 dense decode bs3 220K | table | 33.84 | 34.00 | +0.47% | +0.77% | 512 (512) | 256 |
| FP8 dense verify bs3×4 8K | table | 9.89 | 9.93 | +0.44% | +0.16% | 96 (0) | 256 |
| FP8 dense verify bs3×4 32K | table | 16.82 | 16.37 | −2.66% | +1.09% | 384 (0) | 256 |
| FP8 dense verify bs8×4 32K | table | 23.76 | 23.20 | −2.34% | +0.05% | 512 (512) | 256 |
| FP8 dense verify bs3×4 220K | table | 45.03 | 44.37 | −1.46% | +0.59% | 512 (512) | 256 |
| FP8 sparse decode 4 rows | table | 6.60 | 6.68 | +1.09% | −0.18% | 32 (0) | 256 |
| FP8 sparse decode 64 rows | table | 9.83 | 9.85 | +0.20% | −0.98% | 512 (0) | 256 |
| FP8 sparse verify 3×4 = 12 rows | table | 6.75 | 6.81 | +0.83% | −0.06% | 96 (0) | 256 |
| FP8 sparse prefill 1024 rows | table | 28.60 | 27.98 | −2.18% | −0.11% | 1024 (768) | 256 |
| FP8 sparse prefill 8192 rows | table | 427.08 | 431.24 | +0.98% | +0.16% | 8192 (7936) | 256 |
| BF16 dense decode bs1 8K | table | 7.51 | 7.45 | −0.80% | −0.11% | 32 (0) | 256 |
| BF16 dense decode bs4 8K | table | 7.66 | 7.61 | −0.68% | −0.21% | 128 (0) | 256 |
| BF16 dense decode bs8 8K | table | 10.08 | 9.91 | −1.71% | +0.00% | 256 (0) | 256 |
| BF16 dense decode bs32 8K | table | 24.00 | 23.92 | −0.33% | +0.00% | 512 (512) | 256 |
| BF16 dense decode bs4 32K | table | 16.24 | 15.96 | −1.77% | +1.48% | 512 (0) | 256 |
| BF16 dense decode bs3 220K | table | 66.40 | 65.93 | −0.72% | +0.09% | 512 (512) | 256 |
| BF16 dense verify bs3×4 8K | table | 12.39 | 12.31 | −0.68% | −0.13% | 96 (0) | 256 |
| BF16 dense verify bs3×4 32K | table | 25.50 | 25.61 | +0.42% | +0.31% | 384 (0) | 256 |
| BF16 dense verify bs8×4 32K | table | 39.58 | 39.23 | −0.88% | +0.12% | 512 (512) | 256 |
| BF16 dense verify bs3×4 220K | table | 94.30 | 90.97 | −3.53% | −0.52% | 512 (512) | 256 |
| BF16 sparse decode 4 rows | table | 7.18 | 7.10 | −1.22% | +0.00% | 32 (0) | 256 |
| BF16 sparse decode 64 rows | table | 18.06 | 14.97 | −17.08% | +0.67% | 512 (0) | 256 |
| BF16 sparse verify 3×4 = 12 rows | table | 7.32 | 7.20 | −1.53% | +0.11% | 96 (0) | 256 |
| BF16 sparse prefill 1024 rows | table | 49.87 | 44.82 | −10.12% | +0.30% | 1024 (768) | 256 |
| BF16 sparse prefill 4096 rows | table | 404.56 | 389.40 | −3.75% | −0.02% | 4096 (3840) | 256 |
| FP8 dense decode bs1 8K | ATOM | 7.74 | 7.76 | +0.26% | +0.52% | 32 (0) | 256 |
| FP8 dense decode bs4 8K | ATOM | 7.99 | 7.98 | −0.10% | +0.40% | 128 (0) | 256 |
| FP8 dense decode bs8 8K | ATOM | 8.38 | 8.29 | −1.10% | −0.29% | 256 (0) | 256 |
| FP8 dense decode bs32 8K | ATOM | 16.80 | 16.85 | +0.29% | +0.10% | 512 (512) | 256 |
| FP8 dense decode bs4 32K | ATOM | 11.16 | 11.29 | +1.18% | +1.29% | 512 (0) | 256 |
| FP8 dense decode bs3 220K | ATOM | 33.94 | 34.00 | +0.16% | +0.18% | 512 (512) | 256 |
| FP8 dense verify bs3×4 8K | ATOM | 11.40 | 11.34 | −0.56% | −0.42% | 96 (0) | 256 |
| FP8 dense verify bs3×4 32K | ATOM | 16.96 | 16.54 | −2.50% | −0.07% | 384 (0) | 256 |
| FP8 dense verify bs8×4 32K | ATOM | 23.83 | 23.36 | −1.96% | −0.03% | 512 (512) | 256 |
| FP8 dense verify bs3×4 220K | ATOM | 45.08 | 44.37 | −1.58% | +0.13% | 512 (512) | 256 |
| FP8 sparse decode 4 rows | ATOM | 6.61 | 6.64 | +0.48% | −0.24% | 32 (0) | 8 |
| FP8 sparse decode 64 rows | ATOM | 9.82 | 9.86 | +0.45% | −0.57% | 512 (0) | 8 |
| FP8 sparse decode 128 rows | ATOM | 15.12 | 14.66 | −3.02% | −0.71% | 512 (512) | 4 |
| FP8 sparse decode 256 rows | ATOM | 22.62 | 21.74 | −3.91% | +0.76% | 512 (512) | 2 |
| FP8 sparse verify 3×4 = 12 rows | ATOM | 6.75 | 6.80 | +0.83% | +0.18% | 96 (0) | 8 |
| FP8 sparse prefill 1024 rows | ATOM | 28.40 | 27.72 | −2.40% | −0.52% | 1024 (768) | 1 |
| FP8 sparse prefill 8192 rows | ATOM | 426.21 | 429.96 | +0.88% | +0.07% | 8192 (7936) | 1 |
| BF16 dense decode bs1 8K | ATOM | 8.01 | 8.00 | −0.15% | +0.20% | 32 (0) | 256 |
| BF16 dense decode bs4 8K | ATOM | 8.22 | 8.15 | −0.87% | −0.14% | 128 (0) | 256 |
| BF16 dense decode bs8 8K | ATOM | 10.56 | 10.41 | −1.37% | −0.23% | 256 (0) | 256 |
| BF16 dense decode bs32 8K | ATOM | 24.08 | 24.10 | +0.08% | +0.18% | 512 (512) | 256 |
| BF16 dense decode bs4 32K | ATOM | 16.33 | 15.96 | −2.28% | +0.02% | 512 (0) | 256 |
| BF16 dense decode bs3 220K | ATOM | 66.42 | 66.15 | −0.41% | +0.02% | 512 (512) | 256 |
| BF16 dense verify bs3×4 8K | ATOM | 12.96 | 12.88 | −0.65% | −0.55% | 96 (0) | 256 |
| BF16 dense verify bs3×4 32K | ATOM | 25.45 | 25.39 | −0.24% | +0.36% | 384 (0) | 256 |
| BF16 dense verify bs8×4 32K | ATOM | 39.58 | 39.19 | −0.98% | −0.18% | 512 (512) | 256 |
| BF16 dense verify bs3×4 220K | ATOM | 94.18 | 91.14 | −3.23% | −0.28% | 512 (512) | 256 |
| BF16 sparse decode 4 rows | ATOM | 7.20 | 7.10 | −1.44% | −0.06% | 32 (0) | 8 |
| BF16 sparse decode 64 rows | ATOM | 18.04 | 14.96 | −17.03% | +0.47% | 512 (0) | 8 |
| BF16 sparse decode 128 rows | ATOM | 25.82 | 20.80 | −19.41% | −0.57% | 512 (512) | 4 |
| BF16 sparse decode 256 rows | ATOM | 40.36 | 37.12 | −8.04% | +0.41% | 512 (512) | 2 |
| BF16 sparse verify 3×4 = 12 rows | ATOM | 7.32 | 7.20 | −1.59% | −0.11% | 96 (0) | 8 |
| BF16 sparse prefill 1024 rows | ATOM | 49.56 | 44.51 | −10.20% | +0.40% | 1024 (768) | 1 |
| BF16 sparse prefill 4096 rows | ATOM | 404.02 | 389.04 | −3.71% | +0.03% | 4096 (3840) | 1 |
Tile kernel registers and code size (gfx950)
| Tile kernel | Base regs | Head regs | Waves/SIMD | .text bytes |
|---|---|---|---|---|
| BF16 page16 qlen1 (sparse) | 275 + 19 AGPR | 184 | 1 → 2 | 6,336 → 8,640 |
| BF16 page128 qlen1 (dense decode) | 243 | 224 | 2 → 2 | 6,016 → 8,384 |
| BF16 page128 qlen4 (dense verify) | 376 + 120 AGPR | 356 + 100 AGPR | 1 → 1 | 12,032 → 20,352 |
| FP8 page16 qlen1 (sparse) | 168 | 148 | 3 → 3 | 6,272 → 9,152 |
| FP8 page128 qlen1 (dense decode) | 168 | 162–164 | 3 → 3 | 6,528 → 9,472 |
| FP8 page128 qlen4 (dense verify) | 254 | 242 | 2 → 2 | 14,144 → 22,080 |
| FP8 page128 qlen4, 4 query splits | 166 | 160 | 3 → 3 | 6,400 → 9,088 |
The waves-per-SIMD column assumes the 512-entry unified register file. No kernel reports spills.
Benchmark script
Each process times whichever aiter tree comes first on PYTHONPATH. --prep compiles every case, checks it against an FP32 reference and saves its outputs; without it the script times every case.
# SPDX-License-Identifier: MIT
"""Time MiniMax-M3 pa_decode shapes from the ROCm/aiter#7079 performance table.
Every case runs against the `aiter` tree that comes first on PYTHONPATH, so base
and head are timed by separate processes over identical, seeded inputs. A case's
time is the minimum over five CUDA graphs of ten pa_decode calls (tile kernel
plus reducer), each graph replayed five times; planning and compilation are
excluded.
`--prep` instead compiles every case, checks selected rows against an FP32
reference, and saves the full outputs so two trees can be compared bit for bit.
"""
import argparse
import hashlib
import json
import os
import re
import sys
import time
import torch
import torch.nn.functional as F
HQ, HKV, DIM = 16, 1, 128
SOFTMAX_SCALE = DIM**-0.5
KI = 1024
DENSE_PAGE = 128
SPARSE_PAGE = 16
SPARSE_POOL_PAGES = 4096
TOPK_BLOCK_TOKENS = 128
SPARSE_ROW_TOKENS = 2048
ATOM_DENSE_TABLE_TOKENS = 256 * KI
GRAPHS, CALLS_PER_GRAPH, REPLAYS = 5, 10, 5
def cdiv(a, b):
return -(-a // b)
def recommended_splits(rows, num_compute_units):
"""get_recommended_splits(rows, 1) from aiter.ops.triton.gluon.pa_decode_gluon.
Without max_context_length it returns min(cdiv(2 * CUs, rows), 8).
"""
return min(cdiv(2 * num_compute_units, rows), 8)
def build_cases(num_compute_units):
dense = [
(1, 1, 8 * KI),
(1, 4, 8 * KI),
(1, 8, 8 * KI),
(1, 32, 8 * KI),
(1, 4, 32 * KI),
(1, 3, 220 * KI),
(4, 3, 8 * KI),
(4, 3, 32 * KI),
(4, 8, 32 * KI),
(4, 3, 220 * KI),
]
cases = []
for plan in ("default", "atom"):
for kv in ("fp8", "bf16"):
for qlen, batch, context in dense:
kind = "decode" if qlen == 1 else "verify"
label = f"bs{batch}" if qlen == 1 else f"bs{batch}x{qlen}"
cases.append(
dict(
id=f"{plan}/{kv}/dense-{kind}-{label}-{context // KI}K",
plan=plan,
kv=kv,
layout="dense",
query_length=qlen,
lengths=[context] * batch,
table_tokens=(
ATOM_DENSE_TABLE_TOKENS if plan == "atom" else context
),
max_partitions=None,
max_context_length=None,
)
)
sparse = [("decode", 4), ("decode", 64)]
if plan == "atom":
sparse += [("decode", 128), ("decode", 256)]
sparse += [
("verify", 12),
("prefill", 1024),
("prefill", 8192 if kv == "fp8" else 4096),
]
for kind, rows in sparse:
if kind == "prefill":
lengths = [min(i + 1, SPARSE_ROW_TOKENS) for i in range(rows)]
else:
lengths = [SPARSE_ROW_TOKENS] * rows
label = "3x4=12rows" if kind == "verify" else f"{rows}rows"
cases.append(
dict(
id=f"{plan}/{kv}/sparse-{kind}-{label}",
plan=plan,
kv=kv,
layout="sparse",
query_length=1,
lengths=lengths,
table_tokens=SPARSE_ROW_TOKENS,
max_partitions=(
recommended_splits(rows, num_compute_units)
if plan == "atom"
else None
),
max_context_length=(
SPARSE_ROW_TOKENS if plan == "atom" else None
),
)
)
return cases
def input_seed(case):
"""Seed from the data-defining fields only, stable across processes."""
key = "|".join(
str(case[name]) for name in ("kv", "layout", "query_length", "lengths")
)
return int(hashlib.sha256(key.encode()).hexdigest()[:8], 16)
def quant_per_token(x):
fp8 = torch.float8_e4m3fn
scale = x.abs().amax(dim=-1, keepdim=True).clamp_min(1e-6) / torch.finfo(fp8).max
return (x / scale).to(fp8), scale
def make_inputs(case, device, keep_logical):
seed = input_seed(case)
host = torch.Generator().manual_seed(seed)
gpu = torch.Generator(device=device).manual_seed(seed)
lengths = case["lengths"]
rows = len(lengths)
if case["layout"] == "dense":
page = DENSE_PAGE
pages_per_seq = cdiv(lengths[0], page)
num_pages = rows * pages_per_seq
table = torch.randperm(num_pages, generator=host, dtype=torch.int32)
table = table.reshape(rows, pages_per_seq)
table = F.pad(table, (0, case["table_tokens"] // page - pages_per_seq))
else:
# Each row selects 16 distinct 128-token blocks (8 pages each) of the pool.
page = SPARSE_PAGE
block_pages = TOPK_BLOCK_TOKENS // page
num_pages = SPARSE_POOL_PAGES
picks = torch.rand(rows, num_pages // block_pages, generator=host).argsort(1)
picks = picks[:, : SPARSE_ROW_TOKENS // TOPK_BLOCK_TOKENS]
table = picks[:, :, None] * block_pages + torch.arange(block_pages)
table = table.reshape(rows, -1).to(torch.int32)
table = table.to(device).contiguous()
context = torch.tensor(lengths, dtype=torch.int32, device=device)
shape = (num_pages, HKV, page, DIM)
key = torch.randn(shape, generator=gpu, device=device)
value = torch.randn(shape, generator=gpu, device=device)
query = torch.randn(
(rows * case["query_length"], HQ, DIM), generator=gpu, device=device
).to(torch.bfloat16)
key_scale = value_scale = None
if case["kv"] == "fp8":
key, key_scale = quant_per_token(key)
value, value_scale = quant_per_token(value)
vector = 16
else:
key, value = key.bfloat16(), value.bfloat16()
vector = 8
logical = None
if keep_logical:
logical = tuple(
t.float() * (1.0 if s is None else s)
for t, s in ((key, key_scale), (value, value_scale))
)
key_cache = (
key.reshape(num_pages, HKV, page, DIM // vector, vector)
.permute(0, 1, 3, 2, 4)
.contiguous()
)
value_cache = (
value.reshape(num_pages, HKV, page // vector, vector, DIM)
.permute(0, 1, 2, 4, 3)
.contiguous()
)
if key_scale is not None:
key_scale = key_scale.squeeze(-1).contiguous()
value_scale = value_scale.squeeze(-1).contiguous()
return dict(
query=query,
key_cache=key_cache,
value_cache=value_cache,
key_scale=key_scale,
value_scale=value_scale,
table=table,
context=context,
page=page,
logical=logical,
)
def reference_rows(inputs, case, seqs):
"""FP32 attention over the logical (dequantized) KV for the given sequences."""
query_length = case["query_length"]
lengths = case["lengths"]
lk, lv = inputs["logical"]
table, page = inputs["table"], inputs["page"]
queries = inputs["query"].float().reshape(len(lengths), query_length, HKV, -1, DIM)
positions = torch.arange(query_length, device=table.device)
result = {}
for seq in seqs:
length = lengths[seq]
tokens = torch.arange(length, device=table.device)
pages = table[seq, tokens // page].long()
offsets = tokens % page
keys, values = lk[pages, :, offsets], lv[pages, :, offsets]
scores = torch.einsum("qhgd,khd->qhgk", queries[seq], keys) * SOFTMAX_SCALE
visible = length - query_length + 1 + positions
masked = tokens[None, :] >= visible[:, None]
scores.masked_fill_(masked[:, None, None, :], float("-inf"))
probs = torch.softmax(scores, dim=-1)
out = torch.einsum("qhgk,khd->qhgd", probs, values)
result[seq] = out.reshape(query_length, HQ, DIM)
return result
def check_rows(case):
rows = len(case["lengths"])
if case["layout"] == "dense":
return list(range(rows)) if rows <= 4 else [0, rows - 1]
picks = {0, 1, 15, 16, 17, 255, 256, 257, 1023, 2047, 2048, rows // 2, rows - 1}
return sorted(p for p in picks if p < rows)
def plan_stats(plan):
reduce_info = plan.reduce_info.cpu()
tasks = int(reduce_info[:, 1].sum())
work = plan.work_info[:tasks].cpu()
tiles = (work[:, 2] - work[:, 1]).tolist()
return dict(
plan_max_partitions=plan.max_partitions,
plan_capacity=plan.capacity,
tasks=tasks,
tiles=sum(tiles),
max_tiles_per_task=max(tiles),
multi_tile_tasks=sum(t > 1 for t in tiles),
)
def capture(launch):
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
for _ in range(CALLS_PER_GRAPH):
launch()
torch.cuda.synchronize()
return graph
def time_graphs(launch, warm_ms):
side = torch.cuda.Stream()
side.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(side):
for _ in range(3):
launch()
torch.cuda.current_stream().wait_stream(side)
torch.cuda.synchronize()
# Untimed replays let clocks settle after the host-side gap between cases.
warm = capture(launch)
deadline = time.perf_counter() + warm_ms / 1e3
while time.perf_counter() < deadline:
warm.replay()
torch.cuda.synchronize()
del warm
samples = []
for _ in range(GRAPHS):
graph = capture(launch)
for _ in range(REPLAYS):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
graph.replay()
end.record()
end.synchronize()
samples.append(start.elapsed_time(end) * 1e3 / CALLS_PER_GRAPH)
del graph
return samples
def tensor_sha(tensor):
data = tensor.detach().contiguous().view(torch.uint8).cpu().numpy().tobytes()
return hashlib.sha256(data).hexdigest()[:16]
def run_case(case, pa, device, prep, save_dir, warm_ms):
inputs = make_inputs(case, device, keep_logical=prep)
lengths = case["lengths"]
rows = len(lengths)
query_length = case["query_length"]
plan = pa.plan_pa_decode(
inputs["context"],
HKV,
max_partitions=case["max_partitions"],
max_batch_size=max(rows, 4096),
query_length=query_length,
)
scalar_shape = (HKV, plan.capacity, query_length * HQ // HKV)
workspace = dict(
exp_sums=torch.empty(scalar_shape, dtype=torch.float32, device=device),
max_logits=torch.empty(scalar_shape, dtype=torch.float32, device=device),
temporary_output=torch.empty(
(*scalar_shape, DIM), dtype=torch.bfloat16, device=device
),
)
output = torch.full_like(inputs["query"], float("nan"))
def launch():
pa.pa_decode(
output,
inputs["query"],
inputs["key_cache"],
inputs["value_cache"],
inputs["context"],
inputs["table"],
SOFTMAX_SCALE,
query_length,
key_scale=inputs["key_scale"],
value_scale=inputs["value_scale"],
work_plan=plan,
max_context_length=case["max_context_length"],
**workspace,
)
record = dict(
id=case["id"],
plan=case["plan"],
kv=case["kv"],
layout=case["layout"],
query_length=query_length,
rows=rows,
max_length=max(lengths),
total_tokens=sum(lengths),
table_width=inputs["table"].shape[1],
max_context_length=case["max_context_length"],
**plan_stats(plan),
)
begin = time.perf_counter()
launch()
torch.cuda.synchronize()
record["first_call_s"] = round(time.perf_counter() - begin, 3)
record["finite"] = bool(torch.isfinite(output).all())
record["out_sha"] = tensor_sha(output)
if prep:
seqs = check_rows(case)
reference = reference_rows(inputs, case, seqs)
out = output.float().reshape(rows, query_length, HQ, DIM)
got = torch.cat([out[s] for s in seqs])
want = torch.cat([reference[s] for s in seqs])
record["ref_rows"] = seqs
record["ref_rel_l2"] = float((got - want).norm() / want.norm())
record["ref_max_abs"] = float((got - want).abs().max())
if save_dir:
safe = case["id"].replace("/", "__")
torch.save(output.cpu(), os.path.join(save_dir, f"{safe}.pt"))
else:
samples = time_graphs(launch, warm_ms)
record["us"] = min(samples)
record["us_samples"] = [round(s, 3) for s in samples]
record["out_sha_after"] = tensor_sha(output)
return record
def tree_identity():
import flydsl
import aiter.ops.flydsl.kernels.pa_decode as package
import aiter.ops.flydsl.kernels.pa_decode.pipeline as pipeline
properties = torch.cuda.get_device_properties(0)
with open(pipeline.__file__, "rb") as source:
pipeline_sha = hashlib.sha256(source.read()).hexdigest()
return dict(
pipeline=pipeline.__file__,
pipeline_sha256=pipeline_sha,
implementation_cache_tag=package.implementation_cache_tag(),
flydsl=f"{flydsl.__file__} {getattr(flydsl, '__version__', '?')}",
flydsl_cache_dir=os.environ.get("FLYDSL_RUNTIME_CACHE_DIR"),
torch=torch.__version__,
device=f"{properties.name} {properties.gcnArchName}",
compute_units=properties.multi_processor_count,
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--label", required=True)
parser.add_argument("--round", type=int, default=0)
parser.add_argument("--prep", action="store_true")
parser.add_argument("--only", help="regex selecting case ids")
parser.add_argument("--list", action="store_true")
parser.add_argument("--jsonl")
parser.add_argument("--save-outputs")
parser.add_argument("--warm-ms", type=float, default=30.0)
args = parser.parse_args()
device = torch.device("cuda", 0)
torch.cuda.set_device(device)
cases = build_cases(torch.cuda.get_device_properties(0).multi_processor_count)
if args.only:
cases = [case for case in cases if re.search(args.only, case["id"])]
if args.list:
for case in cases:
print(case["id"], case["max_partitions"], case["max_context_length"])
return
import aiter.ops.flydsl.pa_decode as pa
if args.save_outputs:
os.makedirs(args.save_outputs, exist_ok=True)
sink = open(args.jsonl, "a") if args.jsonl else None
def emit(record):
line = json.dumps(record)
print(line, flush=True)
if sink:
sink.write(line + "\n")
sink.flush()
emit(
dict(
meta=True,
label=args.label,
round=args.round,
prep=args.prep,
warm_ms=args.warm_ms,
start=time.strftime("%Y-%m-%d %H:%M:%S"),
**tree_identity(),
)
)
for case in cases:
try:
record = run_case(
case, pa, device, args.prep, args.save_outputs, args.warm_ms
)
except Exception as error: # noqa: BLE001 - report and continue
record = dict(id=case["id"], error=f"{type(error).__name__}: {error}")
record.update(label=args.label, round=args.round)
emit(record)
torch.cuda.empty_cache()
if sink:
sink.close()
return 0
if __name__ == "__main__":
sys.exit(main())Conflicts in traits.py, pa_decode_kernel.py and pa_decode.py: main's ROCm#7092 added mask_unowned_kv where this PR adds causal (the select, compile_pa_decode_tile and pa_decode signatures and the calls between them). Kept both, mask_unowned_kv first; all are keyword-only. The schedule cache key holds both, in the same order where it is built and unpacked. ROCm#7197 (peeled last KV tile) and ROCm#6767 (gfx1250-strict) also touch these files and merged cleanly; neither needs a change for causal. Signed-off-by: Rebecca Lee <[email protected]>
…il mask (ROCm#7197) Only a sequence's last tile reads rows past its context, and the task guard guarantees part_start < part_end, so the tile loop now runs [part_start, part_end - 1) without the V tail mask and the task's last tile is peeled to carry it. Single-tile plans keep the masked tile. The runtime mask branch was also a basic-block boundary that kept the scheduler from sinking page64/128 V loads next to their PV MFMAs; the unmasked tiles place sched_barrier(0) there to keep the loads early. Signed-off-by: fsx950223 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
FlyDSL
pa_decode(gfx942/gfx950) now peels each task's last KV tile so that only that tile emits #7092's V tail mask. The loop tiles run without it, and an explicitsched_barrier(0)keeps page64/128 V loads early in those tiles. Output is unchanged; the change gives a geomean of -3.25% on gfx950 and -3.37% on gfx942 over 270 Qwen3.5 decode shapes.Motivation
#7092 zeroes V rows past each sequence's context before PV, so that NaN bytes in unowned rows cannot reach the output. It emits a runtime
tile_valid < TILE_TOKbranch, mask computation and ANDs in every KV tile, although only a sequence's last tile can hold such rows. That costs instructions on every full tile.The branch also has a side effect: it is a basic-block boundary that LLVM's machine scheduler does not move instructions across. Removing it from the loop is therefore not free.
global_loadnext to its PV MFMA (load → s_waitcnt vmcnt(1) → mfma), which exposes load latency.mask_unowned_kv=Falseis ~13% slower than with the mask on those shapes.Changes
Only
aiter/ops/flydsl/kernels/pa_decode/pipeline.pychanges.tile(ostate, tt, multi_query, q_ops_all, mask_tail).mainloopruns[part_start, part_end - 1)withmask_tail=False(no V mask code is emitted).mask_tail=True.pa_decode_tile_kernelonly runs a task whenstart < end, so the peeled tile needs no runtime guard.tile_valid < TILE_TOKcheck remains, so non-final partitions and 256-aligned contexts still skip the ANDs.block_size >= 64placefx.rocdl.sched_barrier(0)before PV, where the branch used to be. Page 16 uses a different V gather and measured slightly faster without it.stage_scales;mask_unowned_kv=False(which emits no mask code anywhere);The diff is mostly the loop body dedenting into
tile(). Use "Hide whitespace" to see the logic change.Performance (if applicable)
Kernel time, main
cf831b20cfvs this PR, withmask_unowned_kv=True(the default).ctx - U[0,255].max_partitions=64,workgroup_budget=256.Same-tree noise (round 1 vs rounds 2–3) reached 7.4% (gfx950) and 8.4% (gfx942) on single shapes. Apart from the fp8tok row above, the shapes slower by more than 3% are 15–27 µs calls that are bimodal on main too.
Testing
Documentation
The
mask_unowned_kvcontract documented by #7092 is unchanged; only where the mask is emitted changes.Dependencies
Breaking Changes
None.
PR Self-Review
Reviewed revision
553002c
Behavior and intent
Output is unchanged. FlyDSL
pa_decodeon gfx942/gfx950 now emits #7092's V tail mask only in each task's peeled last tile, instead of a runtime branch plus mask code in every KV tile. The existing behavior paid that mask cost on every full tile even though only a sequence's last tile can read rows past its context.That branch was also the only thing preventing LLVM from sinking page64/128 V loads next to their PV MFMAs. The unmasked loop tiles therefore get an explicit
sched_barrier(0)in its place, without which gfx942 bf16 page64/128 regresses by up to 17%.Validation and unverified scope
Correctness:
python -m pytest -q op_tests/test_flydsl_pa_decode.py, which includes the 72 NaN/Inftest_pa_decode_unowned_kv_rowscases from #7092.plan_pa_decode caps max_partitions at 80 CUs). This torch lacksCudaDeviceProperties.shared_memory_per_block, which main'splan_pa_decodereads, so the gfx942 runs patched it to 65536 in the test process only. The repository code is unchanged.Performance: the 270-shape graph-replay benchmark in the Performance section, 3 alternating rounds per arch. All outputs were finite.
Unverified or not covered:
ATOM_PA_FLYDSL=1) were not run.PR-specific question
The most important boundary is the peeled tile: it must always be the task's last tile and must run exactly once per task.
Invariant:
pa_decode_tile_kernelonly calls the task whenstart < end, sopart_end - 1 >= part_start. The loop then runs zero or more unmasked tiles and the masked tile always runs. If a task could be empty, the peeled tile would read an invalid tile, so this invariant is what makes the guard-free peel safe.Evidence:
The second boundary is the fence: it is only a scheduling hint and cannot change values. The benchmark compares it per arch, page size and dtype.
Changed op tests
None. No
op_tests/file changes; the existingop_tests/test_flydsl_pa_decode.py::test_pa_decode_unowned_kv_rowsfrom #7092 already covers rows past the context through the peeled tile.🤖 Generated with Claude Code