From fae8c1bff1bf1c46034972c2c8ca9cca04371ced Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 13:05:05 +0300 Subject: [PATCH] perf(av1): exact integer SAD/SSE and a vectorizable typed forward basis Two byte-exact rewrites on the encoder search's hottest loops, both proved by the enc_probe FNV set on the three gate clips at four q points. `Plane::block_sad`/`block_sse` replace four hand-rolled `f64` accumulations that ran an integer division and remainder per sample to recover (row, col) from a flat index. The sums they replace are whole numbers far below 2^28, so `f64` held every partial sum exactly and neither the order of the adds nor the accumulator type can change the result. `forward_transform_2d_typed`'s two matmuls summed over a strided basis, which no vectorizer can touch. `axis_basis_t` caches the transposed basis so the pass is contiguous in the basis index and strided in nothing; each lane's terms stay in the same order, so the levels are unchanged. The row pass now also records which rows it filled, and the column pass walks only those. 1080p ladder, 12 frames, 4 q points: 111.09e9 -> 101.65e9 instructions:u (-8.5%, ABAB x2). --- crates/ec-av1/src/encode.rs | 107 +++++++++++++++------------------ crates/ec-av1/src/transform.rs | 65 ++++++++++++++++---- 2 files changed, 104 insertions(+), 68 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0a933f81..f7f1f47e 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1210,6 +1210,40 @@ impl Plane<'_> { /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. #[allow(clippy::too_many_arguments)] + /// Sum of absolute differences between the source block at `(x, y)` and a + /// `side x side` prediction, as the whole number it is. + /// + /// Bit-identical to the `f64` accumulation it replaces: every partial sum + /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds + /// exactly, so no add here rounds and the order of the adds cannot change + /// the result. Dropping the per-pixel `i / side` and `i % side` -- an + /// integer division per sample -- is what lets the row walk vectorize. + fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 { + let mut sad = 0u32; + for row in 0..side { + let source = &self.source[(y + row) * self.width + x..][..side]; + for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) { + sad += u32::from(s.abs_diff(p)); + } + } + f64::from(sad) + } + + /// Squared error between the source block at `(x, y)` and a reconstruction + /// of it. Exact for the same reason [`Self::block_sad`] is: the largest + /// total is `255^2 * 64 * 64`, under 2^28. + fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 { + let mut sse = 0u64; + for row in 0..side { + let source = &self.source[(y + row) * self.width + x..][..side]; + for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) { + let d = u32::from(s.abs_diff(r)); + sse += u64::from(d * d); + } + } + sse as f64 + } + fn trial_typed( &self, at: At, @@ -1259,19 +1293,12 @@ impl Plane<'_> { #[cfg(test)] stage_add(2, t.elapsed()); - let mut reconstruction = vec![0u8; side * side]; - let mut sse = 0.0; - for row in 0..side { - for col in 0..side { - let i = row * side + col; - let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; - reconstruction[i] = sample; - let error = f64::from( - i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), - ); - sse += error * error; - } - } + let reconstruction: Vec = prediction + .iter() + .zip(&coded) + .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) + .collect(); + let sse = self.block_sse(x, y, side, &reconstruction); // What the levels cost is priced through the same CDFs the tile writer // will code them with, so the search ranks modes -- and the partition // trial ranks trees -- by the bits they actually spend. @@ -1319,16 +1346,7 @@ impl Plane<'_> { set: TxbSet, ) -> Trial { if skip { - let mut sse = 0.0; - for row in 0..side { - for col in 0..side { - let error = f64::from( - i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[row * side + col]), - ); - sse += error * error; - } - } + let sse = self.block_sse(x, y, side, prediction); return Trial { levels: vec![0i32; side * side], reconstruction: prediction.to_vec(), @@ -1351,19 +1369,12 @@ impl Plane<'_> { let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); #[cfg(test)] stage_add(2, t.elapsed()); - let mut reconstruction = vec![0u8; side * side]; - let mut sse = 0.0; - for row in 0..side { - for col in 0..side { - let i = row * side + col; - let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; - reconstruction[i] = sample; - let error = f64::from( - i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), - ); - sse += error * error; - } - } + let reconstruction: Vec = prediction + .iter() + .zip(&coded) + .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) + .collect(); + let sse = self.block_sse(x, y, side, &reconstruction); #[cfg(test)] let t = std::time::Instant::now(); let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { @@ -1500,16 +1511,7 @@ impl Plane<'_> { false, &mut prediction, fctx, ); - let sad: f64 = (0..side * side) - .map(|i| { - let (row, col) = (i / side, i % side); - f64::from( - (i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[i])) - .abs(), - ) - }) - .sum(); + let sad = self.block_sad(x, y, side, &prediction); (sad + lambda * mode_bits[usize::from(mode)], mode) }) .collect() @@ -1557,17 +1559,8 @@ impl Plane<'_> { false, &mut prediction, fctx, ); - let sad: f64 = if want_sad { - (0..side * side) - .map(|i| { - let (row, col) = (i / side, i % side); - f64::from( - (i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[i])) - .abs(), - ) - }) - .sum() + let sad = if want_sad { + self.block_sad(x, y, side, &prediction) } else { 0.0 }; diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index acd2e304..ade34b19 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1442,6 +1442,34 @@ fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] { cache[k][idx].get_or_init(|| build_axis_basis(n, kind)) } +/// [`axis_basis`] transposed: `[i * n + u]` is basis function `u`'s sample +/// `i`. Both of [`forward_transform_2d_typed`]'s passes sum over the sample +/// index and are independent across the basis index, so this layout makes the +/// basis index the contiguous one and the two matmuls vectorize -- without +/// touching either sum's order, which is what keeps the levels bit-identical +/// to the strided `.map().sum()` this replaced. +fn axis_basis_t(n: usize, kind: TxType1d) -> &'static [f64] { + use std::sync::OnceLock; + static CACHE: OnceLock<[[OnceLock>; 5]; 3]> = OnceLock::new(); + let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new()))); + let k = match kind { + TxType1d::Dct => 0, + TxType1d::Adst => 1, + TxType1d::Identity => 2, + }; + let idx = (n.trailing_zeros() as usize).saturating_sub(2); + cache[k][idx].get_or_init(|| { + let basis = axis_basis(n, kind); + let mut t = vec![0.0f64; n * n]; + for u in 0..n { + for i in 0..n { + t[i * n + u] = basis[u * n + i]; + } + } + t + }) +} + /// [`forward_transform_2d`] for a block whose transform type is not /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode /// gets, since chroma never codes a `tx_type` symbol and the decoder derives @@ -1461,8 +1489,14 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType "a flipped ADST needs its residual mirrored before this basis applies" ); let (row_kind, col_kind) = tx_type.axes(); - let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); + let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind)); let mut rows = vec![0.0f64; side * side]; + // Which rows of `rows` the pass below actually fills; the column pass + // walks only those. A row of `+0.0` contributes `0.0 * b` terms, which + // are `+-0.0`, and adding either to a running sum that is never `-0.0` + // (it starts at `+0.0` and `x + -x` is `+0.0`) leaves it unchanged. + let mut filled: [usize; 64] = [0; 64]; + let mut nfilled = 0usize; // Zero in, zero out, and `rows` is already zero here -- the skip // [`forward_rows`] takes for the same reason, which this path was // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68% @@ -1476,12 +1510,16 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType continue; } any = true; - for v in 0..side { - rows[i * side + v] = source - .iter() - .zip(&hb[v * side..][..side]) - .map(|(&r, &b)| f64::from(r) * b) - .sum(); + filled[nfilled] = i; + nfilled += 1; + let out = &mut rows[i * side..][..side]; + // `k` ascending is the term order the strided `.map().sum()` had, so + // every lane's partial sums are the same values in the same order. + for (k, &r) in source.iter().enumerate() { + let r = f64::from(r); + for (o, &b) in out.iter_mut().zip(&hb[k * side..][..side]) { + *o += r * b; + } } } if !any { @@ -1489,10 +1527,15 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType } let mut out = vec![0.0f64; side * side]; for u in 0..side { - let column = &vb[u * side..][..side]; - for v in 0..side { - let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum(); - out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum; + let acc = &mut out[u * side..][..side]; + for &i in &filled[..nfilled] { + let c = vb[i * side + u]; + for (a, &r) in acc.iter_mut().zip(&rows[i * side..][..side]) { + *a += r * c; + } + } + for a in acc.iter_mut() { + *a *= INVERSE_GAIN_RECIPROCAL; } } out