Skip to content

spirv_opt: optional native optimize() (tools/spirv_opt_native), ~11x, same text, Python fallback (PERF-SPIRV-OPT-NATIVE) - #9645

Closed
TG0000 wants to merge 2 commits into
ProjectLeonida:mainfrom
TG0000:t3/spirv-opt-native-accelerator
Closed

TG0000 wants to merge 2 commits into
ProjectLeonida:mainfrom
TG0000:t3/spirv-opt-native-accelerator

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Item: PERF-SPIRV-OPT-NATIVE (claim). Same pattern as #8751 / #8447.

What

tools/spirv_opt_native is a zero-dependency Rust port of optimize() in tools/spirv_opt.py. It follows the Python passes line for line, so the output text is identical:

  • the header scan;

  • escape and slot analysis;

  • the CFG and Cooper-Harvey-Kennedy dominators;

  • the dominator-scoped walk with its undo logs;

  • dead-slot store elimination;

  • backward DCE;

  • the reassembly that drops decorations of deleted ids.

  • The native path never reports errors. In each of these cases it declines and optimize() runs the Python code unchanged, with its usual result or exception:

    • text that is not ASCII, or control characters other than tab and line ends;
    • integer literals longer than 1000 characters (CPython's int/str digit limit);
    • more than one OpConstantTrue or OpConstantFalse. Python's next(iter(const_true)) then depends on string hashing, and the test shows two processes disagree on it;
    • inputs where Python raises: _fold_int_op(op, args[0], …) on an instruction with a result and no operands, or a del of a missing undo key;
    • alias cycles, where Python's resolve() never returns (see below);
    • an output buffer that cannot be allocated.
  • Other fallbacks: a missing library and LEONIDA_SPIRV_OPT_NATIVE=0 also keep everything in Python.

  • Hardening:

    • the FFI entry point is wrapped in catch_unwind(AssertUnwindSafe(…));
    • the output goes through try_reserve_exact;
    • import ctypes and the argtypes/restype setup are inside try/except (ImportError, OSError, AttributeError);
    • only an exact str and int take the native path;
    • no gc.disable();
    • no #[target_feature]; it builds on Rust 1.85+.
  • Minimal hook: a _native_optimize / _load_native loader just above optimize(), plus three lines at its top and import os. The Python reference is untouched.

  • CI: a new step in the standard-library job builds and tests the crate (--locked --offline, RUSTFLAGS="-D warnings"), asserts that the library loads, then runs test_spirv_opt_native.py and test_spirv_opt.py with the native path on.

Benchmarks

All inputs are synthetic and there is no game data. AMD Ryzen 9 5900X, Windows 11, Python 3.12.10, rustc 1.100.0. The machine is shared and noisy; the native figure is the best of 5 runs.

corpus Python optimize() native via the hook speedup
translator output for the 52 hand-written tests/semantic fixtures (2.45 MB) 396–423 ms 37.6 ms 10.5–11.3x
189 random synthetic modules (1.18 MB) 162–169 ms 21.8 ms 7.4–7.7x

The Rust core alone runs at about 55–60 MB/s (cargo run --release --example bench); the ctypes round trip costs about 6 µs per call.

This is short of the 20x I aimed for. Much of Python's cost here is already in C (str.split, dict and set operations). What remains is the per-instruction table work of the dominator walk, which the port has to repeat to give the same text. I went from 4x to about 11x by:

  • replacing the std hash map behind the token interner with an open-addressing table;
  • adding a final mix to the hasher (its bare product put every %-token of a given length in one bucket);
  • using flat operand arenas instead of per-line vectors;
  • using flat arrays for the token-keyed tables.

Further gains would mean restructuring the walk itself, which would make the line-for-line check against spirv_opt.py harder to review.

Tests

  • cargo build --release and cargo test --release (7 tests) with RUSTFLAGS="-D warnings": 0 warnings.

  • python -I tests/test_spirv_opt_native.py (new, 11 tests), comparing native against Python:

    • 1,500 random synthetic modules: 1,455 run natively and 45 are declined. Of those 45, 3 are modules where Python never returns; the rest go to Python with the same result. The modules cover every opcode the optimizer reads and odd integer spellings (010, 0x_1f, 1_0, +8, 2^64 + 3). They also cover CRLF and lone CR, comments, quoted lines, decorations and group decorations of deleted ids, unreachable blocks, back edges, switches, phis, volatile accesses, dynamic and mixed-depth access chains, and two-function modules;
    • 200 more with pass counts from -1 to 5, plus True and 10**30;
    • hand-written edge cases;
    • the translator's output for the hand-written tests/semantic fixtures, all run natively;
    • 4 concurrent threads;
    • the fallbacks: env var off, missing library, declined call, non-str input and out-of-range pass counts.

    Declined inputs are compared in a child process with a time limit, where optimize() with and without the native path run under one hash seed. The comparisons skip when the library is not built.

  • python -I tests/test_spirv_opt.py with native on and with LEONIDA_SPIRV_OPT_NATIVE=0: OK.

  • python -m compileall -q make_game.py tools tests: OK.

  • python -I scripts/check_no_game_data.py on every changed file: clean.

  • The translator is unchanged, so tests/semantic was not rerun in full.

Found on the way

The Python optimize() can loop forever in resolve() (tools/spirv_opt.py:547, from the post-walk sweep at line 945) on some synthetic modules with back edges. The test generator produces 3 such modules in 1,500. The port declines those, so behaviour is unchanged. I'm posting it as a finding: in the coordination issue, not fixing it here.

CPU-only change; no GPU or driver involved. Tested on Windows 11 (AMD Ryzen 9 5900X).

AI-assisted: written with Claude Code (Claude Opus 5.5) and reviewed by me.

🤖 Generated with Claude Code

…text, Python fallback

A zero-dependency Rust port of optimize() that follows the Python passes line for line, so the output text is
identical. spirv_opt.py loads it when it is built; LEONIDA_SPIRV_OPT_NATIVE=0, a missing library or any input the
port declines keeps everything in Python. The port declines non-ASCII text, more than one OpConstantTrue or
OpConstantFalse (the result then depends on set order), inputs where Python raises, and alias cycles (where Python
never returns).

tests/test_spirv_opt_native.py compares the two on 1,500 random synthetic modules, random pass counts, edge cases
and the translated tests/semantic fixtures, and checks threads and the fallbacks. A CI step builds and tests the
crate.

PERF-SPIRV-OPT-NATIVE. AI-assisted.

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

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The benchmark counts a module that the native optimizer declines. At ba9daa1 on Windows 11, I used an empty folder and wrote one UTF-8 assembly file into it:

from pathlib import Path
Path("one.spvasm").write_bytes((";\u00e9\n" * 100000).encode("utf-8"))

Run the release example with that folder as its only argument. It reported 1 modules, 0.40 MB: 0.0 ms (inf MB/s). The native entry point returned 1 (declined) for the same 400000 bytes. With 100000 ASCII comments (b";a\n" * 100000), it returned 0 and produced 300000 bytes.

In examples/bench.rs, optimize(m, 4).ok() discards the result status. Please fail the benchmark on a declined input, or report declined modules separately and calculate native throughput from accepted work. This test does not establish that any module in the reported 11x measurement was declined.

AI-assisted.

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

Independent CPU review of ba9daa13f5b56f4937fd4a6378f3859ad7602861, macOS 27.2.1 / Apple Silicon / CPython 3.14.6, Rust release build. No GPU or game files.

Finding: integer subclasses can change the optimization pass count when the native backend is present. tools/spirv_opt.py:1034-1038 accepts any isinstance(max_passes, int) and then calls int(max_passes). The Python implementation passes the original value to range(max_passes), which uses the integer's index value rather than an overridden __int__. For example:

import spirv_opt
class Passes(int):
    def __int__(self):
        return 0

text = '''%uint = OpTypeInt 32 0
%u3 = OpConstant %uint 3
%u5 = OpConstant %uint 5
%u8 = OpConstant %uint 8
%main = OpFunction %void None %fn
%entry = OpLabel
%a = OpIAdd %uint %u3 %u5
OpStore %out %a
OpReturn
OpFunctionEnd
'''
print(spirv_opt.optimize(text, Passes(4)))

With the release library loaded, this leaves OpIAdd and stores %a; with LEONIDA_SPIRV_OPT_NATIVE=0 set before import, it folds to OpStore %out %u8. Thus the two paths return different text for the same call. This is an unusual API input, not evidence of a regression for normal integer pass counts. The documented exact-type guard could decline integer subclasses (while handling bool deliberately), or the conversion could match Python's indexing behavior; please add a parity regression.

Checks:

  • RUSTFLAGS='-D warnings' cargo test --release --locked --offline: 7 passed; release build passed.
  • python3.14 -I tests/test_spirv_opt_native.py: 11 passed; its 1,500 random cases reported 1,455 native, 45 declined, including 3 Python hangs handled by timeouts.
  • tests/test_spirv_opt.py: 11 passed with native enabled and 11 with LEONIDA_SPIRV_OPT_NATIVE=0.
  • Additional independent seed 0xACE171: 5,000 synthetic generated modules at 4 passes; 4,828 accepted results matched the Python output and 172 were declined. This uses the PR's generator with a different seed, not a separate grammar.
  • Changed-source no-game-data check passed. git diff --check 5d74c272 HEAD reports a new blank line at EOF in tools/spirv_opt_native/src/lib.rs (line 2497).

I did not measure GPU behavior, real shaders, Windows integration, or claim that randomized parity proves equivalence. The benchmark's handling of declined modules was already raised separately by @shdann. AI-assisted (Codex). Claim: #9677 (comment)

@catminou4

Copy link
Copy Markdown
Contributor

Tested ba9daa1 on macOS 26 arm64, Python 3.12, CPU only, no game files: pass. cargo build --release in tools/spirv_opt_native (no deps, ~5s) then python -m pytest tests/test_spirv_opt_native.py — 11 passed, 12 subtests passed in 84s, so the native optimize() path is exercised on this host, not skipped. AI-assisted (Devin).

@RAINighty

Copy link
Copy Markdown

Tested ba9daa13f merged with main 5d74c2723 (clean merge) on Windows 11 (10.0.26300), Python 3.13.15 (venv with the pinned tests/requirements.txt), Rust 1.100.0 (stable-x86_64-pc-windows-msvc), Intel Core i7-14650HX: pass, with the native library built.

  • python -I tests/test_spirv_opt_native.py before building: Ran 11 tests, OK (7 skipped, because the native library is not built).
  • cargo build --release --locked --offline --manifest-path tools/spirv_opt_native/Cargo.toml: succeeds with no warnings. cargo test --release --locked --offline on the same manifest: 7 passed, 0 failed.
  • python -I tests/test_spirv_opt_native.py after building: Ran 11 tests, OK, none skipped (the run took 94 s).
  • Windows only; I did not run it on Linux or macOS and did not compare timings. Code not reviewed beyond running it. No GPU or game files.

AI-assisted (Claude Code).

…s, no trailing blank line

- _native_optimize takes the port only for a plain int max_passes; an int subclass that overrides
  __int__ stays in Python, where range() uses __index__. Regression test added.
- examples/bench.rs counts accepted and declined modules apart, times and reports MB/s over the accepted
  bytes only, and exits 1 instead of printing inf MB/s when none is accepted.
- Drop the blank line at the end of src/lib.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
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.

6 participants