say hi
RUST · PARALLELISM · 121 TFLOP/s ACROSS TWO MACHINES

Everything the hardware
can actually do.

A Ryzen 9950X, an RTX 5090 and an M2 Max, and a stubborn refusal to leave any of it idle. The Mandelbrot set is the vehicle, not because it's pretty, but because it is load-imbalanced, purely FMA-bound, and eventually impossible, and each of those forces a different part of the machine into view.

// f32 · GPU · YOUR MACHINE
center -0.600000000000, 0
zoom 1.0×
iter 220
frame – ms
precis f32 headroom ok
scroll to zoom at cursor · drag to pan

Keep zooming and the precis line turns orange, then red. That wall arrives at a scale of roughly 1e-6 here, and it is not a bug in the shader. It is the single fact this entire tutorial is organised around. Every GPU in the building hits a version of it, and the way out is not a bigger number type.

note

This runs on your hardware, not a server. The browser compiles the fragment shader for whatever backend it picks (ANGLE → Metal on the Mac, Vulkan on the Linux box). So the frame number is already a real measurement, and opening this page on both machines is a preview of Part 6.

PART 00

Ground truth

a baseline, a FLOP convention, and a way to be wrong out loud

Before any parallelism: a number to beat, and an honest way to say how far from the ceiling we are. Almost every "we made it faster" claim dies here, because "faster than my first attempt" is not the same as "using the machine".

The two machines

Spec-sheet peaks. These are the expected values: Part 0.3 measures them, and disagreement is a finding rather than an error to bury.

unitf64 peakf32 peaknote
9950X · 16C · AVX-512~2.5 TFLOP/s~5 TFLOP/sfull 512-bit datapath
M2 Max · 8 P-cores · NEON~0.47 TFLOP/s~0.94 TFLOP/s128-bit, no SVE
RTX 50901.64 TFLOP/s104.8 TFLOP/sf64 at 1/64 rate
M2 Max GPU · 30 coresnone10.65 TFLOP/sApple GPUs have no fp64
concept

Read the f64 column again. A naive f64 kernel on the 5090 is slower than the 9950X CPU, and it will not compile for the M2 Max at all. Porting to the GPU without changing the numerics is a regression on one machine and impossible on the other.

So reaching the f32 column isn't an optimisation, it's the only way to use the GPUs, and reaching f32 at depth requires perturbation theory. The algorithm is chosen by the hardware, not by taste. That's Part 8.

0.1 — Workspace

Crate boundaries follow the parts, so the tree grows monotonically and nothing gets retconned later. One rule holds throughout: everything builds with every feature flag off, on both machines. Each flag is an upgrade, never a prerequisite.

0.1Cargo.toml
[workspace]
resolver = "3"
members  = ["crates/*", "xtask"]

[workspace.package]
edition = "2024"

[workspace.dependencies]
# stable SIMD; core::simd lives behind `nightly-simd`
wide         = "0.7"
rayon        = "1.11"
core_affinity = "0.8"
multiversion = "0.8"

[profile.release]
opt-level     = 3
lto           = "fat"
codegen-units = 1
# Keep frame pointers: `perf` needs them for usable call graphs, and
# the cost is under 1% on a workload this register-light.
debug         = "line-tables-only"

0.2 — The baseline

Single-threaded, scalar, f64. The only cleverness is rejecting the cardioid and the period-2 bulb analytically: the two largest interior regions are decidable in closed form, so we never burn max_iter on them. Everything else is deliberately plain.

0.2crates/mandel-core/src/scalar.rs
//! Naive escape-time iteration. The number every later part is measured against.

/// Squared bailout radius. Large (not 4.0) so the continuous escape-time
/// estimate in `smooth()` converges — small bailouts leave visible banding.
pub const BAILOUT2: f64 = 65536.0;

pub struct Escape { pub n: u32, pub z2: f64 }

impl Escape {
    pub fn interior(max: u32) -> Self { Escape { n: max, z2: 0.0 } }

    /// Continuous escape time: n + 1 - log2(log2|z|).
    /// Meaningless for interior points - check `n < max_iter` first.
    pub fn smooth(&self) -> f64 {
        let log_z = 0.5 * self.z2.log2();
        self.n as f64 + 1.0 - log_z.log2()
    }
}

#[inline]
pub fn escape(cx: f64, cy: f64, max_iter: u32) -> Escape {
    // Main cardioid.
    let q = (cx - 0.25) * (cx - 0.25) + cy * cy;
    if q * (q + (cx - 0.25)) <= 0.25 * cy * cy {
        return Escape::interior(max_iter);
    }
    // Period-2 bulb.
    if (cx + 1.0) * (cx + 1.0) + cy * cy <= 0.0625 {
        return Escape::interior(max_iter);
    }

    let (mut x, mut y) = (0.0, 0.0);
    let (mut x2, mut y2) = (0.0, 0.0);
    let mut n = 0;

    // y before x: y needs the OLD x. Reusing x2/y2 for both the
    // iteration and the bailout test keeps this at 3 multiplies.
    while n < max_iter && x2 + y2 <= BAILOUT2 {
        y = (x + x) * y + cy;
        x = x2 - y2 + cx;
        x2 = x * x;
        y2 = y * y;
        n += 1;
    }
    Escape { n, z2: x2 + y2 }
}

0.3 — The measurement contract

Fix the FLOP convention once, here, or no number in Part 8 is comparable to one in Part 3. Eight flops per iteration, and the breakdown lives in the source so nobody has to re-derive it at 2am.

0.3crates/mandel-bench/src/roofline.rs
/// Flops per iteration, counted as:
///   x*x, y*y, x*y      -> 3 mul
///   x2 - y2            -> 1 sub
///   2xy  (as xy + xy)  -> 1 add
///   + c.re, + c.im     -> 2 add
///   |z|2 = x2 + y2     -> 1 add   (reuses x2, y2)
/// Never recount this mid-project. If it's wrong, fix it here.
pub const FLOPS_PER_ITER: f64 = 8.0;

pub enum Prec { F32, F64 }

pub struct Roofline { pub peak_f64: f64, pub peak_f32: f64, pub peak_bw: f64 }

pub struct Run {
    /// Iterations ACTUALLY executed - not pixels x max_iter. Early bailout
    /// means those differ by an order of magnitude on a typical view, and
    /// using the wrong one inflates your throughput into fiction.
    pub iters: u64,
    pub pixels: u64,
    pub wall: Duration,
}

impl Run {
    pub fn flops(&self) -> f64 {
        self.iters as f64 * FLOPS_PER_ITER / self.wall.as_secs_f64()
    }
    pub fn miter_per_s(&self) -> f64 {
        self.iters as f64 / self.wall.as_secs_f64() / 1e6
    }
    pub fn pct_of_peak(&self, r: &Roofline, p: Prec) -> f64 {
        let peak = match p { Prec::F32 => r.peak_f32, Prec::F64 => r.peak_f64 };
        100.0 * self.flops() / peak
    }
}
gotcha

iters is iterations executed, not pixels × max_iter. On a typical view most pixels bail out in single digits while the interior runs the full count, so the two differ by roughly an order of magnitude. Using the product inflates your throughput into fiction, and (worse) it hides the load imbalance that Part 1 exists to expose.

0.4 — The verification ritual

Wall-clock alone can't tell you why something is slow. Every part ends with the same two commands, one per machine, and they answer different halves of the question: is the pipeline full, and is the machine even awake.

verify — part 0
cargo run --release -p mandel-bench -- --calibrate cargo run --release -p mandel-bench -- --scalar --max-iter 1000

On the Arch box, with the counters that matter:

perf stat -e cycles,instructions,fp_ret_sse_avx_ops.all \ ./target/release/mandel-bench --scalar

On the Mac, since perf doesn't exist and package power is the honest signal:

sudo powermetrics --samplers cpu_power -i 500 -n 6

Expected: roughly 240–290 Miter/s on one 9950X core and 190–240 Miter/s on one M2 Max P-core, at IPC near 2. That is about 8–10% of a single core's f64 peak.

If IPC comes in near 1, the loop is latency-bound on the dependency chain rather than throughput-bound, which is correct, and is exactly the gap Part 3 attacks. If you see far less than 8%, check that lto and opt-level 3 actually applied; a debug build lands near 1%.

One core, eight percent. The other ninety-two are not lost to bad code — they're lost to a dependency chain that nothing in this file can break.

The scoreboard

Fill this in as you go. Every part appends a row; the last column is the only one that matters.

parttechnique9950XM2 Max% of peak
0scalar f64, 1 thread___ Miter/s___ Miter/s___%
1threads + atomic tiles_________%
2rayon_________%
3SIMD_________%
PART 01

Threads, and the straggler

why the obvious split is the wrong split

The Mandelbrot set looks embarrassingly parallel, and it is: every pixel is independent. That makes it tempting to hand each thread an equal slice of rows and expect linear speedup. It won't happen, and the reason is more interesting than the fix.

1.1 — One tile abstraction, three implementations

TileDesc crosses a thread boundary in this part, a process boundary in Part 5, and a network socket in Part 11. It is #[repr(C)] from the start so that none of those later moves need a second type.

1.1crates/mandel-cpu/src/tile.rs
/// A rectangle of pixels. Crosses threads now, processes in Part 5,
/// and a TCP socket in Part 11 - hence repr(C) from day one.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct TileDesc {
    pub x: u32, pub y: u32,
    pub w: u32, pub h: u32,
    /// Bumped on every view change. Workers drop stale tiles instead of
    /// finishing them - this is the cancellation mechanism in Part 9.
    pub generation: u64,
}

pub trait TileSource: Send + Sync {
    fn next(&self) -> Option<TileDesc>;
    fn current_generation(&self) -> u64;
}

/// Deliberately naive: contiguous horizontal bands, one per worker.
/// This is the version that fails. Keep it - Part 2 needs the comparison.
pub struct StaticSplit { bands: Vec<TileDesc>, taken: AtomicUsize }

impl StaticSplit {
    pub fn new(w: u32, h: u32, workers: u32, generation: u64) -> Self {
        let rows = h.div_ceil(workers);
        let bands = (0..workers)
            .map(|i| TileDesc {
                x: 0, y: i * rows, w,
                h: rows.min(h.saturating_sub(i * rows)),
                generation,
            })
            .filter(|t| t.h > 0)
            .collect();
        Self { bands, taken: AtomicUsize::new(0) }
    }
}

1.2 — Scoped threads, and the failure

std::thread::scope lets workers borrow the frame buffer directly, with no Arc, no 'static bound, no copying. Split the buffer into non-overlapping row bands with chunks_mut and the borrow checker proves the absence of data races for free.

1.2crates/mandel-cpu/src/scoped.rs
pub fn render_static(buf: &mut [u32], view: &View, workers: usize) -> Run {
    let rows_per = (view.h as usize).div_ceil(workers);
    let t0 = Instant::now();
    let iters = AtomicU64::new(0);

    thread::scope(|s| {
        // chunks_mut hands each thread a disjoint &mut slice. No Arc,
        // no 'static bound, and aliasing is a compile error rather
        // than a race we'd have to reason about.
        for (i, band) in buf.chunks_mut(rows_per * view.w as usize).enumerate() {
            let iters = &iters;
            s.spawn(move || {
                let t = Instant::now();
                let local = render_band(band, view, i * rows_per);
                iters.fetch_add(local, Ordering::Relaxed);
                // Per-band wall time is the whole point of this chunk.
                eprintln!("band {i:2}: {:>7.1} ms  {local:>10} iters",
                          t.elapsed().as_secs_f64() * 1e3);
            });
        }
    });

    Run { iters: iters.into_inner(), pixels: (view.w * view.h) as u64,
          wall: t0.elapsed() }
}

Run it on the default view with 16 workers and read the per-band timings rather than the total. The bands covering the top and bottom of the image finish almost immediately; the ones through the middle — where the set actually is — take an order of magnitude longer. The whole render waits for the slowest.

concept

Points outside the set bail out after a handful of iterations. Points inside run the full max_iter. So the cost of a tile is proportional to how much of the set it contains, and the set is not evenly distributed across rows: it's concentrated in a band through the middle.

Equal pixel counts are not equal work. With 16 static bands on a centred view, expect a straggler ratio (slowest band over mean) of roughly 6–10×, which caps your speedup near 2× no matter how many cores you own. Look at the histogram of band times, not the mean; the mean is what makes this bug invisible.

1.3 — Work stealing, by hand

The fix is to stop deciding in advance. Cut the image into many more tiles than there are workers, and let each worker take the next one whenever it's free. One relaxed atomic is the entire scheduler.

1.3crates/mandel-cpu/src/atomic.rs
/// Tiles are handed out on demand. Relaxed ordering is sufficient:
/// fetch_add is atomic regardless, and no other memory is published
/// through this counter - each tile writes a disjoint region.
pub struct AtomicCounter { tiles: Vec<TileDesc>, next: AtomicUsize }

impl AtomicCounter {
    pub fn new(w: u32, h: u32, tile: u32, generation: u64) -> Self {
        let mut tiles = Vec::new();
        for ty in (0..h).step_by(tile as usize) {
            for tx in (0..w).step_by(tile as usize) {
                tiles.push(TileDesc {
                    x: tx, y: ty,
                    w: tile.min(w - tx), h: tile.min(h - ty),
                    generation,
                });
            }
        }
        // Shuffling decorrelates tile index from cost. Without it the
        // expensive tiles are contiguous, so the last worker to start
        // inherits a run of them and becomes the new straggler.
        tiles.shuffle(&mut SmallRng::seed_from_u64(0xC0FFEE));
        Self { tiles, next: AtomicUsize::new(0) }
    }
}

impl TileSource for AtomicCounter {
    #[inline]
    fn next(&self) -> Option<TileDesc> {
        let i = self.next.fetch_add(1, Ordering::Relaxed);
        self.tiles.get(i).copied()
    }
    fn current_generation(&self) -> u64 {
        self.tiles.first().map_or(0, |t| t.generation)
    }
}

Tile size is now the tuning knob, and it's a genuine tradeoff. Too large and the last tile handed out becomes the new straggler. Too small and you pay atomic contention plus worse cache locality on the output buffer. Sweep it rather than guessing: the answer differs between the two machines, and the reason it differs is Part 4.

verify — part 1
cargo run --release -p mandel-bench -- --static --workers 16 cargo run --release -p mandel-bench -- --atomic --workers 16 --tile-sweep 16,32,64,128,256

Expected: static split lands near 2–4× speedup on 16 threads with a straggler ratio above 6. The atomic counter should reach 13–15× on the 9950X and 6–8× on the M2 Max, with the tile sweep peaking somewhere around 32–64 px.

A much lower M2 Max figure is expected and not yet a bug: 12 cores are not 12 equal cores. Leave it; Part 4 collects it.

PART 02

Rayon

work stealing for free, and where its heuristic misreads the problem

Part 1's atomic counter is a centralised queue: every worker hits the same cache line on every tile. Rayon replaces it with per-worker deques and stealing, which scales better and is roughly four lines of code.

2.1crates/mandel-cpu/src/rayon.rs
use rayon::prelude::*;

pub fn render_rayon(buf: &mut [u32], view: &View, tile: u32) -> Run {
    let t0 = Instant::now();
    let w = view.w as usize;

    // Rows, not tiles: par_chunks_mut needs contiguous slices, and a 2D
    // tile isn't contiguous in a row-major buffer. Scattering into tiles
    // means either an indexed write or a transpose - both are covered in
    // 2.2, where the cache cost of this choice shows up.
    let iters: u64 = buf
        .par_chunks_mut(w * tile as usize)
        .enumerate()
        .map(|(i, band)| render_band(band, view, i * tile as usize))
        .sum();

    Run { iters, pixels: (view.w * view.h) as u64, wall: t0.elapsed() }
}

On a well-behaved view this matches or slightly beats the hand-rolled counter, with less code and no tuning. That's the honest headline: for most of this tutorial, rayon is simply the right answer.

2.2 — Where it loses

Rayon splits a parallel iterator recursively until the pieces look small enough, and "small enough" is measured in element count. It has no idea that one of your chunks costs fifty times another.

gotcha

Point the renderer at a view dominated by interior (a deep zoom into a mini-brot, say) and the cost distribution goes bimodal: a few chunks run the full max_iter, the rest bail out instantly. Rayon splits them into equal counts, so a single chunk can still hold enough interior to outlast everything else combined.

The fix isn't to abandon rayon. It's to make chunks small enough that no individual chunk can dominate (with_min_len, or a fixed small tile) and accept the extra scheduling overhead as insurance. Measure both on the pathological view; the crossover is real and it moves with max_iter.

verify — part 2
cargo run --release -p mandel-bench -- --rayon --view default cargo run --release -p mandel-bench -- --rayon --view minibrot --max-iter 50000 \ --min-len 1,8,64,512

Expected: on default, rayon within ±5% of the Part 1 atomic counter. On minibrot, the default split should lose by 1.5–3×, recovered by a small min_len. If minibrot shows no gap, raise --max-iter until it does; the effect scales with how expensive an interior pixel is.

note

Both machines are now near their thread ceiling and nowhere near their arithmetic ceiling: somewhere around 10% of f64 peak. Part 3 explains where the other 90% went, and why the answer on the 9950X is specifically f64x8 and nothing narrower.

PART 03

SIMD, and the lane that won't stop

where the other 90% went

Sixteen threads and still under 10% of peak. The threads were never the problem. A scalar f64 loop issues one multiply per instruction on a core whose FPU is eight wide, and it does so along a dependency chain — each iteration needs the previous one's x. The pipeline is mostly waiting.

SIMD fixes both at once: eight independent pixels per register means eight lanes of work and eight independent chains to interleave. But escape-time iteration has a shape that makes this awkward, and the awkwardness is the lesson.

concept — the masked escape

Scalar code breaks out of the loop the moment a point escapes. A vector cannot: lanes 0–6 may still be iterating when lane 7 leaves. So you keep iterating all lanes until every one has escaped, and use a mask to freeze the iteration counter of the ones that already did.

The cost model follows directly: a vector costs max(lane_iters), not mean(lane_iters). Lane divergence has a throughput price, and it is the same straggler problem from Part 1 relocated from cores into registers. Which means the same fix applies — keep adjacent pixels together, since neighbouring points usually escape at similar times.

3.2 — Stable: the wide crate

3.2crates/mandel-core/src/simd/wide.rs
use wide::{f64x4, CmpLe};

/// Four pixels at once. `active` is the mask of lanes still iterating;
/// once it is all-false every lane has escaped and we can stop early.
pub fn escape_x4(cx: f64x4, cy: f64x4, max_iter: u32) -> (f64x4, f64x4) {
    let bail = f64x4::splat(BAILOUT2);
    let one  = f64x4::splat(1.0);
    let (mut x, mut y) = (f64x4::ZERO, f64x4::ZERO);
    let (mut x2, mut y2) = (f64x4::ZERO, f64x4::ZERO);
    let mut n = f64x4::ZERO;
    let mut z2 = f64x4::ZERO;

    for _ in 0..max_iter {
        let active = (x2 + y2).cmp_le(bail);   // lanewise mask: all-ones or all-zeros
        if !active.any() { break; }         // every lane escaped - stop the whole vector

        // Blend, don't branch. Escaped lanes keep iterating (harmlessly,
        // into overflow) but their n and z2 are frozen at escape time.
        z2 = active.blend(x2 + y2, z2);
        n  = n + (active & one);          // mask AND 1.0 -> 1.0 or 0.0 per lane

        y  = (x + x) * y + cy;
        x  = x2 - y2 + cx;
        x2 = x * x;
        y2 = y * y;
    }
    (n, z2)
}

active & one is the whole trick: a comparison mask in SIMD is all-ones or all-zeros per lane, and all-ones bitwise-ANDed with 1.0 is 1.0. So the counter increments only for still-active lanes without a single branch.

3.3 — Nightly, and why it matters here specifically

wide tops out at 256 bits. On the 9950X that leaves exactly half the FPU idle, and — this is the part that surprises people — there is no partial credit.

gotcha — Zen 5 is use-it-or-lose-it

Zen 5 has a genuine 512-bit datapath, not Zen 4's double-pumped 256-bit one. But the upper half cannot be split to service two 256-bit instructions per cycle. Run f64x4 and half the hardware sits idle with nothing to do about it. The only way to reach it is to issue 512-bit instructions.

The good news: Zen 5 has no AVX-512 frequency offset. Throttling is thermal only, so unlike older Intel parts there is no clock penalty to weigh against the width.

The bad news: f64x8 needs core::simd, which is still nightly. Stable Rust cannot reach this chip's peak today. That is worth saying plainly rather than engineering around.

3.3crates/mandel-core/src/simd/portable.rs
#![cfg(feature = "nightly-simd")]
use core::simd::{f64x8, u64x8, Simd, Mask, cmp::SimdPartialOrd, num::SimdFloat};

#[target_feature(enable = "avx512f")]
/// # Safety
/// Caller must have verified avx512f at runtime. Calling this on a CPU
/// without it is UB, not a panic - the CPU decodes garbage. The safe
/// wrapper in simd/mod.rs is the only intended entry point.
pub unsafe fn escape_x8(cx: f64x8, cy: f64x8, max_iter: u32) -> (f64x8, f64x8) {
    let bail = f64x8::splat(BAILOUT2);
    let (mut x, mut y) = (f64x8::splat(0.0), f64x8::splat(0.0));
    let (mut x2, mut y2) = (f64x8::splat(0.0), f64x8::splat(0.0));
    let mut n = f64x8::splat(0.0);
    let mut z2 = f64x8::splat(0.0);

    for _ in 0..max_iter {
        let active: Mask<i64, 8> = (x2 + y2).simd_le(bail);
        if !active.any() { break; }
        z2 = active.select(x2 + y2, z2);
        n  = active.select(n + f64x8::splat(1.0), n);

        y  = (x + x).mul_add(y, cy);   // explicit FMA: one instruction, one rounding
        x  = (x2 - y2) + cx;
        x2 = x * x;
        y2 = y * y;
    }
    (n, z2)
}
rustism — #[target_feature] is unsafe, and it should be

In C this is a compiler flag and a prayer. In Rust the function is unsafe because calling AVX-512 code on a CPU without AVX-512 is undefined behaviour — the decoder hits an illegal instruction, or worse, doesn't. The unsafe keyword is carrying real information: someone must check this at runtime.

That someone is the dispatcher, which is the only safe entry point and does the check exactly once. The type system enforces the pattern that C leaves to convention.

3.1crates/mandel-core/src/simd/mod.rs
/// Resolve once, not per tile. A OnceLock costs one relaxed load on the
/// hot path after the first call; is_x86_feature_detected! expands to
/// cpuid on every invocation if you let it.
static KERNEL: OnceLock<Kernel> = OnceLock::new();

pub fn kernel() -> Kernel {
    *KERNEL.get_or_init(|| {
        #[cfg(all(target_arch = "x86_64", feature = "nightly-simd"))]
        if is_x86_feature_detected!("avx512f") { return Kernel::Avx512; }
        #[cfg(target_arch = "x86_64")]
        if is_x86_feature_detected!("avx2") { return Kernel::Avx2; }
        #[cfg(target_arch = "aarch64")]
        { return Kernel::Neon; }   // baseline on every arm64 target
        Kernel::Scalar
    })
}

3.4 — NEON: width is not the lever

The M2 Max has no AVX-512 equivalent. NEON is 128 bits — f64x2 — and Apple silicon has never shipped SVE. Doubling the register width is simply not available.

But Apple's P-cores have four FP pipelines, each capable of an FMA. Two lanes across four pipes is eight f64 FMAs in flight, the same arithmetic width as one AVX-512 unit — provided you give the scheduler four independent chains to fill them with. So on ARM the lever is instruction-level parallelism, not vector width: process four separate f64x2 vectors in one unrolled loop body.

3.4crates/mandel-core/src/simd/neon.rs
/// 4 independent f64x2 chains = 8 pixels, sized to the P-core's four FP
/// pipes rather than to the register width. Const-generic so the unroll
/// factor is a compile-time constant and the loop body fully expands.
pub fn escape_neon<const U: usize>(
    cx: [f64x2; U], cy: [f64x2; U], max_iter: u32,
) -> ([f64x2; U], [f64x2; U]) {
    let mut st = core::array::from_fn::<_, U, _>(|_| Lane::zero());
    for _ in 0..max_iter {
        let mut any = false;
        // U independent dependency chains - the scheduler interleaves them
        // across the four pipes. U=1 leaves three idle.
        for k in 0..U { any |= st[k].step(cx[k], cy[k]); }
        if !any { break; }
    }
    (core::array::from_fn(|k| st[k].n), core::array::from_fn(|k| st[k].z2))
}
rustism — const generics as an unroll directive

U is a compile-time constant, so for k in 0..U fully unrolls and [Lane; U] lives entirely in registers with no bounds checks. Sweeping U ∈ {1,2,4,8} is a monomorphisation per value — four specialised functions from one source, chosen at the call site. In C this is a macro or a template; here it is an ordinary generic parameter that the optimiser can reason about.

rustism — &mut is noalias, and it shows up in the assembly

Rust emits LLVM's noalias on &mut parameters, because the borrow checker has already proven no other reference points at that memory. C compilers have to assume two pointers may alias unless you write restrict, which almost nobody does correctly.

Make this concrete: write the tile renderer twice, once taking &mut [f64] and once taking *mut f64, then diff the output of cargo asm. The raw-pointer version reloads across the store; the slice version keeps values in registers. It is one of the few places where a safety feature is also, measurably, a performance feature.

verify — part 3
cargo run --release -p mandel-bench -- --simd auto cargo +nightly run --release --features nightly-simd -p mandel-bench -- --simd sweep cargo asm --release -p mandel-core mandel_core::simd::portable::escape_x8 | grep -c zmm

Expected on the 9950X: AVX2 f64x4 should land near 3.2–3.8× over scalar, and AVX-512 f64x8 near 6–7× — close to double, because the upper half was genuinely idle before. Combined with 16 threads that's roughly 45–60% of f64 peak, which is where this workload should live.

The grep -c zmm is not decoration: if it returns 0 the dispatcher fell through to AVX2 and your 2× is imaginary. Check -C target-cpu and that the nightly feature actually enabled.

Expected on the M2 Max: f64x2 alone gives roughly 1.7–1.9×. The interesting number is the U sweep — expect a knee at U = 4 reaching 3.5–4.5×, then flattening. If U = 1 and U = 4 perform the same, the loop didn't unroll; check opt-level and that U is genuinely const.

PART 04

Topology

twelve cores are not twelve cores

Both machines lie about their core count, in opposite directions. The 9950X reports 32 threads that are not uniformly connected; the M2 Max reports 12 cores that are not equally fast. A scheduler that believes either number leaves performance on the floor.

4.3 — Two CCDs pretending to be one CPU

The 9950X is two 8-core dies with the memory controller on a third. Cores within a die share an L3 slice; across dies they share nothing but Infinity Fabric. A work-stealing steal that crosses that boundary pulls the tile descriptor and, worse, the destination cache lines across the fabric.

4.3crates/mandel-cpu/src/affinity_linux.rs
/// Group logical CPUs by the L3 they share. On a 9950X this yields two
/// groups of 8 physical cores; sysfs already knows the answer, so we
/// read it rather than guessing from core ids.
pub fn l3_groups() -> Vec<Vec<usize>> {
    let mut by_l3: BTreeMap<String, Vec<usize>> = BTreeMap::new();
    for cpu in online_cpus() {
        let p = format!(
            "/sys/devices/system/cpu/cpu{cpu}/cache/index3/shared_cpu_list");
        if let Ok(s) = read_to_string(&p) {
            by_l3.entry(s.trim().to_owned()).or_default().push(cpu);
        }
    }
    by_l3.into_values().collect()
}

/// Pin rayon worker i to a core, filling one CCD completely before
/// touching the next. Steals then stay intra-die for as long as possible.
pub fn pinned_pool(threads: usize) -> ThreadPool {
    let order: Vec<usize> = l3_groups().into_iter().flatten().collect();
    ThreadPoolBuilder::new()
        .num_threads(threads)
        .start_handler(move |i| {
            if let Some(&cpu) = order.get(i) {
                core_affinity::set_for_current(CoreId { id: cpu });
            }
        })
        .build().unwrap()
}

4.4 — P-cores, E-cores, and a scheduler you cannot command

macOS has no sched_setaffinity. You cannot pin a thread to a core, and Apple considers that a feature. What you get instead is Quality of Service: a hint about intent that the scheduler translates into core-class placement. USER_INTERACTIVE work lands on P-cores; BACKGROUND work is effectively confined to E-cores.

gotcha — QoS is not inherited

A thread spawned from a USER_INTERACTIVE thread starts at QOS_CLASS_DEFAULT. Confirmed by Apple DTS, and it means every rayon worker you create is silently mis-classified unless you set it yourself in start_handler. The main thread's QoS tells you nothing about the pool's.

4.4crates/mandel-cpu/src/qos_macos.rs
const QOS_USER_INTERACTIVE: u32 = 0x21;
const QOS_UTILITY: u32 = 0x11;

unsafe extern "C" {
    fn pthread_set_qos_class_self_np(cls: u32, rel_prio: i32) -> i32;
}

pub fn set_qos(class: Qos) {
    // SAFETY: pthread_set_qos_class_self_np only mutates the calling
    // thread's own scheduling class. No shared state, no lifetimes.
    unsafe { pthread_set_qos_class_self_np(class as u32, 0); }
}

pub fn render_pool(threads: usize) -> ThreadPool {
    ThreadPoolBuilder::new()
        .num_threads(threads)
        // Without this every worker is QOS_CLASS_DEFAULT and the
        // scheduler is free to park half of them on E-cores.
        .start_handler(|_| set_qos(Qos::UserInteractive))
        .build().unwrap()
}

Now the experiment worth running. An E-core is roughly 2.5× slower than a P-core, and under a work-stealing scheduler with equal tiles that means every tile an E-core picks up becomes a potential straggler. There are two ways out and they disagree.

  • Exclude them. Spawn 8 threads instead of 12. The constantine project measured exactly this on an M4 Max (12P+4E) and found P-core-count pools beating full-count pools outright.
  • Feed them differently. Keep 12 threads but hand E-cores tiles at roughly 40% the area, so they finish in step with the P-cores instead of trailing.
verify — part 4
cargo run --release -p mandel-bench -- --threads 8,12,16,24,32 --pin ccd,none # Arch cargo run --release -p mandel-bench -- --threads 4,8,10,12 --qos ui,default # Mac cargo run --release -p mandel-bench -- --threads 12 --etile-ratio 1.0,0.6,0.4 # Mac

Arch: CCD pinning should be worth 3–8% — small, but free and consistent. Above 16 threads expect SMT to give little on a workload this FPU-bound; the two logical siblings compete for the same FMA ports.

Mac: the headline test is whether 8 threads beats 12. If it does, the E-cores are net-negative under equal tiling — then check whether --etile-ratio 0.4 recovers them. Getting them back is worth about 10% of total throughput; leaving them out is worth more than leaving them in badly.

PART 05

Processes

a slower design that buys two things

Everything so far shared an address space. Now we split into separate processes communicating over a socket, with the framebuffer in shared memory. On one machine this is slower than threads and there is no way to argue otherwise. It buys fault isolation, and it buys a protocol that runs unchanged over TCP in Part 11.

5.2crates/mandel-ipc/src/proto.rs
/// Wire format. repr(C), little-endian, no serde on the hot path -
/// a TileDesc is 24 bytes and deserves to stay 24 bytes.
#[repr(u16)]
pub enum Tag { Hello = 1, RefBlob = 2, Assign = 3, Done = 4, Cancel = 5 }

#[repr(C)]
pub struct Header { pub tag: u16, pub _pad: u16, pub len: u32 }

/// Broadcast ONCE per view change, then never again for that view.
/// This is the architectural crux: the head node owns the only
/// arbitrary-precision code in the system. Workers receive f32 pairs
/// and never link astro-float or MPFR at all.
#[repr(C)]
pub struct RefBlobHdr { pub id: u64, pub len: u32, pub _pad: u32 }
// ... followed by len * [f32; 2]
concept — why the reference orbit is broadcast, not recomputed

A worker could compute its own reference orbit. It would then need MPFR, several hundred milliseconds of single-threaded warm-up, and it would produce a bit-identical result to every other worker. Broadcasting instead costs O(reference_len) bytes once — a few megabytes at the deepest zooms — against O(pixels) of work saved.

That asymmetry is what makes Part 11 worth building rather than a distributed-systems tax. Workers are pure f32 delta engines with no high-precision dependency in their Cargo.toml.

5.1crates/mandel-ipc/src/shm.rs
/// The framebuffer lives in /dev/shm; workers map it and write disjoint
/// tiles. No copy back through the socket - only "tile N is done".
pub struct SharedFrame { map: MmapMut, w: u32, h: u32 }

impl SharedFrame {
    /// # Safety
    /// Callers must guarantee that no two live tile views overlap. The
    /// broker guarantees this by construction: it never assigns the same
    /// TileDesc twice within a generation. Rust cannot check across a
    /// process boundary - the borrow checker's proof stops at the
    /// address space, and this is where our own discipline takes over.
    pub unsafe fn tile_mut(&self, t: TileDesc) -> &mut [u32] { /* ... */ }
}
rustism — where the borrow checker stops, and what replaces it

Part 1 got data-race freedom for free: chunks_mut handed out disjoint &mut slices and aliasing became a compile error. That guarantee ends at the process boundary. Two processes mapping the same page have no shared compiler to appeal to.

So the invariant moves from the type system into a // SAFETY comment and a broker that never issues a tile twice. That's not a defeat — it's the interesting part. Rust's value here is that the unchecked region is named, small, and greppable, instead of being the whole program.

Verify what you can: run the single-process path under cargo miri test to check the tile-splitting logic for UB, and model the atomic counter's orderings exhaustively with loom. Neither tool has a mainstream C++ equivalent, and both find things review does not.

verify — part 5
cargo run --release -p mandel-ipc --bin broker -- --workers 8 kill -9 $(pgrep -f 'mandel-worker' | head -1) # mid-render; the frame should still finish cargo miri test -p mandel-cpu tile:: cargo test -p mandel-cpu --features loom --test atomic_orderings

Expected: the process pool lands 5–15% behind the thread pool — spawn cost, page faults on first touch of the shared map, and syscall overhead per tile batch. Killing a worker should cost that worker's in-flight tile and nothing else; the broker reassigns and the frame completes.

If the loss is far worse than 15%, you are almost certainly sending one message per tile instead of per batch. Batch until the socket stops showing up in perf.

PART 06

One shader, both GPUs

wgpu, WGSL, and a wall you should walk into

wgpu compiles one WGSL compute shader to Metal on the Mac and Vulkan on the Linux box. That portability is genuinely free here, because the kernel is arithmetic with no vendor-specific intrinsics. It is also the last comfortable moment in this tutorial.

6.2crates/mandel-gpu/shaders/mandel.wgsl
struct View { center: vec2<f32>, scale: f32, max_iter: u32, w: u32, h: u32 };

@group(0) @binding(0) var<uniform> view: View;
@group(0) @binding(1) var<storage, read_write> out: array<u32>;

// 8x8 = 64 invocations. One subgroup on Apple (32) and two on NVIDIA
// (warp = 32); 64 is the smallest size that is a whole number of both.
@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
  if (gid.x >= view.w || gid.y >= view.h) { return; }

  let px = vec2<f32>(f32(gid.x), f32(gid.y)) - 0.5 * vec2<f32>(f32(view.w), f32(view.h));
  let c = view.center + px * view.scale;

  var z = vec2<f32>(0.0);
  var n: u32 = 0u;
  var d: f32 = 0.0;
  // Uniform loop bound: every invocation in the workgroup runs the same
  // trip count and diverged lanes are simply masked off. A `break` here
  // costs the workgroup max(lane_iters) - the Part 3 lesson, in hardware.
  loop {
    if (n >= view.max_iter) { break; }
    z = vec2<f32>(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;
    d = dot(z, z);
    if (d > 65536.0) { break; }
    n = n + 1u;
  }
  out[gid.y * view.w + gid.x] = pack_result(n, d);
}
gotcha — do not port the f64 kernel

Change f32 to f64 in that shader and two things happen. On the 5090 it runs at 1/64 rate — 1.64 TFLOP/s, slower than the 9950X CPU you just spent three parts optimising. On the M2 Max it does not run at all, because Apple GPUs have no fp64 in any generation.

Try it anyway. Walking into this wall yourself is worth more than being told, and it is the entire reason Part 8 exists: the only path to the GPUs' real numbers is f32, and the only path to f32 at depth is perturbation theory.

6.4 — The readback stall

The naive loop is dispatch, map the buffer, read, present. That serialises the GPU behind the CPU every frame and can cost more than the compute did. The fix is to stop moving pixels across the bus at all: write to a storage texture and sample it directly in the render pass. Readback then happens only when you actually want a PNG.

On the M2 Max there is a second, easier win — unified memory means MAP_READ on a storage buffer is not a transfer, just a cache-coherency point. The same code path costs a PCIe round trip on the Linux box and nearly nothing on the Mac, which is worth measuring rather than assuming.

verify — part 6
cargo run --release -p mandel-gpu -- --adapters cargo run --release -p mandel-gpu -- --wg 4x4,8x8,16x16,8x32 --bench cargo run --release -p mandel-gpu -- --readback map,texture

Expected: f32 on the 5090 should reach 40–70% of 104.8 TFLOP/s at high max_iter — the loop is pure FMA with no memory traffic, so this is one of the rare kernels that gets close. The M2 Max should reach a similar fraction of its 10.65 TFLOP/s.

Workgroup size should matter less than expected (occupancy is not the limiter here) and readback should matter far more. If --readback map and --readback texture perform identically on the Arch box, the map isn't actually stalling and your timing is measuring queue submission rather than completion.

PART 07

Native backends

what portability actually costs

Part 6 gave one shader for both machines. This part asks what you gave up, by writing the same kernel twice against the vendor APIs and measuring the gap. Sometimes the answer is "nothing", and that is a result worth having in writing.

7.1 — Metal, via objc2

note

The metal crate (metal-rs) is deprecated. Use objc2-metal, which is generated from Apple's own headers and tracks new framework versions without waiting on a hand-written binding. wgpu is migrating to the same foundation.

7.1crates/mandel-metal/src/lib.rs
use objc2_metal::{MTLCreateSystemDefaultDevice, MTLDevice, MTLComputePipelineState};

pub struct MetalCtx { device: Retained<dyn MTLDevice>, pipe: Retained<dyn MTLComputePipelineState> }

impl MetalCtx {
    pub fn new(src: &str) -> Result<Self, Error> {
        let device = MTLCreateSystemDefaultDevice().ok_or(Error::NoDevice)?;
        let lib = device.newLibraryWithSource_options_error(&ns_string(src), None)?;
        let f = lib.newFunctionWithName(&ns_string("mandel")).ok_or(Error::NoFn)?;
        let pipe = device.newComputePipelineStateWithFunction_error(&f)?;
        // maxTotalThreadsPerThreadgroup is a property of the compiled
        // pipeline, not of the device: register pressure decides it.
        Ok(Self { device, pipe })
    }
}
rustism — Retained<T> is Arc for Objective-C

Metal objects are reference-counted by the Objective-C runtime. objc2's Retained<T> maps that onto Rust's ownership model: Clone is retain, Drop is release. The classic Objective-C leak — forgetting a release on an early return — becomes structurally impossible, because ? unwinds through Drop like any other Rust value.

7.3 — CUDA, two ways

cudarc is the load-bearing path: safe driver-API bindings, you write .cu, compile to PTX, and launch. Boring, stable, works.

cuda-oxide is the interesting one — NVIDIA's own rustc codegen backend, Rust straight through MIR and LLVM to PTX, host and device in one crate. It reaches the Blackwell features worth having on a 5090: clusters, TMA, and the sm_120 intrinsics.

gotcha — cuda-oxide is alpha, and this part is optional

v0.1.0 shipped 2026-05-07, v0.2.0 four weeks later. It needs Linux, CUDA 12.x+, nightly with rust-src and rustc-dev, LLVM 21+ with NVPTX, and libclang. NVIDIA's own README says to expect bugs and API churn.

So it sits behind a feature flag and cargo oxide doctor is the gate. Nothing downstream depends on it. If it breaks, cudarc carries the tutorial and you lose a section, not a project. That is the general rule for alpha dependencies and it is worth applying deliberately rather than discovering.

verify — part 7
cargo run --release -p mandel-metal -- --bench # vs wgpu on the Mac cargo run --release -p mandel-cuda -- --bench # vs wgpu on the 5090 cargo oxide doctor && cargo run --release -p mandel-cuda --features cuda-oxide -- --parity

Expected: native within 0–8% of wgpu on both machines. This kernel has no vendor-specific tricks to exploit, so a large gap means a configuration difference — workgroup size, fast-math flags, or a different max_iter — not a real API advantage.

--parity compares cuda-oxide output against cudarc pixel-for-pixel. Expect exact equality; f32 arithmetic is deterministic and any difference is a codegen bug worth reporting upstream.

PART 08

The precision wall

the part the whole tutorial was walking toward

Zoom past a span of about 1e-15 and f64 stops resolving adjacent pixels: neighbouring points get the same coordinate and the image goes blocky. The hero at the top of this page hits the f32 version of that wall at around 1e-6.

The obvious fix — give every pixel more bits — is a trap. Arbitrary-precision arithmetic is heap-allocated, branchy, and unvectorisable; it does not run on either GPU. At 4K with 10⁶ iterations that is 8.3 × 10¹² bignum operations per frame. Not slow. Never.

Perturbation theory doesn't make high precision faster. It changes which quantity needs it — from eight million pixels down to one.

8.1 — Two axes, not one

Precision has two independent failure modes and it is easy to conflate them.

  • Mantissa runs out when you need more significant digits than the type carries. Doubling the mantissa fixes it.
  • Exponent runs out when the number itself is smaller than the smallest representable value — below roughly 1e-308 for f64. Doubling the mantissa does nothing; the value flushes to zero regardless.
8.1crates/mandel-core/src/tower/floatexp.rs
/// f64 mantissa, i64 exponent. Not more precise than f64 - just
/// unbounded in range. This is what carries deltas past 1e-308.
#[derive(Clone, Copy)]
pub struct FloatExp { m: f64, e: i64 }   // m normalised to [1.0, 2.0)

impl FloatExp {
    #[inline]
    pub fn mul(self, o: Self) -> Self {
        // Exponents add; the mantissa product stays in [1,4) so at most
        // one renormalisation step. No loop, no branch on the hot path.
        Self::norm(self.m * o.m, self.e + o.e)
    }
}

8.2 — The mantissa ladder

Doubling is the right rule, and it applies to the reference orbit only. Rungs 0–2 are Dekker/Knuth compensated arithmetic — unevaluated sums of 1, 2 or 4 f64s — so the doubling is structural, branch-free, and still vectorises.

rungtypemantissacovers span tocost
0f64531e-131×
1double-double1061e-28~10×
2quad-double2121e-60~40×
3+astro-float, next 2ⁿdynamicunbounded100–500×
rustism — make the invariant unrepresentable

The rule "the reference climbs the ladder, the delta never does" is exactly the kind of thing that survives code review and then quietly dies six months later. So don't write it in a comment — write it in the types.

Give Delta<P> and Ref<R: RefFloat> separate types with no conversion from a high rung into a delta. Widening a delta's mantissa then isn't a bug you catch in review, it's a program that doesn't compile. The two-axis invariant becomes a property of the API rather than of everyone's memory.

Rungs 0–2 monomorphise, so fn orbit<R: RefFloat> generates three specialised, fully inlined functions. Only rung 3+ needs dyn, and it runs once per frame rather than once per pixel — the one place where dynamic dispatch is genuinely free.

8.4 — What one orbit actually costs

Measured, not estimated. Complex squaring at fixed precision, which is the only arbitrary-precision code in the entire renderer:

bitsmax spanastro-floatMPFR (in-place)ratioone 10⁶ orbit
2121e-531040 ns460 ns2.3×0.46 s
8481e-2442258 ns1025 ns2.2×1.03 s
10881e-3172956 ns1339 ns2.2×1.34 s
40961e-122220516 ns6771 ns3.0×6.77 s
concept — this is Amdahl's serial fraction

A 60 Hz frame is 16 ms. One orbit at 1088 bits is 1.34 s on the measurement host, call it 0.4–0.5 s on the 9950X. Per-frame rebuild loses by one and a half to two orders of magnitude, and MPFR's 2.2× advantage does nothing against a 30× deficit — so the backend choice, interesting as it is, changes no architectural decision.

Worse: Z_{m+1} = Z_m² + C is strictly sequential. It cannot be split across cores. In an application with 121 TFLOP/s of embarrassingly parallel work available, this is the serial fraction, running on exactly one core, and it alone decides whether deep zoom feels interactive. Part 9 is not UI polish; it is Amdahl mitigation.

8.5 — Rebasing

Naive perturbation glitches when the delta becomes comparable to the reference value — catastrophic cancellation, and the classic symptom is a solid blob of wrong colour. The older literature detects these and re-renders with secondary references. Don't. Zhuoran's 2021 rebasing avoids them entirely, in three lines:

8.5crates/mandel-core/src/perturb/rebase.rs
/// When the perturbed value is smaller than the perturbation itself, the
/// reference has stopped being a useful basepoint. Fold the reference
/// into the delta and restart the reference index at 0.
///
/// Consequence: exactly ONE reference orbit is ever needed, because the
/// Mandelbrot set has exactly one critical point. No glitch detection,
/// no secondary references, no re-render pass.
#[inline(always)]
pub fn maybe_rebase(z: &mut Cx<f32>, m: &mut u32, zref: Cx<f32>) {
    let sum = zref + *z;
    if sum.norm_sqr() < z.norm_sqr() {
        *z = sum;
        *m = 0;
    }
}

8.6 — BLA, and why it belongs in this tutorial

Bivariate linear approximation replaces series approximation: while the delta is small relative to |2Z|, many iterations are accurately summarised by a single linear map z ↦ A z + B c. Composing two of them gives one that skips both.

And that composition is a parallel reduction. Build M single-step approximations in parallel, merge neighbours pairwise up log M levels, every level internally parallel. Parts 1 through 3 built exactly this machinery for pixels; here it runs on a completely different data structure and the skills transfer intact.

8.6crates/mandel-core/src/perturb/bla.rs
#[derive(Clone, Copy)]
pub struct Bla { pub a: Cx<f64>, pub b: Cx<f64>, pub r: f64, pub l: u32 }

/// Compose x then y into a single map skipping x.l + y.l iterations.
/// The radius formula is the delicate part - it is NOT min(r_x, r_y).
#[inline]
fn merge(x: Bla, y: Bla, c_mag: f64) -> Bla {
    Bla {
        a: y.a * x.a,
        b: y.a * x.b + y.b,
        r: 0.0f64.max(x.r.min((y.r - x.b.abs() * c_mag) / x.a.abs())),
        l: x.l + y.l,
    }
}

impl BlaTable {
    pub fn build(r: &Reference, c_mag: f64) -> Self {
        // Level 0: one BLA per reference iteration, radius |2 Z_n|.
        // Start at 1 - iteration 0 has Z = 0, so its radius is 0.
        let mut levels = vec![(1..r.len).into_par_iter()
            .map(|n| Bla::single(r, n)).collect::<Vec<_>>()];

        // Each level halves the count and doubles the skip. log M levels,
        // every one of them a flat parallel map - same shape as Part 2.
        while levels.last().unwrap().len() > 1 {
            let prev = levels.last().unwrap();
            let next = prev.par_chunks(2)
                .map(|p| if p.len() == 2 { merge(p[0], p[1], c_mag) } else { p[0] })
                .collect();
            levels.push(next);
        }
        Self { levels, m: r.len }
    }
}

The per-pixel loop then becomes: take the largest BLA whose radius still contains |z|; if none fits, take one ordinary perturbation step; check rebasing after either. At depth the BLA path handles the overwhelming majority of iterations, which is what makes deep zoom tractable at all.

verify — part 8
cargo run --release -p mandel-bench -- --tower-sweep # rung transitions vs depth cargo run --release -p mandel-bench -- --deep 1e-100 --glitch-count cargo run --release -p mandel-bench -- --deep 1e-100 --bla-stats

Expected: glitch count exactly 0 at every depth once rebasing is in. Not "low" — zero. A nonzero count means the rebasing test is comparing the wrong magnitudes, and it is the single easiest thing to get subtly wrong in this part.

BLA should skip 90–99% of iterations at 1e-100, rising with depth. If skipping is under 50%, check that you start merging at iteration 1 and that c_mag is the largest |c| in the tile, not the pixel's own.

And compare against a known-good renderer at the same coordinates. Fraktaler 3 is the reference implementation of exactly this algorithm; a visual diff catches sign errors that no unit test will.

PART 09

Hiding a second

interactivity as Amdahl mitigation

Part 8 left us with a half-second of unavoidable, unparallelisable work between a scroll event and a correct frame. No amount of GPU helps. The entire job of this part is to make that half-second invisible, and there are only four moves available.

9.4 — Don't rebuild what's still valid

The largest win by a wide margin. A reference orbit is valid for any view that still contains it, so panning and modest zooming reuse it outright. Rebuild only when the reference leaves the frame, or when the required rung changes.

9.4crates/mandel-app/src/refcache.rs
pub enum RefState {
    Valid(Arc<Reference>),
    /// Usable but shorter than max_iter wants: render with what we have
    /// while a background thread extends it in place.
    Extending { have: Arc<Reference>, want: u32 },
    /// Nothing usable. Preview at a lower rung, full quality when it lands.
    Building { preview: Arc<Reference> },
}

impl RefCache {
    pub fn for_view(&mut self, v: &View) -> RefState {
        let rung = select_rung(required_bits(v.pixel_scale(), v.w));

        // Hysteresis: a rung change invalidates the orbit entirely, so
        // don't switch on a marginal crossing. One extra rung is far
        // cheaper than a rebuild every time the user jitters the wheel.
        if rung > self.rung || rung < self.rung.saturating_sub(1) {
            return self.rebuild_async(v, rung);
        }
        if !v.contains(self.orbit.c) { return self.rebuild_async(v, rung); }
        if self.orbit.len < v.max_iter { return self.extend_async(v.max_iter); }
        RefState::Valid(self.orbit.clone())
    }
}

9.3 — Cancellation, not queueing

A scroll wheel emits events far faster than frames render. Queue them and you get a renderer working steadily through a view the user abandoned four seconds ago. The generation counter from Part 1 is already the answer — it has been sitting in TileDesc since the beginning waiting for this.

9.3crates/mandel-app/src/cancel.rs
/// Workers check this between tiles - never inside the pixel loop, where
/// the load would cost more than finishing the tile. A tile is ~1 ms;
/// that is the cancellation granularity and it is fine.
pub struct Generation(Arc<AtomicU64>);

impl Generation {
    pub fn bump(&self) -> u64 { self.0.fetch_add(1, Ordering::Release) + 1 }
    #[inline]
    pub fn is_stale(&self, mine: u64) -> bool {
        self.0.load(Ordering::Acquire) != mine
    }
}

9.2 — Show something in 16 ms

Render at 1/8 resolution first — 64× fewer pixels, so it lands within a frame — then refine to 1/4, 1/2, full while the view is idle. Combined with a cached reference this makes panning feel immediate even when a rebuild is running behind it.

rustism — the borrow checker is why the background thread is safe

The reference orbit is built on one thread and read by every render worker. In C++ this is where you reach for a mutex and hope nobody forgets it. Arc<Reference> makes it structural: the orbit is immutable once published, Arc is Send + Sync because Reference is, and the extending thread builds a new orbit and swaps the Arc rather than mutating the shared one.

There is no lock in the render path, and there is also no way to accidentally introduce one — a &Reference obtained from the Arc simply cannot be mutated. The design that is fastest here is also the one the compiler will accept, which is not a coincidence.

verify — part 9
cargo run --release -p mandel-app -- --trace-frames # then: pan, zoom slowly, zoom hard, and read the trace

Expected: time-to-first-pixel under 16 ms for any interaction, including one that triggers a rebuild. Cache hit rate above 90% during ordinary panning — if it is low, the containment test is too strict, or hysteresis is missing and the rung is oscillating.

Hard-zoom through several rungs and watch for a frozen UI. If the window stops responding, something is blocking on the orbit build: it must be on its own thread with the result delivered by channel, never awaited inline.

PART 10

Colour

making 10⁶ iteration counts legible

Everything so far produced integers. Turning them into an image is where most Mandelbrot renderers quietly go wrong, in three separate ways.

10.1 — Continuous escape time

Integer iteration counts produce hard concentric bands, because adjacent pixels differ by a whole iteration. The fix is to recover the fractional part from how far past the bailout the orbit actually landed:

10.1crates/mandel-core/src/color.rs
/// sn = n + 1 - log2(log2|z|)
///
/// Requires a LARGE bailout. At |z|^2 = 4 the estimate is visibly wrong
/// and the banding survives; 65536 gives roughly three correct decimals.
/// This is the one place where a bigger bailout costs iterations and
/// buys image quality - about 2 extra iterations per pixel.
#[inline]
pub fn smooth(n: u32, z2: f64) -> f64 {
    n as f64 + 1.0 - (0.5 * z2.log2()).log2()
}

10.2 — The palette, done properly

A ramp built by interpolating hex values in sRGB has non-monotonic lightness: it produces bright bands where none exist in the data, and the eye reads those as structure. The tn_turbo ramp orders Tokyo Night by increasing CIE L* and interpolates in Lab, so lightness rises monotonically across the whole range.

note

Do that offline. Export a 1×256 PNG from the Python palette module and sample it as a texture — Lab conversion and Bézier interpolation per fragment is wasted work computing a constant. The smoothstep-between-eleven-stops ramp in this page's hero is a placeholder for exactly that texture.

10.3 — Keeping contrast at depth

A linear map from iteration count to palette position stops working almost immediately. Iteration counts grow roughly exponentially with zoom depth, so at 1e-100 every pixel in view sits within a fraction of a percent of the same value and the image goes flat.

Two fixes, and they are for different jobs:

  • Cyclic mapping — fract(sqrt(sn) · density) with a ping-pong fold so the ramp wraps seamlessly. The sqrt compresses exponential growth so band width stays roughly constant as you zoom. This is what the hero uses, and it is what produces the familiar contour look.
  • Rank-order (histogram) colouring — sort the iteration counts actually present in the frame and map each pixel to its percentile. Guarantees full palette usage at any depth, and reveals structure that cyclic mapping hides. Costs a sort per frame and makes colours view-dependent, so a pan changes the palette. Good for stills, wrong for animation.
verify — part 10
cargo run --release -p mandel-bench -- --palette-check # monotonic L* assertion cargo run --release -p mandel-app -- --color cyclic,rank --deep 1e-60

Expected: the L* check should pass with a strictly increasing sequence across all 256 LUT entries — assert it in a unit test, since a palette edit that breaks monotonicity is invisible until someone views the output in greyscale.

Compare cyclic against rank-order at 1e-60. If cyclic looks flat, raise density; if it looks like noise, lower it. There is no correct value — it is a viewing preference, which is why it belongs on a slider rather than in a constant.

PART 11

Both machines, one pool

and the wire that decides whether it was worth it

Everything is in place. The tile protocol from Part 5 doesn't care whether the far end is a process or a host, the reference orbit is already a broadcast rather than a recomputation, and generations already cancel stale work. Moving to TCP is mostly a change of transport.

What is not already solved is the split. These machines differ by roughly 10× in GPU throughput and 5× in CPU throughput, and the ratio shifts with max_iter. Any fixed split is wrong somewhere.

11.3 — Don't model it, measure it

The temptation is to compute a split from spec sheets: 104.8 divided by 10.65 says the Arch box takes 91% of the tiles. That number is wrong the moment thermals, another process, or a different view enters the picture. Pull-based scheduling gets it right without knowing anything.

11.3crates/mandel-net/src/split.rs
/// Workers ASK for work rather than being assigned it, so the split is
/// whatever each machine's actual throughput turns out to be. No model,
/// no spec sheets, no recalibration when something else starts running.
///
/// Batch size decays toward the end of a frame: guided self-scheduling.
/// Large batches early amortise the round trip; small batches late stop
/// one worker from inheriting a big chunk nobody can help it finish.
/// This is Part 1's straggler problem again, one level up.
pub fn next_batch(&self, worker: WorkerId) -> Vec<TileDesc> {
    let remaining = self.queue.len();
    let workers = self.active.len().max(1);

    let n = (remaining / (2 * workers))
        .clamp(self.min_batch(worker), 256);

    self.queue.take(n)
}

/// Floor per worker: enough tiles that compute dominates the round trip.
/// Derived from a measured EWMA of that worker's ms-per-tile, not from
/// what kind of hardware it claims to be.
fn min_batch(&self, w: WorkerId) -> usize {
    let per_tile_ms = self.stats[&w].ewma_tile_ms.max(0.01);
    let rtt_ms = self.stats[&w].ewma_rtt_ms;
    // Aim for RTT under 10% of the batch's compute time.
    ((10.0 * rtt_ms / per_tile_ms).ceil() as usize).clamp(1, 64)
}
concept — the split falls out for free

Nobody computes 91%. The 5090 asks for work more often because it finishes faster, and the ratio settles wherever the hardware actually is that minute. Thermal throttling, a background compile, a different view with different iteration costs — all handled, because none of them were modelled in the first place.

This is the same insight as Part 1's atomic counter, applied across a network: stop deciding in advance. A pull queue is a work-stealing scheduler whose steal happens to cost a round trip.

11.4 — Where it stops being worth it

Now the honest part, because this is where distributed rendering usually gets oversold. Compute distributes beautifully. Pixels do not.

what movessize1 GbE2.5 GbE10 GbE
reference orbit (10⁶ × f32 pairs)8 MB64 ms26 ms6.4 ms
one 64×64 tile (u32)16 KB0.13 ms0.05 ms0.01 ms
full 4K frame (u32)33 MB264 ms106 ms26 ms
full 4K frame (u16)17 MB132 ms53 ms13 ms
gotcha — on 1 GbE the network caps you at ~4 fps regardless of compute

A 4K u32 frame is 33 MB. Over gigabit that is 264 ms of pure transfer, so the remote half of your 121 TFLOP/s cannot deliver more than about four frames a second no matter how fast it computes. You added a 5090 and got a network bottleneck.

Three fixes, in order of how much they buy:

  • Send u16. Iteration counts above 65535 are rare and can be escaped separately. Halves the traffic for one line of code.
  • Only send what changed. During a pan most tiles are reusable with an offset; send the newly exposed edge, not the whole frame.
  • Don't send pixels at all. For offline rendering the worker writes its own tiles to disk and the head node merges at the end. Latency stops mattering entirely and the wire carries only tile descriptors.

The general rule worth extracting: distributing compute is easy, distributing results is the actual problem. Notice that Part 12's workload is designed so the results are tiny — that is not a coincidence.

verify — part 11
cargo run --release -p mandel-net --bin head -- --listen 0.0.0.0:7777 # Mac cargo run --release -p mandel-net --bin worker -- --head <mac-hostname>.local:7777 # Arch cargo run --release -p mandel-net --bin head -- --bench-split --report

Expected: combined throughput within 10% of the sum of each machine benchmarked alone, for offline rendering. The observed split should land near 85–92% to the Arch box without you having told it anything.

For interactive rendering on 1 GbE, expect the wire to dominate and the speedup to be disappointing — that is the correct result, and measuring it is the point. Re-run with --pixel-format u16 and watch roughly half of it come back.

PART 12 · STRETCH

Nebulabrot

the other half of the roofline

Twelve parts of chasing the compute ceiling, and by Part 8 the Mandelbrot has stopped cooperating: BLA skips 90–99% of iterations, so the GPUs finish before the frame can consume them. High peak utilisation, poor sustained utilisation. Those are not the same thing, and only one of them was the goal.

Every kernel so far has also been register-resident with essentially zero memory traffic. That makes them excellent for measuring FMA throughput and useless for measuring anything else. The machine has a memory hierarchy we have not touched once.

The Mandelbrot asks what a core can compute. The Buddhabrot asks what it can remember.

12.1 — The algorithm, and why it's expensive

The Buddhabrot plots the density of trajectories rather than membership. Sample a point c; iterate; if it escapes within max_iter, replay its orbit and increment a counter at every pixel the orbit passed through. Points that never escape contribute nothing.

So every iteration becomes a scattered read-modify-write into a large buffer, at a location that has nothing to do with the thread's index. The profile inverts completely:

MandelbrotBuddhabrot
bound byFMA throughputatomics + random-access bandwidth
memory traffic~zeroone scattered RMW per iteration
roofline positioncompute roofmemory roof
parallel unitpixelsample
combining resultsdisjoint writeselementwise addition
concept — why this distributes better than Part 11 did

Samples are independent and merging two partial results is elementwise histogram addition. So the machines exchange O(pixels) bytes once, not O(samples) — one 33 MB transfer at the end of an hour-long run instead of 33 MB per frame.

Which means combined throughput should equal the sum of the two machines measured separately, and any shortfall is a real bug rather than protocol overhead you have to excuse. Part 11 could not give you that test. This can.

12.2 — Where the histogram lives

This is the cache-capacity experiment, and it has a sharp, predictable edge.

12.2crates/buddha/src/hist.rs
/// 4K single channel: 3840 * 2160 * 4 B = 33 MB.  Fits the 5090's 96 MB L2.
/// 8K single channel: 7680 * 4320 * 4 B = 132 MB. Does not. Spills to GDDR7
/// and every atomic becomes a memory transaction instead of a cache hit.
///
/// The fix is not "use a smaller image" - it is to tile the histogram in
/// PLANE space and run one pass per tile, rejecting orbits that miss it.
/// Costs redundant iteration, buys back cache residency. Whether that
/// trade wins is exactly what you measure here.
pub struct Histogram { bins: Vec<u32>, w: u32, h: u32, window: Option<Rect> }

The two devices want opposite solutions, which is the interesting part.

  • 9950X, 128 GB. Give every thread its own private 33 MB histogram — 16 threads is 528 MB, which you have in abundance — and merge once at the end. Zero atomics. Each thread scatters into memory nobody else touches, and the contention problem simply stops existing.
  • RTX 5090. 21 760 CUDA cores cannot each have 33 MB. Atomics are unavoidable, so the goal is keeping them in L2 rather than eliminating them — which is exactly what the 96 MB figure above is about.
  • M2 Max. Unified memory means the GPU histogram is CPU-visible with no copy, so CPU and GPU contributions merge in place. The Arch box pays a PCIe hop for the same operation.

12.3 — Vectorise the search, not the scatter

The iteration vectorises to f64x8 exactly as in Part 3. The scatter does not — there is no efficient vector scatter for a read-modify-write to eight unrelated addresses. The general answer to this shape of problem is to split the phases.

12.3crates/buddha/src/scatter_cpu.rs
/// Phase 1 (vector): iterate 8 candidates at a time, keep only the ones
/// that escape. Pure Part 3 code - the masked escape, unchanged.
/// Phase 2 (scalar): replay each survivor's orbit and scatter.
///
/// Replaying costs a second iteration pass. The alternative - buffering
/// every orbit during phase 1 - needs max_iter * 8 * 16 B of storage,
/// which at max_iter = 1e6 is 128 MB per vector and evicts the histogram
/// we are trying to keep hot. Recompute beats remember here.
pub fn sample_batch(hist: &mut [u32], cs: &[Cx<f64>; 8], max_iter: u32) {
    let (n, _) = escape_x8(splat_re(cs), splat_im(cs), max_iter);

    for lane in 0..8 {
        let iters = n[lane] as u32;
        if iters >= max_iter { continue; }        // interior: contributes nothing
        if iters < MIN_CONTRIB { continue; }        // escaped instantly: no structure

        let mut z = Cx::ZERO;
        for _ in 0..iters {
            z = z * z + cs[lane];
            if let Some(i) = plane_to_bin(z) {
                hist[i] += 1;                        // private buffer - no atomic
                // The set is symmetric about the real axis, so the
                // conjugate orbit is free. Exactly 2x for one add.
                hist[mirror(i)] += 1;
            }
        }
    }
}

12.4 — The hard part: almost every sample is wasted

At max_iter = 10⁶, uniform sampling is close to useless. Most points either escape within a handful of iterations (contributing a short, structureless streak) or never escape at all (contributing nothing). The orbits that draw the nebula — long-lived, hugging the boundary — are vanishingly rare.

The fix is Metropolis-Hastings importance sampling, structurally the same idea as Metropolis Light Transport in rendering: once you find a sample that contributes, look near it.

12.4crates/buddha/src/metropolis.rs
/// One independent Markov chain per thread. Chains never interact, so
/// this scales across every core on both machines with no coordination.
pub fn chain(hist: &mut [u32], rng: &mut SmallRng, cfg: &Cfg) {
    let mut cur = warm_up(rng, cfg);          // reject until something contributes
    let mut cur_score = score(cur, cfg);

    for step in 0..cfg.steps {
        // Two mutation sizes. The small one explores the local basin;
        // the large one escapes it. Without the large jump the chain
        // gets stuck in one filament and the image develops hot spots
        // that never average out.
        let cand = if rng.gen_bool(cfg.large_step_prob) {
            uniform_sample(rng, cfg)
        } else {
            mutate(cur, rng, cfg.r_min, cfg.r_max)
        };

        let cand_score = score(cand, cfg);
        let accept = (cand_score / cur_score.max(f64::MIN_POSITIVE)).min(1.0);

        // Deposit BOTH states weighted by 1/accept-probability. This is
        // the bias correction - depositing only accepted samples
        // oversamples high-contribution regions and the result is a
        // picture of the sampler rather than of the set.
        deposit(hist, cur,  (1.0 - accept) / cur_score, cfg);
        deposit(hist, cand, accept / cand_score, cfg);

        if rng.gen_bool(accept) { cur = cand; cur_score = cand_score; }
    }
}
gotcha — the weighting is not optional

Depositing only accepted samples is the obvious implementation and it is wrong. The chain spends its time where contributions are large, so those regions get sampled more and counted more — the bias compounds. You get a striking image that is not the Buddhabrot.

Both states get deposited, each weighted by the inverse of its own score. If your Metropolis output does not converge to the uniform-sampled result given enough samples, this is where to look first.

12.6 — Three exposures, one image

The classic Nebulabrot runs three histograms with different max_iter cutoffs and maps them to R, G and B. Short cutoffs capture the dense outer haze; long ones capture the sparse filaments. Rather than the standard primaries, map them to Tokyo Night and composite additively over #1a1b26:

bandmax_itercaptureshue
short500dense outer structure#7aa2f7 blue
mid5 000mid filaments#73daca teal
long50 000sparse deep threads#ff9e64 orange

Each band needs its own exposure curve before compositing — the long band has orders of magnitude fewer counts, and a linear map renders it invisible. A per-band percentile normalisation, the rank-order idea from Part 10, is the right tool.

12.7 — Did it actually work

Noise falls as 1/√N, so quality against wall-clock is predictable. That makes the convergence curve a diagnostic rather than a progress bar: plot it, and any deviation from the expected slope is a bug with a location.

verify — part 12
cargo run --release -p buddha -- --sampler uniform,metropolis --report-rate cargo run --release -p buddha -- --res 4k,8k --hist-residency cargo run --release -p buddha -- --distributed --head <mac-hostname>.local:7777 --hours 1 --snr-curve

The five criteria. This is the stretch goal, so it passes or it doesn't:

  1. ≥70% of theoretical f32 peak sustained on each GPU during the compute phase — Nsight Compute on the 5090, Metal System Trace on the Mac.
  2. Combined within 10% of the sum of the machines measured independently.
  3. Metropolis ≥20× the contribution rate of uniform at max_iter = 10⁶.
  4. All four compute units above 90% simultaneously, sustained for 60 minutes.
  5. SNR ∝ √N on the convergence plot, and Metropolis converging to the same image as uniform.

Expect the 4K→8K transition to show a sharp throughput drop on the 5090 as the histogram leaves L2. That cliff is the most satisfying measurement in the whole tutorial, because you predicted it from a datasheet number before running anything.

note — if that turns out to be too easy

Deep-zoom Buddhabrot. Rendering it inside a zoomed region is an inverse problem: you must find orbits that pass through the region, which uniform sampling will essentially never do and naive Metropolis handles badly. There is no clean published solution, and the Part 8 perturbation machinery does not transfer — the reference orbit is a statement about one point, not about which points visit a neighbourhood.

Genuinely open. If you find something that works, it is worth writing up.

Where that leaves the scoreboard

Part 0 measured one core at roughly 8% of its own f64 peak. Twelve parts later the target is four compute units across two machines, held above 90% for an hour, on a workload chosen specifically because it stresses everything the first eleven parts left alone.

The number that matters was never the speedup. It was always the fraction of the ceiling — because that one you cannot fool yourself about.

End of tutorial. Corrections and better numbers welcome — especially yours, measured on your own hardware.