forge
Explore
Log in

Don't you dare go Hollow

EC_AV1_SPLIT_LAMBDA on the split trial's rate, plus a split census

Browse files at this commit

c781f74eb5f4bcacf0a0395bd65a054a5ece2686Ahmet Kaan GümüşParent: 5f55543
  • feat
    • EC_AV1_SPLIT_LAMBDA on the split trial's rate, plus a split census
Show full message
feat(av1): EC_AV1_SPLIT_LAMBDA on the split trial's rate, plus a split census

The class rd-rate-term-calibration knob lane-txd's report asks for. The
intra tx_depth depth>0 candidates and the inter var-tx depth-1 trial now
charge their rate at split_lambda_mult() * lambda (SPLIT_LAMBDA = 1.0, the
control), and EC_AV1_SPLIT_CENSUS=1 prints per site / frame type / block
side how many trials were offered, how many the split won, and the mean
(rate, distortion) of winner and loser.
crates/ec-av1/src/encode.rsmodified+152 -5
@@ -4245,6 +4245,119 @@ fn tx_depth_bits(ctx: usize, side: usize, depth: usize) -> f64 {
42454245 }
42464246 }
42474247
4248+/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4249+/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4250+/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4251+/// (the mode search's own weight); below 1 the split trial is charged less
4252+/// for its bits and fires more often.
4253+///
4254+/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4255+/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4256+/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4257+/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4258+/// so what is mis-calibrated is the weight the split's rate is judged under,
4259+/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4260+pub(crate) fn split_lambda_mult() -> f64 {
4261+ static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4262+ crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4263+ .ok()
4264+ .and_then(|v| v.parse().ok())
4265+ .unwrap_or(SPLIT_LAMBDA)
4266+ });
4267+ *M
4268+}
4269+
4270+/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4271+/// the sweep that chose it.
4272+const SPLIT_LAMBDA: f64 = 1.0;
4273+
4274+/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4275+/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4276+/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4277+/// trials offered, trials the split won, then the (rate, distortion) of the
4278+/// split and flat arms summed apart for the split-won and flat-won trials --
4279+/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4280+static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4281+ [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4282+
4283+/// Whether [`SPLIT_CENSUS`] is armed, read once.
4284+pub(crate) fn split_census_on() -> bool {
4285+ static ON: std::sync::LazyLock<bool> =
4286+ std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4287+ *ON
4288+}
4289+
4290+/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4291+/// `(rate in bits, distortion as squared error)`.
4292+fn split_census(
4293+ site: usize,
4294+ key: bool,
4295+ side: usize,
4296+ split_won: bool,
4297+ split: (f64, f64),
4298+ flat: (f64, f64),
4299+) {
4300+ use std::sync::atomic::Ordering::Relaxed;
4301+ let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4302+ let base = ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10;
4303+ let add = |i: usize, v: u64| {
4304+ SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4305+ };
4306+ add(0, 1);
4307+ let off = if split_won {
4308+ add(1, 1);
4309+ 2
4310+ } else {
4311+ 6
4312+ };
4313+ let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4314+ add(off, (win.0 * 64.0).max(0.0) as u64);
4315+ add(off + 1, win.1.max(0.0) as u64);
4316+ add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4317+ add(off + 3, lose.1.max(0.0) as u64);
4318+}
4319+
4320+/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4321+/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4322+/// last table a run prints is the whole encode's total (there is no flush
4323+/// hook the encoder API guarantees to reach).
4324+pub(crate) fn dump_split_census() {
4325+ use std::sync::atomic::Ordering::Relaxed;
4326+ eprintln!(
4327+ "SPLITCENSUS site frame side offered split share% \
4328+ win_rate win_dist lose_rate lose_dist"
4329+ );
4330+ for site in 0..2 {
4331+ for key in [true, false] {
4332+ for side_idx in 0..4 {
4333+ let base = ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10;
4334+ let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4335+ if v[0] == 0 {
4336+ continue;
4337+ }
4338+ let (n, s) = (v[0] as f64, v[1] as f64);
4339+ // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4340+ // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4341+ // all `n` trials, not a mean of two means.
4342+ eprintln!(
4343+ "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4344+ {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4345+ if site == 0 { "intra" } else { "inter" },
4346+ if key { "key " } else { "inter" },
4347+ 8 << side_idx,
4348+ v[0],
4349+ v[1],
4350+ 100.0 * s / n,
4351+ (v[2] + v[6]) as f64 / n / 64.0,
4352+ (v[3] + v[7]) as f64 / n,
4353+ (v[4] + v[8]) as f64 / n / 64.0,
4354+ (v[5] + v[9]) as f64 / n,
4355+ );
4356+ }
4357+ }
4358+ }
4359+}
4360+
42484361 /// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
42494362 /// the intra witness's fire count stays its own.
42504363 pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
@@ -4651,8 +4764,13 @@ fn commit_inter_luma(
46514764 }
46524765 }
46534766 luma.ctx.tu_split = false;
4654- let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
4655- let flat_cost = flat_ref.sse + search.lambda * (flat_ref.bits + txfm_split_bits(side, 0));
4767+ let split_rate = bits + txfm_split_bits(side, 1);
4768+ let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
4769+ let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
4770+ let flat_cost = flat_ref.sse + search.lambda * flat_rate;
4771+ if split_census_on() {
4772+ split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
4773+ }
46564774 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
46574775 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
46584776 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
@@ -5231,6 +5349,10 @@ fn code_square(
52315349 // ([`tx_depth_bits`]), read by the caller off its own published transform
52325350 // bands -- `0` where the caller keeps none.
52335351 tx_ctx: usize,
5352+ // Whether this is a KEY frame's block, read only by the split census
5353+ // ([`SPLIT_CENSUS`]): the two frame types price `tx_depth` off different
5354+ // band sets and split at different rates, which is the whole finding.
5355+ census_key: bool,
52345356 fctx: &crate::decode::FrameCtx,
52355357 ) -> (BlockCoeffs, f64) {
52365358 let (luma_set, chroma_set) = if side == SUPERBLOCK {
@@ -5285,17 +5407,37 @@ fn code_square(
52855407 luma_coeffs,
52865408 );
52875409 let mut best_types = std::mem::take(&mut luma_tx_types);
5410+ // The census wants the flat arm's own (rate, distortion), which
5411+ // `search_block` only hands back folded into one cost -- so under the
5412+ // env flag alone it is re-coded at depth 0 and the plane restored.
5413+ let census_flat = split_census_on().then(|| {
5414+ let kept = luma.snapshot(x, y, side);
5415+ let (_, sse, bits, _) =
5416+ luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
5417+ luma.restore(x, y, side, &kept);
5418+ (bits + tx_depth_bits(tx_ctx, side, 0), sse)
5419+ });
5420+ let mut census_split: Option<(f64, f64)> = None;
52885421 for depth in 1..=max_tx_depth(side) {
52895422 let (levels, sse, bits, types) =
52905423 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
5291- let cost_d = sse
5292- + search.lambda
5293- * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(tx_ctx, side, depth));
5424+ let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(tx_ctx, side, depth);
5425+ let cost_d = sse + search.lambda * split_lambda_mult() * rate;
5426+ if census_flat.is_some() {
5427+ let c = (bits + tx_depth_bits(tx_ctx, side, depth), sse);
5428+ if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
5429+ {
5430+ census_split = Some(c);
5431+ }
5432+ }
52945433 if cost_d < best.0 {
52955434 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
52965435 best_types = types;
52975436 }
52985437 }
5438+ if let (Some(flat), Some(split)) = (census_flat, census_split) {
5439+ split_census(0, census_key, side, best.1 > 0, split, flat);
5440+ }
52995441 luma_tx_types = best_types;
53005442 luma.restore(x, y, side, &best.2);
53015443 cost = best.0;
@@ -6131,6 +6273,7 @@ fn code_square_inter(
61316273 // inter neighbour votes its own BLOCK size), which `record_mi`
61326274 // now publishes per cell.
61336275 tx_ctx_txfm(grid, (mi_row, mi_col), side.min(64)),
6276+ false,
61346277 fctx,
61356278 );
61366279 let luma_set = if side == 8 {
@@ -7828,6 +7971,7 @@ pub(crate) fn encode_key_frame_inner(
78287971 tx_select,
78297972 None,
78307973 tx_ctx(&above_tx, &left_tx, (x64, y64), SUPERBLOCK),
7974+ true,
78317975 fctx,
78327976 );
78337977 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
@@ -7913,6 +8057,7 @@ pub(crate) fn encode_key_frame_inner(
79138057 tx_select,
79148058 ibc.as_mut(),
79158059 tx_ctx(&above_tx, &left_tx, (x, y), BLOCK),
8060+ true,
79168061 fctx,
79178062 );
79188063 cost_whole += search.lambda * partition_bits(BLOCK, false);
@@ -7955,6 +8100,7 @@ pub(crate) fn encode_key_frame_inner(
79558100 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
79568101 SUB,
79578102 ),
8103+ true,
79588104 fctx,
79598105 );
79608106 cost_split += cost;
@@ -7997,6 +8143,7 @@ pub(crate) fn encode_key_frame_inner(
79978143 tx_select,
79988144 None,
79998145 tx_ctx(&above_tx, &left_tx, (leaf_x, leaf_y), 8),
8146+ true,
80008147 fctx,
80018148 );
80028149 cost_split += cost;
crates/ec-av1/src/encoder.rsmodified+10 -0
@@ -1380,6 +1380,16 @@ impl Av1Encoder {
13801380 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
13811381 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
13821382 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1383+ // lane-split: the split census prints on every exit of this call when
1384+ // armed, so no `return` path loses it; the counters are cumulative, so
1385+ // the last table a run prints is that run's total.
1386+ struct SplitCensusDump;
1387+ impl Drop for SplitCensusDump {
1388+ fn drop(&mut self) {
1389+ crate::encode::dump_split_census();
1390+ }
1391+ }
1392+ let _census = crate::encode::split_census_on().then_some(SplitCensusDump);
13831393 if (picture.width, picture.height) != (self.config.width, self.config.height) {
13841394 return Err(Error::unsupported(
13851395 "AV1 encode",