From ca9f172758ed2430eab084eda5dcc8ccd05dddc7 Mon Sep 17 00:00:00 2001 From: supersurviveur Date: Wed, 30 Sep 2026 22:10:28 +0200 Subject: [PATCH] perf: improve performance --- CLAUDE.md | 23 ++++-- src/fractal/bla.rs | 160 +++++++++++++++++++++++++++++++----- src/shaders/mandelbrot.wgsl | 77 +++++++++++++++-- 3 files changed, 228 insertions(+), 32 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b2f5983..ee38167 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -254,11 +254,16 @@ pixel is a handful of `f32` complex multiplies. `DEEP_PIXEL_SIZE`, raise `DEEP_EXIT_LOG2` to about -8) must reproduce the plain f32 renders on non-chaotic views. That's the check to rerun after changing it. At minibrot depths (seahorse 1e-200) this prologue is most - of the render: about 130 loop turns per pixel, one per BLA jump or plain - step around each near-zero reference point. It's ALU-bound, so - `ldexp_sat` adds to the exponent bits for normal inputs (−25% time). - Measured no help: reading `frexp`'s exponent from the bits, a branchless - `ldexp_sat`, uploading BLA levels 1–2. Known gaps: Lambda's critical point is 1/2, so its step keeps + of the render. The reference passes near 0 once per period, which the + aligned BLA levels cut into ~10 jumps plus up to 8 plain steps; BLA + segments (below) make that one jump and a plain step. It's ALU-bound, + so `ldexp_sat` adds to the exponent bits for normal inputs. Measured no + help: reading `frexp`'s exponent from the bits, a branchless + `ldexp_sat`, uploading BLA levels 1–2. Shallower deep frames (seahorse + 1e-100) are instead ~500 genuinely nonlinear f32 steps per pixel (the + valley's slow spiral), where only per-step instructions matter: that + loop tests the level alignment before `log2_mag` and the lookup, and + doesn't track segments (tracking them there cost 11%). Known gaps: Lambda's critical point is 1/2, so its step keeps the input scale. Lambda set mode's reference sits at the origin, so it never reaches deep zooms anyway. - `src/fractal/bla.rs` — **bivariate linear approximation**: a table of @@ -278,7 +283,13 @@ pixel is a handful of `f32` complex multiplies. thousands of steps before diverging (Mandelbrot 1e-200: 12.7 s → 0.7 s at 960×540). Level `l` node `i` covers steps `1 + i·2^l ..`, and only levels ≥ 3 are uploaded (built across cores, `par_map`; bindings 4/5, 48 B nodes, `bla_meta` = - `[min_level, levels, offsets…]`). Coefficients are floatexp (f32 + `[min_level, levels, offsets…, seg_count, seg_starts…]`). **Segments** + add one node per run between "bad" steps (own radius < 2^-40, i.e. + `|X| < 2^-12` for Mandelbrot: near-zero passes, fold lines), from step 1 + and from just after each bad step, where pixels land after stepping over + one or rebasing. Only the deep prologue uses them (`bla_jump`, with a + per-pixel cursor `seg_i`/`seg_at` reset on rebase), falling back to the + levels. Coefficients are floatexp (f32 mantissas + i32 exponent), so a jump in the deep prologue lands straight at its output scale. `R` depends on the view's largest `|dc|` (`dc_max_log2`), so `FractalApp::bla_table` rebuilds on reference or kind diff --git a/src/fractal/bla.rs b/src/fractal/bla.rs index 6820888..836220a 100644 --- a/src/fractal/bla.rs +++ b/src/fractal/bla.rs @@ -48,12 +48,25 @@ const EPSILON_LOG2: i32 = -28; /// table at 12 bytes per orbit point. const MIN_LEVEL: u32 = 3; +/// A step whose own radius is below `2^SEG_BAD_LOG2` (`|X| < 2^-12` for +/// Mandelbrot: a near-zero pass of the reference, or a fold line for the abs +/// kinds) ends a segment (see [`build`]). +const SEG_BAD_LOG2: f64 = EPSILON_LOG2 as f64 - 12.0; + +/// Shortest segment worth a node (the levels cover shorter runs in a +/// lookup or two). Also bounds the segment count to `steps / SEG_MIN_STEPS`. +const SEG_MIN_STEPS: usize = 64; + +/// Steps folded per parallel task when building segments. +const SEG_CHUNK: usize = 1024; + /// Upload budget (bytes): the WebGPU default storage binding size limit. const MAX_TABLE_BYTES: usize = 128 << 20; /// One table node, as the shader's `Bla` struct: `M = m·2^m_exp`, /// `N = n·2^n_exp` (row-major 2×2: `[m00, m01, m10, m11]`), valid while -/// `log2|e| < r_log2`. +/// `log2|e| < r_log2`. `steps` is the run length of a segment node (0 in +/// the levels, where it follows from the level). #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] pub struct GpuBla { @@ -62,7 +75,7 @@ pub struct GpuBla { pub m_exp: i32, pub n_exp: i32, pub r_log2: f32, - pub _pad: u32, + pub steps: u32, } /// `r_log2` of a node that's never valid (f32 `-inf` is fine in WGSL, but a @@ -71,9 +84,11 @@ const NEVER: f32 = -3.0e38; /// A BLA table ready for upload. /// -/// `meta` is `[min_level, level_count, off_0, …, off_{level_count}]`: level -/// `min_level + k` occupies `nodes[off_k..off_{k+1}]`, and its node `i` -/// covers reference steps `1 + i·2^l .. 1 + (i+1)·2^l`. +/// `meta` is `[min_level, level_count, off_0, …, off_{level_count}, +/// seg_count, seg_start_0, …]`: level `min_level + k` occupies +/// `nodes[off_k..off_{k+1}]`, and its node `i` covers reference steps +/// `1 + i·2^l .. 1 + (i+1)·2^l`. Segment `i` is `nodes[off_{level_count} + i]` +/// and covers `steps` steps from `seg_start_i` (ascending); see [`build`]. #[derive(Clone, Debug, PartialEq)] pub struct BlaTable { pub nodes: Vec, @@ -85,7 +100,7 @@ impl BlaTable { pub fn empty() -> Self { Self { nodes: vec![GpuBla::default()], - meta: vec![MIN_LEVEL, 0, 0], + meta: vec![MIN_LEVEL, 0, 0, 0], } } @@ -532,7 +547,7 @@ impl Node { } else { NEVER }, - _pad: 0, + steps: 0, } } } @@ -567,7 +582,8 @@ pub fn build( }; let mut min_level = MIN_LEVEL; // Level l has steps >> l nodes, so levels >= min hold < 2·(steps >> min). - while (steps >> min_level) * 2 * size_of::() > MAX_TABLE_BYTES { + while ((steps >> min_level) * 2 + steps / SEG_MIN_STEPS) * size_of::() > MAX_TABLE_BYTES + { min_level += 1; } if steps >> min_level == 0 { @@ -583,34 +599,117 @@ pub fn build( Fx::new(re as f64, im as f64, orbit.exps[m]) }; - // First stored level, folded straight from single steps. + // First stored level, folded straight from single steps. The same pass + // notes the "bad" steps (tiny radius) that end segments (below). let run = 1usize << min_level; - let mut level: Vec = par_map(steps >> min_level, |i| { + let is_bad = |nd: &Node| nd.r.log2() < SEG_BAD_LOG2; + let first: Vec<(Node, Vec)> = par_map(steps >> min_level, 4096, |i| { let start = 1 + i * run; - (1..run).fold(Node::step(map, point(start)), |acc, k| { - acc.then(Node::step(map, point(start + k)), dc_max) - }) + let mut bad = Vec::new(); + let mut acc = Node::step(map, point(start)); + if is_bad(&acc) { + bad.push(start); + } + for m in start + 1..start + run { + let nd = Node::step(map, point(m)); + if is_bad(&nd) { + bad.push(m); + } + acc = acc.then(nd, dc_max); + } + (acc, bad) }); + let base: Vec = first.iter().map(|f| f.0).collect(); + let tail = 1 + base.len() * run..steps + 1; // past the last whole run + let bad: Vec = first + .into_iter() + .flat_map(|f| f.1) + .chain(tail.filter(|&m| is_bad(&Node::step(map, point(m))))) + .collect(); let mut nodes = Vec::new(); let mut meta = vec![min_level, 0]; + let mut level = base.clone(); while !level.is_empty() { meta.push(nodes.len() as u32); nodes.extend(level.iter().map(|n| n.gpu())); - level = par_map(level.len() / 2, |i| { + level = par_map(level.len() / 2, 4096, |i| { level[2 * i].then(level[2 * i + 1], dc_max) }); } meta[1] = (meta.len() - 2) as u32; meta.push(nodes.len() as u32); + + // Segments: one node per run between bad steps, from step 1 and from + // just after each bad step, where a pixel lands after stepping over it + // or rebasing. Deep minibrot views pass near 0 once per period, so the + // aligned levels cut every period into ~10 jumps plus up to 2^min_level + // single steps; a segment crosses it in one. + let mut segs = Vec::new(); + let mut start = 1; + for b in bad.into_iter().chain([steps + 1]) { + if b >= start + SEG_MIN_STEPS { + segs.push((start, b)); + } + start = b + 1; + } + // Folded in parallel pieces cut at multiples of `chunk` (aligned to the + // first level), each from first-level nodes plus single steps at its + // ragged ends, then merged in order. + let chunk = SEG_CHUNK.max(run); + let pieces: Vec<(usize, usize)> = segs + .iter() + .flat_map(|&(a, b)| { + let cuts = (a - 1) / chunk + 1..(b - 2) / chunk + 1; + std::iter::once(a) + .chain(cuts.map(move |k| 1 + k * chunk)) + .chain([b]) + .collect::>() + .windows(2) + .map(|w| (w[0], w[1])) + .collect::>() + }) + .collect(); + let folded = par_map(pieces.len(), 4, |i| { + let (a, b) = pieces[i]; + let mut acc: Option = None; + let mut m = a; + while m < b { + let aligned = (m - 1) % run == 0 && m + run <= b && (m - 1) / run < base.len(); + let (nd, k) = if aligned { + (base[(m - 1) / run], run) + } else { + (Node::step(map, point(m)), 1) + }; + acc = Some(acc.map_or(nd, |x| x.then(nd, dc_max))); + m += k; + } + acc.unwrap() + }); + let mut k = 0; + for &(a, b) in &segs { + let mut seg = folded[k]; + k += 1; + while k < pieces.len() && pieces[k].0 < b && pieces[k].0 > a { + seg = seg.then(folded[k], dc_max); + k += 1; + } + nodes.push(GpuBla { + steps: (b - a) as u32, + ..seg.gpu() + }); + } + meta.push(segs.len() as u32); + meta.extend(segs.iter().map(|&(a, _)| a as u32)); BlaTable { nodes, meta } } -/// `(0..n).map(f).collect()`, split across cores when `n` is large enough to -/// pay for the threads (a 900k-step table took ~60 ms on one core). -fn par_map(n: usize, f: impl Fn(usize) -> T + Sync) -> Vec { +/// `(0..n).map(f).collect()`, split across cores when there are at least +/// `min` items, enough work to pay for the threads (a 900k-step table took +/// ~60 ms on one core). +fn par_map(n: usize, min: usize, f: impl Fn(usize) -> T + Sync) -> Vec { #[cfg(not(target_arch = "wasm32"))] - if n >= 4096 { + if n >= min { let threads = std::thread::available_parallelism().map_or(1, |t| t.get()); let chunk = n.div_ceil(threads); let f = &f; @@ -792,13 +891,23 @@ mod tests { } } - /// Replay the shader's lookup: the longest valid aligned node at `m`, - /// of at most `budget` steps. + /// Replay the shader's lookup: the segment starting at `m` if it's + /// valid, else the longest valid aligned node at `m`, of at most + /// `budget` steps. fn lookup(t: &BlaTable, m: usize, e_log2: f64, budget: usize) -> Option<(usize, usize)> { let (lmin, levels) = (t.meta[0], t.meta[1]); if m == 0 || levels == 0 { return None; } + let sc = 3 + levels as usize; // seg_count + let starts = &t.meta[sc + 1..sc + 1 + t.meta[sc] as usize]; + if let Ok(i) = starts.binary_search(&(m as u32)) { + let idx = t.meta[sc - 1] as usize + i; + let nd = &t.nodes[idx]; + if e_log2 < nd.r_log2 as f64 && nd.steps as usize <= budget { + return Some((idx, nd.steps as usize)); + } + } let j = m - 1; let tz = if j == 0 { 32 } else { j.trailing_zeros() }; if tz < lmin { @@ -1097,7 +1206,16 @@ mod tests { let count = t.meta[3 + k] - t.meta[2 + k]; assert_eq!(count as usize, steps >> (MIN_LEVEL as usize + k)); } - assert_eq!(*t.meta.last().unwrap() as usize, t.nodes.len()); + let (levels, sc) = (t.levels() as usize, 3 + t.levels() as usize); + let seg_count = t.meta[sc] as usize; + assert_eq!(t.meta.len(), sc + 1 + seg_count); + assert_eq!(t.meta[2 + levels] as usize + seg_count, t.nodes.len()); + // No bad step in the cardioid: one segment over every step. + assert_eq!(seg_count, 1); + assert_eq!( + (t.meta[sc + 1], t.nodes.last().unwrap().steps), + (1, steps as u32) + ); let tiny = mandel_orbit(-3.0, 0.0, 1000); // escapes at once assert_eq!(build(&tiny, tiny.len(), -30, 1e6, &m).levels(), 0); } diff --git a/src/shaders/mandelbrot.wgsl b/src/shaders/mandelbrot.wgsl index 1565a29..fb40d91 100644 --- a/src/shaders/mandelbrot.wgsl +++ b/src/shaders/mandelbrot.wgsl @@ -35,15 +35,17 @@ // e' = M·e + N·dc, valid while log2|e| < r_log2. M = m·2^m_exp and // N = n·2^n_exp are real 2x2 matrices, row-major (the Jacobian of the map, // so the abs/conjugate kinds are covered too). `bla_meta` is -// [min_level, level_count, off_0, ..., off_{level_count}]; only `BLA` -// pipelines read either. +// [min_level, level_count, off_0, ..., off_{level_count}, seg_count, +// seg_start_0, ...]: segment i is node off_{level_count} + i and covers its +// `steps` steps from seg_start_i (see `bla_seg_find`). Only `BLA` pipelines +// read either. struct Bla { m: vec4, n: vec4, m_exp: i32, n_exp: i32, r_log2: f32, - _pad: u32, + steps: u32, }; @group(0) @binding(4) var bla_nodes: array; @group(0) @binding(5) var bla_meta: array; @@ -668,6 +670,51 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2 { return best; } +// Segment jumps (`bla::build`): one node per run of the reference between +// two steps where it passes near 0 (or a fold line), starting right after +// one. Each pixel tracks the first segment starting at or after its `m` +// (`seg_i`, starting at `seg_at`); m only grows between rebases, so that +// only moves forward. +fn bla_seg_count() -> u32 { + return bla_meta[bla_meta[1] + 3u]; +} + +fn bla_seg_start(i: u32) -> u32 { + if i >= bla_seg_count() { + return 0xffffffffu; + } + return bla_meta[bla_meta[1] + 4u + i]; +} + +// First segment from `lo` on that starts at or after `m` (binary search: a +// long level jump can pass many segments). +fn bla_seg_find(lo: u32, m: u32) -> u32 { + var a = lo; + var b = bla_seg_count(); + while a < b { + let mid = (a + b) / 2u; + if bla_meta[bla_meta[1] + 4u + mid] < m { + a = mid + 1u; + } else { + b = mid; + } + } + return a; +} + +// The segment jump at `m` if segment `seg_i` starts there and is valid, +// else `bla_lookup`'s: (node index, steps), steps = 0 when there's none. +fn bla_jump(m: u32, seg_i: u32, seg_at: u32, e_log2: f32, budget: u32) -> vec2 { + if seg_at == m { + let idx = bla_meta[bla_meta[1] + 2u] + seg_i; + let steps = bla_nodes[idx].steps; + if e_log2 < bla_nodes[idx].r_log2 && steps <= budget { + return vec2(idx, steps); + } + } + return bla_lookup(m, e_log2, budget); +} + // Weight of the Phoenix kind's p*z_{n-1} term in the current map: 1 for plain // Phoenix, its morph share while switching to/from Phoenix, else 0. fn phoenix_weight() -> f32 { @@ -867,6 +914,14 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { var w_old = w; var rebase_exit = false; var cut_exit = false; + // Next BLA segment (see `bla_jump`; the f32 loop below only uses + // the levels: its steps are too cheap to pay for tracking this). + var seg_first = 0xffffffffu; + if BLA { + seg_first = bla_seg_start(0u); + } + var seg_i = 0u; + var seg_at = seg_first; loop { // Full value y = X + e as f32 (e flushes to 0 when negligible). let yt = xt + ldexp2_sat(w, sx); @@ -887,7 +942,11 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { var jumped = false; if BLA { let e_log2 = f32(sx) + log2_mag(w); - let hit = bla_lookup(m, e_log2, min(max_iter - n, ref_len - 1u - m)); + if seg_at < m { + seg_i = bla_seg_find(seg_i + 1u, m); + seg_at = bla_seg_start(seg_i); + } + let hit = bla_jump(m, seg_i, seg_at, e_log2, min(max_iter - n, ref_len - 1u - m)); if hit.y != 0u { let nd = bla_nodes[hit.x]; if DE { @@ -1037,6 +1096,8 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { xf = z0f; xt = z0; m = 0u; + seg_i = 0u; + seg_at = seg_first; } } @@ -1112,6 +1173,12 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { } } + // Level nodes start at 1 + i·2^min_level, so only those steps can jump + // (tested before `log2_mag` and the lookup: most steps here are plain). + var bla_align = 0xffffffffu; + if BLA && bla_meta[1] != 0u { + bla_align = (1u << bla_meta[0]) - 1u; + } loop { // (`escaped` may already be set by the deep phase.) if escaped || z2 > bailout_sq { @@ -1139,7 +1206,7 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { let e_old = e; let z_old = z; var jumped = false; - if BLA && m != 0u { + if BLA && m != 0u && ((m - 1u) & bla_align) == 0u { let hit = bla_lookup(m, log2_mag(e), min(max_iter - n, ref_len - 1u - m)); if hit.y != 0u { let nd = bla_nodes[hit.x];