Skip to content

reprend #2183: loop guard: one total of loop visits per invocation, on top of each loop's limit (SHADER-LOOP-TOTAL) - #2736

Closed
OreoFR wants to merge 4 commits into
ProjectLeonida:mainfrom
OreoFR:carry/pr-2183
Closed

OreoFR wants to merge 4 commits into
ProjectLeonida:mainfrom
OreoFR:carry/pr-2183

Conversation

@OreoFR

@OreoFR OreoFR commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Carries #2183 by @QemmHD, because it conflicts with main after #2566 and the reminder to merge main (#2183 (comment)) got no answer within the delay of the carry rule. If the author comes back, this carry is dropped.

Item: SHADER-LOOP-TOTAL-CARRY (claimed in #2570 (comment); original item SHADER-LOOP-TOTAL).

What this branch is

What conflicted and how it was resolved

  • tools/spirv_loop_guard.py (2 hunks): the PR's TypePointer|EntryPoint added to main's CRLF-safe regex; main's bool/int check on limit applied to total too.

Open question for a human: tests/semantic/test_wave64_single_wave_barrier.py (a main test, a02a5ef) fails on this branch: it requires that a barrier inside a loop depends only on %pc, and the PR adds %loop_guard_total to the loop's exit condition. Is that safe for a barrier under emulated wave64, and should such loops be left out of the total or the test widened? Not decided here. The concern djrolfes raised and qhukz13 reproduced on #2183 (scheduler barrier) is the same area.

Tests

  • On this branch (main f9f3ec4c6 merged), Windows 11, Python 3.12, no GPU used: tests/semantic/test_loop_iteration_guard.py: 6 OK; tests/test_spirv_loop_guard.py: 9 OK; tests/semantic/test_wave64_single_wave_barrier.py: 1 failure (see above).
  • Earlier merge: red: test_loop_iteration_guard 2 errors; full semantic suite 529 files / 6527 tests, 3 failures = main's 2 + test_wave64_single_wave_barrier.
  • python -I scripts/check_no_game_data.py on every file this PR changes: clean.
  • CI on this PR covers the rest (C++ build and ctest, the full translator suite).

Depends on: none.

Needs a careful human read of the resolution and an independent verifier before merge (red/green on another machine).

AI-assisted (Claude Code, oreofr-agent).

🤖 Generated with Claude Code

QemmHD and others added 3 commits November 25, 2026 21:01
…op's limit

tools/spirv_loop_guard.py caps each loop at 65,536 visits from every entry, so
nested loops multiply their caps: an inner loop may make 65,536 visits in each
of 65,536 visits of the outer one. A loop bound computed by a float divide
whose divisor is 0 is +inf. It converts to 0xFFFFFFFF, and an inclusive exit
test against it never fails once the counter wraps. A compute program with
nested loops of that kind ran at the caps for seconds a dispatch, and the
device was lost with no faulting address.

--loop-total N (default 1,048,576; 0 = none) adds one count of every guarded
back edge of the invocation, in a Private variable listed by the entry point.
No back edge passes once it reaches N. Each loop keeps its own limit, so a loop
that ends by itself is cut only after the whole invocation made N visits.
make_game.py passes the flag on and records it with the other translator flags.

The default changes the translation of every program with a loop, so a shader
library takes it when it is translated again.

Tests (tests/semantic/test_loop_iteration_guard.py): two nested loops that
never end stop at the total, in wave32 and in emulated wave64 (whose round
scheduler spends from the same total); loops that end by themselves are
untouched; without a total the per-loop counts multiply. Three test-local SPIR-V
interpreters (test_loop_ballot_barrier, test_control_flow_branches,
test_wave64_emulate_opt) now give each invocation its Private globals, which
every module with a loop has from now on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf
spirv_loop_guard: TypePointer|EntryPoint (PR) in main's CRLF-safe regex; main's bool/int check on limit applied to total too.

Co-authored-by: QemmHD <290605352+QemmHD@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Current main after ProjectLeonida#2566; no new conflicts on top of the earlier carry merge.

Co-authored-by: QemmHD <290605352+QemmHD@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@OreoFR

OreoFR commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator Author

Verified by OreoFR on macOS 27.2.1, Apple M5, Python 3.12.16 (pytest, no GPU), main f9f3ec4c6.

  • MEASURED, red (main + only this PR's tests): test_loop_iteration_guard.py: 1 failed, 4 passed. test_control_flow_branches.py (33), test_loop_ballot_barrier.py (15) and test_wave64_emulate_opt.py (34) pass on both sides.
  • MEASURED, green (main + merge --no-ff of 528e65eb4): test_loop_iteration_guard.py 6 passed; the other three unchanged and passing.
  • MEASURED, still red with this PR: tests/semantic/test_wave64_single_wave_barrier.py: 1 failed, 2 passed. The failure is AssertionError: {'%loop_guard_total', '%pc'} not less than or equal to {'%pc'} (line 103).
  • MEASURED: the same file on plain main f9f3ec4c6 passes (3 passed), so this PR is what turns it red. That matches the open question in the PR description.
  • Verdict: not green. 1 file regresses, and it waits on the human decision the description asks for (leave such loops out of the total, or widen the test).
  • Not covered: the C++ build, ctest and the rest of the suite (CI).

Not independent: this PR and this check share the same owner (OreoFR). Treat it as a second-machine run, not an independent review.

AI-assisted: Claude Code

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent dynamic barrier counterexample on the carry. 528e65eb merged onto main f44904d2 (tree 90f7d91c). CachyOS x86-64, Python 3.14.10, SPIRV-Tools 2026.4. CPU interpretation of synthetic programs only.

MEASURED. I translated the checked-in BarrierInLoopsTests._wave_divergent_barrier_loop_cs(True) fixture as a 128-invocation compute workgroup on 32-lane subgroups (emulate=True, structured=False, per-loop limit 64). The translated form is emulated wave64 rounds.

Loop guard CPU workgroup result
main per-loop only Completed, readback 2 on lanes 0–63 and 4 on lanes 64–127
PR, aggregate limit 0 Completed with the same readback
PR, aggregate limit 16 64/128 invocations arrived (64 already returned) at OpControlBarrier
PR, aggregate limit 16 except at the outer %loop_head Completed with the same readback, aggregate guard still present on the inner chain loop

A separate 64-invocation SPIR-V fixture has a finite first loop taking 1 or 3 iterations and then a shared loop with three workgroup barriers. At aggregate limit 4, only 32 invocations reach the third barrier. Main and a test-only control that leaves the aggregate check off that specific barrier loop complete with all 64 reaching all three barriers. All 10 generated modules pass spirv-val --target-env vulkan1.2. The execution requirement is stated in the SPIR-V specification for OpControlBarrier.

Five stock test modules gave 65/65 on main and 66/67 on the PR. The sole stock failure is the separate single-wave %pc guard assertion. The dynamic failure above uses the real round scheduler and deliberately small test budgets. A second agent recomputed the results from the modules. AI-assisted.

… too

Main's single-wave barrier test (merged after ProjectLeonida#2183 was written) allows only
%pc in the conditions around a barrier. The invocation total of the loop
guard is loaded in those conditions as well; it counts the guarded back
edges, which every invocation takes alike when the loop conditions test only
%pc and the total, so it is as uniform as %pc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@merzleckeier

Copy link
Copy Markdown
Contributor

Wave64 barrier follow-up on 083c011

I reran the two-wave fixture with 083c011a9 merged onto main be769080 (tree b8158809). The new revision updates the single-wave assertion to allow the aggregate guard. The preceding PR revision and this one have the same tools/ tree when merged onto that base.

MEASURED. All five targeted suites pass (66 tests on main, 68 on the merge tree, including three single-wave tests on each). For the two-wave case, I used the repository's synthetic BarrierInLoopsTests._wave_divergent_barrier_loop_cs(True) fixture with 128 invocations, 32-lane subgroups, emulate=True, structured=False, and a per-loop limit of 64. Execution used the CPU interpreter.

Aggregate budget Result on the merge tree
0 (disabled) 64 outputs of 2 followed by 64 outputs of 4, matching main
12 The first 64 outputs are 2. The other 64 are unwritten.
16 Non-uniform OpControlBarrier: 64/128 invocations arrived (64 already returned)
24 All 128 outputs match main.

The budget-16 assembly is byte-identical to the earlier report. In a test-only control, I exempted just the %loop_head scheduler back edge from the aggregate budget. The per-loop limit and the inner loop's aggregate check still apply. That restores all 128 outputs at budgets 12 and 16 for this fixture. All seven modules pass spirv-val --target-env vulkan1.2. An independent CPU replay of the assemblies confirmed the outcomes with both subgroup scheduling orders.

The results show the scheduler's aggregate exit can diverge at a caller-selected budget even with the updated single-wave check. Earlier report

@KelboLive

Copy link
Copy Markdown

Full-suite failure on Windows at 528e65eb4: the branch is red against main in an existing test.

python -I -m unittest discover -s tests/semantic -p test_wave64_single_wave_barrier.py
...
FAIL: test_single_wave_stays_structured_with_pc_only_guards
  File "tests/semantic/test_wave64_single_wave_barrier.py", line 103, in test_single_wave_stays_structured_with_pc_only_guards
    self.assertLessEqual(loaded, {"%pc"})
AssertionError: {'%pc', '%loop_guard_total'} not less than or equal to {'%pc'}
Ran 3 tests: FAILED (failures=1)
  • Same command on main b17b22d33: 3 tests OK.
  • The branch is green on its own targeted files (test_loop_iteration_guard, test_loop_ballot_barrier, test_control_flow_branches, test_wave64_emulate_opt), so this is an expectation the new %loop_guard_total state invalidates in a file the PR does not touch.
  • The full 549-file suite stops on it as FAILED: test_wave64_single_wave_barrier (exit code 1).

Either the test needs %loop_guard_total allowed in that load set (if loading it in a single-wave shader is intended), or the translator should not emit that load for the PC-only-guard case. As-is, CI's semantic job should be red for this head.

AI-assisted: yes (opencode).

@KelboLive

Copy link
Copy Markdown

Full-run summary for the failure above: *549 files, 6,677 tests, 1 file failed — \ est_wave64_single_wave_barrier* (448 s, -j 16). Every other file passes.

@KelboLive

Copy link
Copy Markdown

Suggested resolution: the new %loop_guard_total is a Private per-invocation value (uniform across the wave), so the barrier guards are still uniform — the test's set is what needs widening, not the translator. One-line change in tests/semantic/test_wave64_single_wave_barrier.py:

# The invocation-wide loop total is uniform (a Private variable), so it may appear in a barrier guard.
self.assertLessEqual(loaded, {"%pc", "%loop_guard_total"})

That keeps the property the test is about (no lane-varying value in a barrier guard) while accepting the new guard. The full suite then needs a rerun to confirm nothing else asserts the old set.

@KelboLive

Copy link
Copy Markdown

Applied the one-line change locally on top of 528e65eb4 (not pushed) and re-ran:

  • test_wave64_single_wave_barrier.py: 3 tests OK.
  • Full suite: 549 files, 6,677 tests, 0 files failed in 350 s with -j 24.

So the widened set is the only blocker on this machine; no other test depends on the old assertion. The exact change I applied:

            # The invocation-wide loop total is uniform (a Private variable), so it may appear in a barrier guard.
            self.assertLessEqual(loaded, {"%pc", "%loop_guard_total"})

AI-assisted: yes (opencode).

@KelboLive

Copy link
Copy Markdown

Confirmed on the updated head 083c011a9:

  • test_wave64_single_wave_barrier.py: 3/3 OK (the new test comment covers the uniform loop-total guard).
  • Full suite: 549 files, 6,677 tests, 0 files failed in 393 s with -j 32.

The regression from the earlier head is resolved on Windows. Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, Python 3.12.10, llvm-mc 21.1.8.

AI-assisted: yes (opencode).

@aslan2142 aslan2142 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Although this carry of #2183 is mergeable with green CI on head 083c011, it still has a reproduced correctness blocker in tools/spirv_loop_guard.py:

  • Non-uniform OpControlBarrier hazard: %loop_guard_total is a per-invocation Private counter incremented at every guarded back edge, including outer wave64 round-scheduler loops (%loop_head/%loop_cont) and loops containing OpControlBarrier. When one wave executes more inner-loop iterations than another, it hits --loop-total first and exits the barrier loop while the other wave loops back and waits at OpControlBarrier (independently reproduced on head 083c011 at budgets 12 and 16 using BarrierInLoopsTests._wave_divergent_barrier_loop_cs(True): 64/128 invocations arrived at OpControlBarrier).

Widening tests/semantic/test_wave64_single_wave_barrier.py does not resolve the multi-wave barrier divergence. Please exempt barrier-containing / outer round-scheduler loops from the per-invocation aggregate budget (or make their exit workgroup-uniform) and add a multi-wave regression test before merging.

(AI-assisted review.)

@aslan2142 aslan2142 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Keeping #2736 over closed original #2183 (SHADER-LOOP-TOTAL): thank you for preserving @QemmHD's commit 88abd1609, resolving the tools/spirv_loop_guard.py conflict with main's CRLF and bool checks, and fixing tests/semantic/test_wave64_single_wave_barrier.py so CI is green.

However, requesting changes before merge for the unresolved correctness defect reproduced by @qhukz13 on #2183 (which this carry preserves unchanged):

  • In the --wave64-emulate round-loop form (x_scheduler, x_mini_scheduler, bar_scheduler), %loop_guard_total counts every inner-loop back edge per invocation. When one wave does more inner-loop work than another wave in the same workgroup, the busier wave hits --loop-total and exits the outer scheduler round loop while the other wave continues to the next OpControlBarrier, producing a non-uniform OpControlBarrier (Vulkan UB / GPU hang — reproduced on 2–3 of 24 synthetic NGG mesh programs in spirv_mini_interp.run_workgroup).
  • Please either exempt barrier-containing scheduler round loops from the per-invocation total (keeping their uniform per-loop limit) or make the total-exceeded exit uniform across the workgroup, and add a regression test covering a two-wave workgroup with asymmetric inner-loop trip counts.

(AI-assisted review.)

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

Reproduced the blocker on 083c011a9 (Windows, CPU interpreter, no game data): BarrierInLoopsTests._wave_divergent_barrier_loop_cs(True), 128 invocations, 32-lane subgroups, --wave64-emulate:

--loop-total result
0 (main) ok — lanes 0–63 → 2, 64–127 → 4
8 silent wrong output (second wave unwritten, -1)
12 NonUniformBarrierError: 64/128 invocations arrived at OpControlBarrier
16 / 24 / 32 / 1M ok

So the guard does not only truncate — it can make a valid program hit a non-uniform barrier, which is the class of bug the emulation layer exists to avoid.

The claim in the new test_wave64_single_wave_barrier.py comment — that %loop_guard_total is wave-uniform because it only follows %pc — holds only for that single-wave fixture. %loop_guard_total is a Private per-invocation counter, and the wave64 round-scheduler's %loop_head/%loop_cont spends from it, so as soon as two waves have different inner trip counts the per-lane totals diverge and the scheduler exits per lane. Please exempt barrier-containing/scheduler loops from the aggregate total (or make the total-exceeded exit workgroup-uniform) and add a two-wave asymmetric-trip-count regression test.

Separately, the total silently truncates a program main completes: a terminating nested loop with per-loop limit 4,000 that visits 9,000 times returns 9000 with total=0 and 6000 with total=6000, no diagnostic. At the 1M default any invocation legally exceeding 1M back edges is cut, so that trade-off needs an explicit note (and ideally a diagnostic) in the switch docs.

The boundary itself is pinned correctly: reverting the aggregate gate fails test_total_bounds_nested_loops ([2500] != [41]) and OpULessThan→OpULessThanEqual fails with [42] != [41]. Tests otherwise pass (15 targeted, 85 barrier/emulation, 42 make_game, full semantic 549 files / 6,677 tests), spirv-val is clean, merge-tree is clean, and nothing here is duplicated on main (#2183 is closed unmerged).

Minor: no total= unit test in tests/test_spirv_loop_guard.py, --loop-limit 0 silently suppresses --loop-total, and only the last OpEntryPoint gets the interface entry.

@aslan2142

Copy link
Copy Markdown
Collaborator

Closing this PR because the legacy C++ Vulkan runtime (and legacy Python shader compiler) is now considered deprecated in favor of the new Rust Vulkan runtime (in progress) and the Rust DX12 runtime (d3d12/) available now. Thank you for the contribution! If you believe this PR was closed by mistake (for example, if it still applies to active tools, d3d12/, or general docs), please feel free to reopen it.

@aslan2142 aslan2142 closed this Dec 1, 2026
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.

5 participants