Skip to content

agx: share shifted array indices on M5 (q4_0 mat-vec) - #1428

Merged
RyanTheTide merged 3 commits into
aurora-wipfrom
wip/agx-m5-shifted-index
Dec 1, 2026
Merged

RyanTheTide merged 3 commits into
aurora-wipfrom
wip/agx-m5-shifted-index

Conversation

@satchlj

@satchlj satchlj commented Nov 30, 2026

Copy link
Copy Markdown
Member

Problem

On AGX4 (M5 Max), llama.cpp token generation is limited by the q4_0 matrix-vector shader (mul_mat_vec_q4_0_f32_f32, used for n=1 because this driver reports no accelerated int8 dot product). The shader is issue-bound, not memory-bound: its unrolled loop spends 360 ALU per 4 iterations on 32 loads, and about 96 of those recompute array indices that differ only by a constant before a shift.

Change

Three commits (on top of #1358, now merged):

  1. agx: share shifted array indices between unrolled iterations on M5. A new pass rewrites a + ((y + c) >> s) from an earlier sibling access in the same block as one add. On this hardware a binding is at most INT32_MAX bytes and the index feeds an access-chain multiply, so a wrap that changed the result would make one of the two accesses out of bounds. It runs before speculation and only on non-speculatable, non-robust accesses.
  2. agx: index M5 accesses with non-power-of-two strides in bytes. The existing byte-offset folding now also applies to 16- and 32-bit accesses, so q4_0's 18-byte blocks get their +144/+288/+432 byte offsets as load immediates.
  3. agx: keep the higher-occupancy compile when sharing shifted indices. Where the pass fires and the result runs fewer threads, compile again without it and keep the higher-occupancy result, like the existing unroll-factor choice.

Results (J775c, M5 Max)

Same session, mesa#1358 head 40acc58f345 against this head a024158, MESA_SHADER_CACHE_DISABLE=true.

test-backend-ops -b Vulkan0 -o MUL_MAT,MUL_MAT_ID,GET_ROWS: passes (2/2 backends OK, 0 failures).

test-backend-ops perf -o MUL_MAT, n=1:

shape before after change
q4_0 m=4096 k=4096 18.44 µs 14.51 µs −21%
q4_0 m=11008 k=4096 42.82 µs 30.64 µs −28%
q4_0 m=4096 k=11008 42.98 µs 33.12 µs −23%
q4_0 m=4096 k=14336 55.30 µs 43.32 µs −22%
q6_K m=32000 k=4096 185.79 µs 187.29 µs +0.8%
q6_K m=4096 k=14336 70.23 µs 71.67 µs +2.0%

llama-2-7B Q4_0, fa=1, 5 repetitions, order before/after/after/before:

test before after
tg128 110.51, 110.58 113.24, 112.97 (+2.4%)
pp512 3236.3, 3233.2 3236.9, 3234.4 (unchanged)

Offline (shader-db through the drm shim, M5 Pro identity, same ISA): across 206 MUL_MAT / MUL_MAT_ID shaders, 57 change, 55 with fewer instructions and 2 with more (−4719 instructions, −4619 ALU in total); 20 use fewer GPRs and 2 more; 17 run more threads and none fewer. Cooperative-matrix matmul shaders do not change.

Not tested yet

  • The full Vulkan CTS at this head. The pass also runs on graphics stages, and a broader CTS run is queued.
  • FLASH_ATTN_EXT shaders (not compared offline).
  • The q6_K shaders get slightly slower here; the third commit already keeps their higher-occupancy compile.
  • Other GPU generations: the pass is limited to this hardware's binding-size guarantee.

llama.cpp reads block (row * ncols + col) / 32 of a quantized matrix and
vec4 ((col & ~31) + ((col & 31) >> 1)) / 4 of its vector, with col =
i * 256 + 8 * tid + 256 * k in the k-th unrolled iteration. The constant
256 * k sits under the shift, so every iteration computed its indices
from scratch and nothing folded the constant into the access.

Where c and c0 differ by a multiple of 2^s, (y + c) >> s is
((y + c0) >> s) + ((c - c0) >> s) unless y + c and y + c0 lie on
opposite sides of a 2^32 wrap, and then the two indices are
2^(32 - s) - |c - c0| / 2^s elements apart. M5 buffer bindings span at
most INT32_MAX bytes, so when that many elements of the array stride
cover 2^31 bytes, at most one of the two accesses is in bounds. When the
program performs both, in one block with nothing between them that ends
the invocation, the later index can be computed from the earlier one
with one add, and its constant then folds into the access offset.

The new pass runs before set_speculate(), which marks every access
speculatable under soft faults, and skips accesses that are already
speculatable or bounds-checked. Unrolled iterations write (x + 256k) & 31
for x & 31, so agx_nir_fold_aligned_masks and CSE now also run just
before it, to give every iteration the same terms.

Offline, on the llama.cpp MUL_MAT shaders compiled for M5 through the
drm shim, the unrolled loop of the Q4_0 matrix-vector shader goes from
160 to 119 integer instructions per four iterations (360 to 319 ALU in
all); the four iterations' vector reads share one index with byte
offsets 1024, 2048 and 3072. The cooperative matrix shaders do not
change.

Signed-off-by: Satya Benson <satya@benson.earth>
agx_nir_fold_m5_offsets gave accesses that differ by constants one
shared index and byte offsets only for power-of-two array strides and
byte buffers. The 18-byte blocks of a Q4_0 matrix, read 16 bits at a
time, are neither, so each unrolled iteration computed its own offset
(an add, a multiply by 18 and two more adds per row) even once their
indices differ by constants.

The argument for byte buffers does not depend on the access width:
zext(X + c) = zext(X + c0) + (c - c0) unless X + c wraps between them,
and then one of the offsets is past 2^32 - 2^16, outside every M5
buffer. Apply it to accesses of any width, indexed in bytes.

Offline, on the llama.cpp MUL_MAT shaders compiled for M5 through the
drm shim, the unrolled loop of the Q4_0 matrix-vector shader goes from
119 to 87 integer instructions per four iterations (319 to 287 ALU in
all; 360 before the previous commit), with the same 103 registers. The
Q6_K matrix-vector shader drops from 135 to 127 registers (768 to 832
threads), but its loop now rematerializes five byte masks and is 13
instructions longer. Across 110 MUL_MAT shaders the two commits change
40: 38 have fewer instructions and 2 more, 13 use fewer registers and 12
run more threads; none use more registers or fewer threads. The
cooperative matrix shaders do not change.

Signed-off-by: Satya Benson <satya@benson.earth>
Sharing one index between the unrolled iterations of a loop saves its
instructions, but the shared index stays live across the whole unrolled
body. In a long body that holds several of them, such as the NVFP4
MUL_MAT_ID matrix-vector shader (a 1500-instruction loop over four rows),
that raised the register count from 127 to 234 halves, 832 to 384
threads, while removing 227 instructions; the MXFP4 one went from 1024
to 896 threads.

When agx_nir_opt_shifted_index changed an M5 shader and the result is
below the occupancy of a register-light program, compile it again
without the pass and keep whichever runs more threads, as is already
done for the unroll factor. Also run the pass after the word merge and
the read-only loop load hoist instead of before them, still ahead of
set_speculate().

Offline, on the llama.cpp MUL_MAT (Q4_0, Q4_K, Q5_K, Q6_K, Q8_0, F16)
and MUL_MAT_ID shaders compiled for M5 through the drm shim, counting
the kept compile only, the three commits change 57 of 206 shaders: 55
have fewer instructions and 2 more (4719 fewer in all, 4619 fewer ALU),
20 use fewer registers and 2 use two halves more, 17 run more threads
and none fewer. The Q4_0 matrix-vector shader for one column has 1580
instructions (1653 before), 287 ALU in its unrolled loop of four
iterations (360 before), at 103 registers and 1024 threads. The
cooperative matrix shaders do not change.

Signed-off-by: Satya Benson <satya@benson.earth>
@satchlj

satchlj commented Nov 30, 2026

Copy link
Copy Markdown
Member Author

Broader Vulkan CTS at a024158 vs the parent 40acc58f345 on J775c (AGX4), case by case, MESA_SHADER_CACHE_DISABLE=true:

group cases result
dEQP-VK.compute.* (cooperative_matrix excluded, covered before) 13,781 identical (10,774 Pass, 3,007 NotSupported)
dEQP-VK.ssbo.* 12,225 identical
dEQP-VK.ubo.* 13,240 identical
dEQP-VK.spirv_assembly.instruction.compute.* 19,906 identical
dEQP-VK.memory_model.* 18,530 identical
dEQP-VK.glsl.indexing.* (vertex/fragment/geometry/tessellation stages) 760 identical

78,442 cases, 0 differing. The one Fail, spirv_assembly.instruction.compute.ptr_access_chain.workgroup_bad_stride, fails on both arms. With the earlier row (tg128 +2.4%, MUL_MAT/MUL_MAT_ID/GET_ROWS pass), marking ready.

@satchlj
satchlj marked this pull request as ready for review November 30, 2026 20:03
@satchlj
satchlj requested review from a team and DjDeveloperr as code owners November 30, 2026 20:03

@aurora-silicon-review aurora-silicon-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MERGE at a024158d

Blockers: none

Checked:

  • Full 5-file diff (agx_compile.c, agx_nir.h, agx_nir_fold_m5_offsets.c, agx_nir_opt_shifted_index.c, meson.build, +415/-21), MERGEABLE against aurora-wip.
  • Strict M5-only gating: agx_nir_opt_shifted_index, agx_nir_fold_m5_offsets, and the occupancy fallback in agx_compile_shader_nir_unrolled() are all gated on m5 && !g18_scans (AGX_ISA_ENCODING_AGX3C && !emit_agx3d), leaving non-M5 GPUs untouched.
  • Soundness of agx_nir_opt_shifted_index: runs only when !checked_offsets (non-robust) and before set_speculate(), requires both shifts and their non-speculatable global accesses in the same straight-line segment (split on calls/jumps/terminate/demote), verifies agx_lin_binding_base() (<= INT32_MAX bytes), checks apart = ((1 << (32 - s)) - (|d| >> s)) * stride >= 2^31 (ruling out both indices being in [0, INT32_MAX / stride) across a 32-bit wrap), and dominates all rewritten uses via a->order < q->order.
  • Soundness of agx_nir_fold_m5_offsets: mem_access_size_align_cb already restricts global loads/stores to 8/16/32-bit (<= 4 components) before agx_optimize_nir(), and both agx_emit_load() and agx_emit_store() support AGX_NIR_MEMORY_INDEX_BYTES with 16-bit signed byte offsets.
  • Occupancy retry in agx_compile_shader_nir_unrolled(): properly saves/restores *key, rewinds pre_preamble_blob, and frees unused plain.binary / plain_post_opt / clone.
  • Exact-head a024158 hardware verification on J775c (M5 Max, AGX4): test-backend-ops (MUL_MAT, MUL_MAT_ID, GET_ROWS) 2/2 pass, q4_0 -21% to -28%, llama-2-7B Q4_0 tg128 +2.4% paired (pp512 unchanged), and 78,442 Vulkan CTS cases across compute/ssbo/ubo/spirv_assembly/memory_model/glsl.indexing (0 differing vs parent 40acc58f345).
Evidence
  • Checked agx_compile.c:13120-13158 (!checked_offsets, before set_speculate), agx_compile.c:13297 (agx_nir_fold_m5_offsets), agx_compile.c:13843-13866 (mem_access_size_align_cb), and agx_compile.c:2257/2478 (AGX_NIR_MEMORY_INDEX_BYTES).
  • Nit (non-blocking): in src/asahi/compiler/agx_nir_opt_shifted_index.c:531, (d & ((1 << a->s) - 1)) uses a signed int 1 while a->s can be 1..31, which is signed-shift UB if a->s == 31 under UBSan; (UINT64_C(1) << a->s) - 1 avoids it.

@RyanTheTide

Copy link
Copy Markdown

@DjDeveloperr, code-owner heads-up: App approval at a024158dc090 from a different lane. This PR goes into the merge train's next combined A/B (aurora-wip 84ba0bee + #570 #1128 #1180 #1184 #1260 #1266 #1424 #1428 #1430 #1435) on M1 Pro G13S + M4 G16G. If that row is clean, I plan to land it via --admin under the 6-point rule no earlier than one hour from now, unless you post a hold.

@github-actions github-actions Bot added area:compiler Area from CODEOWNERS (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) needs-template PR body lacks Tested or Risk (bot) labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

Merge readiness at a024158d: not ready yet

Check Detail
CI at head ok no CI for this change (the hardware row is the gate)
Review no needs one approving review from Core or Omarchy Mac (not the author)
Requested changes ok none
Hardware row at head ok comment at a024158d
Conflicts ok none
PR text no add a 'Tested:' line; a 'Risk:' line (door and Macs) (guide)

Areas: area:compiler

Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels.

@RyanTheTide

Copy link
Copy Markdown

Merging at a024158dc090 (B2 merge train, 12-01 merge bar). Approval at this head: aurora-silicon-review[bot]. Row: j713 (M4 Air, G16G, fleet91) full VK+GL row of the M1 candidate vs tip: VK Pass 14679 vs 14659, GL Pass 7497 vs 7448, 0 firmware crashes/fail-stops; every Pass->non-Pass case re-ran clean (6 suspects passed 5/5 alone on both builds). Traces: traces/gpu/20261201-b2-mesa-M1. CI: mesa train M1 = aurora-wip 69a6b8d + #570 #1180 #1184 #1266 #1428 #1435 #1415 #1433 #1437 #631 #664 #673 (candidate e56f7487): host meson asahi+poly 351 OK / 26 fail vs tip 344 / 26 (same 26 pre-existing, 0 new; 7 new tests pass), agx_tests pass. Fork Actions don't run in this repo, so this local run is the CI. Revert: git revert -m 1 <merge commit>.

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

Labels

area:compiler Area from CODEOWNERS (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) needs-template PR body lacks Tested or Risk (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants