forge
Explore
Log in

Don't you dare go Hollow

Explicit AVX2 inverse-DCT column pass, and an empty all-zero residual

Browse files at this commit

ef53b7eaccf2a7ee6a04c72fb78c417503eb065eAhmet Kaan GümüşParent: d60c70e
  • perf
    • explicit AVX2 inverse-DCT column pass, and an empty all-zero residual
Show full message
perf(av1): explicit AVX2 inverse-DCT column pass, and an empty all-zero residual

The eight-wide column pass lane-tx introduced went through `[i32; 8]`, which
LLVM never vectorised (the butterfly products are 64-bit). This adds an
explicit AVX2 `Lane` impl -- `_mm256_mul_epi32` on the even/odd halves, so
every product is exact in 64 bits and the pass is byte-exact with the scalar
network on every input, not only on conformant ones -- dispatched off
`mc::simd_level()`, with the scalar impl kept as the reference.

`inverse_dct_n` is `#[inline(always)]` because the AVX2 instantiation has to
land inside the `target_feature` wrapper: without it every `_mm256_*` stayed
an out-of-line call and the "SIMD" pass measured 5.6% WORSE.

Second, the 60% of transform units that carry no coefficient now return an
EMPTY residual instead of `w * h` zeros: the reconstruction loops expand the
marker against one static zero block, so the per-unit zero `Vec`, its `to_vec`
clone into the recorded op, and (for a deferred unit) the coefficient-grid
clone all disappear.

seg4k at one thread: 523.1 -> 503.5 G instructions:u (-3.7%), min-of-5
cycles:u 142.1 -> 136.4 G. All 12 gate hashes unchanged.
crates/ec-av1/src/decode.rsmodified+33 -3
@@ -2088,6 +2088,11 @@ impl TxParams {
20882088 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
20892089 self.tx_type,
20902090 );
2091+ // An all-zero grid transforms to the empty marker, and a strided copy
2092+ // of zeros is still zeros: the marker passes straight through.
2093+ if residual.is_empty() {
2094+ return residual;
2095+ }
20912096 if self.stride == 0 {
20922097 return residual;
20932098 }
@@ -2108,6 +2113,16 @@ pub(crate) enum Residual {
21082113 }
21092114
21102115 impl Residual {
2116+ /// The record for a transform unit whose coefficient grid is all zero:
2117+ /// the empty marker, so neither the grid nor the residual is cloned and
2118+ /// the worker never runs the transform (60% of the 4K segment's units).
2119+ fn coeffs(tx: TxParams, grid: &[i32]) -> Self {
2120+ if grid.iter().all(|&c| c == 0) {
2121+ return Self::Done(Vec::new());
2122+ }
2123+ Self::Coeffs(tx, grid.to_vec())
2124+ }
2125+
21112126 fn resolve(self) -> Vec<i32> {
21122127 match self {
21132128 Self::Done(v) => v,
@@ -2116,6 +2131,18 @@ impl Residual {
21162131 }
21172132 }
21182133
2134+/// An all-zero residual, for the transform units that code no coefficient:
2135+/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2136+/// and the reconstruction loops below read this instead of a per-unit
2137+/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2138+/// (a 128-wide inter block's prediction stride).
2139+static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2140+
2141+/// `residual`, or `n` zeros when it is the empty all-zero marker.
2142+fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2143+ if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2144+}
2145+
21192146 /// Where a recorded motion-compensated write reads its prediction from.
21202147 ///
21212148 /// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
@@ -2846,7 +2873,7 @@ fn push_intra_tx(
28462873 let pred = take_palette_pred(fctx);
28472874 push_op(fctx, ReconOp::Intra {
28482875 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
2849- residual: Residual::Coeffs(tx, grid.to_vec()), cfl, filter_intra, smooth_neighbor, pred,
2876+ residual: Residual::coeffs(tx, grid), cfl, filter_intra, smooth_neighbor, pred,
28502877 });
28512878 }
28522879
@@ -2877,7 +2904,7 @@ fn push_mc_rect_tx(
28772904 push_op(fctx, ReconOp::Mc {
28782905 plane, x, y, stride: w, w, h,
28792906 prediction: PredSrc::Cur { plane: sp, off, src: ss },
2880- residual: Residual::Coeffs(tx, grid.to_vec()),
2907+ residual: Residual::coeffs(tx, grid),
28812908 });
28822909 return;
28832910 }
@@ -2918,7 +2945,7 @@ fn push_mc_rect_tx(
29182945 tx.stride = 0;
29192946 push_op(fctx, ReconOp::Mc {
29202947 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(window),
2921- residual: Residual::Coeffs(tx, grid.to_vec()),
2948+ residual: Residual::coeffs(tx, grid),
29222949 });
29232950 }
29242951
@@ -12808,6 +12835,7 @@ impl PlaneBuf<'_> {
1280812835 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
1280912836 );
1281012837 }
12838+ let residual = dense_residual(residual, bw * bh);
1281112839 for row in 0..bh {
1281212840 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
1281312841 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
@@ -12914,6 +12942,7 @@ impl PlaneBuf<'_> {
1291412942 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
1291512943 );
1291612944 }
12945+ let residual = dense_residual(residual, side * side);
1291712946 for row in 0..side {
1291812947 // lane-sb128c r8: libaom's frame buffer is superblock
1291912948 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
@@ -21797,6 +21826,7 @@ impl PlaneBuf<'_> {
2179721826 // three row bases are computed once per row instead of a
2179821827 // multiply-add per sample (the samples themselves are unchanged).
2179921828 let max = crate::decode::sample_max(fctx);
21829+ let residual = dense_residual(residual, side * h);
2180021830 for row in 0..h {
2180121831 let src = row * side;
2180221832 let dst = (y + row) * self.width + x;
crates/ec-av1/src/transform.rsmodified+160 -14
@@ -112,8 +112,6 @@ fn clamp_range(x: i32, r: usize) -> i32 {
112112 /// integer arithmetic, so the eight-wide pass is byte-exact with the scalar
113113 /// one by construction -- the network itself is written once, above.
114114 trait Lane: Copy {
115- /// The additive identity, for [`permute`]'s scratch.
116- const ZERO: Self;
117115 /// One butterfly rotation's two outputs, at pre-multiplied `cos`/`sin`.
118116 fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self);
119117 /// One Hadamard rotation's two outputs, clamped to `r` bits.
@@ -126,8 +124,6 @@ fn round_cos(x: i64) -> i32 {
126124 }
127125
128126 impl Lane for i32 {
129- const ZERO: Self = 0;
130-
131127 fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self) {
132128 let (ta, tb) = (i64::from(a), i64::from(b));
133129 (round_cos(ta * c - tb * s), round_cos(ta * s + tb * c))
@@ -141,8 +137,6 @@ impl Lane for i32 {
141137 /// Eight columns at once. Every operation is the [`i32`] impl's, lane by lane,
142138 /// which is what the optimiser turns into one vector op per line.
143139 impl Lane for [i32; 8] {
144- const ZERO: Self = [0; 8];
145-
146140 fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self) {
147141 let mut x = [0i32; 8];
148142 let mut y = [0i32; 8];
@@ -165,8 +159,132 @@ impl Lane for [i32; 8] {
165159 }
166160 }
167161
162+/// The same eight-wide column pass in explicit AVX2. Every operation below is
163+/// the [`i32`] impl's arithmetic, lane for lane, in 64-bit products -- so it is
164+/// byte-exact with the scalar network on every input, not only on conformant
165+/// ones (`the_avx2_dct_matches_the_scalar_one_over_the_full_range`).
166+#[cfg(target_arch = "x86_64")]
167+#[allow(unsafe_code)]
168+mod simd {
169+ use super::{COS_BITS, Lane, inverse_dct_n};
170+ use std::arch::x86_64::*;
171+
172+ /// Eight `i32` lanes in one AVX2 register.
173+ #[derive(Clone, Copy)]
174+ pub(super) struct M256(pub(super) __m256i);
175+
176+ impl Lane for M256 {
177+ /// `round_cos(a*c - b*s)`, `round_cos(a*s + b*c)`.
178+ ///
179+ /// `_mm256_mul_epi32` multiplies the sign-extended low `i32` of each
180+ /// 64-bit lane, so the four even lanes go through directly and the four
181+ /// odd ones after a shuffle; the products and their sum are exact in 64
182+ /// bits (`|a| < 2^31`, `|c| <= 2^12`), and only the low 32 bits of the
183+ /// shifted sum are kept -- which is what the scalar `as i32` keeps, so
184+ /// the logical shift below stands in for the arithmetic one exactly.
185+ #[inline(always)]
186+ fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self) {
187+ unsafe {
188+ let cv = _mm256_set1_epi32(c as i32);
189+ let sv = _mm256_set1_epi32(s as i32);
190+ let rnd = _mm256_set1_epi64x(1 << (COS_BITS - 1));
191+ let (ae, be) = (a.0, b.0);
192+ let (ao, bo) = (_mm256_shuffle_epi32(a.0, 0xB1), _mm256_shuffle_epi32(b.0, 0xB1));
193+ let half = |x: __m256i, y: __m256i, u: __m256i, v: __m256i| {
194+ let p = _mm256_sub_epi64(_mm256_mul_epi32(x, u), _mm256_mul_epi32(y, v));
195+ let q = _mm256_add_epi64(_mm256_mul_epi32(x, v), _mm256_mul_epi32(y, u));
196+ (
197+ _mm256_srli_epi64::<{ COS_BITS as i32 }>(_mm256_add_epi64(p, rnd)),
198+ _mm256_srli_epi64::<{ COS_BITS as i32 }>(_mm256_add_epi64(q, rnd)),
199+ )
200+ };
201+ let (xe, ye) = half(ae, be, cv, sv);
202+ let (xo, yo) = half(ao, bo, cv, sv);
203+ (
204+ M256(_mm256_blend_epi32::<0xAA>(xe, _mm256_slli_epi64::<32>(xo))),
205+ M256(_mm256_blend_epi32::<0xAA>(ye, _mm256_slli_epi64::<32>(yo))),
206+ )
207+ }
208+ }
209+
210+ #[inline(always)]
211+ fn had(a: Self, b: Self, r: usize) -> (Self, Self) {
212+ unsafe {
213+ let hi = _mm256_set1_epi32(((1i64 << (r - 1)) - 1) as i32);
214+ let lo = _mm256_set1_epi32((-(1i64 << (r - 1))) as i32);
215+ let clamp = |v| _mm256_min_epi32(_mm256_max_epi32(v, lo), hi);
216+ (
217+ M256(clamp(_mm256_add_epi32(a.0, b.0))),
218+ M256(clamp(_mm256_sub_epi32(a.0, b.0))),
219+ )
220+ }
221+ }
222+ }
223+
224+ /// The whole DCT column pass of one transform unit: `residual` is the
225+ /// row-pass output (`h` rows of `w`), `out` the residual it writes.
226+ ///
227+ /// # Safety
228+ /// The caller has checked for AVX2 ([`crate::mc::simd_level`]).
229+ #[target_feature(enable = "avx2")]
230+ pub(super) unsafe fn column_pass_dct(
231+ residual: &[i32],
232+ out: &mut [i32],
233+ w: usize,
234+ h: usize,
235+ log2h: u32,
236+ r: usize,
237+ ud_flip: bool,
238+ ) {
239+ let mut t = [M256(_mm256_setzero_si256()); 64];
240+ for j in (0..w).step_by(8) {
241+ let mut any = _mm256_setzero_si256();
242+ for i in 0..h {
243+ let v = unsafe { _mm256_loadu_si256(residual[i * w + j..].as_ptr().cast()) };
244+ t[i] = M256(v);
245+ any = _mm256_or_si256(any, v);
246+ }
247+ // Zero in, zero out -- and `out` is already zero here.
248+ if _mm256_testz_si256(any, any) == 1 {
249+ continue;
250+ }
251+ match log2h {
252+ 2 => inverse_dct_n::<M256, 2>(&mut t, r),
253+ 3 => inverse_dct_n::<M256, 3>(&mut t, r),
254+ 4 => inverse_dct_n::<M256, 4>(&mut t, r),
255+ 5 => inverse_dct_n::<M256, 5>(&mut t, r),
256+ 6 => inverse_dct_n::<M256, 6>(&mut t, r),
257+ _ => unreachable!("the inverse DCT is defined for 4..64"),
258+ }
259+ // `round2(v, 4)` on eight lanes: the shift is arithmetic here
260+ // because the value stays in its own 32-bit lane.
261+ let rnd = _mm256_set1_epi32(8);
262+ for i in 0..h {
263+ let dst_row = if ud_flip { h - 1 - i } else { i };
264+ let v = _mm256_srai_epi32::<4>(_mm256_add_epi32(t[i].0, rnd));
265+ unsafe { _mm256_storeu_si256(out[dst_row * w + j..].as_mut_ptr().cast(), v) };
266+ }
267+ }
268+ }
269+
270+ /// The eight scalar lanes of `v`, for the equivalence gate.
271+ #[cfg(test)]
272+ pub(super) fn lanes(v: M256) -> [i32; 8] {
273+ let mut o = [0i32; 8];
274+ unsafe { _mm256_storeu_si256(o.as_mut_ptr().cast(), v.0) };
275+ o
276+ }
277+
278+ /// `M256` from eight lanes, for the equivalence gate.
279+ #[cfg(test)]
280+ pub(super) fn splat(v: [i32; 8]) -> M256 {
281+ unsafe { M256(_mm256_loadu_si256(v.as_ptr().cast())) }
282+ }
283+}
284+
168285 /// `B(a, b, angle, flip, r)` (spec 7.13.2.1): a butterfly rotation, and an
169286 /// exchange of the two entries when `flip` is set.
287+#[inline(always)]
170288 fn butterfly<T: Lane>(t: &mut [T; 64], a: usize, b: usize, angle: i32, flip: bool, _r: usize) {
171289 let (c, s) = (i64::from(cos128(angle)), i64::from(sin128(angle)));
172290 let (x, y) = T::btf(t[a], t[b], c, s);
@@ -179,6 +297,7 @@ fn butterfly<T: Lane>(t: &mut [T; 64], a: usize, b: usize, angle: i32, flip: boo
179297
180298 /// `H(a, b, flip, r)` (spec 7.13.2.1): a Hadamard rotation, with the indices
181299 /// exchanged when `flip` is set.
300+#[inline(always)]
182301 fn hadamard<T: Lane>(t: &mut [T; 64], a: usize, b: usize, flip: bool, r: usize) {
183302 let (a, b) = if flip { (b, a) } else { (a, b) };
184303 let (x, y) = T::had(t[a], t[b], r);
@@ -188,15 +307,18 @@ fn hadamard<T: Lane>(t: &mut [T; 64], a: usize, b: usize, flip: bool, r: usize)
188307
189308 /// The inverse DCT array permutation (spec 7.13.2.2): an in-place bit-reversal
190309 /// of the first `1 << n` entries.
310+#[inline(always)]
191311 fn permute<T: Lane>(t: &mut [T; 64], n: u32) {
192312 let n0 = 1usize << n;
193- // A stack copy: this ran once per 1D transform and its `Vec` was the
194- // `malloc` at the top of every `inverse_dct` frame in the annotation.
195- let mut copy = [T::ZERO; 64];
196- copy[..n0].copy_from_slice(&t[..n0]);
313+ // In place: a bit reversal is an involution, so swapping every `i` with
314+ // `brev(i) > i` visits each transposed pair once. The scratch copy this
315+ // replaces was a `[T; 64]` fill -- 2 KB per call at `T = M256`.
197316 let tab = &BREV_TAB[n as usize];
198- for (i, v) in t[..n0].iter_mut().enumerate() {
199- *v = copy[tab[i] as usize];
317+ for i in 0..n0 {
318+ let j = tab[i] as usize;
319+ if j > i {
320+ t.swap(i, j);
321+ }
200322 }
201323 }
202324
@@ -247,6 +369,11 @@ fn inverse_dct_x8(t: &mut [[i32; 8]; 64], n: u32, r: usize) {
247369 }
248370
249371 /// [`inverse_dct_fixed`] at one fixed `N = log2(size)`.
372+// `#[inline(always)]`: the AVX2 instantiation has to land INSIDE the
373+// `target_feature` wrapper, or every `_mm256_*` in it stays an out-of-line
374+// call (measured: +5.6% instructions on the 4K segment). Every other
375+// instantiation has exactly one caller, so this costs no extra copy.
376+#[inline(always)]
250377 fn inverse_dct_n<T: Lane, const N: u32>(t: &mut [T; 64], r: usize) {
251378 permute(t, N);
252379
@@ -1063,6 +1190,15 @@ pub fn inverse_transform_2d_typed_wh(
10631190 // eight scalar ones. `lr_flip` reads the columns right-to-left, which
10641191 // is not a contiguous chunk, so it stays on the scalar path below.
10651192 if col_kind == TxType1d::Dct && w >= 8 && !lr_flip {
1193+ #[cfg(target_arch = "x86_64")]
1194+ if matches!(crate::mc::simd_level(), crate::mc::SimdLevel::Avx2) {
1195+ // SAFETY: the branch above is the AVX2 feature detection.
1196+ #[allow(unsafe_code)]
1197+ unsafe {
1198+ simd::column_pass_dct(residual, &mut out, w, h, log2h, col_clamp, ud_flip);
1199+ }
1200+ return;
1201+ }
10661202 let mut t8 = [[0i32; 8]; 64];
10671203 for j in (0..w).step_by(8) {
10681204 let mut any = 0i32;
@@ -1141,7 +1277,12 @@ pub fn dequant_and_inverse_typed(
11411277 ac_delta: i32,
11421278 tx_type: TxType,
11431279 ) -> Vec<i32> {
1144- dequant_and_inverse_typed_wh(levels, side, side, bit_depth, q_idx, dc_delta, ac_delta, tx_type)
1280+ let r =
1281+ dequant_and_inverse_typed_wh(levels, side, side, bit_depth, q_idx, dc_delta, ac_delta, tx_type);
1282+ // This square entry point keeps the dense contract (its callers are the
1283+ // encoder-side model and the gates, which index the result directly);
1284+ // only the decoder's `_wh` path speaks the empty marker.
1285+ if r.is_empty() { vec![0i32; side * side] } else { r }
11451286 }
11461287
11471288 /// [`dequant_and_inverse_typed`] widened to `(w, h)` (lane-recttx). `dc_delta`/
@@ -1165,8 +1306,13 @@ pub fn dequant_and_inverse_typed_wh(
11651306 // to a zero residual, which is exactly the buffer below already returns --
11661307 // so one scan of the levels replaces the dequantization, the row pass and
11671308 // the column pass for those.
1309+ // The residual is returned EMPTY in that case, not as `w * h` zeros: an
1310+ // empty residual is this decoder's "all zero" marker (`ZERO_RESIDUAL` in
1311+ // `decode.rs`), which also drops the `vec![0; w * h]` memset here and the
1312+ // `to_vec` clone the recorded [`crate::decode::Residual`] made of it --
1313+ // together 6.5% of the 4K segment's profile (memset + memmove).
11681314 if levels.iter().all(|&l| l == 0) {
1169- return vec![0i32; w * h];
1315+ return Vec::new();
11701316 }
11711317 DQ_SCRATCH.with(|cell| {
11721318 let mut dq = cell.borrow_mut();