forge
Explore
Log in

Don't you dare go Hollow

Trial-set census, and the intra SAD pre-pass only when something ranks by it

Browse files at this commit

bf299cdcced99d2115931d7aee43ede6bf70e042Ahmet Kaan GümüşParent: e6e02af
  • perf
    • trial-set census, and the intra SAD pre-pass only when something ranks by it
Show full message
perf(av1): trial-set census, and the intra SAD pre-pass only when something ranks by it

The key-frame luma search summed a per-mode SAD the unpruned default never
reads (top_k is None there); byte-exact on all three probe clips, ~2% wall.
EC_AV1_CENSUS=1 counts the search's full RD trials by kind and histograms
where the RD winner sat in the SAD ranking.
crates/ec-av1/examples/enc_probe.rsmodified+15 -0
@@ -51,6 +51,21 @@ fn main() {
5151 h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
5252 }
5353 println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len());
54+ if ec_av1::encode::census_on() {
55+ let (kinds, luma_rank, chroma_rank) = ec_av1::encode::take_census();
56+ for (name, n) in ec_av1::encode::CENSUS_KINDS.iter().zip(kinds) {
57+ println!(" census {name}: {n}");
58+ }
59+ let pct = |h: &[usize]| {
60+ let total: usize = h.iter().sum::<usize>().max(1);
61+ h.iter()
62+ .map(|n| format!("{:.1}%", 100.0 * *n as f64 / total as f64))
63+ .collect::<Vec<_>>()
64+ .join(" ")
65+ };
66+ println!(" census luma SAD rank of RD winner: {}", pct(&luma_rank));
67+ println!(" census chroma SAD rank of RD winner: {}", pct(&chroma_rank));
68+ }
5469 }
5570 println!("wall {:.3}s", start.elapsed().as_secs_f64());
5671 }
crates/ec-av1/src/encode.rsmodified+120 -10
@@ -276,6 +276,73 @@ pub(crate) fn take_partition_hits() -> [usize; 4] {
276276 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
277277 }
278278
279+/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
280+/// rate-distortion trials the block search actually runs, by kind, and where
281+/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
282+/// default, and a measurement build rather than a speed one -- the census
283+/// runs the SAD pre-pass the unpruned search otherwise skips.
284+pub fn census_on() -> bool {
285+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
286+ *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
287+}
288+
289+/// What each [`CENSUS`] counter counts.
290+pub const CENSUS_KINDS: [&str; 8] = [
291+ "intra blocks searched (key frame + inter leaves)",
292+ "intra luma mode trials",
293+ "chroma searches",
294+ "chroma mode trials (each = 2 plane trials)",
295+ "tx-depth trials (transform units, depth >= 1)",
296+ "inter 32x32 blocks searched",
297+ "inter block intra-mode trials",
298+ "inter mv candidates (each = 3 mc trials)",
299+];
300+
301+/// 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];
304+
305+/// 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 kept
307+/// the block the search actually chose.
308+static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
309+ [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
310+static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
311+ [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
312+
313+fn census_add(kind: usize, n: usize) {
314+ if census_on() {
315+ CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
316+ }
317+}
318+
319+/// 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]) {
321+ let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
322+ (
323+ std::array::from_fn(|i| take(&CENSUS[i])),
324+ std::array::from_fn(|i| take(&LUMA_RANK[i])),
325+ std::array::from_fn(|i| take(&CHROMA_RANK[i])),
326+ )
327+}
328+
329+/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
330+/// first -- the census's one shared rule, so the luma and chroma histograms
331+/// mean the same thing.
332+fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
333+ scored
334+ .iter()
335+ .filter(|&&(score, mode)| {
336+ mode != winner
337+ && score
338+ < scored
339+ .iter()
340+ .find(|&&(_, m)| m == winner)
341+ .map_or(f64::INFINITY, |&(s, _)| s)
342+ })
343+ .count()
344+}
345+
279346 /// Whether a 32x32 block may be split into four 16x16 ones when the trial says
280347 /// four cost less. Set from the measurement in the lane report.
281348 const SPLIT_BLOCKS: bool = true;
@@ -1142,6 +1209,7 @@ impl Plane<'_> {
11421209 _ => TxbSet::Luma4,
11431210 };
11441211 let mut levels = vec![0i32; side * side];
1212+ census_add(4, n * n);
11451213 let (mut sse, mut bits) = (0.0, 0.0);
11461214 for tu_row in 0..n {
11471215 for tu_col in 0..n {
@@ -1266,6 +1334,11 @@ impl Plane<'_> {
12661334 x, y, side, reach, ..
12671335 } = at;
12681336 let (above, left, corner) = self.edges(x, y, side, reach);
1337+ // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
1338+ // the census reports it), so summing it under the default unpruned
1339+ // search is `side * side` absolute differences per mode spent on a
1340+ // number no one reads.
1341+ let want_sad = search.top_k.is_some() || census_on();
12691342 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
12701343 .modes
12711344 .iter()
@@ -1283,16 +1356,20 @@ impl Plane<'_> {
12831356 false,
12841357 &mut prediction, fctx,
12851358 );
1286- let sad: f64 = (0..side * side)
1287- .map(|i| {
1288- let (row, col) = (i / side, i % side);
1289- f64::from(
1290- (i32::from(self.source[(y + row) * self.width + x + col])
1291- - i32::from(prediction[i]))
1292- .abs(),
1293- )
1294- })
1295- .sum();
1359+ let sad: f64 = if want_sad {
1360+ (0..side * side)
1361+ .map(|i| {
1362+ let (row, col) = (i / side, i % side);
1363+ f64::from(
1364+ (i32::from(self.source[(y + row) * self.width + x + col])
1365+ - i32::from(prediction[i]))
1366+ .abs(),
1367+ )
1368+ })
1369+ .sum()
1370+ } else {
1371+ 0.0
1372+ };
12961373 (
12971374 sad + search.lambda * mode_bits[usize::from(mode)],
12981375 mode,
@@ -1315,6 +1392,13 @@ impl Plane<'_> {
13151392 }
13161393 }
13171394 }
1395+ let ranking: Vec<(f64, u8)> = if census_on() {
1396+ scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
1397+ } else {
1398+ Vec::new()
1399+ };
1400+ census_add(0, 1);
1401+ census_add(1, scored.len());
13181402 let mut best: Option<(f64, u8, Trial)> = None;
13191403 for (_, mode, prediction) in scored {
13201404 let trial = self.code_from_prediction(
@@ -1336,6 +1420,10 @@ impl Plane<'_> {
13361420 }
13371421 }
13381422 let (cost, mode, trial) = best.expect("the search offers at least one mode");
1423+ if census_on() {
1424+ LUMA_RANK[sad_rank(&ranking, mode).min(12)]
1425+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1426+ }
13391427 self.commit(x, y, side, &trial);
13401428 (coeffs(&trial.levels, side), mode, cost)
13411429 }
@@ -2175,6 +2263,21 @@ fn search_chroma(
21752263 reach: Reach::none(),
21762264 set,
21772265 };
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 prediction
2269+ // summed over both planes, ranked by the same rule the luma histogram
2270+ // uses. Only built under `EC_AV1_CENSUS`.
2271+ let ranking: Vec<(f64, u8)> = if census_on() {
2272+ 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);
2274+ u.iter()
2275+ .zip(v.iter())
2276+ .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
2277+ .collect()
2278+ } else {
2279+ Vec::new()
2280+ };
21782281 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
21792282 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
21802283 let mut best: Option<(f64, u8, Trial, Trial)> = None;
@@ -2192,6 +2295,10 @@ fn search_chroma(
21922295 }
21932296 }
21942297 let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty");
2298+ if census_on() {
2299+ CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2300+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2301+ }
21952302 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
21962303 chroma[0].commit(at.x, at.y, at.side, &u);
21972304 chroma[1].commit(at.x, at.y, at.side, &v);
@@ -3753,6 +3860,8 @@ fn search_inter_block(
37533860 }
37543861 _ => search.modes.to_vec(),
37553862 };
3863+ census_add(5, 1);
3864+ census_add(6, intra_modes.len());
37563865 for &mode in &intra_modes {
37573866 let luma_trial = luma.trial(
37583867 At {
@@ -4007,6 +4116,7 @@ fn search_inter_block(
40074116 .then(a.1.total_cmp(&b.1))
40084117 });
40094118 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
4119+ census_add(7, cands.len());
40104120 {
40114121 for (mv, mode_bits_inter, info) in cands {
40124122 let (ref_luma, ref_u, ref_v) = match extra