Skip to content

[Triton/Gluon] [Perf] Cut per-iteration address math and cndmask in the non-preshuffle MQA logits decode kernel - #5700

Merged
zhiding512 merged 2 commits into
zhiding512/fix-paged-mqa-block-paging-20260917from
maki/mqa-plain-addr-20260920
Sep 21, 2026
Merged

zhiding512 merged 2 commits into
zhiding512/fix-paged-mqa-block-paging-20260917from
maki/mqa-plain-addr-20260920

Conversation

@zhiding512

@zhiding512 zhiding512 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two instruction-level optimizations to the non-preshuffle (Preshuffle=False) Gluon decode kernel. Both are unconditional; the shape gate on the first one is a correctness condition, not a toggle.

Stacked on #5614 so the diff shows only these two commits; the base will retarget to main when that merges. Nothing here changes the preshuffle path, the varctx kernel, or the Triton JIT kernels.

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. Both now come from the first tile and the loop only adds. The identity does not require context_idx to be KVBlockSize-aligned — residual_context can be anything — 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, costing 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 and unmasked columns are untouched. The preshuffle kernel already masks after its reduce at all four of its store sites; only the plain path did it the expensive way. Removing the -inf write also unblocks packed FP32 in the epilogue.

ISA

ChunkQ=32, ChunkK=256, Preshuffle=False, KVBlockSize=64, WavePerEU=2:

in-loop integer address ops v_cndmask v_mul_f32 v_pk_add_f32 v_pk_mul_f32 v_pk_fma_f32 VGPR
#5614 head 168 98 132 35 0 0 186
+ commit 1 76 98 132 35 0 0 188
+ commit 2 76 42 68 18 16 16 190

Commit 2 also removes the s_nop 5 that sat after the first VALU read of the accumulator — an MFMA-to-VALU RAW hazard that no longer applies once the epilogue is restructured.

Neither commit improves register pressure. VGPR goes 186 to 190 and all three allocate 192, so occupancy stays at 2 waves/SIMD. The two loop-carried index vectors in commit 1 cost slightly more than the div/mod temporaries they replace.

Testing

Environment: gfx950, 256 CU at 2.4 GHz, mclk 2000 MHz, ROCm 7.2.4, PyTorch 2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0. One physical GPU pinned, verified at 0% utilisation, 0% VRAM and no KFD process before the run; clocks not locked.

ROCR_VISIBLE_DEVICES=7 PYTHONPATH=. python -m pytest -q op_tests/test_pa_mqa_logits_offset.py
# -> 62 passed, unchanged from #5614

Performance, N=131072, H=32, D=128, next_n=1, KVBlockSize=64, ChunkK=256, WavePerEU=2, one process per point.

Method. Three worktrees — base, base+commit 1, base+both — run back to back inside each round, with the arm order rotated every round, eight rounds. The statistic is the median of the per-round paired ratio, not a ratio of per-arm medians: clocks are not locked on this box and the baseline drifts several percent over an eight-minute window, which only pairing cancels. Preshuffle=True is untouched by both commits, so base and head run the same kernel there and its paired ratio is the noise floor; it was measured separately with the same round structure.

Brackets are the min and max of the eight per-round ratios.

Batch commit 1 commit 2 both control (noise floor)
16 −0.58% [−1.63, −0.23] −2.83% [−4.03, −1.11] −3.57% [−4.85, −2.28] +0.09% [−0.43, +0.84]
64 −0.40% [−15.64, +0.04] −1.02% [−1.39, −0.69] −1.36% [−16.22, −1.10] +0.01% [−0.49, +0.15]
128 −0.12% [−0.36, +0.18] −0.69% [−0.85, −0.48] −0.80% [−0.92, −0.65] +0.06% [−0.13, +0.11]

Absolute medians, us:

Batch base + commit 1 + both Preshuffle=True
16 47.92 47.60 46.16 43.94
64 234.29 233.53 231.05 220.56
128 458.97 458.50 455.36 444.10

Commit 2 carries almost all of the gain. Commit 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. Sixteen paired rounds at num_iters=501: plain moves −0.97% with an IQR of [−3.08%, +0.28%], but the unchanged preshuffle control moves +0.61% with an IQR of [−0.75%, +9.18%]. The kernel is 7 us there and launch overhead dominates.

Shape coverage

HoistKvAddr is KVBlockSize > 1 and ChunkK % KVBlockSize == 0, so commit 1 has a gated-off path. Both sides were measured at the same production scale, three paired rounds:

KVBlockSize ChunkK HoistKvAddr 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 commit 2 is unconditional and only commit 1 is gated. KVBlockSize=1 takes the branch where logical_kv_idx_next is never defined and KVBlockSize > ChunkK takes the branch where it is defined but the hoist is off, so all three paths commit 1 introduces 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 gate split for correctness; this is the production-scale confirmation.

Across every campaign — three-arm 72, control 48, batch 1 64, shape sweep 66, plus 180 from an earlier loosely-paired run — all 430 processes were 0-mismatched against the fp32 reference with no NaN or Inf.

Re-measured after the rebase

The numbers above replace an earlier set taken on 8add88cf7, before #5614 picked up the SplitKV grid change in f2d4101 and 6e5e7f9. That change moved the baseline a long way — batch 16 from 58.41 to 47.92 us (−18.0%), batch 64 from 274.84 to 234.29 (−14.8%), batch 128 from 470.86 to 458.97 (−2.5%) — so the old absolutes are not comparable and everything was re-run on the new base.

The relative gains reproduce: −3.15% / −1.47% / −0.41% before, −3.57% / −1.36% / −0.80% now. Batch 128 was previously at the edge of what the measurement could resolve; tight pairing narrows the noise floor there to ±0.13% and makes it a readable result. That is a change in method, not in the code.

The ISA counts and the numerics analysis are unchanged, because the kernel is byte-identical to what was measured before — the only edit since was removing the two environment-variable toggles.

Numerics

Commit 1 is bit-identical: 0 of 2097152 logits differ at batch 16.

Commit 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 versions are equally far from the truth:

max abs err mean abs err rms err
before 3.839734e-03 4.615302e-04 6.016148e-04
after 3.839734e-03 4.615247e-04 6.016279e-04

The error floor is the fp8 quantisation of q and k, not the fp32 epilogue, and the change between the two versions is 15x below it.

Note for AOT users

The plain kernel's instruction stream changes, so cached .hsaco artifacts for Preshuffle=False have to be regenerated from this branch. This is in addition to the regeneration #5614 already requires for its i32 to i64 stride change. #5614's own SplitKV grid change does not require it — SplitKV is a runtime i32 argument, not a constexpr.

Approaches measured and rejected

Recorded so they are not retried. Each was implemented, verified bit-correct, and measured on an idle gfx950.

Approach Result
Hand-driven LDS staging with gfx950's ds_read_b64_tr_b8 transpose read, replacing convert_layout(k.T) 38–54% slower. The hardware transpose read is emitted (32 of them for 20 ds_read_b128), but all LDS ops together are only 6.1% of stalls while the s_barrier and s_waitcnt the round trip forces are 38%. Same barrier count, same LDS bytes, and the regression holds at ChunkK=128 where both variants fit two workgroups in 64 KB, so it is neither synchronisation nor occupancy — it is 53 LDS instructions against 37. Branch maki/mqa-plain-tr-20260920.
Pairing the two adjacent in-loop logits stores into one burst 13% slower, with VGPR, spills, LDS and occupancy all identical before and after. Moving the store across the _amd_iglp_sched_group_barrier groups displaces the hand-written software pipeline. Branch maki/mqa-batched-store-20260918.
ChunkK=128, which does reach 4 waves/SIMD at 114 VGPR 491.5 us against 471.1 for ChunkK=256.
Raising occupancy through WavePerEU WavePerEU=4 reaches 4 waves/SIMD but spills 128 B: 670.9 us against 470.2 at batch 128. WavePerEU=8 is 1825.9 us.
Hand-packing the epilogue v_mul_f32 into v_pk_mul_f32 Superseded — commit 2 gets it from the compiler for free. The lines involved are 0.69% and 1.15% of stalls, so a hand-written version was never worth it either.

Remaining headroom, for context

The trace says what is left, and neither item is instruction count. s_barrier from the LDS transpose round trip is 18.4% of stalls, and memory is 48.4%. On the memory side the fp32 logits write is 3% of the bytes but 11 percentage points of achievable bandwidth: an isolated reproduction of this kernel's exact access pattern reaches 70.2% of spec with the write removed and 59.0% with it, while the kernel itself measures 62.9%, i.e. already slightly ahead of a no-compute reproduction of its own memory pattern. Store granularity is not the lever — at matched byte counts, bursting four 512 B stores together is 7.3 points worse than one per stage.

After these two commits the plain path still trails preshuffle by 5.1% / 4.8% / 2.5% at batch 16 / 64 / 128, down from 9.1% / 6.2% / 3.3%. The rest is structural: the LDS round trip, and VGPR 190 against 92 with occupancy 2 against 5.

@zufayu
zufayu requested review from a team and Dewei-Wang-sh September 21, 2026 01:11
zhiding512 and others added 2 commits September 21, 2026 07:08
…loop

The non-preshuffle kernel recomputed token // KVBlockSize and
token % KVBlockSize over a ChunkK-wide vector on every iteration. The compiler
cannot fold either because context_idx is loop-variant, so an expression that is
one shift and one AND per register expanded to 64 instructions.

context_idx advances by ChunkK and ChunkK % KVBlockSize == 0, so the modulo is
the same in every iteration and the quotient grows by ChunkK // KVBlockSize.
Both now come from the first tile and the loop only adds. Correct for any
alignment of context_idx -- residual_context does not have to be a multiple of
KVBlockSize -- and gated off when KVBlockSize > ChunkK leaves the quotient
without a constant stride.

In-loop integer address instructions drop 168 -> 76. On its own that buys
almost nothing. N=131072, H=32, D=128, KVBlockSize=64, ChunkK=256, WavePerEU=2
on an idle gfx950, one process per point, eight rounds with the arm order
rotated, median of the per-round paired ratio against the parent commit:

  b=16   -0.58%  [-1.63, -0.23]
  b=64   -0.40%  [-15.64, +0.04]
  b=128  -0.12%  [-0.36, +0.18]

An unchanged Preshuffle=True control run the same way puts the noise floor at
+0.09% [-0.43, +0.84], +0.01% [-0.49, +0.15] and +0.06% [-0.13, +0.11], so b=128
is inside it and b=16 only just clears it.

That is the whole gain, and it is small for a reason the ATT trace already
showed: 71.7% of cycles are stalled on memory and barriers, VALU arithmetic is
not a stall category, and the removed instructions were issuing in the shadow of
those stalls. The hope that it would relieve register pressure did not hold
either -- VGPR goes 186 -> 188, since the two loop-carried index vectors cost
more than the div/mod temporaries they replace, and both still allocate 192 so
occupancy stays at 2 waves/SIMD.

Keep: it is a real improvement and costs nothing. Do not expect more from it.

Co-authored-by: Cursor <[email protected]>
The plain kernel wrote -inf into the whole (ChunkQ, ChunkK) accumulator before
reducing over heads, costing one v_cndmask per accumulator register: 32 in the
loop and 32 more in the epilogue. Masking the reduced logits instead needs four,
and is the same value -- summing ChunkQ copies of -inf is -inf, and unmasked
columns are untouched. The preshuffle kernel already masks after its reduce at
all four of its store sites; only the plain path did it the expensive way.

The -inf write was also blocking packed FP32 in the epilogue. With the
accumulator all finite the compiler emits 16 v_pk_mul_f32 and 16 v_pk_fma_f32 in
place of 64 scalar multiplies and 34 of the reduction adds.

ISA at ChunkQ=32, ChunkK=256, KVBlockSize=64, WavePerEU=2:

  v_cndmask       98 -> 42
  v_mul_f32      132 -> 68
  v_pk_add_f32    35 -> 18
  v_pk_mul_f32     0 -> 16
  v_pk_fma_f32     0 -> 16
  s_nop            5-wait after the first VALU read of the accumulator is gone
  VGPR           188 -> 190   (still allocates 192, so occupancy is unchanged)

Numerics. Folding a multiply and an add into v_pk_fma_f32 skips the rounding of
the intermediate product, so the output is not bit-identical: at b=16 410363 of
2097152 logits move, by at most 3.05e-05 on a +-273 range. Against an fp64
reference both versions are equally far from the truth -- mean absolute error
4.615302e-04 before and 4.615247e-04 after, identical maxima -- because the error
floor here is the fp8 quantisation of q and k, not the fp32 epilogue. The change
between the two versions is 15x smaller than that floor.

Same setup as the previous commit, median of the per-round paired ratio over
eight rounds. Against that commit, and against the merge base for both:

            this commit        both commits
  b=16   -2.83% [-4.03,-1.11]  -3.57% [-4.85,-2.28]
  b=64   -1.02% [-1.39,-0.69]  -1.36% [-16.22,-1.10]
  b=128  -0.69% [-0.85,-0.48]  -0.80% [-0.92,-0.65]

The Preshuffle=True control is +0.09% / +0.01% / +0.06% with a worst case of
+0.84% / -0.49% / -0.13%, so all six figures clear the noise floor. This commit
carries most of the gain of the pair. Absolute medians at b=128 are 458.97 ->
455.36 us, all 72 processes 0 mismatched against the fp32 reference.

The gain shrinks with batch for the reason the ATT trace shows: at b=128 the
2.06 GiB KV stream leaves 71.7% of cycles stalled on memory and barriers, and
VALU work issues in the shadow of those stalls.

Co-authored-by: Cursor <[email protected]>
@zhiding512
zhiding512 force-pushed the maki/mqa-plain-addr-20260920 branch from b41f9c8 to 91d7a36 Compare September 21, 2026 07:11
@zhiding512
zhiding512 merged commit 91d7a36 into zhiding512/fix-paged-mqa-block-paging-20260917 Sep 21, 2026
3 checks passed
@zhiding512
zhiding512 deleted the maki/mqa-plain-addr-20260920 branch September 21, 2026 07:52
@zhiding512

Copy link
Copy Markdown
Contributor Author

Folded into #5614. Both commits (ea05a794 and 91d7a365) were fast-forwarded onto zhiding512/fix-paged-mqa-block-paging-20260917 unchanged, so this branch and the base are now the same commit and the diff here is empty.

Keeping them as two commits there rather than squashing: the first is bit-identical to its parent and the second is not, and the numerics analysis in the second message only makes sense attached to that specific change.

The measurements, the shape coverage across the HoistKvAddr gate, and the AOT note from this PR's description have been merged into #5614's description. Closing.

Note for anyone rebasing on top: the environment-variable toggles this PR originally carried (AITER_MQA_PLAIN_HOIST_ADDR, AITER_MQA_PLAIN_MASK_AFTER_REDUCE) were removed before the fold; both optimizations are unconditional now. The remaining HoistKvAddr gate is a correctness condition on the shape, not a switch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant