forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-perf': cache the DCT basis; the sweep gains four edge sizes

Browse files at this commit

2e9837a861c3e221339a716b50f9a665d4180699Ahmet Kaan GümüşParent: 0e70b278593d36
forward_and_quantize recomputed side^2 cosines on every mode trial;
a OnceLock-cached basis plus contiguous dot-product passes (same
summation order, bit-identical output) takes a 1080p key frame from
3.97s to 1.78s and 3840x2160 from 10.6s to 7.1s. The own-size sweep
now covers 64x56 (historical V-plane bug confirmed closed), 854x480,
216x96 and 192x120; the never-written high-precision-mv CDF fields
are gone.
crates/ec-av1/src/cdf_state.rsmodified+4 -6
@@ -194,14 +194,14 @@ pub(crate) struct MvComponentCdfs {
194 pub class0_bit: [u16; 3],194 pub class0_bit: [u16; 3],
195 /// The fractional part of a small-class magnitude, by its integer bit.195 /// The fractional part of a small-class magnitude, by its integer bit.
196 pub class0_fr: [[u16; 5]; 2],196 pub class0_fr: [[u16; 5]; 2],
197- /// The half-pel bit of a small-class magnitude.197+ // `class0_hp`/`hp` (spec's half-pel-bit CDFs) are never written: this
198- pub class0_hp: [u16; 3],198+ // encoder always sets `allow_high_precision_mv = false`, so the syntax
199+ // that reads them (spec 5.9.32 `mv_class0_hp`/`mv_hp`) never fires --
200+ // dropped rather than kept dead. Add back if/when hp mode ships.
199 /// One bit of an above-small-class magnitude, by its position.201 /// One bit of an above-small-class magnitude, by its position.
200 pub bit: [[u16; 3]; 10],202 pub bit: [[u16; 3]; 10],
201 /// The fractional part of an above-small-class magnitude.203 /// The fractional part of an above-small-class magnitude.
202 pub fr: [u16; 5],204 pub fr: [u16; 5],
203- /// The half-pel bit of an above-small-class magnitude.
204- pub hp: [u16; 3],
205 /// The component's sign.205 /// The component's sign.
206 pub sign: [u16; 3],206 pub sign: [u16; 3],
207 }207 }
@@ -212,10 +212,8 @@ impl MvComponentCdfs {
212 class: cdf::MV_CLASS,212 class: cdf::MV_CLASS,
213 class0_bit: cdf::MV_CLASS0_BIT,213 class0_bit: cdf::MV_CLASS0_BIT,
214 class0_fr: cdf::MV_CLASS0_FR,214 class0_fr: cdf::MV_CLASS0_FR,
215- class0_hp: cdf::MV_CLASS0_HP,
216 bit: cdf::MV_BIT,215 bit: cdf::MV_BIT,
217 fr: cdf::MV_FR,216 fr: cdf::MV_FR,
218- hp: cdf::MV_HP,
219 sign: cdf::MV_SIGN,217 sign: cdf::MV_SIGN,
220 }218 }
221 }219 }
crates/ec-av1/src/encode.rsmodified+120 -1
@@ -2433,7 +2433,15 @@ mod tests {
2433 // 854x480 is covered separately by2433 // 854x480 is covered separately by
2434 // `an_854x480_picture_round_trips_through_its_padding`, which its own2434 // `an_854x480_picture_round_trips_through_its_padding`, which its own
2435 // doc comment explains was worth keeping as its own test.2435 // doc comment explains was worth keeping as its own test.
2436- for &(width, height) in &[(1920usize, 1080usize), (640, 352), (1280, 720)] {2436+ for &(width, height) in &[
2437+ (1920usize, 1080usize),
2438+ (640, 352),
2439+ (1280, 720),
2440+ (64, 56),
2441+ (854, 480),
2442+ (216, 96),
2443+ (192, 120),
2444+ ] {
2437 let picture = test_card(width, height);2445 let picture = test_card(width, height);
2438 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();2446 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
2439 assert_eq!(2447 assert_eq!(
@@ -3452,4 +3460,115 @@ mod tests {
3452 "no inter frame coded a single inter block -- the search never fired"3460 "no inter frame coded a single inter block -- the search never fired"
3453 );3461 );
3454 }3462 }
3463+
3464+ /// A manual perf probe, not a gate: prints where a key frame's and an
3465+ /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
3466+ /// measures before it optimizes rather than guessing. Run with
3467+ /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
3468+ #[test]
3469+ #[ignore = "a perf probe, not a gate"]
3470+ fn stage_timing_breakdown() {
3471+ use std::time::Instant;
3472+
3473+ for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
3474+ let picture = test_card(width, height);
3475+
3476+ let t = Instant::now();
3477+ let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap();
3478+ let dc_only_t = t.elapsed();
3479+
3480+ let t = Instant::now();
3481+ let non_directional =
3482+ encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap();
3483+ let non_directional_t = t.elapsed();
3484+
3485+ let t = Instant::now();
3486+ let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap();
3487+ let all_modes_t = t.elapsed();
3488+
3489+ eprintln!(
3490+ "\n=== key frame {width}x{height} ===\n\
3491+ 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
3492+ 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
3493+ 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
3494+ dc_only.stream.len(),
3495+ non_directional.stream.len(),
3496+ all_modes.stream.len(),
3497+ );
3498+
3499+ // One inter frame predicting off the key frame's own
3500+ // reconstruction, the (256, 256)-padded surface encode_sequence
3501+ // itself would hand encode_inter_frame.
3502+ let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
3503+ let padded_pic = picture.padded_to(SUPERBLOCK);
3504+ let t = Instant::now();
3505+ let inter =
3506+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();
3507+ let inter_t = t.elapsed();
3508+ eprintln!(
3509+ "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
3510+ {:.2})",
3511+ inter.stream.len(),
3512+ inter.inter_block_share
3513+ );
3514+ }
3515+
3516+ // Isolated per-call cost of the trial pipeline's own stages, at both
3517+ // transform sizes the search runs, averaged over enough calls to
3518+ // rise above `Instant::now`'s own noise.
3519+ for side in [16usize, 32] {
3520+ const N: u32 = 20_000;
3521+ let residual: Vec<i32> = (0..side * side)
3522+ .map(|i| ((i * 37 % 61) as i32) - 30)
3523+ .collect();
3524+
3525+ let t = Instant::now();
3526+ let mut levels = Vec::new();
3527+ for _ in 0..N {
3528+ levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
3529+ }
3530+ let forward_t = t.elapsed() / N;
3531+
3532+ let t = Instant::now();
3533+ for _ in 0..N {
3534+ std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100));
3535+ }
3536+ let inverse_t = t.elapsed() / N;
3537+
3538+ let set = if side == 32 {
3539+ crate::cdf_state::TxbSet::Luma32
3540+ } else {
3541+ crate::cdf_state::TxbSet::Luma16
3542+ };
3543+ let t = Instant::now();
3544+ for _ in 0..N {
3545+ std::hint::black_box(crate::tile::coeff_bits(&levels, set));
3546+ }
3547+ let entropy_t = t.elapsed() / N;
3548+
3549+ let above = vec![128u8; side * 2];
3550+ let left = vec![128u8; side * 2];
3551+ let mut prediction = vec![0u8; side * side];
3552+ let t = Instant::now();
3553+ for _ in 0..N {
3554+ crate::intra::predict(
3555+ D45_PRED,
3556+ Some(&above),
3557+ Some(&left),
3558+ Some(128),
3559+ side,
3560+ &mut prediction,
3561+ );
3562+ }
3563+ let predict_t = t.elapsed() / N;
3564+
3565+ eprintln!(
3566+ "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
3567+ predict (1 directional mode): {predict_t:>9.2?}\n\
3568+ forward_and_quantize: {forward_t:>9.2?}\n\
3569+ dequant_and_inverse: {inverse_t:>9.2?}\n\
3570+ coeff_bits: {entropy_t:>9.2?}"
3571+ );
3572+ }
3573+ }
3455 }3574 }
crates/ec-av1/src/transform.rsmodified+43 -10
@@ -349,7 +349,7 @@ pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i3
349 /// undo, and nothing else: measuring the network's response to a unit349 /// undo, and nothing else: measuring the network's response to a unit
350 /// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of350 /// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of
351 /// `dqDenom`, which is what [`forward_transform_2d`] divides out.351 /// `dqDenom`, which is what [`forward_transform_2d`] divides out.
352-fn dct_basis(n: usize) -> Vec<f64> {352+fn build_dct_basis(n: usize) -> Vec<f64> {
353 let mut basis = vec![0.0f64; n * n];353 let mut basis = vec![0.0f64; n * n];
354 let scale = (2.0 / n as f64).sqrt();354 let scale = (2.0 / n as f64).sqrt();
355 for u in 0..n {355 for u in 0..n {
@@ -362,6 +362,23 @@ fn dct_basis(n: usize) -> Vec<f64> {
362 basis362 basis
363 }363 }
364 364
365+/// [`build_dct_basis`], computed once per transform size and reused: the
366+/// search calls [`forward_transform_2d`] for every mode of every block, and
367+/// the basis does not depend on the residual, only on `n` -- recomputing
368+/// `n * n` cosines per call was measured as this search's single largest
369+/// per-trial cost (`stage_timing_breakdown`, ec-av1 perf lane). `n` is always
370+/// one of the transform sizes this crate codes (4 to 64, a power of two), so
371+/// a small fixed table indexed by `log2(n)` covers every caller without a
372+/// hash lookup.
373+fn dct_basis(n: usize) -> &'static [f64] {
374+ use std::sync::OnceLock;
375+ // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2.
376+ static CACHE: OnceLock<[OnceLock<Vec<f64>>; 5]> = OnceLock::new();
377+ let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
378+ let idx = (n.trailing_zeros() as usize).saturating_sub(2);
379+ cache[idx].get_or_init(|| build_dct_basis(n))
380+}
381+
365 /// How much the decoder's inverse transform shrinks an orthonormal DCT.382 /// How much the decoder's inverse transform shrinks an orthonormal DCT.
366 ///383 ///
367 /// Measured, not asserted: feeding a single dequantized coefficient through384 /// Measured, not asserted: feeding a single dequantized coefficient through
@@ -392,24 +409,40 @@ pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> {
392 "one residual sample per position"409 "one residual sample per position"
393 );410 );
394 let basis = dct_basis(side);411 let basis = dct_basis(side);
395- // Rows first, into a scratch of the same shape, then columns.412+ // Rows first, into a scratch of the same shape, then columns. Both passes
413+ // are written as a contiguous dot product (row of `residual`/`rows_t`
414+ // against a row of `basis`) rather than an index loop with one strided
415+ // operand -- same summation order, so the same bits out, but a shape the
416+ // optimizer can autovectorize (measured: this halved the per-call cost
417+ // that `stage_timing_breakdown`, ec-av1 perf lane, found dominant).
396 let mut rows = vec![0.0f64; side * side];418 let mut rows = vec![0.0f64; side * side];
397 for i in 0..side {419 for i in 0..side {
420+ let residual_row = &residual[i * side..][..side];
398 for u in 0..side {421 for u in 0..side {
399- let mut sum = 0.0;422+ let sum: f64 = residual_row
400- for j in 0..side {423+ .iter()
401- sum += f64::from(residual[i * side + j]) * basis[u * side + j];424+ .zip(&basis[u * side..][..side])
402- }425+ .map(|(&r, &b)| f64::from(r) * b)
426+ .sum();
403 rows[i * side + u] = sum;427 rows[i * side + u] = sum;
404 }428 }
405 }429 }
430+ // Transposed so the column pass reads `rows` contiguously too, without
431+ // changing which terms are summed in which order.
432+ let mut rows_t = vec![0.0f64; side * side];
433+ for i in 0..side {
434+ for v in 0..side {
435+ rows_t[v * side + i] = rows[i * side + v];
436+ }
437+ }
406 let mut out = vec![0.0f64; side * side];438 let mut out = vec![0.0f64; side * side];
407 for u in 0..side {439 for u in 0..side {
408 for v in 0..side {440 for v in 0..side {
409- let mut sum = 0.0;441+ let sum: f64 = rows_t[v * side..][..side]
410- for i in 0..side {442+ .iter()
411- sum += rows[i * side + v] * basis[u * side + i];443+ .zip(&basis[u * side..][..side])
412- }444+ .map(|(&r, &b)| r * b)
445+ .sum();
413 out[u * side + v] = sum;446 out[u * side + v] = sum;
414 }447 }
415 }448 }