forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1txbits' (59679eed): per-class pricer census; the frame-tables coefficient price ships as a knob

Browse files at this commit

5ab2d2a6bc6097facef2c5bec55805ec616b007cAhmet Kaan GümüşParent: 0b259731f18bea
Default bytes identical. Census: the RD pricer charged coefficients
against default CDF tables while inter frames write from start_cdfs
(+31% over-price on one-coefficient inter blocks). Pricing with the real
tables (EC_AV1_PRICE_FRAME_CDFS=1) helps both films and hurts screen, so
it ships off; a content-gated variant is in flight.
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+75 -1
@@ -3821,7 +3821,14 @@ fn code_square_inter(
38213821 // compound block's residual is small enough that the four extra
38223822 // per-unit txb_skip/eob symbols cost more ladder bytes than this
38233823 // encoder's static-CDF estimate prices them at, so the local RD
3824- // win does not convert. The flat trial stays.
3824+ // win does not convert. lane-av1txbits REBUILT it on top of a
3825+ // search that prices against the tables the frame is really
3826+ // written with (`tile::arm_pricing_cdfs`, the estimate error on
3827+ // these very blocks measured down from +31% to +3%) and measured
3828+ // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
3829+ // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
3830+ // same build without it. The static-CDF estimate was NOT what
3831+ // held the compound var-tx trial back. The flat trial stays.
38253832 let (levels, tx_depth, dcost) = if info.ref1.is_some() {
38263833 luma.commit(x, y, side, &luma_new);
38273834 (luma_new.levels.clone(), 0, 0.0)
@@ -4535,6 +4542,10 @@ pub(crate) fn encode_key_frame_inner(
45354542 (picture.height).min(render.1),
45364543 );
45374544 arm_seq_screen(screen);
4545+ // A key frame's writer really does start from the defaults, and a search
4546+ // worker may be carrying an inter frame's armed tables (lane-av1txbits):
4547+ // disarm, or a key frame's bits would depend on which thread searched it.
4548+ crate::tile::arm_pricing_cdfs(None);
45384549 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
45394550 // forces deblocking, CDEF and loop restoration OFF for this frame
45404551 // (frame.rs:194/210/252/272), so it is only set when the source repeats
@@ -4674,6 +4685,7 @@ pub(crate) fn encode_key_frame_inner(
46744685 let search_tile = |index: usize,
46754686 fctx: &crate::decode::FrameCtx|
46764687 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
4688+ crate::tile::arm_pricing_cdfs(None);
46774689 let rect = layout.rect(index);
46784690 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
46794691 let mut chroma = [
@@ -4951,6 +4963,7 @@ pub(crate) fn encode_key_frame_inner(
49514963 let mut cdfs = start_cdfs.0.clone();
49524964 crate::tile::arm_screen(screen);
49534965 crate::tile::arm_intrabc(allow_intrabc);
4966+ crate::tile::arm_pricing_cdfs(None);
49544967 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
49554968 mi_cols,
49564969 mi_rows,
@@ -6227,6 +6240,15 @@ fn search_inter_block(
62276240 }
62286241
62296242 let best = best.expect("the search offers at least the intra modes");
6243+ // lane-av1txbits BUILT the transform-depth search this path lacks -- a
6244+ // 32x32 single-reference winner offered `commit_inter_luma`'s four 16x16
6245+ // units against its flat trial, exactly as a 16x16 winner is -- and
6246+ // MEASURED it flat to slightly worse: +78.7/+95.1/+54.6 vs libaom and
6247+ // +36.1/+56.2/+1.8 vs rav1e, against the +78.8/+95.1/+54.5 and
6248+ // +36.1/+56.4/+1.4 this code scores, while the split fired on 40.2% of
6249+ // the film's inter blocks and 17.6% of the screen's. The same shape as
6250+ // the compound trial set below: a local RD win that does not convert into
6251+ // ladder bytes. The flat 32x32 transform stays.
62306252 luma.commit(x, y, BLOCK, &best.luma);
62316253 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
62326254 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
@@ -6381,6 +6403,9 @@ pub(crate) fn encode_inter_frame(
63816403 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
63826404 // never reached the tool).
63836405 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6406+ // The search prices coefficients against the tables this frame's writer
6407+ // starts from, not against the defaults (lane-av1txbits).
6408+ crate::tile::arm_pricing_cdfs(start_cdfs);
63846409 if let Some(p) = pyramid {
63856410 header.show_frame = p.show_frame;
63866411 header.showable_frame = !p.show_frame;
@@ -6501,6 +6526,7 @@ pub(crate) fn encode_inter_frame(
65016526 // search step) is read by the SEARCH, so every worker arms it or the
65026527 // tile's bits depend on the thread count.
65036528 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6529+ crate::tile::arm_pricing_cdfs(start_cdfs);
65046530 let rect = layout.rect(index);
65056531 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
65066532 let mut chroma = [
@@ -6971,6 +6997,7 @@ pub(crate) fn encode_inter_frame(
69716997 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
69726998 crate::tile::arm_screen(screen);
69736999 let mut cdfs = start_cdfs.0.clone();
7000+ crate::tile::arm_pricing_cdfs(Some(&cdfs));
69747001 // Each tile's own MV grid: a candidate scan never reaches past
69757002 // the tile's bounds, so a grid holding only this tile's own
69767003 // blocks reads exactly as the decoder's frame-wide one does
@@ -9459,6 +9486,10 @@ mod tests {
94599486 // (compound share 8.8% -> 11.5%): a compound block carries a second
94609487 // reference tree, a compound mode symbol and -- for the half-new modes
94619488 // -- an MV residual, none of which the coefficient sum counts.
9489+ // lane-av1txbits: under `EC_AV1_PRICE_FRAME_CDFS=1` this reads +32.6%
9490+ // instead -- pricing against the tables the frame's writer really
9491+ // starts from collapses the over-price above to nothing, so the whole
9492+ // remaining gap is the syntax the coefficient sum leaves out.
94629493 assert!(
94639494 worst_under <= 0.32,
94649495 "the writer spent {:.2}% more than the search priced -- more than \
@@ -9467,6 +9498,49 @@ mod tests {
94679498 );
94689499 }
94699500
9501+ /// The census behind step (1) of the pricer lane: for every transform
9502+ /// block the writer really codes, what the search priced those levels at
9503+ /// against what the writer spent on them, split by table set and non-zero
9504+ /// count. One average hides the interesting part -- the classes the
9505+ /// estimate is systematically wrong about (all-zero blocks, the
9506+ /// one-coefficient blocks the inter search lives on) -- so the split is
9507+ /// printed and only the total is asserted on.
9508+ #[test]
9509+ fn pricer_error_census_by_block_class() {
9510+ let fctx = &crate::decode::FrameCtx::new();
9511+ let (width, height) = (256usize, 128usize);
9512+ let pictures: Vec<Picture> = (0..5)
9513+ .map(|i| panned_test_card(width, height, i * 2))
9514+ .collect();
9515+ crate::tile::pricer_census_on();
9516+ let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9517+ let rows = crate::tile::take_pricer_census();
9518+ assert!(!rows.is_empty(), "the census saw no transform block");
9519+
9520+ println!("| set | nz | blocks | priced bits | written bits | error |");
9521+ println!("|---|---|---|---|---|---|");
9522+ let (mut priced_all, mut written_all) = (0.0, 0.0);
9523+ for ((set, bucket), (blocks, priced, written)) in &rows {
9524+ priced_all += priced;
9525+ written_all += written;
9526+ println!(
9527+ "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
9528+ crate::tile::census_bucket_label(*bucket),
9529+ if *written > 0.0 {
9530+ (priced - written) / written * 100.0
9531+ } else {
9532+ 0.0
9533+ }
9534+ );
9535+ }
9536+ println!(
9537+ "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
9538+ rows.values().map(|r| r.0).sum::<u64>(),
9539+ (priced_all - written_all) / written_all * 100.0
9540+ );
9541+ assert!(written_all > 0.0);
9542+ }
9543+
94709544 /// Low motion has to actually buy something: at least one inter frame of
94719545 /// a panning sequence has to cost fewer bytes than the key frame that
94729546 /// starts it, and the inter-block share it prints has to be non-zero --
crates/ec-av1/src/tile.rsmodified+131 -7
@@ -10,6 +10,8 @@
1010 //! off as they arrive.
1111
1212 use std::cell::RefCell;
13+#[cfg(test)]
14+use std::collections::BTreeMap;
1315 use std::sync::LazyLock;
1416
1517 use ec_core::{Error, Result};
@@ -3513,6 +3515,10 @@ fn write_block_planes(
35133515 } else {
35143516 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
35153517 };
3518+ #[cfg(test)]
3519+ let before = enc.tell();
3520+ #[cfg(test)]
3521+ let q_ctx = cdfs.q_ctx;
35163522 write_coeffs(
35173523 enc,
35183524 &mut cdfs.txb(planes[plane], mode),
@@ -3522,6 +3528,8 @@ fn write_block_planes(
35223528 dc_sign_ctx(around[plane].dc_vote),
35233529 Some(plane),
35243530 );
3531+ #[cfg(test)]
3532+ census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before));
35253533 ec_rng_trace(|| {
35263534 format!(
35273535 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
@@ -3602,6 +3610,10 @@ fn write_luma_tus(
36023610 neighbours.luma_skip_ctx(tu_mi, tx / MI)
36033611 };
36043612 let around = neighbours.around_mi(tu_mi, tx)[0];
3613+ #[cfg(test)]
3614+ let before = enc.tell();
3615+ #[cfg(test)]
3616+ let q_ctx = cdfs.q_ctx;
36053617 write_coeffs(
36063618 enc,
36073619 &mut cdfs.txb(set, mode),
@@ -3611,6 +3623,8 @@ fn write_luma_tus(
36113623 dc_sign_ctx(around.dc_vote),
36123624 Some(0),
36133625 );
3626+ #[cfg(test)]
3627+ census_record(set, q_ctx, &unit, f64::from(enc.tell() - before));
36143628 if n > 1 {
36153629 neighbours.record_mi_luma(tu_mi, tx, &unit);
36163630 }
@@ -3970,13 +3984,14 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
39703984 // q-context per thread beside a pristine one and restore just those from
39713985 // it. The state the price is taken against is identical to a fresh
39723986 // `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))));
3987+ // lane-av1txbits: an inter frame's writer does NOT start from the
3988+ // defaults -- it starts from the tables the previous frame stored (spec
3989+ // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the
3990+ // defaults charged the search for a narrowing the writer no longer pays.
3991+ // The census measured that at +31% on the one-coefficient inter blocks
3992+ // the search lives on. `arm_pricing_cdfs` puts the frame's own starting
3993+ // tables under the price; nothing armed keeps the old default behaviour.
3994+ let price = |slot: &mut (Cdfs, Cdfs)| {
39803995 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
39813996 let src = pristine.txb(set, DC_PRED);
39823997 let mut coding = scratch.txb(set, DC_PRED);
@@ -4002,9 +4017,118 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
40024017 let mut enc = SymbolEncoder::pricer();
40034018 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
40044019 enc.bits()
4020+ };
4021+ PRICING_BASE.with_borrow_mut(|base| {
4022+ if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) {
4023+ return price(slot);
4024+ }
4025+ PRICING.with_borrow_mut(|slots| {
4026+ let slot = slots[q_ctx.min(3)]
4027+ .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
4028+ price(slot)
4029+ })
40054030 })
40064031 }
40074032
4033+thread_local! {
4034+ /// The default tables every price falls back to, one pristine/scratch
4035+ /// pair per q-context (see [`coeff_bits`] for why the pair is kept).
4036+ static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
4037+ const { RefCell::new([None, None, None, None]) };
4038+ /// The tables the frame being searched will really be written against,
4039+ /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread
4040+ /// that prices -- the search jobs re-arm their own worker, exactly like
4041+ /// the other tile thread-locals.
4042+ static PRICING_BASE: RefCell<Option<Box<(Cdfs, Cdfs)>>> = const { RefCell::new(None) };
4043+}
4044+
4045+/// Arms the tables [`coeff_bits`] prices against on this thread: the state
4046+/// this frame's tile writer starts from. `None` goes back to the per-q-context
4047+/// defaults (a key frame, whose writer really does start there).
4048+///
4049+/// OFF by default (`EC_AV1_PRICE_FRAME_CDFS=1`). It is the more accurate
4050+/// estimate by measurement -- the pricer census
4051+/// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every
4052+/// transform block, and the one- and two-coefficient inter blocks the search
4053+/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy does not
4054+/// convert into ladder bytes on every clip: on the 640x384 gate it scores
4055+/// +78.8/+95.1/+54.5 vs libaom and +36.1/+56.4/+1.4 vs rav1e against the
4056+/// +79.9/+94.6/+54.5 and +37.3/+55.7/+1.1 the defaults score (film 1080p
4057+/// down 1.1, film 2160p up 0.5, screen flat), and on the native crops
4058+/// +18.0/+47.3/+60.7 and +0.7/+19.2/-7.3 against +18.9/+48.2/+59.3 and
4059+/// +1.5/+19.8/-10.0 (both film clips down against both references, screen up
4060+/// 1.4/2.7). Two clips better, one worse: it does not meet this lane's keep
4061+/// rule, so it ships as a knob rather than as the default.
4062+pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>) {
4063+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4064+ let on = *ON.get_or_init(|| std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() == Ok("1"));
4065+ PRICING_BASE.with_borrow_mut(|slot| {
4066+ *slot = base.filter(|_| on).map(|c| Box::new((c.clone(), c.clone())));
4067+ });
4068+}
4069+
4070+/// The pricer census (`pricer_census_on`): for every transform block the tile
4071+/// writer really codes, the bits it spent against the bits [`coeff_bits`]
4072+/// prices those very levels at -- the search's rate term measured against the
4073+/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a
4074+/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the
4075+/// eob of a one-coefficient block, a whole size) shows up on its own row
4076+/// rather than inside one average.
4077+/// Thread-local, so a census cannot pick up the blocks of another test's
4078+/// encode running beside it; a multi-tile, multi-threaded encode would
4079+/// therefore only census the tiles this thread wrote, which is every tile of
4080+/// the one-tile-one-thread encodes the gates print it from.
4081+#[cfg(test)]
4082+type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>;
4083+#[cfg(test)]
4084+thread_local! {
4085+ static CENSUS: RefCell<Option<CensusRows>> = const { RefCell::new(None) };
4086+}
4087+
4088+/// Starts a census on this thread, discarding anything a previous one left.
4089+#[cfg(test)]
4090+pub(crate) fn pricer_census_on() {
4091+ CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new()));
4092+}
4093+
4094+/// Stops the census and hands back its rows: (set, non-zero bucket) ->
4095+/// (blocks, priced bits, written bits).
4096+#[cfg(test)]
4097+pub(crate) fn take_pricer_census() -> CensusRows {
4098+ CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default()
4099+}
4100+
4101+/// The label of a non-zero bucket, for the tables the gates print.
4102+#[cfg(test)]
4103+pub(crate) fn census_bucket_label(bucket: usize) -> &'static str {
4104+ ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket]
4105+}
4106+
4107+#[cfg(test)]
4108+fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) {
4109+ if CENSUS.with_borrow(|c| c.is_none()) {
4110+ return;
4111+ }
4112+ let nz = grid.iter().filter(|&&l| l != 0).count();
4113+ let bucket = match nz {
4114+ 0 => 0,
4115+ 1 => 1,
4116+ 2 => 2,
4117+ 3..=4 => 3,
4118+ 5..=8 => 4,
4119+ 9..=16 => 5,
4120+ _ => 6,
4121+ };
4122+ let priced = coeff_bits(grid, set, q_ctx);
4123+ CENSUS.with_borrow_mut(|rows| {
4124+ let rows = rows.as_mut().expect("the census is on");
4125+ let row = rows.entry((format!("{set:?}"), bucket)).or_default();
4126+ row.0 += 1;
4127+ row.1 += priced;
4128+ row.2 += written;
4129+ });
4130+}
4131+
40084132 /// What the partition symbol of a block of `side` samples costs, in bits, when
40094133 /// it says the block is split (or that it is not).
40104134 ///