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() {
51 h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);51 h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
52 }52 }
53 println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len());53 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+ }
54 }69 }
55 println!("wall {:.3}s", start.elapsed().as_secs_f64());70 println!("wall {:.3}s", start.elapsed().as_secs_f64());
56 }71 }
crates/ec-av1/src/encode.rsmodified+120 -10
@@ -276,6 +276,73 @@ pub(crate) fn take_partition_hits() -> [usize; 4] {
276 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))276 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
277 }277 }
278 278
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+
279 /// Whether a 32x32 block may be split into four 16x16 ones when the trial says346 /// Whether a 32x32 block may be split into four 16x16 ones when the trial says
280 /// four cost less. Set from the measurement in the lane report.347 /// four cost less. Set from the measurement in the lane report.
281 const SPLIT_BLOCKS: bool = true;348 const SPLIT_BLOCKS: bool = true;
@@ -1142,6 +1209,7 @@ impl Plane<'_> {
1142 _ => TxbSet::Luma4,1209 _ => TxbSet::Luma4,
1143 };1210 };
1144 let mut levels = vec![0i32; side * side];1211 let mut levels = vec![0i32; side * side];
1212+ census_add(4, n * n);
1145 let (mut sse, mut bits) = (0.0, 0.0);1213 let (mut sse, mut bits) = (0.0, 0.0);
1146 for tu_row in 0..n {1214 for tu_row in 0..n {
1147 for tu_col in 0..n {1215 for tu_col in 0..n {
@@ -1266,6 +1334,11 @@ impl Plane<'_> {
1266 x, y, side, reach, ..1334 x, y, side, reach, ..
1267 } = at;1335 } = at;
1268 let (above, left, corner) = self.edges(x, y, side, reach);1336 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();
1269 let mut scored: Vec<(f64, u8, Vec<u8>)> = search1342 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
1270 .modes1343 .modes
1271 .iter()1344 .iter()
@@ -1283,16 +1356,20 @@ impl Plane<'_> {
1283 false,1356 false,
1284 &mut prediction, fctx,1357 &mut prediction, fctx,
1285 );1358 );
1286- let sad: f64 = (0..side * side)1359+ let sad: f64 = if want_sad {
1287- .map(|i| {1360+ (0..side * side)
1288- let (row, col) = (i / side, i % side);1361+ .map(|i| {
1289- f64::from(1362+ let (row, col) = (i / side, i % side);
1290- (i32::from(self.source[(y + row) * self.width + x + col])1363+ f64::from(
1291- - i32::from(prediction[i]))1364+ (i32::from(self.source[(y + row) * self.width + x + col])
1292- .abs(),1365+ - i32::from(prediction[i]))
1293- )1366+ .abs(),
1294- })1367+ )
1295- .sum();1368+ })
1369+ .sum()
1370+ } else {
1371+ 0.0
1372+ };
1296 (1373 (
1297 sad + search.lambda * mode_bits[usize::from(mode)],1374 sad + search.lambda * mode_bits[usize::from(mode)],
1298 mode,1375 mode,
@@ -1315,6 +1392,13 @@ impl Plane<'_> {
1315 }1392 }
1316 }1393 }
1317 }1394 }
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());
1318 let mut best: Option<(f64, u8, Trial)> = None;1402 let mut best: Option<(f64, u8, Trial)> = None;
1319 for (_, mode, prediction) in scored {1403 for (_, mode, prediction) in scored {
1320 let trial = self.code_from_prediction(1404 let trial = self.code_from_prediction(
@@ -1336,6 +1420,10 @@ impl Plane<'_> {
1336 }1420 }
1337 }1421 }
1338 let (cost, mode, trial) = best.expect("the search offers at least one mode");1422 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+ }
1339 self.commit(x, y, side, &trial);1427 self.commit(x, y, side, &trial);
1340 (coeffs(&trial.levels, side), mode, cost)1428 (coeffs(&trial.levels, side), mode, cost)
1341 }1429 }
@@ -2175,6 +2263,21 @@ fn search_chroma(
2175 reach: Reach::none(),2263 reach: Reach::none(),
2176 set,2264 set,
2177 };2265 };
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+ };
2178 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];2281 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
2179 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));2282 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
2180 let mut best: Option<(f64, u8, Trial, Trial)> = None;2283 let mut best: Option<(f64, u8, Trial, Trial)> = None;
@@ -2192,6 +2295,10 @@ fn search_chroma(
2192 }2295 }
2193 }2296 }
2194 let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty");2297 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+ }
2195 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);2302 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2196 chroma[0].commit(at.x, at.y, at.side, &u);2303 chroma[0].commit(at.x, at.y, at.side, &u);
2197 chroma[1].commit(at.x, at.y, at.side, &v);2304 chroma[1].commit(at.x, at.y, at.side, &v);
@@ -3753,6 +3860,8 @@ fn search_inter_block(
3753 }3860 }
3754 _ => search.modes.to_vec(),3861 _ => search.modes.to_vec(),
3755 };3862 };
3863+ census_add(5, 1);
3864+ census_add(6, intra_modes.len());
3756 for &mode in &intra_modes {3865 for &mode in &intra_modes {
3757 let luma_trial = luma.trial(3866 let luma_trial = luma.trial(
3758 At {3867 At {
@@ -4007,6 +4116,7 @@ fn search_inter_block(
4007 .then(a.1.total_cmp(&b.1))4116 .then(a.1.total_cmp(&b.1))
4008 });4117 });
4009 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));4118 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
4119+ census_add(7, cands.len());
4010 {4120 {
4011 for (mv, mode_bits_inter, info) in cands {4121 for (mv, mode_bits_inter, info) in cands {
4012 let (ref_luma, ref_u, ref_v) = match extra4122 let (ref_luma, ref_u, ref_v) = match extra