forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-mot': stop repricing an inter block's chroma trial 13x

Browse files at this commit

348639c8b4dd8eff821cfcb1af15bb7a75007d15Ahmet Kaan GümüşParent: 091129fcc09bf2
The intra-candidate loop inside search_inter_block recomputed the u/v
chroma Trial -- always DC_PRED, independent of the luma mode -- on all
13 iterations. One computation, cloned. Bit-identical (probe frame's
bytes unchanged), and a 24-frame 720p GOP drops 994.5 -> 797.0 ms/frame.
A stage_timing_breakdown_inter probe now attributes inter-frame time;
the remaining big bucket is the same loop's 13 full luma RD trials.
crates/ec-av1/src/encode.rsmodified+140 -24
@@ -578,8 +578,12 @@ impl Plane<'_> {
578578 - i32::from(prediction[row * side + col]);
579579 }
580580 }
581+ #[cfg(test)]
582+ let t = std::time::Instant::now();
581583 let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
582584 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
585+ #[cfg(test)]
586+ stage_add(2, t.elapsed());
583587
584588 let mut reconstruction = vec![0u8; side * side];
585589 let mut sse = 0.0;
@@ -597,6 +601,8 @@ impl Plane<'_> {
597601 // What the levels cost is priced through the same CDFs the tile writer
598602 // will code them with, so the search ranks modes -- and the partition
599603 // trial ranks trees -- by the bits they actually spend.
604+ #[cfg(test)]
605+ let t = std::time::Instant::now();
600606 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
601607 // What the search used before it could price a block exactly: a
602608 // level costs its magnitude's width plus a sign and a run. Kept
@@ -610,6 +616,8 @@ impl Plane<'_> {
610616 } else {
611617 crate::tile::coeff_bits(&levels, at.set)
612618 };
619+ #[cfg(test)]
620+ stage_add(3, t.elapsed());
613621 Trial {
614622 levels,
615623 reconstruction,
@@ -662,8 +670,12 @@ impl Plane<'_> {
662670 - i32::from(prediction[row * side + col]);
663671 }
664672 }
673+ #[cfg(test)]
674+ let t = std::time::Instant::now();
665675 let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
666676 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
677+ #[cfg(test)]
678+ stage_add(2, t.elapsed());
667679 let mut reconstruction = vec![0u8; side * side];
668680 let mut sse = 0.0;
669681 for row in 0..side {
@@ -677,6 +689,8 @@ impl Plane<'_> {
677689 sse += error * error;
678690 }
679691 }
692+ #[cfg(test)]
693+ let t = std::time::Instant::now();
680694 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
681695 levels
682696 .iter()
@@ -686,6 +700,8 @@ impl Plane<'_> {
686700 } else {
687701 crate::tile::coeff_bits(&levels, set)
688702 };
703+ #[cfg(test)]
704+ stage_add(3, t.elapsed());
689705 Trial {
690706 levels,
691707 reconstruction,
@@ -1123,7 +1139,44 @@ fn set_test_top_k_override(value: Option<usize>) {
11231139 /// lever. Set from the sweep in the lane report if the quality gate clears it.
11241140 const PRUNE_TOP_K: Option<usize> = None;
11251141
1142+/// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
1143+/// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
1144+/// inter frame's cost can be attributed to a bucket without changing what
1145+/// the search actually does. Index: 0 = whole-call time inside
1146+/// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
1147+/// [`crate::mc::predict`] (every call, from the motion search's own
1148+/// candidates and from a committed inter block's final prediction alike),
1149+/// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
1150+#[cfg(test)]
1151+thread_local! {
1152+ static STAGE_NS: [std::cell::Cell<u64>; 4] = [
1153+ std::cell::Cell::new(0),
1154+ std::cell::Cell::new(0),
1155+ std::cell::Cell::new(0),
1156+ std::cell::Cell::new(0),
1157+ ];
1158+}
1159+
1160+#[cfg(test)]
1161+pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
1162+ STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
1163+}
1164+
1165+#[cfg(test)]
1166+fn stage_reset() {
1167+ STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
1168+}
1169+
1170+#[cfg(test)]
1171+fn stage_read() -> [std::time::Duration; 4] {
1172+ STAGE_NS.with(|c| {
1173+ c.each_ref()
1174+ .map(|cell| std::time::Duration::from_nanos(cell.get()))
1175+ })
1176+}
1177+
11261178 /// One mode's coding of one block, before it is committed.
1179+#[derive(Clone)]
11271180 struct Trial {
11281181 levels: Vec<i32>,
11291182 reconstruction: Vec<u8>,
@@ -1669,6 +1722,39 @@ fn search_inter_block(
16691722 }
16701723 };
16711724
1725+ // The chroma trial an intra candidate prices does not depend on `mode`
1726+ // at all -- both planes always code `DC_PRED` here (a coding choice this
1727+ // search inherited, not this loop's to second-guess) at the same `reach:
1728+ // Reach::none()` -- so it is the same call with the same inputs on every
1729+ // one of the thirteen iterations below; run it once and reuse the result
1730+ // rather than repeat an already-priced transform/quantize/entropy call
1731+ // twelve times for nothing (bit-identical: the value each iteration
1732+ // reads back is exactly what it used to recompute).
1733+ let u_trial = chroma[0].trial(
1734+ At {
1735+ x: x / 2,
1736+ y: y / 2,
1737+ side: BLOCK / 2,
1738+ reach: Reach::none(),
1739+ set: chroma_set,
1740+ },
1741+ DC_PRED,
1742+ search.base_q_idx,
1743+ search.deadzone,
1744+ );
1745+ let v_trial = chroma[1].trial(
1746+ At {
1747+ x: x / 2,
1748+ y: y / 2,
1749+ side: BLOCK / 2,
1750+ reach: Reach::none(),
1751+ set: chroma_set,
1752+ },
1753+ DC_PRED,
1754+ search.base_q_idx,
1755+ search.deadzone,
1756+ );
1757+
16721758 for &mode in search.modes {
16731759 let luma_trial = luma.trial(
16741760 At {
@@ -1682,30 +1768,8 @@ fn search_inter_block(
16821768 search.base_q_idx,
16831769 search.deadzone,
16841770 );
1685- let u = chroma[0].trial(
1686- At {
1687- x: x / 2,
1688- y: y / 2,
1689- side: BLOCK / 2,
1690- reach: Reach::none(),
1691- set: chroma_set,
1692- },
1693- DC_PRED,
1694- search.base_q_idx,
1695- search.deadzone,
1696- );
1697- let v = chroma[1].trial(
1698- At {
1699- x: x / 2,
1700- y: y / 2,
1701- side: BLOCK / 2,
1702- reach: Reach::none(),
1703- set: chroma_set,
1704- },
1705- DC_PRED,
1706- search.base_q_idx,
1707- search.deadzone,
1708- );
1771+ let u = u_trial.clone();
1772+ let v = v_trial.clone();
17091773 let cost = luma_trial.sse
17101774 + u.sse
17111775 + v.sse
@@ -1843,6 +1907,8 @@ fn search_inter_block(
18431907 }
18441908
18451909 let source_block = luma.source_block(x, y, BLOCK);
1910+ #[cfg(test)]
1911+ let t = std::time::Instant::now();
18461912 let found = motion::search(
18471913 ref_luma.0,
18481914 ref_luma.1,
@@ -1856,6 +1922,8 @@ fn search_inter_block(
18561922 stack.pred_mv,
18571923 search.lambda,
18581924 );
1925+ #[cfg(test)]
1926+ stage_add(0, t.elapsed());
18591927 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
18601928 if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) {
18611929 let luma_trial = mc_trial(
@@ -3684,6 +3752,54 @@ mod tests {
36843752 }
36853753 }
36863754
3755+ /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
3756+ /// (motion search, [`crate::mc::predict`], transform+quantize,
3757+ /// `coeff_bits`), plus what is left over once those are subtracted --
3758+ /// the thirteen-mode intra-candidate loop `search_inter_block` still
3759+ /// runs on every inter block (its own transform/quant/entropy calls are
3760+ /// already inside buckets 2/3, so "left over" here is everything NOT
3761+ /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
3762+ /// symbol-cost lookups outside `coeff_bits`).
3763+ ///
3764+ /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
3765+ #[test]
3766+ #[ignore = "a perf probe, not a gate"]
3767+ fn stage_timing_breakdown_inter() {
3768+ use std::time::Instant;
3769+
3770+ let (width, height) = (1280usize, 720);
3771+ let picture = test_card(width, height);
3772+ let key = encode_key_frame(&picture, 100, 0.5).unwrap();
3773+ let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
3774+ let padded_pic = picture.padded_to(SUPERBLOCK);
3775+
3776+ stage_reset();
3777+ let t = Instant::now();
3778+ let inter =
3779+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();
3780+ let total_t = t.elapsed();
3781+ let [motion_search, interpolation, transform_quant, entropy] = stage_read();
3782+ let accounted = motion_search + transform_quant + entropy;
3783+ // motion_search already contains interpolation's own time (every
3784+ // candidate the search costs calls crate::mc::predict), so it is not
3785+ // added again here -- interpolation is reported alongside as "of
3786+ // which interpolation", not as a fifth additive bucket.
3787+ let other = total_t.saturating_sub(accounted);
3788+
3789+ eprintln!(
3790+ "\n=== inter frame {width}x{height}, one frame ===\n\
3791+ total: {total_t:>9.2?} ({} bytes)\n\
3792+ motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
3793+ {interpolation:>9.2?})\n\
3794+ transform + quantize: {transform_quant:>9.2?}\n\
3795+ coeff_bits (entropy pricing): {entropy:>9.2?}\n\
3796+ everything else (13-mode intra {other:>9.2?}\n\
3797+ candidate loop's own predict/bookkeeping, NEARESTMV's own \
3798+ predict, RD glue):",
3799+ inter.stream.len(),
3800+ );
3801+ }
3802+
36873803 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
36883804 /// frames (a dark/flat one, a detailed one, a normal film one) at two
36893805 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
crates/ec-av1/src/mc.rsmodified+6 -0
@@ -103,6 +103,9 @@ pub fn predict(
103103 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
104104 assert!(!reference.is_empty(), "a reference plane has samples");
105105
106+ #[cfg(test)]
107+ let stage_t = std::time::Instant::now();
108+
106109 let x0 = x_q4.div_euclid(16);
107110 let xfrac = x_q4.rem_euclid(16) as usize;
108111 let y0 = y_q4.div_euclid(16);
@@ -136,6 +139,9 @@ pub fn predict(
136139 dst[row * block_w + col] = round2(sum, INTER_ROUND_1).clamp(0, 255) as u8;
137140 }
138141 }
142+
143+ #[cfg(test)]
144+ crate::encode::stage_add(1, stage_t.elapsed());
139145 }
140146
141147 #[cfg(test)]