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 {
244 /// future explicit speed preset.244 /// future explicit speed preset.
245 const SPLIT_BREAKOUT_COEFFS: usize = 0;245 const SPLIT_BREAKOUT_COEFFS: usize = 0;
246 246
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+
247 /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test286 /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
248 /// build.287 /// build.
249 fn split_breakout_coeffs() -> usize {288 fn split_breakout_coeffs() -> usize {
@@ -287,7 +326,7 @@ pub fn census_on() -> bool {
287 }326 }
288 327
289 /// What each [`CENSUS`] counter counts.328 /// What each [`CENSUS`] counter counts.
290-pub const CENSUS_KINDS: [&str; 8] = [329+pub const CENSUS_KINDS: [&str; 11] = [
291 "intra blocks searched (key frame + inter leaves)",330 "intra blocks searched (key frame + inter leaves)",
292 "intra luma mode trials",331 "intra luma mode trials",
293 "chroma searches",332 "chroma searches",
@@ -296,11 +335,14 @@ pub const CENSUS_KINDS: [&str; 8] = [
296 "inter 32x32 blocks searched",335 "inter 32x32 blocks searched",
297 "inter block intra-mode trials",336 "inter block intra-mode trials",
298 "inter mv candidates (each = 3 mc trials)",337 "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",
299 ];341 ];
300 342
301 /// The census counters themselves, indexed by [`CENSUS_KINDS`].343 /// The census counters themselves, indexed by [`CENSUS_KINDS`].
302-static CENSUS: [std::sync::atomic::AtomicUsize; 8] =344+static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
303- [const { std::sync::atomic::AtomicUsize::new(0) }; 8];345+ [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
304 346
305 /// Where the RD winner sat in the SAD ranking, for the luma intra search and347 /// Where the RD winner sat in the SAD ranking, for the luma intra search and
306 /// the chroma mode search -- what says whether a top-N prune would have kept348 /// 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) {
317 }359 }
318 360
319 /// Reads (and clears) the census, so a driver can attribute it to its own encode.361 /// 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]) {
321 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);363 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
322 (364 (
323 std::array::from_fn(|i| take(&CENSUS[i])),365 std::array::from_fn(|i| take(&CENSUS[i])),
@@ -1028,7 +1070,11 @@ impl Plane<'_> {
1028 x, y, side, reach, ..1070 x, y, side, reach, ..
1029 } = at;1071 } = at;
1030 let (above, left, corner) = self.edges(x, y, side, reach);1072 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];
1032 intra_predict_u8(1078 intra_predict_u8(
1033 mode,1079 mode,
1034 0,1080 0,
@@ -1039,10 +1085,11 @@ impl Plane<'_> {
1039 side,1085 side,
1040 false,1086 false,
1041 false,1087 false,
1042- &mut prediction, fctx,1088+ prediction, fctx,
1043 );1089 );
1044 1090
1045- let mut residual = vec![0i32; side * side];1091+ let mut residual = [0i32; BLOCK * BLOCK];
1092+ let residual = &mut residual[..side * side];
1046 for row in 0..side {1093 for row in 0..side {
1047 for col in 0..side {1094 for col in 0..side {
1048 residual[row * side + col] =1095 residual[row * side + col] =
@@ -1053,7 +1100,7 @@ impl Plane<'_> {
1053 #[cfg(test)]1100 #[cfg(test)]
1054 let t = std::time::Instant::now();1101 let t = std::time::Instant::now();
1055 let levels =1102 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);
1057 let coded =1104 let coded =
1058 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);1105 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
1059 #[cfg(test)]1106 #[cfg(test)]
@@ -1136,7 +1183,8 @@ impl Plane<'_> {
1136 bits: 0.0,1183 bits: 0.0,
1137 };1184 };
1138 }1185 }
1139- let mut residual = vec![0i32; side * side];1186+ let mut residual = [0i32; BLOCK * BLOCK];
1187+ let residual = &mut residual[..side * side];
1140 for row in 0..side {1188 for row in 0..side {
1141 for col in 0..side {1189 for col in 0..side {
1142 residual[row * side + col] =1190 residual[row * side + col] =
@@ -1146,7 +1194,7 @@ impl Plane<'_> {
1146 }1194 }
1147 #[cfg(test)]1195 #[cfg(test)]
1148 let t = std::time::Instant::now();1196 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);
1150 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));1198 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
1151 #[cfg(test)]1199 #[cfg(test)]
1152 stage_add(2, t.elapsed());1200 stage_add(2, t.elapsed());
@@ -2247,6 +2295,34 @@ pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
2247 /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the2295 /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
2248 /// writer then has to code.2296 /// writer then has to code.
2249 #[allow(clippy::too_many_arguments)]2297 #[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+
2250 fn search_chroma(2326 fn search_chroma(
2251 chroma: &mut [Plane; 2],2327 chroma: &mut [Plane; 2],
2252 (x, y): (usize, usize),2328 (x, y): (usize, usize),
@@ -2263,25 +2339,34 @@ fn search_chroma(
2263 reach: Reach::none(),2339 reach: Reach::none(),
2264 set,2340 set,
2265 };2341 };
2266- census_add(2, 1);
2267- census_add(3, CHROMA_MODES.len());
2268 // The census's cheap proxy for a chroma mode: the SAD of its prediction2342 // The census's cheap proxy for a chroma mode: the SAD of its prediction
2269 // summed over both planes, ranked by the same rule the luma histogram2343 // summed over both planes, ranked by the same rule the luma histogram
2270 // uses. Only built under `EC_AV1_CENSUS`.2344 // 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)> {
2272 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);2348 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
2273 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);2349 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
2274 u.iter()2350 u.iter()
2275 .zip(v.iter())2351 .zip(v.iter())
2276 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))2352 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
2277 .collect()2353 .collect()
2278- } else {2354+ };
2279- Vec::new()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(),
2280 };2358 };
2281 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];2359 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
2282 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));2360 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());
2283 let mut best: Option<(f64, u8, Trial, Trial)> = None;2368 let mut best: Option<(f64, u8, Trial, Trial)> = None;
2284- for mode in CHROMA_MODES {2369+ for mode in modes {
2285 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;2370 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
2286 if (V_PRED..=D67_PRED).contains(&mode) {2371 if (V_PRED..=D67_PRED).contains(&mode) {
2287 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);2372 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
@@ -2565,6 +2650,13 @@ fn code_square_inter(
2565 }2650 }
2566 }2651 }
2567 2652
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+ }
2568 if inter_cost < intra_cost {2660 if inter_cost < intra_cost {
2569 let (levels, tx_depth, dcost) = commit_inter_luma(2661 let (levels, tx_depth, dcost) = commit_inter_luma(
2570 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx,2662 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(
4465 // nothing is not offered the split at all.4557 // nothing is not offered the split at all.
4466 let breakout = split_breakout_coeffs();4558 let breakout = split_breakout_coeffs();
4467 let split = (!block.skip4559 let split = (!block.skip
4560+ && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
4468 && (breakout == 0 || block.luma.len() > 4 * breakout)4561 && (breakout == 0 || block.luma.len() > 4 * breakout)
4469 && leaves_legal4562 && leaves_legal
4470 && split_inter_blocks())4563 && split_inter_blocks())
@@ -4499,6 +4592,7 @@ pub(crate) fn encode_inter_frame(
4499 // at BLOCK_16X16 (lane-av1rd2). Same4592 // at BLOCK_16X16 (lane-av1rd2). Same
4500 // skipped-block prune as the level above.4593 // skipped-block prune as the level above.
4501 let eight = (!leaf.skip4594 let eight = (!leaf.skip
4595+ && !split_rd_breakout(leaf_cost, SUB, search.lambda)
4502 && (breakout == 0 || leaf.luma.len() > breakout)4596 && (breakout == 0 || leaf.luma.len() > breakout)
4503 && split_inter_8())4597 && split_inter_8())
4504 .then(|| {4598 .then(|| {