Cache the forward DCT basis
Browse files at this commit91b85b510c54d76d3547ecdf5bf1f0d01422dff4Parent: 1457eaa- perf
- cache the forward DCT basis
- make it contiguous, both bit-exact
2 changed files +155 -10
- crates/ec-av1/src/encode.rs +112 -0
- crates/ec-av1/src/transform.rs +43 -10
crates/ec-av1/src/encode.rsmodified+112 -0
| @@ -3460,4 +3460,116 @@ mod tests { | ||
| 3460 | 3460 | "no inter frame coded a single inter block -- the search never fired" |
| 3461 | 3461 | ); |
| 3462 | 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)) | |
| 3507 | + .unwrap(); | |
| 3508 | + let inter_t = t.elapsed(); | |
| 3509 | + eprintln!( | |
| 3510 | + "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ | |
| 3511 | + {:.2})", | |
| 3512 | + inter.stream.len(), | |
| 3513 | + inter.inter_block_share | |
| 3514 | + ); | |
| 3515 | + } | |
| 3516 | + | |
| 3517 | + // Isolated per-call cost of the trial pipeline's own stages, at both | |
| 3518 | + // transform sizes the search runs, averaged over enough calls to | |
| 3519 | + // rise above `Instant::now`'s own noise. | |
| 3520 | + for side in [16usize, 32] { | |
| 3521 | + const N: u32 = 20_000; | |
| 3522 | + let residual: Vec<i32> = (0..side * side) | |
| 3523 | + .map(|i| ((i * 37 % 61) as i32) - 30) | |
| 3524 | + .collect(); | |
| 3525 | + | |
| 3526 | + let t = Instant::now(); | |
| 3527 | + let mut levels = Vec::new(); | |
| 3528 | + for _ in 0..N { | |
| 3529 | + levels = forward_and_quantize(&residual, side, 8, 100, 0.5); | |
| 3530 | + } | |
| 3531 | + let forward_t = t.elapsed() / N; | |
| 3532 | + | |
| 3533 | + let t = Instant::now(); | |
| 3534 | + for _ in 0..N { | |
| 3535 | + std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100)); | |
| 3536 | + } | |
| 3537 | + let inverse_t = t.elapsed() / N; | |
| 3538 | + | |
| 3539 | + let set = if side == 32 { | |
| 3540 | + crate::cdf_state::TxbSet::Luma32 | |
| 3541 | + } else { | |
| 3542 | + crate::cdf_state::TxbSet::Luma16 | |
| 3543 | + }; | |
| 3544 | + let t = Instant::now(); | |
| 3545 | + for _ in 0..N { | |
| 3546 | + std::hint::black_box(crate::tile::coeff_bits(&levels, set)); | |
| 3547 | + } | |
| 3548 | + let entropy_t = t.elapsed() / N; | |
| 3549 | + | |
| 3550 | + let above = vec![128u8; side * 2]; | |
| 3551 | + let left = vec![128u8; side * 2]; | |
| 3552 | + let mut prediction = vec![0u8; side * side]; | |
| 3553 | + let t = Instant::now(); | |
| 3554 | + for _ in 0..N { | |
| 3555 | + crate::intra::predict( | |
| 3556 | + D45_PRED, | |
| 3557 | + Some(&above), | |
| 3558 | + Some(&left), | |
| 3559 | + Some(128), | |
| 3560 | + side, | |
| 3561 | + &mut prediction, | |
| 3562 | + ); | |
| 3563 | + } | |
| 3564 | + let predict_t = t.elapsed() / N; | |
| 3565 | + | |
| 3566 | + eprintln!( | |
| 3567 | + "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ | |
| 3568 | + predict (1 directional mode): {predict_t:>9.2?}\n\ | |
| 3569 | + forward_and_quantize: {forward_t:>9.2?}\n\ | |
| 3570 | + dequant_and_inverse: {inverse_t:>9.2?}\n\ | |
| 3571 | + coeff_bits: {entropy_t:>9.2?}" | |
| 3572 | + ); | |
| 3573 | + } | |
| 3574 | + } | |
| 3463 | 3575 | } |
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 | 349 | /// undo, and nothing else: measuring the network's response to a unit |
| 350 | 350 | /// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of |
| 351 | 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 | 353 | let mut basis = vec![0.0f64; n * n]; |
| 354 | 354 | let scale = (2.0 / n as f64).sqrt(); |
| 355 | 355 | for u in 0..n { |
| @@ -362,6 +362,23 @@ fn dct_basis(n: usize) -> Vec<f64> { | ||
| 362 | 362 | 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 | 382 | /// How much the decoder's inverse transform shrinks an orthonormal DCT. |
| 366 | 383 | /// |
| 367 | 384 | /// 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 | 409 | "one residual sample per position" |
| 393 | 410 | ); |
| 394 | 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 | 418 | let mut rows = vec![0.0f64; side * side]; |
| 397 | 419 | for i in 0..side { |
| 420 | + let residual_row = &residual[i * side..][..side]; | |
| 398 | 421 | for u in 0..side { |
| 399 | - let mut sum = 0.0; | |
| 400 | - for j in 0..side { | |
| 401 | - sum += f64::from(residual[i * side + j]) * basis[u * side + j]; | |
| 402 | - } | |
| 422 | + let sum: f64 = residual_row | |
| 423 | + .iter() | |
| 424 | + .zip(&basis[u * side..][..side]) | |
| 425 | + .map(|(&r, &b)| f64::from(r) * b) | |
| 426 | + .sum(); | |
| 403 | 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 | 438 | let mut out = vec![0.0f64; side * side]; |
| 407 | 439 | for u in 0..side { |
| 408 | 440 | for v in 0..side { |
| 409 | - let mut sum = 0.0; | |
| 410 | - for i in 0..side { | |
| 411 | - sum += rows[i * side + v] * basis[u * side + i]; | |
| 412 | - } | |
| 441 | + let sum: f64 = rows_t[v * side..][..side] | |
| 442 | + .iter() | |
| 443 | + .zip(&basis[u * side..][..side]) | |
| 444 | + .map(|(&r, &b)| r * b) | |
| 445 | + .sum(); | |
| 413 | 446 | out[u * side + v] = sum; |
| 414 | 447 | } |
| 415 | 448 | } |