Merge branch 'lane-av1-fdct': FFT-based forward DCT
Browse files at this commit1 changed file +165 -12
- crates/ec-av1/src/transform.rs +165 -12
crates/ec-av1/src/transform.rsmodified+165 -12
| @@ -393,28 +393,163 @@ fn dct_basis(n: usize) -> &'static [f64] { | |||
| 393 | /// to agree on for a level to mean what the encoder thinks it means. | 393 | /// to agree on for a level to mean what the encoder thinks it means. |
| 394 | const INVERSE_GAIN_RECIPROCAL: f64 = 8.0; | 394 | const INVERSE_GAIN_RECIPROCAL: f64 = 8.0; |
| 395 | 395 | ||
| 396 | +/// A complex sample, `(re, im)`, for the radix-2 FFT beneath [`dct1d`]. | ||
| 397 | +type Complex = (f64, f64); | ||
| 398 | + | ||
| 399 | +fn cmul(a: Complex, b: Complex) -> Complex { | ||
| 400 | + (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0) | ||
| 401 | +} | ||
| 402 | + | ||
| 403 | +/// An in-place iterative radix-2 Cooley-Tukey FFT (forward, i.e. the `exp(-i | ||
| 404 | +/// theta)` convention), `a.len()` a power of two. Only [`dct1d`] calls this, | ||
| 405 | +/// on sizes 4 to 64, so no bounds beyond "power of two" are enforced. | ||
| 406 | +fn fft(a: &mut [Complex]) { | ||
| 407 | + let n = a.len(); | ||
| 408 | + if n <= 1 { | ||
| 409 | + return; | ||
| 410 | + } | ||
| 411 | + let mut j = 0; | ||
| 412 | + for i in 1..n { | ||
| 413 | + let mut bit = n >> 1; | ||
| 414 | + while j & bit != 0 { | ||
| 415 | + j ^= bit; | ||
| 416 | + bit >>= 1; | ||
| 417 | + } | ||
| 418 | + j |= bit; | ||
| 419 | + if i < j { | ||
| 420 | + a.swap(i, j); | ||
| 421 | + } | ||
| 422 | + } | ||
| 423 | + let mut len = 2; | ||
| 424 | + while len <= n { | ||
| 425 | + let ang = -2.0 * std::f64::consts::PI / len as f64; | ||
| 426 | + let wlen = (ang.cos(), ang.sin()); | ||
| 427 | + let mut i = 0; | ||
| 428 | + while i < n { | ||
| 429 | + let mut w = (1.0, 0.0); | ||
| 430 | + for k in 0..len / 2 { | ||
| 431 | + let u = a[i + k]; | ||
| 432 | + let v = cmul(a[i + k + len / 2], w); | ||
| 433 | + a[i + k] = (u.0 + v.0, u.1 + v.1); | ||
| 434 | + a[i + k + len / 2] = (u.0 - v.0, u.1 - v.1); | ||
| 435 | + w = cmul(w, wlen); | ||
| 436 | + } | ||
| 437 | + i += len; | ||
| 438 | + } | ||
| 439 | + len <<= 1; | ||
| 440 | + } | ||
| 441 | +} | ||
| 442 | + | ||
| 443 | +/// The orthonormal DCT-II of one line of `n` samples, in `O(n log n)` via | ||
| 444 | +/// Makhoul's FFT reduction rather than the `n^2` direct dot product against | ||
| 445 | +/// [`build_dct_basis`]'s rows. | ||
| 446 | +/// | ||
| 447 | +/// The reduction: reorder `x` into `v[i] = x[2i]`, `v[n-1-i] = x[2i+1]` for | ||
| 448 | +/// `i < n/2`; an `n`-point FFT of `v` then gives the unnormalized DCT-II as | ||
| 449 | +/// `X_k = Re(V_k * exp(-i*pi*k/(2n)))` (measured against the direct | ||
| 450 | +/// definition, not the textbook `2 * Re(...)` form, which double-counts here | ||
| 451 | +/// because `v`'s construction already folds each input pair once). What is | ||
| 452 | +/// returned here is that, | ||
| 453 | +/// scaled to match [`build_dct_basis`]'s convention exactly (`alpha_0 = | ||
| 454 | +/// 1/sqrt(2)`, `alpha_k = 1` otherwise, both times `sqrt(2/n)`) so the result | ||
| 455 | +/// is bit-for-bit the same *contract* as the old matmul, only reordered in | ||
| 456 | +/// its summation (equal up to floating-point rounding, checked in | ||
| 457 | +/// `fast_forward_matches_the_naive_matmul`). | ||
| 458 | +/// The post-FFT twist for [`dct1d`], `(cos(theta_k), sin(theta_k), alpha_k * | ||
| 459 | +/// sqrt(2/n))` per output `k` -- cached per size for the same reason | ||
| 460 | +/// [`dct_basis`] is: computed from a `k`-dependent angle, so a call-time | ||
| 461 | +/// `cos`/`sin` per output (`n` of them, every call) was measured as this | ||
| 462 | +/// factorization's actual bottleneck, worse than the matmul it was meant to | ||
| 463 | +/// beat. | ||
| 464 | +fn dct_twist(n: usize) -> &'static [(f64, f64, f64)] { | ||
| 465 | + use std::sync::OnceLock; | ||
| 466 | + static CACHE: OnceLock<[OnceLock<Vec<(f64, f64, f64)>>; 5]> = OnceLock::new(); | ||
| 467 | + let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new())); | ||
| 468 | + let idx = (n.trailing_zeros() as usize).saturating_sub(2); | ||
| 469 | + cache[idx].get_or_init(|| { | ||
| 470 | + (0..n) | ||
| 471 | + .map(|k| { | ||
| 472 | + let theta = std::f64::consts::PI * k as f64 / (2.0 * n as f64); | ||
| 473 | + let alpha = if k == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 }; | ||
| 474 | + (theta.cos(), theta.sin(), alpha * (2.0 / n as f64).sqrt()) | ||
| 475 | + }) | ||
| 476 | + .collect() | ||
| 477 | + }) | ||
| 478 | +} | ||
| 479 | + | ||
| 480 | +/// | ||
| 481 | +/// `x` and `out` are both exactly `n` long (`n` at most 64, the largest | ||
| 482 | +/// transform side this crate codes); the FFT itself runs on a fixed 64-slot | ||
| 483 | +/// stack array rather than a heap `Vec` -- this call happens twice per row | ||
| 484 | +/// and twice per column of every RD trial's transform, and the allocations | ||
| 485 | +/// that a `Vec` per call cost here were measured as a first source of a first | ||
| 486 | +/// cut of this factorization being *slower* than the matmul it replaced (the | ||
| 487 | +/// call-time trig in [`dct_twist`]'s table was the other, larger one). | ||
| 488 | +fn dct1d(x: &[f64], out: &mut [f64]) { | ||
| 489 | + let n = x.len(); | ||
| 490 | + let half = n / 2; | ||
| 491 | + let mut v = [(0.0f64, 0.0f64); 64]; | ||
| 492 | + for i in 0..half { | ||
| 493 | + v[i] = (x[2 * i], 0.0); | ||
| 494 | + v[n - 1 - i] = (x[2 * i + 1], 0.0); | ||
| 495 | + } | ||
| 496 | + fft(&mut v[..n]); | ||
| 497 | + let twist = dct_twist(n); | ||
| 498 | + for (k, &(c, s, scale)) in twist.iter().enumerate() { | ||
| 499 | + out[k] = scale * (v[k].0 * c + v[k].1 * s); | ||
| 500 | + } | ||
| 501 | +} | ||
| 502 | + | ||
| 396 | /// The forward transform (encoder side, spec-free): the transpose of what the | 503 | /// The forward transform (encoder side, spec-free): the transpose of what the |
| 397 | /// decoder's inverse does, so that `inverse_transform_2d` of the result | 504 | /// decoder's inverse does, so that `inverse_transform_2d` of the result |
| 398 | /// reproduces `residual`. | 505 | /// reproduces `residual`. |
| 399 | /// | 506 | /// |
| 400 | /// AV1 specifies only the inverse transform. The encoder may reach its | 507 | /// AV1 specifies only the inverse transform. The encoder may reach its |
| 401 | -/// coefficients however it likes, and this reaches them the direct way — an | 508 | +/// coefficients however it likes, and this reaches them via [`dct1d`], an |
| 402 | -/// orthonormal DCT-II in double precision, scaled to the decoder's fixed-point | 509 | +/// `O(n log n)` orthonormal DCT-II factorization equal to the direct |
| 403 | -/// gain. It is deterministic, and its accuracy is measured against the | 510 | +/// `O(n^2)` matmul up to floating-point rounding (see |
| 404 | -/// decoder's own inverse rather than asserted. | 511 | +/// `fast_forward_matches_the_naive_matmul`), scaled to the decoder's |
| 512 | +/// fixed-point gain. It is deterministic, and its accuracy is measured | ||
| 513 | +/// against the decoder's own inverse rather than asserted. | ||
| 405 | pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> { | 514 | pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> { |
| 406 | assert_eq!( | 515 | assert_eq!( |
| 407 | residual.len(), | 516 | residual.len(), |
| 408 | side * side, | 517 | side * side, |
| 409 | "one residual sample per position" | 518 | "one residual sample per position" |
| 410 | ); | 519 | ); |
| 520 | + let mut rows = vec![0.0f64; side * side]; | ||
| 521 | + let mut buf = [0.0f64; 64]; | ||
| 522 | + let mut line = [0.0f64; 64]; | ||
| 523 | + for i in 0..side { | ||
| 524 | + for (j, &r) in residual[i * side..][..side].iter().enumerate() { | ||
| 525 | + buf[j] = f64::from(r); | ||
| 526 | + } | ||
| 527 | + dct1d(&buf[..side], &mut line[..side]); | ||
| 528 | + rows[i * side..][..side].copy_from_slice(&line[..side]); | ||
| 529 | + } | ||
| 530 | + let mut out = vec![0.0f64; side * side]; | ||
| 531 | + for v in 0..side { | ||
| 532 | + for (i, c) in buf[..side].iter_mut().enumerate() { | ||
| 533 | + *c = rows[i * side + v]; | ||
| 534 | + } | ||
| 535 | + dct1d(&buf[..side], &mut line[..side]); | ||
| 536 | + for (u, &t) in line[..side].iter().enumerate() { | ||
| 537 | + out[u * side + v] = t; | ||
| 538 | + } | ||
| 539 | + } | ||
| 540 | + let scale = INVERSE_GAIN_RECIPROCAL; | ||
| 541 | + for v in &mut out { | ||
| 542 | + *v *= scale; | ||
| 543 | + } | ||
| 544 | + out | ||
| 545 | +} | ||
| 546 | + | ||
| 547 | +/// The old direct `O(n^2)` matmul against [`build_dct_basis`], kept only as | ||
| 548 | +/// the differential oracle for [`forward_transform_2d`]'s fast replacement | ||
| 549 | +/// (`fast_forward_matches_the_naive_matmul`). | ||
| 550 | +#[cfg(test)] | ||
| 551 | +fn forward_transform_2d_naive(residual: &[i32], side: usize) -> Vec<f64> { | ||
| 411 | let basis = dct_basis(side); | 552 | let basis = dct_basis(side); |
| 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). | ||
| 418 | let mut rows = vec![0.0f64; side * side]; | 553 | let mut rows = vec![0.0f64; side * side]; |
| 419 | for i in 0..side { | 554 | for i in 0..side { |
| 420 | let residual_row = &residual[i * side..][..side]; | 555 | let residual_row = &residual[i * side..][..side]; |
| @@ -427,8 +562,6 @@ pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> { | |||
| 427 | rows[i * side + u] = sum; | 562 | rows[i * side + u] = sum; |
| 428 | } | 563 | } |
| 429 | } | 564 | } |
| 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]; | 565 | let mut rows_t = vec![0.0f64; side * side]; |
| 433 | for i in 0..side { | 566 | for i in 0..side { |
| 434 | for v in 0..side { | 567 | for v in 0..side { |
| @@ -540,6 +673,26 @@ mod tests { | |||
| 540 | (sum / a.len() as f64).sqrt() | 673 | (sum / a.len() as f64).sqrt() |
| 541 | } | 674 | } |
| 542 | 675 | ||
| 676 | + /// [`forward_transform_2d`]'s fast FFT-based factorization against | ||
| 677 | + /// [`forward_transform_2d_naive`]'s direct matmul: same summation | ||
| 678 | + /// reordered, so equal up to floating-point rounding, not bit-exact. | ||
| 679 | + #[test] | ||
| 680 | + fn fast_forward_matches_the_naive_matmul() { | ||
| 681 | + for &side in &[4usize, 8, 16, 32, 64] { | ||
| 682 | + for seed in [1u64, 2, 3] { | ||
| 683 | + let residual = noise(side * side, seed * 1000 + side as u64); | ||
| 684 | + let fast = forward_transform_2d(&residual, side); | ||
| 685 | + let naive = forward_transform_2d_naive(&residual, side); | ||
| 686 | + for (i, (&f, &n)) in fast.iter().zip(&naive).enumerate() { | ||
| 687 | + assert!( | ||
| 688 | + (f - n).abs() < 1e-6 * n.abs().max(1.0), | ||
| 689 | + "{side}x{side} seed {seed} coefficient {i}: fast {f} vs naive {n}" | ||
| 690 | + ); | ||
| 691 | + } | ||
| 692 | + } | ||
| 693 | + } | ||
| 694 | + } | ||
| 695 | + | ||
| 543 | /// The one thing the encoder and the decoder have to agree on. | 696 | /// The one thing the encoder and the decoder have to agree on. |
| 544 | /// | 697 | /// |
| 545 | /// The spec's inverse network is not documented as a scaled orthonormal | 698 | /// The spec's inverse network is not documented as a scaled orthonormal |