p3_dft/traits.rs
1use alloc::vec::Vec;
2
3use p3_field::{BasedVectorSpace, TwoAdicField};
4use p3_matrix::Matrix;
5use p3_matrix::bitrev::BitReversibleMatrix;
6use p3_matrix::dense::{RowMajorMatrix, RowMajorMatrixViewMut};
7use p3_matrix::util::swap_rows;
8
9use crate::util::{coset_shift_cols, divide_by_height};
10
11/// This trait gives an interface for computing discrete fourier transforms (DFT's) and their inverses over
12/// cosets of two-adic subgroups of a field `F`. It also contains combined methods which allow you to take the
13/// evaluation vector of a polynomial on a coset `gH` and extend it to a coset `g'K` for some possibly larger
14/// subgroup `K` and different shift `g'`.
15///
16/// It supports polynomials with evaluations/coefficients valued in either `F` or `A` where `A`
17/// is a vector space over `F` with specified basis. This latter case makes use of the fact that the DFT
18/// is linear meaning we can decompose an `A` valued polynomial into a collection of `F` valued polynomials,
19/// apply the DFT to each of them, and then recombine. When `A` is an extension field, this approach
20/// is much faster than using a `TwoAdicSubgroupDft<A>` implementation directly.
21///
22/// Most implementations of this trait are optimised for the batch case where the input
23/// is a matrix and we is a want to perform the same operation on every column. Note that
24/// depending on the width and height of the matrix (as well as whether or not you are using the
25/// parallel feature) different implementation may be faster. Hence depending on your use case
26/// you may want to be using `Radix2Dit`, `Radix2DitParallel`, `Radix2DFTSmallBatch` or
27/// `Radix2Bowers` (or, for `MontyField31` fields, `p3_monty_31::RecursiveDft`).
28pub trait TwoAdicSubgroupDft<F: TwoAdicField>: Clone + Default {
29 /// The matrix type used to store the result of a batched DFT operation.
30 ///
31 /// This type represents a matrix of field elements, used to hold the evaluations
32 /// of multiple polynomials over a two-adic subgroup or its coset.
33 /// It is always owned and supports efficient access and transformation
34 /// patterns used in FFT-based algorithms.
35 ///
36 /// Most implementations use `RowMajorMatrix<F>` or a wrapper like
37 /// `BitReversedMatrixView<RowMajorMatrix<F>>` to allow in-place bit-reversed access.
38 type Evaluations: BitReversibleMatrix<F> + 'static;
39
40 /// Compute the discrete Fourier transform (DFT) of `vec`.
41 ///
42 /// #### Mathematical Description
43 ///
44 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
45 /// Treating `vec` as coefficients of a polynomial, compute the evaluations
46 /// of that polynomial on the subgroup `H`.
47 fn dft(&self, vec: Vec<F>) -> Vec<F> {
48 self.dft_batch(RowMajorMatrix::new_col(vec))
49 .to_row_major_matrix()
50 .values
51 }
52
53 /// Compute the discrete Fourier transform (DFT) of each column in `mat`.
54 /// This is the only method an implementer needs to define, all other
55 /// methods can be derived from this one.
56 ///
57 /// #### Mathematical Description
58 ///
59 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
60 /// Treating each column of `mat` as the coefficients of a polynomial, compute the
61 /// evaluations of those polynomials on the subgroup `H`.
62 fn dft_batch(&self, mat: RowMajorMatrix<F>) -> Self::Evaluations;
63
64 /// Compute the "coset DFT" of `vec`.
65 ///
66 /// #### Mathematical Description
67 ///
68 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
69 /// Treating `vec` as coefficients of a polynomial, compute the evaluations
70 /// of that polynomial on the coset `shift * H`.
71 fn coset_dft(&self, vec: Vec<F>, shift: F) -> Vec<F> {
72 self.coset_dft_batch(RowMajorMatrix::new_col(vec), shift)
73 .to_row_major_matrix()
74 .values
75 }
76
77 /// Compute the "coset DFT" of each column in `mat`.
78 ///
79 /// #### Mathematical Description
80 ///
81 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
82 /// Treating each column of `mat` as the coefficients of a polynomial, compute the
83 /// evaluations of those polynomials on the coset `shift * H`.
84 fn coset_dft_batch(&self, mut mat: RowMajorMatrix<F>, shift: F) -> Self::Evaluations {
85 // Observe that
86 // y_i = \sum_j c_j (s g^i)^j
87 // = \sum_j (c_j s^j) (g^i)^j
88 // which has the structure of an ordinary DFT, except each coefficient `c_j` is first replaced
89 // by `c_j s^j`.
90 coset_shift_cols(&mut mat, shift);
91 self.dft_batch(mat)
92 }
93
94 /// Compute the inverse DFT of `vec`.
95 ///
96 /// #### Mathematical Description
97 ///
98 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
99 /// Treating `vec` as the evaluations of a polynomial on `H`, compute the
100 /// coefficients of that polynomial.
101 fn idft(&self, vec: Vec<F>) -> Vec<F> {
102 self.idft_batch(RowMajorMatrix::new_col(vec)).values
103 }
104
105 /// Compute the inverse DFT of each column in `mat`.
106 ///
107 /// #### Mathematical Description
108 ///
109 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
110 /// Treating each column of `mat` as the evaluations of a polynomial on `H`,
111 /// compute the coefficients of those polynomials.
112 fn idft_batch(&self, mat: RowMajorMatrix<F>) -> RowMajorMatrix<F> {
113 let mut dft = self.dft_batch(mat).to_row_major_matrix();
114 let h = dft.height();
115
116 divide_by_height(&mut dft);
117
118 for row in 1..h / 2 {
119 swap_rows(&mut dft, row, h - row);
120 }
121
122 dft
123 }
124
125 /// Compute the "coset iDFT" of `vec`. This is the inverse operation of "coset DFT".
126 ///
127 /// #### Mathematical Description
128 ///
129 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
130 /// Treating `vec` as the evaluations of a polynomial on `shift * H`,
131 /// compute the coefficients of this polynomial.
132 fn coset_idft(&self, vec: Vec<F>, shift: F) -> Vec<F> {
133 self.coset_idft_batch(RowMajorMatrix::new_col(vec), shift)
134 .values
135 }
136
137 /// Compute the "coset iDFT" of each column in `mat`. This is the inverse operation
138 /// of "coset DFT".
139 ///
140 /// #### Mathematical Description
141 ///
142 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
143 /// Treating each column of `mat` as the evaluations of a polynomial on `shift * H`,
144 /// compute the coefficients of those polynomials.
145 fn coset_idft_batch(&self, mut mat: RowMajorMatrix<F>, shift: F) -> RowMajorMatrix<F> {
146 // Let `f(x)` denote the polynomial we want. Then, if we reinterpret the columns
147 // as being over the subgroup `H`, this is equivalent to switching our polynomial
148 // to `g(x) = f(sx)`.
149 // The output of the iDFT is the coefficients of `g` so to get the coefficients of
150 // `f` we need to scale the `i`'th coefficient by `s^{-i}`.
151 mat = self.idft_batch(mat);
152 coset_shift_cols(&mut mat, shift.inverse());
153 mat
154 }
155
156 /// Compute the low-degree extension of `vec` onto a larger subgroup.
157 ///
158 /// #### Mathematical Description
159 ///
160 /// Let `H, K` denote the unique multiplicative subgroups of order `vec.len()`
161 /// and `vec.len() << added_bits`, respectively.
162 /// Treating `vec` as the evaluations of a polynomial on the subgroup `H`,
163 /// compute the evaluations of that polynomial on the subgroup `K`.
164 ///
165 /// There is another way to interpret this transformation which gives a larger
166 /// use case. We can also view it as treating columns of `mat` as evaluations
167 /// over a coset `gH` and then computing the evaluations of those polynomials
168 /// on the coset `gK`.
169 fn lde(&self, vec: Vec<F>, added_bits: usize) -> Vec<F> {
170 self.lde_batch(RowMajorMatrix::new_col(vec), added_bits)
171 .to_row_major_matrix()
172 .values
173 }
174
175 /// Compute the low-degree extension of each column in `mat` onto a larger subgroup.
176 ///
177 /// #### Mathematical Description
178 ///
179 /// Let `H, K` denote the unique multiplicative subgroups of order `mat.height()`
180 /// and `mat.height() << added_bits`, respectively.
181 /// Treating each column of `mat` as the evaluations of a polynomial on the subgroup `H`,
182 /// compute the evaluations of those polynomials on the subgroup `K`.
183 ///
184 /// There is another way to interpret this transformation which gives a larger
185 /// use case. We can also view it as treating columns of `mat` as evaluations
186 /// over a coset `gH` and then computing the evaluations of those polynomials
187 /// on the coset `gK`.
188 fn lde_batch(&self, mat: RowMajorMatrix<F>, added_bits: usize) -> Self::Evaluations {
189 // This is a better default as several implementations have a custom implementation
190 // of `coset_lde_batch` and often the fact that the shift is `ONE` won't give any
191 // performance improvements anyway.
192 self.coset_lde_batch(mat, added_bits, F::ONE)
193 }
194
195 /// Compute the low-degree extension of of `vec` onto a coset of a larger subgroup.
196 ///
197 /// #### Mathematical Description
198 ///
199 /// Let `H, K` denote the unique multiplicative subgroups of order `vec.len()`
200 /// and `vec.len() << added_bits`, respectively.
201 /// Treating `vec` as the evaluations of a polynomial on the subgroup `H`,
202 /// compute the evaluations of that polynomial on the coset `shift * K`.
203 ///
204 /// There is another way to interpret this transformation which gives a larger
205 /// use case. We can also view it as treating `vec` as the evaluations of a polynomial
206 /// over a coset `gH` and then computing the evaluations of that polynomial
207 /// on the coset `g'K` where `g' = g * shift`.
208 fn coset_lde(&self, vec: Vec<F>, added_bits: usize, shift: F) -> Vec<F> {
209 self.coset_lde_batch(RowMajorMatrix::new_col(vec), added_bits, shift)
210 .to_row_major_matrix()
211 .values
212 }
213
214 /// Compute the low-degree extension of each column in `mat` onto a coset of a larger subgroup.
215 ///
216 /// #### Mathematical Description
217 ///
218 /// Let `H, K` denote the unique multiplicative subgroups of order `mat.height()`
219 /// and `mat.height() << added_bits`, respectively.
220 /// Treating each column of `mat` as the evaluations of a polynomial on the subgroup `H`,
221 /// compute the evaluations of those polynomials on the coset `shift * K`.
222 ///
223 /// There is another way to interpret this transformation which gives a larger
224 /// use case. We can also view it as treating columns of `mat` as evaluations
225 /// over a coset `gH` and then computing the evaluations of those polynomials
226 /// on the coset `g'K` where `g' = g * shift`.
227 fn coset_lde_batch(
228 &self,
229 mat: RowMajorMatrix<F>,
230 added_bits: usize,
231 shift: F,
232 ) -> Self::Evaluations {
233 self.coset_lde_batch_with_transform(mat, added_bits, shift, |_, _| {})
234 }
235
236 /// Like [`coset_lde_batch`](Self::coset_lde_batch), but with a closure
237 /// invoked on the intermediate coefficient buffer between the iDFT and
238 /// the forward DFT phases. The [`Layout`] argument tells the closure
239 /// whether the buffer is in natural or bit-reversed memory order, so the
240 /// closure can translate memory positions to natural-order coefficient
241 /// indices when relevant.
242 fn coset_lde_batch_with_transform<T>(
243 &self,
244 mat: RowMajorMatrix<F>,
245 added_bits: usize,
246 shift: F,
247 transform: T,
248 ) -> Self::Evaluations
249 where
250 T: FnOnce(&mut RowMajorMatrixViewMut<'_, F>, Layout),
251 {
252 let mut coeffs = self.idft_batch(mat);
253 transform(&mut coeffs.as_view_mut(), Layout::Natural);
254 // PANICS: possible panic if the new resized length overflows
255 let scale = 1usize.checked_shl(added_bits.try_into().unwrap()).unwrap();
256 let new_len = coeffs.values.len().checked_mul(scale).unwrap();
257 coeffs.values.resize(new_len, F::ZERO);
258 self.coset_dft_batch(coeffs, shift)
259 }
260
261 /// Compute the discrete Fourier transform (DFT) of `vec`.
262 ///
263 /// #### Mathematical Description
264 ///
265 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
266 /// Treating `vec` as coefficients of a polynomial, compute the evaluations
267 /// of that polynomial on the subgroup `H`.
268 fn dft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(&self, vec: Vec<V>) -> Vec<V> {
269 self.dft_algebra_batch(RowMajorMatrix::new_col(vec)).values
270 }
271
272 /// Compute the discrete Fourier transform (DFT) of each column in `mat`.
273 ///
274 /// #### Mathematical Description
275 ///
276 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
277 /// Treating each column of `mat` as the coefficients of a polynomial, compute the
278 /// evaluations of those polynomials on the subgroup `H`.
279 fn dft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
280 &self,
281 mat: RowMajorMatrix<V>,
282 ) -> RowMajorMatrix<V> {
283 let init_width = mat.width();
284 let base_mat =
285 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
286 let base_dft_output = self.dft_batch(base_mat).to_row_major_matrix();
287 RowMajorMatrix::new(
288 V::reconstitute_from_base(base_dft_output.values),
289 init_width,
290 )
291 }
292
293 /// Compute the "coset DFT" of `vec`.
294 ///
295 /// #### Mathematical Description
296 ///
297 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
298 /// Treating `vec` as coefficients of a polynomial, compute the evaluations
299 /// of that polynomial on the coset `shift * H`.
300 fn coset_dft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
301 &self,
302 vec: Vec<V>,
303 shift: F,
304 ) -> Vec<V> {
305 self.coset_dft_algebra_batch(RowMajorMatrix::new_col(vec), shift)
306 .to_row_major_matrix()
307 .values
308 }
309
310 /// Compute the "coset DFT" of each column in `mat`.
311 ///
312 /// #### Mathematical Description
313 ///
314 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
315 /// Treating each column of `mat` as the coefficients of a polynomial, compute the
316 /// evaluations of those polynomials on the coset `shift * H`.
317 fn coset_dft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
318 &self,
319 mat: RowMajorMatrix<V>,
320 shift: F,
321 ) -> RowMajorMatrix<V> {
322 let init_width = mat.width();
323 let base_mat =
324 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
325 let base_dft_output = self.coset_dft_batch(base_mat, shift).to_row_major_matrix();
326 RowMajorMatrix::new(
327 V::reconstitute_from_base(base_dft_output.values),
328 init_width,
329 )
330 }
331
332 /// Compute the inverse DFT of `vec`.
333 ///
334 /// #### Mathematical Description
335 ///
336 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
337 /// Treating `vec` as the evaluations of a polynomial on `H`, compute the
338 /// coefficients of that polynomial.
339 fn idft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(&self, vec: Vec<V>) -> Vec<V> {
340 self.idft_algebra_batch(RowMajorMatrix::new_col(vec)).values
341 }
342
343 /// Compute the inverse DFT of each column in `mat`.
344 ///
345 /// #### Mathematical Description
346 ///
347 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
348 /// Treating each column of `mat` as the evaluations of a polynomial on `H`,
349 /// compute the coefficients of those polynomials.
350 fn idft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
351 &self,
352 mat: RowMajorMatrix<V>,
353 ) -> RowMajorMatrix<V> {
354 let init_width = mat.width();
355 let base_mat =
356 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
357 let base_dft_output = self.idft_batch(base_mat);
358 RowMajorMatrix::new(
359 V::reconstitute_from_base(base_dft_output.values),
360 init_width,
361 )
362 }
363
364 /// Compute the "coset iDFT" of `vec`. This is the inverse operation of "coset DFT".
365 ///
366 /// #### Mathematical Description
367 ///
368 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
369 /// Treating `vec` as the evaluations of a polynomial on `shift * H`,
370 /// compute the coefficients of this polynomial.
371 fn coset_idft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
372 &self,
373 vec: Vec<V>,
374 shift: F,
375 ) -> Vec<V> {
376 self.coset_idft_algebra_batch(RowMajorMatrix::new_col(vec), shift)
377 .values
378 }
379
380 /// Compute the "coset iDFT" of each column in `mat`. This is the inverse operation
381 /// of "coset DFT".
382 ///
383 /// #### Mathematical Description
384 ///
385 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
386 /// Treating each column of `mat` as the evaluations of a polynomial on `shift * H`,
387 /// compute the coefficients of those polynomials.
388 fn coset_idft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
389 &self,
390 mat: RowMajorMatrix<V>,
391 shift: F,
392 ) -> RowMajorMatrix<V> {
393 let init_width = mat.width();
394 let base_mat =
395 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
396 let base_dft_output = self.coset_idft_batch(base_mat, shift);
397 RowMajorMatrix::new(
398 V::reconstitute_from_base(base_dft_output.values),
399 init_width,
400 )
401 }
402
403 /// Compute the low-degree extension of `vec` onto a larger subgroup.
404 ///
405 /// #### Mathematical Description
406 ///
407 /// Let `H, K` denote the unique multiplicative subgroups of order `vec.len()`
408 /// and `vec.len() << added_bits`, respectively.
409 /// Treating `vec` as the evaluations of a polynomial on the subgroup `H`,
410 /// compute the evaluations of that polynomial on the subgroup `K`.
411 ///
412 /// There is another way to interpret this transformation which gives a larger
413 /// use case. We can also view it as treating columns of `mat` as evaluations
414 /// over a coset `gH` and then computing the evaluations of those polynomials
415 /// on the coset `gK`.
416 fn lde_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
417 &self,
418 vec: Vec<V>,
419 added_bits: usize,
420 ) -> Vec<V> {
421 self.lde_algebra_batch(RowMajorMatrix::new_col(vec), added_bits)
422 .to_row_major_matrix()
423 .values
424 }
425
426 /// Compute the low-degree extension of each column in `mat` onto a larger subgroup.
427 ///
428 /// #### Mathematical Description
429 ///
430 /// Let `H, K` denote the unique multiplicative subgroups of order `mat.height()`
431 /// and `mat.height() << added_bits`, respectively.
432 /// Treating each column of `mat` as the evaluations of a polynomial on the subgroup `H`,
433 /// compute the evaluations of those polynomials on the subgroup `K`.
434 ///
435 /// There is another way to interpret this transformation which gives a larger
436 /// use case. We can also view it as treating columns of `mat` as evaluations
437 /// over a coset `gH` and then computing the evaluations of those polynomials
438 /// on the coset `gK`.
439 fn lde_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
440 &self,
441 mat: RowMajorMatrix<V>,
442 added_bits: usize,
443 ) -> RowMajorMatrix<V> {
444 let init_width = mat.width();
445 let base_mat =
446 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
447 let base_dft_output = self.lde_batch(base_mat, added_bits).to_row_major_matrix();
448 RowMajorMatrix::new(
449 V::reconstitute_from_base(base_dft_output.values),
450 init_width,
451 )
452 }
453
454 /// Compute the low-degree extension of of `vec` onto a coset of a larger subgroup.
455 ///
456 /// #### Mathematical Description
457 ///
458 /// Let `H, K` denote the unique multiplicative subgroups of order `vec.len()`
459 /// and `vec.len() << added_bits`, respectively.
460 /// Treating `vec` as the evaluations of a polynomial on the subgroup `H`,
461 /// compute the evaluations of that polynomial on the coset `shift * K`.
462 ///
463 /// There is another way to interpret this transformation which gives a larger
464 /// use case. We can also view it as treating `vec` as the evaluations of a polynomial
465 /// over a coset `gH` and then computing the evaluations of that polynomial
466 /// on the coset `g'K` where `g' = g * shift`.
467 fn coset_lde_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
468 &self,
469 vec: Vec<V>,
470 added_bits: usize,
471 shift: F,
472 ) -> Vec<V> {
473 self.coset_lde_algebra_batch(RowMajorMatrix::new_col(vec), added_bits, shift)
474 .to_row_major_matrix()
475 .values
476 }
477
478 /// Compute the low-degree extension of each column in `mat` onto a coset of a larger subgroup.
479 ///
480 /// #### Mathematical Description
481 ///
482 /// Let `H, K` denote the unique multiplicative subgroups of order `mat.height()`
483 /// and `mat.height() << added_bits`, respectively.
484 /// Treating each column of `mat` as the evaluations of a polynomial on the subgroup `H`,
485 /// compute the evaluations of those polynomials on the coset `shift * K`.
486 ///
487 /// There is another way to interpret this transformation which gives a larger
488 /// use case. We can also view it as treating columns of `mat` as evaluations
489 /// over a coset `gH` and then computing the evaluations of those polynomials
490 /// on the coset `g'K` where `g' = g * shift`.
491 fn coset_lde_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
492 &self,
493 mat: RowMajorMatrix<V>,
494 added_bits: usize,
495 shift: F,
496 ) -> RowMajorMatrix<V> {
497 let init_width = mat.width();
498 let base_mat =
499 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
500 let base_dft_output = self
501 .coset_lde_batch(base_mat, added_bits, shift)
502 .to_row_major_matrix();
503 RowMajorMatrix::new(
504 V::reconstitute_from_base(base_dft_output.values),
505 init_width,
506 )
507 }
508}
509
510/// Memory layout of the coefficient buffer passed to a transform closure in
511/// [`TwoAdicSubgroupDft::coset_lde_batch_with_transform`].
512#[derive(Copy, Clone, Debug, PartialEq, Eq)]
513pub enum Layout {
514 /// Memory row `m` corresponds to natural-order index `m`.
515 Natural,
516 /// Memory row `m` corresponds to natural-order index
517 /// `reverse_bits_len(m, log2_strict_usize(buf.height()))`.
518 BitReversed,
519}