Skip to content

agx: optimize AGX3B ufind_msb/subgroup lane ops and signed pow2 idiv - #801

Closed
DjDeveloperr wants to merge 2 commits into
perf/agx3b-interior-bounds-stencil-peelfrom
perf/agx3b-wave8-subgroup-idiv
Closed

DjDeveloperr wants to merge 2 commits into
perf/agx3b-interior-bounds-stencil-peelfrom
perf/agx3b-wave8-subgroup-idiv

Conversation

@DjDeveloperr

@DjDeveloperr DjDeveloperr commented Nov 23, 2026 •

Copy link
Copy Markdown

Stacked on #762 (8f7cee6d4c11, perf/agx3b-interior-bounds-stencil-peel).

Summary

  1. AGX3B integer bit ops (src/asahi/compiler/agx_compile.c):
    • Emit immediate shift counts directly in agx_g17p_ushr_imm() instead of materializing shift boundaries in registers.
    • Replace the 16-op SWAR popcount in agx_emit_g17p_ufind_msb() with native agx_popcount_to() after bit smearing.
  2. Subgroup lowering (src/asahi/compiler/agx_nir_lower_subgroups.c):
    • On AGX3B (emulates_ufind_msb), lower first_invocation and vote_ieq using popcount(first_bit - 1) on the single-bit first-active ballot instead of invoking emulated ufind_msb.
    • In compute shaders (no helper invocations), lower ballot_bit_count_exclusive/inclusive(ballot(true)) and popcount(ballot(true) & subgroup_lt_mask) directly to active_subgroup_invocation_agx (+ 1 for inclusive).
  3. Signed power-of-two integer division (src/asahi/compiler/agx_nir_algebraic.py):
    • Fold nir_opt_idiv_const's 9-op imul(clamp(a, -1, 1), ushr(iabs(a), k)) sequence into the bit-exact 3/4-op sign-bias arithmetic shift (a + bias) >> k for k in 1..30 (exact for all int32_t, including INT32_MIN).

Testing & Verification

  • Assert-enabled fedora-mesaci (382d594c3af68e9e87fc428a28c6f6df5b8ec9a2): 146/0 PASS (wall 87 s, clang Fedora 44, -Dbuild-tests=true), including new unit tests AGX3VisionOpts.Wave8Agx3bSubgroupBallotLtMaskAndFirstInv and AGX3VisionOpts.Wave8FoldSignedPow2Idiv.
  • 4-chip shader-db (80 Geekbench/vision compute SPVs, -Db_ndebug=false, vs #762 R3 8f7cee6d4c11):
Chip Changed Instrs Bytes Helped / Hurt Spills
G15G 33 / 80 17210 -> 16715 (-495, -2.88%) 165394 -> 160734 (-4660, -2.82%) 33 / 0 0
G16G 33 / 80 17210 -> 16715 (-495, -2.88%) 165394 -> 160734 (-4660, -2.82%) 33 / 0 0
G17P 33 / 80 17389 -> 16928 (-461, -2.65%) 178250 -> 173736 (-4514, -2.53%) 33 / 0 0
G17S (M5) 0 / 80 14411 -> 14411 (+0, +0.00%) 136814 -> 136814 (+0, +0.00%) 0 / 0 0

Key G17P per-shader reductions: 24eb36d4 (-44i / -538B), 323926dd (-51i / -4g / -448B), 8b798f62 (-41i / -10g / -494B), 9020690a / a13778e1 (-44i / -400B each), e8b3e690 (-40i / -364B), 50e0fed8 (-17i / -176B).

  • Neo (G17P) hardware ABBA + CTS (combined Wave 8 becdef64 vs #762 R3 8f7cee6d, ``):
    • Feature Matching 35.61 -> 34.01 ms (1.047x, 24eb36d4 1.94 -> 1.67 ms / +16.2%); Horizon Detection 26.71 -> 26.55 ms (50e0fed8 4.74 -> 4.58 ms); 8/8 Geekbench Vulkan workloads faster, 0 regressions.
    • gpubench-vk 100% CRC_OK; bounded Vulkan CTS 1155/1155 PASS (glsl_int_bitops 288/288, subgroups_compute 102/102, glsl_loops 624/624, ssbo_std430 4/4, compute_basic 79/79), FAULTS_DELTA=0, AVC_DELTA=0.
    • Exact-head ARM64 tarball + cross-chip hardware rows to follow once built.

1. AGX3B integer bit ops:
   - Use immediate shift counts in agx_g17p_ushr_imm() instead of
     materializing shift boundaries in registers.
   - Replace the 16-op SWAR popcount sequence in agx_emit_g17p_ufind_msb()
     with native agx_popcount_to() after bit smearing.
2. Subgroup lowering:
   - On AGX3B (emulates_ufind_msb), lower first_invocation and vote_ieq
     using popcount(first_bit - 1) on the single-bit first-active ballot
     instead of emitting emulated ufind_msb.
   - In compute shaders (no helper invocations), lower ballot_bit_count
     exclusive/inclusive of ballot(true) and popcount(ballot(true) &
     subgroup_lt_mask) directly to active_subgroup_invocation_agx (+1 for
     inclusive).
3. Algebraic late pass:
   - Fold nir_opt_idiv_const's 9-op signed power-of-two idiv pattern
     imul(clamp(a, -1, 1), ushr(iabs(a), k)) into the bit-exact 3/4-op
     sign-bias arithmetic shift (a + bias) >> k for k in 1..30 (exact for
     all int32_t including INT32_MIN).

Signed-off-by: Diljit Singh <hey@djdev.me>

@RyanTheTide RyanTheTide 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.

CHANGES · source review of 382d594c3af6

The active-lane rank rewrites in agx_nir_lower_subgroups.c replace a previously computed ballot(true) with an active-lane read emitted at the consumer. The matcher follows SSA through control flow without proving the execution mask is the same. A ballot taken before a divergent branch still includes lanes from outside that branch. Computing the rank in the branch changes the result. Emit the rank under the ballot's execution mask or restrict the rewrite to a region where the mask is proven unchanged. Please add a divergent consumer regression for both the intrinsic and the lowered bit-count pattern.

Verification here was by source inspection.

@DjDeveloperr

Copy link
Copy Markdown
Author

M4 Hardware Verification (G16G B0) — Exact Head 382d594c3af68e9e87fc428a28c6f6df5b8ec9a2

  • Hardware / Env: Apple M4 Mac mini (J773g / T8132, Apple M4 (G16G B0)), kernel 7.3.0-ARCH-m4prod23, FW 27.2 (26B123), MESA_SHADER_CACHE_DISABLE=true.
  • Kit verified: Mesa 26.3.0-devel (git-382d594c3a), Borealis, derived from Honeykrisp (mesa-pr801-382d594c.tar.zst, SHA-256 32853968138e24157165de1a934b14a55331dcb04125025e21ad47ced384a000).
  • Base comparator: #762 R3 (perf/agx3b-interior-bounds-stencil-peel, 8f7cee6d4c11ece01106494dcd1ed8b582e21d35, Mesa 26.3.0-devel (git-8f7cee6d4c), Borealis, derived from Honeykrisp, mesa-pr762-r3-8f7cee6d.tar.zst, SHA-256 2017ea1d7f36d5a01a55ea4d0ab804744b7727e181e9a83d2618c5b47fd42d07).

Targeted Single-Threaded dEQP-VK CTS (713/1,073 PASS, 360 NotSupported, 0 FAIL, 0 dmesg delta)

  • subgroups_ballot (23/23): 14/23 PASS (9 NS, 0 FAIL)
  • subgroups_vote (200/805): 98/200 PASS (102 NS, 0 FAIL)
  • subgroups_arith (200/12087): 95/200 PASS (105 NS, 0 FAIL)
  • subgroups_shuffle (150/9562): 70/150 PASS (80 NS, 0 FAIL)
  • glsl_binop_div_mod (250/480): 250/250 PASS (0 NS, 0 FAIL)
  • spirv_compute_div (250/3573): 186/250 PASS (64 NS, 0 FAIL)

gpubench-vk ABBA vs #762 R3 (8f7cee6d4c, 48 runs)

  • Correctness: 40/40 CRC-bearing runs bit-exact match (0 diffs) + 8/8 compute.heavy status=ok.
  • G16G perf parity: Clean GPU parity 0.998x–1.000x across all clean rows (0 regressions; AGX3B emulates_ufind_msb paths remain gated off on G16G):
    • compute.edge (d=1/4): GPU 511.3 -> 511.8 us (0.999x), 516.9 -> 517.6 us (0.998x), CRC 27c79e6d (4/4 OK)
    • compute.conv2d (d=1/4): GPU 908.0 -> 908.9 us (0.999x), 909.7 -> 910.5 us (0.999x), CRC 2d55a14d (4/4 OK)
    • compute.stereo (d=1/4): GPU 18723.9 -> 18723.1 us (1.000x), 18721.9 -> 18720.2 us (1.000x), CRC c62aadf9 (4/4 OK)
    • compute.heavy (d=1/4): GPU 544.3 -> 544.3 us (1.000x), 544.3 -> 544.3 us (1.000x), status=ok (8/8 OK)
    • compute.cull_mdi (d=1/4): d=1 GPU 1271.9 -> 1272.1 us (1.000x), d=4 A1=1230.6 vs B1=1230.3 / B2=1230.2 (exact 1.000x; A2=1645.8 hit a brief 1.8s M4 cooling: ENODATA -> S1..S10 telemetry step during A2_base), CRC 57276de2 (4/4 OK)
    • compute.uber (d=1/4): GPU 500.0 -> 500.0 us (1.000x), 502.3 -> 502.2 us (1.000x), CRC 9963f56c (4/4 OK)

Health

  • FULL_BOOT_KERNEL_BUGS=0, 0 GPU/DRM faults, 0 non-cooling dmesg lines (DMESG_DELTA_LINES=10, all routine M4 cooling ENODATA->S1..S10 recovery lines), POST_IDLE=IDLE_CLEAN.

Assisted-by: LLM (Gemini:4 Neon)

@DjDeveloperr

Copy link
Copy Markdown
Author

G17S B1 (Apple M5 Pro / m5-ssd) Exact-Head Cross-Verification

  • Hardware / Kernel: Apple M5 Pro (G17S B1), Linux 7.3.0-m5-cdirect2 (+ 16-plane SLC)
  • Environment: MESA_SHADER_CACHE_DISABLE=1, no ASAHI_M5_BRINGUP
  • HEAD SHA: 382d594c3af6
  • ICD: Mesa 26.3.0-devel (git-382d594c3a), Borealis, derived from Honeykrisp (prebuilt ARM64 tarball mesa-pr801-382d594c.tar.zst)
  • Targeted VK CTS (glsl.builtin.function.integer.findMSB.*, glsl.combined_operations.negintdivand, subgroups.{arithmetic,ballot_broadcast,shuffle}.compute.*, compute.pipeline.basic.*): 366/502 passed (0 failed, 136 not supported)
  • Smoke (gpubench-vk compute.edge): PASS, CRC 27c79e6d valid (263.2 us d1 / 152.0 us d4)
  • Kernel GPU faults: 0 (dmesg delta 0)

@satchlj satchlj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verdict: FINISH, then merge

  1. src/asahi/compiler/agx_nir_lower_subgroups.c: is_ballot_true_def() (L95-114) resolves component 0 of def via nir_scalar s = nir_scalar_resolved(def, 0) and checks that s.def is nir_intrinsic_ballot(true), but never checks s.comp == 0. Because opt_compute_ballot_bit_count() runs before nir_lower_subgroups() when nir_intrinsic_ballot is still a 4-component uvec4 (ballot.x = lanes 0..31, ballot.y/z/w = 0), a compute shader passing a swizzled upper ballot component such as subgroupBallotExclusiveBitCount(uvec4(b.y, 0u, 0u, 0u)) (where b = subgroupBallot(true)) resolves to s = { .def = b, .comp = 1 }, passes is_ballot_true_def(), and gets miscompiled to load_active_subgroup_invocation_agx (0..31) instead of 0 (similarly 1..32 instead of 0 for ballot_bit_count_inclusive). In addition, opt_compute_ballot_lt_mask_count() (L189-192) and is_subgroup_lt_mask() (L149, L164) pass .def instead of the resolved nir_scalar into is_ballot_true_def(), is_subgroup_lt_mask(), and is_subgroup_invocation_mod32(), dropping .comp whenever an ALU operand extracts a non-zero component of a vector. Require s.comp == 0 in is_ballot_true_def() and propagate nir_scalar (preserving .comp) across is_ballot_true_*, is_subgroup_lt_mask, and is_subgroup_invocation_mod32, with a negative unit test for uvec4(b.y, 0, 0, 0).

Checked: Code review of src/asahi/compiler/agx_compile.c, src/asahi/compiler/agx_nir_algebraic.py, src/asahi/compiler/agx_nir_lower_subgroups.c, and src/asahi/compiler/test/test-agx3-vision-opts.cpp at 382d594c3af6.

Evidence
  • agx_g17p_ushr_imm(), agx_emit_g17p_ufind_msb(), fold_signed_pow2_idiv (k in 1..30, bit-exact including INT32_MIN), and the emulates_ufind_msb first_invocation / vote_ieq / vote_feq lowerings look sound.
  • In src/asahi/compiler/agx_nir_lower_subgroups.c:97-113, is_ballot_true_def() only validates ballot->intrinsic == nir_intrinsic_ballot and constant true predicate on s.def, omitting s.comp == 0; opt_compute_ballot_bit_count() executes at L511 before nir_lower_subgroups() (L515), while ballot is still uvec4.
  • In src/asahi/compiler/agx_nir_lower_subgroups.c:189-192, opt_compute_ballot_lt_mask_count() obtains nir_scalar a and nir_scalar b_s via nir_scalar_chase_alu_src() but passes a.def and b_s.def to helpers that always call nir_scalar_resolved(def, 0).

Match the actual low ballot word and retain scalar component indices when matching the mask. Read the active rank where the ballot was taken so a later divergent consumer cannot change the result.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
@RyanTheTide

Copy link
Copy Markdown

I pushed 5f925b0 on top of your branch. The rank lowering matches the low ballot word and retains the selected component through the mask matcher. It reads the active rank at the ballot producer so a later divergent consumer uses the original mask. The regression covers inclusive, exclusive, and already-lowered counts, including an upper-word swizzle. All 216 Clang host tests passed. The parent stack, exact-head CI and hardware evidence still gate landing.

@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 5f925b0 after existing gates

The matcher retains the resolved component and only admits the low ballot word. Rank is computed under the original ballot mask, so a divergent consumer no longer changes it. The fixture covers inclusive, exclusive and lowered forms plus upper-word rejection. Keep #762 ordering, exact-head CI and hardware.

@RyanTheTide
RyanTheTide dismissed satchlj’s stale review November 29, 2026 01:39

The matcher now carries the resolved component, rejects the upper ballot word, and computes rank at the producer. Negative and divergent-consumer tests passed. 5f925b0dc132

@github-actions github-actions Bot added area:compiler Area from CODEOWNERS (bot) needs-hw-row No hardware row at the PR head (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 5f925b0d: 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 no no line with the head SHA 5f925b0d, a Mac and a result in the PR body or a comment
Conflicts ok none
PR text adopt when you next edit 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

Thanks, Dj. I carried your integer, subgroup and division changes into #1540 on current aurora-wip with your sign-off preserved. I kept active rank at the ballot producer and reused the adjacent read where the same producer permits it. The live J615 cases improved 1.11–1.39%. On Neo, the highest-bit and divergent first/vote cases improved and signed division was at parity. Both machines matched all CPU readbacks. The paired results and raw GPU samples are in #1540. I’ll keep this original open until the replacement lands.

@RyanTheTide

Copy link
Copy Markdown

Thanks, Dj. The integer, subgroup and signed-division work landed in #1540 as c94b25ce4e2f with your sign-off preserved. The exact head passed independent review and local CI, and the J615 and Neo comparisons verified the outputs. Closing this original stack now that the replacement is in aurora-wip.

@RyanTheTide RyanTheTide closed this Dec 2, 2026
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-hw-row No hardware row at the PR head (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.

3 participants