Skip to main content

log_fft/paper/grid/
toeplitz.rs

1//! Triangular Toeplitz actions (Lemma up:toeplitz, layers.tex).
2//!
3//! A lower triangular Toeplitz matrix of side `a` with first column `h` is
4//! multiplication by `h(X)` in `K[X]/(X^a)`. The paper realises it
5//! *in place* (scratch registers come back unchanged) using only:
6//!
7//! * shear additions `y ← y ± A x` with `A` Toeplitz. Each is one cyclic
8//!   convolution of length `b ≥ 2a`, computed by `F_b = V_b(u)`.
9//! * diagonal scalings, including `D_u = diag(1, u, …, u^{a−1})`.
10//! * a signed interchange.
11//!
12//! Construction: normalise `h(0) = 1` and solve `f(uX) = h(X) f(X) mod X^a`
13//! with `f(0) = 1`. Let `S` be multiplication by `f`. Then
14//! `T = D_u S D_u^{-1} S^{-1}`.
15//! `B = diag(S, S^{-1}) = [[I,S],[0,I]]·[[I,0],[−S^{-1},I]]·[[I,S],[0,I]]·[[0,−I],[I,0]]`,
16//! and `(D_u ⊕ I) B (D_u^{-1} ⊕ I) B^{-1} = T ⊕ I`.
17
18use super::smooth::SmoothDft;
19use crate::field::Fp;
20
21/// `(f · x) mod X^a`, computed directly in `O(a²)`. Used as the reference.
22pub fn mul_trunc_direct(f: &[Fp], x: &[Fp]) -> Vec<Fp> {
23    let a = x.len();
24    let mut y = vec![Fp::ZERO; a];
25    for i in 0..a {
26        for k in 0..=i.min(f.len().saturating_sub(1)) {
27            y[i] += f[k] * x[i - k];
28        }
29    }
30    y
31}
32
33/// Inverse power series `f^{-1} mod X^a`. Needs `f(0) ≠ 0`.
34pub fn series_inv(f: &[Fp], a: usize) -> Vec<Fp> {
35    let inv0 = f[0].inv();
36    let mut g = vec![Fp::ZERO; a];
37    g[0] = inv0;
38    for i in 1..a {
39        let mut s = Fp::ZERO;
40        for k in 1..=i.min(f.len() - 1) {
41            s += f[k] * g[i - k];
42        }
43        g[i] = -s * inv0;
44    }
45    g
46}
47
48/// Convolution engine: Toeplitz shears `y ← y + (f·x mod X^a)` via `F_b`.
49#[derive(Clone, Debug)]
50pub struct ShearEngine {
51    pub a: usize,
52    pub dft: SmoothDft,
53    /// Number of length-`b` transforms performed (forward and inverse).
54    pub transforms: std::cell::Cell<u64>,
55}
56
57impl ShearEngine {
58    pub fn new(a: usize, b: usize) -> Self {
59        assert!(b >= 2 * a, "need b ≥ 2a (got a={a}, b={b})");
60        ShearEngine { a, dft: SmoothDft::new(b), transforms: Default::default() }
61    }
62
63    /// `(f·x) mod X^a`, computed through one cyclic convolution of length `b`.
64    pub fn mul_trunc(&self, f: &[Fp], x: &[Fp]) -> Vec<Fp> {
65        let (a, b) = (self.a, self.dft.b);
66        let mut fp = vec![Fp::ZERO; b];
67        let mut xp = vec![Fp::ZERO; b];
68        fp[..a.min(f.len())].copy_from_slice(&f[..a.min(f.len())]);
69        xp[..a].copy_from_slice(x);
70        self.transforms.set(self.transforms.get() + 3);
71        self.dft.cyclic_convolve(&fp, &xp)[..a].to_vec()
72    }
73
74    /// Shear `y ← y + sign·(f·x mod X^a)`.
75    fn shear(&self, y: &mut [Fp], f: &[Fp], x: &[Fp], sign: Fp) {
76        let t = self.mul_trunc(f, x);
77        for (yi, ti) in y.iter_mut().zip(t) {
78            *yi += sign * ti;
79        }
80    }
81}
82
83/// Coefficients prepared once per Toeplitz factor ("coefficient preparation").
84#[derive(Clone, Debug)]
85pub struct ToeplitzPlan {
86    pub a: usize,
87    /// `h(0)`, factored out so that the normalised `h` has constant term 1.
88    pub scale: Fp,
89    /// `f` with `f(uX) = h(X) f(X) mod X^a`, `f(0) = 1`.
90    pub f: Vec<Fp>,
91    /// `f^{-1} mod X^a`.
92    pub f_inv: Vec<Fp>,
93    /// `u^i` for `i < a`.
94    pub du: Vec<Fp>,
95}
96
97impl ToeplitzPlan {
98    /// `h` is the first column (`h.len() ≤ a`, `h(0) ≠ 0`). `u` is the root of `F_b`.
99    pub fn new(h: &[Fp], a: usize, u: Fp) -> Self {
100        assert!(h[0] != Fp::ZERO, "triangular Toeplitz must be invertible");
101        let scale = h[0];
102        let inv = scale.inv();
103        let hn: Vec<Fp> = (0..a).map(|i| h.get(i).copied().unwrap_or(Fp::ZERO) * inv).collect();
104        let du: Vec<Fp> = (0..a).map(|i| u.pow(i as u64)).collect();
105        let mut f = vec![Fp::ZERO; a];
106        f[0] = Fp::ONE;
107        for i in 1..a {
108            // u^i f_i = Σ_{k=0}^{i} h_k f_{i−k}  ⇒  f_i (u^i − 1) = Σ_{k≥1} h_k f_{i−k}
109            let mut s = Fp::ZERO;
110            for k in 1..=i {
111                s += hn[k] * f[i - k];
112            }
113            let den = du[i] - Fp::ONE;
114            assert!(den != Fp::ZERO, "u^i = 1 for some 1 ≤ i < a; need ord(u) ≥ a");
115            f[i] = s * den.inv();
116        }
117        let f_inv = series_inv(&f, a);
118        ToeplitzPlan { a, scale, f, f_inv, du }
119    }
120}
121
122/// `B = diag(S, S^{-1})` on registers `(x, y)`, using three shears and a signed interchange.
123fn apply_b(eng: &ShearEngine, plan: &ToeplitzPlan, x: &mut Vec<Fp>, y: &mut Vec<Fp>) {
124    let one = Fp::ONE;
125    // Right to left: [[0,−I],[I,0]] : (x, y) → (−y, x)
126    let nx: Vec<Fp> = y.iter().map(|v| -*v).collect();
127    *y = std::mem::replace(x, nx);
128    eng.shear(x, &plan.f, y, one); //      x ← x + S y
129    eng.shear(y, &plan.f_inv, x, -one); // y ← y − S^{-1} x
130    eng.shear(x, &plan.f, y, one); //      x ← x + S y
131}
132
133/// `B^{-1} = diag(S^{-1}, S)`: undo the factors of [`apply_b`] in reverse order.
134fn apply_b_inv(eng: &ShearEngine, plan: &ToeplitzPlan, x: &mut Vec<Fp>, y: &mut Vec<Fp>) {
135    let one = Fp::ONE;
136    eng.shear(x, &plan.f, y, -one);
137    eng.shear(y, &plan.f_inv, x, one);
138    eng.shear(x, &plan.f, y, -one);
139    // inverse of (x, y) → (−y, x) is (x, y) → (y, −x)
140    let ny: Vec<Fp> = x.iter().map(|v| -*v).collect();
141    *x = std::mem::replace(y, ny);
142}
143
144/// Apply the lower triangular Toeplitz `T` with first column `h` to `x`,
145/// in place, as in the paper. `scratch` must come back unchanged, and the
146/// function returns `T x`. Arbitrary scratch contents are allowed, because
147/// the construction restores them.
148pub fn lower_toeplitz_paper(
149    eng: &ShearEngine,
150    plan: &ToeplitzPlan,
151    x: &[Fp],
152    scratch: &mut Vec<Fp>,
153) -> Vec<Fp> {
154    let mut r1 = x.to_vec();
155    // (D_u ⊕ I) B (D_u^{-1} ⊕ I) B^{-1}, applied right to left.
156    apply_b_inv(eng, plan, &mut r1, scratch);
157    let du_inv: Vec<Fp> = plan.du.iter().map(|v| v.inv()).collect();
158    for (v, d) in r1.iter_mut().zip(&du_inv) {
159        *v *= *d;
160    }
161    apply_b(eng, plan, &mut r1, scratch);
162    for (v, d) in r1.iter_mut().zip(&plan.du) {
163        *v *= *d;
164    }
165    // Restore h(0).
166    for v in &mut r1 {
167        *v *= plan.scale;
168    }
169    r1
170}
171
172/// Upper triangular Toeplitz `U = R L R` (`R` = reversal), with `L` having first column `h`.
173pub fn upper_toeplitz_paper(
174    eng: &ShearEngine,
175    plan: &ToeplitzPlan,
176    x: &[Fp],
177    scratch: &mut Vec<Fp>,
178) -> Vec<Fp> {
179    let rx: Vec<Fp> = x.iter().rev().copied().collect();
180    let mut y = lower_toeplitz_paper(eng, plan, &rx, scratch);
181    y.reverse();
182    y
183}
184
185/// Reference: upper triangular Toeplitz with first row `h`.
186pub fn upper_toeplitz_direct(h: &[Fp], x: &[Fp]) -> Vec<Fp> {
187    let rx: Vec<Fp> = x.iter().rev().copied().collect();
188    let mut y = mul_trunc_direct(h, &rx);
189    y.reverse();
190    y
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate::paper::grid::smooth::choose_b;
197
198    fn seq(a: usize, s: u64) -> Vec<Fp> {
199        (0..a as u64).map(|i| Fp::new(i * i * s + 3 * i + s)).collect()
200    }
201
202    #[test]
203    fn conv_engine_matches_direct() {
204        for a in [1, 2, 5, 17, 40, 100] {
205            let eng = ShearEngine::new(a, choose_b(a));
206            let (f, x) = (seq(a, 7), seq(a, 11));
207            assert_eq!(eng.mul_trunc(&f, &x), mul_trunc_direct(&f, &x));
208        }
209    }
210
211    #[test]
212    fn paper_construction_exact_and_restores_scratch() {
213        for a in [1, 2, 3, 8, 17, 64, 129] {
214            let eng = ShearEngine::new(a, choose_b(a));
215            let h = seq(a, 5);
216            let plan = ToeplitzPlan::new(&h, a, eng.dft.root);
217            // f(uX) = h(X) f(X) / h(0)
218            let fu: Vec<Fp> = plan.f.iter().zip(&plan.du).map(|(c, d)| *c * *d).collect();
219            let hn: Vec<Fp> = h.iter().map(|v| *v * plan.scale.inv()).collect();
220            assert_eq!(fu, mul_trunc_direct(&hn, &plan.f));
221
222            let x = seq(a, 13);
223            let original_scratch = seq(a, 99);
224            let mut scratch = original_scratch.clone();
225            let y = lower_toeplitz_paper(&eng, &plan, &x, &mut scratch);
226            assert_eq!(y, mul_trunc_direct(&h, &x), "a={a}");
227            assert_eq!(scratch, original_scratch, "scratch not restored, a={a}");
228
229            let yu = upper_toeplitz_paper(&eng, &plan, &x, &mut scratch);
230            assert_eq!(yu, upper_toeplitz_direct(&h, &x));
231            assert_eq!(scratch, original_scratch);
232        }
233    }
234}