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<'_> {
1210 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps1210 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
1211 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.1211 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
1212 #[allow(clippy::too_many_arguments)]1212 #[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+
1213 fn trial_typed(1247 fn trial_typed(
1214 &self,1248 &self,
1215 at: At,1249 at: At,
@@ -1259,19 +1293,12 @@ impl Plane<'_> {
1259 #[cfg(test)]1293 #[cfg(test)]
1260 stage_add(2, t.elapsed());1294 stage_add(2, t.elapsed());
1261 1295
1262- let mut reconstruction = vec![0u8; side * side];1296+ let reconstruction: Vec<u8> = prediction
1263- let mut sse = 0.0;1297+ .iter()
1264- for row in 0..side {1298+ .zip(&coded)
1265- for col in 0..side {1299+ .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1266- let i = row * side + col;1300+ .collect();
1267- let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;1301+ let sse = self.block_sse(x, y, side, &reconstruction);
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- }
1275 // What the levels cost is priced through the same CDFs the tile writer1302 // What the levels cost is priced through the same CDFs the tile writer
1276 // will code them with, so the search ranks modes -- and the partition1303 // will code them with, so the search ranks modes -- and the partition
1277 // trial ranks trees -- by the bits they actually spend.1304 // trial ranks trees -- by the bits they actually spend.
@@ -1319,16 +1346,7 @@ impl Plane<'_> {
1319 set: TxbSet,1346 set: TxbSet,
1320 ) -> Trial {1347 ) -> Trial {
1321 if skip {1348 if skip {
1322- let mut sse = 0.0;1349+ let sse = self.block_sse(x, y, side, prediction);
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- }
1332 return Trial {1350 return Trial {
1333 levels: vec![0i32; side * side],1351 levels: vec![0i32; side * side],
1334 reconstruction: prediction.to_vec(),1352 reconstruction: prediction.to_vec(),
@@ -1351,19 +1369,12 @@ impl Plane<'_> {
1351 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));1369 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
1352 #[cfg(test)]1370 #[cfg(test)]
1353 stage_add(2, t.elapsed());1371 stage_add(2, t.elapsed());
1354- let mut reconstruction = vec![0u8; side * side];1372+ let reconstruction: Vec<u8> = prediction
1355- let mut sse = 0.0;1373+ .iter()
1356- for row in 0..side {1374+ .zip(&coded)
1357- for col in 0..side {1375+ .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1358- let i = row * side + col;1376+ .collect();
1359- let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;1377+ let sse = self.block_sse(x, y, side, &reconstruction);
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- }
1367 #[cfg(test)]1378 #[cfg(test)]
1368 let t = std::time::Instant::now();1379 let t = std::time::Instant::now();
1369 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {1380 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
@@ -1500,16 +1511,7 @@ impl Plane<'_> {
1500 false,1511 false,
1501 &mut prediction, fctx,1512 &mut prediction, fctx,
1502 );1513 );
1503- let sad: f64 = (0..side * side)1514+ let sad = self.block_sad(x, y, side, &prediction);
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();
1513 (sad + lambda * mode_bits[usize::from(mode)], mode)1515 (sad + lambda * mode_bits[usize::from(mode)], mode)
1514 })1516 })
1515 .collect()1517 .collect()
@@ -1557,17 +1559,8 @@ impl Plane<'_> {
1557 false,1559 false,
1558 &mut prediction, fctx,1560 &mut prediction, fctx,
1559 );1561 );
1560- let sad: f64 = if want_sad {1562+ let sad = if want_sad {
1561- (0..side * side)1563+ self.block_sad(x, y, side, &prediction)
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()
1571 } else {1564 } else {
1572 0.01565 0.0
1573 };1566 };
crates/ec-av1/src/transform.rsmodified+54 -11
@@ -1442,6 +1442,34 @@ fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] {
1442 cache[k][idx].get_or_init(|| build_axis_basis(n, kind))1442 cache[k][idx].get_or_init(|| build_axis_basis(n, kind))
1443 }1443 }
1444 1444
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+
1445 /// [`forward_transform_2d`] for a block whose transform type is not1473 /// [`forward_transform_2d`] for a block whose transform type is not
1446 /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode1474 /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode
1447 /// gets, since chroma never codes a `tx_type` symbol and the decoder derives1475 /// 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
1461 "a flipped ADST needs its residual mirrored before this basis applies"1489 "a flipped ADST needs its residual mirrored before this basis applies"
1462 );1490 );
1463 let (row_kind, col_kind) = tx_type.axes();1491 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));
1465 let mut rows = vec![0.0f64; side * side];1493 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;
1466 // Zero in, zero out, and `rows` is already zero here -- the skip1500 // Zero in, zero out, and `rows` is already zero here -- the skip
1467 // [`forward_rows`] takes for the same reason, which this path was1501 // [`forward_rows`] takes for the same reason, which this path was
1468 // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68%1502 // 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
1476 continue;1510 continue;
1477 }1511 }
1478 any = true;1512 any = true;
1479- for v in 0..side {1513+ filled[nfilled] = i;
1480- rows[i * side + v] = source1514+ nfilled += 1;
1481- .iter()1515+ let out = &mut rows[i * side..][..side];
1482- .zip(&hb[v * side..][..side])1516+ // `k` ascending is the term order the strided `.map().sum()` had, so
1483- .map(|(&r, &b)| f64::from(r) * b)1517+ // every lane's partial sums are the same values in the same order.
1484- .sum();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+ }
1485 }1523 }
1486 }1524 }
1487 if !any {1525 if !any {
@@ -1489,10 +1527,15 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType
1489 }1527 }
1490 let mut out = vec![0.0f64; side * side];1528 let mut out = vec![0.0f64; side * side];
1491 for u in 0..side {1529 for u in 0..side {
1492- let column = &vb[u * side..][..side];1530+ let acc = &mut out[u * side..][..side];
1493- for v in 0..side {1531+ for &i in &filled[..nfilled] {
1494- let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum();1532+ let c = vb[i * side + u];
1495- out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum;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;
1496 }1539 }
1497 }1540 }
1498 out1541 out