You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Triton/Gluon] [Bugfix] [Perf] Fix non-preshuffle MQA paging and large KV offsets, retune the decode grid, and cut plain-path instruction count - #5614
Four defects in the paged MQA logits decode path, all silent: no fault, no NaN or Inf, just wrong or missing logits.
The branch has since picked up two pieces of performance work on the same path, both originally reviewed as stacked PRs and now folded in: the decode grid sizing from #5711 and its follow-up, and the two instruction-level changes to the plain kernel from #5700. They are described in their own sections below and neither touches the correctness of the four fixes.
1. Block paging for non-preshuffled multi-token blocks. With Preshuffle=False and KVBlockSize > 1 the Gluon kernel used token positions as page-table columns and always read token 0's K values and scale from each physical block. Compact block tables caused illegal memory accesses; padding the table kept the reads in allocated memory but produced incorrect logits. Resolve the physical block with token_pos // KVBlockSize and add the in-block token offset to both the K and the scale address, in the initial loads and in the prefetch loop. This fixes the failures reproduced in #5591. Related: #5600.
2. KV caches past 2 GiB in the plain kernel. That kernel forms a per-token address from the page table, so physical_block * stride overflowed a 32-bit product and wrapped into another page once the cache crossed 2 GiB. Its KV and scale strides are now 64-bit for every shape and the loads go through global pointers. A size-dependent switch between a 32-bit and a 64-bit variant was considered and dropped: it gives one shape two ABIs behind one AOT directory name, and the measured cost of always using 64-bit is bounded (see Performance).
3. KV caches past 2 GiB in the preshuffle kernel. When ChunkKPerStage % KVBlockSize != 0, which is KVBlockSize=256 at ChunkK=256, the K and scale addresses came from the same 32-bit page-index product. Read them through a global pointer with the index promoted to 64 bits, the way the other branch of that kernel already does.
4. Preshuffle tail store reaching into the next output row. The branch that loads a page index per lane stored its last stage across the whole tile, including the columns past context_length that hold -inf. When the output width equals an unaligned context those columns land in the next row: with context_lengths=(3001, 513) and a compact output, row 1 lost its first 7 logits. Those three stores are now bounded by max_model_len, which the kernel's six other stores already did.
Changes
Correct block-table, K and scale addressing for sectioned, non-preshuffled caches, and keep negative positions in the backward-shifted first tile mapped to token 0 of physical block 0 after masking the page-table load.
Generate the new address arithmetic only for KVBlockSize > 1, preserving the original scalar-first expressions, code generation and register usage for KVBlockSize=1.
Use 64-bit KV and scale strides in the plain kernel unconditionally, and drop the now dead 32-bit load paths.
Promote the preshuffle per-stage K and scale addresses to 64 bits.
Bound the preshuffle per-lane stores by max_model_len.
Extend op_tests/test_pa_mqa_logits_offset.py: 48 paging cases (block sizes 1/16/64/128, chunks 64/256, compact and padded tables, randomized physical pages, per-token scales, short and empty contexts, MTP, multiple prefetch iterations) and 12 large-offset cases (plain B1/B64 and preshuffle B64/B256, each at the 2, 4 and 8 GiB boundaries) against an independent FP32 reference, plus the two existing output-offset cases.
Note for AOT users: the plain kernel's stride arguments changed from i32 to i64, its instruction stream changed again with the two optimizations below, and the preshuffle kernel's instruction stream changed, so cached .hsaco artifacts have to be regenerated from this branch. The grid change does not add to that — SplitKV is a runtime i32 argument, not a constexpr, so it is not part of the compile key.
Decode grid sizing
deepgemm_fp8_paged_mqa_logits derived SplitKV from the batch and rounded SplitKV up to a multiple of five, but the thing that has to line up with the CU count is the grid, and the two differ by a factor of TileQCount. At batch 16/32/64 on 256 CU that landed on 2.5 workgroups per CU, so half the CUs ran three and half ran two and the kernel waited for the deeper half. The grid is now sized directly at two workgroups per CU, clamped so splits that start past the end of the context are not launched.
Two per CU is not enough at the top of the batch range, where each workgroup ends up chewing 128 to 256 chunks with no queue behind it, so a second term raises SplitKV toward 32 chunks per workgroup — by at most 2x, because max_model_len is only an upper bound on the real context and a loose bound must not be able to over-split without limit.
Scoring each candidate rule by how far its pick sits from the best SplitKV measured at each of 42 shapes:
rule
exact
4x over-estimate
16x
64x
the original formula
7.69%
7.69%
7.69%
7.69%
two per CU (context-free)
0.85%
0.87%
0.89%
0.89%
+ cap 32 chunks/WG, unbounded
0.46%
1.69%
7.45%
20.11%
+ cap 32, at most 2x
0.56%
1.40%
2.87%
4.08%
Against the original formula, at N=131072:
layout
batch
SplitKV
grid
before
after
change
plain
1
520→512
520→512
5.95
5.96
+0.22%
plain
16
40→32
640→512
60.32
51.59
−14.46%
plain
64
10→16
640→1024
274.44
233.42
−14.95%
plain
128
10→8
1280→1024
469.96
456.88
−2.78%
plain
256
10→4
2560→1024
913.21
926.29
+1.43%
preshuffle
16
40→32
640→512
49.54
42.65
−13.92%
preshuffle
64
10→16
640→1024
249.40
220.28
−11.68%
preshuffle
128
10→8
1280→1024
465.27
445.93
−4.16%
Over 48 shapes (batch 1..256, context 8k/32k/128k, next_n 1 and 2, both layouts) the median is −2.01%, 21 shapes improve by more than 5%, the best is −18.90%, and zero mismatches. Batch 256 at a 128k context is the one shape that stays slower: its grid was already an exact 10 per CU so it never paid the quantisation cost, and its curve is a broad plateau on which the old value sat near the middle. Closing the remaining 1.9% would need the real context length, which lives in a device tensor.
The optional SplitKV argument added here is an override in the same spirit as the existing TotalCuCount; it is what lets both arms of the measurements come from a single binary. gfx1250 keeps its own formula, having had no part available to re-tune on.
Correctness for this part: 62 passed, plus a 91-case scan aimed at the split seams — awkward chunk counts, non-uniform context lengths including (8192, 8191, 1, 256, 257, 255, 65536, 3) and (20000, 3001, 513, 131072), contexts of length 1 and 2, exact multiples of ChunkK and one less, and KVBlockSize 1/16/64/256 on both layouts — zero mismatches over the whole output, masked region included.
Plain-path instruction-level optimizations
Two changes to the Preshuffle=False Gluon kernel. Both are unconditional; the shape gate on the first is a correctness condition, not a switch.
1. Hoist the KV block index and in-block offset out of the loop. The kernel recomputed token // KVBlockSize and token % KVBlockSize over a ChunkK-wide vector every iteration. KVBlockSize is a constexpr power of two, so that should be one shift and one AND per register, but it expanded to 64 instructions because context_idx is loop-variant and the compiler cannot fold through it. context_idx advances by ChunkK and the gate requires ChunkK % KVBlockSize == 0, so the modulo is loop-invariant and the quotient grows by a constant. The identity does not require context_idx to be KVBlockSize-aligned, and KVBlockSize > ChunkK leaves the quotient without a constant stride, so those shapes keep the general form.
2. Mask the logits after the head reduce, not before. The kernel wrote -inf into the whole (ChunkQ, ChunkK) accumulator before reducing over heads, one v_cndmask per accumulator register: 32 in the loop and 32 more in the epilogue. Masking the reduced logits needs four and is the same value, since summing ChunkQ copies of -inf is -inf. The preshuffle kernel already masks after its reduce at all four of its store sites. Removing the -inf write also unblocks packed FP32 in the epilogue.
in-loop integer address ops
v_cndmask
v_mul_f32
v_pk_add_f32
v_pk_mul_f32
v_pk_fma_f32
VGPR
before
168
98
132
35
0
0
186
+ 1
76
98
132
35
0
0
188
+ 2
76
42
68
18
16
16
190
Neither improves register pressure: all three allocate 192 VGPR, so occupancy stays at 2 waves/SIMD.
Measured on top of the grid change above. Three worktrees run back to back inside each round with the arm order rotated, eight rounds; the statistic is the median of the per-round paired ratio, since clocks are not locked here and only pairing cancels the drift. Preshuffle=True is untouched by both, so its paired ratio is the noise floor.
Batch
change 1
change 2
both
control (noise floor)
16
−0.58%
−2.83%
−3.57%
+0.09%
64
−0.40%
−1.02%
−1.36%
+0.01%
128
−0.12%
−0.69%
−0.80%
+0.06%
Change 2 carries almost all of the gain. Change 1 only just clears the noise floor at batch 16 and sits inside it at batch 128; it is worth keeping because it costs nothing and the instruction count genuinely drops, not because it is a measurable speedup on its own. Batch 1 does not resolve and no claim is made for it: over 16 paired rounds plain moves −0.97% with an IQR of [−3.08%, +0.28%] while the unchanged control moves +0.61% with an IQR of [−0.75%, +9.18%].
Both sides of the HoistKvAddr gate were measured at the same production scale:
KVBlockSize
ChunkK
gate
b=16
b=128
16
256
on
−2.88%
−0.66%
64
256
on
−3.57%
−0.80%
128
256
on
−3.95%
−0.89%
256
256
on
−5.02%
−1.38%
128
64
off
−2.21%
−1.38%
256
128
off
−0.58%
−0.35%
1
256
off
−2.96%
—
No shape regresses. The gated-off shapes still gain because change 2 is unconditional. KVBlockSize=1 takes the branch where the logical index is never computed and KVBlockSize > ChunkK takes the branch where it is computed but the hoist is off, so all three paths are exercised; op_tests/test_pa_mqa_logits_offset.py already parametrises block_size ∈ {1, 16, 64, 128} × chunk_k ∈ {64, 256}, which covers the same split for correctness.
Change 1 is bit-identical to its parent. Change 2 is not, because folding a multiply and an add into v_pk_fma_f32 skips the rounding of the intermediate product: 410363 of 2097152 logits move by at most 3.05e-05 on a ±273 range. Against an fp64 reference the two are equally far from the truth (mean absolute error 4.615302e-04 before, 4.615247e-04 after, identical maxima), because the error floor is the fp8 quantisation of q and k, not the fp32 epilogue.
All 430 measurement processes across these campaigns were 0-mismatched against the fp32 reference, with no NaN or Inf.
Testing
Environment: gfx950 (256 CU), ROCm 7.2.4, PyTorch 2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0, one physical GPU pinned per process, clocks not locked.
# regression module, JIT gluon kernels
ROCR_VISIBLE_DEVICES=1 PYTHONPATH=. python -m pytest -q op_tests/test_pa_mqa_logits_offset.py
# -> 62 passed# the original #5591 repro, unmodified
ROCR_VISIBLE_DEVICES=1 PYTHONPATH=. python repro_paged_mqa_logits_preshuffle_false.py
# -> [issue2] allclose=True mismatch=0/6000 (was 5968/6000)# -> [issue1] no illegal access, exit code 0 (was HIP error 700, exit code 1)# same repro with AOT loading enabled, after regenerating the artifacts
ROCR_VISIBLE_DEVICES=1 AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS=1 PYTHONPATH=. \
python repro_paged_mqa_logits_preshuffle_false.py
# -> mismatch=0/6000, no illegal access
ROCR_VISIBLE_DEVICES=1 AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS=1 PYTHONPATH=. \
python -m pytest -q op_tests/test_pa_mqa_logits_offset.py
# -> 2 passed, 60 skipped (the JIT-gated cases skip in AOT mode)
Defect 4 was also swept outside pytest with the same shape at cache sizes from 1 MiB to 8 GiB, context pairs (3001, 513), (3001, 512), (513, 3001), (513, 1025), (3072, 513) and (3001,), and TotalCuCount of 1, 2, 8, 256 and the default: KVBlockSize=64 and 256 now match the reference everywhere. Before the fix, every case whose first context was not a multiple of the KV block lost the leading logits of the next row.
Cost of the four fixes
This section predates the two performance sections above and is the cost of the correctness fixes alone, measured before the grid change; its absolutes are not comparable with the numbers there.
Decode, N=131072, H=32, D=128, next_n=1, ChunkK=256, WavePerEU=2, one process per point, median of three, accuracy checked over the whole output on every run.
# both files in one directory: the fixed test_mqa_logits.py from #5434 (commit# 849c7c2) for input generation, packing and the FP32 reference, plus the# driver belowforroundin 1 2 3;doforbatchin 1 16 64 128;doforlayoutin preshuffle plain;do
ROCR_VISIBLE_DEVICES=1 PYTHONPATH=. python run_perf.py \
--batch "$batch" --layout "$layout" --kv-block 64 \
--output "out/$layout-b$batch-r$round.json"donedonedone
Measured on this branch:
Layout
KVBlock
Batch
KV cache
us
TFLOPS
TB/s
mismatch
Preshuffle=False
64
1
0.02 GiB
7.258
147.9
2.457
0/131072
Preshuffle=False
64
16
0.26 GiB
58.647
292.9
4.864
0/2097152
Preshuffle=False
64
64
1.03 GiB
274.822
250.1
4.152
0/8388608
Preshuffle=False
64
128
2.06 GiB
470.838
291.9
4.847
0/16777216
Preshuffle=True
64
1
0.02 GiB
5.004
214.6
3.563
0/131072
Preshuffle=True
64
16
0.26 GiB
50.272
341.7
5.675
0/2097152
Preshuffle=True
64
64
1.03 GiB
250.720
274.1
4.551
0/8388608
Preshuffle=True
64
128
2.06 GiB
463.818
296.3
4.921
0/16777216
Preshuffle=True
256
64
1.03 GiB
237.888
288.9
4.797
0/8388608
Preshuffle=True
256
128
2.06 GiB
451.407
304.5
5.056
0/16777216
Per-change cost, from paired runs that alternate the two versions within each round. These are deltas only; absolute numbers from different sessions are not comparable, since an unchanged control moved by more than 10% between sessions on this unlocked machine.
Unconditional 64-bit strides in the plain kernel, KVBlockSize=64:
Batch
conditional
unconditional
delta
1
5.728
6.677
+16.55%
16
55.701
57.955
+4.05%
64
270.004
274.738
+1.75%
128
418.183
417.427
-0.18%
Batch 128 crosses 2 GiB, so both versions compile the same kernel there; its -0.18% is the noise floor of the setup. With KVBlockSize=1 the unconditional kernel is faster instead: 247.617 -> 95.281 us at batch 16 and 1053.010 -> 463.740 us at batch 64.
Preshuffle 64-bit addressing and the store bound:
KVBlock
Batch
before
after
delta
accuracy
256
64
250.599
238.254
-4.93%
0 -> 0 mismatched
256
128
449.150
451.121
+0.44%
508281/16777216 -> 0
64
128
464.583
463.802
-0.17%
0 -> 0 mismatched
Folding the page base into a buffer_load pointer fixes the same addressing but pays a descriptor setup per stage: +4.59% at batch 64 and +3.74% at batch 128, against +0.44% and -4.93% for the global-load form that was kept. Rounds did not overlap between arms, e.g. 247.898/250.599/251.677 before against 238.032/238.254/238.422 after at batch 64.
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 5614 --add-label <label>
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 opt this PR out.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Empty-context coverage is missing, and the regression tests should be relocated.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
op_tests/test_pa_mqa_logits_offset.py:149
The new regression matrix still contains only positive context lengths, so it never exercises the split_context_length <= 0 early-return path for an empty sequence even though empty contexts are part of the claimed coverage. Add a mixed batch containing a zero-length context to verify that the kernel leaves that row at -inf without touching the page table or output guards.
This reverts commit de3c504.
Routing non-preshuffled KVBlockSize>1 to the Triton kernel in AOT mode makes
the Gluon addressing fix of a7e2cd2 unreachable on that path, and silently
selects a kernel whose latency was not measured. On runtimes before Triton
3.4 that path is the only way to reach the Gluon kernel at all.
AOT directory names encode only shape and layout, never a kernel revision or
signature variant, so a cached binary can go stale for any kernel in this
file. That belongs in the cache key rather than in a per-shape dispatch
carve-out, which also leaves no way back once artifacts are rebuilt.
The accompanying test cases asserted the fallback instead of exercising the
fixed Gluon kernel, so the JIT parametrization is restored as well.
Signed-off-by: zhimding <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
AOT routing and corresponding regression coverage do not yet protect against stale unsafe Gluon binaries.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
aiter/ops/triton/gluon/pa_mqa_logits.py:224
This updates only the JIT Gluon source, but the AOT path still enters enable_gluon_pa_mqa_logits in aiter/ops/triton/attention/pa_mqa_logits.py, compiles this same Gluon function under the existing paged_mqa_logits...B{KVBlockSize}... cache key, and never routes non-preshuffle KVBlockSize > 1 to the block-aware Triton kernel. With AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS=1, an old cached artifact therefore remains unsafe despite this source change. Add the KVBlockSize > 1 and not Preshuffle selection before AOT loading (or otherwise version/invalidate the artifact).
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Affected AOT inputs may still load unsafe cached kernels, and the intended AOT fallback tests are skipped.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
op_tests/test_pa_mqa_logits_offset.py:265
This skip condition excludes every new regression case whenever AOT mode is enabled, because enable_jit_gluon_pa_mqa_logits_kernel is false in that mode. Consequently the promised AOT-fallback coverage (and protection against loading an unsafe cached Gluon binary) never runs; allow the cases on these architectures and let the wrapper select either the JIT Gluon or Triton fallback path.
get_gfx() not in ("gfx942", "gfx950") or not enable_jit_gluon_pa_mqa_logits_kernel,
The 2 GiB threshold gave one shape two ABIs: a 32-bit stride kernel for
small caches and a 64-bit one past the buffer descriptor range, told apart
only by a _kv64 suffix on the AOT directory. Compile the non-preshuffle
kernel with 64-bit KV and scale strides for every shape instead, so one
shape maps to one binary again and the dead 32-bit load paths go away.
Measured on gfx950 at N=131072, H=32, D=128, ChunkK=256, WavePerEU=2,
median of three processes per point, arms alternating within a round.
With KVBlockSize=64 the unconditional kernel costs +16.6% at batch 1
(5.728 -> 6.677 us), +4.1% at 16, +1.8% at 64, and -0.2% at 128, where
the cache already crossed 2 GiB and the kernel is unchanged, which puts
the noise floor of that setup near 0.2%. KVBlockSize=1 moves the other
way: 247.6 -> 95.3 us at batch 16 and 1053.0 -> 463.7 us at batch 64.
The preshuffle kernels keep 32-bit stride arguments; their addressing is
handled separately.
Signed-off-by: zhimding <[email protected]>
…kernel
Two defects in _gluon_deepgemm_fp8_paged_mqa_logits_preshuffle, both silent
until the KV cache is large or the context lengths are unaligned.
When ChunkKPerStage % KVBlockSize != 0, which is KVBlockSize=256 at
ChunkK=256, the K and scale addresses came from a 32-bit page-index product,
so a cache past 2 GiB wrapped into another page. Read them through a global
pointer with the index promoted to 64 bits, the way the per-lane branch
already does. Folding the page base into a buffer_load pointer also fixes the
addressing but costs a descriptor setup per stage, so it is not used here.
The per-lane branch stored its last stage across the whole tile, including
the columns past context_length that hold -inf. With an output width equal to
an unaligned context those columns land in the next row: context lengths
(3001, 513) lost the first 7 logits of row 1. Bound those three stores by
max_model_len, which the kernel's other stores already do.
Measured on gfx950 at N=131072, H=32, D=128, ChunkK=256, median of three
processes per point, arms alternating within a round:
KVBlockSize=256, batch 128, 2.06 GiB cache: 508281/16777216 mismatched
logits -> 0, and 449.150 -> 451.121 us (+0.44%)
KVBlockSize=256, batch 64, 1.03 GiB cache: clean before and after, and
250.599 -> 238.254 us (-4.93%)
KVBlockSize=64, batch 128, 2.06 GiB cache: clean before and after, and
464.583 -> 463.802 us (-0.17%)
The large-KV regression test now covers the preshuffle layout for
KVBlockSize=64 and 256 at the 2, 4 and 8 GiB boundaries. Its unaligned
context lengths and compact output width also cover the tail store.
Signed-off-by: zhimding <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Critical AOT lookup issues and unresolved specialization and test-coverage problems remain.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (5)
aiter/ops/triton/gluon/pa_mqa_logits.py:270
This unconditionally replaces the non-preshuffle buffer_load path with 64-bit gl.load addressing. There is no KV64 compile-time/host selection in this change, so ordinary caches below 2 GiB also take the slower global-load/i64 specialization, contradicting the claimed byte-identical small-cache path and adding overhead to the common case. Keep the existing buffer-load/i32 path for small extents and select the global/i64 path only for large caches.
# The KV strides are 64-bit, so a cache past the 2 GiB buffer descriptor
# range still addresses correctly. Global pointers, not buffer loads.
k_next = gl.load(KV_buffer + kv_offsets)
op_tests/test_pa_mqa_logits_offset.py:282
[verified] This parameterization creates 4 layout/block-size pairs × 3 boundary values = 12 large-input cases, so with 48 paging cases and 2 existing offset cases it yields 62 tests, not the stated 6/56. The validation summary and expected CI count are therefore inaccurate. Author must update the validation counts or reduce the parameterization to the claimed cases.
[verified] This test excludes gfx1250, but the diff changes the IS_GFX1250 preshuffle path from buffer loads to flat gl.load at the corresponding kernel sites. The new tests therefore cannot catch an arch-specific compile or address regression in that path. Author must add a gfx1250-compatible preshuffle case or split the unsupported plain cases so the preshuffle path is exercised there.
@pytest.mark.skipif(
get_gfx() not in ("gfx942", "gfx950") or not enable_jit_gluon_pa_mqa_logits_kernel,
reason="Requires the CDNA Gluon JIT paged MQA kernel",
op_tests/test_pa_mqa_logits_offset.py:37
This new preshuffle helper import bypasses the arch-aware aiter.ops.triton.utils.shuffle.shuffle_weight, which is the shared shuffle entry point for Triton code. Use that helper here rather than importing the legacy base implementation directly, so the test does not encode a layout that becomes wrong if this coverage is enabled for gfx1250.
from aiter.ops.shuffle import shuffle_weight
op_tests/test_pa_mqa_logits_offset.py:144
The new Gluon kernel coverage is being added to a flat op_tests/ module, while the repository's attention tests are organized under op_tests/triton_tests/attention/ (for example test_fp8_mqa_logits.py). Please move this new coverage into that category directory rather than extending the root-level legacy regression file.
@pytest.mark.skipif(
get_gfx() not in ("gfx942", "gfx950") or not enable_jit_gluon_pa_mqa_logits_kernel,
reason="Requires the CDNA Gluon JIT paged MQA kernel",
)
@pytest.mark.parametrize("block_size", [1, 16, 64, 128])
@pytest.mark.parametrize("chunk_k", [64, 256])
@pytest.mark.parametrize("padded_table", [False, True], ids=["compact", "padded"])
Keep the hoisted KV address math together with main's prefetch masks, and keep both the page-8 coverage and the gfx1250 block_size==1 gate.
Co-authored-by: Cursor <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Persistent scheduling lacks required correctness and benchmark coverage, the new kernel needs specialization metadata, and explicit SplitKV values require validation.
…tage
The non-persistent preshuffle kernel applies the causal mask only to the
last stage of each window and, on the large-page path, to the stage-0
stores. The window end is rounded up -- to a whole page when a stage holds
whole pages, to a whole chunk otherwise -- so when the padding nears a
stage, the first columns past an MTP row's causal end fall in the stage
before it, which the loop stores unmasked. Those columns get a finite logit
instead of -inf, and top-k can pick a future token. Page 64, ChunkK 128,
next_n 3 and context_length % 64 == 1 is one such case.
main has the same gap: its kernel fails at context 12801 with that config.
test_paged_mqa_logits_preshuffle only started catching it here because the
retuned grid runs TotalCuCount=1 as one split instead of ten, so the
257-token MTP row is one window rather than three one-chunk splits.
In the non-persistent path, rewrite those columns with -inf after the final
store. The rewrite uses the layout and offsets of the store that wrote them,
so the same lane performs both stores in program order. The persistent path
already masks every stage. The varctx kernel rounds its window the same way
and is not changed here.
Masking every loop stage instead also fixes it, but it reshuffled the
loop's s_waitcnt placement and cost up to 4.7% on MTP shapes. This keeps
the hot loop instruction-for-instruction identical. On gfx950, paired A/B
over page/ChunkK 64/128, 64/256 and 256/256, batch 16/128, next_n 1/3 and
context 32K/128K gives a median ratio of 0.9997; an A/A control stays
within 0.16%.
op_tests/test_pa_mqa_logits_offset.py: 125 passed. A random sweep over
page 8-256, ChunkK 128/256, next_n 1-4, SplitKV None/1/3/10 and contexts
near page and chunk boundaries passes 168/168; the previous kernel fails 7.
Co-authored-by: Cursor <[email protected]>
batch_size and slots were constexpr, so every new decode batch size built
another schedule binary. A batch 1-512 sweep on gfx950 compiled 512
variants, about 156 s on a cold cache and 0.3 s per new batch size. As
runtime arguments the same sweep compiles 16: one per power-of-two
BLOCK_B, plus Triton's default integer specialization.
The constexpr only turned the uniform branch's divisors into compile-time
constants, worth about 0.1-0.3 us per launch on a 2-11 us kernel that runs
once per decode step. The tables match the constexpr kernel bit for bit
over 1092 shape and context cases, including int64 context lengths and
explicit NumCTAs.
Co-authored-by: Cursor <[email protected]>
Replace the -(-a // b) ceil-divisions with triton.cdiv, and the hard-coded
2 workgroups per CU with WavePerEU, which is what it stood for:
waves_per_eu is passed to LLVM as both the minimum and the maximum, so one
residency wave is WavePerEU 4-warp workgroups per CU. The grid is unchanged
at the default WavePerEU=2; other values scale it again, as main's formula
did.
Co-authored-by: Cursor <[email protected]>
This diff introduces a separate public persistent-CTA scheduling API and a new persistent execution ABI, but the PR description only scopes the nonpersistent SplitKV grid retune, paging fixes, and plain-path instruction changes. That independent runtime surface increases review/AOT risk and is not part of the stated fix. Author must split the persistent scheduler into a follow-up PR or document its production contract and validate it separately.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Four defects in the paged MQA logits decode path, all silent: no fault, no NaN or Inf, just wrong or missing logits.
The branch has since picked up two pieces of performance work on the same path, both originally reviewed as stacked PRs and now folded in: the decode grid sizing from #5711 and its follow-up, and the two instruction-level changes to the plain kernel from #5700. They are described in their own sections below and neither touches the correctness of the four fixes.
1. Block paging for non-preshuffled multi-token blocks. With
Preshuffle=FalseandKVBlockSize > 1the Gluon kernel used token positions as page-table columns and always read token 0's K values and scale from each physical block. Compact block tables caused illegal memory accesses; padding the table kept the reads in allocated memory but produced incorrect logits. Resolve the physical block withtoken_pos // KVBlockSizeand add the in-block token offset to both the K and the scale address, in the initial loads and in the prefetch loop. This fixes the failures reproduced in #5591. Related: #5600.2. KV caches past 2 GiB in the plain kernel. That kernel forms a per-token address from the page table, so
physical_block * strideoverflowed a 32-bit product and wrapped into another page once the cache crossed 2 GiB. Its KV and scale strides are now 64-bit for every shape and the loads go through global pointers. A size-dependent switch between a 32-bit and a 64-bit variant was considered and dropped: it gives one shape two ABIs behind one AOT directory name, and the measured cost of always using 64-bit is bounded (see Performance).3. KV caches past 2 GiB in the preshuffle kernel. When
ChunkKPerStage % KVBlockSize != 0, which isKVBlockSize=256atChunkK=256, the K and scale addresses came from the same 32-bit page-index product. Read them through a global pointer with the index promoted to 64 bits, the way the other branch of that kernel already does.4. Preshuffle tail store reaching into the next output row. The branch that loads a page index per lane stored its last stage across the whole tile, including the columns past
context_lengththat hold-inf. When the output width equals an unaligned context those columns land in the next row: withcontext_lengths=(3001, 513)and a compact output, row 1 lost its first 7 logits. Those three stores are now bounded bymax_model_len, which the kernel's six other stores already did.Changes
KVBlockSize > 1, preserving the original scalar-first expressions, code generation and register usage forKVBlockSize=1.max_model_len.op_tests/test_pa_mqa_logits_offset.py: 48 paging cases (block sizes 1/16/64/128, chunks 64/256, compact and padded tables, randomized physical pages, per-token scales, short and empty contexts, MTP, multiple prefetch iterations) and 12 large-offset cases (plainB1/B64and preshuffleB64/B256, each at the 2, 4 and 8 GiB boundaries) against an independent FP32 reference, plus the two existing output-offset cases.Note for AOT users: the plain kernel's stride arguments changed from
i32toi64, its instruction stream changed again with the two optimizations below, and the preshuffle kernel's instruction stream changed, so cached.hsacoartifacts have to be regenerated from this branch. The grid change does not add to that —SplitKVis a runtimei32argument, not aconstexpr, so it is not part of the compile key.Decode grid sizing
deepgemm_fp8_paged_mqa_logitsderivedSplitKVfrom the batch and rounded SplitKV up to a multiple of five, but the thing that has to line up with the CU count is the grid, and the two differ by a factor ofTileQCount. At batch 16/32/64 on 256 CU that landed on 2.5 workgroups per CU, so half the CUs ran three and half ran two and the kernel waited for the deeper half. The grid is now sized directly at two workgroups per CU, clamped so splits that start past the end of the context are not launched.Two per CU is not enough at the top of the batch range, where each workgroup ends up chewing 128 to 256 chunks with no queue behind it, so a second term raises
SplitKVtoward 32 chunks per workgroup — by at most 2x, becausemax_model_lenis only an upper bound on the real context and a loose bound must not be able to over-split without limit.Scoring each candidate rule by how far its pick sits from the best
SplitKVmeasured at each of 42 shapes:Against the original formula, at
N=131072:Over 48 shapes (batch 1..256, context 8k/32k/128k,
next_n1 and 2, both layouts) the median is −2.01%, 21 shapes improve by more than 5%, the best is −18.90%, and zero mismatches. Batch 256 at a 128k context is the one shape that stays slower: its grid was already an exact 10 per CU so it never paid the quantisation cost, and its curve is a broad plateau on which the old value sat near the middle. Closing the remaining 1.9% would need the real context length, which lives in a device tensor.The optional
SplitKVargument added here is an override in the same spirit as the existingTotalCuCount; it is what lets both arms of the measurements come from a single binary.gfx1250keeps its own formula, having had no part available to re-tune on.Correctness for this part: 62 passed, plus a 91-case scan aimed at the split seams — awkward chunk counts, non-uniform context lengths including
(8192, 8191, 1, 256, 257, 255, 65536, 3)and(20000, 3001, 513, 131072), contexts of length 1 and 2, exact multiples ofChunkKand one less, andKVBlockSize1/16/64/256 on both layouts — zero mismatches over the whole output, masked region included.Plain-path instruction-level optimizations
Two changes to the
Preshuffle=FalseGluon kernel. Both are unconditional; the shape gate on the first is a correctness condition, not a switch.1. Hoist the KV block index and in-block offset out of the loop. The kernel recomputed
token // KVBlockSizeandtoken % KVBlockSizeover aChunkK-wide vector every iteration.KVBlockSizeis aconstexprpower of two, so that should be one shift and one AND per register, but it expanded to 64 instructions becausecontext_idxis loop-variant and the compiler cannot fold through it.context_idxadvances byChunkKand the gate requiresChunkK % KVBlockSize == 0, so the modulo is loop-invariant and the quotient grows by a constant. The identity does not requirecontext_idxto beKVBlockSize-aligned, andKVBlockSize > ChunkKleaves the quotient without a constant stride, so those shapes keep the general form.2. Mask the logits after the head reduce, not before. The kernel wrote
-infinto the whole(ChunkQ, ChunkK)accumulator before reducing over heads, onev_cndmaskper accumulator register: 32 in the loop and 32 more in the epilogue. Masking the reduced logits needs four and is the same value, since summingChunkQcopies of-infis-inf. The preshuffle kernel already masks after its reduce at all four of its store sites. Removing the-infwrite also unblocks packed FP32 in the epilogue.v_cndmaskv_mul_f32v_pk_add_f32v_pk_mul_f32v_pk_fma_f32Neither improves register pressure: all three allocate 192 VGPR, so occupancy stays at 2 waves/SIMD.
Measured on top of the grid change above. Three worktrees run back to back inside each round with the arm order rotated, eight rounds; the statistic is the median of the per-round paired ratio, since clocks are not locked here and only pairing cancels the drift.
Preshuffle=Trueis untouched by both, so its paired ratio is the noise floor.Change 2 carries almost all of the gain. Change 1 only just clears the noise floor at batch 16 and sits inside it at batch 128; it is worth keeping because it costs nothing and the instruction count genuinely drops, not because it is a measurable speedup on its own. Batch 1 does not resolve and no claim is made for it: over 16 paired rounds plain moves −0.97% with an IQR of [−3.08%, +0.28%] while the unchanged control moves +0.61% with an IQR of [−0.75%, +9.18%].
Both sides of the
HoistKvAddrgate were measured at the same production scale:No shape regresses. The gated-off shapes still gain because change 2 is unconditional.
KVBlockSize=1takes the branch where the logical index is never computed andKVBlockSize > ChunkKtakes the branch where it is computed but the hoist is off, so all three paths are exercised;op_tests/test_pa_mqa_logits_offset.pyalready parametrisesblock_size ∈ {1, 16, 64, 128} × chunk_k ∈ {64, 256}, which covers the same split for correctness.Change 1 is bit-identical to its parent. Change 2 is not, because folding a multiply and an add into
v_pk_fma_f32skips the rounding of the intermediate product: 410363 of 2097152 logits move by at most3.05e-05on a±273range. Against an fp64 reference the two are equally far from the truth (mean absolute error4.615302e-04before,4.615247e-04after, identical maxima), because the error floor is the fp8 quantisation ofqandk, not the fp32 epilogue.All 430 measurement processes across these campaigns were 0-mismatched against the fp32 reference, with no NaN or Inf.
Testing
Environment: gfx950 (256 CU), ROCm 7.2.4, PyTorch
2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0, one physical GPU pinned per process, clocks not locked.The repro script is PR #5591's file at commit
81d4380.Defect 4 was also swept outside pytest with the same shape at cache sizes from 1 MiB to 8 GiB, context pairs
(3001, 513),(3001, 512),(513, 3001),(513, 1025),(3072, 513)and(3001,), andTotalCuCountof 1, 2, 8, 256 and the default:KVBlockSize=64and256now match the reference everywhere. Before the fix, every case whose first context was not a multiple of the KV block lost the leading logits of the next row.Cost of the four fixes
This section predates the two performance sections above and is the cost of the correctness fixes alone, measured before the grid change; its absolutes are not comparable with the numbers there.
Decode,
N=131072,H=32,D=128,next_n=1,ChunkK=256,WavePerEU=2, one process per point, median of three, accuracy checked over the whole output on every run.Measured on this branch:
Per-change cost, from paired runs that alternate the two versions within each round. These are deltas only; absolute numbers from different sessions are not comparable, since an unchanged control moved by more than 10% between sessions on this unlocked machine.
Unconditional 64-bit strides in the plain kernel,
KVBlockSize=64:Batch 128 crosses 2 GiB, so both versions compile the same kernel there; its -0.18% is the noise floor of the setup. With
KVBlockSize=1the unconditional kernel is faster instead: 247.617 -> 95.281 us at batch 16 and 1053.010 -> 463.740 us at batch 64.Preshuffle 64-bit addressing and the store bound:
Folding the page base into a
buffer_loadpointer fixes the same addressing but pays a descriptor setup per stage: +4.59% at batch 64 and +3.74% at batch 128, against +0.44% and -4.93% for the global-load form that was kept. Rounds did not overlap between arms, e.g. 247.898/250.599/251.677 before against 238.032/238.254/238.422 after at batch 64.run_perf.py