Skip to content

agx/compiler: fold cooperative-matrix shared offsets and hoist invariant bases (+14.4% llama.cpp pp512) - #1280

Merged
RyanTheTide merged 1 commit into
aurora-wipfrom
satya/cmat-shared-offset-licm
Nov 28, 2026
Merged

RyanTheTide merged 1 commit into
aurora-wipfrom
satya/cmat-shared-offset-licm

Conversation

@satchlj

@satchlj satchlj commented Nov 28, 2026

Copy link
Copy Markdown
Member

What

Eliminates redundant per-iteration shared-memory address arithmetic in cooperative-matrix GEMM / flash-attention inner loops on AGX3 (llama.cpp mul_mm Q4_0 inner loop shrinks from 368 to 264 instructions; pp512 improves +14.37% on Apple M5 Max):

  1. agx_nir_lower_cmat.c (matrix_row, matrix_col, layout_coord):
    • Use nir_iadd_imm() instead of nir_ior_imm() for constant per-element row/column offsets (the element and lane bits are disjoint by construction).
    • Allows nir_opt_algebraic to distribute (base + k) * stride -> base * stride + k * stride, collapsing 6 stride multiplies in mul_mm to 2 and exposing constant element offsets to shared-offset folding.
  2. agx_nir_lower_shared_bitsize.c (agx_nir_opt_shared_byte_offsets):
    • Raise gather_sum() depth from 3 to 5 so distributed cooperative-matrix sums flatten cleanly, and accept 1-term anchors (c = 0) alongside iadd offsets.
    • When shader->info.shared_size is known and <= 32768, every in-bounds 16/32-bit shared access has element index < 2^14, so signed 16-bit deltas between same-block accesses sharing the same variable terms are exact and anchor + delta cannot wrap 16 bits even when variable terms include preamble uniforms or subgroup IDs. Greedily anchor each 256-byte window at its lowest executed member so offsets fold into LDTG/STTG.base (collapsing all 32 local_loads in mul_mm Q4_0 down to 6 shared base indices).
    • Split same-block segments across terminate/demote intrinsics and reject shared_size > 32768 or shared_size == 0 for the unbounded path.
  3. agx_compile.c & agx_nir_opt_licm.c:
    • Run agx_nir_opt_shared_byte_offsets (+ CSE/DCE) before agx_nir_opt_licm so LICM sees the 6 collapsed shared bases instead of 32 separate address expressions and hoists them out of the K-loop within register budget.
    • Allow pure per-invocation system values load_subgroup_invocation and load_subgroup_id in agx_licm_can_speculate().
  4. test-shared-byte-offsets.cpp:
    • Added SmallSharedGreedyAnchorUnbounded (verifying non-chunk-aligned greedy 256-byte anchoring with unbounded variable terms) and LargeSharedRejectsUnbounded (verifying > 32 KiB allocations do not apply the <= 32 KiB assumption).

Tested

All tests run on Apple M5 Max (J775c, G17C B1), native aarch64 release build with assertions enabled (-Dbuildtype=release -Db_ndebug=false), DRIRC_CONFIGDIR=/usr/share/drirc.d:

  • Unit tests: meson test -C build --suite asahi — 337/337 PASS (including 23/23 SharedByteOffsets.* tests).
  • Vulkan CTS: dEQP-VK.compute.pipeline.*coop* — 1,569/1,569 PASS on all supported non-dequant cases (0 regressions; the only 6 failures are the pre-existing subgroupscope.matrixmuladd_dequant.* ASR bug fixed separately in agx/optimizer: keep out-of-range ASR shift counts in a register on AGX3 #1279).
  • Interleaved ABBA llama-bench (llama-2-7b.Q4_0.gguf, -ngl 99, Borealis):
    • pp512 (-p 512 -n 0 -r 5):
      • Baseline dd57f9350c2: A1 = 2,293.43 ± 0.67, A2 = 2,294.20 ± 1.37 (mean 2,293.82 tok/s)
      • Branch 749e1820ef6: B1 = 2,622.76 ± 1.17, B2 = 2,624.11 ± 2.35 (mean 2,623.44 tok/s)
      • Delta: +329.62 tok/s (+14.37%)
    • tg128 (-p 0 -n 128 -r 3): 108.18 -> 108.07 tok/s (neutral, within noise)
  • vkpeak (A vs B): fp16-matrix 62,833 -> 62,807 GFLOPS, bf16-matrix 29,665 -> 29,759 GFLOPS, fp32-vec4 16,541 -> 16,542 GFLOPS (neutral).
  • ShaderDB (llama-bench pp512):
    • mul_mm Q4_0: 1587 -> 1520 instrs (-67), block2 368 -> 264 lines (-104), code size 15602 -> 14870 bytes.
    • flash_attn (KHR_coopmat): 3201 -> 3117 instrs (-84), code size 29654 -> 28752 bytes.
    • Kernel [13]: 1403 -> 1365 instrs, 157 -> 131 GPRs (640 -> 768 threads).
  • Kernel log: 0 new GPU/MMU faults in dmesg.

Risk

Low. The small_shared greedy anchor fold relies on the same shared_size <= 32768 in-bounds no-wrap invariant as agx_fold_shared_offsets(), requires at least two accesses in the same non-terminated basic-block segment sharing identical variable terms, and leaves shared_size == 0 / > 32768 shaders on the existing term_upper_bound() path.

Not yet

  • 2-gen peer verification on AGX2 (G13/G14) and AGX3B (G15/G16/G17P).
  • Follow-up work on remaining mul_mm Q4_0 inner-loop bottlenecks: u2f32(u2u8(...)) byte-unpack lowering on M5 and coopMatLoad collect/mov1 register shuffles.

…ant bases

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

satchlj commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Exact-head Apple M5 Max (J775c, G17C B1) unstacked VK-CTS verification on 749e1820ef6c (libvulkan_asahi.so SHA-256 ea6f1d5a37a14ef6dfc8318c76b7f5d9a50c582580164901135f5b7209ef0ab1) with ASAHI_MESA_DEBUG=verify MESA_SHADER_CACHE_DISABLE=true:

  • dEQP-VK.compute.pipeline.cooperative_matrix.khr_r.subgroupscope.matrixmuladd.float16_float32.*: 20/20 PASS (0 failed, 0 not supported)
  • dEQP-VK.compute.pipeline.basic.*: 80/80 PASS
  • dEQP-VK.ssbo.layout.single_basic_type.std430.* (basessbo): 336/336 PASS
  • dmesg GPU fault / WARN delta: 0

@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 749e1820

Blockers: none.

Checked: no Apple material, no AI attribution, no chip/board/firmware gates, human Signed-off-by, disjoint-bit nir_ior_imm -> nir_iadd_imm equivalence in agx_nir_lower_cmat.c, small_shared <= 32768 no-wrap math and same-block/same-segment gating in agx_nir_lower_shared_bitsize.c, LICM speculation safety for load_subgroup_invocation and load_subgroup_id in agx_nir_opt_licm.c, 337/337 asahi unit tests (including SmallSharedGreedyAnchorUnbounded and LargeSharedRejectsUnbounded), CTS compute.pipeline.*coop* 1,569/1,569 PASS, J775c llama.cpp pp512 +14.4%.

Evidence
  • Inspected all 5 files (agx_compile.c, agx_nir_lower_cmat.c, agx_nir_lower_shared_bitsize.c, agx_nir_opt_licm.c, test-shared-byte-offsets.cpp).
  • Verified small_shared greedy anchoring restricts grouping to the same basic block and same terminate/demote segment, enforces rel[m - 1] - rel[0] < (32768 >> shift) and cand->base + (delta << cand->shift) <= 255, and rejects shared_size > 32768 (negative control tested).
  • Verified load_subgroup_invocation and load_subgroup_id are invariant per invocation across loop iterations and safe to hoist before the general NIR_INTRINSIC_SUBGROUP barrier.
  • Verified on J775c M5 Max (G17C B1): 337/337 asahi tests, CTS *coop* 1,569/1,569 PASS, llama.cpp pp512 +14.37%, 0 regressions.

@RyanTheTide

Copy link
Copy Markdown

@DjDeveloperr, code-owner heads-up: this PR has an aurora-silicon-review App approval at 749e1820ef6c from a different lane plus the author's exact-head hardware row. I plan to land it no earlier than 06:29Z, after a combined A/B regression row on two lab GPU families (M1 Pro G13S + M4 G16G). The App approval doesn't count toward the ruleset, so that merge uses --admin under the 6-point rule. Please post a review here if you want it held.

@RyanTheTide

Copy link
Copy Markdown

Merge-train landing at 749e1820ef6c.

  • Review: aurora-silicon-review App APPROVE at this head by NEON-PR-REVIEW (Gemini lane, different model family from the author), with the author's exact-head J775c (M5 Max, G17C) row (non-author).
  • Feature row: the author's exact-head hardware row on this PR.
  • Regression: combined A/B overlay of aurora-wip plus this PR and the other queued PRs, user space, default kernel command line. M1 Pro (G13S, fleet89): 0 status changes. M4 Pro (G16S, fleet89): 0 regressions. The only flips there are 5 synchronization multi_queue timeouts under 4-job load; all 5 pass 3/3 alone on both arms, and the base arm shows the same flake. Each Mac ran 26,595 dEQP-VK + 8,153 dEQP-GLES cases, with 0 GPU firmware crashes, Enforcing, 0 failed units. Evidence traces/gpu/20261128-mergetrain-mesa.
  • --admin under the 6-point rule: the App approval does not count toward the ruleset. Dj was pinged here more than 1 h ago, and no blocking review is open.

Revert: git revert -m 1 <merge commit> on aurora-wip. A regression gets reverted first and fixed after.

@RyanTheTide
RyanTheTide merged commit 76f96bb into aurora-wip Nov 28, 2026
@RyanTheTide
RyanTheTide deleted the satya/cmat-shared-offset-licm branch November 28, 2026 06:33
jgoyvaerts pushed a commit to jgoyvaerts/mesa that referenced this pull request Nov 28, 2026
… collect in-flight tracking

Fix three scheduling accuracy bugs in ilp_schedule_block() that
severely hurt cooperative-matrix compute loops (such as llama.cpp
mul_mm Q4_0 and Flash Attention):

1. Exclude loop-carried PHI halves from consuming fwd_cap:
   Loop-header PHIs (e.g. 64 halves of matmad16 accumulators plus loop
   IVs) are already live on block entry and cannot be reduced by
   intra-block scheduling. Charging them against AGX_ILP_FS_SAMPLE_HALVES
   (88 halves) immediately pushed live > fwd_cap before the first real
   instruction, forcing the scheduler into smallest-destination-first
   mode and starving wide vec4 device_loads behind scalar ALU and
   local_stores.

2. Use net register growth (dest halves minus dying SSA source halves)
   for the fwd_cap fits check and !fits tie-breaker:
   Counting only destination size made accumulator-updating instructions
   like matmad16_agx3 (+16 dest, -16 to -32 dying inputs, net <= 0) look
   like the worst pressure offenders compared to local_loads (+2/+4),
   starving all matmad16 ops behind every local_load in the block.

3. Treat AGX_OPCODE_COLLECT like AGX_OPCODE_SPLIT for in-flight load
   consumption:
   A collect that regroups split channels from hoisted loads does not
   consume those loads; advancing consumed_loads on collect caused all
   32 local_loads in a cooperative-matrix K-tile loop to hoist ahead of
   all 8 matmad16 instructions and hold both K-halves live across the
   end-of-tile barrier.

On Apple M5 Max (J775c, G17C B1) with llama.cpp Vulkan (Llama-2-7B Q4_0,
fa=1, ngl=99, r=3), interleaved ABBA stacked on aurora-silicon#1280+aurora-silicon#1283+aurora-silicon#1284+aurora-silicon#1286:
- pp512:         2719.53 -> 2951.92 tok/s (+232.39 tok/s / +8.55%)
- pp2048:        2578.13 -> 2787.53 tok/s (+209.40 tok/s / +8.12%)
- tg128:         109.20  -> 109.20  tok/s (neutral)
- tg128 @ d2048: 76.12   -> 76.25   tok/s (+0.17%)
- mul_mm Q4_0 drops from 207 GPRs (512 threads) to 168 GPRs (640 threads),
  overlapping B-matrix device_loads with A dequant and interleaving all
  8 matmad16 ops with local_loads; Flash Attention drops 191 -> 175 GPRs
  (512 -> 576 threads).

Signed-off-by: Satya Benson <satya@benson.earth>
jgoyvaerts pushed a commit to jgoyvaerts/mesa that referenced this pull request Nov 28, 2026
… with occupancy headroom

Extend the wide_flat ({8, 6, 4, 2, 1}) in-flight load window selection
in agx_ilp_schedule() to M5 (AGX3C, non-G18G) compute loop bodies when
device_loads > 4 and the block has register headroom inside its current
occupancy step (device_load_cap > peak).

Because windows > 4 remain strictly capped to device_load_cap - peak
(occ_cap), this never crosses an occupancy boundary and falls back
cleanly to {6, 4, 2, 1} when headroom is tight. Straight-line compute
blocks and G18G are unchanged.

In memory-latency-bound quantized GEMV loops (such as llama.cpp
mul_mat_vec Q4_0 / Q6_K with 10-14 device_loads per loop iteration),
widening the in-flight window from 4 to 6/8 overlaps trailing activation
and weight loads with dequantization ALU instead of stalling shortly
before consumption.

On Apple M5 Max (J775c, G17C B1) with llama.cpp Vulkan (Llama-2-7B Q4_0,
fa=1, ngl=99, r=3), interleaved ABBA stacked on aurora-silicon#1280+aurora-silicon#1283+aurora-silicon#1284+aurora-silicon#1286+aurora-silicon#1287:
- tg128:         109.17 -> 111.34 tok/s (+2.17 tok/s / +1.99%)
- tg128 @ d2048: 76.30  -> 77.13  tok/s (+0.83 tok/s / +1.09%)
- pp512:         2953.41 -> 2953.88 tok/s (neutral)
- pp2048:        2785.65 -> 2787.48 tok/s (+0.07%)

Signed-off-by: Satya Benson <satya@benson.earth>
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.

2 participants