Repository navigation
asahi/compiler: fold proven zext byte offsets and unroll compact guarded loops 8x - #1202
Conversation
…ded loops 8x Enable three general AGX3 compute loop optimizations that compose cleanly across compute workloads without chip allowlists or signed-index assumptions: 1. Zero-extended constant byte-offset folding (agx_nir_lower_address): AGX3B supports native signed 16-bit byte offsets on device loads and stores while exposing full 4 GiB storage buffers (UINT32_MAX), so unrolled loop indices cannot blindly sign-extend. Prove that (uint32_t)idx + c cannot wrap modulo 2^32 from unsigned range bounds, constant left shifts, or enclosing top-tested loop guards (unsigned and non-negative signed IVs), and fold c into byte_off while keeping sign_extend = 0. 2. Compact-prefix guarded loop 8x unrolling & 8-wide guard coalescing (agx_nir_unroll_runtime_loops, agx_nir_opt_guard_chains, agx_compile): Count only unconditional top-level loads toward the >4x in-flight read budget, allow guarded loops with a compact unconditional prefix (top_size * f <= max_instrs / 2, size * 4 <= max_instrs) to unroll 8x up to 2x total size, raise guard-chain coalescing to 8 ifs (48 live dwords) and unwrap fneg(fneg(x)) -> x in try_unwrap_zero_fadd_bias, and retry factor 4 before factor 1 on AGX3B when 8x exceeds half the register file (96 halves). 3. Scalar branch-compare LICM (agx_opt_licm): Treat IF/ELSE/WHILE/BREAK_IF scalar compares as plain register uses so loop-invariant uniform copies feeding branch compares hoist and merge with ALU copies in the loop preheader. Signed-off-by: DjDeveloperr <hey@djdev.me>
|
J773g (M4 Mac mini, G16G B0, second generation) at exact head Both arms are release Borealis Vulkan overlays built natively on the Mac and loaded from private prefixes through VK CTS at 2 workers, 89,959 cases: gpubench-vk ABBA (
An earlier ABBA pass in the same hold overlapped a native build on the Mac, so it's discarded; the table is the clean rerun. GPU health: 0 faults, 0 recoveries and Older head Both arms are release Borealis Vulkan overlays, cross-built off the Mac and loaded from private prefixes through gpubench-vk ABBA (
VK CTS at 2 workers, GPU health: 0 faults, 0 recoveries and GB6 Particle Physics wasn't run on this Mac. |
RyanTheTide
left a comment
There was a problem hiding this comment.
Verdict: FINISH, then merge at ac5e53a157bb8a4f8b442be16d8c97001ba81079
Blockers: none in the code. The branch is DIRTY against aurora-wip. Please merge aurora-wip once (no rebase). The conflict is real, in agx_nir_unroll_runtime_loops.c, which this PR touches:
count_unrollable()gained a third argument, and #1183's new caller (count_unrollable(loop, cl.nif)near the runtime-step path) needsNULL.- aurora-wip's
count_unrollable()now also skipsload_const/undef. Keep that skip and add yourtop_levelcounter inside the same braces. loaded_dwords()is needed again byloop_is_readonly_with_loads(), which keeps the forward declaration ofloop_is_readonly().
My resolution (below) builds and passes the gate. The 8x rows at the current head then no longer cover the merged file.
Checked: I read the whole diff and tried to break u32_add_no_wrap(). I found no input that breaks it:
iandwith a constant <= K,ushrby s > 0 <=UINT32_MAX >> s, andusub_sat(x, m)<=UINT32_MAX - mare all exact bounds. Shift counts are masked like NIR's, soushr 32gives no bound.- The
bcsel(uge(N,K), N-M, 0)form with0 < M <= Kis exactly whatguard_bound()emits for unsigned REL_LT/LE.rest < limit <= UINT32_MAX-Mwithuc <= M+1cannot carry. The signed form (INT32_MINdefault) mirrors it. - The
u2u32narrow andishllow-zero-bit arguments are right. - Loop-guard path: the compare must be the first CF node after the header, the access cannot sit in the header or inside the break
if, andrestis the same SSA scalar the header tested in this iteration. For the signed path, non-negativity needs a const init >= 0, a 2-source phi (nocontinueedges) andmax_rest + step <= INT32_MAX, so the IV cannot wrap negative. checked_offsetsrefuses everything.fneg(fneg(x))unwrap: bit-exact, and the dominance check is there.- LICM branch-compare uses: the register-demand revert still bounds it.
- The
encoding == AGX3Bretry inagx_compile_shader_nir_unrolled()keys on the ISA encoding's register file, not on a chip. Acceptable.
Local drm-shim gate (x86 clang, asahi + poly): aurora-wip 65866bbd 336/336, merged 336/336. The new tests are real: with only the PR's three test files on aurora-wip, agx_tests fails 4 of them (OptLicm.HoistsUniformUsedByBranchCompare, LowerAddressCheckedOffsets.ZeroExtendedByteOffsetGuardProof, GuardChains.CoalesceFloatThreshTreeVariantsAndRefusals, GuardChains.CoalescesEightGuardedIfsAndCompactPrefixLoopUnrollsByEight).
Non-blocking: loaded_dwords_in_loop(..., true) now applies to every loop with more than 4 iterations, not only the compact-guarded ones, and the address, LICM and guard-chain changes reach every AGX3 chip. So this needs rows beyond J700.
Row owed: J773g/J713 (G16G) and J714s (M5, AGX3C byte offsets) at the merged head: dEQP-VK.compute.* dEQP-VK.glsl.loops.* dEQP-VK.ssbo.layout.random.* dEQP-VK.spirv_assembly.instruction.compute.*, plus Particle Physics output check.
Resolve two small merge hunks in agx_nir_unroll_runtime_loops.c: - keep aurora-wip's load_const/undef exclusion inside the instruction counter while tracking top_level instructions - keep both loaded_dwords() and aurora-wip's loop_is_readonly() forward declaration. Signed-off-by: DjDeveloperr <hey@djdev.me>
…e caller Fix the 1-line compile break after merging aurora-wip's new count_unrollable() call site in agx_nir_unroll_runtime_loops.c. Signed-off-by: DjDeveloperr <hey@djdev.me>
|
J700 (MacBook Neo, G17P B1) at
Exact-head addendum (
|
RyanTheTide
left a comment
There was a problem hiding this comment.
Verdict: FINISH, then merge at 3ea292e40fc136a55af00d6440bdee1369efdd5c
Blockers: none in the code. One row is still owed before merge: J714s (M5 Pro, AGX3C byte offsets) at this head. Run dEQP-VK.compute.*, dEQP-VK.glsl.loops.*, dEQP-VK.ssbo.layout.random.*, dEQP-VK.spirv_assembly.instruction.compute.* and the Particle Physics output check. The M5 is the only AGX3C chip in the set, and the byte-offset fold changes its address path. There was no M5 row at the older head either, and the delta since then is a real conflict merge, so no earlier row carries over. Merge once that row is on the PR.
Checked: I read the delta ac5e53a157bb..3ea292e40fc1: the merge of aurora-wip 6041c9351efa plus the one-line follow-up. The resolution in agx_nir_unroll_runtime_loops.c is the one I asked for:
count_unrollable()keeps aurora-wip'sload_const/undefskip and countstop_levelinside the same braces.- #1183's
peel_straight_prefix()caller passesNULLfortop_level_out. loaded_dwords()and theloop_is_readonly()forward declaration stay forloop_is_readonly_with_loads().
Comparing the PR's net diff against its merge-base before and after shows only those hunks; the rest of the PR diff is unchanged. aurora-wip has moved 53 commits past 6041c935, and the head still merges into the current tip 5ab97d0f2c60 without conflicts. Rows at this head: J773g (G16G) shows no regression with 0 CTS differences across 89,959 cases. J700 (G17P) shows Particle Physics at -21 % GPU time, 0 validation errors, and 0 Fail across 89,959 CTS cases.
Evidence
Local drm-shim gate (x86 clang, release + asserts, meson test --suite asahi --suite poly):
- aurora-wip
5ab97d0f2c60: Ok 338, Fail 0 - aurora-wip
5ab97d0f2c60+3ea292e40fc1(clean merge): Ok 338, Fail 0
Net-diff comparison: git diff 2cb5e1a5cbd9 ac5e53a157bb vs git diff 6041c9351efa 3ea292e40fc1. Only the count_unrollable() braces, the NULL argument and the forward-declaration move differ.
|
Merge order changed: #1204 merged first (a97571c), because it was ready first: J516s row at its head (posted 11:31Z), plus J700 and J714s. This PR now conflicts with aurora-wip in To finish:
The approval at 3ea292e covers the code. We'll do a resolution review of the merge commit and gate it as soon as it's pushed. |
|
Verdict at Blockers None. Checked
Nit (not blocking): two of the new proof rules have no test that fails when they're made unsound: dropping Still owed before merge:
|
RyanTheTide
left a comment
There was a problem hiding this comment.
Verdict: FINISH, then merge at 25022fffb995d4217fe6396f69df9b4ff023fe1c
Blockers: none in the code. Rows are owed at this head: J773g (G16G) and J700 (G17P), plus the J714s (M5) row that was already owed. The merge hand-resolves a conflict in agx_nir_unroll_runtime_loops.c, a file this PR touches, and the factor a loop gets now depends on #1204's trip bound too. So the rows at 3ea292e40fc1 don't carry over.
Checked: this is a resolution review of the aurora-wip merge 25022fffb995 (git show --remerge-diff).
-
choose_factor(). The resolution is the union of both sides, in this order:- #1202's
compact_guarded_prefixbudget (2xmax_instrsonly when 4x fits and the unconditional prefix stays within half); - the halving to the budget;
- the 16-dword in-flight cap above 4x;
- #1204's
max_trips()cap (2 * f > tripshalves;f < 2returns 0); - the final check against
budget, notmax_instrs.
The trip cap can only lower
f, so the 2x budget never grants more than #1202 already allowed, and a constant-trip loop can't be unrolled past its trip count. - #1202's
-
Runtime step and step 0. In
struct counted_loop,step == 0means a loop-invariant runtime step (step_def).max_trips()returnsUINT64_MAXforstep <= 0,offset_is_step, a non-constant bound orREL_*other than LT/LE, before it divides bycl->step. So runtime-step loops get no trip cap and keep this PR's factor, and there is no division by zero.M5RuntimeLoops.RuntimeStepReductionUnrolls(runtime step),M5RuntimeLoops.TripBoundLimitsFactor(#1204's cap) andGuardChains.CoalescesEightGuardedIfsAndCompactPrefixLoopUnrollsByEight(this PR's 8x budget with a runtime bound) all pass in the merged tree. -
test-opt-licm.cpp:369. Braces only: they fix the-Wdangling-elsewarning, and the test is unchanged. -
Merge. No other hunk in the merge differs from a plain merge. The head merges cleanly into aurora-wip
fffdc5c7c634. -
Nit (non-blocking, also in your own review): the
M <= Kpart of thebcselbound andc < 2^sin theishlrule have no negative test.
Evidence
Local drm-shim gate (x86 clang, release + asserts, meson test --suite asahi --suite poly):
- aurora-wip
fffdc5c7c634: Ok 338, Fail 0 - aurora-wip
fffdc5c7c634+25022fffb995(clean merge, treebd93d97bac70): Ok 338, Fail 0
|
J714s (MacBook Pro 14" M5 Pro, G17S B1, AGX3C) row at Setup:
1. Vulkan CTS (
2. Geekbench 6.7.1 Vulkan:
3. Kernel log: 0 GPU faults, 0 WARN and 0 error lines in both slots. The GPU was online with 0 crashed and 0 quarantined owners before and after. |
Verification row — MacBook Pro M5 Pro (
|
|
|
What: Three general, chip-agnostic AGX3 compute loop optimizations: proven zero-extended constant byte-offset folding (
u32_add_no_wrap()), compact-prefix 8x guarded loop unrolling with 8-wide guard coalescing and AGX3B register-file retry, and scalar branch-compare LICM.Tested:
J700, G17P B1, AGX3B): exact-head ABBA+BAAB (n = 4per arm) atac5e53a157bband3ea292e40fc1(#issuecomment-7216513527): Geekbench 6.7.1 Vulkan Particle Physics-20.66%(42.449 → 33.678 msGPU busy,0validation errors across all runs), Feature Matching-0.60%, other 6 workloads neutral;89,959VK CTS cases (compute.*,glsl.loops.*,ssbo.layout.random.*,spirv_assembly.instruction.compute.*)0Fail;stock.shPRE/POST=0,0GPU faults/AVCs.J773g, G16G B0, AGX3B): PASS atac5e53a157bb(#issuecomment-7211111651) and exact-head3ea292e40fc1(0Fail).agx_tests(OptLicm.*,LowerAddressCheckedOffsets.*,GuardChains.*) PASS; Ryan confirmed336/336asahi + poly clean; Reviewer A confirmed215/215asahi +5/5poly on the#1204merged tree.Risk: two-way · M3, M4, Neo, M5 — Reverting cleanly disables all three compiler optimizations;
checked_offsetsremains strictly disabled and the existing half-factor AGX3B register-pressure retry prevents spill/occupancy regressions.Not yet: J714s (
M5 Pro,AGX3C)89,959-case CTS passed (0new fails) with GB6 Particle Physics ABBA finishing before comment post; quick J700 spot check on the#1204merge commit pending.Details and verification evidence
Summary
Three general, chip-agnostic AGX3 compute loop optimizations that compose cleanly without signed-index assumptions or shader allowlists:
Zero-extended constant byte-offset folding (
src/asahi/compiler/agx_nir_lower_address.c)device_load/device_storewhile supporting full 4 GiB storage buffers (UINT32_MAX), so zero-extended indices cannot blindly switch to sign extension.u32_add_no_wrap()to prove(uint32_t)rest + c <= UINT32_MAX(when!checked_offsets) fromno_unsigned_wrap, exact modular upper bounds (iand,ushr,usub_sat,bcselguard bounds, narrowu2u32), constant left-shift low zero bits, and enclosing top-tested loop guards (unsigned and non-negative signed IVs), foldingcintobyte_offwhile keepingsign_extend = 0.nir_unsigned_upper_bound()'s unsoundmax / const * construle on wrapping non-power-of-twoimul, and keepschecked_offsetsstrictly disabled.Compact-prefix guarded loop 8x unrolling & 8-wide guard coalescing (
src/asahi/compiler/agx_nir_unroll_runtime_loops.c,src/asahi/compiler/agx_nir_opt_guard_chains.c,src/asahi/compiler/agx_compile.c)>4x16-dword in-flight read budget (loaded_dwords_in_loop), since loads inside nestedifbodies are guarded and do not issue concurrently across iterations.top_size * f <= max_instrs / 2,size * 4 <= max_instrs) to unroll 8x up to2 * max_instrstotal code size.ifs (MAX_GROUP_IFS = 8,MAX_LIVE_HOISTED_DWORDS = 48) and unwrapfneg(fneg(x)) -> xintry_unwrap_zero_fadd_bias()(IEEE-754 bit-exact).agx_compile_shader_nir_unrolled(), retry factor 4 before factor 1 on AGX3B when 8x exceeds half the register file (> 96halves), preventing Dynamic Caching / occupancy regressions.Scalar branch-compare LICM (
src/asahi/compiler/agx_opt_licm.c)IF/ELSE/WHILE/BREAK_IF_{FCMP,ICMP}as plain register uses so loop-invariant uniform copies feeding branch compares hoist to the loop preheader and merge with identical ALU copies.Hardware Verification — MacBook Neo (
J700, Apple A18 ProT8140,G17P B1, AGX3B)Exact-commit same-boot
ABBA+BAAB(n = 4per arm:A1 B1 B2 A2 B3 A3 A4 B4) comparing cleanaurora-wip(2cb5e1a5cbd9) vsac5e53a157bb(0diff lines, stock kernel7.3.0-41.fc44.aurora.aarch64,stock.shPRE=0 / POST=0, same boot65f30b5a-68ce-499f-bf13-617842e616fd,0GPU faults / AVCs / recoveries).Geekbench 6.7.1 Vulkan (
0validation errors,0warnings across all 9 runs)2cb5e1a5cbmedian (range)ac5e53a157median (range)290i/69g/1luc->405i/87g/0luc(1024t,0sp), hot loop68 -> 54dynamic instrs / 8 particles (-20.6%)fm-h370i->368i,fm-v554i->551i,3ba0a508187i->186igemm-aligned320i->319i)b55b9b9d503i/85g,ebb331db465i/81g);diag2measured11.178 msvs11.213 msandgpubench-vkgaussianis+0.07%Diagnostic ablation on the same hardware (
A1 -> VarA -> VarB -> A2):VarA, 4x unroll,290i/57g):42.449 ms -> 39.963 ms(-5.86%).VarB,405i/87g/0luc):42.449 ms -> 33.677 ms(-20.66%).gpubench-vkCompute ABBA+BAAB (n = 4per arm) & Bit-Exact CRCscompute.conv2d bilateral 1080p6cdc0716(exact)compute.conv2d gaussian 1080p2d55a14d(exact)compute.edge harris 1080p4cebadfc(exact)compute.edge sobel 1080p27c79e6d(exact)compute.stereo disp=64c62aadf9(exact)Correctness & CI
6,366cases):5,874 Passed,0 Failed,492 Not supported,0 Warnings,0 Waived.ASAHI_MESA_DEBUG=verify: PASS on J700 (compute.edge sobel, CRC27c79e6d) +0failures across offline G17P replay of all 82 GB6.fozarchives (0spills,1024threads on all)../rig/fedora-mesaci.sh ac5e53a157bb):216/216PASS (0fail,0skipped,0new warnings in touched C files), including new positive and negative controls intest-lower-address-checked-offsets.cpp,test-opt-licm.cpp, andtest-guard-chains.cpp..github/aurora/agent-policy.sh pr HEAD->PR is clean.