Skip to content

opencl: extend, speed up and widen the MQ/cluster decode flash-attention (head sizes 64-512, GQA 2-16) - #26430

Closed
wanghqc wants to merge 5 commits into
ggml-org:masterfrom
qualcomm:hq/opencl-fa-decode-mq-coverage-r0730
Closed

wanghqc wants to merge 5 commits into
ggml-org:masterfrom
qualcomm:hq/opencl-fa-decode-mq-coverage-r0730

Conversation

@wanghqc

@wanghqc wanghqc commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR widens kernel selection to the shapes that were falling through, speeds up the cluster
kernel, and moves gemma-4's DK=512 decode onto the GPU via FA on. Massive gains on TG are observed:
a number of models now run faster with FA on than off.

Issues

The Adreno decode flash-attention path selected its multi-query (MQ) and cluster kernels for a narrow set of shapes; everything else fell back to the q1/q1_split kernels. Those fallbacks are bad in two specific ways:

  • Register pressure. flash_attn_f32_f16_q1_split reports 1168 bytes of private memory per work item (the q8_0 twin 1664, the DV=512 q1 2048) against the ~512-byte budget where this compiler stops spilling; their workgroup cap drops to 192.
  • Redundant traffic. They run one workgroup per query head, so every head in a GQA group re-reads the same K and V rows. The MQ kernels read each row once per KV head.

Solutions

Commit 1 - coverage and cluster performance.

  • Adds MQ_GQA=2/3 programs at head_dim 128, an MQ_GQA=8/FA_CL_C=16 cluster at head_dim 64 (the stock GQA=8 width fails the DK_VEC % FA_CL_C check there), and the same cluster for q8_0 KV, which previously had no MQ route at all. - Four performance changes follow:
    • pooling the flash-decoding partials buffer (it was a clCreateBuffer per attention layer per token);
    • folding the per-head cluster reductions into one halving butterfly (32 sub_group_shuffle_xor per KV row down to 15, bit-identical)
    • a head split that runs an MQ_GQA = gqa/N program on N workgroups per KV head.
    • a 64-thread workgroup for it.

Commit 2 - gemma-4 DK=512 decode.

  • gemma-4 interleaves DK=256 sliding-window layers with DK=512 global ones. supports_op declined FLASH_ATTN_EXT for DK=512 at decode, so every global layer became a CPU island: 17 graph splits against 3, with that layer's K and V views (8.4 MB each at n_kv=4096) copied device-to-host every token.
  • Declining was nevertheless the better trade, because the only DK=512 decode kernel was the 2 KB/work-item q1 - forcing that back onto the GPU measures 27% slower than paying for the CPU islands.

The shared DK=512 program is built -D FA_DECODE_MINIMAL (dropping q1_vec) to stay under the shader compiler's host-memory ceiling, so that spilled fallback was all those layers had. Two new single-kernel programs fix that, the way FA_PREFILL_ONLY already isolates the BM tile:

  • FA_VEC_ONLY builds q1_vec alone (2 KB -> 192 B per work item) and FA_MQ_SPLIT_ONLY buildsq1_vec_mq_split alone. The same narrow build also serves DK=256 GQA=8, whose stock kernel requests a 192-thread workgroup that the X2-90 refuses per-kernel - it registered as compiled and then never dispatched.
  • These shapes carry their own n_kv floor, since gemma-4's window caps n_kv at 1024/256, below the split-tuned FD_MIN_N_KV; the floor is scoped to shapes that have a narrow kernel, so no other model's decode routing changes.

Results

tg32 at depth 4096 against the same tree with the new paths disabled, as base/patched/patched/base
sequences with a clock proxy sampled per arm.

model shape X2-90 X1-85 Adreno 840
gpt-oss-20b MXFP4 dk 64, GQA 8 +7.7% (+19.8% at d16384) - +8.3%
Qwen3-4B Q4_K_M dk 128, GQA 4 +4.8% (+5.9% at d16384) +18.0% +61%
Llama-3-8B Q4_0 dk 128, GQA 4 +3.2% - +42%
Mistral-7B v0.3 Q4_K_M dk 128, GQA 4 - - +33%
gemma-4 E4B Q4_0 dk 512 + dk 256 +44.5% (+59.6% at d8192) +21…37% +34…36%
gemma-4 E2B Q4_0 dk 512 + dk 256 +53.9% (+60.1% at d8192) +17…45% +96%

Two notes:

  • On the Adreno 840, GQA=4 at head_dim 128 previously ran slower with flash attention than
    without.
    • FA-on now beats FA-off by 9-13% on all three GQA=4 models there, so the "use -fa 0 on this device" workaround is no longer needed for that shape.
    • GQA=3 still trails FA-off by ~10% and is not addressed here.
  • On gemma-4, -fa auto previously resolved to disabled, because the DK=512 decline fired at the n_q == 1 probe shape. It now resolves to enabled. Users who never passed -fa will see this change.

Additional shapes and kernel improvements

Four further gaps in the same routing table, added after the first review pass.

Head size 128: the head split, and an n_kv floor of its own

The head-split program was never built at head size 128. It was fenced to head size 64, and the
narrow multi-query builder to head sizes 256 and 512, so a GQA-8 shape at 128 — Qwen3-30B-A3B's
decode shape — had no head-split form to route to and ran one work-group per KV head. Building it
there is worth, per-op on test-backend-ops at KV 4096 and 8192 with the split off then on:
+49.9% / +51.8% on an Adreno X2-90, +82.1% / +55.3% on an Adreno 840, and +112.4% / +119.3% on an
X1-85. Three generations, no inversion. End to end on Qwen3-30B-A3B that is +23.5% and +28.8% tg at
4096 and 8192 tokens of depth.

The multi-query routes inherited the flash-decoding split's n_kv floor, which answers a
different question — whether splitting the KV range across work-groups pays — and at 2048 it meant
the MQ routes did not engage at all below that length. Giving them their own floor at 32 gains, at
depth 0 and 1024: +12% / +63% on Qwen3-30B-A3B, +10% / +43% on Qwen3-4B, +1% / +8% on gpt-oss-20b,
and neutral on gemma-4-26B. Depth 4096 is flat everywhere, which is the control — above the old
floor the routing does not change, and it does not move.

FLASH_ATTN_EXT in test-backend-ops: 5117 and 2696 cases OK, 0 FAIL, unchanged from the
unpatched baseline build on the same device.

GQA ratio 16

gemma-4-12B has 16 query heads over a single KV head on its 8 global-attention layers, i.e.
DK=DV=512 at GQA ratio 16. The narrow multi-query decode gate admits ratios 4, 8 and 2, so that
shape matched no arm and every one of its decode dispatches fell back to
flash_attn_f32_f16_q1_vec, which has neither the flash-decoding split nor any query sharing and
therefore reads the whole KV cache once per query head — 16 times here. A dispatch trace on an
Adreno X2-90 shows 40 of 40 global-layer decode calls landing there. The model's SWA layers
(head size 256 at ratio 2) were already served by the narrow kernel and are unchanged.

Ratio 16 is now admitted with a head split of 8, so the program is MQ_GQA=2. At DV=512 the
per-head lane state is what pushes this shape past the occupancy cliff at roughly 512 bytes per
work item, which is the same reason the DK=512 ratio-8 shape uses a head split of 4 rather than 2.
That is measured rather than assumed: a head split of 4 (MQ_GQA=4) gains nothing at a 4096-token
depth and about a third of the gain at 8192.

gemma-4-12B Q4_0, tg32, one binary, this route off then on. Adreno X2-90 at the shipped default,
bracketed by opt-out arms that agree to 1%: 12.19 → 14.33 t/s (+17.6%) at depth 4096, and
10.28 → 13.40 (+30.3%) at 8192. Depth 0 is parity, because the MQ route barely engages at shallow
KV lengths. Against -fa 0 the same arm turns −7.4% and −16.0% at those depths into +8.9% and
+11.7%. On an Adreno 840, three matched pairs taken from the same start temperature: 3.63 → 4.46
(+22.9%) at depth 8192, with the three on-arms agreeing to 0.4%.

It is on by default, GGML_OPENCL_FA_MQN_GQA16=0 opts out, and there is no device predicate,
matching the ratio 4, 8 and 2 arms beside it. An X1-class part is the one generation with no usable
number and is deliberately not gated out: this model is 6.26 GiB against a per-context allocation
cap near 6 GB there, so runs abort in clCreateBuffer non-deterministically with this route off as
well. A7X and E17 parts never reach this function, since supports_op declines f16-KV flash
attention on both.

test-backend-ops gains the shape, which the suite has never covered — its generic sweep caps the
ratio-16 broadcast at head size 192, so a backend that selects its decode kernel per head size and
ratio had no correctness gate here at all. FLASH_ATTN_EXT reports 2698 OK / 0 FAIL at the shipped
default and with the route forced off.

One note for anyone reading those numbers on an Adreno device: the process exits without flushing
its final line, so whichever test case is emitted last silently never reports a verdict. The run
itself completes — only the tail line is lost — but it means case ordering matters. The new cases
are placed ahead of the existing head-size-512 block so that the kv=4099 tail case, which
exercises the non-multiple KV remainder, does not land in that slot.

DK=512: a build attempted before the compile options no longer latches

The DK=512 programs added here are compiled lazily from inside supports_op, which is reached
through the -fa auto probe during context creation. Their option string starts from
backend_ctx->kernel_compile_opts, and that field is written by load_cl_kernels(), which does not
run until the first buffer allocation. Nothing orders the two, so the probe can run with an empty
prefix — the build then loses -cl-std, the compiler rejects the subgroup extensions, and the
ensure_ helper latches a static failed flag that disables the shape for the rest of the process
even after the options exist.

The helper now declines to latch when the prefix is not up yet, so an early attempt is retried
rather than made permanent. The ordering problem itself is fixed separately and upstream, by
building the prefix in ggml_cl_init(); this change is the part that belongs with the DK=512
kernels.

The q8_0 cluster decode kernel: four improvements

The q8_0 cluster kernel flash_attn_f32_q8_0_q1_vec_mq_split_c8 introduced above for the
gpt-oss-class dk=64/gqa=8 shape is a fork of the f16 cluster kernel, and had not received an
optimisation round the f16 side did — so it was running an older shape of the same algorithm:

  1. Fused multi-head cluster reduce. The per-head loop ran MQ_GQA independent all-reduces over
    FA_CL_C lanes = 32 shuffles per KV row. A halving butterfly does it in 15. Rounds run in
    increasing xor distance, so each head's summation tree is pairwise identical to the per-head
    butterfly's and the scores are bit-identical.
  2. Head split. The gqa=8 shape now runs as two MQ_GQA=4 workgroups per KV head, halving the
    per-lane head state: private_mem 592 → 352 B/WI, against the f16 kernel's 368 for the same
    shape. Costs one extra read of each KV row.
  3. Mask broadcast and hoist. The mask was read inside the per-head score loop, after the cluster
    reduce — a late, scattered, dependent load, one per head where every head shares a row. At
    mask_ne2 == 1 it is now loaded once per position and issued at the top of the KV iteration
    alongside the K row.
  4. Mask subgroup staging. Over FA_CL_C iterations the subgroup's clusters touch exactly
    Q1_WG_SIZE consecutive mask positions — one per lane — so one coalesced load plus shuffles
    replaces FA_CL_C scattered loads. Deliberately not staged in local memory: the kernel is
    occupancy-bound and the head split already doubled the workgroups per KV head.

gpt-oss-20b (MXFP4, q8_0 attention weights) on the Adreno X2-90, -fa 1 -ctk q8_0 -ctv q8_0,
tg128. Each step measured as matched pairs in a single binary behind its own opt-out, alternating
which arm leads:

step @D4096 @d8192
baseline 30.96 26.96
+ fused cluster reduce 31.57 (+2.0%) 28.02 (+3.9%)
+ head split 33.01 (+4.6%) 29.86 (+6.8%)
+ mask broadcast/hoist 34.15 (+3.3%) 31.63 (+5.4%)
+ mask subgroup staging 34.54 (+1.1%) 32.14 (+1.7%)
cumulative +11.6% +19.2%

For reference an f16 KV cache on the same model and build is 35.70 / 33.46, so the gap to it
narrows from −13.3/−19.4% to −3.2/−3.9%. The value of a q8_0 KV cache here is capacity rather than
speed; this makes that capacity close to free.

What established that the deficit was not the dequantisation was a set of numerically-wrong
instrumented builds: deleting the KV read outright still left the kernel behind f16 (33.37 / 30.56
against 35.70 / 33.46), and dropping the per-lane scale load alone measured exactly 0. That is what
pointed at occupancy, and then at the mask. Those builds are not part of this PR.

test-backend-ops -o FLASH_ATTN_EXT on the X2-90: 2696 OK / 0 FAIL at every step of the work
above, with each knob both on and off. On this branch as it stands the suite reports 2724 OK / 0
FAIL
with the four knobs at their defaults and the same 2724 OK / 0 FAIL with all four forced
off, on an X2-90 and on an X1-85 alike. On both devices the head-split program is built only in the
first of those two runs, so the two arms are genuinely different code rather than a knob that
failed to reach the build.

Opt-outs, all default-on: GGML_OPENCL_FA_Q8_MHRED=0, GGML_OPENCL_FA_Q8_HEAD_SUB=0,
GGML_OPENCL_FA_Q8_MASK_BCAST=0, GGML_OPENCL_FA_Q8_MASK_SG=0.

This one is measured on a single device and a single model — no other device on hand has a
q8_0-KV gqa=8 head-size-64 shape — which is why every step is default-on behind its own opt-out.

Additional information

Verification.

  • test-backend-ops -o FLASH_ATTN_EXT: Adreno X2-90 2716 OK / 0 FAIL, Adreno 840 2719 OK / 0 FAIL.
  • Greedy generation at ~2700 tokens of context is byte-identical to -fa 0 on gemma-4 E2B and E4B.
  • Shapes outside the widened set are unchanged: Qwen3-4B-Q4_K_M -0.1%, gpt-oss-20b -0.8%, both inside run-to-run spread.
  • The Adreno 740 and 850 cannot reach these kernels: the A7X declines every mixed and quantized FA combination (clBuildProgram SIGSEGV) and E17 declines FLASH_ATTN_EXT outright. Confirmed on both devices.

K as a texture. In the narrow MQ programs K is bound as an image1d_buffer_t where one workgroup owns the whole GQA group. That is +3.5/+3.8% there, but -4.5/-9.3% where the group is split across workgroups, since each KV row is then re-read by every one of them and the texture path pays its per-access latency on each re-read rather than amortising it over one streaming pass. The path is gated on that condition.

Opt-outs, all default-on: GGML_OPENCL_FA_DK512_DECODE=0 restores the previous DK=512 decline, GGML_OPENCL_FA_HS_GQA4=0 the pre-head-split GQA=4 program, GGML_OPENCL_FA_MQN_KIMG=0 the buffer K path, GGML_OPENCL_FA_MQN_GQA16=0 the ratio-16 route, and the four GGML_OPENCL_FA_Q8_* knobs listed above.

Requirements

  • I have read and agree with the contributing guidelines Yes
  • AI usage disclosure: Yes, for prototyping and testing.

@github-actions github-actions Bot added ggml changes relating to the ggml tensor library for machine learning OpenCL Issues specific to the OpenCL backend labels Aug 2, 2026
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch 2 times, most recently from c443361 to 52bb000 Compare August 3, 2026 13:21
@github-actions github-actions Bot added the Apple Metal https://en.wikipedia.org/wiki/Metal_(API) label Aug 3, 2026
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch 2 times, most recently from 4f9d812 to 14243ff Compare August 3, 2026 17:26
wanghqc added a commit to qualcomm/llama.cpp that referenced this pull request Aug 3, 2026
Port of the change carved for ggml-org#26430, adapted to this branch.

supports_op declined FLASH_ATTN_EXT for DK=512 at decode, so gemma-4's
global-attention layers ran on the CPU backend - 17 graph splits against 3,
with each layer's K and V views copied device-to-host every token. That was
still the better trade while the only DK=512 decode kernel was the
2 KB/work-item q1, which the shared program is forced to fall back to because
it must be built FA_DECODE_MINIMAL to fit the shader compiler.

FA_VEC_ONLY and FA_MQ_SPLIT_ONLY build q1_vec and q1_vec_mq_split as
single-kernel programs, FA_HEAD_SUB is ported into both split kernels, and the
same narrow build serves DK=256 gqa=8 (whose stock kernel wants a 192-thread
workgroup the X2-90 refuses per-kernel). Those shapes carry their own n_kv
floor, so no other model's decode routing changes.

gemma-4 QAT Q4_0 tg32 on the X2-90: E4B 21.4 -> 30.9 @D4096, E2B 32.2 -> 49.6.
-fa auto on gemma-4 now resolves to enabled, where it previously resolved to
disabled. Opt out with GGML_OPENCL_FA_DK512_DECODE=0.
@wanghqc wanghqc changed the title opencl: extend the MQ/cluster decode flash-attention to more model shapes (optimization) opencl: extend, speed up and widen the MQ/cluster decode flash-attention (incl. gemma-4) Aug 3, 2026
@github-actions github-actions Bot added the testing Everything test related label Aug 4, 2026
@wanghqc wanghqc changed the title opencl: extend, speed up and widen the MQ/cluster decode flash-attention (incl. gemma-4) opencl: extend, speed up and widen the MQ/cluster decode flash-attention (head sizes 64-512, GQA 2-16) Aug 6, 2026
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch 3 times, most recently from ccea3c4 to c328196 Compare August 14, 2026 06:51
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch from c328196 to c276c36 Compare August 22, 2026 20:47
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch from c276c36 to 2d5898a Compare September 25, 2026 02:33
@lhez
lhez force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch from 97cd76c to ba2cec2 Compare October 7, 2026 21:47
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch from ba2cec2 to 61afeeb Compare October 8, 2026 11:02
@wanghqc
wanghqc force-pushed the hq/opencl-fa-decode-mq-coverage-r0730 branch from 61afeeb to 7fad9d0 Compare October 8, 2026 20:28
@wanghqc

wanghqc commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #30182 (same change, part of the consolidated OpenCL series #30178-#30186).

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

Labels

Apple Metal https://en.wikipedia.org/wiki/Metal_(API) ggml changes relating to the ggml tensor library for machine learning OpenCL Issues specific to the OpenCL backend testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant