forge
Explore
Log in

Don't you dare go Hollow

The mode search prices its coefficients through the writer's CDFs

Browse files at this commit

870ed18e458ed6d0912109a4ff1421d7206ab939Ahmet Kaan GümüşParent: eba2ab8
  • feat
    • the mode search prices its coefficients through the writer's CDFs
Show full message
feat(av1): the mode search prices its coefficients through the writer's CDFs

The mode search costed the mode symbol exactly and the levels with a
magnitude estimate. Now the levels go through write_coeffs on a throwaway
encoder, so a trial is ranked by the bits the tile writer will really spend
on it: end-of-block position, base levels, base range, signs and the Golomb
tail, under the block's own contexts.

The bit account prices the interval narrowing each symbol performs rather
than its table entry, because the coder's eight-bit range multiply and its
EC_MIN_PROB floor put the table entry 8% off the bytes actually written.

Worth -1.19% BD-rate on a 1080p film frame and -0.20% on a screen capture
against the estimate; LAMBDA_SCALE stays 0.1, re-swept.
crates/ec-av1/src/encode.rsmodified+55 -15
@@ -36,15 +36,27 @@ const BLOCK: usize = 32;
36 /// How heavily the mode search weighs rate against squared error, in units of36 /// How heavily the mode search weighs rate against squared error, in units of
37 /// the quantizer's reconstruction step squared per bit.37 /// the quantizer's reconstruction step squared per bit.
38 ///38 ///
39-/// Swept twice over three of his clips and three synthetic pictures39+/// Swept three times over his clips and three synthetic pictures
40-/// (`probe_lambda` and `probe_directional`, and the tables in the two lane40+/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
41-/// reports). The first sweep, before the mode symbol was costed, put the best41+/// the three lane reports). The first sweep, before the mode symbol was
42-/// point at 0.05; costing it moved the point to 0.1, where the directional42+/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
43-/// modes stop costing rate on the pictures that do not want them (+0.05% on43+/// third sweep, after the levels were costed through the writer's own CDFs
44-/// screen capture against +0.19% at 0.05) without giving up any of what they44+/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
45-/// save on the pictures that do (-53.0% on a diagonal).45+/// on film and -0.20% against -0.14% on screen capture.
46 const LAMBDA_SCALE: f64 = 0.1;46 const LAMBDA_SCALE: f64 = 0.1;
47 47
48+/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
49+/// picks it is the thing running. A release build has no such knob.
50+fn lambda_scale() -> f64 {
51+ let swept = std::env::var("EC_AV1_LAMBDA")
52+ .ok()
53+ .and_then(|v| v.parse::<f64>().ok());
54+ match swept {
55+ Some(scale) if cfg!(test) => scale,
56+ _ => LAMBDA_SCALE,
57+ }
58+}
59+
48 /// One 8-bit planar 4:2:0 picture.60 /// One 8-bit planar 4:2:0 picture.
49 #[derive(Clone, Debug, PartialEq, Eq)]61 #[derive(Clone, Debug, PartialEq, Eq)]
50 pub struct Picture {62 pub struct Picture {
@@ -303,13 +315,25 @@ impl Plane<'_> {
303 sse += error * error;315 sse += error * error;
304 }316 }
305 }317 }
306- // What a level costs is close enough to its magnitude's width plus a318+ // What the levels cost is priced through the same CDFs the tile writer
307- // sign and a run, which is all the search needs to rank modes.319+ // will code them with, so the search ranks modes by the bits they
308- let bits: f64 = levels320+ // actually spend. Chroma blocks are not searched, so only the 32x32
309- .iter()321+ // luma table is asked for.
310- .filter(|&&level| level != 0)322+ let bits = if side != BLOCK {
311- .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())323+ 0.0
312- .sum();324+ } else if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
325+ // What the search used before it could price a block exactly: a
326+ // level costs its magnitude's width plus a sign and a run. Kept
327+ // reachable from the sweep so the two rate terms can be compared
328+ // on one build.
329+ levels
330+ .iter()
331+ .filter(|&&level| level != 0)
332+ .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
333+ .sum()
334+ } else {
335+ crate::tile::luma_32_coeff_bits(&levels)
336+ };
313 Trial {337 Trial {
314 levels,338 levels,
315 reconstruction,339 reconstruction,
@@ -535,7 +559,7 @@ pub fn encode_key_frame_with_modes(
535 let search = Search {559 let search = Search {
536 base_q_idx,560 base_q_idx,
537 deadzone,561 deadzone,
538- lambda: LAMBDA_SCALE * step * step,562+ lambda: lambda_scale() * step * step,
539 modes,563 modes,
540 };564 };
541 565
@@ -809,6 +833,22 @@ mod tests {
809 }833 }
810 }834 }
811 835
836+ /// Prints the whole mode-search ladder, so two builds of the search can be
837+ /// compared against each other rather than each against its own baseline.
838+ #[test]
839+ #[ignore = "a sweep, not a gate"]
840+ fn probe_ladder() {
841+ for (name, picture) in sweep_pictures() {
842+ let all = ladder(&picture, &KEY_FRAME_MODES);
843+ let points = all
844+ .iter()
845+ .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
846+ .collect::<Vec<_>>()
847+ .join(" ");
848+ println!("ladder {name}: {points}");
849+ }
850+ }
851+
812 /// A striped picture, running one way or the other. The stripes are what852 /// A striped picture, running one way or the other. The stripes are what
813 /// separates a vertical predictor from a horizontal one: a mode search853 /// separates a vertical predictor from a horizontal one: a mode search
814 /// reading a transposed edge would pick the wrong one of the pair, which no854 /// reading a transposed edge would pick the wrong one of the pair, which no
crates/ec-av1/src/msac.rsmodified+49 -0
@@ -46,6 +46,11 @@ pub struct SymbolEncoder {
46 /// Flushed bytes before carry propagation: each entry can exceed `0xff` by46 /// Flushed bytes before carry propagation: each entry can exceed `0xff` by
47 /// the carry it owes the byte before it, which [`Self::finish`] adds in.47 /// the carry it owes the byte before it, which [`Self::finish`] adds in.
48 precarry: Vec<u16>,48 precarry: Vec<u16>,
49+ /// What every symbol written so far cost against the CDF it was written
50+ /// with, in bits. The arithmetic coder spends `-log2(p)` on a symbol of
51+ /// probability `p` to within the rounding of its interval, so this is what
52+ /// a search may price a decision with without coding it twice.
53+ bits: f64,
49 }54 }
50 55
51 impl Default for SymbolEncoder {56 impl Default for SymbolEncoder {
@@ -63,9 +68,21 @@ impl SymbolEncoder {
63 rng: 0x8000,68 rng: 0x8000,
64 cnt: -9,69 cnt: -9,
65 precarry: Vec::new(),70 precarry: Vec::new(),
71+ bits: 0.0,
66 }72 }
67 }73 }
68 74
75+ /// What the symbols written so far cost, in bits.
76+ pub fn bits(&self) -> f64 {
77+ self.bits
78+ }
79+
80+ /// Forgets the cost accumulated so far, so that the next stretch of
81+ /// symbols can be priced on its own.
82+ pub fn reset_bits(&mut self) {
83+ self.bits = 0.0;
84+ }
85+
69 /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder86 /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder
70 /// will after reading it (spec 8.3.2).87 /// will after reading it (spec 8.3.2).
71 ///88 ///
@@ -107,6 +124,12 @@ impl SymbolEncoder {
107 // Symbol 0 owns the top of the interval, so only its width moves.124 // Symbol 0 owns the top of the interval, so only its width moves.
108 r - v125 r - v
109 };126 };
127+ // What this symbol really cost is how far it narrowed the interval,
128+ // which is not quite its nominal probability: the coder works the
129+ // range through an eight-bit multiply and hands every symbol above
130+ // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than
131+ // the table entry is what makes the account match the bytes.
132+ self.bits -= (f64::from(rng) / f64::from(r)).log2();
110 self.normalize(low, rng);133 self.normalize(low, rng);
111 }134 }
112 135
@@ -431,6 +454,32 @@ pub(crate) mod tests {
431 }454 }
432 }455 }
433 456
457+ /// The bit account is what a search prices decisions with, so it has to
458+ /// agree with what the coder actually spends: over a long enough string the
459+ /// two are within the coder's own rounding, a fraction of a percent.
460+ #[test]
461+ fn the_bit_account_matches_the_bytes_written() {
462+ let mut enc = SymbolEncoder::new();
463+ let mut state: u32 = 0x1234_5678;
464+ let mut next = || {
465+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
466+ state
467+ };
468+ // A skewed CDF, so that the account has something to be wrong about:
469+ // an equiprobable string costs one bit a symbol however it is priced.
470+ let skewed: [u16; 3] = [29000, 1 << 15, 0];
471+ for _ in 0..20_000 {
472+ let symbol = usize::from(next() % 100 < 12);
473+ enc.symbol_fixed(symbol, &skewed);
474+ }
475+ let priced = enc.bits();
476+ let spent = (enc.finish().len() * 8) as f64;
477+ assert!(
478+ (priced - spent).abs() / spent < 0.01,
479+ "priced {priced:.0} bits, spent {spent:.0}"
480+ );
481+ }
482+
434 #[test]483 #[test]
435 fn empty_payload_is_short() {484 fn empty_payload_is_short() {
436 assert!(SymbolEncoder::new().finish().len() <= 2);485 assert!(SymbolEncoder::new().finish().len() <= 2);
crates/ec-av1/src/tile.rsmodified+92 -0
@@ -9,6 +9,8 @@
9 //! It is the skeleton the block modes, transform sizes and coefficients hang9 //! It is the skeleton the block modes, transform sizes and coefficients hang
10 //! off as they arrive.10 //! off as they arrive.
11 11
12+use std::sync::LazyLock;
13+
12 use ec_core::{Error, Result};14 use ec_core::{Error, Result};
13 15
14 use crate::cdf;16 use crate::cdf;
@@ -857,6 +859,29 @@ fn default_scan(side: usize) -> Vec<u16> {
857 scan859 scan
858 }860 }
859 861
862+/// What one 32x32 luma transform block's levels cost, in bits, priced through
863+/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
864+/// position, base levels, base range, signs and the Golomb tail all included.
865+///
866+/// The mode search calls this before the block's neighbours exist, so the two
867+/// neighbour-derived contexts (the block-skip context and the DC sign context)
868+/// are taken as zero. Every other context inside the block is exact, because
869+/// those are read from the block's own levels.
870+///
871+/// The encoder codes 32x32 luma only -- every superblock it emits is split --
872+/// so one table is all the search needs; a second block size would need its
873+/// own entry point rather than a size argument, because the table and the scan
874+/// have to agree.
875+pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
876+ /// Built once: the search prices thirteen modes for every block, and the
877+ /// scan is the same table every time.
878+ static SCAN: LazyLock<Vec<u16>> = LazyLock::new(|| default_scan(TX32));
879+ let mut enc = SymbolEncoder::new();
880+ enc.reset_bits();
881+ write_coeffs(&mut enc, &LUMA_32, grid, &SCAN, 0, 0);
882+ enc.bits()
883+}
884+
860 /// coeffs() for one plane's transform block of any coefficients the base and885 /// coeffs() for one plane's transform block of any coefficients the base and
861 /// base-range syntax reach (spec 5.11.39).886 /// base-range syntax reach (spec 5.11.39).
862 ///887 ///
@@ -1783,6 +1808,73 @@ mod tests {
1783 }1808 }
1784 }1809 }
1785 1810
1811+ /// The price the mode search pays for a block's levels has to be the price
1812+ /// the writer charges for them, or the search is ranking modes by a
1813+ /// fiction. Both halves are asked for the same grids under the same
1814+ /// neutral contexts, and the priced bits are compared against the bytes
1815+ /// the writer really spends.
1816+ #[test]
1817+ fn the_priced_coefficient_bits_match_the_bytes_written() {
1818+ let scan = default_scan(TX32);
1819+ // Three grids that reach different parts of the syntax: a lone DC, a
1820+ // sparse spread of small levels with both signs, and levels past the
1821+ // base-range alphabet so the Golomb tail runs.
1822+ let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
1823+ grids[0][0] = -7;
1824+ for (i, &pos) in scan.iter().enumerate().take(400) {
1825+ if i % 7 == 0 {
1826+ grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
1827+ }
1828+ }
1829+ grids[2][0] = 40;
1830+ for (i, &pos) in scan.iter().enumerate().take(64) {
1831+ grids[2][pos as usize] += i as i32 % 23 - 11;
1832+ }
1833+
1834+ // A single block is too short for the coder's own flush to average
1835+ // out, so all three go through one encoder and one flush.
1836+ let mut enc = SymbolEncoder::new();
1837+ let mut priced = 0.0;
1838+ for grid in &grids {
1839+ write_coeffs(&mut enc, &LUMA_32, grid, &scan, 0, 0);
1840+ priced += luma_32_coeff_bits(grid);
1841+ }
1842+ let spent = enc.finish().len() as f64 * 8.0;
1843+ assert!(
1844+ (priced - spent).abs() / spent < 0.02,
1845+ "priced {priced} bits, wrote {spent}"
1846+ );
1847+ }
1848+
1849+ /// A rate term the search can read as constant is a rate term that ranks
1850+ /// nothing, so the price is checked to move the way the levels move: an
1851+ /// empty block is the cheapest thing there is, one coefficient costs more
1852+ /// than none, and both spreading the coefficients and growing them costs
1853+ /// more again.
1854+ #[test]
1855+ fn the_price_grows_with_the_levels() {
1856+ let grid = |f: &dyn Fn(&mut Vec<i32>)| {
1857+ let mut g = vec![0i32; TX32 * TX32];
1858+ f(&mut g);
1859+ luma_32_coeff_bits(&g)
1860+ };
1861+ let empty = grid(&|_| {});
1862+ let one = grid(&|g| g[0] = 1);
1863+ let bigger = grid(&|g| g[0] = 30);
1864+ let spread = grid(&|g| {
1865+ for i in 0..TX32 {
1866+ g[i * TX32 + i] = 1;
1867+ }
1868+ });
1869+ assert!(empty < one, "{empty} {one}");
1870+ assert!(one < bigger, "{one} {bigger}");
1871+ assert!(one < spread, "{one} {spread}");
1872+ // An empty block is one symbol -- an expensive one, because a block
1873+ // with no coefficients at all is the rarer of the two under the
1874+ // neutral context -- and nothing else.
1875+ assert!(empty < 6.0, "an empty block is one skip symbol, not {empty}");
1876+ }
1877+
1786 /// Neighbouring blocks that each carry coefficients read their DC sign1878 /// Neighbouring blocks that each carry coefficients read their DC sign
1787 /// context, their prediction and their own contexts off each other, so a1879 /// context, their prediction and their own contexts off each other, so a
1788 /// frame whose four blocks all carry mixed-sign coefficients exercises what1880 /// frame whose four blocks all carry mixed-sign coefficients exercises what
lanes/av1-coeffcost-r1.report.mdadded+86 -0
@@ -0,0 +1,86 @@
1+# lane-av1-coeffcost r1 — the mode search prices its coefficients exactly
2+
3+The directional lane closed with the mode half of the rate term costed through
4+the writer's own CDFs and the level half still an estimate
5+(`2 + 2*log2(|level|+1)` per non-zero coefficient). This lane replaces that
6+estimate: a trial's levels are now priced through the very syntax and the very
7+tables `write_coeffs` will code them with.
8+
9+## What landed
10+
11+- `crates/ec-av1/src/msac.rs`: `SymbolEncoder` keeps a bit account.
12+ `symbol_fixed` prices *the interval narrowing it performs*, not the nominal
13+ probability of the table entry — the coder works its range through an
14+ eight-bit multiply and gives every symbol above the coded one a floor of
15+ `EC_MIN_PROB`, so the table entry is 8% off the truth on real coefficient
16+ data while the narrowing is exact. `bits()` and `reset_bits()` expose it.
17+- `crates/ec-av1/src/tile.rs`: `luma_32_coeff_bits()` — what one 32x32 luma
18+ transform block's levels cost, run through `write_coeffs` on a throwaway
19+ encoder: end-of-block group and offset, base levels, base range, DC sign,
20+ raw signs and the Golomb tail. The two neighbour-derived contexts (block
21+ skip, DC sign) are neutral because the search runs before the block's
22+ neighbours exist; every context read from the block's own levels is exact.
23+- `crates/ec-av1/src/encode.rs`: `Trial::bits` calls it. Chroma is not
24+ searched, so only the 32x32 luma table is asked for.
25+- `EC_AV1_LAMBDA` and `EC_AV1_ESTIMATE` sweep knobs, both `cfg!(test)`-only,
26+ so the two rate terms and any weight can be compared on one build.
27+
28+## Gates
29+
30+| Gate | Result |
31+| --- | --- |
32+| `the_priced_coefficient_bits_match_the_bytes_written` | three grids (lone DC, sparse ±small spread, levels past the base-range alphabet) priced within 2% of the bytes one encoder really spends |
33+| `the_bit_account_matches_the_bytes_written` (msac) | 20 000 skewed symbols, within 1% |
34+| `the_price_grows_with_the_levels` | empty < one coefficient < a bigger one; empty < a spread of 32; an empty block costs one skip symbol |
35+| full `ec-av1` suite | 78 passed, 0 failed, 3 ignored |
36+| `cargo clippy --release -p ec-av1 --all-targets` | 0 warnings |
37+
38+## Mutation kills
39+
40+| Mutation | Killed by |
41+| --- | --- |
42+| the price counts non-zero coefficients at 4 bits each | `the_price_grows_with_the_levels`, `the_priced_coefficient_bits_match_the_bytes_written` |
43+| the price is zero | those two, plus `the_search_beats_dc_alone` and `the_search_picks_the_direction_the_picture_runs` |
44+| the account adds one bit per symbol instead of pricing the narrowing | `the_priced_coefficient_bits_match_the_bytes_written` |
45+
46+## What it is worth (`probe_ladder`, BD-rate against the merged estimate arm)
47+
48+Three-point ladder (base_q_idx 110/90/70), luma PSNR. Negative is better.
49+
50+| Picture | exact @ 0.1 | exact @ 0.2 | estimate @ 0.05 |
51+| --- | --- | --- | --- |
52+| ReelC, 1080p film frame @600s, 640x352 | **-1.19%** | -0.98% | -0.08% |
53+| OBS screen capture 2026-08-25 16-27-54 @5s, 640x352 | **-0.20%** | -0.14% | +0.21% |
54+| test card 160x96 | -2.09% | -2.10% | +0.16% |
55+| diagonal 160x96 | -3.93% | -3.93% | +0.06% |
56+| stripes 160x96 | +0.00% | +0.00% | +0.51% |
57+
58+`LAMBDA_SCALE` stays 0.1: it is the best point on both of his clips, and 0.2
59+buys nothing on the synthetics. `probe_directional` at 0.1 with the exact term
60+reports the six directional modes worth -0.48% on the film frame and +0.06% on
61+screen capture against the seven non-directional ones (-53.0% → -54.90% on the
62+synthetic diagonal), with 43 of 220 and 14 of 220 blocks directional.
63+
64+Both clips are his own; no fixture-only claim in this table.
65+
66+## Dispositions
67+
68+- The block-skip and DC-sign contexts are neutral in the price while the writer
69+ reads them from neighbours: **accepted**. They cost at most one symbol per
70+ block and the search has no neighbour state to read at that point.
71+- Chroma trials are priced at zero bits: **accepted**. Chroma is coded DC-only
72+ and is not searched, so no ranking depends on it.
73+- Only the 32x32 luma table is priced: **accepted** for as long as the encoder
74+ emits split superblocks only. A whole-64x64 decision would need `LUMA_64`,
75+ and the table and the scan have to agree, so it takes an entry point of its
76+ own rather than a size argument.
77+
78+## Not in this lane
79+
80+- Block sizes below 32x32 and the partition decision (needs the luma-16 CDF
81+ tables and `EOB_PT_256_LUMA`).
82+- Transform types beyond `DCT_DCT`, and transform-size selection.
83+- CDF adaptation: every symbol is still written against the pinned tables, so
84+ the price is the price of a non-adaptive stream.
85+- Trellis or any rate-distortion optimisation of the levels themselves; this
86+ lane prices the levels the quantizer already chose, it does not change them.