forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1dct' (98e4912e): encoder forward DCT is the decoder's fixed-point network transposed (i32, no libm; f64 FFT path deleted), gain measured from the network, forward_and_quantize fused; -14.3% encoder instructions; BD-rate vs rav1e 157.4/175.9/138.1 (was 157.8/178.3/141.1), vs libaom 216.6/233.5/289.8 (was 216.4/235.5/289.2)

Browse files at this commit

dad20ab6e2bab5b77428b4a1e5f0bdfa6282b748Ahmet Kaan GümüşParent: 96d82d0636712f
crates/ec-av1/src/transform.rsmodified+392 -141
@@ -1390,7 +1390,7 @@ fn build_dct_basis(n: usize) -> Vec<f64> {
1390 /// one of the transform sizes this crate codes (4 to 64, a power of two), so1390 /// one of the transform sizes this crate codes (4 to 64, a power of two), so
1391 /// a small fixed table indexed by `log2(n)` covers every caller without a1391 /// a small fixed table indexed by `log2(n)` covers every caller without a
1392 /// hash lookup.1392 /// hash lookup.
1393-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates1393+// Also the reference [`forward_gain`] measures the fixed-point network against.
1394 fn dct_basis(n: usize) -> &'static [f64] {1394 fn dct_basis(n: usize) -> &'static [f64] {
1395 use std::sync::OnceLock;1395 use std::sync::OnceLock;
1396 // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2.1396 // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2.
@@ -1511,123 +1511,261 @@ pub fn forward_and_quantize_typed(
1511 /// to agree on for a level to mean what the encoder thinks it means.1511 /// to agree on for a level to mean what the encoder thinks it means.
1512 const INVERSE_GAIN_RECIPROCAL: f64 = 8.0;1512 const INVERSE_GAIN_RECIPROCAL: f64 = 8.0;
1513 1513
1514-/// A complex sample, `(re, im)`, for the radix-2 FFT beneath [`dct1d`].1514+/// The forward DCT network: [`inverse_dct_n`]'s stages in reverse order, each
1515-type Complex = (f64, f64);1515+/// one transposed.
1516-1516+///
1517-fn cmul(a: Complex, b: Complex) -> Complex {1517+/// The encoder's forward transform is its own business -- only the quantized
1518- (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0)1518+/// levels reach the decoder, and the reconstruction the search scores comes
1519-}1519+/// back through the decoder's exact inverse -- so what it owes is a good
1520-1520+/// analysis basis, not a specified one. The cheapest good one is the
1521-/// An in-place iterative radix-2 Cooley-Tukey FFT (forward, i.e. the `exp(-i1521+/// decoder's: a butterfly network's transpose is that network run backwards
1522-/// theta)` convention), `a.len()` a power of two. Only [`dct1d`] calls this,1522+/// with every elementary matrix transposed, and all of this one's elements
1523-/// on sizes 4 to 64, so no bounds beyond "power of two" are enforced.1523+/// are symmetric except the unflipped rotation, whose transpose is the same
1524-fn fft(a: &mut [Complex]) {1524+/// rotation at the negated angle. (`hadamard` is `[[1, 1], [1, -1]]` without
1525- let n = a.len();1525+/// its flip and `[[-1, 1], [1, 1]]` with it; a flipped `butterfly` is
1526- if n <= 1 {1526+/// `[[s, c], [c, -s]]`; `permute` is a bit reversal, an involution.) So the
1527- return;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;1542+ if N == 6 {
1530- for i in 1..n {1543+ for i in 0..8 {
1531- let mut bit = n >> 1;1544+ butterfly(t, 55 - i, 40 + i, 32, true, r);
1532- while j & bit != 0 {1545+ }
1533- j ^= bit;1546+ }
1534- bit >>= 1;1547+ if N >= 5 {
1535- }1548+ for i in 0..16 {
1536- j |= bit;1549+ hadamard(t, i, 31 - i, false, r);
1537- if i < j {1550+ }
1538- a.swap(i, j);1551+ }
1539- }1552+ if N == 6 {
1540- }1553+ for i in 0..8 {
1541- let mut len = 2;1554+ hadamard(t, 32 + i, 47 - i, false, r);
1542- while len <= n {1555+ hadamard(t, 48 + i, 63 - i, true, r);
1543- // lane-av1speed: the stage twiddle depends on `len` alone, so the1556+ }
1544- // eight values this loop can ever ask for are computed once instead1557+ }
1545- // of two libm `sincos` calls per stage per call (`__sincos_fma` was1558+ if N >= 5 {
1546- // 9% of the encoder's profile). Same values, so the recurrence below1559+ for i in 0..4 {
1547- // -- and every coefficient it produces -- is bit-identical.1560+ butterfly(t, 27 - i, 20 + i, 32, true, r);
1548- static WLEN: std::sync::OnceLock<[(f64, f64); 7]> = std::sync::OnceLock::new();1561+ }
1549- let wlen = WLEN.get_or_init(|| {1562+ }
1550- std::array::from_fn(|i| {1563+ if N >= 4 {
1551- let ang = -2.0 * std::f64::consts::PI / (2u32 << i) as f64;1564+ for i in 0..8 {
1552- (ang.cos(), ang.sin())1565+ hadamard(t, i, 15 - i, false, r);
1553- })1566+ }
1554- })[len.trailing_zeros() as usize - 1];1567+ }
1555- let mut i = 0;1568+ if N == 6 {
1556- while i < n {1569+ for i in 0..8 {
1557- let mut w = (1.0, 0.0);1570+ butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r);
1558- for k in 0..len / 2 {1571+ }
1559- let u = a[i + k];1572+ }
1560- let v = cmul(a[i + k + len / 2], w);1573+ if N >= 5 {
1561- a[i + k] = (u.0 + v.0, u.1 + v.1);1574+ for i in 0..2 {
1562- a[i + k + len / 2] = (u.0 - v.0, u.1 - v.1);1575+ for j in 0..4 {
1563- w = cmul(w, wlen);1576+ hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r);
1577+ }
1578+ }
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);
1564 }1673 }
1565- i += len;
1566 }1674 }
1567- len <<= 1;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)` via1727+/// The range the forward network's intermediates are clamped to. The residual
1572-/// Makhoul's FFT reduction rather than the `n^2` direct dot product against1728+/// is at most +-2^bit_depth and one pass multiplies by the network's gain
1573-/// [`build_dct_basis`]'s rows.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]` for1736+/// The network rounds to an integer at every butterfly, so its output LSB is
1576-/// `i < n/2`; an `n`-point FFT of `v` then gives the unnormalized DCT-II as1737+/// what the quantizer's input resolution costs: unshifted, one LSB at 4x4 is
1577-/// `X_k = Re(V_k * exp(-i*pi*k/(2n)))` (measured against the direct1738+/// four whole units of the `8 * orthonormal` scale the levels are formed on
1578-/// definition, not the textbook `2 * Re(...)` form, which double-counts here1739+/// -- coarser than a fine quantizer's own step, and worth 3.9 BD points on
1579-/// because `v`'s construction already folds each input pair once). What is1740+/// screen capture. Ten bits put it at 1/256 of a unit, which is where the BD
1580-/// returned here is that,1741+/// gate stops moving (13 bits measured identical), and cost nothing: the
1581-/// scaled to match [`build_dct_basis`]'s convention exactly (`alpha_0 =1742+/// widest case, a 12-bit residual through two 64-point passes (gain 32),
1582-/// 1/sqrt(2)`, `alpha_k = 1` otherwise, both times `sqrt(2/n)`) so the result1743+/// stays under 2^27 -- inside `i32` and far inside [`FORWARD_RANGE`].
1583-/// is bit-for-bit the same *contract* as the old matmul, only reordered in1744+const FORWARD_PRECISION_BITS: u32 = 10;
1584-/// its summation (equal up to floating-point rounding, checked in1745+
1585-/// `fast_forward_matches_the_naive_matmul`).1746+/// [`forward_dct_n`]'s uniform gain at one size, measured from the network
1586-/// The post-FFT twist for [`dct1d`], `(cos(theta_k), sin(theta_k), alpha_k *1747+/// itself rather than derived: an impulse through it is `g` times
1587-/// sqrt(2/n))` per output `k` -- cached per size for the same reason1748+/// [`dct_basis`]'s corresponding column, so a least-squares fit over the
1588-/// [`dct_basis`] is: computed from a `k`-dependent angle, so a call-time1749+/// whole column returns `g` without trusting any single output's rounding.
1589-/// `cos`/`sin` per output (`n` of them, every call) was measured as this1750+/// Cached per size, like every other table here.
1590-/// factorization's actual bottleneck, worse than the matmul it was meant to1751+fn forward_gain(n: usize) -> f64 {
1591-/// beat.
1592-fn dct_twist(n: usize) -> &'static [(f64, f64, f64)] {
1593 use std::sync::OnceLock;1752 use std::sync::OnceLock;
1594- static CACHE: OnceLock<[OnceLock<Vec<(f64, f64, f64)>>; 5]> = OnceLock::new();1753+ static CACHE: OnceLock<[OnceLock<f64>; 5]> = OnceLock::new();
1595 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));1754 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
1596- let idx = (n.trailing_zeros() as usize).saturating_sub(2);1755+ *cache[(n.trailing_zeros() as usize).saturating_sub(2)].get_or_init(|| {
1597- cache[idx].get_or_init(|| {1756+ // Large enough that the network's rounding is negligible against it,
1598- (0..n)1757+ // far below anything `FORWARD_RANGE` clamps.
1599- .map(|k| {1758+ const AMP: i32 = 1 << 14;
1600- let theta = std::f64::consts::PI * k as f64 / (2.0 * n as f64);1759+ let mut t = [0i32; 64];
1601- let alpha = if k == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 };1760+ t[0] = AMP;
1602- (theta.cos(), theta.sin(), alpha * (2.0 / n as f64).sqrt())1761+ forward_dct_fixed(&mut t, n.trailing_zeros(), FORWARD_RANGE);
1603- })1762+ let basis = dct_basis(n);
1604- .collect()1763+ let num: f64 = (0..n).map(|u| f64::from(t[u]) * basis[u * n]).sum();
1764+ let den: f64 = (0..n).map(|u| basis[u * n] * basis[u * n]).sum();
1765+ num / (f64::from(AMP) * den)
1605 })1766 })
1606 }1767 }
1607 1768
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 /// The forward transform (encoder side, spec-free): the transpose of what the1769 /// The forward transform (encoder side, spec-free): the transpose of what the
1632 /// decoder's inverse does, so that `inverse_transform_2d` of the result1770 /// decoder's inverse does, so that `inverse_transform_2d` of the result
1633 /// reproduces `residual`.1771 /// reproduces `residual`.
@@ -1640,36 +1778,84 @@ fn dct1d(x: &[f64], out: &mut [f64]) {
1640 /// fixed-point gain. It is deterministic, and its accuracy is measured1778 /// fixed-point gain. It is deterministic, and its accuracy is measured
1641 /// against the decoder's own inverse rather than asserted.1779 /// against the decoder's own inverse rather than asserted.
1642 pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> {1780 pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> {
1781+ let rows = forward_rows(residual, side);
1782+ let scale = forward_scale(side);
1783+ let mut out = vec![0.0f64; side * side];
1784+ let mut t = [0i32; 64];
1785+ for v in 0..side {
1786+ if !forward_column(&rows, side, v, &mut t) {
1787+ continue;
1788+ }
1789+ for u in 0..side {
1790+ out[u * side + v] = f64::from(t[u]) * scale;
1791+ }
1792+ }
1793+ out
1794+}
1795+
1796+/// The row pass, in fixed point: each of `side` residual rows through
1797+/// [`forward_dct_fixed`], at [`FORWARD_PRECISION_BITS`] extra precision and
1798+/// the network's own gain (both of which [`forward_scale`] divides back out).
1799+///
1800+/// The `Vec` is per call on purpose: holding it in a thread-local scratch, as
1801+/// the inverse transform's row pass does, was MEASURED +5.0% instructions on
1802+/// the sequence bench -- a fresh zeroed allocation costs less here than the
1803+/// `memset` reusing one needs plus the thread-local access, because the
1804+/// zeroing is what the all-zero-row skip below reads.
1805+fn forward_rows(residual: &[i32], side: usize) -> Vec<i32> {
1643 assert_eq!(1806 assert_eq!(
1644 residual.len(),1807 residual.len(),
1645 side * side,1808 side * side,
1646 "one residual sample per position"1809 "one residual sample per position"
1647 );1810 );
1648- let mut rows = vec![0.0f64; side * side];1811+ let log2 = side.trailing_zeros();
1649- let mut buf = [0.0f64; 64];1812+ let mut rows = vec![0i32; side * side];
1650- let mut line = [0.0f64; 64];1813+ let mut t = [0i32; 64];
1651 for i in 0..side {1814 for i in 0..side {
1652- for (j, &r) in residual[i * side..][..side].iter().enumerate() {1815+ let source = &residual[i * side..][..side];
1653- buf[j] = f64::from(r);1816+ // Zero in, zero out, and `rows` is already zero here -- the skip the
1654- }1817+ // decoder's column pass takes for the same reason.
1655- dct1d(&buf[..side], &mut line[..side]);1818+ if source.iter().all(|&r| r == 0) {
1656- rows[i * side..][..side].copy_from_slice(&line[..side]);1819+ continue;
1657- }
1658- let mut out = vec![0.0f64; side * side];
1659- for v in 0..side {
1660- for (i, c) in buf[..side].iter_mut().enumerate() {
1661- *c = rows[i * side + v];
1662 }1820 }
1663- dct1d(&buf[..side], &mut line[..side]);1821+ for (dst, &r) in t[..side].iter_mut().zip(source) {
1664- for (u, &t) in line[..side].iter().enumerate() {1822+ *dst = r << FORWARD_PRECISION_BITS;
1665- out[u * side + v] = t;
1666 }1823 }
1824+ forward_dct_fixed(&mut t, log2, FORWARD_RANGE);
1825+ rows[i * side..][..side].copy_from_slice(&t[..side]);
1667 }1826 }
1668- let scale = INVERSE_GAIN_RECIPROCAL;1827+ rows
1669- for v in &mut out {1828+}
1670- *v *= scale;1829+
1830+/// One column of [`forward_rows`]'s output through the network, into `t`;
1831+/// `false` when the column is all zero and `t` was left untouched.
1832+///
1833+/// One column at a time, and the caller consumes `t` before asking for the
1834+/// next: eight columns through the same `[i32; 8]` [`Lane`] the decoder's
1835+/// column pass uses was MEASURED SLOWER (+3.4% instructions on the sequence
1836+/// bench, and +2.3% for an in-place whole-buffer column pass). This encoder's
1837+/// transforms are mostly small -- a group of eight loses the per-column zero
1838+/// skip that a 4x4 or 8x8 residual keeps hitting, and the levels stop being
1839+/// formed while the column is still in registers.
1840+fn forward_column(rows: &[i32], side: usize, v: usize, t: &mut [i32; 64]) -> bool {
1841+ let mut any = 0i32;
1842+ for i in 0..side {
1843+ t[i] = rows[i * side + v];
1844+ any |= t[i];
1671 }1845 }
1672- out1846+ if any == 0 {
1847+ return false;
1848+ }
1849+ forward_dct_fixed(t, side.trailing_zeros(), FORWARD_RANGE);
1850+ true
1851+}
1852+
1853+/// What one fixed-point coefficient is worth on the `8 * orthonormal` scale
1854+/// the levels are formed on: both passes carry the network's gain, and the
1855+/// row pass carried the headroom shift too.
1856+fn forward_scale(side: usize) -> f64 {
1857+ let g = forward_gain(side);
1858+ INVERSE_GAIN_RECIPROCAL / (g * g * f64::from(1u32 << FORWARD_PRECISION_BITS))
1673 }1859 }
1674 1860
1675 /// The old direct `O(n^2)` matmul against [`build_dct_basis`], kept only as1861 /// The old direct `O(n^2)` matmul against [`build_dct_basis`], kept only as
@@ -1755,8 +1941,34 @@ pub fn forward_and_quantize(
1755 q_idx: i32,1941 q_idx: i32,
1756 deadzone: f64,1942 deadzone: f64,
1757 ) -> Vec<i32> {1943 ) -> Vec<i32> {
1758- let coeffs = forward_transform_2d(residual, side);1944+ // Fused: the levels are formed straight off the fixed-point coefficients,
1759- quantize(&coeffs, side, bit_depth, q_idx, deadzone)1945+ // so neither the `Vec<f64>` of coefficients nor the pass that reads it
1946+ // exists.
1947+ let rows = forward_rows(residual, side);
1948+ let scale = forward_scale(side);
1949+ let dc = scale / f64::from(crate::quant::dc_q(bit_depth, q_idx));
1950+ let ac = scale / f64::from(crate::quant::ac_q(bit_depth, q_idx));
1951+ // A 64-point transform carries its top-left 32x32 alone, so the other
1952+ // half's columns are not even transformed.
1953+ let coded = side.min(32);
1954+ let mut levels = vec![0i32; side * side];
1955+ let mut t = [0i32; 64];
1956+ for v in 0..coded {
1957+ if !forward_column(&rows, side, v, &mut t) {
1958+ continue;
1959+ }
1960+ for u in 0..coded {
1961+ let scaled = f64::from(t[u]) * if u == 0 && v == 0 { dc } else { ac };
1962+ let magnitude = scaled.abs() + deadzone;
1963+ let level = if magnitude < 1.0 {
1964+ 0
1965+ } else {
1966+ magnitude.floor().min(f64::from(i32::MAX)) as i32
1967+ };
1968+ levels[u * side + v] = if scaled < 0.0 { -level } else { level };
1969+ }
1970+ }
1971+ levels
1760 }1972 }
1761 1973
1762 #[cfg(test)]1974 #[cfg(test)]
@@ -1913,31 +2125,70 @@ mod tests {
1913 /// [`forward_transform_2d_naive`]'s direct matmul: same summation2125 /// [`forward_transform_2d_naive`]'s direct matmul: same summation
1914 /// reordered, so equal up to floating-point rounding, not bit-exact.2126 /// reordered, so equal up to floating-point rounding, not bit-exact.
1915 #[test]2127 #[test]
1916- fn fast_forward_matches_the_naive_matmul() {2128+ fn the_fixed_point_forward_matches_the_exact_matmul() {
1917 for &side in &[4usize, 8, 16, 32, 64] {2129 for &side in &[4usize, 8, 16, 32, 64] {
1918 for seed in [1u64, 2, 3] {2130 for seed in [1u64, 2, 3] {
1919 let residual = noise(side * side, seed * 1000 + side as u64);2131 let residual = noise(side * side, seed * 1000 + side as u64);
1920 let fast = forward_transform_2d(&residual, side);2132 let fast = forward_transform_2d(&residual, side);
1921 let naive = forward_transform_2d_naive(&residual, side);2133 let naive = forward_transform_2d_naive(&residual, side);
1922- for (i, (&f, &n)) in fast.iter().zip(&naive).enumerate() {2134+ let worst = fast
2135+ .iter()
2136+ .zip(&naive)
2137+ .map(|(f, n)| (f - n).abs())
2138+ .fold(0.0f64, f64::max);
2139+ let energy: f64 = naive.iter().map(|n| n * n).sum::<f64>().sqrt();
2140+ let err: f64 = fast
2141+ .iter()
2142+ .zip(&naive)
2143+ .map(|(f, n)| (f - n) * (f - n))
2144+ .sum::<f64>()
2145+ .sqrt();
2146+ // The network rounds at every butterfly, so it is not the
2147+ // matmul to the last bit -- it is the same transform to well
2148+ // inside one quantizer step. One unit here is an eighth of an
2149+ // orthonormal coefficient ([`INVERSE_GAIN_RECIPROCAL`]), and
2150+ // the finest step any level is formed on is `dc_q(8, 0) = 4`.
2151+ assert!(worst < 1.0, "{side}x{side} seed {seed}: worst {worst}");
2152+ assert!(
2153+ err < 1e-3 * energy,
2154+ "{side}x{side} seed {seed}: rmse {err} of energy {energy}"
2155+ );
2156+ }
2157+ }
2158+ }
2159+
2160+ /// The gain [`forward_transform_2d`] divides out is the network's own, and
2161+ /// it is ONE number per size -- if the network's gain varied by output the
2162+ /// single scale would tilt the spectrum. Pinned per size against the
2163+ /// orthonormal basis it is measured from.
2164+ #[test]
2165+ fn the_forward_network_has_one_uniform_gain() {
2166+ for &n in &[4usize, 8, 16, 32, 64] {
2167+ let g = forward_gain(n);
2168+ assert!(
2169+ (g - (n as f64 / 2.0).sqrt()).abs() < 1e-3,
2170+ "{n}-point gain {g}"
2171+ );
2172+ let basis = dct_basis(n);
2173+ for i in 0..n {
2174+ let mut t = [0i32; 64];
2175+ t[i] = 1 << 14;
2176+ forward_dct_fixed(&mut t, n.trailing_zeros(), FORWARD_RANGE);
2177+ for u in 0..n {
2178+ let want = g * f64::from(1 << 14) * basis[u * n + i];
2179+ // A thousandth of the impulse's own amplitude: the
2180+ // network's rounding accumulates over its stages, and
2181+ // what is pinned here is that the SHAPE is the basis.
1923 assert!(2182 assert!(
1924- (f - n).abs() < 1e-6 * n.abs().max(1.0),2183+ (f64::from(t[u]) - want).abs() < 1e-3 * g * f64::from(1 << 14),
1925- "{side}x{side} seed {seed} coefficient {i}: fast {f} vs naive {n}"2184+ "{n}-point impulse {i} output {u}: {} vs {want}",
2185+ t[u]
1926 );2186 );
1927 }2187 }
1928 }2188 }
1929 }2189 }
1930 }2190 }
1931 2191
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 #[test]2192 #[test]
1942 fn the_inverse_network_is_an_orthonormal_dct_over_eight() {2193 fn the_inverse_network_is_an_orthonormal_dct_over_eight() {
1943 for &side in &[4usize, 8, 16, 32, 64] {2194 for &side in &[4usize, 8, 16, 32, 64] {