forge
Explore
Log in

Don't you dare go Hollow

RD breakout on the inter split trial, chroma top-K lever, leaf census

Browse files at this commit

4e368e43e523b3e7476885e20e7ff07b4e6e4123Ahmet Kaan GümüşParent: bf299cd
  • perf
    • RD breakout on the inter split trial, chroma top-K lever, leaf census
Show full message
perf(av1): RD breakout on the inter split trial, chroma top-K lever, leaf census

The census says the split trial runs on nearly every non-skip 32x32 block and
wins 7.6% of the time on film, 3.0% on screen. A 32x32 whose whole-block RD
cost per pixel comes out under 0.125*lambda (and a 16x16 leaf likewise) is no
longer offered the split: -10.0%/-5.7% instructions (1080p/screen) for
+0.1/+0.3/-0.2 BD points vs libaom. Chroma top-K by prediction SAD ships off:
no K bought >=5% wall inside +0.3 BD.
crates/ec-av1/src/encode.rsmodified+110 -16
@@ -244,6 +244,45 @@ fn restoration_enabled() -> bool {
244244 /// future explicit speed preset.
245245 const SPLIT_BREAKOUT_COEFFS: usize = 0;
246246
247+/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
248+/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
249+/// out under `threshold * lambda` is not offered the split at all, and a
250+/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
251+/// always, as before this lever.
252+///
253+/// The census is what points here: the split trial runs on nearly every
254+/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
255+/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
256+/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
257+/// points, so the gate has to read the block's own RD cost, not its levels.
258+///
259+/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
260+/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
261+/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
262+/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
263+/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
264+/// the largest threshold whose BD stays inside the +0.3 keep rule on every
265+/// clip.
266+const SPLIT_RD_THRESHOLD: f64 = 0.125;
267+
268+/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
269+fn split_rd_threshold() -> f64 {
270+ static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
271+ *T.get_or_init(|| {
272+ std::env::var("EC_AV1_SPLIT_RD")
273+ .ok()
274+ .and_then(|v| v.parse().ok())
275+ .unwrap_or(SPLIT_RD_THRESHOLD)
276+ })
277+}
278+
279+/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
280+/// [`split_rd_threshold`] withholds the split trial.
281+fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
282+ let t = split_rd_threshold();
283+ t > 0.0 && cost < t * lambda * (side * side) as f64
284+}
285+
247286 /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
248287 /// build.
249288 fn split_breakout_coeffs() -> usize {
@@ -287,7 +326,7 @@ pub fn census_on() -> bool {
287326 }
288327
289328 /// What each [`CENSUS`] counter counts.
290-pub const CENSUS_KINDS: [&str; 8] = [
329+pub const CENSUS_KINDS: [&str; 11] = [
291330 "intra blocks searched (key frame + inter leaves)",
292331 "intra luma mode trials",
293332 "chroma searches",
@@ -296,11 +335,14 @@ pub const CENSUS_KINDS: [&str; 8] = [
296335 "inter 32x32 blocks searched",
297336 "inter block intra-mode trials",
298337 "inter mv candidates (each = 3 mc trials)",
338+ "inter leaves searched (intra vs NEARESTMV/NEWMV)",
339+ " of those, intra won",
340+ " of those, the NEARESTMV trial coded no residual",
299341 ];
300342
301343 /// The census counters themselves, indexed by [`CENSUS_KINDS`].
302-static CENSUS: [std::sync::atomic::AtomicUsize; 8] =
303- [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
344+static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
345+ [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
304346
305347 /// Where the RD winner sat in the SAD ranking, for the luma intra search and
306348 /// the chroma mode search -- what says whether a top-N prune would have kept
@@ -317,7 +359,7 @@ fn census_add(kind: usize, n: usize) {
317359 }
318360
319361 /// Reads (and clears) the census, so a driver can attribute it to its own encode.
320-pub fn take_census() -> ([usize; 8], [usize; 13], [usize; 7]) {
362+pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
321363 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
322364 (
323365 std::array::from_fn(|i| take(&CENSUS[i])),
@@ -1028,7 +1070,11 @@ impl Plane<'_> {
10281070 x, y, side, reach, ..
10291071 } = at;
10301072 let (above, left, corner) = self.edges(x, y, side, reach);
1031- let mut prediction = vec![0u8; side * side];
1073+ // Per-candidate scratch on the search's hottest path, so both buffers
1074+ // live on the stack -- `side` is at most `BLOCK` -- rather than
1075+ // costing a malloc/free pair per trial (`mc_trial` already does this).
1076+ let mut prediction = [0u8; BLOCK * BLOCK];
1077+ let prediction = &mut prediction[..side * side];
10321078 intra_predict_u8(
10331079 mode,
10341080 0,
@@ -1039,10 +1085,11 @@ impl Plane<'_> {
10391085 side,
10401086 false,
10411087 false,
1042- &mut prediction, fctx,
1088+ prediction, fctx,
10431089 );
10441090
1045- let mut residual = vec![0i32; side * side];
1091+ let mut residual = [0i32; BLOCK * BLOCK];
1092+ let residual = &mut residual[..side * side];
10461093 for row in 0..side {
10471094 for col in 0..side {
10481095 residual[row * side + col] =
@@ -1053,7 +1100,7 @@ impl Plane<'_> {
10531100 #[cfg(test)]
10541101 let t = std::time::Instant::now();
10551102 let levels =
1056- forward_and_quantize_typed(&residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
1103+ forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
10571104 let coded =
10581105 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
10591106 #[cfg(test)]
@@ -1136,7 +1183,8 @@ impl Plane<'_> {
11361183 bits: 0.0,
11371184 };
11381185 }
1139- let mut residual = vec![0i32; side * side];
1186+ let mut residual = [0i32; BLOCK * BLOCK];
1187+ let residual = &mut residual[..side * side];
11401188 for row in 0..side {
11411189 for col in 0..side {
11421190 residual[row * side + col] =
@@ -1146,7 +1194,7 @@ impl Plane<'_> {
11461194 }
11471195 #[cfg(test)]
11481196 let t = std::time::Instant::now();
1149- let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
1197+ let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone);
11501198 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
11511199 #[cfg(test)]
11521200 stage_add(2, t.elapsed());
@@ -2247,6 +2295,34 @@ pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
22472295 /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
22482296 /// writer then has to code.
22492297 #[allow(clippy::too_many_arguments)]
2298+/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
2299+/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
2300+/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
2301+/// trials all seven, as before this lever.
2302+///
2303+/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
2304+/// the search's largest trial population by far -- seven modes times two
2305+/// planes for every intra block, against 3.7 luma trials -- and the RD
2306+/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
2307+/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
2308+fn chroma_top_k() -> Option<usize> {
2309+ static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
2310+ *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
2311+ Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
2312+ None => CHROMA_TOP_K,
2313+ })
2314+}
2315+
2316+/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
2317+/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
2318+/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
2319+/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
2320+/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
2321+/// BD swings by about a point in either direction as near-tie chroma modes
2322+/// flip, which is the measurement's own sensitivity, not a trend: nothing
2323+/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
2324+const CHROMA_TOP_K: Option<usize> = None;
2325+
22502326 fn search_chroma(
22512327 chroma: &mut [Plane; 2],
22522328 (x, y): (usize, usize),
@@ -2263,25 +2339,34 @@ fn search_chroma(
22632339 reach: Reach::none(),
22642340 set,
22652341 };
2266- census_add(2, 1);
2267- census_add(3, CHROMA_MODES.len());
22682342 // The census's cheap proxy for a chroma mode: the SAD of its prediction
22692343 // summed over both planes, ranked by the same rule the luma histogram
22702344 // uses. Only built under `EC_AV1_CENSUS`.
2271- let ranking: Vec<(f64, u8)> = if census_on() {
2345+ // The SAD of each mode's prediction, summed over both planes -- the
2346+ // census's ranking rule, and what [`chroma_top_k`] prunes by.
2347+ let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
22722348 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
22732349 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
22742350 u.iter()
22752351 .zip(v.iter())
22762352 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
22772353 .collect()
2278- } else {
2279- Vec::new()
2354+ };
2355+ let modes: Vec<u8> = match chroma_top_k() {
2356+ Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
2357+ _ => CHROMA_MODES.to_vec(),
22802358 };
22812359 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
22822360 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
2361+ let ranking: Vec<(f64, u8)> = if census_on() {
2362+ sad_scores(chroma)
2363+ } else {
2364+ Vec::new()
2365+ };
2366+ census_add(2, 1);
2367+ census_add(3, modes.len());
22832368 let mut best: Option<(f64, u8, Trial, Trial)> = None;
2284- for mode in CHROMA_MODES {
2369+ for mode in modes {
22852370 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
22862371 if (V_PRED..=D67_PRED).contains(&mode) {
22872372 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
@@ -2565,6 +2650,13 @@ fn code_square_inter(
25652650 }
25662651 }
25672652
2653+ census_add(8, 1);
2654+ if skip {
2655+ census_add(10, 1);
2656+ }
2657+ if inter_cost >= intra_cost {
2658+ census_add(9, 1);
2659+ }
25682660 if inter_cost < intra_cost {
25692661 let (levels, tx_depth, dcost) = commit_inter_luma(
25702662 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx,
@@ -4465,6 +4557,7 @@ pub(crate) fn encode_inter_frame(
44654557 // nothing is not offered the split at all.
44664558 let breakout = split_breakout_coeffs();
44674559 let split = (!block.skip
4560+ && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
44684561 && (breakout == 0 || block.luma.len() > 4 * breakout)
44694562 && leaves_legal
44704563 && split_inter_blocks())
@@ -4499,6 +4592,7 @@ pub(crate) fn encode_inter_frame(
44994592 // at BLOCK_16X16 (lane-av1rd2). Same
45004593 // skipped-block prune as the level above.
45014594 let eight = (!leaf.skip
4595+ && !split_rd_breakout(leaf_cost, SUB, search.lambda)
45024596 && (breakout == 0 || leaf.luma.len() > breakout)
45034597 && split_inter_8())
45044598 .then(|| {