Repository navigation
agx: fuse disjoint shifted ior and masked shifts into imadshl_agx - #1559
DjDeveloperr merged 4 commits into
Conversation
Extend agx_nir_opt_bitfield_slices() to recognize two common 32-bit quantized bit-unpack patterns when adjacent slice merging does not apply: 1. Disjoint ior(other, base << k) (including imadshl_agx(0, 1, base, k)) with 1 <= k <= 4 and a single-use shifted operand: when known-zero-bit analysis proves (~known_zero_bits_u32(other) & (~known_zero_bits_u32(base) << k)) == 0, bitwise OR has no carries and folds directly into imadshl_agx(other, 1, base, k). 2. Disjoint ior(other, iand(ushr(x, s), ((1 << w) - 1) << tz)) with 1 <= tz <= 4, single-use inner ops, other known zero across mask, and upper-bound analysis proving s <= 32 - (tz + w) (non-wrapping shift): folds into imadshl_agx(other, 1, ubitfield_extract(x, s + tz, w), tz), removing the separate mask instruction and fusing shift+or. Add unit test SharedByteOffsets.BitfieldSlicesDisjointIorShlAndShiftedMask covering both positive fusions and negative guards for unbounded shifts and overlapping bit positions. Signed-off-by: Dylan Ironside <dylan@dylanironside.io>
DjDeveloperr
left a comment
There was a problem hiding this comment.
HOLD at 894f01856237: no hardware row at the head yet, and one case where slices that merge today stop merging. I found no wrong result.
Correctness, checked line by line
ior(other, base << k):1 <= k <= 4, 32-bit scalar, and the known-zero masks must not overlap after the shift, so the OR has no carry andimadshl_agx(other, 1, base, k)gives the same bits. Shift amounts are masked with 31 as NIR does.ior(other, iand(ushr(x, s), mask)): withs <= 32 - (tz + w)andw >= 1,s + tzis at most 31, so the extract offset cannot reach 32. That matters becausebfeildoes not wrap.iaddcannot overflow.u32_upper_bound()falls back to the full range on every possible wrap, on depth 0 and on 8/64-bit sources. I found no case where it is too low.- The GEMM matcher runs after this pass and evaluates
imadshl_agxas well asior(agx_nir_match_gemm.c:68-125), so shared-index expressions still match. I found no other later pass that depends on these 32-bitiors.
Should fix: the fusion runs before the tree has been merged. nir_shader_alu_pass reaches an inner ior before its root. Fusing it there hides its terms from collect_add_or_terms() at the root, and known_zero_bits_u32() returns little for the fused form, so the rest of the chain cannot fuse either. ALU counts after the pass and DCE (scratch unit test on x86-64):
| pattern | base | this head | fuse only at the root |
|---|---|---|---|
(x & 3) | ((y & 3) << 4) | (ubfe(x, 2, 2) << 2) |
4 | 6 | 3 |
(x & 3) | ((y & 3) << 2) | ((z & 3) << 4) |
7 | 6 | 5 |
(x & 15) | ((y & 15) << 4) | (ubfe(x, 4, 4) << 8) |
7 | 6 | 7 |
The last column returns early from step 3 when the only use of the ior is another ior; the existing BitfieldSlices* tests still pass with it. It is not a clean win (third row), so which order you want is your call; I have not pushed anything. The first row is a step back from aurora-wip and should go away either way.
Scope is wider than the text says. is_agx3 here is AGX3B and AGX3C: M3, M4, A18 Pro and M5, in every shader stage, not only compute. Please say so in Risk.
Performance claim. The tok/s figures come from a combined build, so they say nothing about this patch. 3b swaps ushr + iand + ior for iadd + ubfe + imadshl, which is three for three unless the iadd is shared, so it needs its own A/B (base vs head, same boot, policy/mesa-performance-claims.md).
Nits: nir_unsigned_upper_bound() handles ubfe but not ubitfield_extract/imadshl_agx; u32_upper_bound() here and u32_interval() in #1560 are two copies of the same walk, so one shared helper would be better. The new unit test counts opcodes only; a value check would be stronger. This PR and #1560 conflict at the end of test-shared-byte-offsets.cpp, so the second one to land needs a forward merge.
Local check. Merge into 3146ce4726a1 (tree aa7effd07dd8), assert-enabled x86-64: asahi, poly and vulkan suites 464 ok, 0 failed, 1 skipped; agx_tests 1970 passed, 1 skipped. Merges cleanly into the current tip e4346bdb3a55. Commit and sign-off are fine.
Rows owed at the head
- J773g (M4, G16G B0) or your J604: llama-bench Q4_K_M and Q6_K
pp512/tg32, base vs head ABBA, plus gpubenchcompute.*with CRC match anddEQP-VK.glsl.operators.*,dEQP-VK.spirv_assembly.instruction.compute.*, 0 regressions. Expect parity or better. - J714s (M5 Pro, G17S, AGX3C): the same CTS subset, gpubench
compute.*and one graphics row, no regression. Required, as the code runs on AGX3C. - J700 (A18 Pro, G17P): gpubench
compute.*and the CTS subset. Good to have.
…zero bits Split step 3 (disjoint ior -> imadshl_agx fusion) out of opt_bitfield_slice_instr() into a separate opt_disjoint_ior_instr() pass that runs after adjacent bitfield slice merging completes (with DCE and a cleared upper-bound cache in between when slice merging made progress). This prevents an inner ior from fusing before its enclosing tree has had a chance to merge adjacent bitfield slices in collect_add_or_terms(), fixing the 4 -> 6 ALU regression on ((x & 3) | ((y & 3) << 4)) | (ubfe(x, 2, 2) << 2) and dropping it to 3 ALUs. Also teach known_zero_bits_u32() that unit-multiplier imadshl_agx(a, 1, c, k) is carry-free when a and (c << k) have disjoint non-zero bit masks, so chained disjoint shifts such as ((x & 3) | ((y & 3) << 2)) | ((z & 3) << 4) fuse both shifts (5 ALUs) while inner-only patterns such as ((x & 15) | ((y & 15) << 4)) | (ubfe(x, 4, 4) << 8) still fuse the inner shift (6 ALUs). Add value-equivalence checks to BitfieldSlicesDisjointIorShlAndShiftedMask and add BitfieldSlicesMergeBeforeDisjointIorFusion covering all four 3-term merge/chain cases. Signed-off-by: Dylan Ironside <dylan@dylanironside.io>
|
Thanks for the detailed review and for catching the inner-
|
nir_unsigned_upper_bound() caches by SSA index, and every implementation numbers its defs from zero. agx_nir_opt_bitfield_slices() used one table for the whole shader, so a bound found in the main shader could be used for an unrelated value of the preamble: - ushr(ishl(x, a), c) lost the truncation of x << a, a wrong value (already possible before the disjoint ior fusion); - the new masked-shift fusion formed a ubitfield_extract whose offset reaches 32. Start every implementation with an empty table, like agx_nir_lower_address() and agx_nir_lower_bitfield_u2f(). Add a test for it, and one for two overlaps the existing tests do not reach: a carry inside a unit imadshl_agx, and a masked shift that shares a bit with the other operand. Signed-off-by: DjDeveloperr <hey@djdev.me>
DjDeveloperr
left a comment
There was a problem hiding this comment.
Verdict: FINISH, then merge, at f5ff0023b6ca. Only hardware rows are missing; no open code finding.
Blockers: none in the code. Rows owed at this head: J773g (M4, G16G), J700 (A18 Pro, G17P), J714s (M5 Pro, G17S, the only AGX3C row). We are queuing all three on our Macs.
The points from the last review, checked at 98547a87cbbe
- Fusing before slices merge: fixed. My three patterns now give 3, 5 and 6 ALU ops (base 4, 7, 7). Compiled for G16G, G17P and G17C, none of 14 fixed shaders gets longer.
- Scope, performance text and value checks: fixed. Putting the old order back, or dropping the DCE, makes the new test fail.
One bug, fixed in f5ff0023b6ca (a fix commit on top of yours, nothing rewritten). agx_nir_opt_bitfield_slices() kept one range table for the whole shader, but nir_unsigned_upper_bound() caches by SSA index, and the main shader and the preamble both number from zero. A bound from the main shader was then used in the preamble:
ushr(ishl(x, 12), 4)lost its truncation:0x0fffff00became0xffffff00.aurora-wipalready has this one;- your masked-shift fusion built an extract whose offset reaches 32.
The commit empties the table for each function. It adds a test that fails on 98547a87cbbe, and one for two overlaps your tests did not reach (a carry inside imadshl_agx(a, 1, c, k), and a masked shift that shares a bit with the other operand).
Checked: disjointness, carries, shift and width limits, 16/32-bit bounds; 64-bit values are never matched. 150,000 random shaders with 45,920 fusions: 0 wrong values. AGX3B, AGX3C and, through AGX3C, G18G (M6) compile it, and all three encode the shifted iadd with shifts 1 to 4; AGX2 never sees it. No Apple material, no chip gate, commits and sign-offs fine.
Evidence and notes
- Merge with aurora-wip
4f2853ac8250(tree3b6ab80c6c79), assert-enabled x86-64: asahi, poly and vulkan suites 465 ok, 0 failed, 1 skipped;agx_tests1975 passed, 1 skipped. It also merges cleanly into80a0ac5d0cdd. - Mutations: 19 changes to the new conditions. The tests or the fuzzer catch all that change a value, except one:
u32_upper_bound()ishlwithout its wrap check survives (nothing generated reaches it; the code reads right). Four others only cost performance or are equivalent. - llama MUL_MAT q4_K/q6_K, 35 shaders, offline: 21 change, none longer. G16G 65,675 to 65,174 instructions; G17P 59,722 to 59,222 with soft faults on and 59,017 to 58,547 with them off. Spills equal. With soft faults on, two G17P shaders lose a thread step (768 to 704, 704 to 640), so this still needs timing.
- GTA V pipelines, base vs head: G16G 23 of 4,429 shorter, 0 longer; G17P 22 shorter, 0 longer; G17S 145 of 26,443 shorter, 12 longer (+4 to +235 instructions;
c7a1b8c6400de3754,572 to 4,666, where I looked, is register copies), net -2,024, threads equal or better; G18G 31 of 12,720 shorter, 0 longer. The fix commit changes none of the G16G and G17S ones. - Not blocking:
agx_nir_opt_shared_vec2()bounds its index withnir_unsigned_upper_bound(), which knowsiorbut notimadshl_agx. In a unit test, two shared loads indexed bylo | (hi << k), k 2 to 4, no longer pair after this pass. In a full compile of the same shape they still pair and the shader is one instruction shorter, so I have not seen it cost anything. - Not blocking:
u32_upper_bound()repeats most ofterm_upper_bound()in the same file. - The CTS group is
dEQP-VK.glsl.operator.*;glsl.operators.*(my last review had it wrong too) matches no case. I corrected it in the description and added M6 to Risk.
Rows: base cb983a61cb14, head f5ff0023b6ca, zero reboot. CTS glsl.operator, glsl.builtin.function.{integer,pack_unpack}, spirv_assembly.instruction.compute, spirv_assembly.type.scalar, compute.*shared*, memory_model.shared, image.store, graphicsfuzz (32,965 cases, 0 differences); MUL_MAT q4_K/q6_K against the CPU with instruction counts on both arms; gpubench compute.* ABBA with CRCs. J773g adds llama-bench Q4_K_M and Q6_K ABBA, J700 the MUL_MAT timing, J714s GTA V ABBA.
|
J773g (Apple M4, Verdict: PASS (correctness, CTS, shaderdb, detlogits, GPUBench CRCs, and 0 faults; timings flat within noise / thermal spread).
Follow-up shader check (
|
J700 (MacBook Neo, A18 Pro, G17P B1) at
|
| Part | Result |
|---|---|
| CTS, the recipe's 32,965 cases, base then head | 32,965 of 32,965 on both arms (22,157 Pass, 10,808 NotSupported), 0 status differences |
| MUL_MAT q4_K/q6_K against the CPU | 192 of 192 OK on both arms, 0 failures |
| Shaders the pass changes | 21 of 35, all shorter, 0 longer: 59,017 → 58,547 instructions, threads unchanged, spills 963 → 963 |
MUL_MAT perf, 64 rows, 5 samples per arm |
head/base median 0.9989 (0.9822 to 1.0164), 0 slower and 1 faster than the base spread |
| llama-bench, TinyLlama Q4_K_M | pp512 551.05 → 546.14 tok/s (0.9911, spread 8.24 %), tg32 45.74 → 45.77 tok/s (1.0008, spread 7.69 %) |
GPUBench compute.*, 20 configurations, 40 rows |
39 rows inside the base spread. light depth 8: 1.0084, 0.84 % slower against a base spread of 0.78 %, so this row fails the kit's bar. All CRCs equal |
| Kernel log | 0 GPU-side lines, 0 WARN, SLC on |
The light depth-8 failure, and what followed
- I fixed the re-run's rule before running it: ten ABBA rounds of
light(20 slots per arm) at depths 1, 8 and 32, and the new rounds decide, with the first failure reported. The rule is loose on purpose: the head median must not be above the base by more than the base spread of the pooled windows. - Re-run: depth 1 102.30 → 102.70 µs (1.0039, spread 2.80 %), depth 8 16.077 → 15.969 µs (0.9933, spread 4.74 %), depth 32 13.544 → 13.445 µs (0.9927, spread 38 %): PASS at all three. Bootstrap 95 % intervals over the rounds: 1.0008 to 1.0076, 0.9904 to 1.0008, 0.9815 to 0.9960. Depth 1 was slower in 8 of 10 rounds, by about 0.4 %, so a real effect that small can't be excluded.
- The compiled shaders are identical: all 20 GPUBench configurations compile to byte-identical code in base and head on this GPU (58 shader parts,
AGX_MESA_DEBUG=binaries, base repeats itself). So the first failure isn't caused by the compiled shaders. A CPU-side layout effect isn't excluded (the library's.textgrew by 608 bytes). The first run's spread came from only two base slots, which misses slot-to-slot drift.
A gap in this row: the PR also changes 27 of the 97 built-in G17P GPU kernels (84,432 → 84,088 bytes, none larger): decompress, fast clear, copy image, mipmap, reset compression metadata and resolve. They are compiled when Mesa is built, so neither the MUL_MAT counts nor the shader dump shows them, and the CTS list above wasn't chosen for them. A small base/head CTS group for image copy, clear, mipmap and resolve is being built for the J700 and the J773g; it isn't in this row.
Not covered: there was no Q6_K model, light at depth 1 is the only depth whose interval sits above 1.0, and the two runs were on the stock kernel only. (Two earlier starts of the second half were stopped and redone; they carry no measurements.)
RyanTheTide
left a comment
There was a problem hiding this comment.
The fusion follows slice merging and checks that the shifted operands cannot overlap. The masked path also bounds the full extract within the source word. The per-function range cache prevents a main-shader bound from leaking into the preamble. J773g and J700 receipts are in. The current base has a merge conflict in the range-cache work, so the resolved head needs a fresh read. The G17S row is pending.
Forward-merge origin/aurora-wip (d59f5ae) and resolve the conflict in src/asahi/compiler/agx_nir_lower_shared_bitsize.c where both branches introduced per-implementation bitfield_slice_state range tables. Signed-off-by: Dylan Ironside <dylan@dylanironside.io>
|
Thanks @RyanTheTide for the review/approval and @DjDeveloperr for the J773g/J700 receipts. Forward-merged Offline verification at
|
RyanTheTide
left a comment
There was a problem hiding this comment.
The merge resolution preserves the reviewed production logic. Comparing the compiler source with the previously reviewed head shows only a blank-line change, and the disjoint fusion uses the shared per-function range cache. The reported exact-head bitfield and compiler suites pass.
|
Rows. The J773g and J700 rows at |
|
J773g ( Provenance & custody
1. Built-in kernel CTS group (3,027 cases across
|
| Arm | Total | Pass | NotSupported | Fail / Crash / Timeout | Status diffs vs base |
|---|---|---|---|---|---|
base (d59f5aee1d9d) |
3,027 | 3,003 | 24 | 0 | — |
head (f8a608c0a016) |
3,027 | 3,003 | 24 | 0 | 0 |
2. Targeted readback tests (base, head, head, base + probe)
All 6 readback tests passed on real Apple M4 (G16G B0) hardware across every slot (rc=0, PASS, 0 differences):
msaa_r8_2x: PASS (base/head/head/base + probe) — reachesFAST_CLEAR_0,FAST_CLEAR_5decompress_1x_layered: PASS — reachesAGX3_DECOMPRESS_3,FAST_CLEAR_4,RESET_COMPRESSION_METADATAdecompress_2x_layered: PASS — reachesAGX3_DECOMPRESS_4,FAST_CLEAR_3decompress_4x_layered: PASS — reachesAGX3_DECOMPRESS_5,FAST_CLEAR_3,RESET_COMPRESSION_METADATAmip_plain: PASS (7 mip chains: PASS) — reachesMIPMAP_UNORM8X4,MIPMAP_UNORM8X4_ODDresolve_plain: PASS (all 12 2x/4x casesbad bytes 0 max 0, identical CRCs base vs head) — reachesRESOLVE_UNORM8X4
3. Hardware reachability (probe ICD LIBAGX-DISPATCH trace)
- 24 / 27 changed G16G kernels reached on real J773g hardware (
19via CTS +5additional via the readback tests):- CTS (19):
AGX3_DECOMPRESS_{0,1,2},COPY_IMAGE,FAST_CLEAR_{0..4,6..8,10..13},MIPMAP_UNORM8X4,RESET_COMPRESSION_METADATA,RESOLVE_UNORM8X4 - Test-only (5):
AGX3_DECOMPRESS_{3,4,5},FAST_CLEAR_5,MIPMAP_UNORM8X4_ODD - Unreached (3, expected non-Vulkan-reachable):
FAST_CLEAR_9,FAST_CLEAR_14,MIPMAP_UNORM8X4_2LEVEL
- CTS (19):
GPU health
0new kernel/GPU fault or recovery lines (health: failed 0 errno 0 degraded 0before and after).
J700 (MacBook Neo, A18 Pro, G17P B1) at
|
| Check | Result |
|---|---|
| CTS, 3,027 cases chosen because they launch at least one of the built-in kernels this PR changes | 3,027 of 3,027 recorded and Pass on both arms, 0 status differences, 0 head-only failures |
The readback tests, each in base, head, head, base order (msaa_r8_2x, decompress_{1,2,4}x_layered, mip_plain, resolve_plain) |
PASS: exit 0 in all runs, head's output byte-equal to base's |
| Kernel reach, measured with a probe build: of the 27 changed kernels on G17P, how many run in these cases or tests | 24 covered (19 by CTS cases that pass on both arms, 5 only by the readback tests). 3 not reachable from Vulkan here: FAST_CLEAR_9 and FAST_CLEAR_14 (16-byte multisampled images are never compressed) and MIPMAP_UNORM8X4_2LEVEL (only the GL driver launches it) |
| Size | 27 of 97 kernels change, none is larger (84,432 to 84,088 bytes in total) |
| GPU faults, recoveries, lost devices, kernel WARN/BUG | 0 |
The J773g half of this group (G16G, same case list) is in the lead's receipt: #1559 (comment)
Not covered: the readback tests were built from f5ff0023's sources (unchanged at this head for what they test).
J714s (Apple M5 Pro / T6050 / G17S B1) exact-head receipt at
|
What: Extend
agx_nir_opt_bitfield_slices()with a follow-upopt_disjoint_ior_instr()pass (running after adjacent bitfield slice merging completes, with DCE + upper-bound cache reset when slice merging makes progress) to fuse two disjoint 32-bit bit-unpack patterns intoimadshl_agx(other, 1, ..., sh)(1 <= sh <= 4):ior(other, base << k)(orimadshl_agx(0, 1, base, k)) when single-use andknown_zero_bits_u32()proves zero overlapping 1-bits ((~kz(other) & (~kz(base) << k)) == 0).ior(other, iand(ushr(x, s), ((1 << w) - 1) << tz))when single-use,otheris known zero across the mask, and upper-bound analysis (nir_unsigned_upper_bound()+u32_upper_bound()) provess <= 32 - (tz + w)(non-wrapping shift), folding directly toimadshl_agx(other, 1, ubitfield_extract(x, s + tz, w), tz).Also teach
known_zero_bits_u32()that carry-free unit-multiplierimadshl_agx(a, 1, c, k)preserves the intersection ofa's and(c << k)'s known-zero bit masks so chained disjoint shifts continue to fuse.Tested:
aurora-wipd59f5aee1d9(headf8a608c0a01), x86-64, clang, asserts on:libvulkan_asahi.soand all compiler tests build; 59 of 59 compiler tests pass,agx_tests1980 passed / 0 failed / 1 skipped. The built-in kernels this changes are the same 27 (G16G), 27 (G17P) and 29 (G17S), with the same code, as before the merge.f5ff0023b6c, before the merge: PASS, see the receipts in the comments.origin/aurora-wip(cb983a61cb1, head98547a87cbb,gcc 16.1.1,aarch64,-Dbuildtype=release -Db_ndebug=false):libvulkan_asahi.sobuilt with0warnings in touched files;meson test -t 4 --suite asahi398 Ok / 0 Fail / 1 Skipped;agx_tests1971 passed / 0 failed / 1 skipped (7/7*BitfieldSlices*, including value-checkedSharedByteOffsets.BitfieldSlicesDisjointIorShlAndShiftedMaskandSharedByteOffsets.BitfieldSlicesMergeBeforeDisjointIorFusion).llama-benchpipelines showedq4_K -160instrs (HOT -6),q6_K -112instrs (HOT -8),MUL_MAT_VEC -16instrs (HOT -4),0:0spills. (Earlier J604llama-benchnumbers came from a combined build and are not standalone proof for this commit.)Risk: two-way door · AGX3B and AGX3C (M3, M4, A18 Pro, M5, and M6 through AGX3C) across all shader stages (not compute-only) —
agx_nir_opt_bitfield_slices()runs underis_agx3. Carry-freeior -> imadshl_agxreplacement andknown_zero_bits_u32()propagation are strictly gated on disjoint known-zero bit masks, and theushr + iand -> ubitfield_extractrewrite is strictly gated on proven non-wrapping shift boundss + tz + w <= 32and single-use scalar operands. Running disjointiorfusion after slice merging guarantees no existing bitfield slice merge is hidden.Not yet:
gpubench compute.*and one graphics row.llama-benchwith a Q6_K model (neither Mac had one).Offline & unit test details
origin/aurora-wip(cb983a61cb1, standalone, zero stacking dependencies)98547a87cbbe836e43403bab186ed62f484dd76esrc/asahi/compiler/agx_nir_lower_shared_bitsize.c,src/asahi/compiler/test/test-shared-byte-offsets.cppSharedByteOffsets.BitfieldSlicesDisjointIorShlAndShiftedMask: verifies both positive fusions, negative guards (unbounded shiftidxand overlapping bit 4), and concrete value equivalence before/after the pass.SharedByteOffsets.BitfieldSlicesMergeBeforeDisjointIorFusion: verifies value equivalence and exact post-DCE ALU counts for all 3-term merge/chain cases (((x & 3) | ((y & 3) << 4)) | (ubfe(x, 2, 2) << 2)->3ALUs,((x & 3) | ((y & 3) << 2)) | ((z & 3) << 4)->5ALUs,((x & 15) | ((y & 15) << 4)) | (ubfe(x, 4, 4) << 8)->6ALUs, and a non-slice second term((x & 3) | ((y & 0x0f0f) << 4)) | (ubfe(x, 2, 2) << 2)->3ALUs).