forge
Explore
Log in

Don't you dare go Hollow

instrument(av1): a NEWMV census plus mv-rate weights for the block decision and the search

Browse files at this commit

f00abe407aae87ef4ad2f15a60b13e18fd9ecdb7Ahmet Kaan GümüşParent: 19e7ef8
EC_AV1_NEWMV_CENSUS=1 prints, per block side, how often a LAST NEWMV is
searched, offered to RD, and wins, the RD margin either way, the searched
vector's distance from NEARESTMV, and the mv syntax bits it spends, plus the
two pre-RD margins' skip shares and the search's own bound witness (how often
the winner was walked to at the log stage's widest step).

EC_AV1_MV_LAMBDA weights the mv rate term of the block decision only and
EC_AV1_MV_SEARCH_LAMBDA the search's own; both default 1.0, byte-identical.
crates/ec-av1/src/encode.rsmodified+206 -4
@@ -4360,6 +4360,155 @@ pub(crate) fn dump_split_census() {
43604360 }
43614361 }
43624362
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+
43634512 /// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
43644513 /// the intra witness's fire count stays its own.
43654514 pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
@@ -6435,7 +6584,12 @@ fn code_square_inter(
64356584 );
64366585 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
64376586 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 {
64396593 searched_new = Some(new_mv);
64406594 // Same reuse as `search_inter_block`: a NEWMV equal to the
64416595 // stack's NEARESTMV is the same three trials, already run above.
@@ -6477,11 +6631,13 @@ fn code_square_inter(
64776631 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
64786632 + drl_bits
64796633 + mv_bits
6634+ + mv_rate_surcharge(mv_bits)
64806635 + if skip_new {
64816636 0.0
64826637 } else {
64836638 luma_new.bits + u_new.bits + v_new.bits
64846639 });
6640+ newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
64856641 if cost_new < best.0 {
64866642 single_syntax = intra_inter_bits(true)
64876643 + single_ref_bits
@@ -6571,6 +6727,7 @@ fn code_square_inter(
65716727 let margin = leaf_second_new_margin();
65726728 let mut second_new: Option<(i32, i32)> = None;
65736729 if leaf_second_new_mv() {
6730+ newmv_census_global(2);
65746731 let skip = margin > 0.0
65756732 && searched_new_cost.is_some_and(|last| {
65766733 motion::cost_at(
@@ -6579,6 +6736,9 @@ fn code_square_inter(
65796736 ) * margin
65806737 <= last
65816738 });
6739+ if skip {
6740+ newmv_census_global(3);
6741+ }
65826742 if !skip {
65836743 let mut seeds = [(0, 0); 4];
65846744 let mut seed_n = 1;
@@ -9130,7 +9290,7 @@ fn search_skip_64(
91309290 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
91319291 last_new_mv = Some(mv);
91329292 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),
91349294 info_of(InterMode::NewMv, mv, ref_mv_idx),
91359295 ));
91369296 }
@@ -9672,13 +9832,20 @@ fn search_inter_block(
96729832 #[cfg(test)]
96739833 stage_since(0, t);
96749834 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;
96759838 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
96769839 // the same vector costs a different residual from each: take the index
96779840 // whose residual plus DRL bits is cheapest, not entry 0 by default.
96789841 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
9842+ newmv_syntax = Some((mv, bits));
96799843 cands.push((
96809844 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),
96829849 InterInfo {
96839850 ref1: None,
96849851 mv1: (0, 0),
@@ -9739,6 +9906,9 @@ fn search_inter_block(
97399906 let searched = extra_ref_new_mv()
97409907 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
97419908 let margin = extra_new_skip_margin();
9909+ if searched {
9910+ newmv_census_global(0);
9911+ }
97429912 let skip_search = searched
97439913 && margin > 0.0
97449914 && motion::cost_at(
@@ -9757,6 +9927,9 @@ fn search_inter_block(
97579927 fctx,
97589928 ) * margin
97599929 <= found.cost;
9930+ if skip_search {
9931+ newmv_census_global(1);
9932+ }
97609933 if searched && !skip_search {
97619934 let (gseeds, gn) = mv_seeds(gstack);
97629935 #[cfg(test)]
@@ -9980,6 +10153,10 @@ fn search_inter_block(
998010153 });
998110154 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
998210155 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);
998310160 {
998410161 for (mv, mode_bits_inter, info) in cands {
998510162 let (ref_luma, ref_u, ref_v) = match extra
@@ -10066,8 +10243,23 @@ fn search_inter_block(
1006610243 mode_bits: mode_bits_inter,
1006710244 inter: Some(info),
1006810245 });
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+ }
1006910256 }
1007010257 }
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+ }
1007110263
1007210264 let best = best.expect("the search offers at least the intra modes");
1007310265 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
@@ -16944,7 +17136,8 @@ mod tests {
1694417136 // evaluations (one `mc::predict` + SAD each) a search spends, how
1694517137 // many of them are subpel, and how often the winner is the seed
1694617138 // it started from -- the census the seeded search is judged by.
16947- let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
17139+ let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
17140+ crate::motion::take_census();
1694817141 let per = |n: u64| n as f64 / calls.max(1) as f64;
1694917142 eprintln!(
1695017143 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
@@ -16956,6 +17149,15 @@ mod tests {
1695617149 100.0 * near_pred as f64 / calls.max(1) as f64,
1695717150 100.0 * unmoved as f64 / calls.max(1) as f64,
1695817151 );
17152+ // lane-newmv, class `instrument at bound`: how often the winner
17153+ // was walked to at the log stage's own WIDEST step -- a high
17154+ // share means the search stops where its step lets it, not where
17155+ // the content is.
17156+ eprintln!(
17157+ "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
17158+ 100.0 * widest as f64 / calls.max(1) as f64,
17159+ per(widest_moves),
17160+ );
1695917161 eprintln!(
1696017162 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
1696117163 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
crates/ec-av1/src/encoder.rsmodified+8 -2
@@ -1386,13 +1386,19 @@ impl Av1Encoder {
13861386 struct SplitCensusDump;
13871387 impl Drop for SplitCensusDump {
13881388 fn drop(&mut self) {
1389- crate::encode::dump_split_census();
1389+ if crate::encode::split_census_on() {
1390+ crate::encode::dump_split_census();
1391+ }
1392+ if crate::encode::newmv_census_on() {
1393+ crate::encode::dump_newmv_census();
1394+ }
13901395 }
13911396 }
13921397 // `then_some` would CONSTRUCT the guard eagerly and drop it when the
13931398 // flag is off, which runs `Drop` -- and printed the census header on
13941399 // 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);
13961402 if (picture.width, picture.height) != (self.config.width, self.config.height) {
13971403 return Err(Error::unsupported(
13981404 "AV1 encode",
crates/ec-av1/src/motion.rsmodified+39 -7
@@ -88,9 +88,15 @@ fn seeded() -> bool {
8888 /// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in
8989 /// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is
9090 /// 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 the
92-/// wall-owning stage goes (gate-blind-to-feature).
93-static CENSUS: [std::sync::atomic::AtomicU64; 6] = [
91+/// starting centre itself, 6 calls that moved at least once at the log
92+/// stage's WIDEST step (the class `instrument at bound`: a search whose
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),
94100 std::sync::atomic::AtomicU64::new(0),
95101 std::sync::atomic::AtomicU64::new(0),
96102 std::sync::atomic::AtomicU64::new(0),
@@ -100,9 +106,8 @@ static CENSUS: [std::sync::atomic::AtomicU64; 6] = [
100106 ];
101107
102108 /// Takes (and clears) the census.
103-#[cfg(test)]
104-pub(crate) fn take_census() -> [u64; 6] {
105- [0, 1, 2, 3, 4, 5].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
109+pub(crate) fn take_census() -> [u64; 8] {
110+ [0, 1, 2, 3, 4, 5, 6, 7].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
106111 }
107112
108113 /// The eight offsets, at `step` in each axis, a diamond/log search round
@@ -198,6 +203,25 @@ fn mv_bits((diff_row, diff_col): (i32, i32)) -> f64 {
198203 bits
199204 }
200205
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 is the control.
214+const MV_SEARCH_LAMBDA: f64 = 1.0;
215+
216+/// [`MV_SEARCH_LAMBDA`], read once (this is the per-candidate cost path).
217+fn search_lambda_mult() -> f64 {
218+ static M: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
219+ *M.get_or_init(|| match std::env::var("EC_AV1_MV_SEARCH_LAMBDA").ok() {
220+ Some(v) => v.parse().unwrap_or(MV_SEARCH_LAMBDA),
221+ None => MV_SEARCH_LAMBDA,
222+ })
223+}
224+
201225 /// One search's outcome: the best MV found and the `SAD + lambda * mv_bits`
202226 /// cost it settled at.
203227 #[derive(Clone, Copy, Debug, PartialEq)]
@@ -244,7 +268,7 @@ fn cost_of_mv(
244268 .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs())
245269 .sum();
246270 let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
247- f64::from(sad) + lambda * mv_bits(diff)
271+ f64::from(sad) + lambda * search_lambda_mult() * mv_bits(diff)
248272 }
249273
250274 /// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to
@@ -480,6 +504,7 @@ fn search_traced_from_step(
480504 // Stage 1: log/diamond search over whole-pel steps, halving the step
481505 // each time a round finds no better neighbour, down to one sample.
482506 let mut step_pel = initial_step_pel;
507+ let mut widest_moves = 0u64;
483508 while step_pel >= SEARCH_MIN_STEP_PEL {
484509 let step = step_pel * PEL_Q3;
485510 loop {
@@ -498,6 +523,9 @@ fn search_traced_from_step(
498523 }
499524 }
500525 let moved = best_in_round < best_cost;
526+ if moved && step_pel == initial_step_pel {
527+ widest_moves += 1;
528+ }
501529 best_cost = best_in_round;
502530 CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
503531 trace.push(best_cost);
@@ -535,6 +563,10 @@ fn search_traced_from_step(
535563 if centre == start_centre {
536564 CENSUS[5].fetch_add(1, Relaxed);
537565 }
566+ if widest_moves > 0 {
567+ CENSUS[6].fetch_add(1, Relaxed);
568+ CENSUS[7].fetch_add(widest_moves, Relaxed);
569+ }
538570
539571 (
540572 MotionSearch {