forge
Explore
Log in

Don't you dare go Hollow

Price the search at the frame's own coefficient q-context, and measure the rate term's drift

Browse files at this commit

40e1d9474ec08e1debeffee903eab8382e8a9d80Ahmet Kaan GümüşParent: f336d0c
  • feat
    • price the search at the frame's own coefficient q-context, and measure the rate term's drift
Show full message
feat(av1): price the search at the frame's own coefficient q-context, and measure the rate term's drift

coeff_bits built its CDFs at a pinned q-context 2, so two of the four
points of the BD ladder ranked modes against another quantizer's
tables; it now takes the frame's own q_ctx_of(base_q_idx), the same one
the tile writer hands Cdfs::new.

Adds the instrument the rate work needs: predicted_coeff_bits(_sb) sums
what the search paid for the coefficients each kept block carries, and
predicted_coeff_bits_track_the_tile_the_writer_wrote compares that sum
with the bytes the writer emitted. Measured: -13.5% at the key frame
falling to +1.8% by the fifth frame -- the search over-prices, because
its CDFs stay at the tile defaults while the writer's adapt.
crates/ec-av1/src/encode.rsmodified+74 -3
@@ -89,6 +89,27 @@ fn lambda_scale() -> f64 {
89 }89 }
90 }90 }
91 91
92+// Every frame's predicted coefficient bits since the last
93+// `take_predicted_bits`, in coding order -- the encoder half of
94+// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
95+#[cfg(test)]
96+thread_local! {
97+ static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
98+}
99+
100+/// Records one frame's predicted coefficient bits.
101+#[cfg(test)]
102+fn record_predicted_bits(bits: f64) {
103+ PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
104+}
105+
106+/// Takes (and clears) what the frames encoded on this thread were predicted to
107+/// spend on coefficients.
108+#[cfg(test)]
109+pub(crate) fn take_predicted_bits() -> Vec<f64> {
110+ PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
111+}
112+
92 /// Whether a 32x32 block may be split into four 16x16 ones when the trial says113 /// Whether a 32x32 block may be split into four 16x16 ones when the trial says
93 /// four cost less. Set from the measurement in the lane report.114 /// four cost less. Set from the measurement in the lane report.
94 const SPLIT_BLOCKS: bool = true;115 const SPLIT_BLOCKS: bool = true;
@@ -719,7 +740,7 @@ impl Plane<'_> {
719 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())740 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
720 .sum()741 .sum()
721 } else {742 } else {
722- crate::tile::coeff_bits(&levels, at.set)743+ crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx))
723 };744 };
724 #[cfg(test)]745 #[cfg(test)]
725 stage_add(3, t.elapsed());746 stage_add(3, t.elapsed());
@@ -803,7 +824,7 @@ impl Plane<'_> {
803 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())824 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
804 .sum()825 .sum()
805 } else {826 } else {
806- crate::tile::coeff_bits(&levels, set)827+ crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx))
807 };828 };
808 #[cfg(test)]829 #[cfg(test)]
809 stage_add(3, t.elapsed());830 stage_add(3, t.elapsed());
@@ -2364,6 +2385,8 @@ pub(crate) fn encode_key_frame_inner(
2364 }2385 }
2365 }2386 }
2366 2387
2388+ #[cfg(test)]
2389+ record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
2367 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?;2390 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?;
2368 let mut stream = temporal_delimiter();2391 let mut stream = temporal_delimiter();
2369 stream.extend_from_slice(&sequence_header_obu(&seq)?);2392 stream.extend_from_slice(&sequence_header_obu(&seq)?);
@@ -3308,6 +3331,8 @@ pub(crate) fn encode_inter_frame(
3308 .filter(|b| b.inter.is_some())3331 .filter(|b| b.inter.is_some())
3309 .count() as f643332 .count() as f64
3310 / modes.len() as f64;3333 / modes.len() as f64;
3334+ #[cfg(test)]
3335+ record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
3311 let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?;3336 let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?;
3312 let mut stream = temporal_delimiter();3337 let mut stream = temporal_delimiter();
3313 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3338 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -5168,6 +5193,52 @@ mod tests {
5168 }5193 }
5169 }5194 }
5170 5195
5196+ /// The rate term the mode search ranks every decision by has to be the
5197+ /// rate the writer then spends. The search prices a block's coefficients
5198+ /// through `tile::coeff_bits` -- the writer's own symbol chain, but
5199+ /// against the default CDFs a tile starts from and the contexts of a
5200+ /// block whose neighbours coded nothing -- while the tile writer codes
5201+ /// them against a state that has been adapting all frame (the
5202+ /// price-the-narrowing class). This measures that drift: the sum of what
5203+ /// the search paid for the coefficients it kept, against the bytes the
5204+ /// writer actually emitted for the whole tile (which also carries the
5205+ /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
5206+ /// expected to be the larger of the two).
5207+ #[test]
5208+ fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
5209+ let fctx = &crate::decode::FrameCtx::new();
5210+ let (width, height) = (256usize, 128usize);
5211+ let pictures: Vec<Picture> = (0..5)
5212+ .map(|i| panned_test_card(width, height, i * 2))
5213+ .collect();
5214+ let _ = take_predicted_bits();
5215+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
5216+ let predicted = take_predicted_bits();
5217+ assert_eq!(predicted.len(), encoded.frames.len());
5218+
5219+ eprintln!("frame predicted bits written bits drift");
5220+ let mut worst: f64 = 0.0;
5221+ for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() {
5222+ let written = frame.tile.len() as f64 * 8.0;
5223+ let drift = (written - bits) / written;
5224+ worst = worst.max(drift.abs());
5225+ eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
5226+ }
5227+ // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
5228+ // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
5229+ // over-prices every frame but the last (its sum EXCLUDES the
5230+ // partition/mode/skip/mv syntax the written side carries, so the true
5231+ // coefficient over-price is larger still): the writer's CDFs adapt to
5232+ // the content while the search's stay at the defaults. The bound is
5233+ // set just above the worst measured point -- a widening drift is the
5234+ // thing this gate exists to catch.
5235+ assert!(
5236+ worst <= 0.16,
5237+ "the search's rate term drifted {:.2}% from the bits the writer spent",
5238+ worst * 100.0
5239+ );
5240+ }
5241+
5171 /// Low motion has to actually buy something: at least one inter frame of5242 /// Low motion has to actually buy something: at least one inter frame of
5172 /// a panning sequence has to cost fewer bytes than the key frame that5243 /// a panning sequence has to cost fewer bytes than the key frame that
5173 /// starts it, and the inter-block share it prints has to be non-zero --5244 /// starts it, and the inter-block share it prints has to be non-zero --
@@ -5289,7 +5360,7 @@ mod tests {
5289 };5360 };
5290 let t = Instant::now();5361 let t = Instant::now();
5291 for _ in 0..N {5362 for _ in 0..N {
5292- std::hint::black_box(crate::tile::coeff_bits(&levels, set));5363+ std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2));
5293 }5364 }
5294 let entropy_t = t.elapsed() / N;5365 let entropy_t = t.elapsed() / N;
5295 5366
crates/ec-av1/src/tile.rsmodified+83 -5
@@ -1557,18 +1557,96 @@ fn default_scan(side: usize) -> Vec<u16> {
1557 /// so one table is all the search needs; a second block size would need its1557 /// so one table is all the search needs; a second block size would need its
1558 /// own entry point rather than a size argument, because the table and the scan1558 /// own entry point rather than a size argument, because the table and the scan
1559 /// have to agree.1559 /// have to agree.
1560+/// What the search paid for every coefficient of `blocks`, in bits: the same
1561+/// [`coeff_bits`] price the mode search ranked those blocks by, summed over
1562+/// the blocks that were actually kept.
1563+///
1564+/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote`
1565+/// (lane-av1rd1): the writer codes these levels against a state that has
1566+/// adapted away from the defaults `coeff_bits` prices with, and against real
1567+/// neighbour contexts instead of the empty ones, so the sum here and the tile
1568+/// the writer produced differ by exactly that drift plus the non-coefficient
1569+/// syntax (partition/mode/skip/mv symbols) the sum leaves out.
1570+#[cfg(test)]
1571+fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> {
1572+ let mut grid = vec![0i32; side * side];
1573+ for c in coeffs {
1574+ grid[usize::from(c.row) * side + usize::from(c.col)] = c.level;
1575+ }
1576+ grid
1577+}
1578+
1579+#[cfg(test)]
1580+pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 {
1581+ let q_ctx = crate::decode::q_ctx_of(base_q_idx);
1582+ superblocks
1583+ .iter()
1584+ .map(|sb| match sb {
1585+ // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the
1586+ // top-left 32x32 carries coefficients) and each chroma plane at
1587+ // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
1588+ Superblock::Whole(block) if !block.skip => {
1589+ coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx)
1590+ + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx)
1591+ + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx)
1592+ }
1593+ Superblock::Whole(_) => 0.0,
1594+ Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),
1595+ })
1596+ .sum()
1597+}
1598+
1599+#[cfg(test)]
1600+pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
1601+ let q_ctx = crate::decode::q_ctx_of(base_q_idx);
1602+ fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 {
1603+ if let Some(leaves) = &block.eight {
1604+ return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum();
1605+ }
1606+ if block.skip {
1607+ return 0.0;
1608+ }
1609+ let inter = block.inter.is_some();
1610+ let (luma, chroma) = match (side, inter) {
1611+ (32, false) => (TxbSet::Luma32, TxbSet::Chroma16),
1612+ (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16),
1613+ (16, false) => (TxbSet::Luma16, TxbSet::Chroma8),
1614+ (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8),
1615+ (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
1616+ (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
1617+ };
1618+ coeff_bits(&dense(&block.luma, side), luma, q_ctx)
1619+ + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx)
1620+ + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx)
1621+ }
1622+ blocks
1623+ .iter()
1624+ .map(|q| {
1625+ let side = match q {
1626+ Quadrant::Whole(_) => 32,
1627+ Quadrant::Split(_) => 16,
1628+ };
1629+ q.blocks().iter().map(|b| block_bits(b, side, q_ctx)).sum::<f64>()
1630+ })
1631+ .sum()
1632+}
1633+
1560 #[cfg(test)]1634 #[cfg(test)]
1561 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {1635 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
1562- coeff_bits(grid, TxbSet::Luma32)1636+ coeff_bits(grid, TxbSet::Luma32, 2)
1563 }1637 }
1564 1638
1565 /// What one transform block's levels cost through the CDFs of `set`, in bits.1639 /// What one transform block's levels cost through the CDFs of `set`, in bits.
1566 ///1640 ///
1567 /// The search runs before the tile is written, so the adapted state the block1641 /// The search runs before the tile is written, so the adapted state the block
1568 /// will really be coded against does not exist yet: the price is taken against1642 /// will really be coded against does not exist yet: the price is taken against
1569-/// the defaults every tile starts from, and against the contexts a block whose1643+/// the defaults every tile starts from, at the frame's own coefficient
1570-/// neighbours coded nothing reads.1644+/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at
1571-pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 {1645+/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of
1646+/// the four points of the BD ladder were priced against another quantizer's
1647+/// tables), and against the contexts a block whose neighbours coded nothing
1648+/// reads.
1649+pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
1572 /// Built once per size: the search prices thirteen modes for every block,1650 /// Built once per size: the search prices thirteen modes for every block,
1573 /// and the scan is the same table every time.1651 /// and the scan is the same table every time.
1574 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {1652 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
@@ -1579,7 +1657,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 {
1579 default_scan(TX32),1657 default_scan(TX32),
1580 ]1658 ]
1581 });1659 });
1582- let mut cdfs = Cdfs::new(2);1660+ let mut cdfs = Cdfs::new(q_ctx);
1583 let mut coding = cdfs.txb(set, DC_PRED);1661 let mut coding = cdfs.txb(set, DC_PRED);
1584 let scan = match coding.side {1662 let scan = match coding.side {
1585 TX4 => &SCANS[0],1663 TX4 => &SCANS[0],