forge
Explore
Log in

Don't you dare go Hollow

Inverse transform without per-call allocation or runtime bit-reversal

Browse files at this commit

ee4e9758d93a3e363495d37728e670eb4f879f39Ahmet Kaan GümüşParent: 6352a70
  • perf
    • inverse transform without per-call allocation or runtime bit-reversal
Show full message
perf(av1): inverse transform without per-call allocation or runtime bit-reversal

`perf annotate` of `inverse_dct` (12.3% self time) opened every call with a
`malloc`/`memcpy` pair -- `permute`'s `Vec` -- and then spent its hottest
single instruction in the inlined `brev` bit-fold, recomputed per butterfly
index. `cos128` was a four-way branch per butterfly, and the 2D driver
(7.6% self) allocated two more `Vec`s per transform unit while looking up
`row_shift_wh` through a match once per output sample.

All four are now compile-time or loop-invariant: `brev` and the whole-circle
cosine are const tables, `permute` copies into a stack array, the row pass
writes a thread-local scratch it fully overwrites, and the shift is hoisted.
The row and column passes also skip an all-zero vector, which is exact rather
than approximate -- every butterfly and Hadamard of zeros is zero and
`Round2(0, n)` is zero at every `n` -- and is what makes rows 32..64 of a
64-point transform, and the tail of any EOB-limited block, free.
`a_zero_vector_transforms_to_zero` pins that property per 1D transform and
end to end.

Byte-exact: `EC_PROBE_OUT16` dumps cmp IDENTICAL against the pre-change
binary on a 299-frame 1080p 10-bit segment, a 4 s 2160p HDR segment and the
8-bit palette fixture. Interleaved medians: 1080p 16.72 s -> 13.74 s
(17.9 -> 21.8 fps), 4K 78.74 s -> 70.05 s.
crates/ec-av1/src/transform.rsmodified+156 -30
@@ -8,7 +8,7 @@
8 //! rounded DCT would drift away from the decoder by a sample here and there.8 //! rounded DCT would drift away from the decoder by a sample here and there.
9 9
10 /// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.10 /// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.
11-static COS128_LOOKUP: [i32; 65] = [11+const COS128_LOOKUP: [i32; 65] = [
12 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822,12 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822,
13 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967,13 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967,
14 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660,14 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660,
@@ -18,15 +18,32 @@ static COS128_LOOKUP: [i32; 65] = [
18 /// The fixed-point position of the cosine table.18 /// The fixed-point position of the cosine table.
19 const COS_BITS: usize = 12;19 const COS_BITS: usize = 12;
20 20
21+/// [`COS128_LOOKUP`] unfolded to the whole circle at compile time -- the same
22+/// four quadrant cases the spec writes, evaluated once here so a butterfly's
23+/// cosine is one load instead of a four-way branch per call.
24+const fn build_cos128_full() -> [i32; 256] {
25+ let mut t = [0i32; 256];
26+ let mut a = 0usize;
27+ while a < 256 {
28+ t[a] = if a <= 64 {
29+ COS128_LOOKUP[a]
30+ } else if a <= 128 {
31+ -COS128_LOOKUP[128 - a]
32+ } else if a <= 192 {
33+ -COS128_LOOKUP[a - 128]
34+ } else {
35+ COS128_LOOKUP[256 - a]
36+ };
37+ a += 1;
38+ }
39+ t
40+}
41+
42+static COS128_FULL: [i32; 256] = build_cos128_full();
43+
21 /// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table.44 /// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table.
22 fn cos128(angle: i32) -> i32 {45 fn cos128(angle: i32) -> i32 {
23- let angle2 = (angle & 255) as usize;46+ COS128_FULL[(angle & 255) as usize]
24- match angle2 {
25- 0..=64 => COS128_LOOKUP[angle2],
26- 65..=128 => -COS128_LOOKUP[128 - angle2],
27- 129..=192 => -COS128_LOOKUP[angle2 - 128],
28- _ => COS128_LOOKUP[256 - angle2],
29- }
30 }47 }
31 48
32 /// `sin128(angle)` (spec 7.13.2.1).49 /// `sin128(angle)` (spec 7.13.2.1).
@@ -34,9 +51,39 @@ fn sin128(angle: i32) -> i32 {
34 cos128(angle - 64)51 cos128(angle - 64)
35 }52 }
36 53
54+/// `brev(numBits, x)` (spec 7.13.2.1) tabulated at compile time, one row per
55+/// `num_bits`. The bit-fold ran per butterfly index at runtime and was the
56+/// single hottest instruction sequence in `inverse_dct`'s annotation.
57+const fn build_brev(num_bits: u32) -> [u8; 64] {
58+ let mut t = [0u8; 64];
59+ let n0 = 1usize << num_bits;
60+ let mut x = 0usize;
61+ while x < n0 {
62+ let mut v = 0usize;
63+ let mut i = 0u32;
64+ while i < num_bits {
65+ v |= ((x >> i) & 1) << (num_bits - 1 - i);
66+ i += 1;
67+ }
68+ t[x] = v as u8;
69+ x += 1;
70+ }
71+ t
72+}
73+
74+static BREV_TAB: [[u8; 64]; 7] = [
75+ build_brev(0),
76+ build_brev(1),
77+ build_brev(2),
78+ build_brev(3),
79+ build_brev(4),
80+ build_brev(5),
81+ build_brev(6),
82+];
83+
37 /// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.84 /// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.
38 fn brev(num_bits: u32, x: usize) -> usize {85 fn brev(num_bits: u32, x: usize) -> usize {
39- (0..num_bits).fold(0, |t, i| t | (((x >> i) & 1) << (num_bits - 1 - i)))86+ BREV_TAB[num_bits as usize][x] as usize
40 }87 }
41 88
42 /// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.89 /// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.
@@ -85,9 +132,13 @@ fn hadamard(t: &mut [i32], a: usize, b: usize, flip: bool, r: usize) {
85 /// of the first `1 << n` entries.132 /// of the first `1 << n` entries.
86 fn permute(t: &mut [i32], n: u32) {133 fn permute(t: &mut [i32], n: u32) {
87 let n0 = 1usize << n;134 let n0 = 1usize << n;
88- let copy: Vec<i32> = t[..n0].to_vec();135+ // A stack copy: this ran once per 1D transform and its `Vec` was the
136+ // `malloc` at the top of every `inverse_dct` frame in the annotation.
137+ let mut copy = [0i32; 64];
138+ copy[..n0].copy_from_slice(&t[..n0]);
139+ let tab = &BREV_TAB[n as usize];
89 for (i, v) in t[..n0].iter_mut().enumerate() {140 for (i, v) in t[..n0].iter_mut().enumerate() {
90- *v = copy[brev(n, i)];141+ *v = copy[tab[i] as usize];
91 }142 }
92 }143 }
93 144
@@ -828,44 +879,71 @@ pub fn inverse_transform_2d_typed_wh(
828 assert_eq!(dequant.len(), w * h, "one coefficient per position");879 assert_eq!(dequant.len(), w * h, "one coefficient per position");
829 let row_clamp = usize::from(bit_depth) + 8;880 let row_clamp = usize::from(bit_depth) + 8;
830 let col_clamp = (usize::from(bit_depth) + 6).max(16);881 let col_clamp = (usize::from(bit_depth) + 6).max(16);
831- let mut residual = vec![0i32; w * h];
832 let (row_kind, col_kind) = tx_type.axes();882 let (row_kind, col_kind) = tx_type.axes();
833 let (ud_flip, lr_flip) = tx_type.flip();883 let (ud_flip, lr_flip) = tx_type.flip();
834 // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only884 // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only
835 // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/885 // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/
836 // 16x64/64x16).886 // 16x64/64x16).
837 let rect_scale = (log2w as i32 - log2h as i32).abs() == 1;887 let rect_scale = (log2w as i32 - log2h as i32).abs() == 1;
838-888+ // Loop-invariant: the shift is keyed on the transform size, and was being
889+ // looked up through a match once per output sample.
890+ let shift = row_shift_wh(w, h);
891+ // A FLIPADST axis reads the row-pass output right-to-left and/or writes
892+ // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c`
893+ // lines 291-314): `out` is a second buffer, not the row scratch reused in
894+ // place, because a flipped read/write pair aliases a column this same
895+ // loop has not visited yet (column `j`'s write target under `lr_flip`
896+ // is a column an unflipped loop would still need to read from later).
897+ // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`.
898+ let mut out = vec![0i32; w * h];
899+ let cols = w.min(32);
900+ ROW_SCRATCH.with(|cell| {
901+ let mut scratch = cell.borrow_mut();
902+ if scratch.len() < w * h {
903+ scratch.resize(64 * 64, 0);
904+ }
905+ let residual = &mut scratch[..w * h];
839 let mut t = [0i32; 64];906 let mut t = [0i32; 64];
840 for i in 0..h {907 for i in 0..h {
841- for j in 0..w {908+ let dst = &mut residual[i * w..(i + 1) * w];
842- let c = if i < 32 && j < 32 { dequant[i * w + j] } else { 0 };909+ // Rows at or past 32 carry no coefficients (the spec zeroes them
843- t[j] = if rect_scale {910+ // before the row transform), and a zero row transforms to a zero
844- round2(c * 2896, 12)911+ // row: every butterfly and Hadamard of zeros is zero, and
912+ // `Round2(0, n)` is zero at every `n`, so this is the full
913+ // network's own answer, not an approximation of it.
914+ let src = if i < 32 { &dequant[i * w..i * w + cols] } else { &[][..] };
915+ if src.iter().all(|&c| c == 0) {
916+ dst.fill(0);
917+ continue;
918+ }
919+ if rect_scale {
920+ for (tj, &c) in t[..cols].iter_mut().zip(src) {
921+ *tj = round2(c * 2896, 12);
922+ }
845 } else {923 } else {
846- c924+ t[..cols].copy_from_slice(src);
847- };
848 }925 }
926+ t[cols..w].fill(0);
849 inverse_1d(&mut t, log2w, row_clamp, row_kind);927 inverse_1d(&mut t, log2w, row_clamp, row_kind);
850- for j in 0..w {
851 // The row's output is shifted, then clamped before the column928 // The row's output is shifted, then clamped before the column
852 // transform reads it back.929 // transform reads it back.
853- residual[i * w + j] = clamp_range(round2(t[j], row_shift_wh(w, h)), col_clamp);930+ for (d, &v) in dst.iter_mut().zip(t[..w].iter()) {
931+ *d = clamp_range(round2(v, shift), col_clamp);
854 }932 }
855 }933 }
856 934
857- // A FLIPADST axis reads the row-pass output right-to-left and/or writes
858- // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c`
859- // lines 291-314): `out` is a second buffer, not `residual` reused in
860- // place, because a flipped read/write pair aliases a column this same
861- // loop has not visited yet (column `j`'s write target under `lr_flip`
862- // is a column an unflipped loop would still need to read from later).
863- // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`.
864- let mut out = vec![0i32; w * h];
865 for j in 0..w {935 for j in 0..w {
866 let src_col = if lr_flip { w - 1 - j } else { j };936 let src_col = if lr_flip { w - 1 - j } else { j };
937+ let mut any = 0i32;
867 for i in 0..h {938 for i in 0..h {
868- t[i] = residual[i * w + src_col];939+ let v = residual[i * w + src_col];
940+ t[i] = v;
941+ any |= v;
942+ }
943+ // Same zero-in/zero-out argument as the row pass, and `out` is
944+ // already zero at every position this column would write.
945+ if any == 0 {
946+ continue;
869 }947 }
870 inverse_1d(&mut t, log2h, col_clamp, col_kind);948 inverse_1d(&mut t, log2h, col_clamp, col_kind);
871 for i in 0..h {949 for i in 0..h {
@@ -873,9 +951,18 @@ pub fn inverse_transform_2d_typed_wh(
873 out[dst_row * w + j] = round2(t[i], 4);951 out[dst_row * w + j] = round2(t[i], 4);
874 }952 }
875 }953 }
954+ });
876 out955 out
877 }956 }
878 957
958+thread_local! {
959+ /// Row-pass scratch, reused per thread. The row pass writes every position
960+ /// it later reads, so the buffer needs no zeroing, and the two `Vec`s this
961+ /// function allocated per transform unit become one.
962+ static ROW_SCRATCH: std::cell::RefCell<Vec<i32>> =
963+ const { std::cell::RefCell::new(Vec::new()) };
964+}
965+
879 /// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original966 /// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original
880 /// (and still most common) transform.967 /// (and still most common) transform.
881 pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {968 pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {
@@ -1217,6 +1304,45 @@ pub fn forward_and_quantize(
1217 mod tests {1304 mod tests {
1218 use super::*;1305 use super::*;
1219 1306
1307+ /// The row and column passes skip an all-zero vector instead of running
1308+ /// the butterfly network over it. That is only bit-exact because a zero
1309+ /// vector transforms to a zero vector at every size, type and bit depth --
1310+ /// which is what this pins, per 1D transform and end to end.
1311+ #[test]
1312+ fn a_zero_vector_transforms_to_zero() {
1313+ for log2 in 2..=6u32 {
1314+ for kind in [TxType1d::Dct, TxType1d::Adst, TxType1d::Identity] {
1315+ if kind == TxType1d::Adst && log2 > 4 {
1316+ continue;
1317+ }
1318+ if kind == TxType1d::Identity && log2 > 5 {
1319+ continue;
1320+ }
1321+ for bit_depth in [8u8, 10, 12] {
1322+ let r = (usize::from(bit_depth) + 6).max(16);
1323+ let mut t = [0i32; 64];
1324+ inverse_1d(&mut t, log2, r, kind);
1325+ assert!(
1326+ t.iter().all(|&v| v == 0),
1327+ "1D {kind:?} log2={log2} depth={bit_depth} left a non-zero"
1328+ );
1329+ }
1330+ }
1331+ }
1332+ for (w, h) in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64), (8, 16), (16, 8), (4, 16), (32, 8)] {
1333+ for tx in [TxType::DctDct, TxType::AdstAdst, TxType::Idtx, TxType::AdstDct, TxType::DctAdst] {
1334+ if w.max(h) > 16 && tx != TxType::DctDct && tx != TxType::Idtx {
1335+ continue;
1336+ }
1337+ if w.max(h) > 32 && tx != TxType::DctDct {
1338+ continue;
1339+ }
1340+ let out = inverse_transform_2d_typed_wh(&vec![0i32; w * h], w, h, 10, tx);
1341+ assert!(out.iter().all(|&v| v == 0), "2D {w}x{h} {tx:?} left a non-zero");
1342+ }
1343+ }
1344+ }
1345+
1220 /// The orthonormal DCT-II basis the forward transform is written against,1346 /// The orthonormal DCT-II basis the forward transform is written against,
1221 /// computed independently of `dct_basis` so a test is not checking a1347 /// computed independently of `dct_basis` so a test is not checking a
1222 /// function against itself.1348 /// function against itself.