diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 60d85406..6aa5fa23 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -798,6 +798,93 @@ fn b128_rect() -> bool { ENV.unwrap_or(true) && b128_root() } +/// lane-rectdq: whether the delta_q symbol group is priced on the root +/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's +/// attribution control (the pre-lane pricing, where a 128 rect root and the +/// four-superblock arm were both priced as if the group were free). +fn rectdq() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0") + }); + ENV.unwrap_or(true) +} + +/// lane-rectdq: what `crate::tile::write_delta_q` spends to move +/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of +/// `res` -- the same three pieces that writer codes, in its order: the +/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the +/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from +/// exactly this row), the escape literal pair when `abs >= 3`, and the sign +/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`). +pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 { + if res <= 0 { + return 0.0; + } + /// spec `DELTA_Q_SMALL`, as in the writer. + const DELTA_Q_SMALL: usize = 3; + let reduced = (target - cur) / res; + let abs = reduced.unsigned_abs() as usize; + // A pricing coder, not a sum of table entries: the escape's literal bits + // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB` + // floor, so each really costs a little over one bit (class + // `price-the-narrowing-not-the-table`). Read off the same + // `SymbolEncoder::bits` account the writer's own coder keeps. + let mut enc = crate::msac::SymbolEncoder::pricer(); + enc.reset_bits(); + enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q); + if abs >= DELTA_Q_SMALL { + let rem_bits = 31 - ((abs as u32) - 1).leading_zeros(); + enc.literal(rem_bits - 1, 3); + enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits); + } + if abs != 0 { + enc.literal(u32::from(reduced < 0), 1); + } + enc.bits() +} + +/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64 +/// superblock units): the group every root shape but a SKIPPED +/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for +/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64 +/// superblock under a 128 grid is that. +/// +/// The target is the root's own cell of the `sb_q` grid, exactly the entry +/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search -- +/// the writer's `plan.cur` only advances at the roots that really code a +/// group, and which those are is decided by this very comparison -- so the +/// PREVIOUS 128 root's target in raster order stands in for it (the frame's +/// `base_q_idx` at the first root of the frame, which is also the writer's +/// own per-tile reset). Wrong only where a neighbouring root came out a +/// skipped NONE block, and then only by the difference of two adjacent tpl +/// cells. +fn delta_q_bits_at_root( + sb_q: Option<&Vec>, + sb_cols: usize, + base_q_idx: u8, + res: i32, + (root_r, root_c): (usize, usize), +) -> f64 { + if !rectdq() || res <= 0 { + return 0.0; + } + let Some(q) = sb_q.filter(|q| !q.is_empty()) else { + return 0.0; + }; + let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]); + let target = at(root_r, root_c); + let cur = if root_c >= 2 { + at(root_r, root_c - 2) + } else if root_r >= 2 { + // The last 128 root of the row above, i.e. the previous one in the + // writer's raster walk. + at(root_r - 2, (sb_cols.saturating_sub(1)) & !1) + } else { + i32::from(base_q_idx) + }; + delta_q_bits(target, cur, res) +} + /// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT) /// halves since the last take (class `gate-blind-to-feature`). static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -9641,6 +9728,9 @@ fn search_root_128( sb_cols: usize, tpl_cells_x: usize, base_q_idx: u8, + // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan, + // zero when it does not -- what [`delta_q_bits_at_root`] prices with. + dq_res: i32, reference: &Picture, // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window, // built by the caller off the same grid the tile writer rebuilds its @@ -9798,8 +9888,16 @@ fn search_root_128( } let after = snapshot(luma, chroma, (x128, y128), SIDE); restore(luma, chroma, (x128, y128), SIDE, &base); + // lane-rectdq: a SKIPPED whole-superblock root is the one shape that + // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the + // residual arm above codes it like every other block does. + let dq = if block.skip { + 0.0 + } else { + delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c)) + }; Some(( - cost + lambda * crate::tile::partition_bits(SIDE, false), + cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq), lambda, block, after, @@ -9836,6 +9934,8 @@ fn search_root_128_rect( sb_cols: usize, tpl_cells_x: usize, base_q_idx: u8, + // lane-rectdq: see [`search_root_128`]'s own `dq_res`. + dq_res: i32, reference: &Picture, // The `LAST` + extra-reference pairs offered at this root; only the // reference and its picture are read here, since each HALF derives its @@ -9957,8 +10057,13 @@ fn search_root_128_rect( grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); let symbol = if horz { 1 } else { 2 }; let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?; + // lane-rectdq: the FIRST half sits at the root's own mode-info origin and + // codes the delta_q group whether it is skipped or not + // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second + // half is at a non-origin mi and codes none. + let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c)); Some(( - cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol), + cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq), lambda, [b0, b1], after, @@ -12690,6 +12795,9 @@ pub(crate) fn encode_inter_frame( header.delta.q_present = true; header.delta.q_res = res.trailing_zeros() as u8; } + // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with + // below, so the root search prices the group the writer really codes. + let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0); if let Some(g) = &sb_q { let mut levels: Vec = g.clone(); levels.sort_unstable(); @@ -12841,6 +12949,7 @@ pub(crate) fn encode_inter_frame( sb_cols, tpl_cells_x, base_q_idx, + dq_res, reference, &root_compound, fctx, @@ -12870,6 +12979,7 @@ pub(crate) fn encode_inter_frame( sb_cols, tpl_cells_x, base_q_idx, + dq_res, reference, &root_compound, horz, @@ -13525,8 +13635,19 @@ pub(crate) fn encode_inter_frame( cands.retain(|c| c.2 == usize::from(forced_ab)); } cands.sort_by(|a, b| a.0.total_cmp(&b.0)); + // lane-rectdq class sweep: under a 128 superblock grid the FOUR- + // superblock arm codes the delta_q group too -- the Whole64 writer + // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call + // with `!sb128_armed()`) and every smaller shape below it pass + // `is_whole_sb = false` under a 128 grid, so the arm's first + // (root-origin) superblock codes the group even when skipped. Only the skipped 128 + // NONE root escapes it, so the split side is charged here at the same + // root lambda the candidates are priced with. + let split_dq = + delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c)); if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next() - && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true) + && (cost128 + < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq) // The witness knobs take the root whatever it costs, so the // forced block really reaches the writer. || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed) diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index e1293230..2a357973 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -10939,4 +10939,46 @@ mod tests { "KF_Y_MODE's different probabilities must decode a different mode" ); } + + /// lane-rectdq witness: [`crate::encode::delta_q_bits`] prices exactly + /// what [`write_delta_q`] writes, over the whole `delta_q_abs` domain + /// (0..=20 steps, both signs -- the escape literal pair starts at 3 and + /// its `rem_bits` widens at 4, 5, 9 and 17). The writer is run into a + /// PRICING coder whose account (`SymbolEncoder::bits`) is the same + /// arithmetic-coder cost the pricer's `symbol_bits` sums, so the two + /// agree to floating-point noise, not to a tolerance band. + /// + /// Both sides read the DEFAULT `delta_q` row: the writer's `cdfs` is + /// rebuilt per case, exactly as every tile's is armed before its first + /// superblock. + #[test] + fn the_delta_q_pricer_matches_the_writer_over_the_whole_domain() { + const RES: i32 = 4; + const CUR: i32 = 128; + for steps in -20i32..=20 { + let target = CUR + steps * RES; + arm_delta_q(RES, 1, vec![u8::try_from(target).expect("in range")], 128); + let mut cdfs = Cdfs::new(2); + let mut enc = SymbolEncoder::pricer(); + enc.reset_bits(); + // `is_whole_sb = false`: the rect half / 64-superblock shape, + // the one whose pricer this witnesses. + write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true); + let written = enc.bits(); + let priced = crate::encode::delta_q_bits(target, CUR, RES); + assert!( + (written - priced).abs() < 1e-9, + "steps {steps}: writer {written} bits, pricer {priced}" + ); + } + // Disarmed plan: the writer codes nothing and the pricer charges + // nothing. + arm_delta_q(0, 1, Vec::new(), 128); + let mut cdfs = Cdfs::new(2); + let mut enc = SymbolEncoder::pricer(); + enc.reset_bits(); + write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true); + assert!(enc.bits().abs() < 1e-9, "a disarmed plan writes no symbol"); + assert!((crate::encode::delta_q_bits(200, 128, 0)).abs() < 1e-9); + } } diff --git a/lanes/rectdq.report.md b/lanes/rectdq.report.md new file mode 100644 index 00000000..cd76167d --- /dev/null +++ b/lanes/rectdq.report.md @@ -0,0 +1,131 @@ +# lane-rectdq — the 128 rect root pays for the delta_q group it codes + +Branch `lane-rectdq` off main 748e4328. Class name: **pricer omits a group the +writer codes** (sibling of `pricer-context-zero`: there the pricer priced the +right tree at the wrong context, here it priced a tree with a whole symbol +group missing). + +## The defect + +`crate::tile::write_delta_q` codes its symbol group for every block that sits +at its superblock's mode-info origin, with ONE exception: a block that is the +whole superblock AND is skipped (`if is_whole_sb && skip { return }`), which +mirrors decode.rs' `whole_sb = (side == write_w == write_h == sb_px)`. + +So at a 128 superblock root: + +| root shape | codes the delta_q group? | was it priced? | +|---|---|---| +| `PARTITION_NONE`, skipped | no | n/a (correct) | +| `PARTITION_NONE`, residual (`EC_AV1_B128RES`) | yes | NO | +| `PARTITION_HORZ`/`VERT` halves (first half only) | yes | NO | +| four 64 superblocks under a 128 grid (first cell) | yes | NO | + +The rect arm and the split arm were both under-priced by the group's bits on +every root of every frame that arms a delta_q plan (preset 0 has objective tpl +delta_q on, `DQ_TPL_K`) — the rect arm was measured against a NONE arm that +really is free, so it looked cheaper than it is. The class sweep +(`grep -n write_delta_q crates/ec-av1/src/tile.rs`) found the four writer sites +beyond the two 128 ones (Whole64 at `!sb128_armed()`, the 32 square, and both +inter leaves); under a 128 grid every one of them passes `is_whole_sb = false`, +which is why the four-superblock arm is charged here too. + +## The fix + +* `encode::delta_q_bits(target, cur, res)` — the writer's own three pieces in + the writer's order, priced through a `SymbolEncoder::pricer` rather than a + sum of table entries, because the escape's literal bits are equiprobable + SYMBOLS carrying the `EC_MIN_PROB` floor and cost a little over one bit each + (class `price-the-narrowing-not-the-table`; a table-entry sum was 0.43 bits + light at `abs = 20`). +* `encode::delta_q_bits_at_root(...)` — the charge at one 128 root: the target + is the root's own `sb_q` cell, exactly the entry `write_delta_q` indexes. + **Stated approximation:** the writer's `CurrentQIndex` (`plan.cur`) is not + knowable in the search — it only advances at the roots that really code a + group, and which those are is what this very comparison decides — so the + PREVIOUS 128 root's target in raster order stands in for it (`base_q_idx` at + the first root, which is also the writer's per-tile reset). Wrong only where + a neighbouring root came out a skipped NONE block, and then only by the + difference between two adjacent tpl cells. +* Charged in `search_root_128_rect` for the FIRST half only (the second half + sits at a non-origin mi and codes no group — `write_inter_block_128_rect`, + tile.rs:517), in `search_root_128` only when the block is NOT skipped, and on + the four-superblock side of the root comparison. +* `EC_AV1_RECTDQ=0` is the attribution control (pre-lane pricing). + +## Witness + +`tile::tests::the_delta_q_pricer_matches_the_writer_over_the_whole_domain` +enumerates the domain — `delta_q_abs` steps -20..=20, both signs, `res = 4` — +running `write_delta_q` into a pricing coder and comparing its `bits()` account +against `delta_q_bits`. Agreement is exact (`< 1e-9`), plus the disarmed case. + + cargo test -p ec-av1 --release --lib -- --exact \ + tile::tests::the_delta_q_pricer_matches_the_writer_over_the_whole_domain + +Result: ok, 1 passed. + +## Gates (lower BD = better; control = `EC_AV1_RECTDQ=0`, arm = default) + +12 frames, `encode::tests::bd_rate_screen_native`, all five rows +(`~/.cache/rectdq/s.log`): + +| row | vs libaom ctl → arm | vs rav1e ctl → arm | wall ours ctl → arm | +|---|---|---|---| +| bars 1080p | -3.4% → **-3.5%** | -19.0% → **-19.1%** | 186.2s → 189.2s | +| bars 2160p | +8.4% → +8.4% | -14.0% → -14.0% | 160.2s → 181.4s | +| film A | +18.0% → +18.0% | -6.3% → -6.3% | 177.6s → 179.1s | +| film B | +23.0% → **+22.8%** | -3.5% → **-3.7%** | 155.9s → 138.5s | +| screen capture | +14.4% → +14.4% | -33.2% → -33.2% | 144.6s → 106.9s | + +48 frames, `encode::tests::bd_rate_film_long_gop` (`~/.cache/rectdq/g.log`): + +| row | vs libaom ctl → arm | vs rav1e ctl → arm | wall ours ctl → arm | +|---|---|---|---| +| film A (`EC_AV1_NATIVE_FILM=1`) | +21.9% → +22.0% | -8.6% → -8.5% | 655.6s → 698.9s | +| film B (`EC_AV1_NATIVE_FILM4K=1`) | +75.8% → **+75.7%** | +0.8% → **+0.7%** | 494.1s → 464.7s | + +Wall: every row inside +15% (the +13% on bars 2160p and +6.6% on long-GOP film +A are contention — two gate units shared the box, and the arm's own film B rows +came out FASTER on both gates; the search does one extra pricer call per root). + +**Keep rule, honestly:** not met as written. No row goes >=0.5 down. The arm is +BD-NEUTRAL: the largest move in either direction is 0.2 (12f film B, down on +both columns), long-GOP film B is 0.1 down on both, long-GOP film A is 0.1 UP +on both, screen is byte-identical. It ships default-on as a CORRECTNESS fix +(the pricer now prices the tree the writer writes, witnessed exactly), not as a +win; the b128hv "+0.1 on the 12-frame film rows" premise this lane was chartered +from is not explained by the missing group — the group is worth ~2-9 bits a +root against roots costing thousands. + +## Pins + +`encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins` PASS +at default and at `EC_AV1_SPEED=6` — the pins did NOT move (the pin fixtures +arm no delta_q plan, so `delta_q_bits_at_root` returns 0 there). +`encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders` +PASS; `encode::tests::a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders` +PASS (`~/.cache/rectdq/p.log`). + +## Suite + +Three detached lanes, all green (`~/.cache/rectdq/t.log`): + +* `cargo test -p ec-av1 --release -j4 -- --skip stream::` — 346 passed, 0 failed, 39 ignored (460s) +* `... -- stream:: --skip 10bit` — 202 passed, 0 failed, 15 ignored (927s) +* `... -- 10bit` — 42 passed, 0 failed, 1 ignored (66s) +* `timeout 900 cargo check --workspace --all-targets -j4` — 0 errors, 0 ec-av1 warnings (the only warnings are the pre-existing ec-vorbis `decode_capture` and ec-opus ones). + +## Deviations from the charter + +1. The charter's gate commands omit `--ignored`; both BD tests are `#[ignore]`, + so `--ignored` was added or they would have filtered out silently. +2. The 12-frame gate was run WITHOUT `EC_AV1_NATIVE_FILM*` (one run per arm + covering all five rows) instead of two per-film runs: the same two film rows + plus the screen row the keep rule asks for, at half the runs. +3. The charge is made on the four-superblock arm as well as on the rect arm + (charter item 2's class sweep) — charging only the rect arm would have + biased the comparison toward SPLIT, which codes the same group. Both are + under the single `EC_AV1_RECTDQ` knob. +4. The unit witness lives in `tile.rs`'s test module (it needs the private + `write_delta_q`), not in `encode.rs`.