Price the search against the tables the frame is really written with, plus a per-class pricer census
Browse files at this commit95c183bfc7d0bc82aea932f3d128f0d883868350Parent: 8060962- feat
- price the search against the tables the frame is really written with, plus a per-class pricer census
3 changed files +168 -9
- crates/ec-av1/src/cdf_state.rs +6 -1
- crates/ec-av1/src/encode.rs +60 -1
- crates/ec-av1/src/tile.rs +102 -7
crates/ec-av1/src/cdf_state.rsmodified+6 -1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | use crate::cdf; |
| 15 | 15 | |
| 16 | 16 | /// Which of the four coefficient table sets a transform block is coded with. |
| 17 | -#[derive(Clone, Copy)] | |
| 17 | +#[derive(Clone, Copy, Debug)] | |
| 18 | 18 | pub(crate) enum TxbSet { |
| 19 | 19 | /// The 32x32 luma transform of an intra 32x32 block. `get_tx_set` is |
| 20 | 20 | /// DCT-only at this size for an intra block, so no `tx_type` symbol is |
| @@ -303,6 +303,10 @@ pub(crate) struct TxbTables<'a> { | ||
| 303 | 303 | /// Every table a key frame's tile writer adapts. |
| 304 | 304 | #[derive(Clone)] |
| 305 | 305 | 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, | |
| 306 | 310 | /// The partition symbol of a 64x64 superblock. |
| 307 | 311 | /// `partition_cdf`'s `BLOCK_128X128` rows (8 symbols). |
| 308 | 312 | pub partition_w128: [[u16; 9]; 4], |
| @@ -968,6 +972,7 @@ impl Cdfs { | ||
| 968 | 972 | /// quantizer, so they are the same for every `q_ctx`. |
| 969 | 973 | pub fn new(q_ctx: usize) -> Cdfs { |
| 970 | 974 | Cdfs { |
| 975 | + q_ctx, | |
| 971 | 976 | partition_w128: cdf::PARTITION_W128, |
| 972 | 977 | partition_w64: cdf::PARTITION_W64, |
| 973 | 978 | partition_w32: cdf::PARTITION_W32, |
crates/ec-av1/src/encode.rsmodified+60 -1
| @@ -4535,6 +4535,10 @@ pub(crate) fn encode_key_frame_inner( | ||
| 4535 | 4535 | (picture.height).min(render.1), |
| 4536 | 4536 | ); |
| 4537 | 4537 | 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); | |
| 4538 | 4542 | // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit |
| 4539 | 4543 | // forces deblocking, CDEF and loop restoration OFF for this frame |
| 4540 | 4544 | // (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( | ||
| 4674 | 4678 | let search_tile = |index: usize, |
| 4675 | 4679 | fctx: &crate::decode::FrameCtx| |
| 4676 | 4680 | -> Result<Vec<(usize, Superblock, Vec<u8>)>> { |
| 4681 | + crate::tile::arm_pricing_cdfs(None); | |
| 4677 | 4682 | let rect = layout.rect(index); |
| 4678 | 4683 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 4679 | 4684 | let mut chroma = [ |
| @@ -4951,6 +4956,7 @@ pub(crate) fn encode_key_frame_inner( | ||
| 4951 | 4956 | let mut cdfs = start_cdfs.0.clone(); |
| 4952 | 4957 | crate::tile::arm_screen(screen); |
| 4953 | 4958 | crate::tile::arm_intrabc(allow_intrabc); |
| 4959 | + crate::tile::arm_pricing_cdfs(None); | |
| 4954 | 4960 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 4955 | 4961 | mi_cols, |
| 4956 | 4962 | mi_rows, |
| @@ -6381,6 +6387,9 @@ pub(crate) fn encode_inter_frame( | ||
| 6381 | 6387 | // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob |
| 6382 | 6388 | // never reached the tool). |
| 6383 | 6389 | 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); | |
| 6384 | 6393 | if let Some(p) = pyramid { |
| 6385 | 6394 | header.show_frame = p.show_frame; |
| 6386 | 6395 | header.showable_frame = !p.show_frame; |
| @@ -6501,6 +6510,7 @@ pub(crate) fn encode_inter_frame( | ||
| 6501 | 6510 | // search step) is read by the SEARCH, so every worker arms it or the |
| 6502 | 6511 | // tile's bits depend on the thread count. |
| 6503 | 6512 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 6513 | + crate::tile::arm_pricing_cdfs(start_cdfs); | |
| 6504 | 6514 | let rect = layout.rect(index); |
| 6505 | 6515 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 6506 | 6516 | let mut chroma = [ |
| @@ -6971,6 +6981,7 @@ pub(crate) fn encode_inter_frame( | ||
| 6971 | 6981 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 6972 | 6982 | crate::tile::arm_screen(screen); |
| 6973 | 6983 | let mut cdfs = start_cdfs.0.clone(); |
| 6984 | + crate::tile::arm_pricing_cdfs(Some(&cdfs)); | |
| 6974 | 6985 | // Each tile's own MV grid: a candidate scan never reaches past |
| 6975 | 6986 | // the tile's bounds, so a grid holding only this tile's own |
| 6976 | 6987 | // blocks reads exactly as the decoder's frame-wide one does |
| @@ -9459,14 +9470,62 @@ mod tests { | ||
| 9459 | 9470 | // (compound share 8.8% -> 11.5%): a compound block carries a second |
| 9460 | 9471 | // reference tree, a compound mode symbol and -- for the half-new modes |
| 9461 | 9472 | // -- 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. | |
| 9462 | 9478 | assert!( |
| 9463 | - worst_under <= 0.32, | |
| 9479 | + worst_under <= 0.40, | |
| 9464 | 9480 | "the writer spent {:.2}% more than the search priced -- more than \ |
| 9465 | 9481 | the mode/mv syntax outside the coefficient sum explains", |
| 9466 | 9482 | worst_under * 100.0 |
| 9467 | 9483 | ); |
| 9468 | 9484 | } |
| 9469 | 9485 | |
| 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 | + | |
| 9470 | 9529 | /// Low motion has to actually buy something: at least one inter frame of |
| 9471 | 9530 | /// a panning sequence has to cost fewer bytes than the key frame that |
| 9472 | 9531 | /// 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 @@ | ||
| 10 | 10 | //! off as they arrive. |
| 11 | 11 | |
| 12 | 12 | use std::cell::RefCell; |
| 13 | +use std::collections::BTreeMap; | |
| 13 | 14 | use std::sync::LazyLock; |
| 14 | 15 | |
| 15 | 16 | use ec_core::{Error, Result}; |
| @@ -3513,6 +3514,8 @@ fn write_block_planes( | ||
| 3513 | 3514 | } else { |
| 3514 | 3515 | usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded) |
| 3515 | 3516 | }; |
| 3517 | + let before = enc.tell(); | |
| 3518 | + let q_ctx = cdfs.q_ctx; | |
| 3516 | 3519 | write_coeffs( |
| 3517 | 3520 | enc, |
| 3518 | 3521 | &mut cdfs.txb(planes[plane], mode), |
| @@ -3522,6 +3525,7 @@ fn write_block_planes( | ||
| 3522 | 3525 | dc_sign_ctx(around[plane].dc_vote), |
| 3523 | 3526 | Some(plane), |
| 3524 | 3527 | ); |
| 3528 | + census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before)); | |
| 3525 | 3529 | ec_rng_trace(|| { |
| 3526 | 3530 | format!( |
| 3527 | 3531 | "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", |
| @@ -3602,6 +3606,8 @@ fn write_luma_tus( | ||
| 3602 | 3606 | neighbours.luma_skip_ctx(tu_mi, tx / MI) |
| 3603 | 3607 | }; |
| 3604 | 3608 | let around = neighbours.around_mi(tu_mi, tx)[0]; |
| 3609 | + let before = enc.tell(); | |
| 3610 | + let q_ctx = cdfs.q_ctx; | |
| 3605 | 3611 | write_coeffs( |
| 3606 | 3612 | enc, |
| 3607 | 3613 | &mut cdfs.txb(set, mode), |
| @@ -3611,6 +3617,7 @@ fn write_luma_tus( | ||
| 3611 | 3617 | dc_sign_ctx(around.dc_vote), |
| 3612 | 3618 | Some(0), |
| 3613 | 3619 | ); |
| 3620 | + census_record(set, q_ctx, &unit, f64::from(enc.tell() - before)); | |
| 3614 | 3621 | if n > 1 { |
| 3615 | 3622 | neighbours.record_mi_luma(tu_mi, tx, &unit); |
| 3616 | 3623 | } |
| @@ -3970,13 +3977,14 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { | ||
| 3970 | 3977 | // q-context per thread beside a pristine one and restore just those from |
| 3971 | 3978 | // it. The state the price is taken against is identical to a fresh |
| 3972 | 3979 | // `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)| { | |
| 3980 | 3988 | let (pristine, scratch) = (&mut slot.0, &mut slot.1); |
| 3981 | 3989 | let src = pristine.txb(set, DC_PRED); |
| 3982 | 3990 | 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 { | ||
| 4002 | 4010 | let mut enc = SymbolEncoder::pricer(); |
| 4003 | 4011 | write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); |
| 4004 | 4012 | 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 | + }) | |
| 4005 | 4023 | }) |
| 4006 | 4024 | } |
| 4007 | 4025 | |
| 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 | + | |
| 4008 | 4103 | /// What the partition symbol of a block of `side` samples costs, in bits, when |
| 4009 | 4104 | /// it says the block is split (or that it is not). |
| 4010 | 4105 | /// |