Repository navigation
[Triton/Gluon] [Perf] Cut per-iteration address math and cndmask in the non-preshuffle MQA logits decode kernel - #5700
Conversation
…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]>
b41f9c8 to
91d7a36
Compare
91d7a36
into
zhiding512/fix-paged-mqa-block-paging-20260917
|
Folded into #5614. Both commits ( 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 Note for anyone rebasing on top: the environment-variable toggles this PR originally carried ( |
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
mainwhen 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 // 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. Both now come from the first tile and the loop only adds. The identity does not requirecontext_idxto beKVBlockSize-aligned —residual_contextcan be anything — 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, costing 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-infand 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-infwrite also unblocks packed FP32 in the epilogue.ISA
ChunkQ=32, ChunkK=256, Preshuffle=False, KVBlockSize=64, WavePerEU=2:v_cndmaskv_mul_f32v_pk_add_f32v_pk_mul_f32v_pk_fma_f32Commit 2 also removes the
s_nop 5that 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 #5614Performance,
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=Trueis 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.
Absolute medians, us:
Preshuffle=TrueCommit 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
HoistKvAddrisKVBlockSize > 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:HoistKvAddrNo shape regresses. The gated-off shapes still gain, because commit 2 is unconditional and only commit 1 is gated.
KVBlockSize=1takes the branch wherelogical_kv_idx_nextis never defined andKVBlockSize > ChunkKtakes 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.pyalready parametrisesblock_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 inf2d4101and6e5e7f9. 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_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 versions are equally far from the truth:The error floor is the fp8 quantisation of
qandk, 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
.hsacoartifacts forPreshuffle=Falsehave to be regenerated from this branch. This is in addition to the regeneration #5614 already requires for itsi32toi64stride change. #5614's own SplitKV grid change does not require it —SplitKVis a runtimei32argument, not aconstexpr.Approaches measured and rejected
Recorded so they are not retried. Each was implemented, verified bit-correct, and measured on an idle gfx950.
ds_read_b64_tr_b8transpose read, replacingconvert_layout(k.T)ds_read_b128), but all LDS ops together are only 6.1% of stalls while thes_barrierands_waitcntthe round trip forces are 38%. Same barrier count, same LDS bytes, and the regression holds atChunkK=128where both variants fit two workgroups in 64 KB, so it is neither synchronisation nor occupancy — it is 53 LDS instructions against 37. Branchmaki/mqa-plain-tr-20260920._amd_iglp_sched_group_barriergroups displaces the hand-written software pipeline. Branchmaki/mqa-batched-store-20260918.ChunkK=128, which does reach 4 waves/SIMD at 114 VGPRChunkK=256.WavePerEUWavePerEU=4reaches 4 waves/SIMD but spills 128 B: 670.9 us against 470.2 at batch 128.WavePerEU=8is 1825.9 us.v_mul_f32intov_pk_mul_f32Remaining headroom, for context
The trace says what is left, and neither item is instruction count.
s_barrierfrom 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.