forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1simd' (5da4ea68): exact integer SAD/SSE, cached transposed forward basis, no per-row / per-prediction allocations

Browse files at this commit

107329c685f0c0d4514185c67e718648d171bebdAhmet Kaan GümüşParent: cbbd6e2c8907e1
Byte-identical (FNV sets on the three gate clips against a clean-checkout
baseline binary); single-thread ladder -11.1% instructions; 3840x1608
4x2/8 threads 1.41 -> 1.60 fps. AVX2 forward passes not built: 67% of
forward transforms are 4x4 and the addressable share is ~1.4%.
crates/ec-av1/src/encode.rsmodified+88 -69
@@ -552,20 +552,37 @@ fn intra_predict_u8(
552552 smooth_neighbor: bool,
553553 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
554554 ) {
555- let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect());
556- let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect());
557- let mut dst16 = vec![0u16; dst.len()];
555+ // Three heap allocations per call became three stack buffers: this runs
556+ // once per mode per trial, and an edge is at most `bw + bh` samples while
557+ // a block is at most `BLOCK * BLOCK`. Same samples either way.
558+ let mut above_buf = [0u16; 2 * BLOCK];
559+ let mut left_buf = [0u16; 2 * BLOCK];
560+ let mut dst_buf = [0u16; BLOCK * BLOCK];
561+ let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
562+ for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
563+ *d = u16::from(v);
564+ }
565+ };
566+ if let Some(s) = above {
567+ widen(s, &mut above_buf);
568+ }
569+ if let Some(s) = left {
570+ widen(s, &mut left_buf);
571+ }
572+ let above16 = above.map(|s| &above_buf[..s.len()]);
573+ let left16 = left.map(|s| &left_buf[..s.len()]);
574+ let dst16 = &mut dst_buf[..dst.len()];
558575 crate::intra::predict(
559576 mode,
560577 angle_delta,
561- above16.as_deref(),
562- left16.as_deref(),
578+ above16,
579+ left16,
563580 corner.map(u16::from),
564581 bw,
565582 bh,
566583 enable_edge_filter,
567584 smooth_neighbor,
568- &mut dst16, fctx,
585+ dst16, fctx,
569586 );
570587 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
571588 *d = s as u8;
@@ -1244,6 +1261,40 @@ impl Plane<'_> {
12441261 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
12451262 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
12461263 #[allow(clippy::too_many_arguments)]
1264+ /// Sum of absolute differences between the source block at `(x, y)` and a
1265+ /// `side x side` prediction, as the whole number it is.
1266+ ///
1267+ /// Bit-identical to the `f64` accumulation it replaces: every partial sum
1268+ /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
1269+ /// exactly, so no add here rounds and the order of the adds cannot change
1270+ /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
1271+ /// integer division per sample -- is what lets the row walk vectorize.
1272+ fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
1273+ let mut sad = 0u32;
1274+ for row in 0..side {
1275+ let source = &self.source[(y + row) * self.width + x..][..side];
1276+ for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
1277+ sad += u32::from(s.abs_diff(p));
1278+ }
1279+ }
1280+ f64::from(sad)
1281+ }
1282+
1283+ /// Squared error between the source block at `(x, y)` and a reconstruction
1284+ /// of it. Exact for the same reason [`Self::block_sad`] is: the largest
1285+ /// total is `255^2 * 64 * 64`, under 2^28.
1286+ fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
1287+ let mut sse = 0u64;
1288+ for row in 0..side {
1289+ let source = &self.source[(y + row) * self.width + x..][..side];
1290+ for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) {
1291+ let d = u32::from(s.abs_diff(r));
1292+ sse += u64::from(d * d);
1293+ }
1294+ }
1295+ sse as f64
1296+ }
1297+
12471298 fn trial_typed(
12481299 &self,
12491300 at: At,
@@ -1293,19 +1344,12 @@ impl Plane<'_> {
12931344 #[cfg(test)]
12941345 stage_add(2, t.elapsed());
12951346
1296- let mut reconstruction = vec![0u8; side * side];
1297- let mut sse = 0.0;
1298- for row in 0..side {
1299- for col in 0..side {
1300- let i = row * side + col;
1301- let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1302- reconstruction[i] = sample;
1303- let error = f64::from(
1304- i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1305- );
1306- sse += error * error;
1307- }
1308- }
1347+ let reconstruction: Vec<u8> = prediction
1348+ .iter()
1349+ .zip(&coded)
1350+ .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1351+ .collect();
1352+ let sse = self.block_sse(x, y, side, &reconstruction);
13091353 // What the levels cost is priced through the same CDFs the tile writer
13101354 // will code them with, so the search ranks modes -- and the partition
13111355 // trial ranks trees -- by the bits they actually spend.
@@ -1353,16 +1397,7 @@ impl Plane<'_> {
13531397 set: TxbSet,
13541398 ) -> Trial {
13551399 if skip {
1356- let mut sse = 0.0;
1357- for row in 0..side {
1358- for col in 0..side {
1359- let error = f64::from(
1360- i32::from(self.source[(y + row) * self.width + x + col])
1361- - i32::from(prediction[row * side + col]),
1362- );
1363- sse += error * error;
1364- }
1365- }
1400+ let sse = self.block_sse(x, y, side, prediction);
13661401 return Trial {
13671402 levels: vec![0i32; side * side],
13681403 reconstruction: prediction.to_vec(),
@@ -1385,19 +1420,12 @@ impl Plane<'_> {
13851420 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
13861421 #[cfg(test)]
13871422 stage_add(2, t.elapsed());
1388- let mut reconstruction = vec![0u8; side * side];
1389- let mut sse = 0.0;
1390- for row in 0..side {
1391- for col in 0..side {
1392- let i = row * side + col;
1393- let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1394- reconstruction[i] = sample;
1395- let error = f64::from(
1396- i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1397- );
1398- sse += error * error;
1399- }
1400- }
1423+ let reconstruction: Vec<u8> = prediction
1424+ .iter()
1425+ .zip(&coded)
1426+ .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1427+ .collect();
1428+ let sse = self.block_sse(x, y, side, &reconstruction);
14011429 #[cfg(test)]
14021430 let t = std::time::Instant::now();
14031431 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
@@ -1482,17 +1510,13 @@ impl Plane<'_> {
14821510 /// `source`), since [`Self::source`] itself is the whole plane, strided
14831511 /// by [`Self::width`].
14841512 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1485- (y..y + side)
1486- .flat_map(|row| self.source[row * self.width + x..][..side].to_vec())
1487- .collect()
1513+ rows_of(self.source, self.width, x, y, side)
14881514 }
14891515
14901516 /// The reconstructed samples of one square, so that a partition trial can
14911517 /// be undone.
14921518 fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1493- (y..y + side)
1494- .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec())
1495- .collect()
1519+ rows_of(&self.reconstruction, self.width, x, y, side)
14961520 }
14971521
14981522 /// Puts a snapshot back.
@@ -1534,16 +1558,7 @@ impl Plane<'_> {
15341558 false,
15351559 &mut prediction, fctx,
15361560 );
1537- let sad: f64 = (0..side * side)
1538- .map(|i| {
1539- let (row, col) = (i / side, i % side);
1540- f64::from(
1541- (i32::from(self.source[(y + row) * self.width + x + col])
1542- - i32::from(prediction[i]))
1543- .abs(),
1544- )
1545- })
1546- .sum();
1561+ let sad = self.block_sad(x, y, side, &prediction);
15471562 (sad + lambda * mode_bits[usize::from(mode)], mode)
15481563 })
15491564 .collect()
@@ -1591,17 +1606,8 @@ impl Plane<'_> {
15911606 false,
15921607 &mut prediction, fctx,
15931608 );
1594- let sad: f64 = if want_sad {
1595- (0..side * side)
1596- .map(|i| {
1597- let (row, col) = (i / side, i % side);
1598- f64::from(
1599- (i32::from(self.source[(y + row) * self.width + x + col])
1600- - i32::from(prediction[i]))
1601- .abs(),
1602- )
1603- })
1604- .sum()
1609+ let sad = if want_sad {
1610+ self.block_sad(x, y, side, &prediction)
16051611 } else {
16061612 0.0
16071613 };
@@ -3783,6 +3789,19 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O
37833789
37843790 /// The reconstructed samples one 32x32 square covers in all three planes, so
37853791 /// that a partition trial can be undone.
3792+/// One square of a plane, row-major, the inverse of [`Plane::restore`].
3793+///
3794+/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
3795+/// which allocated and freed a `Vec` per row of every block it copied --
3796+/// `Plane::snapshot` runs once per partition trial.
3797+fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
3798+ let mut out = vec![0u8; side * side];
3799+ for row in 0..side {
3800+ out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
3801+ }
3802+ out
3803+}
3804+
37863805 fn snapshot(
37873806 luma: &Plane,
37883807 chroma: &[Plane; 2],
crates/ec-av1/src/transform.rsmodified+138 -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
@@ -2613,6 +2656,90 @@ mod tests {
26132656 /// full-range noise. A single differing lane at any size would be a
26142657 /// silent pixel drift on whatever stream first reaches it.
26152658 #[cfg(target_arch = "x86_64")]
2659+ /// [`forward_transform_2d_typed`]'s contiguous-basis passes are the
2660+ /// strided `.map().sum()` they replaced, bit for bit.
2661+ ///
2662+ /// The reordering is safe only because each output's terms stay in the
2663+ /// same order -- only the loop that iterates the *outputs* moved -- so
2664+ /// this compares raw bit patterns, not an epsilon: any reassociation
2665+ /// would show up here as a last-place difference at some size.
2666+ #[test]
2667+ fn the_typed_forward_transform_is_bit_identical_to_the_strided_form() {
2668+ fn strided(residual: &[i32], side: usize, tx_type: TxType) -> Vec<f64> {
2669+ let (row_kind, col_kind) = tx_type.axes();
2670+ let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind));
2671+ let mut rows = vec![0.0f64; side * side];
2672+ for i in 0..side {
2673+ let source = &residual[i * side..][..side];
2674+ if source.iter().all(|&r| r == 0) {
2675+ continue;
2676+ }
2677+ for v in 0..side {
2678+ rows[i * side + v] = source
2679+ .iter()
2680+ .zip(&hb[v * side..][..side])
2681+ .map(|(&r, &b)| f64::from(r) * b)
2682+ .sum();
2683+ }
2684+ }
2685+ let mut out = vec![0.0f64; side * side];
2686+ for u in 0..side {
2687+ let column = &vb[u * side..][..side];
2688+ for v in 0..side {
2689+ let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum();
2690+ out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum;
2691+ }
2692+ }
2693+ out
2694+ }
2695+ let mut seed = 0x9E37_79B9_7F4A_7C15u64;
2696+ let mut next = move || {
2697+ seed ^= seed << 13;
2698+ seed ^= seed >> 7;
2699+ seed ^= seed << 17;
2700+ seed
2701+ };
2702+ let types = [
2703+ TxType::Idtx,
2704+ TxType::AdstAdst,
2705+ TxType::AdstDct,
2706+ TxType::DctAdst,
2707+ TxType::VDct,
2708+ TxType::HDct,
2709+ ];
2710+ for side in [4usize, 8, 16, 32] {
2711+ for tx_type in types {
2712+ // ADST is undefined above 16 (the spec's 32+ sets are
2713+ // DCT/identity only), so those pairs never reach this path.
2714+ let adst = matches!(tx_type.axes(), (TxType1d::Adst, _) | (_, TxType1d::Adst));
2715+ if side > 16 && adst {
2716+ continue;
2717+ }
2718+ for round in 0..8 {
2719+ // Round 0 is an all-zero residual and round 1 has whole
2720+ // zero rows, so both skips are exercised at every size.
2721+ let residual: Vec<i32> = (0..side * side)
2722+ .map(|i| match round {
2723+ 0 => 0,
2724+ 1 if (i / side) % 2 == 0 => 0,
2725+ _ => (next() % 511) as i32 - 255,
2726+ })
2727+ .collect();
2728+ let ours = forward_transform_2d_typed(&residual, side, tx_type);
2729+ let theirs = strided(&residual, side, tx_type);
2730+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2731+ assert_eq!(
2732+ a.to_bits(),
2733+ b.to_bits(),
2734+ "{tx_type:?} {side}x{side} round {round} coefficient {i}: \
2735+ {a} vs {b}"
2736+ );
2737+ }
2738+ }
2739+ }
2740+ }
2741+ }
2742+
26162743 #[test]
26172744 fn the_avx2_dct_matches_the_scalar_one_over_the_full_range() {
26182745 if !std::arch::is_x86_feature_detected!("avx2") {