Debian Codegraph @

third_party/rust/prio/src/flp/gadgets.rs

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! A collection of gadgets.
4
5 use crate::fft::{discrete_fourier_transform, discrete_fourier_transform_inv_finish};
6 use crate::field::FftFriendlyFieldElement;
7 use crate::flp::{gadget_poly_len, wire_poly_len, FlpError, Gadget};
8 use crate::polynomial::{poly_deg, poly_eval, poly_mul};
9
10 #[cfg(feature = "multithreaded")]
11 use rayon::prelude::*;
12
13 use std::any::Any;
14 use std::convert::TryFrom;
15 use std::fmt::Debug;
16 use std::marker::PhantomData;
17
18 /// For input polynomials larger than or equal to this threshold, gadgets will use FFT for
19 /// polynomial multiplication. Otherwise, the gadget uses direct multiplication.
20 const FFT_THRESHOLD: usize = 60;
21
22 /// An arity-2 gadget that multiples its inputs.
23 #[derive(Clone, Debug, Eq, PartialEq)]
24 pub struct Mul<F: FftFriendlyFieldElement> {
25 /// Size of buffer for FFT operations.
26 n: usize,
27 /// Inverse of `n` in `F`.
28 n_inv: F,
29 /// The number of times this gadget will be called.
30 num_calls: usize,
31 }
32
33 impl<F: FftFriendlyFieldElement> Mul<F> {
34 /// Return a new multiplier gadget. `num_calls` is the number of times this gadget will be
35 /// called by the validity circuit.
36 pub fn new(num_calls: usize) -> Self {
37 let n = gadget_poly_fft_mem_len(2, num_calls);
38 let n_inv = F::from(F::Integer::try_from(n).unwrap()).inv();
39 Self {
40 n,
41 n_inv,
42 num_calls,
43 }
44 }
45
46 // Multiply input polynomials directly.
47 pub(crate) fn call_poly_direct(
48 &mut self,
49 outp: &mut [F],
50 inp: &[Vec<F>],
51 ) -> Result<(), FlpError> {
52 let v = poly_mul(&inp[0], &inp[1]);
53 outp[..v.len()].clone_from_slice(&v);
54 Ok(())
55 }
56
57 // Multiply input polynomials using FFT.
58 pub(crate) fn call_poly_fft(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
59 let n = self.n;
60 let mut buf = vec![F::zero(); n];
61
62 discrete_fourier_transform(&mut buf, &inp[0], n)?;
63 discrete_fourier_transform(outp, &inp[1], n)?;
64
65 for i in 0..n {
66 buf[i] *= outp[i];
67 }
68
69 discrete_fourier_transform(outp, &buf, n)?;
70 discrete_fourier_transform_inv_finish(outp, n, self.n_inv);
71 Ok(())
72 }
73 }
74
75 impl<F: FftFriendlyFieldElement> Gadget<F> for Mul<F> {
76 fn call(&mut self, inp: &[F]) -> Result<F, FlpError> {
77 gadget_call_check(self, inp.len())?;
78 Ok(inp[0] * inp[1])
79 }
80
81 fn call_poly(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
82 gadget_call_poly_check(self, outp, inp)?;
83 if inp[0].len() >= FFT_THRESHOLD {
84 self.call_poly_fft(outp, inp)
85 } else {
86 self.call_poly_direct(outp, inp)
87 }
88 }
89
90 fn arity(&self) -> usize {
91 2
92 }
93
94 fn degree(&self) -> usize {
95 2
96 }
97
98 fn calls(&self) -> usize {
99 self.num_calls
100 }
101
102 fn as_any(&mut self) -> &mut dyn Any {
103 self
104 }
105 }
106
107 /// An arity-1 gadget that evaluates its input on some polynomial.
108 //
109 // TODO Make `poly` an array of length determined by a const generic.
110 #[derive(Clone, Debug, Eq, PartialEq)]
111 pub struct PolyEval<F: FftFriendlyFieldElement> {
112 poly: Vec<F>,
113 /// Size of buffer for FFT operations.
114 n: usize,
115 /// Inverse of `n` in `F`.
116 n_inv: F,
117 /// The number of times this gadget will be called.
118 num_calls: usize,
119 }
120
121 impl<F: FftFriendlyFieldElement> PolyEval<F> {
122 /// Returns a gadget that evaluates its input on `poly`. `num_calls` is the number of times
123 /// this gadget is called by the validity circuit.
124 pub fn new(poly: Vec<F>, num_calls: usize) -> Self {
125 let n = gadget_poly_fft_mem_len(poly_deg(&poly), num_calls);
126 let n_inv = F::from(F::Integer::try_from(n).unwrap()).inv();
127 Self {
128 poly,
129 n,
130 n_inv,
131 num_calls,
132 }
133 }
134 }
135
136 impl<F: FftFriendlyFieldElement> PolyEval<F> {
137 // Multiply input polynomials directly.
138 fn call_poly_direct(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
139 outp[0] = self.poly[0];
140 let mut x = inp[0].to_vec();
141 for i in 1..self.poly.len() {
142 for j in 0..x.len() {
143 outp[j] += self.poly[i] * x[j];
144 }
145
146 if i < self.poly.len() - 1 {
147 x = poly_mul(&x, &inp[0]);
148 }
149 }
150 Ok(())
151 }
152
153 // Multiply input polynomials using FFT.
154 fn call_poly_fft(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
155 let n = self.n;
156 let inp = &inp[0];
157
158 let mut inp_vals = vec![F::zero(); n];
159 discrete_fourier_transform(&mut inp_vals, inp, n)?;
160
161 let mut x_vals = inp_vals.clone();
162 let mut x = vec![F::zero(); n];
163 x[..inp.len()].clone_from_slice(inp);
164
165 outp[0] = self.poly[0];
166 for i in 1..self.poly.len() {
167 for j in 0..n {
168 outp[j] += self.poly[i] * x[j];
169 }
170
171 if i < self.poly.len() - 1 {
172 for j in 0..n {
173 x_vals[j] *= inp_vals[j];
174 }
175
176 discrete_fourier_transform(&mut x, &x_vals, n)?;
177 discrete_fourier_transform_inv_finish(&mut x, n, self.n_inv);
178 }
179 }
180 Ok(())
181 }
182 }
183
184 impl<F: FftFriendlyFieldElement> Gadget<F> for PolyEval<F> {
185 fn call(&mut self, inp: &[F]) -> Result<F, FlpError> {
186 gadget_call_check(self, inp.len())?;
187 Ok(poly_eval(&self.poly, inp[0]))
188 }
189
190 fn call_poly(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
191 gadget_call_poly_check(self, outp, inp)?;
192
193 for item in outp.iter_mut() {
194 *item = F::zero();
195 }
196
197 if inp[0].len() >= FFT_THRESHOLD {
198 self.call_poly_fft(outp, inp)
199 } else {
200 self.call_poly_direct(outp, inp)
201 }
202 }
203
204 fn arity(&self) -> usize {
205 1
206 }
207
208 fn degree(&self) -> usize {
209 poly_deg(&self.poly)
210 }
211
212 fn calls(&self) -> usize {
213 self.num_calls
214 }
215
216 fn as_any(&mut self) -> &mut dyn Any {
217 self
218 }
219 }
220
221 /// Trait for abstracting over [`ParallelSum`].
222 pub trait ParallelSumGadget<F: FftFriendlyFieldElement, G>: Gadget<F> + Debug {
223 /// Wraps `inner` into a sum gadget that calls it `chunks` many times, and adds the reuslts.
224 fn new(inner: G, chunks: usize) -> Self;
225 }
226
227 /// A wrapper gadget that applies the inner gadget to chunks of input and returns the sum of the
228 /// outputs. The arity is equal to the arity of the inner gadget times the number of times it is
229 /// called.
230 #[derive(Clone, Debug, Eq, PartialEq)]
231 pub struct ParallelSum<F: FftFriendlyFieldElement, G: Gadget<F>> {
232 inner: G,
233 chunks: usize,
234 phantom: PhantomData<F>,
235 }
236
237 impl<F: FftFriendlyFieldElement, G: 'static + Gadget<F>> ParallelSumGadget<F, G>
238 for ParallelSum<F, G>
239 {
240 fn new(inner: G, chunks: usize) -> Self {
241 Self {
242 inner,
243 chunks,
244 phantom: PhantomData,
245 }
246 }
247 }
248
249 impl<F: FftFriendlyFieldElement, G: 'static + Gadget<F>> Gadget<F> for ParallelSum<F, G> {
250 fn call(&mut self, inp: &[F]) -> Result<F, FlpError> {
251 gadget_call_check(self, inp.len())?;
252 let mut outp = F::zero();
253 for chunk in inp.chunks(self.inner.arity()) {
254 outp += self.inner.call(chunk)?;
255 }
256 Ok(outp)
257 }
258
259 fn call_poly(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
260 gadget_call_poly_check(self, outp, inp)?;
261
262 for x in outp.iter_mut() {
263 *x = F::zero();
264 }
265
266 let mut partial_outp = vec![F::zero(); outp.len()];
267
268 for chunk in inp.chunks(self.inner.arity()) {
269 self.inner.call_poly(&mut partial_outp, chunk)?;
270 for i in 0..outp.len() {
271 outp[i] += partial_outp[i]
272 }
273 }
274
275 Ok(())
276 }
277
278 fn arity(&self) -> usize {
279 self.chunks * self.inner.arity()
280 }
281
282 fn degree(&self) -> usize {
283 self.inner.degree()
284 }
285
286 fn calls(&self) -> usize {
287 self.inner.calls()
288 }
289
290 fn as_any(&mut self) -> &mut dyn Any {
291 self
292 }
293 }
294
295 /// A wrapper gadget that applies the inner gadget to chunks of input and returns the sum of the
296 /// outputs. The arity is equal to the arity of the inner gadget times the number of chunks. The sum
297 /// evaluation is multithreaded.
298 #[cfg(feature = "multithreaded")]
299 #[cfg_attr(docsrs, doc(cfg(feature = "multithreaded")))]
300 #[derive(Clone, Debug, Eq, PartialEq)]
301 pub struct ParallelSumMultithreaded<F: FftFriendlyFieldElement, G: Gadget<F>> {
302 serial_sum: ParallelSum<F, G>,
303 }
304
305 #[cfg(feature = "multithreaded")]
306 impl<F, G> ParallelSumGadget<F, G> for ParallelSumMultithreaded<F, G>
307 where
308 F: FftFriendlyFieldElement + Sync + Send,
309 G: 'static + Gadget<F> + Clone + Sync + Send,
310 {
311 fn new(inner: G, chunks: usize) -> Self {
312 Self {
313 serial_sum: ParallelSum::new(inner, chunks),
314 }
315 }
316 }
317
318 /// Data structures passed between fold operations in [`ParallelSumMultithreaded`].
319 #[cfg(feature = "multithreaded")]
320 struct ParallelSumFoldState<F, G> {
321 /// Inner gadget.
322 inner: G,
323 /// Output buffer for `call_poly()`.
324 partial_output: Vec<F>,
325 /// Sum accumulator.
326 partial_sum: Vec<F>,
327 }
328
329 #[cfg(feature = "multithreaded")]
330 impl<F, G> ParallelSumFoldState<F, G> {
331 fn new(gadget: &G, length: usize) -> ParallelSumFoldState<F, G>
332 where
333 G: Clone,
334 F: FftFriendlyFieldElement,
335 {
336 ParallelSumFoldState {
337 inner: gadget.clone(),
338 partial_output: vec![F::zero(); length],
339 partial_sum: vec![F::zero(); length],
340 }
341 }
342 }
343
344 #[cfg(feature = "multithreaded")]
345 impl<F, G> Gadget<F> for ParallelSumMultithreaded<F, G>
346 where
347 F: FftFriendlyFieldElement + Sync + Send,
348 G: 'static + Gadget<F> + Clone + Sync + Send,
349 {
350 fn call(&mut self, inp: &[F]) -> Result<F, FlpError> {
351 self.serial_sum.call(inp)
352 }
353
354 fn call_poly(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> {
355 gadget_call_poly_check(self, outp, inp)?;
356
357 // Create a copy of the inner gadget and two working buffers on each thread. Evaluate the
358 // gadget on each input polynomial, using the first temporary buffer as an output buffer.
359 // Then accumulate that result into the second temporary buffer, which acts as a running
360 // sum. Then, discard everything but the partial sums, add them, and finally copy the sum
361 // to the output parameter. This is equivalent to the single threaded calculation in
362 // ParallelSum, since we only rearrange additions, and field addition is associative.
363 let res = inp
364 .par_chunks(self.serial_sum.inner.arity())
365 .fold(
366 || ParallelSumFoldState::new(&self.serial_sum.inner, outp.len()),
367 |mut state, chunk| {
368 state
369 .inner
370 .call_poly(&mut state.partial_output, chunk)
371 .unwrap();
372 for (sum_elem, output_elem) in state
373 .partial_sum
374 .iter_mut()
375 .zip(state.partial_output.iter())
376 {
377 *sum_elem += *output_elem;
378 }
379 state
380 },
381 )
382 .map(|state| state.partial_sum)
383 .reduce(
384 || vec![F::zero(); outp.len()],
385 |mut x, y| {
386 for (xi, yi) in x.iter_mut().zip(y.iter()) {
387 *xi += *yi;
388 }
389 x
390 },
391 );
392
393 outp.copy_from_slice(&res[..]);
394 Ok(())
395 }
396
397 fn arity(&self) -> usize {
398 self.serial_sum.arity()
399 }
400
401 fn degree(&self) -> usize {
402 self.serial_sum.degree()
403 }
404
405 fn calls(&self) -> usize {
406 self.serial_sum.calls()
407 }
408
409 fn as_any(&mut self) -> &mut dyn Any {
410 self
411 }
412 }
413
414 // Check that the input parameters of g.call() are well-formed.
415 fn gadget_call_check<F: FftFriendlyFieldElement, G: Gadget<F>>(
416 gadget: &G,
417 in_len: usize,
418 ) -> Result<(), FlpError> {
419 if in_len != gadget.arity() {
420 return Err(FlpError::Gadget(format!(
421 "unexpected number of inputs: got {}; want {}",
422 in_len,
423 gadget.arity()
424 )));
425 }
426
427 if in_len == 0 {
428 return Err(FlpError::Gadget("can't call an arity-0 gadget".to_string()));
429 }
430
431 Ok(())
432 }
433
434 // Check that the input parameters of g.call_poly() are well-formed.
435 fn gadget_call_poly_check<F: FftFriendlyFieldElement, G: Gadget<F>>(
436 gadget: &G,
437 outp: &[F],
438 inp: &[Vec<F>],
439 ) -> Result<(), FlpError>
440 where
441 G: Gadget<F>,
442 {
443 gadget_call_check(gadget, inp.len())?;
444
445 for i in 1..inp.len() {
446 if inp[i].len() != inp[0].len() {
447 return Err(FlpError::Gadget(
448 "gadget called on wire polynomials with different lengths".to_string(),
449 ));
450 }
451 }
452
453 let expected = gadget_poly_len(gadget.degree(), inp[0].len()).next_power_of_two();
454 if outp.len() != expected {
455 return Err(FlpError::Gadget(format!(
456 "incorrect output length: got {}; want {}",
457 outp.len(),
458 expected
459 )));
460 }
461
462 Ok(())
463 }
464
465 #[inline]
466 fn gadget_poly_fft_mem_len(degree: usize, num_calls: usize) -> usize {
467 gadget_poly_len(degree, wire_poly_len(num_calls)).next_power_of_two()
468 }
469
470 #[cfg(test)]
471 mod tests {
472 use super::*;
473
474 #[cfg(feature = "multithreaded")]
475 use crate::field::FieldElement;
476 use crate::field::{random_vector, Field64 as TestField};
477 use crate::prng::Prng;
478
479 #[test]
480 fn test_mul() {
481 // Test the gadget with input polynomials shorter than `FFT_THRESHOLD`. This exercises the
482 // naive multiplication code path.
483 let num_calls = FFT_THRESHOLD / 2;
484 let mut g: Mul<TestField> = Mul::new(num_calls);
485 gadget_test(&mut g, num_calls);
486
487 // Test the gadget with input polynomials longer than `FFT_THRESHOLD`. This exercises
488 // FFT-based polynomial multiplication.
489 let num_calls = FFT_THRESHOLD;
490 let mut g: Mul<TestField> = Mul::new(num_calls);
491 gadget_test(&mut g, num_calls);
492 }
493
494 #[test]
495 fn test_poly_eval() {
496 let poly: Vec<TestField> = random_vector(10).unwrap();
497
498 let num_calls = FFT_THRESHOLD / 2;
499 let mut g: PolyEval<TestField> = PolyEval::new(poly.clone(), num_calls);
500 gadget_test(&mut g, num_calls);
501
502 let num_calls = FFT_THRESHOLD;
503 let mut g: PolyEval<TestField> = PolyEval::new(poly, num_calls);
504 gadget_test(&mut g, num_calls);
505 }
506
507 #[test]
508 fn test_parallel_sum() {
509 let num_calls = 10;
510 let chunks = 23;
511
512 let mut g = ParallelSum::new(Mul::<TestField>::new(num_calls), chunks);
513 gadget_test(&mut g, num_calls);
514 }
515
516 #[test]
517 #[cfg(feature = "multithreaded")]
518 fn test_parallel_sum_multithreaded() {
519 use std::iter;
520
521 for num_calls in [1, 10, 100] {
522 let chunks = 23;
523
524 let mut g = ParallelSumMultithreaded::new(Mul::new(num_calls), chunks);
525 gadget_test(&mut g, num_calls);
526
527 // Test that the multithreaded version has the same output as the normal version.
528 let mut g_serial = ParallelSum::new(Mul::new(num_calls), chunks);
529 assert_eq!(g.arity(), g_serial.arity());
530 assert_eq!(g.degree(), g_serial.degree());
531 assert_eq!(g.calls(), g_serial.calls());
532
533 let arity = g.arity();
534 let degree = g.degree();
535
536 // Test that both gadgets evaluate to the same value when run on scalar inputs.
537 let inp: Vec<TestField> = random_vector(arity).unwrap();
538 let result = g.call(&inp).unwrap();
539 let result_serial = g_serial.call(&inp).unwrap();
540 assert_eq!(result, result_serial);
541
542 // Test that both gadgets evaluate to the same value when run on polynomial inputs.
543 let mut poly_outp =
544 vec![TestField::zero(); (degree * num_calls + 1).next_power_of_two()];
545 let mut poly_outp_serial =
546 vec![TestField::zero(); (degree * num_calls + 1).next_power_of_two()];
547 let mut prng: Prng<TestField, _> = Prng::new().unwrap();
548 let poly_inp: Vec<_> = iter::repeat_with(|| {
549 iter::repeat_with(|| prng.get())
550 .take(1 + num_calls)
551 .collect::<Vec<_>>()
552 })
553 .take(arity)
554 .collect();
555
556 g.call_poly(&mut poly_outp, &poly_inp).unwrap();
557 g_serial
558 .call_poly(&mut poly_outp_serial, &poly_inp)
559 .unwrap();
560 assert_eq!(poly_outp, poly_outp_serial);
561 }
562 }
563
564 // Test that calling g.call_poly() and evaluating the output at a given point is equivalent
565 // to evaluating each of the inputs at the same point and applying g.call() on the results.
566 fn gadget_test<F: FftFriendlyFieldElement, G: Gadget<F>>(g: &mut G, num_calls: usize) {
567 let wire_poly_len = (1 + num_calls).next_power_of_two();
568 let mut prng = Prng::new().unwrap();
569 let mut inp = vec![F::zero(); g.arity()];
570 let mut gadget_poly = vec![F::zero(); gadget_poly_fft_mem_len(g.degree(), num_calls)];
571 let mut wire_polys = vec![vec![F::zero(); wire_poly_len]; g.arity()];
572
573 let r = prng.get();
574 for i in 0..g.arity() {
575 for j in 0..wire_poly_len {
576 wire_polys[i][j] = prng.get();
577 }
578 inp[i] = poly_eval(&wire_polys[i], r);
579 }
580
581 g.call_poly(&mut gadget_poly, &wire_polys).unwrap();
582 let got = poly_eval(&gadget_poly, r);
583 let want = g.call(&inp).unwrap();
584 assert_eq!(got, want);
585
586 // Repeat the call to make sure that the gadget's memory is reset properly between calls.
587 g.call_poly(&mut gadget_poly, &wire_polys).unwrap();
588 let got = poly_eval(&gadget_poly, r);
589 assert_eq!(got, want);
590 }
591 }