p3_commit/domain.rs
1use alloc::vec::Vec;
2
3use itertools::Itertools;
4use p3_field::coset::TwoAdicMultiplicativeCoset;
5use p3_field::{ExtensionField, Field, TwoAdicField, batch_multiplicative_inverse};
6use p3_matrix::Matrix;
7use p3_matrix::dense::RowMajorMatrix;
8use p3_util::{log2_ceil_usize, log2_strict_usize};
9
10/// Given a `PolynomialSpace`, `S`, and a subset `R`, a Lagrange selector `P_R` is
11/// a polynomial which is not equal to `0` for every element in `R` but is equal
12/// to `0` for every element of `S` not in `R`.
13///
14/// This struct contains evaluations of several Lagrange selectors for a fixed
15/// `PolynomialSpace` over some collection of points disjoint from that
16/// `PolynomialSpace`.
17///
18/// The Lagrange selector is normalized if it is equal to `1` for every element in `R`.
19/// The LagrangeSelectors given here are not normalized.
20#[derive(Debug)]
21pub struct LagrangeSelectors<T> {
22 /// A Lagrange selector corresponding to the first point in the space.
23 pub is_first_row: T,
24 /// A Lagrange selector corresponding to the last point in the space.
25 pub is_last_row: T,
26 /// A Lagrange selector corresponding the subset of all but the last point.
27 pub is_transition: T,
28 /// The inverse of the vanishing polynomial which is a Lagrange selector corresponding to the empty set
29 pub inv_vanishing: T,
30}
31
32/// Fixing a field, `F`, `PolynomialSpace<Val = F>` denotes an indexed subset of `F^n`
33/// with some additional algebraic structure.
34///
35/// We do not expect `PolynomialSpace` to store this subset, instead it usually contains
36/// some associated data which allows it to generate the subset or pieces of it.
37///
38/// Each `PolynomialSpace` should be part of a family of similar spaces for some
39/// collection of sizes (usually powers of two). Any space other than at the smallest size
40/// should be decomposable into a disjoint collection of smaller spaces. Additionally, the
41/// set of all `PolynomialSpace` of a given size should form a disjoint partition of some
42/// subset of `F^n` which supports a group structure.
43///
44/// The canonical example of a `PolynomialSpace` is a coset `gH` of
45/// a two-adic subgroup `H` of the multiplicative group `F*`. This satisfies the properties
46/// above as cosets partition the group and decompose as `gH = g(H^2) u gh(H^2)` for `h` any
47/// generator of `H`.
48///
49/// The other example in this code base is twin cosets which are sets of the form `gH u g^{-1}H`.
50/// The decomposition above extends easily to this case as `h` is a generator if and only if `h^{-1}`
51/// is and so `gH u g^{-1}H = (g(H^2) u g^{-1}(H^2)) u (gh(H^2) u (gh)^{-1}(H^2))`.
52pub trait PolynomialSpace: Copy {
53 /// The base field `F`.
54 type Val: Field;
55
56 /// The number of elements of the space.
57 fn size(&self) -> usize;
58
59 /// The first point in the space.
60 fn first_point(&self) -> Self::Val;
61
62 /// An algebraic function which takes the i'th element of the space and returns
63 /// the (i+1)'th evaluated on the given point.
64 ///
65 /// When `PolynomialSpace` corresponds to a coset, `gH` this
66 /// function is multiplication by `h` for a chosen generator `h` of `H`.
67 ///
68 /// This function may not exist for other classes of `PolynomialSpace` in which
69 /// case this will return `None`.
70 fn next_point<Ext: ExtensionField<Self::Val>>(&self, x: Ext) -> Option<Ext>;
71
72 /// Return another `PolynomialSpace` with size at least `min_size` disjoint from this space.
73 ///
74 /// When working with spaces of power of two size, this will return a space of size `2^ceil(log_2(min_size))`.
75 /// This will fail if `min_size` is too large. In particular, `log_2(min_size)` should be
76 /// smaller than the `2`-adicity of the field.
77 ///
78 /// This fixes a canonical choice for prover/verifier determinism and LDE caching.
79 fn create_disjoint_domain(&self, min_size: usize) -> Self;
80
81 /// Split the `PolynomialSpace` into `num_chunks` smaller `PolynomialSpaces` of equal size.
82 ///
83 /// `num_chunks` must divide `self.size()` (which usually forces it to be a power of 2.) or
84 /// this function will panic.
85 fn split_domains(&self, num_chunks: usize) -> Vec<Self>;
86
87 /// Split a set of polynomial evaluations over this `PolynomialSpace` into a vector
88 /// of polynomial evaluations over each `PolynomialSpace` generated from `split_domains`.
89 ///
90 /// `evals.height()` must equal `self.size()` and `num_chunks` must divide `self.size()`.
91 /// `evals` are assumed to be in standard (not bit-reversed) order.
92 fn split_evals(
93 &self,
94 num_chunks: usize,
95 evals: RowMajorMatrix<Self::Val>,
96 ) -> Vec<RowMajorMatrix<Self::Val>>;
97
98 /// Compute the vanishing polynomial of the space, evaluated at the given point.
99 ///
100 /// This is a polynomial which evaluates to `0` on every point of the
101 /// space `self` and has degree equal to `self.size()`. In other words it is
102 /// a choice of element of the defining ideal of the given set with this extra
103 /// degree property.
104 ///
105 /// In the univariate case, it is equal, up to a linear factor, to the product over
106 /// all elements `x`, of `(X - x)`. In particular this implies it will not evaluate
107 /// to `0` at any point not in `self`.
108 fn vanishing_poly_at_point<Ext: ExtensionField<Self::Val>>(&self, point: Ext) -> Ext;
109
110 /// Compute several Lagrange selectors at a given point.
111 /// - The Lagrange selector of the first point.
112 /// - The Lagrange selector of the last point.
113 /// - The Lagrange selector of everything but the last point.
114 /// - The inverse of the vanishing polynomial.
115 ///
116 /// Note that these may not be normalized.
117 fn selectors_at_point<Ext: ExtensionField<Self::Val>>(
118 &self,
119 point: Ext,
120 ) -> LagrangeSelectors<Ext>;
121
122 /// Compute several Lagrange selectors at all points of the given disjoint `PolynomialSpace`.
123 /// - The Lagrange selector of the first point.
124 /// - The Lagrange selector of the last point.
125 /// - The Lagrange selector of everything but the last point.
126 /// - The inverse of the vanishing polynomial.
127 ///
128 /// Note that these may not be normalized.
129 fn selectors_on_coset(&self, coset: Self) -> LagrangeSelectors<Vec<Self::Val>>;
130}
131
132impl<Val: TwoAdicField> PolynomialSpace for TwoAdicMultiplicativeCoset<Val> {
133 type Val = Val;
134
135 fn size(&self) -> usize {
136 self.size()
137 }
138
139 fn first_point(&self) -> Self::Val {
140 self.shift()
141 }
142
143 /// Getting the next point corresponds to multiplication by the generator.
144 fn next_point<Ext: ExtensionField<Val>>(&self, x: Ext) -> Option<Ext> {
145 Some(x * self.subgroup_generator())
146 }
147
148 /// Given the coset `gH`, return the disjoint coset `gfK` where `f`
149 /// is a fixed generator of `F^*` and `K` is the unique two-adic subgroup
150 /// of with size `2^(ceil(log_2(min_size)))`.
151 ///
152 /// # Panics
153 ///
154 /// This will panic if `min_size` > `1 << Val::TWO_ADICITY`.
155 fn create_disjoint_domain(&self, min_size: usize) -> Self {
156 // We provide a short proof that these cosets are always disjoint:
157 //
158 // Assume without loss of generality that `|H| <= min_size <= |K|`.
159 // Then we know that `gH` is entirely contained in `gK`. As cosets are
160 // either equal or disjoint, this means that `gH` is disjoint from `g'K`
161 // for every `g'` not contained in `gK`. As `f` is a generator of `F^*`
162 // it does not lie in `K` and so `gf` cannot lie in `gK`.
163 //
164 // Thus `gH` and `gfK` are disjoint.
165
166 // This panics if (and only if) `min_size` > `1 << Val::TWO_ADICITY`.
167 Self::new(self.shift() * Val::GENERATOR, log2_ceil_usize(min_size)).unwrap()
168 }
169
170 /// Given the coset `gH` and generator `h` of `H`, let `K = H^{num_chunks}`
171 /// be the unique group of order `|H|/num_chunks`.
172 ///
173 /// Then we decompose `gH` into `gK, ghK, gh^2K, ..., gh^{num_chunks}K`.
174 fn split_domains(&self, num_chunks: usize) -> Vec<Self> {
175 let log_chunks = log2_strict_usize(num_chunks);
176 debug_assert!(log_chunks <= self.log_size());
177 (0..num_chunks)
178 .map(|i| {
179 Self::new(
180 self.shift() * self.subgroup_generator().exp_u64(i as u64),
181 self.log_size() - log_chunks,
182 )
183 .unwrap() // This won't panic as `self.log_size() - log_chunks < self.log_size() < Val::TWO_ADICITY`
184 })
185 .collect()
186 }
187
188 fn split_evals(
189 &self,
190 num_chunks: usize,
191 evals: RowMajorMatrix<Self::Val>,
192 ) -> Vec<RowMajorMatrix<Self::Val>> {
193 debug_assert_eq!(evals.height(), self.size());
194 debug_assert!(log2_strict_usize(num_chunks) <= self.log_size());
195 let height = evals.height();
196 let width = evals.width();
197 let rows_per_chunk = height / num_chunks;
198
199 // Preallocate zeroed buffers per chunk; often faster for field elements.
200 let mut values: Vec<Vec<Self::Val>> = (0..num_chunks)
201 .map(|_| Self::Val::zero_vec(rows_per_chunk * width))
202 .collect();
203
204 // Distribute rows without using modulo: iterate blocks of size num_chunks.
205 for i in 0..rows_per_chunk {
206 let base_row = i * num_chunks;
207 let dst_start = i * width;
208 let dst_end = dst_start + width;
209 for (chunk, dst_vec) in values.iter_mut().enumerate().take(num_chunks) {
210 let r = base_row + chunk;
211 // Safety: r < height == rows_per_chunk * num_chunks
212 let row = unsafe { evals.row_slice_unchecked(r) };
213 dst_vec[dst_start..dst_end].copy_from_slice(&row);
214 }
215 }
216
217 values
218 .into_iter()
219 .map(|v| RowMajorMatrix::new(v, width))
220 .collect()
221 }
222
223 /// Compute the vanishing polynomial at the given point:
224 ///
225 /// `Z_{gH}(X) = g^{-|H|}\prod_{h \in H} (X - gh) = (g^{-1}X)^|H| - 1`
226 fn vanishing_poly_at_point<Ext: ExtensionField<Val>>(&self, point: Ext) -> Ext {
227 (point * self.shift_inverse()).exp_power_of_2(self.log_size()) - Ext::ONE
228 }
229
230 /// Compute several Lagrange selectors at the given point:
231 ///
232 /// Defining the vanishing polynomial by `Z_{gH}(X) = g^{-|H|}\prod_{h \in H} (X - gh) = (g^{-1}X)^|H| - 1` return:
233 /// - `Z_{gH}(X)/(g^{-1}X - 1)`: The Lagrange selector of the point `g`.
234 /// - `Z_{gH}(X)/(g^{-1}X - h^{-1})`: The Lagrange selector of the point `gh^{-1}` where `h` is the generator of `H`.
235 /// - `(g^{-1}X - h^{-1})`: The Lagrange selector of the subset consisting of everything but the point `gh^{-1}`.
236 /// - `1/Z_{gH}(X)`: The inverse of the vanishing polynomial.
237 fn selectors_at_point<Ext: ExtensionField<Val>>(&self, point: Ext) -> LagrangeSelectors<Ext> {
238 let unshifted_point = point * self.shift_inverse();
239 let z_h = unshifted_point.exp_power_of_2(self.log_size()) - Ext::ONE;
240 LagrangeSelectors {
241 is_first_row: z_h / (unshifted_point - Ext::ONE),
242 is_last_row: z_h / (unshifted_point - self.subgroup_generator().inverse()),
243 is_transition: unshifted_point - self.subgroup_generator().inverse(),
244 inv_vanishing: z_h.inverse(),
245 }
246 }
247
248 /// Compute the Lagrange selectors of our space at every point in the coset.
249 ///
250 /// This will error if our space is not the group `H` and if the given
251 /// coset is not disjoint from `H`.
252 fn selectors_on_coset(&self, coset: Self) -> LagrangeSelectors<Vec<Val>> {
253 assert_eq!(self.shift(), Val::ONE);
254 assert_ne!(coset.shift(), Val::ONE);
255 assert!(coset.log_size() >= self.log_size());
256 let rate_bits = coset.log_size() - self.log_size();
257
258 let s_pow_n = coset.shift().exp_power_of_2(self.log_size());
259 // evals of Z_H(X) = X^n - 1
260 let evals = Val::two_adic_generator(rate_bits)
261 .powers()
262 .take(1 << rate_bits)
263 .map(|x| s_pow_n * x - Val::ONE)
264 .collect_vec();
265
266 let xs = coset.iter().collect();
267
268 let single_point_selector = |i: u64| {
269 let coset_i = self.subgroup_generator().exp_u64(i);
270 let denoms = xs.iter().map(|&x| x - coset_i).collect_vec();
271 let invs = batch_multiplicative_inverse(&denoms);
272 evals
273 .iter()
274 .cycle()
275 .zip(invs)
276 .map(|(&z_h, inv)| z_h * inv)
277 .collect_vec()
278 };
279
280 let subgroup_last = self.subgroup_generator().inverse();
281
282 LagrangeSelectors {
283 is_first_row: single_point_selector(0),
284 is_last_row: single_point_selector(self.size() as u64 - 1),
285 is_transition: xs.into_iter().map(|x| x - subgroup_last).collect(),
286 inv_vanishing: batch_multiplicative_inverse(&evals)
287 .into_iter()
288 .cycle()
289 .take(coset.size())
290 .collect(),
291 }
292 }
293}