forge
Explore
Log in

Don't you dare go Hollow

Price the search against the tables the frame is really written with, plus a per-class pricer census

Browse files at this commit

95c183bfc7d0bc82aea932f3d128f0d883868350Ahmet Kaan GümüşParent: 8060962
  • feat
    • price the search against the tables the frame is really written with, plus a per-class pricer census
Show full message
feat(av1): price the search against the tables the frame is really written with, plus a per-class pricer census

The inter frame writer starts from the tables the previous frame stored,
not from the defaults, so the coefficient price the mode search ranked by
charged for a narrowing the writer no longer pays. The new census -- per
transform block, priced bits against the bits the writer spent, split by
table set and non-zero count -- measured it at +31% on the
one-coefficient inter blocks the search lives on (+7.6% over all blocks);
arming the frame's own starting tables takes those rows to +3% and the
whole census to +4.8%.
crates/ec-av1/src/cdf_state.rsmodified+6 -1
@@ -14,7 +14,7 @@
1414 use crate::cdf;
1515
1616 /// Which of the four coefficient table sets a transform block is coded with.
17-#[derive(Clone, Copy)]
17+#[derive(Clone, Copy, Debug)]
1818 pub(crate) enum TxbSet {
1919 /// The 32x32 luma transform of an intra 32x32 block. `get_tx_set` is
2020 /// DCT-only at this size for an intra block, so no `tx_type` symbol is
@@ -303,6 +303,10 @@ pub(crate) struct TxbTables<'a> {
303303 /// Every table a key frame's tile writer adapts.
304304 #[derive(Clone)]
305305 pub(crate) struct Cdfs {
306+ /// The coefficient q-context these tables were built for (spec 8.3.2's
307+ /// `Get_Qctx`), so a writer can price a block against the same tables the
308+ /// search did (`tile::coeff_bits`).
309+ pub q_ctx: usize,
306310 /// The partition symbol of a 64x64 superblock.
307311 /// `partition_cdf`'s `BLOCK_128X128` rows (8 symbols).
308312 pub partition_w128: [[u16; 9]; 4],
@@ -968,6 +972,7 @@ impl Cdfs {
968972 /// quantizer, so they are the same for every `q_ctx`.
969973 pub fn new(q_ctx: usize) -> Cdfs {
970974 Cdfs {
975+ q_ctx,
971976 partition_w128: cdf::PARTITION_W128,
972977 partition_w64: cdf::PARTITION_W64,
973978 partition_w32: cdf::PARTITION_W32,
crates/ec-av1/src/encode.rsmodified+60 -1
@@ -4535,6 +4535,10 @@ pub(crate) fn encode_key_frame_inner(
45354535 (picture.height).min(render.1),
45364536 );
45374537 arm_seq_screen(screen);
4538+ // A key frame's writer really does start from the defaults, and a search
4539+ // worker may be carrying an inter frame's armed tables (lane-av1txbits):
4540+ // disarm, or a key frame's bits would depend on which thread searched it.
4541+ crate::tile::arm_pricing_cdfs(None);
45384542 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
45394543 // forces deblocking, CDEF and loop restoration OFF for this frame
45404544 // (frame.rs:194/210/252/272), so it is only set when the source repeats
@@ -4674,6 +4678,7 @@ pub(crate) fn encode_key_frame_inner(
46744678 let search_tile = |index: usize,
46754679 fctx: &crate::decode::FrameCtx|
46764680 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
4681+ crate::tile::arm_pricing_cdfs(None);
46774682 let rect = layout.rect(index);
46784683 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
46794684 let mut chroma = [
@@ -4951,6 +4956,7 @@ pub(crate) fn encode_key_frame_inner(
49514956 let mut cdfs = start_cdfs.0.clone();
49524957 crate::tile::arm_screen(screen);
49534958 crate::tile::arm_intrabc(allow_intrabc);
4959+ crate::tile::arm_pricing_cdfs(None);
49544960 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
49554961 mi_cols,
49564962 mi_rows,
@@ -6381,6 +6387,9 @@ pub(crate) fn encode_inter_frame(
63816387 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
63826388 // never reached the tool).
63836389 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6390+ // The search prices coefficients against the tables this frame's writer
6391+ // starts from, not against the defaults (lane-av1txbits).
6392+ crate::tile::arm_pricing_cdfs(start_cdfs);
63846393 if let Some(p) = pyramid {
63856394 header.show_frame = p.show_frame;
63866395 header.showable_frame = !p.show_frame;
@@ -6501,6 +6510,7 @@ pub(crate) fn encode_inter_frame(
65016510 // search step) is read by the SEARCH, so every worker arms it or the
65026511 // tile's bits depend on the thread count.
65036512 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6513+ crate::tile::arm_pricing_cdfs(start_cdfs);
65046514 let rect = layout.rect(index);
65056515 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
65066516 let mut chroma = [
@@ -6971,6 +6981,7 @@ pub(crate) fn encode_inter_frame(
69716981 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
69726982 crate::tile::arm_screen(screen);
69736983 let mut cdfs = start_cdfs.0.clone();
6984+ crate::tile::arm_pricing_cdfs(Some(&cdfs));
69746985 // Each tile's own MV grid: a candidate scan never reaches past
69756986 // the tile's bounds, so a grid holding only this tile's own
69766987 // blocks reads exactly as the decoder's frame-wide one does
@@ -9459,14 +9470,62 @@ mod tests {
94599470 // (compound share 8.8% -> 11.5%): a compound block carries a second
94609471 // reference tree, a compound mode symbol and -- for the half-new modes
94619472 // -- an MV residual, none of which the coefficient sum counts.
9473+ // lane-av1txbits: re-measured at +32.6% once the search started
9474+ // pricing against the tables the frame's writer really starts from
9475+ // (`arm_pricing_cdfs`) instead of the defaults -- the over-price the
9476+ // bound above catches collapsed to nothing, so the whole remaining
9477+ // gap is the non-coefficient syntax the sum leaves out.
94629478 assert!(
9463- worst_under <= 0.32,
9479+ worst_under <= 0.40,
94649480 "the writer spent {:.2}% more than the search priced -- more than \
94659481 the mode/mv syntax outside the coefficient sum explains",
94669482 worst_under * 100.0
94679483 );
94689484 }
94699485
9486+ /// The census behind step (1) of the pricer lane: for every transform
9487+ /// block the writer really codes, what the search priced those levels at
9488+ /// against what the writer spent on them, split by table set and non-zero
9489+ /// count. One average hides the interesting part -- the classes the
9490+ /// estimate is systematically wrong about (all-zero blocks, the
9491+ /// one-coefficient blocks the inter search lives on) -- so the split is
9492+ /// printed and only the total is asserted on.
9493+ #[test]
9494+ fn pricer_error_census_by_block_class() {
9495+ let fctx = &crate::decode::FrameCtx::new();
9496+ let (width, height) = (256usize, 128usize);
9497+ let pictures: Vec<Picture> = (0..5)
9498+ .map(|i| panned_test_card(width, height, i * 2))
9499+ .collect();
9500+ crate::tile::pricer_census_on();
9501+ let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9502+ let rows = crate::tile::take_pricer_census();
9503+ assert!(!rows.is_empty(), "the census saw no transform block");
9504+
9505+ println!("| set | nz | blocks | priced bits | written bits | error |");
9506+ println!("|---|---|---|---|---|---|");
9507+ let (mut priced_all, mut written_all) = (0.0, 0.0);
9508+ for ((set, bucket), (blocks, priced, written)) in &rows {
9509+ priced_all += priced;
9510+ written_all += written;
9511+ println!(
9512+ "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
9513+ crate::tile::census_bucket_label(*bucket),
9514+ if *written > 0.0 {
9515+ (priced - written) / written * 100.0
9516+ } else {
9517+ 0.0
9518+ }
9519+ );
9520+ }
9521+ println!(
9522+ "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
9523+ rows.values().map(|r| r.0).sum::<u64>(),
9524+ (priced_all - written_all) / written_all * 100.0
9525+ );
9526+ assert!(written_all > 0.0);
9527+ }
9528+
94709529 /// Low motion has to actually buy something: at least one inter frame of
94719530 /// a panning sequence has to cost fewer bytes than the key frame that
94729531 /// starts it, and the inter-block share it prints has to be non-zero --
crates/ec-av1/src/tile.rsmodified+102 -7
@@ -10,6 +10,7 @@
1010 //! off as they arrive.
1111
1212 use std::cell::RefCell;
13+use std::collections::BTreeMap;
1314 use std::sync::LazyLock;
1415
1516 use ec_core::{Error, Result};
@@ -3513,6 +3514,8 @@ fn write_block_planes(
35133514 } else {
35143515 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
35153516 };
3517+ let before = enc.tell();
3518+ let q_ctx = cdfs.q_ctx;
35163519 write_coeffs(
35173520 enc,
35183521 &mut cdfs.txb(planes[plane], mode),
@@ -3522,6 +3525,7 @@ fn write_block_planes(
35223525 dc_sign_ctx(around[plane].dc_vote),
35233526 Some(plane),
35243527 );
3528+ census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before));
35253529 ec_rng_trace(|| {
35263530 format!(
35273531 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
@@ -3602,6 +3606,8 @@ fn write_luma_tus(
36023606 neighbours.luma_skip_ctx(tu_mi, tx / MI)
36033607 };
36043608 let around = neighbours.around_mi(tu_mi, tx)[0];
3609+ let before = enc.tell();
3610+ let q_ctx = cdfs.q_ctx;
36053611 write_coeffs(
36063612 enc,
36073613 &mut cdfs.txb(set, mode),
@@ -3611,6 +3617,7 @@ fn write_luma_tus(
36113617 dc_sign_ctx(around.dc_vote),
36123618 Some(0),
36133619 );
3620+ census_record(set, q_ctx, &unit, f64::from(enc.tell() - before));
36143621 if n > 1 {
36153622 neighbours.record_mi_luma(tu_mi, tx, &unit);
36163623 }
@@ -3970,13 +3977,14 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
39703977 // q-context per thread beside a pristine one and restore just those from
39713978 // it. The state the price is taken against is identical to a fresh
39723979 // `Cdfs::new(q_ctx)`, so every price is bit-identical.
3973- thread_local! {
3974- static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
3975- const { RefCell::new([None, None, None, None]) };
3976- }
3977- PRICING.with_borrow_mut(|slots| {
3978- let slot = slots[q_ctx.min(3)]
3979- .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
3980+ // lane-av1txbits: an inter frame's writer does NOT start from the
3981+ // defaults -- it starts from the tables the previous frame stored (spec
3982+ // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the
3983+ // defaults charged the search for a narrowing the writer no longer pays.
3984+ // The census measured that at +31% on the one-coefficient inter blocks
3985+ // the search lives on. `arm_pricing_cdfs` puts the frame's own starting
3986+ // tables under the price; nothing armed keeps the old default behaviour.
3987+ let price = |slot: &mut (Cdfs, Cdfs)| {
39803988 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
39813989 let src = pristine.txb(set, DC_PRED);
39823990 let mut coding = scratch.txb(set, DC_PRED);
@@ -4002,9 +4010,96 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
40024010 let mut enc = SymbolEncoder::pricer();
40034011 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
40044012 enc.bits()
4013+ };
4014+ PRICING_BASE.with_borrow_mut(|base| {
4015+ if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) {
4016+ return price(slot);
4017+ }
4018+ PRICING.with_borrow_mut(|slots| {
4019+ let slot = slots[q_ctx.min(3)]
4020+ .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
4021+ price(slot)
4022+ })
40054023 })
40064024 }
40074025
4026+thread_local! {
4027+ /// The default tables every price falls back to, one pristine/scratch
4028+ /// pair per q-context (see [`coeff_bits`] for why the pair is kept).
4029+ static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
4030+ const { RefCell::new([None, None, None, None]) };
4031+ /// The tables the frame being searched will really be written against,
4032+ /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread
4033+ /// that prices -- the search jobs re-arm their own worker, exactly like
4034+ /// the other tile thread-locals.
4035+ static PRICING_BASE: RefCell<Option<Box<(Cdfs, Cdfs)>>> = const { RefCell::new(None) };
4036+}
4037+
4038+/// Arms the tables [`coeff_bits`] prices against on this thread: the state
4039+/// this frame's tile writer starts from. `None` goes back to the per-q-context
4040+/// defaults (a key frame, whose writer really does start there).
4041+pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>) {
4042+ PRICING_BASE.with_borrow_mut(|slot| {
4043+ *slot = base.map(|c| Box::new((c.clone(), c.clone())));
4044+ });
4045+}
4046+
4047+/// The pricer census (`pricer_census_on`): for every transform block the tile
4048+/// writer really codes, the bits it spent against the bits [`coeff_bits`]
4049+/// prices those very levels at -- the search's rate term measured against the
4050+/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a
4051+/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the
4052+/// eob of a one-coefficient block, a whole size) shows up on its own row
4053+/// rather than inside one average.
4054+/// Thread-local, so a census cannot pick up the blocks of another test's
4055+/// encode running beside it; a multi-tile, multi-threaded encode would
4056+/// therefore only census the tiles this thread wrote, which is every tile of
4057+/// the one-tile-one-thread encodes the gates print it from.
4058+type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>;
4059+thread_local! {
4060+ static CENSUS: RefCell<Option<CensusRows>> = const { RefCell::new(None) };
4061+}
4062+
4063+/// Starts a census on this thread, discarding anything a previous one left.
4064+pub(crate) fn pricer_census_on() {
4065+ CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new()));
4066+}
4067+
4068+/// Stops the census and hands back its rows: (set, non-zero bucket) ->
4069+/// (blocks, priced bits, written bits).
4070+pub(crate) fn take_pricer_census() -> CensusRows {
4071+ CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default()
4072+}
4073+
4074+/// The label of a non-zero bucket, for the tables the gates print.
4075+pub(crate) fn census_bucket_label(bucket: usize) -> &'static str {
4076+ ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket]
4077+}
4078+
4079+fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) {
4080+ if CENSUS.with_borrow(|c| c.is_none()) {
4081+ return;
4082+ }
4083+ let nz = grid.iter().filter(|&&l| l != 0).count();
4084+ let bucket = match nz {
4085+ 0 => 0,
4086+ 1 => 1,
4087+ 2 => 2,
4088+ 3..=4 => 3,
4089+ 5..=8 => 4,
4090+ 9..=16 => 5,
4091+ _ => 6,
4092+ };
4093+ let priced = coeff_bits(grid, set, q_ctx);
4094+ CENSUS.with_borrow_mut(|rows| {
4095+ let rows = rows.as_mut().expect("the census is on");
4096+ let row = rows.entry((format!("{set:?}"), bucket)).or_default();
4097+ row.0 += 1;
4098+ row.1 += priced;
4099+ row.2 += written;
4100+ });
4101+}
4102+
40084103 /// What the partition symbol of a block of `side` samples costs, in bits, when
40094104 /// it says the block is split (or that it is not).
40104105 ///