The encoder's forward DCT is the decoder's network, transposed
Browse files at this commiteb8e099be35f047b8d08025c495f03552d6741b8Parent: 0e574b5- perf
- the encoder's forward DCT is the decoder's network, transposed
1 changed file +323 -135
- crates/ec-av1/src/transform.rs +323 -135
crates/ec-av1/src/transform.rsmodified+323 -135
| @@ -1390,7 +1390,7 @@ fn build_dct_basis(n: usize) -> Vec<f64> { | ||
| 1390 | 1390 | /// one of the transform sizes this crate codes (4 to 64, a power of two), so |
| 1391 | 1391 | /// a small fixed table indexed by `log2(n)` covers every caller without a |
| 1392 | 1392 | /// hash lookup. |
| 1393 | -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates | |
| 1393 | +// Also the reference [`forward_gain`] measures the fixed-point network against. | |
| 1394 | 1394 | fn dct_basis(n: usize) -> &'static [f64] { |
| 1395 | 1395 | use std::sync::OnceLock; |
| 1396 | 1396 | // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2. |
| @@ -1511,123 +1511,260 @@ pub fn forward_and_quantize_typed( | ||
| 1511 | 1511 | /// to agree on for a level to mean what the encoder thinks it means. |
| 1512 | 1512 | const INVERSE_GAIN_RECIPROCAL: f64 = 8.0; |
| 1513 | 1513 | |
| 1514 | -/// A complex sample, `(re, im)`, for the radix-2 FFT beneath [`dct1d`]. | |
| 1515 | -type Complex = (f64, f64); | |
| 1516 | - | |
| 1517 | -fn cmul(a: Complex, b: Complex) -> Complex { | |
| 1518 | - (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0) | |
| 1519 | -} | |
| 1520 | - | |
| 1521 | -/// An in-place iterative radix-2 Cooley-Tukey FFT (forward, i.e. the `exp(-i | |
| 1522 | -/// theta)` convention), `a.len()` a power of two. Only [`dct1d`] calls this, | |
| 1523 | -/// on sizes 4 to 64, so no bounds beyond "power of two" are enforced. | |
| 1524 | -fn fft(a: &mut [Complex]) { | |
| 1525 | - let n = a.len(); | |
| 1526 | - if n <= 1 { | |
| 1527 | - return; | |
| 1514 | +/// The forward DCT network: [`inverse_dct_n`]'s stages in reverse order, each | |
| 1515 | +/// one transposed. | |
| 1516 | +/// | |
| 1517 | +/// The encoder's forward transform is its own business -- only the quantized | |
| 1518 | +/// levels reach the decoder, and the reconstruction the search scores comes | |
| 1519 | +/// back through the decoder's exact inverse -- so what it owes is a good | |
| 1520 | +/// analysis basis, not a specified one. The cheapest good one is the | |
| 1521 | +/// decoder's: a butterfly network's transpose is that network run backwards | |
| 1522 | +/// with every elementary matrix transposed, and all of this one's elements | |
| 1523 | +/// are symmetric except the unflipped rotation, whose transpose is the same | |
| 1524 | +/// rotation at the negated angle. (`hadamard` is `[[1, 1], [1, -1]]` without | |
| 1525 | +/// its flip and `[[-1, 1], [1, 1]]` with it; a flipped `butterfly` is | |
| 1526 | +/// `[[s, c], [c, -s]]`; `permute` is a bit reversal, an involution.) So the | |
| 1527 | +/// body below -- the inverse's stages reversed, its unflipped angles negated, | |
| 1528 | +/// its permutation moved to the end -- is the analysis half of the same | |
| 1529 | +/// orthogonal transform, in `i32` arithmetic against the decoder's own cosine | |
| 1530 | +/// table: no libm, no complex FFT, and the eight-wide [`Lane`] impls apply to | |
| 1531 | +/// it unchanged. | |
| 1532 | +/// | |
| 1533 | +/// The gain is the inverse network's, since a transpose preserves it; | |
| 1534 | +/// [`forward_gain`] measures it from this network rather than asserting it. | |
| 1535 | +#[inline(always)] | |
| 1536 | +fn forward_dct_n<T: Lane, const N: u32>(t: &mut [T; 64], r: usize) { | |
| 1537 | + if N == 6 { | |
| 1538 | + for i in 0..32 { | |
| 1539 | + hadamard(t, i, 63 - i, false, r); | |
| 1540 | + } | |
| 1528 | 1541 | } |
| 1529 | - let mut j = 0; | |
| 1530 | - for i in 1..n { | |
| 1531 | - let mut bit = n >> 1; | |
| 1532 | - while j & bit != 0 { | |
| 1533 | - j ^= bit; | |
| 1534 | - bit >>= 1; | |
| 1535 | - } | |
| 1536 | - j |= bit; | |
| 1537 | - if i < j { | |
| 1538 | - a.swap(i, j); | |
| 1539 | - } | |
| 1540 | - } | |
| 1541 | - let mut len = 2; | |
| 1542 | - while len <= n { | |
| 1543 | - // lane-av1speed: the stage twiddle depends on `len` alone, so the | |
| 1544 | - // eight values this loop can ever ask for are computed once instead | |
| 1545 | - // of two libm `sincos` calls per stage per call (`__sincos_fma` was | |
| 1546 | - // 9% of the encoder's profile). Same values, so the recurrence below | |
| 1547 | - // -- and every coefficient it produces -- is bit-identical. | |
| 1548 | - static WLEN: std::sync::OnceLock<[(f64, f64); 7]> = std::sync::OnceLock::new(); | |
| 1549 | - let wlen = WLEN.get_or_init(|| { | |
| 1550 | - std::array::from_fn(|i| { | |
| 1551 | - let ang = -2.0 * std::f64::consts::PI / (2u32 << i) as f64; | |
| 1552 | - (ang.cos(), ang.sin()) | |
| 1553 | - }) | |
| 1554 | - })[len.trailing_zeros() as usize - 1]; | |
| 1555 | - let mut i = 0; | |
| 1556 | - while i < n { | |
| 1557 | - let mut w = (1.0, 0.0); | |
| 1558 | - for k in 0..len / 2 { | |
| 1559 | - let u = a[i + k]; | |
| 1560 | - let v = cmul(a[i + k + len / 2], w); | |
| 1561 | - a[i + k] = (u.0 + v.0, u.1 + v.1); | |
| 1562 | - a[i + k + len / 2] = (u.0 - v.0, u.1 - v.1); | |
| 1563 | - w = cmul(w, wlen); | |
| 1542 | + if N == 6 { | |
| 1543 | + for i in 0..8 { | |
| 1544 | + butterfly(t, 55 - i, 40 + i, 32, true, r); | |
| 1545 | + } | |
| 1546 | + } | |
| 1547 | + if N >= 5 { | |
| 1548 | + for i in 0..16 { | |
| 1549 | + hadamard(t, i, 31 - i, false, r); | |
| 1550 | + } | |
| 1551 | + } | |
| 1552 | + if N == 6 { | |
| 1553 | + for i in 0..8 { | |
| 1554 | + hadamard(t, 32 + i, 47 - i, false, r); | |
| 1555 | + hadamard(t, 48 + i, 63 - i, true, r); | |
| 1556 | + } | |
| 1557 | + } | |
| 1558 | + if N >= 5 { | |
| 1559 | + for i in 0..4 { | |
| 1560 | + butterfly(t, 27 - i, 20 + i, 32, true, r); | |
| 1561 | + } | |
| 1562 | + } | |
| 1563 | + if N >= 4 { | |
| 1564 | + for i in 0..8 { | |
| 1565 | + hadamard(t, i, 15 - i, false, r); | |
| 1566 | + } | |
| 1567 | + } | |
| 1568 | + if N == 6 { | |
| 1569 | + for i in 0..8 { | |
| 1570 | + butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r); | |
| 1571 | + } | |
| 1572 | + } | |
| 1573 | + if N >= 5 { | |
| 1574 | + for i in 0..2 { | |
| 1575 | + for j in 0..4 { | |
| 1576 | + hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r); | |
| 1564 | 1577 | } |
| 1565 | - i += len; | |
| 1566 | 1578 | } |
| 1567 | - len <<= 1; | |
| 1579 | + } | |
| 1580 | + if N >= 4 { | |
| 1581 | + for i in 0..2 { | |
| 1582 | + butterfly(t, 13 - i, 10 + i, 32, true, r); | |
| 1583 | + } | |
| 1584 | + } | |
| 1585 | + if N >= 3 { | |
| 1586 | + for i in 0..4 { | |
| 1587 | + hadamard(t, i, 7 - i, false, r); | |
| 1588 | + } | |
| 1589 | + } | |
| 1590 | + if N == 6 { | |
| 1591 | + for i in 0..4 { | |
| 1592 | + for j in 0..4 { | |
| 1593 | + hadamard(t, 32 + 8 * i + j, 39 + 8 * i - j, i & 1 == 1, r); | |
| 1594 | + } | |
| 1595 | + } | |
| 1596 | + } | |
| 1597 | + if N >= 5 { | |
| 1598 | + for i in 0..4 { | |
| 1599 | + butterfly(t, 29 - i, 18 + i, 48 + ((i as i32) >> 1) * 64, true, r); | |
| 1600 | + } | |
| 1601 | + } | |
| 1602 | + if N >= 4 { | |
| 1603 | + for i in 0..2 { | |
| 1604 | + for j in 0..2 { | |
| 1605 | + hadamard(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r); | |
| 1606 | + } | |
| 1607 | + } | |
| 1608 | + } | |
| 1609 | + if N >= 3 { | |
| 1610 | + butterfly(t, 6, 5, 32, true, r); | |
| 1611 | + } | |
| 1612 | + for i in 0..2 { | |
| 1613 | + hadamard(t, i, 3 - i, false, r); | |
| 1614 | + } | |
| 1615 | + if N == 6 { | |
| 1616 | + for i in 0..2 { | |
| 1617 | + for j in 0..4 { | |
| 1618 | + let angle = 56 - (i as i32) * 32 + ((j as i32) >> 1) * 64; | |
| 1619 | + butterfly(t, 61 - i * 8 - j, 34 + i * 8 + j, angle, true, r); | |
| 1620 | + } | |
| 1621 | + } | |
| 1622 | + } | |
| 1623 | + if N >= 5 { | |
| 1624 | + for i in 0..4 { | |
| 1625 | + for j in 0..2 { | |
| 1626 | + hadamard(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r); | |
| 1627 | + } | |
| 1628 | + } | |
| 1629 | + } | |
| 1630 | + if N >= 4 { | |
| 1631 | + for i in 0..2 { | |
| 1632 | + butterfly(t, 14 - i, 9 + i, 48 + 64 * i as i32, true, r); | |
| 1633 | + } | |
| 1634 | + } | |
| 1635 | + if N >= 3 { | |
| 1636 | + for i in 0..2 { | |
| 1637 | + hadamard(t, 4 + 2 * i, 5 + 2 * i, i == 1, r); | |
| 1638 | + } | |
| 1639 | + } | |
| 1640 | + for i in 0..2 { | |
| 1641 | + butterfly(t, 2 * i, 2 * i + 1, if i == 0 { 32 + 16 * i as i32 } else { -(32 + 16 * i as i32) }, i == 0, r); | |
| 1642 | + } | |
| 1643 | + if N == 6 { | |
| 1644 | + for i in 0..8 { | |
| 1645 | + for j in 0..2 { | |
| 1646 | + hadamard(t, 32 + i * 4 + j, 35 + i * 4 - j, i & 1 == 1, r); | |
| 1647 | + } | |
| 1648 | + } | |
| 1649 | + } | |
| 1650 | + if N >= 5 { | |
| 1651 | + for i in 0..2 { | |
| 1652 | + for j in 0..2 { | |
| 1653 | + let angle = 24 + ((j as i32) << 6) + ((1 - i as i32) << 5); | |
| 1654 | + butterfly(t, 30 - 4 * i - j, 17 + 4 * i + j, angle, true, r); | |
| 1655 | + } | |
| 1656 | + } | |
| 1657 | + } | |
| 1658 | + if N >= 4 { | |
| 1659 | + for i in 0..4 { | |
| 1660 | + hadamard(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r); | |
| 1661 | + } | |
| 1662 | + } | |
| 1663 | + if N >= 3 { | |
| 1664 | + for i in 0..2 { | |
| 1665 | + butterfly(t, 4 + i, 7 - i, -(56 - 32 * i as i32), false, r); | |
| 1666 | + } | |
| 1667 | + } | |
| 1668 | + if N == 6 { | |
| 1669 | + for i in 0..4 { | |
| 1670 | + for j in 0..2 { | |
| 1671 | + let angle = 60 - 16 * brev(2, i) as i32 + 64 * j as i32; | |
| 1672 | + butterfly(t, 62 - i * 4 - j, 33 + i * 4 + j, angle, true, r); | |
| 1673 | + } | |
| 1674 | + } | |
| 1675 | + } | |
| 1676 | + if N >= 5 { | |
| 1677 | + for i in 0..8 { | |
| 1678 | + hadamard(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r); | |
| 1679 | + } | |
| 1680 | + } | |
| 1681 | + if N >= 4 { | |
| 1682 | + for i in 0..4 { | |
| 1683 | + butterfly( | |
| 1684 | + t, | |
| 1685 | + 8 + i, | |
| 1686 | + 15 - i, -(12 + ((brev(2, 3 - i) as i32) << 4)), | |
| 1687 | + false, | |
| 1688 | + r); | |
| 1689 | + } | |
| 1690 | + } | |
| 1691 | + if N == 6 { | |
| 1692 | + for i in 0..16 { | |
| 1693 | + hadamard(t, 32 + i * 2, 33 + i * 2, i & 1 == 1, r); | |
| 1694 | + } | |
| 1695 | + } | |
| 1696 | + if N >= 5 { | |
| 1697 | + for i in 0..8 { | |
| 1698 | + butterfly( | |
| 1699 | + t, | |
| 1700 | + 16 + i, | |
| 1701 | + 31 - i, -(6 + ((brev(3, 7 - i) as i32) << 3)), | |
| 1702 | + false, | |
| 1703 | + r); | |
| 1704 | + } | |
| 1705 | + } | |
| 1706 | + if N == 6 { | |
| 1707 | + for i in 0..16 { | |
| 1708 | + butterfly(t, 32 + i, 63 - i, -(63 - 4 * brev(4, i) as i32), false, r); | |
| 1709 | + } | |
| 1710 | + } | |
| 1711 | + | |
| 1712 | + permute(t, N); | |
| 1713 | +} | |
| 1714 | + | |
| 1715 | +/// [`forward_dct_n`] dispatched on the size, as [`inverse_dct_fixed`] is. | |
| 1716 | +fn forward_dct_fixed(t: &mut [i32; 64], n: u32, r: usize) { | |
| 1717 | + match n { | |
| 1718 | + 2 => forward_dct_n::<i32, 2>(t, r), | |
| 1719 | + 3 => forward_dct_n::<i32, 3>(t, r), | |
| 1720 | + 4 => forward_dct_n::<i32, 4>(t, r), | |
| 1721 | + 5 => forward_dct_n::<i32, 5>(t, r), | |
| 1722 | + 6 => forward_dct_n::<i32, 6>(t, r), | |
| 1723 | + _ => unreachable!("the forward DCT is defined for 4..64"), | |
| 1568 | 1724 | } |
| 1569 | 1725 | } |
| 1570 | 1726 | |
| 1571 | -/// The orthonormal DCT-II of one line of `n` samples, in `O(n log n)` via | |
| 1572 | -/// Makhoul's FFT reduction rather than the `n^2` direct dot product against | |
| 1573 | -/// [`build_dct_basis`]'s rows. | |
| 1727 | +/// The range the forward network's intermediates are clamped to. The residual | |
| 1728 | +/// is at most +-2^bit_depth and one pass multiplies by the network's gain | |
| 1729 | +/// (`sqrt(n / 2)`, at most 5.66), so two passes stay under 2^20 for 8-bit and | |
| 1730 | +/// nothing here ever reaches this bound -- it exists so `Lane::had` has the | |
| 1731 | +/// same shape it has in the decoder. | |
| 1732 | +const FORWARD_RANGE: usize = 32; | |
| 1733 | + | |
| 1734 | +/// Headroom bits the residual is shifted up by before the row pass. | |
| 1574 | 1735 | /// |
| 1575 | -/// The reduction: reorder `x` into `v[i] = x[2i]`, `v[n-1-i] = x[2i+1]` for | |
| 1576 | -/// `i < n/2`; an `n`-point FFT of `v` then gives the unnormalized DCT-II as | |
| 1577 | -/// `X_k = Re(V_k * exp(-i*pi*k/(2n)))` (measured against the direct | |
| 1578 | -/// definition, not the textbook `2 * Re(...)` form, which double-counts here | |
| 1579 | -/// because `v`'s construction already folds each input pair once). What is | |
| 1580 | -/// returned here is that, | |
| 1581 | -/// scaled to match [`build_dct_basis`]'s convention exactly (`alpha_0 = | |
| 1582 | -/// 1/sqrt(2)`, `alpha_k = 1` otherwise, both times `sqrt(2/n)`) so the result | |
| 1583 | -/// is bit-for-bit the same *contract* as the old matmul, only reordered in | |
| 1584 | -/// its summation (equal up to floating-point rounding, checked in | |
| 1585 | -/// `fast_forward_matches_the_naive_matmul`). | |
| 1586 | -/// The post-FFT twist for [`dct1d`], `(cos(theta_k), sin(theta_k), alpha_k * | |
| 1587 | -/// sqrt(2/n))` per output `k` -- cached per size for the same reason | |
| 1588 | -/// [`dct_basis`] is: computed from a `k`-dependent angle, so a call-time | |
| 1589 | -/// `cos`/`sin` per output (`n` of them, every call) was measured as this | |
| 1590 | -/// factorization's actual bottleneck, worse than the matmul it was meant to | |
| 1591 | -/// beat. | |
| 1592 | -fn dct_twist(n: usize) -> &'static [(f64, f64, f64)] { | |
| 1736 | +/// The network rounds to an integer at every butterfly, so its output LSB is | |
| 1737 | +/// what the quantizer's input resolution costs: unshifted, one LSB at 4x4 is | |
| 1738 | +/// four whole units of the `8 * orthonormal` scale the levels are formed on | |
| 1739 | +/// -- coarser than a fine quantizer's own step. Six bits put that back at | |
| 1740 | +/// 1/16 of a unit and cost nothing: the widest case (a 13-bit residual | |
| 1741 | +/// through two 64-point passes, gain 32) stays under 2^25, well inside `i32` | |
| 1742 | +/// and far inside [`FORWARD_RANGE`]. | |
| 1743 | +const FORWARD_PRECISION_BITS: u32 = 6; | |
| 1744 | + | |
| 1745 | +/// [`forward_dct_n`]'s uniform gain at one size, measured from the network | |
| 1746 | +/// itself rather than derived: an impulse through it is `g` times | |
| 1747 | +/// [`dct_basis`]'s corresponding column, so a least-squares fit over the | |
| 1748 | +/// whole column returns `g` without trusting any single output's rounding. | |
| 1749 | +/// Cached per size, like every other table here. | |
| 1750 | +fn forward_gain(n: usize) -> f64 { | |
| 1593 | 1751 | use std::sync::OnceLock; |
| 1594 | - static CACHE: OnceLock<[OnceLock<Vec<(f64, f64, f64)>>; 5]> = OnceLock::new(); | |
| 1752 | + static CACHE: OnceLock<[OnceLock<f64>; 5]> = OnceLock::new(); | |
| 1595 | 1753 | let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new())); |
| 1596 | - let idx = (n.trailing_zeros() as usize).saturating_sub(2); | |
| 1597 | - cache[idx].get_or_init(|| { | |
| 1598 | - (0..n) | |
| 1599 | - .map(|k| { | |
| 1600 | - let theta = std::f64::consts::PI * k as f64 / (2.0 * n as f64); | |
| 1601 | - let alpha = if k == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 }; | |
| 1602 | - (theta.cos(), theta.sin(), alpha * (2.0 / n as f64).sqrt()) | |
| 1603 | - }) | |
| 1604 | - .collect() | |
| 1754 | + *cache[(n.trailing_zeros() as usize).saturating_sub(2)].get_or_init(|| { | |
| 1755 | + // Large enough that the network's rounding is negligible against it, | |
| 1756 | + // far below anything `FORWARD_RANGE` clamps. | |
| 1757 | + const AMP: i32 = 1 << 14; | |
| 1758 | + let mut t = [0i32; 64]; | |
| 1759 | + t[0] = AMP; | |
| 1760 | + forward_dct_fixed(&mut t, n.trailing_zeros(), FORWARD_RANGE); | |
| 1761 | + let basis = dct_basis(n); | |
| 1762 | + let num: f64 = (0..n).map(|u| f64::from(t[u]) * basis[u * n]).sum(); | |
| 1763 | + let den: f64 = (0..n).map(|u| basis[u * n] * basis[u * n]).sum(); | |
| 1764 | + num / (f64::from(AMP) * den) | |
| 1605 | 1765 | }) |
| 1606 | 1766 | } |
| 1607 | 1767 | |
| 1608 | -/// | |
| 1609 | -/// `x` and `out` are both exactly `n` long (`n` at most 64, the largest | |
| 1610 | -/// transform side this crate codes); the FFT itself runs on a fixed 64-slot | |
| 1611 | -/// stack array rather than a heap `Vec` -- this call happens twice per row | |
| 1612 | -/// and twice per column of every RD trial's transform, and the allocations | |
| 1613 | -/// that a `Vec` per call cost here were measured as a first source of a first | |
| 1614 | -/// cut of this factorization being *slower* than the matmul it replaced (the | |
| 1615 | -/// call-time trig in [`dct_twist`]'s table was the other, larger one). | |
| 1616 | -fn dct1d(x: &[f64], out: &mut [f64]) { | |
| 1617 | - let n = x.len(); | |
| 1618 | - let half = n / 2; | |
| 1619 | - let mut v = [(0.0f64, 0.0f64); 64]; | |
| 1620 | - for i in 0..half { | |
| 1621 | - v[i] = (x[2 * i], 0.0); | |
| 1622 | - v[n - 1 - i] = (x[2 * i + 1], 0.0); | |
| 1623 | - } | |
| 1624 | - fft(&mut v[..n]); | |
| 1625 | - let twist = dct_twist(n); | |
| 1626 | - for (k, &(c, s, scale)) in twist.iter().enumerate() { | |
| 1627 | - out[k] = scale * (v[k].0 * c + v[k].1 * s); | |
| 1628 | - } | |
| 1629 | -} | |
| 1630 | - | |
| 1631 | 1768 | /// The forward transform (encoder side, spec-free): the transpose of what the |
| 1632 | 1769 | /// decoder's inverse does, so that `inverse_transform_2d` of the result |
| 1633 | 1770 | /// reproduces `residual`. |
| @@ -1645,29 +1782,41 @@ pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> { | ||
| 1645 | 1782 | side * side, |
| 1646 | 1783 | "one residual sample per position" |
| 1647 | 1784 | ); |
| 1648 | - let mut rows = vec![0.0f64; side * side]; | |
| 1649 | - let mut buf = [0.0f64; 64]; | |
| 1650 | - let mut line = [0.0f64; 64]; | |
| 1785 | + let log2 = side.trailing_zeros(); | |
| 1786 | + let mut rows = vec![0i32; side * side]; | |
| 1787 | + let mut t = [0i32; 64]; | |
| 1651 | 1788 | for i in 0..side { |
| 1652 | - for (j, &r) in residual[i * side..][..side].iter().enumerate() { | |
| 1653 | - buf[j] = f64::from(r); | |
| 1789 | + let source = &residual[i * side..][..side]; | |
| 1790 | + // Zero in, zero out, and `rows` is already zero here -- the skip the | |
| 1791 | + // decoder's column pass takes for the same reason. | |
| 1792 | + if source.iter().all(|&r| r == 0) { | |
| 1793 | + continue; | |
| 1794 | + } | |
| 1795 | + for (dst, &r) in t[..side].iter_mut().zip(source) { | |
| 1796 | + *dst = r << FORWARD_PRECISION_BITS; | |
| 1654 | 1797 | } |
| 1655 | - dct1d(&buf[..side], &mut line[..side]); | |
| 1656 | - rows[i * side..][..side].copy_from_slice(&line[..side]); | |
| 1798 | + forward_dct_fixed(&mut t, log2, FORWARD_RANGE); | |
| 1799 | + rows[i * side..][..side].copy_from_slice(&t[..side]); | |
| 1657 | 1800 | } |
| 1801 | + // Both passes carry the network's gain, and the decoder owes the levels | |
| 1802 | + // `INVERSE_GAIN_RECIPROCAL` times the ORTHONORMAL coefficient, so the one | |
| 1803 | + // multiply that leaves fixed point divides it back out. | |
| 1804 | + let g = forward_gain(side); | |
| 1805 | + let scale = INVERSE_GAIN_RECIPROCAL / (g * g * f64::from(1u32 << FORWARD_PRECISION_BITS)); | |
| 1658 | 1806 | let mut out = vec![0.0f64; side * side]; |
| 1659 | 1807 | for v in 0..side { |
| 1660 | - for (i, c) in buf[..side].iter_mut().enumerate() { | |
| 1661 | - *c = rows[i * side + v]; | |
| 1808 | + let mut any = 0i32; | |
| 1809 | + for i in 0..side { | |
| 1810 | + t[i] = rows[i * side + v]; | |
| 1811 | + any |= t[i]; | |
| 1662 | 1812 | } |
| 1663 | - dct1d(&buf[..side], &mut line[..side]); | |
| 1664 | - for (u, &t) in line[..side].iter().enumerate() { | |
| 1665 | - out[u * side + v] = t; | |
| 1813 | + if any == 0 { | |
| 1814 | + continue; | |
| 1815 | + } | |
| 1816 | + forward_dct_fixed(&mut t, log2, FORWARD_RANGE); | |
| 1817 | + for u in 0..side { | |
| 1818 | + out[u * side + v] = f64::from(t[u]) * scale; | |
| 1666 | 1819 | } |
| 1667 | - } | |
| 1668 | - let scale = INVERSE_GAIN_RECIPROCAL; | |
| 1669 | - for v in &mut out { | |
| 1670 | - *v *= scale; | |
| 1671 | 1820 | } |
| 1672 | 1821 | out |
| 1673 | 1822 | } |
| @@ -1913,31 +2062,70 @@ mod tests { | ||
| 1913 | 2062 | /// [`forward_transform_2d_naive`]'s direct matmul: same summation |
| 1914 | 2063 | /// reordered, so equal up to floating-point rounding, not bit-exact. |
| 1915 | 2064 | #[test] |
| 1916 | - fn fast_forward_matches_the_naive_matmul() { | |
| 2065 | + fn the_fixed_point_forward_matches_the_exact_matmul() { | |
| 1917 | 2066 | for &side in &[4usize, 8, 16, 32, 64] { |
| 1918 | 2067 | for seed in [1u64, 2, 3] { |
| 1919 | 2068 | let residual = noise(side * side, seed * 1000 + side as u64); |
| 1920 | 2069 | let fast = forward_transform_2d(&residual, side); |
| 1921 | 2070 | let naive = forward_transform_2d_naive(&residual, side); |
| 1922 | - for (i, (&f, &n)) in fast.iter().zip(&naive).enumerate() { | |
| 2071 | + let worst = fast | |
| 2072 | + .iter() | |
| 2073 | + .zip(&naive) | |
| 2074 | + .map(|(f, n)| (f - n).abs()) | |
| 2075 | + .fold(0.0f64, f64::max); | |
| 2076 | + let energy: f64 = naive.iter().map(|n| n * n).sum::<f64>().sqrt(); | |
| 2077 | + let err: f64 = fast | |
| 2078 | + .iter() | |
| 2079 | + .zip(&naive) | |
| 2080 | + .map(|(f, n)| (f - n) * (f - n)) | |
| 2081 | + .sum::<f64>() | |
| 2082 | + .sqrt(); | |
| 2083 | + // The network rounds at every butterfly, so it is not the | |
| 2084 | + // matmul to the last bit -- it is the same transform to well | |
| 2085 | + // inside one quantizer step. One unit here is an eighth of an | |
| 2086 | + // orthonormal coefficient ([`INVERSE_GAIN_RECIPROCAL`]), and | |
| 2087 | + // the finest step any level is formed on is `dc_q(8, 0) = 4`. | |
| 2088 | + assert!(worst < 1.0, "{side}x{side} seed {seed}: worst {worst}"); | |
| 2089 | + assert!( | |
| 2090 | + err < 1e-3 * energy, | |
| 2091 | + "{side}x{side} seed {seed}: rmse {err} of energy {energy}" | |
| 2092 | + ); | |
| 2093 | + } | |
| 2094 | + } | |
| 2095 | + } | |
| 2096 | + | |
| 2097 | + /// The gain [`forward_transform_2d`] divides out is the network's own, and | |
| 2098 | + /// it is ONE number per size -- if the network's gain varied by output the | |
| 2099 | + /// single scale would tilt the spectrum. Pinned per size against the | |
| 2100 | + /// orthonormal basis it is measured from. | |
| 2101 | + #[test] | |
| 2102 | + fn the_forward_network_has_one_uniform_gain() { | |
| 2103 | + for &n in &[4usize, 8, 16, 32, 64] { | |
| 2104 | + let g = forward_gain(n); | |
| 2105 | + assert!( | |
| 2106 | + (g - (n as f64 / 2.0).sqrt()).abs() < 1e-3, | |
| 2107 | + "{n}-point gain {g}" | |
| 2108 | + ); | |
| 2109 | + let basis = dct_basis(n); | |
| 2110 | + for i in 0..n { | |
| 2111 | + let mut t = [0i32; 64]; | |
| 2112 | + t[i] = 1 << 14; | |
| 2113 | + forward_dct_fixed(&mut t, n.trailing_zeros(), FORWARD_RANGE); | |
| 2114 | + for u in 0..n { | |
| 2115 | + let want = g * f64::from(1 << 14) * basis[u * n + i]; | |
| 2116 | + // A thousandth of the impulse's own amplitude: the | |
| 2117 | + // network's rounding accumulates over its stages, and | |
| 2118 | + // what is pinned here is that the SHAPE is the basis. | |
| 1923 | 2119 | assert!( |
| 1924 | - (f - n).abs() < 1e-6 * n.abs().max(1.0), | |
| 1925 | - "{side}x{side} seed {seed} coefficient {i}: fast {f} vs naive {n}" | |
| 2120 | + (f64::from(t[u]) - want).abs() < 1e-3 * g * f64::from(1 << 14), | |
| 2121 | + "{n}-point impulse {i} output {u}: {} vs {want}", | |
| 2122 | + t[u] | |
| 1926 | 2123 | ); |
| 1927 | 2124 | } |
| 1928 | 2125 | } |
| 1929 | 2126 | } |
| 1930 | 2127 | } |
| 1931 | 2128 | |
| 1932 | - /// The one thing the encoder and the decoder have to agree on. | |
| 1933 | - /// | |
| 1934 | - /// The spec's inverse network is not documented as a scaled orthonormal | |
| 1935 | - /// DCT, so this measures it: each dequantized coefficient, on its own, | |
| 1936 | - /// comes back out as its orthonormal basis function scaled by | |
| 1937 | - /// `dq_denom(side) / 8` — the same factor for every coefficient of a | |
| 1938 | - /// size, which is what makes a single constant enough for the encoder. | |
| 1939 | - /// The fit is checked as well as the scale, so an inverse that scaled | |
| 1940 | - /// right but mixed positions apart could not pass. | |
| 1941 | 2129 | #[test] |
| 1942 | 2130 | fn the_inverse_network_is_an_orthonormal_dct_over_eight() { |
| 1943 | 2131 | for &side in &[4usize, 8, 16, 32, 64] { |