forge
Explore
Log in

Don't you dare go Hollow

Exact integer SAD/SSE and a vectorizable typed forward basis

Browse files at this commit

fae8c1bff1bf1c46034972c2c8ca9cca04371cedAhmet Kaan GümüşParent: 691f69e
  • perf
    • exact integer SAD/SSE and a vectorizable typed forward basis
Show full message
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.rsmodified+50 -57
@@ -1210,6 +1210,40 @@ impl Plane<'_> {
12101210 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
12111211 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
12121212 #[allow(clippy::too_many_arguments)]
1213+ /// Sum of absolute differences between the source block at `(x, y)` and a
1214+ /// `side x side` prediction, as the whole number it is.
1215+ ///
1216+ /// Bit-identical to the `f64` accumulation it replaces: every partial sum
1217+ /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
1218+ /// exactly, so no add here rounds and the order of the adds cannot change
1219+ /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
1220+ /// integer division per sample -- is what lets the row walk vectorize.
1221+ fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
1222+ let mut sad = 0u32;
1223+ for row in 0..side {
1224+ let source = &self.source[(y + row) * self.width + x..][..side];
1225+ for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
1226+ sad += u32::from(s.abs_diff(p));
1227+ }
1228+ }
1229+ f64::from(sad)
1230+ }
1231+
1232+ /// Squared error between the source block at `(x, y)` and a reconstruction
1233+ /// of it. Exact for the same reason [`Self::block_sad`] is: the largest
1234+ /// total is `255^2 * 64 * 64`, under 2^28.
1235+ fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
1236+ let mut sse = 0u64;
1237+ for row in 0..side {
1238+ let source = &self.source[(y + row) * self.width + x..][..side];
1239+ for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) {
1240+ let d = u32::from(s.abs_diff(r));
1241+ sse += u64::from(d * d);
1242+ }
1243+ }
1244+ sse as f64
1245+ }
1246+
12131247 fn trial_typed(
12141248 &self,
12151249 at: At,
@@ -1259,19 +1293,12 @@ impl Plane<'_> {
12591293 #[cfg(test)]
12601294 stage_add(2, t.elapsed());
12611295
1262- let mut reconstruction = vec![0u8; side * side];
1263- let mut sse = 0.0;
1264- for row in 0..side {
1265- for col in 0..side {
1266- let i = row * side + col;
1267- let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1268- reconstruction[i] = sample;
1269- let error = f64::from(
1270- i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1271- );
1272- sse += error * error;
1273- }
1274- }
1296+ let reconstruction: Vec<u8> = prediction
1297+ .iter()
1298+ .zip(&coded)
1299+ .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1300+ .collect();
1301+ let sse = self.block_sse(x, y, side, &reconstruction);
12751302 // What the levels cost is priced through the same CDFs the tile writer
12761303 // will code them with, so the search ranks modes -- and the partition
12771304 // trial ranks trees -- by the bits they actually spend.
@@ -1319,16 +1346,7 @@ impl Plane<'_> {
13191346 set: TxbSet,
13201347 ) -> Trial {
13211348 if skip {
1322- let mut sse = 0.0;
1323- for row in 0..side {
1324- for col in 0..side {
1325- let error = f64::from(
1326- i32::from(self.source[(y + row) * self.width + x + col])
1327- - i32::from(prediction[row * side + col]),
1328- );
1329- sse += error * error;
1330- }
1331- }
1349+ let sse = self.block_sse(x, y, side, prediction);
13321350 return Trial {
13331351 levels: vec![0i32; side * side],
13341352 reconstruction: prediction.to_vec(),
@@ -1351,19 +1369,12 @@ impl Plane<'_> {
13511369 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
13521370 #[cfg(test)]
13531371 stage_add(2, t.elapsed());
1354- let mut reconstruction = vec![0u8; side * side];
1355- let mut sse = 0.0;
1356- for row in 0..side {
1357- for col in 0..side {
1358- let i = row * side + col;
1359- let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1360- reconstruction[i] = sample;
1361- let error = f64::from(
1362- i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1363- );
1364- sse += error * error;
1365- }
1366- }
1372+ let reconstruction: Vec<u8> = prediction
1373+ .iter()
1374+ .zip(&coded)
1375+ .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1376+ .collect();
1377+ let sse = self.block_sse(x, y, side, &reconstruction);
13671378 #[cfg(test)]
13681379 let t = std::time::Instant::now();
13691380 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
@@ -1500,16 +1511,7 @@ impl Plane<'_> {
15001511 false,
15011512 &mut prediction, fctx,
15021513 );
1503- let sad: f64 = (0..side * side)
1504- .map(|i| {
1505- let (row, col) = (i / side, i % side);
1506- f64::from(
1507- (i32::from(self.source[(y + row) * self.width + x + col])
1508- - i32::from(prediction[i]))
1509- .abs(),
1510- )
1511- })
1512- .sum();
1514+ let sad = self.block_sad(x, y, side, &prediction);
15131515 (sad + lambda * mode_bits[usize::from(mode)], mode)
15141516 })
15151517 .collect()
@@ -1557,17 +1559,8 @@ impl Plane<'_> {
15571559 false,
15581560 &mut prediction, fctx,
15591561 );
1560- let sad: f64 = if want_sad {
1561- (0..side * side)
1562- .map(|i| {
1563- let (row, col) = (i / side, i % side);
1564- f64::from(
1565- (i32::from(self.source[(y + row) * self.width + x + col])
1566- - i32::from(prediction[i]))
1567- .abs(),
1568- )
1569- })
1570- .sum()
1562+ let sad = if want_sad {
1563+ self.block_sad(x, y, side, &prediction)
15711564 } else {
15721565 0.0
15731566 };
crates/ec-av1/src/transform.rsmodified+54 -11
@@ -1442,6 +1442,34 @@ fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] {
14421442 cache[k][idx].get_or_init(|| build_axis_basis(n, kind))
14431443 }
14441444
1445+/// [`axis_basis`] transposed: `[i * n + u]` is basis function `u`'s sample
1446+/// `i`. Both of [`forward_transform_2d_typed`]'s passes sum over the sample
1447+/// index and are independent across the basis index, so this layout makes the
1448+/// basis index the contiguous one and the two matmuls vectorize -- without
1449+/// touching either sum's order, which is what keeps the levels bit-identical
1450+/// to the strided `.map().sum()` this replaced.
1451+fn axis_basis_t(n: usize, kind: TxType1d) -> &'static [f64] {
1452+ use std::sync::OnceLock;
1453+ static CACHE: OnceLock<[[OnceLock<Vec<f64>>; 5]; 3]> = OnceLock::new();
1454+ let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new())));
1455+ let k = match kind {
1456+ TxType1d::Dct => 0,
1457+ TxType1d::Adst => 1,
1458+ TxType1d::Identity => 2,
1459+ };
1460+ let idx = (n.trailing_zeros() as usize).saturating_sub(2);
1461+ cache[k][idx].get_or_init(|| {
1462+ let basis = axis_basis(n, kind);
1463+ let mut t = vec![0.0f64; n * n];
1464+ for u in 0..n {
1465+ for i in 0..n {
1466+ t[i * n + u] = basis[u * n + i];
1467+ }
1468+ }
1469+ t
1470+ })
1471+}
1472+
14451473 /// [`forward_transform_2d`] for a block whose transform type is not
14461474 /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode
14471475 /// 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
14611489 "a flipped ADST needs its residual mirrored before this basis applies"
14621490 );
14631491 let (row_kind, col_kind) = tx_type.axes();
1464- let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind));
1492+ let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind));
14651493 let mut rows = vec![0.0f64; side * side];
1494+ // Which rows of `rows` the pass below actually fills; the column pass
1495+ // walks only those. A row of `+0.0` contributes `0.0 * b` terms, which
1496+ // are `+-0.0`, and adding either to a running sum that is never `-0.0`
1497+ // (it starts at `+0.0` and `x + -x` is `+0.0`) leaves it unchanged.
1498+ let mut filled: [usize; 64] = [0; 64];
1499+ let mut nfilled = 0usize;
14661500 // Zero in, zero out, and `rows` is already zero here -- the skip
14671501 // [`forward_rows`] takes for the same reason, which this path was
14681502 // 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
14761510 continue;
14771511 }
14781512 any = true;
1479- for v in 0..side {
1480- rows[i * side + v] = source
1481- .iter()
1482- .zip(&hb[v * side..][..side])
1483- .map(|(&r, &b)| f64::from(r) * b)
1484- .sum();
1513+ filled[nfilled] = i;
1514+ nfilled += 1;
1515+ let out = &mut rows[i * side..][..side];
1516+ // `k` ascending is the term order the strided `.map().sum()` had, so
1517+ // every lane's partial sums are the same values in the same order.
1518+ for (k, &r) in source.iter().enumerate() {
1519+ let r = f64::from(r);
1520+ for (o, &b) in out.iter_mut().zip(&hb[k * side..][..side]) {
1521+ *o += r * b;
1522+ }
14851523 }
14861524 }
14871525 if !any {
@@ -1489,10 +1527,15 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType
14891527 }
14901528 let mut out = vec![0.0f64; side * side];
14911529 for u in 0..side {
1492- let column = &vb[u * side..][..side];
1493- for v in 0..side {
1494- let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum();
1495- out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum;
1530+ let acc = &mut out[u * side..][..side];
1531+ for &i in &filled[..nfilled] {
1532+ let c = vb[i * side + u];
1533+ for (a, &r) in acc.iter_mut().zip(&rows[i * side..][..side]) {
1534+ *a += r * c;
1535+ }
1536+ }
1537+ for a in acc.iter_mut() {
1538+ *a *= INVERSE_GAIN_RECIPROCAL;
14961539 }
14971540 }
14981541 out