Skip to content

Size the MQA logits decode grid to the CU count, not the batch - #5711

Merged
zhiding512 merged 1 commit into
zhiding512/fix-paged-mqa-block-paging-20260917from
maki/mqa-splitkv-grid-20260920
Sep 21, 2026
Merged

zhiding512 merged 1 commit into
zhiding512/fix-paged-mqa-block-paging-20260917from
maki/mqa-splitkv-grid-20260920

Conversation

@zhiding512

Copy link
Copy Markdown
Contributor

Stacked on #5614 (zhiding512/fix-paged-mqa-block-paging-20260917). One file, +14 -7.

The problem

deepgemm_fp8_paged_mqa_logits derives SplitKV from the batch and then rounds
SplitKV up to a multiple of five:

TileQCount = batch_size * next_n
SplitKV = (max(1, TotalCuCount // TileQCount) + 4) // 5 * 5 * WavePerEU
grid = (batch_size * next_n * SplitKV, 1, 1)

But the thing that has to line up with the CU count is the grid, and the two
differ by a factor of TileQCount. So where the grid lands is decided by that
factor rather than by the machine:

batch SplitKV grid workgroups per CU (256 CU)
1 520 520 2.03
4 130 520 2.03
16 40 640 2.50
32 20 640 2.50
64 10 640 2.50
128 10 1280 5.00

At 2.5 per CU half the CUs run three workgroups and half run two, and the kernel
waits for the deeper half. Batch 128 happens to land on an exact 5, which is why
it was never paying this and why it barely moves here.

The change

Size the grid, not SplitKV:

SplitKV = max(1, ceil(2 * TotalCuCount / TileQCount))
SplitKV = min(SplitKV, max(1, ceil(max_model_len / ChunkK)))

The second line is an upper clamp only: a split whose start is already past the
end of the context returns immediately, so there is no reason to launch it.
max_model_len is the width of the logits buffer and is always >= the real
context, so the clamp is monotonically safe -- when it is loose it simply stops
binding and the first line stands.

gfx1250 keeps the old formula; no such part was available to re-tune on.

The new optional SplitKV argument is an override in the same spirit as the
existing TotalCuCount. It is what lets both arms of every measurement below
come from a single binary, and what makes the sweep reproducible.

Why two workgroups per CU

Sweeping SplitKV directly over 36 shapes -- batch 1/4/16/32/64/128 x context
8k/32k/128k x both layouts -- and scoring each candidate formula by how far its
pick sits from the best SplitKV measured at that shape:

formula mean regret worst regret
current 8.34% 23.78%
grid = 1 x CU 9.53% 37.63%
grid = 1.5 x CU 10.79% 37.69%
grid = 2 x CU 0.86% 5.04%
grid = 2.5 x CU 9.33% 23.78%
grid = 3 x CU 6.40% 19.33%
grid = 4 x CU 3.76% 14.41%
grid = 8 x CU 6.64% 25.53%

It is a sharp optimum, and the cliff is visible in the raw curve. Batch 64,
context 128k:

SplitKV grid per CU us regret
8 512 2.00 236.54 1.6%
10 (current) 640 2.50 273.95 17.6%
11 704 2.75 257.32 10.5%
16 1024 4.00 232.86 0.0%
32 2048 8.00 241.31 3.6%

The varctx path in this same file already sizes its grid as
TotalCuCount * WavePerEU, so this brings the two into agreement.

A better variant that was deliberately not taken

Adding a second term that also caps chunks per workgroup at 32 brings mean
regret to 0.50% and buys a further -2.9% (plain) / -3.8% (preshuffle) at batch
128 with a 128k context. It needs the context length, and the only bound the
host has is max_model_len -- the real lengths live in a GPU tensor and reading
them would mean a device sync on the decode critical path. Mean regret when that
bound over-estimates:

rule exact 2x 4x 8x 16x 64x
grid = 2 x CU (context-free) 0.86% 0.92% 0.88% 0.88% 0.91% 0.91%
+ cap 32 chunks/WG 0.50% 1.35% 1.61% 3.39% 6.94% 18.55%
+ cap 32, at most 2x 0.57% 1.16% 1.34% 1.71% 3.06% 4.46%
current (context-free) 8.34% 8.34% 8.34% 8.34% 8.34% 8.34%

op_tests/test_pa_mqa_logits_offset.py in this repo already exercises
max_model_len = 1<<20, which is a hundredfold over-estimate. Giving up 0.36
points of mean regret to be insensitive to how a caller sizes that buffer seemed
the better trade.

Measurements

gfx950 (MI355X), 256 CU, ROCm 7.2.4 / HIP 7.2.53211, PyTorch
2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0, bare host, clocks not locked, an
otherwise idle GPU confirmed with rocm-smi before each round.
KVBlockSize=64, ChunkK=256, WavePerEU=2, H=32, D=128.

One process per point, num_iters=101, mismatches counted over the whole
output against an fp32 reference. Both arms come from the same binary -- the
new SplitKV override reproduces the old formula's value exactly -- and the two
are run back to back, order reversed on even rounds, median of three. Raw
per-round values are in the report linked at the end.

42 shapes over batch 1..128, context 8k/32k/128k, next_n 1 and 2, both
layouts. Median -2.99%, 19 shapes better by more than 5%, best -19.06%, and
exactly one shape worse by more than 1%. Zero mismatches everywhere.

layout batch next_n context SplitKV grid before us after us change
plain 16 1 131072 40->32 640->512 58.74 47.55 -19.06%
plain 64 1 32768 10->8 640->512 58.50 47.51 -18.79%
plain 32 1 32768 20->16 640->512 32.69 26.64 -18.51%
plain 32 1 131072 20->16 640->512 138.69 113.26 -18.34%
plain 16 2 32768 20->16 640->512 32.60 26.64 -18.28%
plain 64 1 131072 10->8 640->512 274.11 237.67 -13.29%
plain 128 1 32768 10->4 1280->512 121.01 115.67 -4.41%
plain 128 1 8192 10->4 1280->512 26.91 26.07 -3.10%
plain 128 1 131072 10->4 1280->512 470.65 476.18 +1.17%
preshuffle 16 2 32768 20->16 640->512 18.82 15.33 -18.53%
preshuffle 32 1 131072 20->16 640->512 130.97 108.54 -17.12%
preshuffle 64 1 32768 10->8 640->512 51.20 43.16 -15.70%
preshuffle 32 1 8192 20->16 640->512 8.54 7.26 -14.96%
preshuffle 4 1 131072 130->128 520->512 15.83 13.56 -14.34%
preshuffle 16 1 131072 40->32 640->512 50.01 43.49 -13.04%
preshuffle 64 2 32768 10->4 1280->512 62.71 56.10 -10.53%
preshuffle 64 1 131072 10->8 640->512 250.75 225.34 -10.14%
preshuffle 64 1 8192 10->8 640->512 15.55 14.07 -9.54%
preshuffle 128 1 32768 10->4 1280->512 118.10 107.87 -8.66%
preshuffle 16 1 32768 40->32 640->512 15.69 14.61 -6.93%
preshuffle 128 1 8192 10->4 1280->512 24.23 22.89 -5.53%
preshuffle 128 1 131072 10->4 1280->512 463.60 456.21 -1.60%

The remaining 20 shapes move between -2.89% and +0.53%, 17 of them within +-1%.

The gains land exactly where the old grid was 640. The +1.17% at plain /
batch 128 / 128k is the only shape worse by more than a percent; its grid was
already an exact 5 per CU, so it had nothing to gain and the change costs it the
5-workgroup-deep schedule it happened to like. Preshuffle at batch 4 gaining
14.34% off 520 -> 512 says the cliff is steeper than the table suggests.

Correctness

  • op_tests/test_pa_mqa_logits_offset.py: 62 passed.
  • A scan aimed at the split seams, since a grid change moves where each
    workgroup's token range begins: the chunk counts where the split arithmetic is
    awkward, 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 against an fp32 reference over the whole output,
    masked region included.
  • Every one of the 42 performance processes also checked its full output; zero
    mismatches.

Not in this PR

  • The same SplitKV formula appears in deepgemm_fp8_paged_mqa_logits_stage1,
    a different entry point. Not touched and not measured.
  • The plain kernel splits with cdiv, so trailing splits can start past the end
    of the context and return having done nothing -- at batch <= 16 that strands up
    to half the grid for roughly half of all context lengths. Switching it to the
    even split the preshuffle kernel already uses is worth up to -18% on the
    affected shapes but costs a flat ~+1% where the old form already used the whole
    grid, by a mechanism I could not pin down (identical VGPR/SGPR/spill, five more
    instructions). Left out deliberately; the data is in section 6.2 of the report.
  • gfx1250 and gfx942 are unmeasured. gfx1250 keeps its existing formula.
  • Performance was measured with uniform context lengths only. Variable contexts
    were covered for correctness; that case is what the varctx path exists for and
    it is untouched here.
  • Batch 1, and plain at batch 4 with a 32k context, are bimodal on this host
    (two clusters ~9% apart, present in the unmodified baseline as well). No
    conclusion is drawn from those points.

Full report, including all raw per-round values, the 36-shape sweep, and the
measurements that were discarded for contamination:
mqa_logits_splitkv_grid_20260920.md.

SplitKV was derived from the batch alone and then rounded up to a multiple
of five, so the workgroup count -- batch * next_n * SplitKV -- landed wherever
that left it. At batch 16, 32 and 64 it landed on 640 workgroups, 2.5 per CU
on a 256 CU part, so half the CUs ran three workgroups and half ran two and
the kernel waited for the deeper half. Rounding SplitKV instead of the grid is
what allowed that.

Pick SplitKV so the grid is two workgroups per CU, and clamp it to the chunk
count so splits that would start past the end of the context are not launched
at all.

Measured on gfx950 (MI355X, 256 CU), ROCm 7.2.4 / Triton 3.7.0, KVBlockSize=64,
ChunkK=256, WavePerEU=2, both arms from one binary with the new `SplitKV`
override reproducing the old value, three alternating rounds of 101 iterations,
median. 42 shapes over batch 1..128, context 8k/32k/128k, next_n 1 and 2, both
layouts; every arm checked against an fp32 reference with zero mismatches:

  batch 16  context 128k  plain       58.74 ->  47.55 us  -19.1%
  batch 32  context 128k  plain      138.69 -> 113.26 us  -18.3%
  batch 32  context  32k  plain       32.69 ->  26.64 us  -18.5%
  batch 64  context  32k  plain       58.50 ->  47.51 us  -18.8%
  batch 16  context  32k  preshuffle, next_n 2
                                      18.82 ->  15.33 us  -18.5%
  batch 64  context 128k  plain      274.11 -> 237.67 us  -13.3%
  batch 128 context  32k  preshuffle 118.10 -> 107.87 us   -8.7%
  batch 128 context 128k  plain      470.65 -> 476.18 us   +1.2%

Batch 128 at 128k context is the one shape that does not improve: its grid was
already an exact 5 workgroups per CU, so it was not paying the quantisation
cost. The worst regression over all 42 shapes is +1.2%.

A sweep of SplitKV over 36 shapes puts this rule within 0.9% of the best value
measured at each shape, against 8.3% for the old formula. A variant that also
caps chunks per workgroup reaches 0.5%, but it needs the context length, and
the only bound the host has is `max_model_len`; when that bound is 16x the real
context -- a wide preallocated logits buffer, which this repo's own tests
exercise at 1 MiB -- the variant degrades to 3-4.5% while this rule stays flat.
The varctx path in this file already sizes its grid the same way.

gfx1250 keeps the old formula: no such part was available to re-tune on.

The new `SplitKV` argument is an override in the same spirit as `TotalCuCount`,
and is what makes the sweep above reproducible.
@zhiding512
zhiding512 merged commit b9f5576 into zhiding512/fix-paged-mqa-block-paging-20260917 Sep 21, 2026
3 checks passed
@zhiding512
zhiding512 deleted the maki/mqa-splitkv-grid-20260920 branch September 21, 2026 02:04
zhiding512 added a commit that referenced this pull request Sep 21, 2026
…+ chunks

#5711 sized the decode grid at two workgroups per CU, which fixed the
2.5-per-CU quantisation at batch 16/32/64. Two per CU is not enough at the top
of the batch range: at batch 128 and 256 with a 128k context it leaves each
workgroup chewing 128 and 256 chunks with no queue behind it to rebalance
against, and both shapes sit off their optimum -- batch 128 by 4.2%, batch 256
by 2.4%.

Sweeping SplitKV over 42 shapes shows what the optima line up with at large
batch: `ceil(chunks / 32)`. At batch 128 and 256 that is the best SplitKV for
both the 128k and the 32k context, and only at an 8k context does the
two-per-CU floor take over. So raise SplitKV toward 32 chunks per workgroup,
but by at most 2x: `max_model_len` is only an upper bound on the context -- the
real lengths are in a device tensor and reading them would mean a sync on the
decode critical path -- and a loose bound must not be able to over-split
without limit.

Mean regret against the best SplitKV measured at each of the 42 shapes, by how
far `max_model_len` over-estimates the real context:

  formula                                 exact     4x    16x    64x
  the formula before #5711                7.69%  7.69%  7.69%  7.69%
  #5711, two per CU (context-free)        0.85%  0.87%  0.89%  0.89%
  this, unbounded                         0.46%  1.69%  7.45% 20.11%
  this, at most 2x                        0.56%  1.40%  2.87%  4.08%

op_tests/test_pa_mqa_logits_offset.py already exercises max_model_len = 1<<20
against much shorter contexts, so a hundredfold over-estimate is not
hypothetical. Bounding the second term costs 0.10 points when the bound is
exact and keeps the rule inside the formula it replaces even at 64x.

Measurements: gfx950 (MI355X, 256 CU), ROCm 7.2.4 / HIP 7.2.53211, PyTorch
2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0, bare host, clocks not locked, an
idle GPU confirmed with rocm-smi before each round. N=131072, H=32, D=128,
next_n=1, KVBlockSize=64, ChunkK=256, WavePerEU=2. Both arms come from one
binary -- the SplitKV override added in #5711 reproduces the value the other
rule would pick -- run back to back, order reversed on even rounds, median of
three, 101 iterations, full output checked against an fp32 reference.

The five shapes the decode sweep tests by default, against the formula #5711
replaced:

  layout      batch  SplitKV       grid        before      after   change    TB/s
  plain           1  520->512   520->512      5.95 us    5.96 us   +0.22%  3.00 -> 2.99
  plain          16   40->32    640->512     60.32 us   51.59 us  -14.46%  4.73 -> 5.53
  plain          64   10->16    640->1024   274.44 us  233.42 us  -14.95%  4.16 -> 4.89
  plain         128   10->8    1280->1024   469.96 us  456.88 us   -2.78%  4.86 -> 5.00
  plain         256   10->4    2560->1024   913.21 us  926.29 us   +1.43%  5.00 -> 4.93
  preshuffle      1  520->512   520->512      4.35 us    4.35 us   +0.12%  4.10 -> 4.10
  preshuffle     16   40->32    640->512     49.54 us   42.65 us  -13.92%  5.76 -> 6.69
  preshuffle     64   10->16    640->1024   249.40 us  220.28 us  -11.68%  4.58 -> 5.18
  preshuffle    128   10->8    1280->1024   465.27 us  445.93 us   -4.16%  4.91 -> 5.12
  preshuffle    256   10->4    2560->1024   780.91 us  785.89 us   +0.64%  5.85 -> 5.81

Against #5711 as it stands, rather than against the older formula, the shapes
this commit actually moves are:

  plain      batch  64  context 128k  SplitKV  8 -> 16  237.75 -> 233.32 us  -1.9%
  preshuffle batch  64  context 128k  SplitKV  8 -> 16  225.04 -> 219.48 us  -2.5%
  plain      batch 128  context 128k  SplitKV  4 ->  8  471.32 -> 457.62 us  -2.9%
  preshuffle batch 128  context 128k  SplitKV  4 ->  8  458.16 -> 444.81 us  -2.9%
  plain      batch 256  context 128k  SplitKV  2 ->  4  931.82 -> 926.74 us  -0.5%
  plain      batch 256  context  32k  SplitKV  2 ->  4  239.78 -> 237.68 us  -0.9%

Everything else picks the same SplitKV as #5711 and is the same launch.

Over the wider grid -- 48 shapes, batch 1..256, context 8k/32k/128k, next_n 1
and 2, both layouts -- the median against the pre-#5711 formula is -2.01%, 21
shapes are better by more than 5%, the best is -18.90%, and there are zero
mismatches. Four shapes come out worse by more than 1% on three rounds; a
501-iteration six-round re-run resolves three of them as noise:

  plain      batch   4  context 128k  +17.07% on three rounds, arms spread 42%;
                                      -1.13% at 501x6
  plain      batch   4  context  32k  +1.45%; at 501x6 both arms are bimodal
                                      (13% and 46% spread), unreadable
  preshuffle batch   4  context  32k  +1.18%; at 501x6 both arms are bimodal,
                                      unreadable
  plain      batch 256  context 128k  +1.78%, and +1.43% at 501x6 -- real

Batch 256 at a 128k context is the one shape that stays slower than the
original formula. Its grid was already an exact 10 workgroups per CU so it
never paid the quantisation cost, and its curve is a broad plateau from 6 to 51
workgroups per CU (regret 0.15% to 1.16%) on which the old SplitKV=10 sat near
the middle. This commit moves it from 2.4% off its optimum to 1.9% off; closing
the rest would need the real context length.

Correctness: op_tests/test_pa_mqa_logits_offset.py 62 passed, plus a 91-case
scan aimed at the split seams -- the chunk counts where the split arithmetic is
awkward, 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 against an fp32 reference over the whole output, masked
region included. All 48 performance processes also checked their full output.

gfx1250 is untouched and keeps its own formula.
azaidy pushed a commit that referenced this pull request Oct 13, 2026
…e KV offsets, retune the decode grid, and cut plain-path instruction count (#5614)

* Fix block paging in non-preshuffle MQA logits

Signed-off-by: zhimding <[email protected]>

* Extend existing paged MQA regression tests

Signed-off-by: zhimding <[email protected]>

* Avoid stale Gluon AOT binaries for block-paged MQA

Signed-off-by: zhimding <[email protected]>

* Revert "Avoid stale Gluon AOT binaries for block-paged MQA"

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]>

* Fix large KV offsets in non-preshuffle Gluon MQA

Signed-off-by: zhimding <[email protected]>

* Always use 64-bit KV strides in the plain 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]>

* Fix large KV offsets and the tail store in the preshuffle MQA logits 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]>

* Size the MQA logits decode grid to the CU count, not the batch

SplitKV was derived from the batch alone and then rounded up to a multiple
of five, so the workgroup count -- batch * next_n * SplitKV -- landed wherever
that left it. At batch 16, 32 and 64 it landed on 640 workgroups, 2.5 per CU
on a 256 CU part, so half the CUs ran three workgroups and half ran two and
the kernel waited for the deeper half. Rounding SplitKV instead of the grid is
what allowed that.

Pick SplitKV so the grid is two workgroups per CU, and clamp it to the chunk
count so splits that would start past the end of the context are not launched
at all.

Measured on gfx950 (MI355X, 256 CU), ROCm 7.2.4 / Triton 3.7.0, KVBlockSize=64,
ChunkK=256, WavePerEU=2, both arms from one binary with the new `SplitKV`
override reproducing the old value, three alternating rounds of 101 iterations,
median. 42 shapes over batch 1..128, context 8k/32k/128k, next_n 1 and 2, both
layouts; every arm checked against an fp32 reference with zero mismatches:

  batch 16  context 128k  plain       58.74 ->  47.55 us  -19.1%
  batch 32  context 128k  plain      138.69 -> 113.26 us  -18.3%
  batch 32  context  32k  plain       32.69 ->  26.64 us  -18.5%
  batch 64  context  32k  plain       58.50 ->  47.51 us  -18.8%
  batch 16  context  32k  preshuffle, next_n 2
                                      18.82 ->  15.33 us  -18.5%
  batch 64  context 128k  plain      274.11 -> 237.67 us  -13.3%
  batch 128 context  32k  preshuffle 118.10 -> 107.87 us   -8.7%
  batch 128 context 128k  plain      470.65 -> 476.18 us   +1.2%

Batch 128 at 128k context is the one shape that does not improve: its grid was
already an exact 5 workgroups per CU, so it was not paying the quantisation
cost. The worst regression over all 42 shapes is +1.2%.

A sweep of SplitKV over 36 shapes puts this rule within 0.9% of the best value
measured at each shape, against 8.3% for the old formula. A variant that also
caps chunks per workgroup reaches 0.5%, but it needs the context length, and
the only bound the host has is `max_model_len`; when that bound is 16x the real
context -- a wide preallocated logits buffer, which this repo's own tests
exercise at 1 MiB -- the variant degrades to 3-4.5% while this rule stays flat.
The varctx path in this file already sizes its grid the same way.

gfx1250 keeps the old formula: no such part was available to re-tune on.

The new `SplitKV` argument is an override in the same spirit as `TotalCuCount`,
and is what makes the sweep above reproducible.

* Split the MQA logits decode context further once a workgroup holds 32+ chunks

#5711 sized the decode grid at two workgroups per CU, which fixed the
2.5-per-CU quantisation at batch 16/32/64. Two per CU is not enough at the top
of the batch range: at batch 128 and 256 with a 128k context it leaves each
workgroup chewing 128 and 256 chunks with no queue behind it to rebalance
against, and both shapes sit off their optimum -- batch 128 by 4.2%, batch 256
by 2.4%.

Sweeping SplitKV over 42 shapes shows what the optima line up with at large
batch: `ceil(chunks / 32)`. At batch 128 and 256 that is the best SplitKV for
both the 128k and the 32k context, and only at an 8k context does the
two-per-CU floor take over. So raise SplitKV toward 32 chunks per workgroup,
but by at most 2x: `max_model_len` is only an upper bound on the context -- the
real lengths are in a device tensor and reading them would mean a sync on the
decode critical path -- and a loose bound must not be able to over-split
without limit.

Mean regret against the best SplitKV measured at each of the 42 shapes, by how
far `max_model_len` over-estimates the real context:

  formula                                 exact     4x    16x    64x
  the formula before #5711                7.69%  7.69%  7.69%  7.69%
  #5711, two per CU (context-free)        0.85%  0.87%  0.89%  0.89%
  this, unbounded                         0.46%  1.69%  7.45% 20.11%
  this, at most 2x                        0.56%  1.40%  2.87%  4.08%

op_tests/test_pa_mqa_logits_offset.py already exercises max_model_len = 1<<20
against much shorter contexts, so a hundredfold over-estimate is not
hypothetical. Bounding the second term costs 0.10 points when the bound is
exact and keeps the rule inside the formula it replaces even at 64x.

Measurements: gfx950 (MI355X, 256 CU), ROCm 7.2.4 / HIP 7.2.53211, PyTorch
2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0, bare host, clocks not locked, an
idle GPU confirmed with rocm-smi before each round. N=131072, H=32, D=128,
next_n=1, KVBlockSize=64, ChunkK=256, WavePerEU=2. Both arms come from one
binary -- the SplitKV override added in #5711 reproduces the value the other
rule would pick -- run back to back, order reversed on even rounds, median of
three, 101 iterations, full output checked against an fp32 reference.

The five shapes the decode sweep tests by default, against the formula #5711
replaced:

  layout      batch  SplitKV       grid        before      after   change    TB/s
  plain           1  520->512   520->512      5.95 us    5.96 us   +0.22%  3.00 -> 2.99
  plain          16   40->32    640->512     60.32 us   51.59 us  -14.46%  4.73 -> 5.53
  plain          64   10->16    640->1024   274.44 us  233.42 us  -14.95%  4.16 -> 4.89
  plain         128   10->8    1280->1024   469.96 us  456.88 us   -2.78%  4.86 -> 5.00
  plain         256   10->4    2560->1024   913.21 us  926.29 us   +1.43%  5.00 -> 4.93
  preshuffle      1  520->512   520->512      4.35 us    4.35 us   +0.12%  4.10 -> 4.10
  preshuffle     16   40->32    640->512     49.54 us   42.65 us  -13.92%  5.76 -> 6.69
  preshuffle     64   10->16    640->1024   249.40 us  220.28 us  -11.68%  4.58 -> 5.18
  preshuffle    128   10->8    1280->1024   465.27 us  445.93 us   -4.16%  4.91 -> 5.12
  preshuffle    256   10->4    2560->1024   780.91 us  785.89 us   +0.64%  5.85 -> 5.81

Against #5711 as it stands, rather than against the older formula, the shapes
this commit actually moves are:

  plain      batch  64  context 128k  SplitKV  8 -> 16  237.75 -> 233.32 us  -1.9%
  preshuffle batch  64  context 128k  SplitKV  8 -> 16  225.04 -> 219.48 us  -2.5%
  plain      batch 128  context 128k  SplitKV  4 ->  8  471.32 -> 457.62 us  -2.9%
  preshuffle batch 128  context 128k  SplitKV  4 ->  8  458.16 -> 444.81 us  -2.9%
  plain      batch 256  context 128k  SplitKV  2 ->  4  931.82 -> 926.74 us  -0.5%
  plain      batch 256  context  32k  SplitKV  2 ->  4  239.78 -> 237.68 us  -0.9%

Everything else picks the same SplitKV as #5711 and is the same launch.

Over the wider grid -- 48 shapes, batch 1..256, context 8k/32k/128k, next_n 1
and 2, both layouts -- the median against the pre-#5711 formula is -2.01%, 21
shapes are better by more than 5%, the best is -18.90%, and there are zero
mismatches. Four shapes come out worse by more than 1% on three rounds; a
501-iteration six-round re-run resolves three of them as noise:

  plain      batch   4  context 128k  +17.07% on three rounds, arms spread 42%;
                                      -1.13% at 501x6
  plain      batch   4  context  32k  +1.45%; at 501x6 both arms are bimodal
                                      (13% and 46% spread), unreadable
  preshuffle batch   4  context  32k  +1.18%; at 501x6 both arms are bimodal,
                                      unreadable
  plain      batch 256  context 128k  +1.78%, and +1.43% at 501x6 -- real

Batch 256 at a 128k context is the one shape that stays slower than the
original formula. Its grid was already an exact 10 workgroups per CU so it
never paid the quantisation cost, and its curve is a broad plateau from 6 to 51
workgroups per CU (regret 0.15% to 1.16%) on which the old SplitKV=10 sat near
the middle. This commit moves it from 2.4% off its optimum to 1.9% off; closing
the rest would need the real context length.

Correctness: op_tests/test_pa_mqa_logits_offset.py 62 passed, plus a 91-case
scan aimed at the split seams -- the chunk counts where the split arithmetic is
awkward, 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 against an fp32 reference over the whole output, masked
region included. All 48 performance processes also checked their full output.

gfx1250 is untouched and keeps its own formula.

* Hoist the KV block index and in-block offset out of the plain decode 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.

* Mask the plain decode logits after the head reduce, not before

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.

* Add persistent CTA scheduling for paged FP8 MQA decode

Build a reusable GPU schedule for plain and preshuffled decode, specialize the persistent query count, and balance work across variable contexts. Add paging, graph-replay, AOT, and wide-offset coverage plus reproducible benchmarks and measured tradeoffs.

Signed-off-by: root <[email protected]>

* Rewrite the MTP columns the preshuffle loop stores before the final stage

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.

* Pass the persistent schedule's batch size and slot count at runtime

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.

* Write the decode SplitKV sizing with triton.cdiv and WavePerEU

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.

---------

Signed-off-by: zhimding <[email protected]>
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