forge
Explore
Log in

Don't you dare go Hollow

Fuse the inter vertical pass's rounding into its kernel

Browse files at this commit

209d00389647f7e9189aee661bbfa6ddb661c658Ahmet Kaan GümüşParent: ad664df
  • perf
    • fuse the inter vertical pass's rounding into its kernel
Show full message
perf(av1): fuse the inter vertical pass's rounding into its kernel

The vertical pass stored a row of unrounded `i32` sums to a scratch
buffer that the very next loop read back to round, clamp and narrow to
the block's `u16` samples. The sums never need to reach memory:
`packus_epi32` IS the clamp's lower half (a negative sum saturates to
zero) and `min_epu16` its upper, so `round2(sum, InterRound1).clamp(0,
max)` is two instructions on the register the taps were accumulated in.

`vpass_row` keeps its unrounded form for the compound intermediate and
for restoration's wiener pass, whose roundings differ.

-1.7% instructions on the 4K segment (532.7 -> 523.7 G at one thread),
-5.3% cumulative for the lane; all four gate hashes unchanged.
crates/ec-av1/src/mc.rsmodified+236 -23
@@ -339,12 +339,20 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
339 #[cfg(target_arch = "x86_64")]339 #[cfg(target_arch = "x86_64")]
340 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract340 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
341 mod simd {341 mod simd {
342- use super::{round2, sat16, INTER_ROUND_0};342+ use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1};
343 use std::arch::x86_64::*;343 use std::arch::x86_64::*;
344 344
345 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape345 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
346 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is346 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is
347 /// `s[2j]*t_even + s[2j+1]*t_odd`, i.e. two taps of one output at once.347 /// `s[2j]*t_even + s[2j+1]*t_odd`, i.e. two taps of one output at once.
348+ #[inline]
349+ fn taps16(taps: &[i32; 8]) -> [i16; 8] {
350+ [
351+ taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
352+ taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
353+ ]
354+ }
355+
348 #[inline]356 #[inline]
349 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {357 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
350 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);358 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);
@@ -418,11 +426,7 @@ mod simd {
418 acc: &mut [i32],426 acc: &mut [i32],
419 ) {427 ) {
420 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);428 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
421- let t16 = [429+ let tp = tap_pairs(&taps16(taps));
422- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
423- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
424- ];
425- let tp = tap_pairs(&t16);
426 let ip = intermediate.as_ptr().add(row * block_w);430 let ip = intermediate.as_ptr().add(row * block_w);
427 let ap = acc.as_mut_ptr();431 let ap = acc.as_mut_ptr();
428 let mut c = 0usize;432 let mut c = 0usize;
@@ -509,6 +513,135 @@ mod simd {
509 }513 }
510 }514 }
511 515
516+ /// [`vpass_avx2`] with the output rounding fused in: the sums never reach
517+ /// memory as `i32`, they are rounded by `INTER_ROUND_1`, clamped and
518+ /// stored as the block's own `u16` samples. `packus_epi32` is the clamp's
519+ /// lower half (a negative sum saturates to 0) and `min_epu16` its upper,
520+ /// which is exactly `round2(sum, INTER_ROUND_1).clamp(0, max)`.
521+ ///
522+ /// # Safety
523+ /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
524+ /// and `dst` at least `block_w`.
525+ #[target_feature(enable = "avx2")]
526+ pub unsafe fn vpass_row_u16_avx2(
527+ intermediate: &[i16],
528+ block_w: usize,
529+ row: usize,
530+ taps: &[i32; 8],
531+ max: i32,
532+ dst: &mut [u16],
533+ ) {
534+ debug_assert!(intermediate.len() >= (row + 8) * block_w && dst.len() >= block_w);
535+ let tp = tap_pairs(&taps16(taps));
536+ let ip = intermediate.as_ptr().add(row * block_w);
537+ let dp = dst.as_mut_ptr();
538+ let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_1 - 1));
539+ let mx = _mm256_set1_epi16(max as i16);
540+ let mut c = 0usize;
541+ while c + 16 <= block_w {
542+ let mut lo = rnd;
543+ let mut hi = rnd;
544+ for k in 0..4 {
545+ if tp[k] == 0 {
546+ continue;
547+ }
548+ let tv = _mm256_set1_epi32(tp[k]);
549+ let a = _mm256_loadu_si256(ip.add(2 * k * block_w + c).cast());
550+ let b = _mm256_loadu_si256(ip.add((2 * k + 1) * block_w + c).cast());
551+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
552+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
553+ }
554+ lo = _mm256_srai_epi32(lo, INTER_ROUND_1 as i32);
555+ hi = _mm256_srai_epi32(hi, INTER_ROUND_1 as i32);
556+ // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
557+ // per lane in order, so this is c..c+16 in order.
558+ let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
559+ _mm256_storeu_si256(dp.add(c).cast(), v);
560+ c += 16;
561+ }
562+ vpass_u16_tail_sse(ip, block_w, &tp, taps, max, dp, c);
563+ }
564+
565+ /// [`vpass_row_u16_avx2`]'s 8- and 4-column steps (SSE4.1 for
566+ /// `packus_epi32`), and the scalar remainder.
567+ ///
568+ /// # Safety
569+ /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
570+ #[target_feature(enable = "sse4.1")]
571+ unsafe fn vpass_u16_tail_sse(
572+ ip: *const i16,
573+ block_w: usize,
574+ tp: &[i32; 4],
575+ taps: &[i32; 8],
576+ max: i32,
577+ dp: *mut u16,
578+ mut c: usize,
579+ ) {
580+ let rnd = _mm_set1_epi32(1 << (INTER_ROUND_1 - 1));
581+ let mx = _mm_set1_epi16(max as i16);
582+ while c + 4 <= block_w {
583+ let wide = c + 8 <= block_w;
584+ let mut lo = rnd;
585+ let mut hi = rnd;
586+ for k in 0..4 {
587+ if tp[k] == 0 {
588+ continue;
589+ }
590+ let tv = _mm_set1_epi32(tp[k]);
591+ let (pa, pb) = (ip.add(2 * k * block_w + c), ip.add((2 * k + 1) * block_w + c));
592+ let (a, b) = if wide {
593+ (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast()))
594+ } else {
595+ (_mm_loadl_epi64(pa.cast()), _mm_loadl_epi64(pb.cast()))
596+ };
597+ lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
598+ if wide {
599+ hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
600+ }
601+ }
602+ let v = _mm_min_epu16(
603+ _mm_packus_epi32(_mm_srai_epi32(lo, INTER_ROUND_1 as i32), _mm_srai_epi32(hi, INTER_ROUND_1 as i32)),
604+ mx,
605+ );
606+ if wide {
607+ _mm_storeu_si128(dp.add(c).cast(), v);
608+ c += 8;
609+ } else {
610+ _mm_storel_epi64(dp.add(c).cast(), v);
611+ c += 4;
612+ }
613+ }
614+ while c < block_w {
615+ let mut sum = 0i32;
616+ for (t, &tap) in taps.iter().enumerate() {
617+ sum += tap * i32::from(*ip.add(t * block_w + c));
618+ }
619+ *dp.add(c) = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
620+ c += 1;
621+ }
622+ }
623+
624+ /// [`vpass_row_u16_avx2`] without the 16-column step.
625+ ///
626+ /// # Safety
627+ /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
628+ #[target_feature(enable = "sse4.1")]
629+ pub unsafe fn vpass_row_u16_sse41(
630+ intermediate: &[i16],
631+ block_w: usize,
632+ row: usize,
633+ taps: &[i32; 8],
634+ max: i32,
635+ dst: &mut [u16],
636+ ) {
637+ debug_assert!(intermediate.len() >= (row + 8) * block_w && dst.len() >= block_w);
638+ let tp = tap_pairs(&taps16(taps));
639+ vpass_u16_tail_sse(
640+ intermediate.as_ptr().add(row * block_w), block_w, &tp, taps, max,
641+ dst.as_mut_ptr(), 0,
642+ );
643+ }
644+
512 /// Vertical pass, SSE2: [`vpass_avx2`] without the 16-column step.645 /// Vertical pass, SSE2: [`vpass_avx2`] without the 16-column step.
513 ///646 ///
514 /// # Safety647 /// # Safety
@@ -521,11 +654,7 @@ mod simd {
521 acc: &mut [i32],654 acc: &mut [i32],
522 ) {655 ) {
523 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);656 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
524- let t16 = [657+ let tp = tap_pairs(&taps16(taps));
525- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
526- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
527- ];
528- let tp = tap_pairs(&t16);
529 vpass_tail_sse(intermediate.as_ptr().add(row * block_w), block_w, &tp, taps, acc.as_mut_ptr(), 0);658 vpass_tail_sse(intermediate.as_ptr().add(row * block_w), block_w, &tp, taps, acc.as_mut_ptr(), 0);
530 }659 }
531 660
@@ -681,6 +810,59 @@ pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, row: usize, taps:
681 vpass_row_scalar(intermediate, block_w, row, taps, acc);810 vpass_row_scalar(intermediate, block_w, row, taps, acc);
682 }811 }
683 812
813+/// lane-mc: [`vpass_row`] with the output rounding fused in, for the two
814+/// entry points whose destination is `u16` samples. The unrounded `i32` sums
815+/// used to be stored to a scratch row and read straight back by a rounding
816+/// loop; here they never leave the register.
817+#[inline]
818+#[allow(unsafe_code)]
819+fn vpass_row_u16(
820+ intermediate: &[i16],
821+ block_w: usize,
822+ row: usize,
823+ taps: &[i32; 8],
824+ max: i32,
825+ dst: &mut [u16],
826+) {
827+ #[cfg(target_arch = "x86_64")]
828+ {
829+ match simd_level() {
830+ // SAFETY: the arm is reached only when the CPU reports the
831+ // feature; the kernel reads `intermediate[(row+t)*block_w ..
832+ // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which
833+ // the debug asserts pin.
834+ SimdLevel::Avx2 => {
835+ unsafe { simd::vpass_row_u16_avx2(intermediate, block_w, row, taps, max, dst) };
836+ return;
837+ }
838+ SimdLevel::Sse41 => {
839+ unsafe { simd::vpass_row_u16_sse41(intermediate, block_w, row, taps, max, dst) };
840+ return;
841+ }
842+ SimdLevel::Scalar => {}
843+ }
844+ }
845+ vpass_row_u16_scalar(intermediate, block_w, row, taps, max, dst);
846+}
847+
848+/// The scalar reference for [`vpass_row_u16`].
849+fn vpass_row_u16_scalar(
850+ intermediate: &[i16],
851+ block_w: usize,
852+ row: usize,
853+ taps: &[i32; 8],
854+ max: i32,
855+ dst: &mut [u16],
856+) {
857+ for (c, d) in dst[..block_w].iter_mut().enumerate() {
858+ let mut sum = 0i32;
859+ for (t, &tap) in taps.iter().enumerate() {
860+ sum += tap * i32::from(intermediate[(row + t) * block_w + c]);
861+ }
862+ *d = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
863+ }
864+}
865+
684 /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).866 /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).
685 fn vpass_row_scalar(intermediate: &[i16], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {867 fn vpass_row_scalar(intermediate: &[i16], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
686 acc[..block_w].fill(0);868 acc[..block_w].fill(0);
@@ -917,7 +1099,7 @@ pub(crate) fn predict_with_filters_kern(
917 // block's own first row where the pass would have put the 4th.1099 // block's own first row where the pass would have put the 4th.
918 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1100 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
919 let max = crate::decode::sample_max(fctx);1101 let max = crate::decode::sample_max(fctx);
920- with_scratch(rows, block_w, |intermediate, acc| {1102+ with_scratch(rows, block_w, |intermediate, _acc| {
921 horizontal_pass_unscaled(1103 horizontal_pass_unscaled(
922 reference, stride, true_width, true_height, x0,1104 reference, stride, true_width, true_height, x0,
923 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,1105 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
@@ -930,10 +1112,10 @@ pub(crate) fn predict_with_filters_kern(
930 return;1112 return;
931 }1113 }
932 for row in 0..block_h {1114 for row in 0..block_h {
933- vpass_row(intermediate, block_w, row, v_filter, acc);1115+ vpass_row_u16(
934- for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {1116+ intermediate, block_w, row, v_filter, max,
935- *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;1117+ &mut dst[row * block_w..(row + 1) * block_w],
936- }1118+ );
937 }1119 }
938 });1120 });
939 1121
@@ -1207,7 +1389,7 @@ pub(crate) fn predict_scaled_kern(
1207 1389
1208 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1390 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1209 let max = crate::decode::sample_max(fctx);1391 let max = crate::decode::sample_max(fctx);
1210- with_scratch(rows, block_w, |intermediate, acc| {1392+ with_scratch(rows, block_w, |intermediate, _acc| {
1211 horizontal_pass(1393 horizontal_pass(
1212 reference, stride, true_width, true_height, x_q4,1394 reference, stride, true_width, true_height, x_q4,
1213 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,1395 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
@@ -1220,10 +1402,10 @@ pub(crate) fn predict_scaled_kern(
1220 return;1402 return;
1221 }1403 }
1222 for row in 0..block_h {1404 for row in 0..block_h {
1223- vpass_row(intermediate, block_w, row, v_filter, acc);1405+ vpass_row_u16(
1224- for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {1406+ intermediate, block_w, row, v_filter, max,
1225- *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;1407+ &mut dst[row * block_w..(row + 1) * block_w],
1226- }1408+ );
1227 }1409 }
1228 });1410 });
1229 }1411 }
@@ -2015,7 +2197,7 @@ mod tests {
2015 for table in [wide, narrow] {2197 for table in [wide, narrow] {
2016 for frac in 0..16usize {2198 for frac in 0..16usize {
2017 let taps = &table[frac];2199 let taps = &table[frac];
2018- for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {2200+ for w in [4usize, 5, 8, 12, 16, 20, 32, 64, 128] {
2019 let rows = 12usize;2201 let rows = 12usize;
2020 let inter: Vec<i16> = (0..rows * w)2202 let inter: Vec<i16> = (0..rows * w)
2021 .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)2203 .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
@@ -2039,6 +2221,37 @@ mod tests {
2039 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");2221 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");
2040 }2222 }
2041 }2223 }
2224+ // lane-mc: the rounding-fused form, over both
2225+ // sample maxima this decoder accepts -- its
2226+ // `packus`/`min_epu16` pair must reproduce
2227+ // `round2(_, InterRound1).clamp(0, max)`.
2228+ for max in [255i32, 1023] {
2229+ let mut want_u16 = vec![0u16; w];
2230+ super::vpass_row_u16_scalar(&inter, w, row, taps, max, &mut want_u16);
2231+ for (d, &a) in want_u16.iter().zip(want.iter()) {
2232+ assert_eq!(
2233+ i32::from(*d),
2234+ super::round2(a, super::INTER_ROUND_1).clamp(0, max),
2235+ "the fused reference is the two-step one"
2236+ );
2237+ }
2238+ let mut got_u16 = vec![0u16; w];
2239+ super::vpass_row_u16(&inter, w, row, taps, max, &mut got_u16);
2240+ assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}");
2241+ #[cfg(target_arch = "x86_64")]
2242+ {
2243+ if std::arch::is_x86_feature_detected!("sse4.1") {
2244+ let mut sse = vec![0u16; w];
2245+ unsafe { super::simd::vpass_row_u16_sse41(&inter, w, row, taps, max, &mut sse) };
2246+ assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}");
2247+ }
2248+ if std::arch::is_x86_feature_detected!("avx2") {
2249+ let mut avx = vec![0u16; w];
2250+ unsafe { super::simd::vpass_row_u16_avx2(&inter, w, row, taps, max, &mut avx) };
2251+ assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}");
2252+ }
2253+ }
2254+ }
2042 checked += 1;2255 checked += 1;
2043 }2256 }
2044 }2257 }
@@ -2046,6 +2259,6 @@ mod tests {
2046 }2259 }
2047 }2260 }
2048 }2261 }
2049- assert_eq!(checked, 3 * 4 * 2 * 16 * 8 * 3);2262+ assert_eq!(checked, 3 * 4 * 2 * 16 * 9 * 3);
2050 }2263 }
2051 }2264 }