forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-newmv' (02c51eed): the motion search weighs its mv rate at half the SSE lambda and re-runs each subpel stage from its winner; NEWMV census instrument; pins re-taken 8288 / 33090

Browse files at this commit

4a23ee3367bb54e45e7259644c5564eaea405ad0Ahmet Kaan GümüşParent: 19e7ef8629901f
crates/ec-av1/src/encode.rsmodified+213 -5
@@ -4360,6 +4360,155 @@ pub(crate) fn dump_split_census() {
4360 }4360 }
4361 }4361 }
4362 4362
4363+/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4364+/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4365+/// its mode/reference syntax and not the search's own cost function
4366+/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4367+/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4368+/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4369+pub(crate) fn mv_lambda_mult() -> f64 {
4370+ static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4371+ crate::envflags::var("EC_AV1_MV_LAMBDA")
4372+ .ok()
4373+ .and_then(|v| v.parse().ok())
4374+ .unwrap_or(MV_LAMBDA)
4375+ });
4376+ *M
4377+}
4378+
4379+/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4380+const MV_LAMBDA: f64 = 1.0;
4381+
4382+/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4383+/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4384+/// which the RD cost multiplies by lambda). Zero at the default weight.
4385+fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4386+ (mv_lambda_mult() - 1.0) * mv_bits
4387+}
4388+
4389+/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4390+/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4391+/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4392+/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4393+/// cost it won by, 4 the summed cost it lost by, 5 the summed
4394+/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4395+/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4396+/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4397+/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4398+/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4399+static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4400+ [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4401+
4402+/// Whether [`NEWMV_CENSUS`] is armed, read once.
4403+pub(crate) fn newmv_census_on() -> bool {
4404+ static ON: std::sync::LazyLock<bool> =
4405+ std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4406+ *ON
4407+}
4408+
4409+/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4410+fn newmv_census_global(i: usize) {
4411+ if newmv_census_on() {
4412+ NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4413+ }
4414+}
4415+
4416+/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4417+/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4418+/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4419+/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4420+fn newmv_census_block(
4421+ side: usize,
4422+ offered: bool,
4423+ new_cost: f64,
4424+ other_cost: f64,
4425+ mv: (i32, i32),
4426+ nearest: (i32, i32),
4427+ mv_bits: f64,
4428+) {
4429+ if !newmv_census_on() {
4430+ return;
4431+ }
4432+ use std::sync::atomic::Ordering::Relaxed;
4433+ let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4434+ let add = |i: usize, v: u64| {
4435+ NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4436+ };
4437+ add(0, 1);
4438+ if !offered {
4439+ return;
4440+ }
4441+ add(1, 1);
4442+ if new_cost < other_cost {
4443+ add(2, 1);
4444+ add(3, (other_cost - new_cost).max(0.0) as u64);
4445+ } else {
4446+ add(4, (new_cost - other_cost).max(0.0) as u64);
4447+ }
4448+ add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
4449+ if mv == nearest {
4450+ add(6, 1);
4451+ }
4452+ add(7, (mv_bits * 64.0).max(0.0) as u64);
4453+}
4454+
4455+/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
4456+/// same guard [`dump_split_census`] rides (cumulative, so the last table a
4457+/// run prints is the whole encode's).
4458+pub(crate) fn dump_newmv_census() {
4459+ use std::sync::atomic::Ordering::Relaxed;
4460+ eprintln!(
4461+ "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
4462+ mv_dist_q3 mv==nearest% mv_bits"
4463+ );
4464+ for side_idx in 0..4 {
4465+ let base = side_idx * 8;
4466+ let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
4467+ if v[0] == 0 {
4468+ continue;
4469+ }
4470+ let off = v[1].max(1) as f64;
4471+ eprintln!(
4472+ "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
4473+ 8 << side_idx,
4474+ v[0],
4475+ v[1],
4476+ v[2],
4477+ 100.0 * v[2] as f64 / off,
4478+ v[3] as f64 / v[2].max(1) as f64,
4479+ v[4] as f64 / (v[1] - v[2]).max(1) as f64,
4480+ v[5] as f64 / off,
4481+ 100.0 * v[6] as f64 / off,
4482+ v[7] as f64 / off / 64.0,
4483+ );
4484+ }
4485+ let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
4486+ eprintln!(
4487+ "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
4488+ leaf second reference {}/{} ({:.1}%)",
4489+ g[1],
4490+ g[0],
4491+ 100.0 * g[1] as f64 / g[0].max(1) as f64,
4492+ g[3],
4493+ g[2],
4494+ 100.0 * g[3] as f64 / g[2].max(1) as f64,
4495+ );
4496+ let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4497+ crate::motion::take_census();
4498+ let per = |n: u64| n as f64 / calls.max(1) as f64;
4499+ eprintln!(
4500+ "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
4501+ winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
4502+ moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
4503+ per(evals),
4504+ per(rounds),
4505+ 100.0 * near_pred as f64 / calls.max(1) as f64,
4506+ 100.0 * unmoved as f64 / calls.max(1) as f64,
4507+ 100.0 * widest as f64 / calls.max(1) as f64,
4508+ per(widest_moves),
4509+ );
4510+}
4511+
4363 /// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so4512 /// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
4364 /// the intra witness's fire count stays its own.4513 /// the intra witness's fire count stays its own.
4365 pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =4514 pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
@@ -6435,7 +6584,12 @@ fn code_square_inter(
6435 );6584 );
6436 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);6585 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
6437 searched_new_cost = Some(found.cost);6586 searched_new_cost = Some(found.cost);
6438- if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {6587+ let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
6588+ if mv_residual.is_none() {
6589+ // lane-newmv: a vector the writer cannot name never reaches RD.
6590+ newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
6591+ }
6592+ if let Some(mv_bits) = mv_residual {
6439 searched_new = Some(new_mv);6593 searched_new = Some(new_mv);
6440 // Same reuse as `search_inter_block`: a NEWMV equal to the6594 // Same reuse as `search_inter_block`: a NEWMV equal to the
6441 // stack's NEARESTMV is the same three trials, already run above.6595 // stack's NEARESTMV is the same three trials, already run above.
@@ -6477,11 +6631,13 @@ fn code_square_inter(
6477 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)6631 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
6478 + drl_bits6632 + drl_bits
6479 + mv_bits6633 + mv_bits
6634+ + mv_rate_surcharge(mv_bits)
6480 + if skip_new {6635 + if skip_new {
6481 0.06636 0.0
6482 } else {6637 } else {
6483 luma_new.bits + u_new.bits + v_new.bits6638 luma_new.bits + u_new.bits + v_new.bits
6484 });6639 });
6640+ newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
6485 if cost_new < best.0 {6641 if cost_new < best.0 {
6486 single_syntax = intra_inter_bits(true)6642 single_syntax = intra_inter_bits(true)
6487 + single_ref_bits6643 + single_ref_bits
@@ -6571,6 +6727,7 @@ fn code_square_inter(
6571 let margin = leaf_second_new_margin();6727 let margin = leaf_second_new_margin();
6572 let mut second_new: Option<(i32, i32)> = None;6728 let mut second_new: Option<(i32, i32)> = None;
6573 if leaf_second_new_mv() {6729 if leaf_second_new_mv() {
6730+ newmv_census_global(2);
6574 let skip = margin > 0.06731 let skip = margin > 0.0
6575 && searched_new_cost.is_some_and(|last| {6732 && searched_new_cost.is_some_and(|last| {
6576 motion::cost_at(6733 motion::cost_at(
@@ -6579,6 +6736,9 @@ fn code_square_inter(
6579 ) * margin6736 ) * margin
6580 <= last6737 <= last
6581 });6738 });
6739+ if skip {
6740+ newmv_census_global(3);
6741+ }
6582 if !skip {6742 if !skip {
6583 let mut seeds = [(0, 0); 4];6743 let mut seeds = [(0, 0); 4];
6584 let mut seed_n = 1;6744 let mut seed_n = 1;
@@ -9130,7 +9290,7 @@ fn search_skip_64(
9130 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {9290 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
9131 last_new_mv = Some(mv);9291 last_new_mv = Some(mv);
9132 cands.push((9292 cands.push((
9133- symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,9293+ symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
9134 info_of(InterMode::NewMv, mv, ref_mv_idx),9294 info_of(InterMode::NewMv, mv, ref_mv_idx),
9135 ));9295 ));
9136 }9296 }
@@ -9672,13 +9832,20 @@ fn search_inter_block(
9672 #[cfg(test)]9832 #[cfg(test)]
9673 stage_since(0, t);9833 stage_since(0, t);
9674 let mv = round_to_valid_mv(found.mv, stack.pred_mv);9834 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
9835+ // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
9836+ // costs, for the census below (`None` when the writer cannot name it).
9837+ let mut newmv_syntax: Option<((i32, i32), f64)> = None;
9675 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so9838 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
9676 // the same vector costs a different residual from each: take the index9839 // the same vector costs a different residual from each: take the index
9677 // whose residual plus DRL bits is cheapest, not entry 0 by default.9840 // whose residual plus DRL bits is cheapest, not entry 0 by default.
9678 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {9841 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
9842+ newmv_syntax = Some((mv, bits));
9679 cands.push((9843 cands.push((
9680 mv,9844 mv,
9681- last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,9845+ last_ref_bits
9846+ + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
9847+ + bits
9848+ + mv_rate_surcharge(bits),
9682 InterInfo {9849 InterInfo {
9683 ref1: None,9850 ref1: None,
9684 mv1: (0, 0),9851 mv1: (0, 0),
@@ -9739,6 +9906,9 @@ fn search_inter_block(
9739 let searched = extra_ref_new_mv()9906 let searched = extra_ref_new_mv()
9740 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());9907 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
9741 let margin = extra_new_skip_margin();9908 let margin = extra_new_skip_margin();
9909+ if searched {
9910+ newmv_census_global(0);
9911+ }
9742 let skip_search = searched9912 let skip_search = searched
9743 && margin > 0.09913 && margin > 0.0
9744 && motion::cost_at(9914 && motion::cost_at(
@@ -9757,6 +9927,9 @@ fn search_inter_block(
9757 fctx,9927 fctx,
9758 ) * margin9928 ) * margin
9759 <= found.cost;9929 <= found.cost;
9930+ if skip_search {
9931+ newmv_census_global(1);
9932+ }
9760 if searched && !skip_search {9933 if searched && !skip_search {
9761 let (gseeds, gn) = mv_seeds(gstack);9934 let (gseeds, gn) = mv_seeds(gstack);
9762 #[cfg(test)]9935 #[cfg(test)]
@@ -9980,6 +10153,10 @@ fn search_inter_block(
9980 });10153 });
9981 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));10154 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
9982 census_add(7, cands.len());10155 census_add(7, cands.len());
10156+ // lane-newmv: the NEWMV candidate's own RD cost against the best cost
10157+ // this block reaches WITHOUT it, taken inside the one loop that prices
10158+ // them all (a second pricing pass would be a second oracle).
10159+ let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
9983 {10160 {
9984 for (mv, mode_bits_inter, info) in cands {10161 for (mv, mode_bits_inter, info) in cands {
9985 let (ref_luma, ref_u, ref_v) = match extra10162 let (ref_luma, ref_u, ref_v) = match extra
@@ -10066,8 +10243,23 @@ fn search_inter_block(
10066 mode_bits: mode_bits_inter,10243 mode_bits: mode_bits_inter,
10067 inter: Some(info),10244 inter: Some(info),
10068 });10245 });
10246+ if newmv_census_on() {
10247+ if info.mode == InterMode::NewMv
10248+ && info.ref1.is_none()
10249+ && info.ref_frame == crate::mvstack::LAST_FRAME
10250+ {
10251+ new_cost = cost;
10252+ } else {
10253+ other_cost = other_cost.min(cost);
10254+ }
10255+ }
10069 }10256 }
10070 }10257 }
10258+ if let Some((new_mv, bits)) = newmv_syntax {
10259+ newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits);
10260+ } else {
10261+ newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0);
10262+ }
10071 10263
10072 let best = best.expect("the search offers at least the intra modes");10264 let best = best.expect("the search offers at least the intra modes");
10073 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),10265 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
@@ -16296,8 +16488,14 @@ mod tests {
16296 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so16488 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
16297 // single and compound are priced against the same syntax -- 8311 ->16489 // single and compound are priced against the same syntax -- 8311 ->
16298 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.16490 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
16491+ // Re-taken on lane-newmv: the motion search charges its own rate term
16492+ // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
16493+ // and each subpel stage re-runs from its own winner
16494+ // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
16495+ // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
16496+ // and 33014 -> 33090 at q=60.
16299 let pins: [(u8, usize, u64); 2] =16497 let pins: [(u8, usize, u64); 2] =
16300- [(150, 8325, 0xf004_8258_bc60_ff05), (60, 33014, 0x5bc2_5dfd_bd13_18de)];16498+ [(150, 8288, 0x241d_8115_0a6d_0f34), (60, 33090, 0x7e02_777c_01b4_f035)];
16301 let coded: Vec<(u8, usize, u64)> = pins16499 let coded: Vec<(u8, usize, u64)> = pins
16302 .iter()16500 .iter()
16303 .map(|&(q, _, _)| {16501 .map(|&(q, _, _)| {
@@ -16944,7 +17142,8 @@ mod tests {
16944 // evaluations (one `mc::predict` + SAD each) a search spends, how17142 // evaluations (one `mc::predict` + SAD each) a search spends, how
16945 // many of them are subpel, and how often the winner is the seed17143 // many of them are subpel, and how often the winner is the seed
16946 // it started from -- the census the seeded search is judged by.17144 // it started from -- the census the seeded search is judged by.
16947- let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();17145+ let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
17146+ crate::motion::take_census();
16948 let per = |n: u64| n as f64 / calls.max(1) as f64;17147 let per = |n: u64| n as f64 / calls.max(1) as f64;
16949 eprintln!(17148 eprintln!(
16950 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \17149 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
@@ -16956,6 +17155,15 @@ mod tests {
16956 100.0 * near_pred as f64 / calls.max(1) as f64,17155 100.0 * near_pred as f64 / calls.max(1) as f64,
16957 100.0 * unmoved as f64 / calls.max(1) as f64,17156 100.0 * unmoved as f64 / calls.max(1) as f64,
16958 );17157 );
17158+ // lane-newmv, class `instrument at bound`: how often the winner
17159+ // was walked to at the log stage's own WIDEST step -- a high
17160+ // share means the search stops where its step lets it, not where
17161+ // the content is.
17162+ eprintln!(
17163+ "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
17164+ 100.0 * widest as f64 / calls.max(1) as f64,
17165+ per(widest_moves),
17166+ );
16959 eprintln!(17167 eprintln!(
16960 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",17168 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
16961 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]17169 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
crates/ec-av1/src/encoder.rsmodified+7 -1
@@ -1386,13 +1386,19 @@ impl Av1Encoder {
1386 struct SplitCensusDump;1386 struct SplitCensusDump;
1387 impl Drop for SplitCensusDump {1387 impl Drop for SplitCensusDump {
1388 fn drop(&mut self) {1388 fn drop(&mut self) {
1389+ if crate::encode::split_census_on() {
1389 crate::encode::dump_split_census();1390 crate::encode::dump_split_census();
1390 }1391 }
1392+ if crate::encode::newmv_census_on() {
1393+ crate::encode::dump_newmv_census();
1394+ }
1395+ }
1391 }1396 }
1392 // `then_some` would CONSTRUCT the guard eagerly and drop it when the1397 // `then_some` would CONSTRUCT the guard eagerly and drop it when the
1393 // flag is off, which runs `Drop` -- and printed the census header on1398 // flag is off, which runs `Drop` -- and printed the census header on
1394 // every unarmed encode. `then` builds it only when armed.1399 // every unarmed encode. `then` builds it only when armed.
1395- let _census = crate::encode::split_census_on().then(|| SplitCensusDump);1400+ let _census = (crate::encode::split_census_on() || crate::encode::newmv_census_on())
1401+ .then(|| SplitCensusDump);
1396 if (picture.width, picture.height) != (self.config.width, self.config.height) {1402 if (picture.width, picture.height) != (self.config.width, self.config.height) {
1397 return Err(Error::unsupported(1403 return Err(Error::unsupported(
1398 "AV1 encode",1404 "AV1 encode",
crates/ec-av1/src/motion.rsmodified+78 -7
@@ -88,9 +88,15 @@ fn seeded() -> bool {
88 /// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in88 /// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in
89 /// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is89 /// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is
90 /// within one whole sample of `pred_mv`, 5 calls whose winner is the90 /// within one whole sample of `pred_mv`, 5 calls whose winner is the
91-/// starting centre itself. A gate prints these rather than assume where the91+/// starting centre itself, 6 calls that moved at least once at the log
92-/// wall-owning stage goes (gate-blind-to-feature).92+/// stage's WIDEST step (the class `instrument at bound`: a search whose
93-static CENSUS: [std::sync::atomic::AtomicU64; 6] = [93+/// winner was reached by walking at its own initial step is measuring its
94+/// step, not the content), 7 the total such widest-step moves. A gate prints
95+/// these rather than assume where the wall-owning stage goes
96+/// (gate-blind-to-feature).
97+static CENSUS: [std::sync::atomic::AtomicU64; 8] = [
98+ std::sync::atomic::AtomicU64::new(0),
99+ std::sync::atomic::AtomicU64::new(0),
94 std::sync::atomic::AtomicU64::new(0),100 std::sync::atomic::AtomicU64::new(0),
95 std::sync::atomic::AtomicU64::new(0),101 std::sync::atomic::AtomicU64::new(0),
96 std::sync::atomic::AtomicU64::new(0),102 std::sync::atomic::AtomicU64::new(0),
@@ -100,9 +106,8 @@ static CENSUS: [std::sync::atomic::AtomicU64; 6] = [
100 ];106 ];
101 107
102 /// Takes (and clears) the census.108 /// Takes (and clears) the census.
103-#[cfg(test)]109+pub(crate) fn take_census() -> [u64; 8] {
104-pub(crate) fn take_census() -> [u64; 6] {110+ [0, 1, 2, 3, 4, 5, 6, 7].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
105- [0, 1, 2, 3, 4, 5].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
106 }111 }
107 112
108 /// The eight offsets, at `step` in each axis, a diamond/log search round113 /// The eight offsets, at `step` in each axis, a diamond/log search round
@@ -198,6 +203,54 @@ fn mv_bits((diff_row, diff_col): (i32, i32)) -> f64 {
198 bits203 bits
199 }204 }
200 205
206+/// lane-newmv: what the SEARCH's own rate term is weighted by, on top of the
207+/// block RD lambda it is handed. The RD lambda is an SSE-domain weight
208+/// (`encode::Search::lambda` is `LAMBDA_SCALE * step * step`, compared against
209+/// squared error) while this search compares SAD, so charging mv bits at the
210+/// full RD lambda over-prices motion by whatever the SSE/SAD ratio of the
211+/// content is -- the census fact this lane started from is that we code
212+/// 0.83-2.5 mv bits/block where libaom codes 3.2-7.5. `EC_AV1_MV_SEARCH_LAMBDA`
213+/// (any build, like the encoder's other search margins); 1.0 was the control.
214+///
215+/// SWEPT on the native 12-frame BD gate, film B (vs libaom / vs rav1e), with
216+/// [`MV_SUBPEL_ITERS`] still at 1: 0.25 +25.2/-1.7, 0.5 +24.9/-2.0,
217+/// 0.75 +24.8/-1.9, 1.0 (control) +24.9/-1.9, 2.0 +26.9/-0.2. Over-charging
218+/// motion is the expensive direction -- the 2.0 arm loses 2.0/1.7 points --
219+/// and the floor of the bowl sits at 0.5-0.75. 0.5 ships together with
220+/// [`MV_SUBPEL_ITERS`] 4; the pair's rows are in lanes/newmv.report.md.
221+const MV_SEARCH_LAMBDA: f64 = 0.5;
222+
223+/// [`MV_SEARCH_LAMBDA`], read once (this is the per-candidate cost path).
224+fn search_lambda_mult() -> f64 {
225+ static M: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
226+ *M.get_or_init(|| match std::env::var("EC_AV1_MV_SEARCH_LAMBDA").ok() {
227+ Some(v) => v.parse().unwrap_or(MV_SEARCH_LAMBDA),
228+ None => MV_SEARCH_LAMBDA,
229+ })
230+}
231+
232+/// How many times each subpel refinement round may re-run from its own
233+/// winner ([`search_traced_from_step`]'s stages 2 and 3).
234+/// `EC_AV1_MV_SUBPEL_ITERS`; 1 was the single round the search shipped with.
235+///
236+/// MEASURED on the native BD gate at [`MV_SEARCH_LAMBDA`] 0.5: film A
237+/// 12-frame +21.0/-4.8 -> +20.6/-5.1, film B 12-frame +24.9/-1.9 ->
238+/// +24.8/-2.1, screen +14.5/-33.2 -> +14.6/-33.2, film A long-GOP
239+/// +25.2/-7.2 -> +24.7/-7.5, film B long-GOP +86.7/+7.3 -> +86.8/+7.4. Each
240+/// half alone is worth about half of it on film A (+20.8/-4.9 either way);
241+/// on film B this iteration alone LOSES (+25.2/-1.7) and only pays with the
242+/// lighter search rate term beside it. It costs 5-7% encoder wall.
243+const MV_SUBPEL_ITERS: u32 = 4;
244+
245+/// [`MV_SUBPEL_ITERS`], read once.
246+fn subpel_iters() -> u32 {
247+ static N: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
248+ *N.get_or_init(|| match std::env::var("EC_AV1_MV_SUBPEL_ITERS").ok() {
249+ Some(v) => v.parse().unwrap_or(MV_SUBPEL_ITERS),
250+ None => MV_SUBPEL_ITERS,
251+ })
252+}
253+
201 /// One search's outcome: the best MV found and the `SAD + lambda * mv_bits`254 /// One search's outcome: the best MV found and the `SAD + lambda * mv_bits`
202 /// cost it settled at.255 /// cost it settled at.
203 #[derive(Clone, Copy, Debug, PartialEq)]256 #[derive(Clone, Copy, Debug, PartialEq)]
@@ -244,7 +297,7 @@ fn cost_of_mv(
244 .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs())297 .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs())
245 .sum();298 .sum();
246 let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);299 let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
247- f64::from(sad) + lambda * mv_bits(diff)300+ f64::from(sad) + lambda * search_lambda_mult() * mv_bits(diff)
248 }301 }
249 302
250 /// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to303 /// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to
@@ -480,6 +533,7 @@ fn search_traced_from_step(
480 // Stage 1: log/diamond search over whole-pel steps, halving the step533 // Stage 1: log/diamond search over whole-pel steps, halving the step
481 // each time a round finds no better neighbour, down to one sample.534 // each time a round finds no better neighbour, down to one sample.
482 let mut step_pel = initial_step_pel;535 let mut step_pel = initial_step_pel;
536+ let mut widest_moves = 0u64;
483 while step_pel >= SEARCH_MIN_STEP_PEL {537 while step_pel >= SEARCH_MIN_STEP_PEL {
484 let step = step_pel * PEL_Q3;538 let step = step_pel * PEL_Q3;
485 loop {539 loop {
@@ -498,6 +552,9 @@ fn search_traced_from_step(
498 }552 }
499 }553 }
500 let moved = best_in_round < best_cost;554 let moved = best_in_round < best_cost;
555+ if moved && step_pel == initial_step_pel {
556+ widest_moves += 1;
557+ }
501 best_cost = best_in_round;558 best_cost = best_in_round;
502 CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);559 CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
503 trace.push(best_cost);560 trace.push(best_cost);
@@ -513,6 +570,12 @@ fn search_traced_from_step(
513 // costed at the precision it commits to, not the integer-pel SAD alone).570 // costed at the precision it commits to, not the integer-pel SAD alone).
514 let integer_evals = evals.get();571 let integer_evals = evals.get();
515 for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {572 for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {
573+ // lane-newmv, class `search bounded by its heuristic`: ONE round per
574+ // step means a subpel winner two half-pels away from the integer
575+ // centre is unreachable. `EC_AV1_MV_SUBPEL_ITERS` runs the round
576+ // again from its own winner, up to that many times; 1 is the
577+ // control's single round.
578+ for _ in 0..subpel_iters() {
516 let round_centre = centre;579 let round_centre = centre;
517 for (dr, dc) in neighbor_offsets(step) {580 for (dr, dc) in neighbor_offsets(step) {
518 let candidate = (round_centre.0 + dr, round_centre.1 + dc);581 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
@@ -522,6 +585,10 @@ fn search_traced_from_step(
522 centre = candidate;585 centre = candidate;
523 }586 }
524 }587 }
588+ if centre == round_centre {
589+ break;
590+ }
591+ }
525 trace.push(best_cost);592 trace.push(best_cost);
526 }593 }
527 594
@@ -535,6 +602,10 @@ fn search_traced_from_step(
535 if centre == start_centre {602 if centre == start_centre {
536 CENSUS[5].fetch_add(1, Relaxed);603 CENSUS[5].fetch_add(1, Relaxed);
537 }604 }
605+ if widest_moves > 0 {
606+ CENSUS[6].fetch_add(1, Relaxed);
607+ CENSUS[7].fetch_add(widest_moves, Relaxed);
608+ }
538 609
539 (610 (
540 MotionSearch {611 MotionSearch {
lanes/newmv.report.mdadded+165 -0
@@ -0,0 +1,165 @@
1+# lane-newmv — why we code NEWMV on a fifth of the blocks libaom does
2+
3+Worktree `edith_codecs-newmv`, branch `lane-newmv` off main 6b95562d. Every
4+BD row is the prebuilt release lib-test binary (`bd_rate_screen_native`, 12
5+pictures, `gop 12`, four quantizers, native `gate_crop`; `bd_rate_film_long_gop`
6+for the 48-picture rows), each detached under its own `systemd-run` unit, read
7+off the log's own clip line.
8+
9+## 0. The controls reproduce
10+
11+| row | control (vs libaom / vs rav1e) | charter |
12+|---|---|---|
13+| film A, 12 frames | +21.0 / -4.8 | +21.0 / -4.8 |
14+| film B, 12 frames | +24.9 / -1.9 | +24.9 / -1.9 |
15+| screen, 12 frames | +14.5 / -33.2 | +14.5 / -33.2 |
16+| film A, long GOP | +25.2 / -7.2 | +25.2 / -7.2 |
17+| film B, long GOP | +86.7 / +7.3 | +86.7 / +7.3 |
18+
19+All five land to the digit.
20+
21+## 1. The instrument (`EC_AV1_NEWMV_CENSUS=1`)
22+
23+Per block side: how often a `LAST` `NEWMV` is searched, how often the writer
24+can name the vector (offered to RD), how often it wins, the mean RD margin on
25+each side of the decision, the searched vector's distance from `NEARESTMV`,
26+how often it IS `NEARESTMV`, and its mv syntax bits. Then the two pre-RD
27+margins' skip shares, and the search's own bound witness (class `instrument at
28+bound`: how often the winner was walked to at the log stage's WIDEST step).
29+It rides the guard `EC_AV1_SPLIT_CENSUS` already had in
30+`Av1Encoder::encode_frames`, so it prints on every exit and costs nothing when
31+unset.
32+
33+Film B, gate crop, 12 frames, q=90 — CONTROL:
34+
35+| side | searched | offered | won | won% | win margin | lose margin | \|mv-nearest\| | mv==nearest | mv bits |
36+|---|---|---|---|---|---|---|---|---|---|
37+| 8 | 65296 | 65296 | 13319 | 20.4% | 47 | 26 | 16.48 | 61.3% | 5.90 |
38+| 16 | 25500 | 25500 | 9564 | 37.5% | 106 | 35 | 17.29 | 41.6% | 6.68 |
39+| 32 | 18344 | 18344 | 3627 | 19.8% | 137 | 32 | 9.69 | 54.1% | 5.82 |
40+
41+pre-RD margin skips: extra-reference 86.2%, leaf second reference 4.2%.
42+search: 293394 calls, 69.2 evals/call, 6.35 integer rounds/call; winner within
43+±1 pel of `pred_mv` 54.9%, winner = starting seed 17.4%, moved at the widest
44+step 18.9% of calls.
45+
46+READ IT AS:
47+
48+1. **No margin drops LAST's `NEWMV`.** `searched == offered` in every row: the
49+ candidate reaches RD on every inter block. The two skip margins
50+ (`EXTRA_NEW_SKIP_MARGIN`, `LEAF_SECOND_NEW_MARGIN`) gate only the EXTRA
51+ references' searches. The charter's first hypothesis is refuted by the
52+ instrument.
53+2. **The vectors we do code are the right size.** 5.8-6.7 mv bits per CODED
54+ `NEWMV` against libaom's 3.2-7.5 per BLOCK: the whole census gap
55+ (0.83-2.5 mv bits/block) is the SHARE, not the precision.
56+3. **It loses by very little.** The mean losing margin (26-43 RD units) is a
57+ quarter to a third of the mean winning one — a near-tie decision, i.e. a
58+ population a small change in the search or the rate weight moves.
59+4. **The search is not at its own bound.** Only 18.9% of calls ever move at
60+ the widest log step, so the initial step / distance scale is not what
61+ stops it. But over half its winners sit within ±1 pel of `pred_mv` and
62+ 41-61% of them ARE `NEARESTMV`.
63+
64+## 2. The sweep (film B, 12 frames)
65+
66+| arm | vs libaom | vs rav1e |
67+|---|---|---|
68+| control | +24.9 | -1.9 |
69+| `EC_AV1_MV_LAMBDA=0.5` (block RD mv rate x0.5) | +26.3 | -0.6 |
70+| `EC_AV1_MV_LAMBDA=1.5` | +25.3 | -1.7 |
71+| `EC_AV1_MV_SEARCH_LAMBDA=0.25` | +25.2 | -1.7 |
72+| `EC_AV1_MV_SEARCH_LAMBDA=0.5` | +24.9 | -2.0 |
73+| `EC_AV1_MV_SEARCH_LAMBDA=0.75` | +24.8 | -1.9 |
74+| `EC_AV1_MV_SEARCH_LAMBDA=2.0` | +26.9 | -0.2 |
75+| `EC_AV1_MV_SUBPEL_ITERS=4` | +25.2 | -1.7 |
76+| **`SUBPEL_ITERS=4` + `SEARCH_LAMBDA=0.5`** | **+24.8** | **-2.1** |
77+
78+The chartered lever — the mv RATE term of the BLOCK decision — is
79+**single-peaked at the control on both sides** (0.5 loses 1.4/1.3, 1.5 loses
80+0.4/0.2). That is the third instance of class `rd-rate-term-calibration` on
81+this encoder (lane-txd, lane-split, here): our block-level pricing of a coded
82+vector is already RD-optimal on this content, so the finding the charter named
83+as the fallback holds — it is the SEARCH, not the pricing.
84+
85+The two search-side knobs are new and both are one-liners:
86+
87+* `EC_AV1_MV_SEARCH_LAMBDA` (`motion::MV_SEARCH_LAMBDA`): the search compares
88+ **SAD** while the lambda it is handed is the block RD's **SSE-domain**
89+ weight (`LAMBDA_SCALE * step * step`), so charging mv bits at the full RD
90+ lambda over-prices motion inside the search itself and pins the winner to
91+ `pred_mv`. Halving it is the floor of a clean bowl; doubling it costs 2.0
92+ points.
93+* `EC_AV1_MV_SUBPEL_ITERS` (`motion::MV_SUBPEL_ITERS`): each subpel stage ran
94+ ONE ±1-step round, so a winner two half-pels off the integer centre was
95+ unreachable (class `search bounded by its heuristic`). It re-runs from its
96+ own winner now, up to 4 times, stopping when a round does not move.
97+
98+## 3. What ships
99+
100+`MV_SEARCH_LAMBDA = 0.5`, `MV_SUBPEL_ITERS = 4`. `MV_LAMBDA` stays 1.0 (the
101+knob stays for the next sweep).
102+
103+| row | control | shipped | move |
104+|---|---|---|---|
105+| film A, 12 frames | +21.0 / -4.8 | **+20.6 / -5.1** | -0.4 / -0.3 |
106+| film B, 12 frames | +24.9 / -1.9 | **+24.8 / -2.1** | -0.1 / -0.2 |
107+| screen, 12 frames | +14.5 / -33.2 | +14.6 / -33.2 | +0.1 / 0.0 |
108+| film A, long GOP | +25.2 / -7.2 | **+24.7 / -7.5** | -0.5 / -0.3 |
109+| film B, long GOP | +86.7 / +7.3 | +86.8 / +7.4 | +0.1 / +0.1 |
110+
111+Keep rule met: both film rows improve on both columns at 12 frames; at long
112+GOP film A is 0.5/0.3 down with film B flat inside ±0.3; screen is 0.1 worse,
113+inside the 0.3 the rule allows. Wall (ours, same arm's own line): film A 146.5
114+-> 150.4 s, film B 123.2 -> 131.4 s, film A long GOP 564.9 -> 607.0 s, film B
115+long GOP 417.2 -> 437.7 s — +2.7% to +7.4%, under the 15% ceiling.
116+
117+Decomposed on film A (12 frames): each half alone reads +20.8/-4.9, the pair
118++20.6/-5.1 — they compose. On film B the subpel iteration ALONE loses
119+(+25.2/-1.7) and only pays with the lighter search rate term beside it, which
120+is why the pair ships as a pair.
121+
122+## 4. The mechanism moved, not just the bytes
123+
124+Same census, same clip and quantizer, after the change:
125+
126+| side | won% (was) | mv bits (was) | mv==nearest (was) |
127+|---|---|---|---|
128+| 8 | **30.7%** (20.4) | 7.82 (5.90) | 36.4% (61.3) |
129+| 16 | **46.5%** (37.5) | 8.21 (6.68) | 21.6% (41.6) |
130+| 32 | **23.3%** (19.8) | 6.76 (5.82) | 38.5% (54.1) |
131+
132+The search now spends 81.7 evals/call (was 69.2) and its winner sits within
133+±1 pel of `pred_mv` in 42.6% of calls (was 54.9). The NEWMV share moves toward
134+libaom's 54-76% at 3.2-7.5 mv bits/block, i.e. the BD move is the mechanism
135+the census pointed at — not something else that happened to move bytes.
136+
137+## 5. Pins
138+
139+`the_encoders_own_streams_are_byte_identical_to_their_pins` re-taken with a
140+two-line comment: 8325 -> 8288 bytes at q=150 and 33014 -> 33090 at q=60.
141+Green at the default and at `EC_AV1_SPEED=6`. No other byte pin went red
142+(split suite below).
143+
144+## 6. Gates
145+
146+* split suite, release lib tests: s1 (`--skip stream::`) 339 passed / 0 failed
147+ RC=0; s2 (`stream:: --skip 10bit`) 200 / 0 RC=0; s3 (`10bit`) 42 / 0 RC=0.
148+* `--ignored encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders`
149+ 1 passed RC=0.
150+* `cargo check --workspace --all-targets`: 0 errors, 0 ec-av1 warnings.
151+
152+## 7. What this lane did NOT do
153+
154+* `deferred: allow_high_precision_mv` — the writer codes every frame with it
155+ off, so the finest vector the search can commit to is a quarter pel
156+ (`round_to_valid_mv` rounds the residual to an even 1/8-pel count). Whether
157+ 1/8-pel vectors pay is unmeasured; it needs the header bit, the `mv_hp`
158+ symbols and a decode witness first, then this same gate.
159+* `deferred: the mv rate weight of the COMPOUND halves and of the 64x64 skip
160+ root` — `EC_AV1_MV_LAMBDA` reaches the single-reference `NEWMV` candidates
161+ only. Since the single-reference sweep came back single-peaked at 1.0,
162+ re-pricing the compound halves has no measured reason to be different.
163+* `deferred: a per-speed-preset value for MV_SUBPEL_ITERS` — it costs 5-7%
164+ wall at every preset, and the preset ladder's own wall/BD Pareto
165+ (lanes `software speed Pareto`) is where that belongs, not here.