forge
Explore
Log in

Don't you dare go Hollow

Inline the temporal-MV probe and shrink the tpl cell, -0.4% parse instructions

Browse files at this commit

ac2315576e9297ea853e1d1b6f815fbe796f24eeAhmet Kaan GümüşParent: a263e1e
  • perf
    • inline the temporal-MV probe and shrink the tpl cell, -0.4% parse instructions
Show full message
perf(av1): inline the temporal-MV probe and shrink the tpl cell, -0.4% parse instructions

The mv-stack builders' temporal-MV sample was a closure LLVM would not
inline into either builder (both far past its size threshold), so it was
emitted as a real function -- find_mv_stack_with_sign_bias::{closure#1}
and find_mv_stack_compound::{closure#1}, together 3.5% of the parse
thread -- and every one of the up-to-19 probes per inter block paid a
call plus the argument shuffle. Making it an #[inline(always)] free
function with the EC_TRACE_TPL dump split off #[cold] removes both
symbols (-0.26% instructions).

motion_field_projection re-derived two of libaom's three pos_valid terms
for every one of a 4K field's 129600 cells per direction although
neither depends on the cell; they are now one early return and one
per-ref table, and the cell walk reads contiguous row slices instead of
a bounds-checked accessor (-0.13%).

The projected tpl cell dropped its Option tag: the projection only ever
stores a strictly positive ref_frame_offset, so 0 already is libaom's
own 'never projected' marker, and the tag cost 8 bytes per cell (20 vs
12) over a field that is 2.6 MB at 4K.

Byte-exact: 12/12 gate hashes at 1, 4 and 16 threads.
crates/ec-av1/src/motion_field.rsmodified+64 -27
@@ -94,24 +94,29 @@ impl MotionField {
94 pub(crate) fn cells_mut(&mut self) -> (usize, usize, &mut [Option<SavedMv>]) {94 pub(crate) fn cells_mut(&mut self) -> (usize, usize, &mut [Option<SavedMv>]) {
95 (self.cols, self.rows, &mut self.cells)95 (self.cols, self.rows, &mut self.cells)
96 }96 }
97-
98- fn get(&self, row8: usize, col8: usize) -> Option<SavedMv> {
99- if row8 < self.rows && col8 < self.cols {
100- self.cells[row8 * self.cols + col8]
101- } else {
102- None
103- }
104- }
105 }97 }
106 98
99+/// lane-mvstack3: one 8x8 temporal-MV cell -- the projected `(mv,
100+/// ref_frame_offset)` pair. `motion_field_projection` writes a cell only
101+/// with a STRICTLY POSITIVE `ref_frame_offset` (its own `pos_valid` test),
102+/// so `0` is exactly libaom's own "this `tpl_mvs` entry was never projected"
103+/// marker and the `Option` tag this used to carry was redundant: it cost 8
104+/// bytes per cell (20 vs 12) over a field that is 2.6 MB at 4K, read up to
105+/// 19 times per inter block.
106+pub(crate) type TplCell = ((i32, i32), i32);
107+
108+/// An unprojected [`TplCell`].
109+const TPL_EMPTY: TplCell = ((0, 0), 0);
110+
107 /// The current frame's projected temporal motion field (spec 7.9.2's111 /// The current frame's projected temporal motion field (spec 7.9.2's
108-/// `MotionFieldMvs`): one projected `(mv, ref_frame_offset)` per 8x8 cell,112+/// `MotionFieldMvs`): one projected [`TplCell`] per 8x8 cell, its
109-/// `None` where no source candidate landed (libaom's `INVALID_MV`).113+/// `ref_frame_offset` left at `0` where no source candidate landed
114+/// (libaom's `INVALID_MV`).
110 #[derive(Clone, Debug)]115 #[derive(Clone, Debug)]
111 pub struct TplField {116 pub struct TplField {
112 cols: usize,117 cols: usize,
113 rows: usize,118 rows: usize,
114- cells: Vec<Option<((i32, i32), i32)>>,119+ cells: Vec<TplCell>,
115 }120 }
116 121
117 impl TplField {122 impl TplField {
@@ -119,7 +124,7 @@ impl TplField {
119 /// actually filled -- an empty field means every temporal candidate is124 /// actually filled -- an empty field means every temporal candidate is
120 /// silently absent while the entropy stream still matches.125 /// silently absent while the entropy stream still matches.
121 pub fn filled_cells(&self) -> usize {126 pub fn filled_cells(&self) -> usize {
122- self.cells.iter().filter(|c| c.is_some()).count()127+ self.cells.iter().filter(|c| c.1 != 0).count()
123 }128 }
124 129
125 }130 }
@@ -250,7 +255,7 @@ fn motion_field_projection(
250 mi_rows: usize,255 mi_rows: usize,
251 mi_cols: usize,256 mi_cols: usize,
252 dir: u8,257 dir: u8,
253- tpl_cells: &mut [Option<((i32, i32), i32)>],258+ tpl_cells: &mut [TplCell],
254 ) -> bool {259 ) -> bool {
255 // libaom's own first two `return 0`s, in order: a key/intra-only start260 // libaom's own first two `return 0`s, in order: a key/intra-only start
256 // frame is never projected (and so never spends a `ref_stamp` slot --261 // frame is never projected (and so never spends a `ref_stamp` slot --
@@ -281,26 +286,38 @@ fn motion_field_projection(
281 )286 )
282 }287 }
283 });288 });
289+ // lane-mvstack3: two of libaom's three `pos_valid` terms do not depend on
290+ // the cell at all -- `start_to_current` is one value for the whole field,
291+ // and a reference's own offset is one value per `ref_frame` -- so fold
292+ // them into a per-ref table read once instead of re-deriving them for
293+ // every 8x8 cell (a 4K field is 129600 of them, per direction, per
294+ // frame). Same terms, same order of rejection.
295+ if start_to_current.abs() > MAX_FRAME_DISTANCE {
296+ return true;
297+ }
298+ let ref_valid: [bool; 8] =
299+ std::array::from_fn(|rf| ref_offset[rf] > 0 && ref_offset[rf] <= MAX_FRAME_DISTANCE);
300+ let cols = start.cols;
284 for row8 in 0..start.rows {301 for row8 in 0..start.rows {
285- for col8 in 0..start.cols {302+ // The row is contiguous, so walk it as a slice: `MotionField::get`'s
286- let Some(saved) = start.get(row8, col8) else {303+ // per-cell bounds test is the same test the loop bounds already make.
304+ let row = &start.cells[row8 * cols..][..cols];
305+ for (col8, cell) in row.iter().enumerate() {
306+ let Some(saved) = *cell else {
287 continue;307 continue;
288 };308 };
289 if saved.ref_frame <= 0 {309 if saved.ref_frame <= 0 {
290 continue;310 continue;
291 }311 }
292 let ref_frame_offset = ref_offset[saved.ref_frame as usize];312 let ref_frame_offset = ref_offset[saved.ref_frame as usize];
293- let pos_valid = ref_frame_offset.abs() <= MAX_FRAME_DISTANCE313+ if !ref_valid[saved.ref_frame as usize] {
294- && ref_frame_offset > 0
295- && start_to_current.abs() <= MAX_FRAME_DISTANCE;
296- if !pos_valid {
297 continue;314 continue;
298 }315 }
299 let projected = get_mv_projection(saved.mv, start_to_current, ref_frame_offset);316 let projected = get_mv_projection(saved.mv, start_to_current, ref_frame_offset);
300 if let Some((r, c)) =317 if let Some((r, c)) =
301 get_block_position(mvs_rows, mvs_cols, row8, col8, projected, dir >> 1 == 1)318 get_block_position(mvs_rows, mvs_cols, row8, col8, projected, dir >> 1 == 1)
302 {319 {
303- tpl_cells[r * mvs_cols + c] = Some((saved.mv, ref_frame_offset));320+ tpl_cells[r * mvs_cols + c] = (saved.mv, ref_frame_offset);
304 }321 }
305 }322 }
306 }323 }
@@ -348,7 +365,7 @@ pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>(
348 ) -> TplField {365 ) -> TplField {
349 let cols = mi_cols.div_ceil(2);366 let cols = mi_cols.div_ceil(2);
350 let rows = mi_rows.div_ceil(2);367 let rows = mi_rows.div_ceil(2);
351- let mut cells = vec![None; cols * rows];368+ let mut cells = vec![TPL_EMPTY; cols * rows];
352 // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;`369 // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;`
353 // leaves every `tpl_mvs` cell INVALID.370 // leaves every `tpl_mvs` cell INVALID.
354 if order_hint_bits == 0 {371 if order_hint_bits == 0 {
@@ -474,7 +491,7 @@ pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>(
474 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");491 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");
475 for r in 0..rows {492 for r in 0..rows {
476 let row: String = (0..cols)493 let row: String = (0..cols)
477- .map(|c| if cells[r * cols + c].is_some() { '#' } else { '.' })494+ .map(|c| if cells[r * cols + c].1 != 0 { '#' } else { '.' })
478 .collect();495 .collect();
479 eprintln!("EC_TPL_FIELD r{r} {row}");496 eprintln!("EC_TPL_FIELD r{r} {row}");
480 }497 }
@@ -548,7 +565,7 @@ pub fn project_tpl_mv(
548 /// keeps the spec's `row8 < 0` rejection exact (`row8 < 0` iff the shifted565 /// keeps the spec's `row8 < 0` rejection exact (`row8 < 0` iff the shifted
549 /// index is negative).566 /// index is negative).
550 pub struct TplProbe<'a> {567 pub struct TplProbe<'a> {
551- cells: &'a [Option<((i32, i32), i32)>],568+ cells: &'a [TplCell],
552 cols: isize,569 cols: isize,
553 rows: isize,570 rows: isize,
554 base_row: isize,571 base_row: isize,
@@ -580,7 +597,8 @@ impl TplProbe<'_> {
580 if row < 0 || col < 0 || row >= self.rows || col >= self.cols {597 if row < 0 || col < 0 || row >= self.rows || col >= self.cols {
581 return None;598 return None;
582 }599 }
583- self.cells[(row * self.cols + col) as usize]600+ let cell = self.cells[(row * self.cols + col) as usize];
601+ if cell.1 == 0 { None } else { Some(cell) }
584 }602 }
585 }603 }
586 604
@@ -595,8 +613,8 @@ mod tests {
595 #[test]613 #[test]
596 fn probe_cell_matches_the_spec_parity_derivation() {614 fn probe_cell_matches_the_spec_parity_derivation() {
597 let (rows, cols) = (5usize, 6usize);615 let (rows, cols) = (5usize, 6usize);
598- let cells: Vec<Option<((i32, i32), i32)>> = (0..rows * cols)616+ let cells: Vec<TplCell> = (0..rows * cols)
599- .map(|i| Some(((i as i32, -(i as i32)), 1)))617+ .map(|i| ((i as i32, -(i as i32)), 1))
600 .collect();618 .collect();
601 let tpl = TplField { cols, rows, cells };619 let tpl = TplField { cols, rows, cells };
602 for mi_row in 0..2 * rows {620 for mi_row in 0..2 * rows {
@@ -614,7 +632,7 @@ mod tests {
614 } else {632 } else {
615 let (r, c) = (row8 as usize / 2, col8 as usize / 2);633 let (r, c) = (row8 as usize / 2, col8 as usize / 2);
616 if r < rows && c < cols {634 if r < rows && c < cols {
617- tpl.cells[r * cols + c]635+ Some(tpl.cells[r * cols + c])
618 } else {636 } else {
619 None637 None
620 }638 }
@@ -630,6 +648,25 @@ mod tests {
630 }648 }
631 }649 }
632 650
651+ /// lane-mvstack3: [`TplCell`] dropped its `Option` tag for the
652+ /// `ref_frame_offset == 0` sentinel `motion_field_projection` already
653+ /// guarantees (it only ever stores a strictly positive offset). This pins
654+ /// that sentinel: an unprojected cell must still read as `None` through
655+ /// [`TplProbe::cell`], and a projected one with a zero MV must not.
656+ #[test]
657+ fn an_unprojected_tpl_cell_reads_as_none_but_a_zero_mv_one_does_not() {
658+ let (rows, cols) = (2usize, 2usize);
659+ let cells: Vec<TplCell> = vec![TPL_EMPTY, ((0, 0), 3), ((7, -7), 1), TPL_EMPTY];
660+ let tpl = TplField { cols, rows, cells };
661+ // mi=(0,0) probes cell (0,0) at blk (-1,-1) and (0,1) at blk (-1,1).
662+ let probe = tpl.probe(0, 0);
663+ assert_eq!(probe.cell(-1, -1), None, "unprojected cell");
664+ assert_eq!(probe.cell(-1, 1), Some(((0, 0), 3)), "projected zero mv");
665+ assert_eq!(probe.cell(1, -1), Some(((7, -7), 1)));
666+ assert_eq!(probe.cell(1, 1), None, "unprojected cell");
667+ assert_eq!(tpl.filled_cells(), 2);
668+ }
669+
633 #[test]670 #[test]
634 fn relative_dist_wraps_at_order_hint_bits() {671 fn relative_dist_wraps_at_order_hint_bits() {
635 // 7-bit order hints (aomenc's usual default): 1 - 126 should read as672 // 7-bit order hints (aomenc's usual default): 1 - 126 should read as
crates/ec-av1/src/mvstack.rsmodified+148 -45
@@ -994,6 +994,134 @@ fn clamp_mv_ref(
994 )994 )
995 }995 }
996 996
997+/// lane-mvstack3: the `EC_TRACE_TPL` dump path of the temporal-MV sample,
998+/// moved out of the sample closure itself. Inlining `add_tpl_ref_mv` into
999+/// that closure made its body too big for LLVM to inline at the (four) probe
1000+/// call sites, so the closure was emitted as a real function
1001+/// (`find_mv_stack_with_sign_bias::{closure#1}`, 1.9% of the parse thread)
1002+/// and every one of the up-to-19 probes per inter block paid a call. The
1003+/// traced path keeps the exact same reads in the exact same order.
1004+#[cold]
1005+#[inline(never)]
1006+fn tpl_trace_sample(
1007+ field: &crate::motion_field::TplField,
1008+ mi_row: usize,
1009+ mi_col: usize,
1010+ blk_row: isize,
1011+ blk_col: isize,
1012+ cur_offset: i32,
1013+ allow_high_precision_mv: bool,
1014+) -> Option<(i32, i32)> {
1015+ crate::motion_field::add_tpl_ref_mv(
1016+ field,
1017+ mi_row,
1018+ mi_col,
1019+ blk_row,
1020+ blk_col,
1021+ cur_offset,
1022+ allow_high_precision_mv,
1023+ )
1024+ .map(|c| c.mv)
1025+}
1026+
1027+/// [`tpl_trace_sample`] for the compound stack, whose trace pass dumps both
1028+/// reference offsets and discards the values.
1029+#[cold]
1030+#[inline(never)]
1031+fn tpl_trace_sample_compound(
1032+ field: &crate::motion_field::TplField,
1033+ mi_row: usize,
1034+ mi_col: usize,
1035+ blk_row: isize,
1036+ blk_col: isize,
1037+ cur_offsets: (i32, i32),
1038+ allow_high_precision_mv: bool,
1039+) {
1040+ for off in [cur_offsets.0, cur_offsets.1] {
1041+ let _ = crate::motion_field::add_tpl_ref_mv(
1042+ field,
1043+ mi_row,
1044+ mi_col,
1045+ blk_row,
1046+ blk_col,
1047+ off,
1048+ allow_high_precision_mv,
1049+ );
1050+ }
1051+}
1052+
1053+/// lane-mvstack3: the temporal-MV probe, as a `#[inline(always)]` free
1054+/// function instead of a closure. LLVM would not inline the closure into
1055+/// either mv-stack builder (both are far past its size threshold), so it was
1056+/// emitted as `find_mv_stack_with_sign_bias::{closure#1}` /
1057+/// `find_mv_stack_compound::{closure#1}` -- together 3.5% of the parse
1058+/// thread -- and every one of the up-to-19 probes per inter block paid a
1059+/// call plus the argument shuffle. Same reads, same order.
1060+#[inline(always)]
1061+fn tpl_sample(
1062+ probe: &crate::motion_field::TplProbe<'_>,
1063+ trace_tpl: bool,
1064+ field: &crate::motion_field::TplField,
1065+ mi_row: usize,
1066+ mi_col: usize,
1067+ blk_row: isize,
1068+ blk_col: isize,
1069+ cur_offset: i32,
1070+ allow_high_precision_mv: bool,
1071+) -> Option<(i32, i32)> {
1072+ if trace_tpl {
1073+ return tpl_trace_sample(
1074+ field,
1075+ mi_row,
1076+ mi_col,
1077+ blk_row,
1078+ blk_col,
1079+ cur_offset,
1080+ allow_high_precision_mv,
1081+ );
1082+ }
1083+ let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?;
1084+ Some(crate::motion_field::project_tpl_mv(
1085+ fwd_mv,
1086+ cur_offset,
1087+ rfo,
1088+ allow_high_precision_mv,
1089+ ))
1090+}
1091+
1092+/// [`tpl_sample`] for the compound stack: one field read projected to both
1093+/// reference offsets.
1094+#[allow(clippy::too_many_arguments)]
1095+#[inline(always)]
1096+fn tpl_sample_compound(
1097+ probe: &crate::motion_field::TplProbe<'_>,
1098+ trace_tpl: bool,
1099+ field: &crate::motion_field::TplField,
1100+ mi_row: usize,
1101+ mi_col: usize,
1102+ blk_row: isize,
1103+ blk_col: isize,
1104+ cur_offsets: (i32, i32),
1105+ allow_high_precision_mv: bool,
1106+) -> Option<((i32, i32), (i32, i32))> {
1107+ if trace_tpl {
1108+ tpl_trace_sample_compound(
1109+ field,
1110+ mi_row,
1111+ mi_col,
1112+ blk_row,
1113+ blk_col,
1114+ cur_offsets,
1115+ allow_high_precision_mv,
1116+ );
1117+ }
1118+ let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?;
1119+ Some((
1120+ crate::motion_field::project_tpl_mv(fwd_mv, cur_offsets.0, rfo, allow_high_precision_mv),
1121+ crate::motion_field::project_tpl_mv(fwd_mv, cur_offsets.1, rfo, allow_high_precision_mv),
1122+ ))
1123+}
1124+
997 /// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)1125 /// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
998 /// block at `(mi_row, mi_col)`, predicting against `ref_frame`, in a frame1126 /// block at `(mi_row, mi_col)`, predicting against `ref_frame`, in a frame
999 /// that is `mi_cols`-by-`mi_rows` 4x4 units (used only to clamp the1127 /// that is `mi_cols`-by-`mi_rows` 4x4 units (used only to clamp the
@@ -1179,25 +1307,17 @@ pub fn find_mv_stack_with_sign_bias(
1179 let trace_tpl = crate::envflags::env_flag!("EC_TRACE_TPL");1307 let trace_tpl = crate::envflags::env_flag!("EC_TRACE_TPL");
1180 let probe = field.probe(mi_row, mi_col);1308 let probe = field.probe(mi_row, mi_col);
1181 let sample = |blk_row: isize, blk_col: isize| -> Option<(i32, i32)> {1309 let sample = |blk_row: isize, blk_col: isize| -> Option<(i32, i32)> {
1182- if trace_tpl {1310+ tpl_sample(
1183- return crate::motion_field::add_tpl_ref_mv(1311+ &probe,
1184- field,1312+ trace_tpl,
1185- mi_row,1313+ field,
1186- mi_col,1314+ mi_row,
1187- blk_row,1315+ mi_col,
1188- blk_col,1316+ blk_row,
1189- cur_offset_0,1317+ blk_col,
1190- allow_high_precision_mv,
1191- )
1192- .map(|c| c.mv);
1193- }
1194- let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?;
1195- Some(crate::motion_field::project_tpl_mv(
1196- fwd_mv,
1197 cur_offset_0,1318 cur_offset_0,
1198- rfo,
1199 allow_high_precision_mv,1319 allow_high_precision_mv,
1200- ))1320+ )
1201 };1321 };
1202 let mut blk_row = 0usize;1322 let mut blk_row = 0usize;
1203 while blk_row < blk_row_end {1323 while blk_row < blk_row_end {
@@ -1989,34 +2109,17 @@ pub fn find_mv_stack_compound(
1989 let trace_tpl = crate::envflags::env_flag!("EC_TRACE_TPL");2109 let trace_tpl = crate::envflags::env_flag!("EC_TRACE_TPL");
1990 let probe = field.probe(mi_row, mi_col);2110 let probe = field.probe(mi_row, mi_col);
1991 let sample = |blk_row: isize, blk_col: isize| -> Option<((i32, i32), (i32, i32))> {2111 let sample = |blk_row: isize, blk_col: isize| -> Option<((i32, i32), (i32, i32))> {
1992- if trace_tpl {2112+ tpl_sample_compound(
1993- for off in [cur_offset_0, cur_offset_1] {2113+ &probe,
1994- let _ = crate::motion_field::add_tpl_ref_mv(2114+ trace_tpl,
1995- field,2115+ field,
1996- mi_row,2116+ mi_row,
1997- mi_col,2117+ mi_col,
1998- blk_row,2118+ blk_row,
1999- blk_col,2119+ blk_col,
2000- off,2120+ (cur_offset_0, cur_offset_1),
2001- allow_high_precision_mv,2121+ allow_high_precision_mv,
2002- );2122+ )
2003- }
2004- }
2005- let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?;
2006- Some((
2007- crate::motion_field::project_tpl_mv(
2008- fwd_mv,
2009- cur_offset_0,
2010- rfo,
2011- allow_high_precision_mv,
2012- ),
2013- crate::motion_field::project_tpl_mv(
2014- fwd_mv,
2015- cur_offset_1,
2016- rfo,
2017- allow_high_precision_mv,
2018- ),
2019- ))
2020 };2123 };
2021 let mut blk_row = 0usize;2124 let mut blk_row = 0usize;
2022 while blk_row < blk_row_end {2125 while blk_row < blk_row_end {