Skip to content

Generate the RNG's batch four numbers at a time with AVX2 - #53

Closed
ashveikin wants to merge 1 commit into
omacom:masterfrom
ashveikin:rng-avx2
Closed

ashveikin wants to merge 1 commit into
omacom:masterfrom
ashveikin:rng-avx2

Conversation

@ashveikin

@ashveikin ashveikin commented Sep 30, 2026 •

Copy link
Copy Markdown

Adds AVX2 optimisation alongside already existing AVX-512 for src/utils/rng.rs

Why?

The Steam Hardware & Software Survey 2026 shows that AVX2 support is vastly more prevalent (around 95.4%) compared to AVX-512 support (around 23.9%), meaning that having an AVX2 fallback is going to cover more CPUs, thus making the optimisations available to more people on older CPUs.

How it fits in

  • Adds AVX2 optimisation alongside already existing AVX-512 for src/utils/rng.rs

Verification

  • All effects pass all available tiers (up to AVX2 for my machine) (oracle-simd.sh quick)

  • cargo test --release passes

Performance

Measured on Intel i7-10850H (12) with python3 tools/tests/bench_compare.py /tmp/ttfx-before target/release/ttfx --size 200x50 --repeats 31 --warmups 2 --cpu 8

The only reliable speedup was ~1.1–1.2x on matrix effect, every other effect ramained the same.

The same matrix animation (virtual clock, pacing off) completes ~1.1–1.2x faster using the test above - under the real clock that translates to better frame-rate.

effect before ms after ms speedup
matrix 48.13 41.49 1.160x

@omarchybot

Copy link
Copy Markdown
Collaborator

Reviewed at eabd204 by Claude Opus 5.5, with a second opinion from Codex Medium and muse-spark-1.3-contributor (via pi, thinking high). The AVX2 kernel produces exactly the scalar xoshiro256++ stream, detection keeps it off CPUs without AVX2, and the output is byte-identical to master. One gap in the tests and two stale SAFETY comments are below, with a fix I could not push. The speedup did not reproduce on the hardware I had.

Sequence identity. Run on a disposable VM worker (AMD Ryzen 9 9955HX, Zen 5, which has AVX-512). I forced each kernel on an Rng and compared it with plain scalar steps: 8 seeds, 12 batches plus a partial one each, with state() and from_state continuation checked inside batches. Scalar, AVX2 and AVX-512 all matched on every draw. The suite is green natively and under TTFX_NO_AVX512=1 (the AVX2 kernel end to end): 44 Rust tests, 354 effect-parity checks against the Python reference, 41 tty byte-stream checks, plus the CLI, signal and resize suites.

CPUs without AVX2. qemu-x86_64 -cpu Nehalem and -cpu qemu64: avx2_available() reports false, the RNG stays scalar, nothing traps, and the RNG tests pass. -cpu Haswell (AVX2, no AVX-512) picks the AVX2 kernel and passes. On non-x86_64 the cfg removes both SIMD arms. The AVX instructions inside the avx2 function are covered because avx2 implies avx.

Output parity. All 37 effects, 3 seeds, framed and --parity-dump output, both engines (TTFX_FX=1 and 0): byte-identical between master and this branch natively, under TTFX_NO_AVX512=1, and with both binaries under emulated Nehalem. The AVX2 kernel's output is also identical to the AVX-512 and scalar kernels on this branch (444 runs each).

Test gap (Claude and both reviewers). refill always prefers AVX-512, so on an AVX-512 machine batches_follow_the_stream never runs the new kernel. I swapped one _mm256_permute2f128_si256 immediate (0x20 to 0x31): cargo test stayed green on this worker, and the kernel only failed when forced. CI runners may well have AVX-512 too.

Stale SAFETY comments (Codex). The comments on both arms say lanes is only recorded when that one feature is available. Lanes are now recorded for either feature, so the comments are wrong. The new if self.avx512 / if self.avx2 guards are what make each call sound, and the comments should name them.

The fix, not pushed. I could not push to this branch from here, so it is below for you to apply. It is one commit to src/utils/rng.rs, 12 lines added and 7 removed. batches_follow_the_stream runs scalar, AVX2 and AVX-512 in turn, each capped at what the CPU reports, and the two comments name the guards. With it, the same transpose mutation fails the test natively, and so does a wrong rotate shift (19 to 18). The full suite is green with it on the worker, and under emulated Nehalem and Haswell.

-            // SAFETY: `lanes` is only recorded when AVX-512F is available.
+            // SAFETY: `avx512` is only set when AVX-512F is available.
             Some(lanes) if self.avx512 => unsafe { self.refill_lanes(lanes) },
             #[cfg(target_arch = "x86_64")]
-            // SAFETY: `lanes` is only recorded when AVX2 is available.
+            // SAFETY: `avx2` is only set when AVX2 is available.
             Some(lanes) if self.avx2 => unsafe { self.refill_lanes_avx2(lanes) },
@@ fn batches_follow_the_stream
-        // several batches, so the lane path (when available) runs too
-        let mut rng = Rng::seeded(99);
-        let mut s = Rng::seeded(99).s;
-        for _ in 0..3 * BATCH + 17 {
-            assert_eq!(rng.next_u64(), scalar_step(&mut s));
+        // several batches, so the lane paths run too: every kernel the CPU
+        // has, since refill only ever picks the widest
+        for (avx512, avx2) in [(false, false), (false, true), (true, true)] {
+            let mut rng = Rng::seeded(99);
+            rng.avx512 &= avx512;
+            rng.avx2 &= avx2;
+            let mut s = Rng::seeded(99).s;
+            for _ in 0..3 * BATCH + 17 {
+                assert_eq!(rng.next_u64(), scalar_step(&mut s));
+            }
         }

Performance, measured rather than taken from the description. This worker has AVX-512, so on it this branch changes nothing natively: matrix and decrypt land within noise in both orders. I simulated an AVX2-only CPU with TTFX_NO_AVX512=1, so master runs scalar and this branch runs AVX2. There, bench_compare.py at 200x50 with 31 repeats gave matrix 1.015x one way and 0.988x with the order reversed. Across all 37 effects the median was 0.995x: no end-to-end change I could measure. Timing refill alone, AVX2 is about 6% faster than scalar (0.50 vs 0.53 ns per draw), against 0.21 for AVX-512. Without a native 64-bit rotate, AVX2 spends three instructions per rotate, which eats most of the lane parallelism. Zen 5's scalar integer throughput may also be hiding a gain your i7-10850H shows. I had no Intel AVX2-only machine, so your 1.16x on matrix is unconfirmed rather than refuted. Numbers from another AVX2-only CPU (TTFX_NO_AVX512=1 on any AVX-512 box only simulates one) would settle it.

Consider (not a defect in this branch). TTFX_NO_AVX2 turns off AVX-512 too in src/fx/batch.rs tier(), but not in the RNG, so oracle-simd.sh's no-avx2 pass still uses the AVX-512 RNG on AVX-512 hardware. That was already true before this branch.

Second opinion. Both reviewers traced the kernel by hand and found it exact: the state update order, the 23/41 and 45/19 rotate pairs, the jump mask including bit 63, the per-128-bit-lane unpack, and the 0x20/0x31 permutes. That agrees with what the worker showed. They could read this review's working notes, so their agreement is not guaranteed independent. The stale SAFETY comments were Codex's alone.

Next. This waits on you, @ashveikin, to apply the test change above or make your own. It also waits on the maintainer: CI on this branch is waiting for workflow approval and has not run.

@omarchybot omarchybot added the enhancement New feature or request label Oct 24, 2026
@omarchybot

Copy link
Copy Markdown
Collaborator

Closing this because the speedup it is for didn't reproduce. On a Ryzen 9 9955HX worker, with AVX-512 turned off so the AVX2 kernel is the one in use (TTFX_NO_AVX512=1), bench_compare.py at 200x50 over 31 repeats measured matrix at 1.015x one way and 0.988x with the build order reversed, and 0.995x as the median across all 37 effects. The refill itself is about 6% faster per draw (0.50 vs 0.53 ns), which doesn't show up in any animation. The kernel's output is exactly right, so nothing is wrong with the code, but without a measurable gain it isn't worth carrying 80 lines of unsafe SIMD. If you can show the gain on an AVX2-only Intel machine with a run that alternates the two builds, we'd be glad to look again. Measured by Claude Opus 5.5, with the code review checked by Codex Medium and muse-spark-1.3 (high).

@omarchybot omarchybot closed this Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants