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 coeffs.values.resize(
256 coeffs
257 .values
258 .len()
259 .checked_shl(added_bits.try_into().unwrap())
260 .unwrap(),
261 F::ZERO,
262 );
263 self.coset_dft_batch(coeffs, shift)
264 }
265
266 /// Compute the discrete Fourier transform (DFT) of `vec`.
267 ///
268 /// #### Mathematical Description
269 ///
270 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
271 /// Treating `vec` as coefficients of a polynomial, compute the evaluations
272 /// of that polynomial on the subgroup `H`.
273 fn dft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(&self, vec: Vec<V>) -> Vec<V> {
274 self.dft_algebra_batch(RowMajorMatrix::new_col(vec)).values
275 }
276
277 /// Compute the discrete Fourier transform (DFT) of each column in `mat`.
278 ///
279 /// #### Mathematical Description
280 ///
281 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
282 /// Treating each column of `mat` as the coefficients of a polynomial, compute the
283 /// evaluations of those polynomials on the subgroup `H`.
284 fn dft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
285 &self,
286 mat: RowMajorMatrix<V>,
287 ) -> RowMajorMatrix<V> {
288 let init_width = mat.width();
289 let base_mat =
290 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
291 let base_dft_output = self.dft_batch(base_mat).to_row_major_matrix();
292 RowMajorMatrix::new(
293 V::reconstitute_from_base(base_dft_output.values),
294 init_width,
295 )
296 }
297
298 /// Compute the "coset DFT" of `vec`.
299 ///
300 /// #### Mathematical Description
301 ///
302 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
303 /// Treating `vec` as coefficients of a polynomial, compute the evaluations
304 /// of that polynomial on the coset `shift * H`.
305 fn coset_dft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
306 &self,
307 vec: Vec<V>,
308 shift: F,
309 ) -> Vec<V> {
310 self.coset_dft_algebra_batch(RowMajorMatrix::new_col(vec), shift)
311 .to_row_major_matrix()
312 .values
313 }
314
315 /// Compute the "coset DFT" of each column in `mat`.
316 ///
317 /// #### Mathematical Description
318 ///
319 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
320 /// Treating each column of `mat` as the coefficients of a polynomial, compute the
321 /// evaluations of those polynomials on the coset `shift * H`.
322 fn coset_dft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
323 &self,
324 mat: RowMajorMatrix<V>,
325 shift: F,
326 ) -> RowMajorMatrix<V> {
327 let init_width = mat.width();
328 let base_mat =
329 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
330 let base_dft_output = self.coset_dft_batch(base_mat, shift).to_row_major_matrix();
331 RowMajorMatrix::new(
332 V::reconstitute_from_base(base_dft_output.values),
333 init_width,
334 )
335 }
336
337 /// Compute the inverse DFT of `vec`.
338 ///
339 /// #### Mathematical Description
340 ///
341 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
342 /// Treating `vec` as the evaluations of a polynomial on `H`, compute the
343 /// coefficients of that polynomial.
344 fn idft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(&self, vec: Vec<V>) -> Vec<V> {
345 self.idft_algebra_batch(RowMajorMatrix::new_col(vec)).values
346 }
347
348 /// Compute the inverse DFT of each column in `mat`.
349 ///
350 /// #### Mathematical Description
351 ///
352 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
353 /// Treating each column of `mat` as the evaluations of a polynomial on `H`,
354 /// compute the coefficients of those polynomials.
355 fn idft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
356 &self,
357 mat: RowMajorMatrix<V>,
358 ) -> RowMajorMatrix<V> {
359 let init_width = mat.width();
360 let base_mat =
361 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
362 let base_dft_output = self.idft_batch(base_mat);
363 RowMajorMatrix::new(
364 V::reconstitute_from_base(base_dft_output.values),
365 init_width,
366 )
367 }
368
369 /// Compute the "coset iDFT" of `vec`. This is the inverse operation of "coset DFT".
370 ///
371 /// #### Mathematical Description
372 ///
373 /// Let `H` denote the unique multiplicative subgroup of order `vec.len()`.
374 /// Treating `vec` as the evaluations of a polynomial on `shift * H`,
375 /// compute the coefficients of this polynomial.
376 fn coset_idft_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
377 &self,
378 vec: Vec<V>,
379 shift: F,
380 ) -> Vec<V> {
381 self.coset_idft_algebra_batch(RowMajorMatrix::new_col(vec), shift)
382 .values
383 }
384
385 /// Compute the "coset iDFT" of each column in `mat`. This is the inverse operation
386 /// of "coset DFT".
387 ///
388 /// #### Mathematical Description
389 ///
390 /// Let `H` denote the unique multiplicative subgroup of order `mat.height()`.
391 /// Treating each column of `mat` as the evaluations of a polynomial on `shift * H`,
392 /// compute the coefficients of those polynomials.
393 fn coset_idft_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
394 &self,
395 mat: RowMajorMatrix<V>,
396 shift: F,
397 ) -> RowMajorMatrix<V> {
398 let init_width = mat.width();
399 let base_mat =
400 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
401 let base_dft_output = self.coset_idft_batch(base_mat, shift);
402 RowMajorMatrix::new(
403 V::reconstitute_from_base(base_dft_output.values),
404 init_width,
405 )
406 }
407
408 /// Compute the low-degree extension of `vec` onto a larger subgroup.
409 ///
410 /// #### Mathematical Description
411 ///
412 /// Let `H, K` denote the unique multiplicative subgroups of order `vec.len()`
413 /// and `vec.len() << added_bits`, respectively.
414 /// Treating `vec` as the evaluations of a polynomial on the subgroup `H`,
415 /// compute the evaluations of that polynomial on the subgroup `K`.
416 ///
417 /// There is another way to interpret this transformation which gives a larger
418 /// use case. We can also view it as treating columns of `mat` as evaluations
419 /// over a coset `gH` and then computing the evaluations of those polynomials
420 /// on the coset `gK`.
421 fn lde_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
422 &self,
423 vec: Vec<V>,
424 added_bits: usize,
425 ) -> Vec<V> {
426 self.lde_algebra_batch(RowMajorMatrix::new_col(vec), added_bits)
427 .to_row_major_matrix()
428 .values
429 }
430
431 /// Compute the low-degree extension of each column in `mat` onto a larger subgroup.
432 ///
433 /// #### Mathematical Description
434 ///
435 /// Let `H, K` denote the unique multiplicative subgroups of order `mat.height()`
436 /// and `mat.height() << added_bits`, respectively.
437 /// Treating each column of `mat` as the evaluations of a polynomial on the subgroup `H`,
438 /// compute the evaluations of those polynomials on the subgroup `K`.
439 ///
440 /// There is another way to interpret this transformation which gives a larger
441 /// use case. We can also view it as treating columns of `mat` as evaluations
442 /// over a coset `gH` and then computing the evaluations of those polynomials
443 /// on the coset `gK`.
444 fn lde_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
445 &self,
446 mat: RowMajorMatrix<V>,
447 added_bits: usize,
448 ) -> RowMajorMatrix<V> {
449 let init_width = mat.width();
450 let base_mat =
451 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
452 let base_dft_output = self.lde_batch(base_mat, added_bits).to_row_major_matrix();
453 RowMajorMatrix::new(
454 V::reconstitute_from_base(base_dft_output.values),
455 init_width,
456 )
457 }
458
459 /// Compute the low-degree extension of of `vec` onto a coset of a larger subgroup.
460 ///
461 /// #### Mathematical Description
462 ///
463 /// Let `H, K` denote the unique multiplicative subgroups of order `vec.len()`
464 /// and `vec.len() << added_bits`, respectively.
465 /// Treating `vec` as the evaluations of a polynomial on the subgroup `H`,
466 /// compute the evaluations of that polynomial on the coset `shift * K`.
467 ///
468 /// There is another way to interpret this transformation which gives a larger
469 /// use case. We can also view it as treating `vec` as the evaluations of a polynomial
470 /// over a coset `gH` and then computing the evaluations of that polynomial
471 /// on the coset `g'K` where `g' = g * shift`.
472 fn coset_lde_algebra<V: BasedVectorSpace<F> + Clone + Send + Sync>(
473 &self,
474 vec: Vec<V>,
475 added_bits: usize,
476 shift: F,
477 ) -> Vec<V> {
478 self.coset_lde_algebra_batch(RowMajorMatrix::new_col(vec), added_bits, shift)
479 .to_row_major_matrix()
480 .values
481 }
482
483 /// Compute the low-degree extension of each column in `mat` onto a coset of a larger subgroup.
484 ///
485 /// #### Mathematical Description
486 ///
487 /// Let `H, K` denote the unique multiplicative subgroups of order `mat.height()`
488 /// and `mat.height() << added_bits`, respectively.
489 /// Treating each column of `mat` as the evaluations of a polynomial on the subgroup `H`,
490 /// compute the evaluations of those polynomials on the coset `shift * K`.
491 ///
492 /// There is another way to interpret this transformation which gives a larger
493 /// use case. We can also view it as treating columns of `mat` as evaluations
494 /// over a coset `gH` and then computing the evaluations of those polynomials
495 /// on the coset `g'K` where `g' = g * shift`.
496 fn coset_lde_algebra_batch<V: BasedVectorSpace<F> + Clone + Send + Sync>(
497 &self,
498 mat: RowMajorMatrix<V>,
499 added_bits: usize,
500 shift: F,
501 ) -> RowMajorMatrix<V> {
502 let init_width = mat.width();
503 let base_mat =
504 RowMajorMatrix::new(V::flatten_to_base(mat.values), init_width * V::DIMENSION);
505 let base_dft_output = self
506 .coset_lde_batch(base_mat, added_bits, shift)
507 .to_row_major_matrix();
508 RowMajorMatrix::new(
509 V::reconstitute_from_base(base_dft_output.values),
510 init_width,
511 )
512 }
513}
514
515/// Memory layout of the coefficient buffer passed to a transform closure in
516/// [`TwoAdicSubgroupDft::coset_lde_batch_with_transform`].
517#[derive(Copy, Clone, Debug, PartialEq, Eq)]
518pub enum Layout {
519 /// Memory row `m` corresponds to natural-order index `m`.
520 Natural,
521 /// Memory row `m` corresponds to natural-order index
522 /// `reverse_bits_len(m, log2_strict_usize(buf.height()))`.
523 BitReversed,
524}