forge
Explore
Log in

Don't you dare go Hollow

Sgrproj box sums in i32 over a contiguous row, (A,B) map under AVX2

Browse files at this commit

9c6f09fb9a7d86ad0463ed89c7e4559e70a5fa36Ahmet Kaan GümüşParent: 8cdbcf4
  • perf
    • sgrproj box sums in i32 over a contiguous row, (A,B) map under AVX2
Show full message
perf(av1): sgrproj box sums in i32 over a contiguous row, (A,B) map under AVX2

`compute_ab` fetched every window sample through `lr_sample` -- a
stripe-boundary decision plus a column clamp per element -- and carried
both box sums as `i64`. A sample is at most `2^bd - 1 <= 4095`, so the
widest window sum of squares is `25 * 4095^2 == 419M`: the sums fit `i32`
with room to spare, and the column clamp is a pure function of the
column, so one contiguous per-row copy with the plane edge replicated
serves the whole accumulate pass branch-free.

On top of that the per-grid-point `(A[k], B[k])` map -- the part a
previous lane measured as the real cost -- becomes a straight-line pass
over two row arrays, so it runs eight points at a time under AVX2:
lane-wise the same arithmetic, with the only two products that exceed 32
bits (`p * s` and `(256 - A) * one_by_x * b`) formed in 64-bit even/odd
halves and packed back after their rounding shift, and `av1_x_by_xplus1`
read by gather. `ab_point` stays the scalar reference for the tail and
for every non-AVX2 target.

Byte-exact: all four gate streams hash identically to the parent at 1 and
4 threads. instructions:u on the 4K restoration segment 602.650 G ->
597.501 G (-0.86%; -0.29% from the sums, -0.57% from the AVX2 map).
crates/ec-av1/src/restoration.rsmodified+213 -52
@@ -745,91 +745,252 @@ fn compute_ab(
745 let gh = h + 2;745 let gh = h + 2;
746 ab.clear();746 ab.clear();
747 ab.resize(gw * gh, (0i32, 0i64));747 ab.resize(gw * gh, (0i32, 0i64));
748- let n = ((2 * r + 1) * (2 * r + 1)) as i64;748+ let n = ((2 * r + 1) * (2 * r + 1)) as i32;
749 // lane-perf6: the box sums are separable. Summing every grid point's own749 // lane-perf6: the box sums are separable. Summing every grid point's own
750 // (2r+1)^2 window called `lr_sample` -- whose stripe-boundary test is the750 // (2r+1)^2 window called `lr_sample` -- whose stripe-boundary test is the
751 // expensive part -- (2r+1) times more often than needed; one column-sum751 // expensive part -- (2r+1) times more often than needed; one column-sum
752 // pass per grid row reads each source sample once per row instead, and752 // pass per grid row reads each source sample once per row instead, and
753- // the horizontal sum is then (2r+1) adds of i64s. Integer addition is753+ // the horizontal sum is then (2r+1) adds.
754- // exact and associative, so the totals are unchanged bit for bit.
755 let ru = r as usize;754 let ru = r as usize;
756 let ncols = gw + 2 * ru;755 let ncols = gw + 2 * ru;
757- let mut col_a = vec![0i64; ncols];756+ // lane-sgr: `i32` sums. A sample is at most `2^bd - 1 <= 4095`, so the
758- let mut col_b = vec![0i64; ncols];757+ // widest possible window sum of squares is `25 * 4095^2 == 419M` and the
758+ // widest plain sum `25 * 4095 == 102k`: both far inside `i32`, and every
759+ // downstream product is either kept in `i64` (the two that need it) or
760+ // likewise bounded (`a_s * n <= 25 * 25 * 65025 / 16`). Halving the
761+ // accumulator width is what lets the row loops below vectorise.
762+ debug_assert!(crate::decode::sample_max(fctx) <= 4095);
763+ debug_assert!(s > 0);
764+ let mut sums = vec![0i32; 2 * ncols + 2 * gw];
765+ let (col_a, rest) = sums.split_at_mut(ncols);
766+ let (col_b, rest) = rest.split_at_mut(ncols);
767+ // lane-sgr: the sliding horizontal sums are laid down as two rows first,
768+ // so the `(A, B)` map over them is a straight-line pass `ab_row` can run
769+ // eight points at a time.
770+ let (a_row, b_row) = rest.split_at_mut(gw);
771+ // lane-sgr: one contiguous copy of the source row's whole footprint, with
772+ // the column clamp (edge replication) applied while filling, so the
773+ // accumulate loops below are branch-free over a plain slice instead of a
774+ // `lr_sample` call -- clamp included -- per element.
775+ let mut samp = vec![0u16; ncols];
759 // Hoisted out of the per-point body: one thread-local read per call.776 // Hoisted out of the per-point body: one thread-local read per call.
760 let bd_shift = u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);777 let bd_shift = u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
761 let base_col = h_start as i64 - 1 - r as i64;778 let base_col = h_start as i64 - 1 - r as i64;
779+ let dump = crate::envflags::env_flag!("EC_LR_CALL_DUMP");
780+ let one_by_x = SGR_ONE_BY_X[(n - 1) as usize] as i64;
762 // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s781 // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s
763 // window is row `gi`'s minus its top source row plus one new bottom row,782 // window is row `gi`'s minus its top source row plus one new bottom row,
764 // so each source sample is read once per grid row instead of (2r+1)783 // so each source sample is read once per grid row instead of (2r+1)
765 // times -- the same exactness argument as the separable split above784 // times -- the same exactness argument as the separable split above
766- // (i64 addition is associative, and subtracting a row that was added is785+ // (integer addition is associative, and subtracting a row that was added
767- // exact), and `lr_sample`'s stripe-boundary test, which is what makes a786+ // is exact), and `lr_sample`'s stripe-boundary test, which is what makes
768- // sample read expensive, is a pure function of `(row, col)`.787+ // a sample read expensive, is a pure function of `(row, col)`.
769 for gi in 0..gh {788 for gi in 0..gh {
770 let i = gi as i64 - 1;789 let i = gi as i64 - 1;
771 {790 {
772- let mut accumulate = |row: i64, sign: i64| {791+ let mut accumulate = |row: i64, add: bool| {
773- for k in 0..ncols {792+ let src =
774- let px = lr_sample(793+ lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row);
775- cdef,794+ fill_clamped_row(src, plane_w, base_col, &mut samp);
776- deblocked,795+ if add {
777- stride,796+ for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter())
778- plane_w,797+ {
779- plane_h,798+ let px = i32::from(px);
780- v_start,799+ *c_a += px * px;
781- v_end,800+ *c_b += px;
782- row,801+ }
783- base_col + k as i64,802+ } else {
784- ) as i64;803+ for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter())
785- col_a[k] += sign * px * px;804+ {
786- col_b[k] += sign * px;805+ let px = i32::from(px);
806+ *c_a -= px * px;
807+ *c_b -= px;
808+ }
787 }809 }
788 };810 };
789 if gi == 0 {811 if gi == 0 {
790 for dr in -r..=r {812 for dr in -r..=r {
791- accumulate(v_start as i64 + i + dr as i64, 1);813+ accumulate(v_start as i64 + i + dr as i64, true);
792 }814 }
793 } else {815 } else {
794- accumulate(v_start as i64 + i - 1 - r as i64, -1);816+ accumulate(v_start as i64 + i - 1 - r as i64, false);
795- accumulate(v_start as i64 + i + r as i64, 1);817+ accumulate(v_start as i64 + i + r as i64, true);
796 }818 }
797 }819 }
798 // The horizontal sum slides the same way (one add and one subtract820 // The horizontal sum slides the same way (one add and one subtract
799 // per grid point instead of 2r+1 adds).821 // per grid point instead of 2r+1 adds).
800- let mut a = col_a[..2 * ru + 1].iter().sum::<i64>();822+ let mut a = col_a[..2 * ru + 1].iter().sum::<i32>();
801- let mut b = col_b[..2 * ru + 1].iter().sum::<i64>();823+ let mut b = col_b[..2 * ru + 1].iter().sum::<i32>();
802 for gj in 0..gw {824 for gj in 0..gw {
803- let j = gj as i64 - 1;
804 if gj > 0 {825 if gj > 0 {
805 a += col_a[gj + 2 * ru] - col_a[gj - 1];826 a += col_a[gj + 2 * ru] - col_a[gj - 1];
806 b += col_b[gj + 2 * ru] - col_b[gj - 1];827 b += col_b[gj + 2 * ru] - col_b[gj - 1];
807 }828 }
808- // libaom `restoration.c:660` -- the box sums are brought back829+ a_row[gj] = a;
809- // to the 8-bit scale before `p` is formed (`a` is a sum of830+ b_row[gj] = b;
810- // squares, so it loses twice the shift `b` does); `B[k]` below831+ }
811- // keeps the RAW `b`, only `p` uses the scaled pair. At 8-bit832+ ab_row(a_row, b_row, n, s, bd_shift, one_by_x, &mut ab[gi * gw..gi * gw + gw]);
812- // both shifts are 0, which is why this was invisible until now.833+ let dump_gj = 6i64 - h_start as i64 + 1;
813- let a_s = round2(a, 2 * bd_shift);834+ if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) {
814- let b_s = round2(b, bd_shift);835+ let gj = dump_gj as usize;
815- let p = if a_s * n < b_s * b_s { 0 } else { a_s * n - b_s * b_s };836+ let (a, b) = (a_row[gj], b_row[gj]);
816- let z = round2(p * s as i64, SGRPROJ_MTABLE_BITS).clamp(0, 255) as usize;837+ let a_s = round2_u31(a, 2 * bd_shift);
817- let a_val = SGR_X_BY_XPLUS1[z];838+ let b_s = round2_u31(b, bd_shift);
818- let b_val = round2(839+ let p = (a_s * n - b_s * b_s).max(0);
819- (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64,840+ let z = z_index(p, s);
820- SGRPROJ_RECIP_BITS,841+ let (a_val, b_val) = ab[gi * gw + gj];
842+ eprintln!(
843+ "EC_LR_CALL_DUMP compute_ab u_tap: r={r} s={s} n={n} box_a={a} box_b={b} \
844+ p={p} z={z} a_val={a_val} b_val={b_val}"
821 );845 );
822- if crate::envflags::env_flag!("EC_LR_CALL_DUMP")846+ }
823- && v_start as i64 + i == 60847+ }
824- && h_start as i64 + j == 6848+}
825- && r == 1849+
826- {850+/// `z = Round2(p * s, SGRPROJ_MTABLE_BITS)` clamped to the
827- eprintln!(851+/// [`SGR_X_BY_XPLUS1`] domain -- the one product that does not fit 32 bits.
828- "EC_LR_CALL_DUMP compute_ab u_tap: r={r} s={s} n={n} box_a={a} box_b={b} \852+#[inline]
829- p={p} z={z} a_val={a_val} b_val={b_val}"853+fn z_index(p: i32, s: i32) -> usize {
830- );854+ ((i64::from(p) * i64::from(s) + (1 << (SGRPROJ_MTABLE_BITS - 1))) >> SGRPROJ_MTABLE_BITS)
855+ .clamp(0, 255) as usize
856+}
857+
858+/// One grid point's `(A[k], B[k])` from its two box sums -- libaom
859+/// `restoration.c:660..672`, and the reference every [`ab_row`] arm matches.
860+#[inline]
861+fn ab_point(a: i32, b: i32, n: i32, s: i32, bd_shift: u32, one_by_x: i64) -> (i32, i64) {
862+ // libaom `restoration.c:660` -- the box sums are brought back to the
863+ // 8-bit scale before `p` is formed (`a` is a sum of squares, so it loses
864+ // twice the shift `b` does); `B[k]` keeps the RAW `b`, only `p` uses the
865+ // scaled pair. At 8-bit both shifts are 0, which is why this was
866+ // invisible until now.
867+ let a_s = round2_u31(a, 2 * bd_shift);
868+ let b_s = round2_u31(b, bd_shift);
869+ let p = (a_s * n - b_s * b_s).max(0);
870+ let a_val = SGR_X_BY_XPLUS1[z_index(p, s)];
871+ let b_val = round2((256 - a_val) as i64 * i64::from(b) * one_by_x, SGRPROJ_RECIP_BITS);
872+ (a_val, b_val)
873+}
874+
875+/// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time
876+/// under AVX2 (the kernel is that arithmetic lane-wise, same widths).
877+fn ab_row(
878+ a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i64,
879+ out: &mut [(i32, i64)],
880+) {
881+ let mut done = 0usize;
882+ #[cfg(target_arch = "x86_64")]
883+ #[allow(unsafe_code)]
884+ {
885+ if matches!(crate::mc::simd_level(), crate::mc::SimdLevel::Avx2) {
886+ // SAFETY: the arm is reached only when the CPU reports avx2, and
887+ // the kernel touches `8 * (out.len() / 8)` elements of each of
888+ // the three equally long slices.
889+ done = unsafe {
890+ sgr_simd::ab_row_avx2(a_row, b_row, n, s, bd_shift, one_by_x as i32, out)
891+ };
892+ }
893+ }
894+ for gj in done..out.len() {
895+ out[gj] = ab_point(a_row[gj], b_row[gj], n, s, bd_shift, one_by_x);
896+ }
897+}
898+
899+/// [`ab_row`]'s AVX2 kernel.
900+#[cfg(target_arch = "x86_64")]
901+#[allow(unsafe_code)]
902+#[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
903+mod sgr_simd {
904+ use super::{SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS, SGR_X_BY_XPLUS1};
905+ use std::arch::x86_64::*;
906+
907+ /// Eight grid points of `super::ab_point` per iteration, returning how
908+ /// many points were written (a multiple of 8; the tail stays scalar).
909+ ///
910+ /// # Safety
911+ /// Requires AVX2. Every lane repeats the scalar arithmetic at the widths
912+ /// `compute_ab` proves: `a, b >= 0` and `s > 0`, `p < 2^26`,
913+ /// `p * s < 2^38`, `(256 - A) * one_by_x < 2^21` and that times
914+ /// `b < 2^17` is `< 2^38` -- so the two 64-bit products below lose no
915+ /// bit, and the unsigned `mul_epu32` sees no negative operand.
916+ #[target_feature(enable = "avx2")]
917+ #[allow(clippy::too_many_arguments)]
918+ pub unsafe fn ab_row_avx2(
919+ a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i32,
920+ out: &mut [(i32, i64)],
921+ ) -> usize {
922+ let len = out.len().min(a_row.len()).min(b_row.len());
923+ let nv = _mm256_set1_epi32(n);
924+ let sv = _mm256_set1_epi32(s);
925+ let obx = _mm256_set1_epi32(one_by_x);
926+ let c255 = _mm256_set1_epi32(255);
927+ let c256 = _mm256_set1_epi32(256);
928+ let zero = _mm256_setzero_si256();
929+ let rnd_z = _mm256_set1_epi64x(1 << (SGRPROJ_MTABLE_BITS - 1));
930+ let rnd_b = _mm256_set1_epi64x(1 << (SGRPROJ_RECIP_BITS - 1));
931+ let sh_z = _mm_cvtsi32_si128(SGRPROJ_MTABLE_BITS as i32);
932+ let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32);
933+ let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32);
934+ let sh_bd = _mm_cvtsi32_si128(bd_shift as i32);
935+ let rnd_a = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (2 * bd_shift - 1) });
936+ let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (bd_shift - 1) });
937+ let mut av = [0i32; 8];
938+ let mut bv = [0i32; 8];
939+ let mut gj = 0usize;
940+ while gj + 8 <= len {
941+ let a = _mm256_loadu_si256(a_row.as_ptr().add(gj).cast());
942+ let b = _mm256_loadu_si256(b_row.as_ptr().add(gj).cast());
943+ let a_s = _mm256_srl_epi32(_mm256_add_epi32(a, rnd_a), sh_a);
944+ let b_s = _mm256_srl_epi32(_mm256_add_epi32(b, rnd_bd), sh_bd);
945+ let p = _mm256_max_epi32(
946+ _mm256_sub_epi32(_mm256_mullo_epi32(a_s, nv), _mm256_mullo_epi32(b_s, b_s)),
947+ zero,
948+ );
949+ let z = _mm256_min_epi32(mul_shift(p, sv, rnd_z, sh_z), c255);
950+ let a_val = _mm256_i32gather_epi32(SGR_X_BY_XPLUS1.as_ptr(), z, 4);
951+ let t = _mm256_mullo_epi32(_mm256_sub_epi32(c256, a_val), obx);
952+ let b_val = mul_shift(t, b, rnd_b, sh_b);
953+ _mm256_storeu_si256(av.as_mut_ptr().cast(), a_val);
954+ _mm256_storeu_si256(bv.as_mut_ptr().cast(), b_val);
955+ for k in 0..8 {
956+ out[gj + k] = (av[k], i64::from(bv[k]));
831 }957 }
832- ab[gi * gw + gj] = (a_val, b_val);958+ gj += 8;
959+ }
960+ gj
961+ }
962+
963+ /// `Round2(x * y, shift)` lane-wise for eight non-negative `i32` lanes,
964+ /// with the product formed in 64 bits (even and odd lanes separately,
965+ /// `mul_epu32`) and packed back once the shift makes it fit again.
966+ #[target_feature(enable = "avx2")]
967+ unsafe fn mul_shift(x: __m256i, y: __m256i, rnd: __m256i, shift: __m128i) -> __m256i {
968+ let ev = _mm256_mul_epu32(x, y);
969+ let od = _mm256_mul_epu32(_mm256_srli_epi64(x, 32), _mm256_srli_epi64(y, 32));
970+ let ev = _mm256_srl_epi64(_mm256_add_epi64(ev, rnd), shift);
971+ let od = _mm256_srl_epi64(_mm256_add_epi64(od, rnd), shift);
972+ _mm256_blend_epi32(ev, _mm256_slli_epi64(od, 32), 0b1010_1010)
973+ }
974+}
975+
976+/// `Round2` for the non-negative box sums (same value as [`round2`], one
977+/// width narrower).
978+#[inline]
979+fn round2_u31(value: i32, shift: u32) -> i32 {
980+ if shift == 0 { value } else { (value + (1 << (shift - 1))) >> shift }
981+}
982+
983+/// Copies one source row's `out.len()` samples starting at `base_col` into a
984+/// contiguous scratch, replicating the plane's edge sample outside
985+/// `[0, plane_w)` -- exactly the clamp [`lr_sample`] applies per element.
986+#[inline]
987+fn fill_clamped_row(src: &[u16], plane_w: usize, base_col: i64, out: &mut [u16]) {
988+ let ncols = out.len();
989+ if base_col >= 0 && base_col as usize + ncols <= plane_w {
990+ out.copy_from_slice(&src[base_col as usize..base_col as usize + ncols]);
991+ } else {
992+ for (k, o) in out.iter_mut().enumerate() {
993+ *o = src[(base_col + k as i64).clamp(0, plane_w as i64 - 1) as usize];
833 }994 }
834 }995 }
835 }996 }