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