binius_core/transparent/
ring_switch.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Copyright 2024 Irreducible Inc.

use crate::{
	polynomial::{Error, MultivariatePoly},
	tensor_algebra::TensorAlgebra,
	tower::TowerFamily,
};
use binius_field::{
	util::inner_product_unchecked, ExtensionField, Field, PackedExtension, PackedField,
	PackedFieldIndexable, TowerField,
};
use binius_hal::{make_portable_backend, ComputationBackend, ComputationBackendExt};
use binius_math::MultilinearExtension;
use binius_utils::bail;
use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
use std::{fmt::Debug, iter, marker::PhantomData};
use tracing::instrument;

/// This struct provides generic functionality for the multilinear function $A$ from [DP24] Section 5.
///
/// Unlike the `RingSwitchEqInd` struct, this struct is parameterized by the tower height, which is
/// a runtime parameter.
///
/// Recall that the "ring-switched eq indicator" is a transparent multilinear required for the ring-switching argument.
/// The principal purpose of the below abstraction is for `fri_pcs` to not need to know about the small field.
///
/// [DP24]: <https://eprint.iacr.org/2024/504>
#[allow(dead_code)]
#[derive(Debug)]
enum TowerRingSwitchEqInd<Tower>
where
	Tower: TowerFamily + Debug,
	Tower::B128: PackedField<Scalar = Tower::B128>
		+ PackedExtension<Tower::B1>
		+ PackedExtension<Tower::B8>
		+ PackedExtension<Tower::B16>
		+ PackedExtension<Tower::B32>
		+ PackedExtension<Tower::B64>
		+ PackedExtension<Tower::B128>,
{
	B1(RingSwitchEqInd<Tower::B1, Tower::B128>),
	B8(RingSwitchEqInd<Tower::B8, Tower::B128>),
	B16(RingSwitchEqInd<Tower::B16, Tower::B128>),
	B32(RingSwitchEqInd<Tower::B32, Tower::B128>),
	B64(RingSwitchEqInd<Tower::B64, Tower::B128>),
	B128(RingSwitchEqInd<Tower::B128, Tower::B128>),
}

impl<Tower> TowerRingSwitchEqInd<Tower>
where
	Tower: TowerFamily + Debug,
	Tower::B128: PackedField<Scalar = Tower::B128>
		+ PackedExtension<Tower::B1>
		+ PackedExtension<Tower::B8>
		+ PackedExtension<Tower::B16>
		+ PackedExtension<Tower::B32>
		+ PackedExtension<Tower::B64>
		+ PackedExtension<Tower::B128>,
{
	fn n_vars(&self) -> usize {
		match self {
			TowerRingSwitchEqInd::B1(rs_eq) => rs_eq.n_vars(),
			TowerRingSwitchEqInd::B8(rs_eq) => rs_eq.n_vars(),
			TowerRingSwitchEqInd::B16(rs_eq) => rs_eq.n_vars(),
			TowerRingSwitchEqInd::B32(rs_eq) => rs_eq.n_vars(),
			TowerRingSwitchEqInd::B64(rs_eq) => rs_eq.n_vars(),
			TowerRingSwitchEqInd::B128(rs_eq) => rs_eq.n_vars(),
		}
	}

	#[allow(dead_code)]
	pub fn new(
		tower_height: usize,
		r_evals: Vec<Tower::B128>,
		r_mixing_challenges: Vec<Tower::B128>,
	) -> Result<Self, Error> {
		let tower_rs_eq_id = match tower_height {
			0 => TowerRingSwitchEqInd::B1(RingSwitchEqInd::<Tower::B1, _>::new(
				r_evals,
				r_mixing_challenges,
			)?),
			3 => TowerRingSwitchEqInd::B8(RingSwitchEqInd::<Tower::B8, _>::new(
				r_evals,
				r_mixing_challenges,
			)?),
			4 => TowerRingSwitchEqInd::B16(RingSwitchEqInd::<Tower::B16, _>::new(
				r_evals,
				r_mixing_challenges,
			)?),
			5 => TowerRingSwitchEqInd::B32(RingSwitchEqInd::<Tower::B32, _>::new(
				r_evals,
				r_mixing_challenges,
			)?),
			6 => TowerRingSwitchEqInd::B64(RingSwitchEqInd::<Tower::B64, _>::new(
				r_evals,
				r_mixing_challenges,
			)?),
			7 => TowerRingSwitchEqInd::B128(RingSwitchEqInd::<Tower::B128, _>::new(
				r_evals,
				r_mixing_challenges,
			)?),
			_ => Err(Error::InvalidTowerHeight {
				actual: tower_height,
			})?,
		};
		Ok(tower_rs_eq_id)
	}

	#[allow(dead_code)]
	pub fn multilinear_extension<
		P: PackedFieldIndexable<Scalar = Tower::B128>,
		Backend: ComputationBackend,
	>(
		&self,
		backend: &Backend,
	) -> Result<MultilinearExtension<P, Backend::Vec<P>>, Error> {
		match self {
			TowerRingSwitchEqInd::B1(rs_eq) => rs_eq.multilinear_extension(backend),
			TowerRingSwitchEqInd::B8(rs_eq) => rs_eq.multilinear_extension(backend),
			TowerRingSwitchEqInd::B16(rs_eq) => rs_eq.multilinear_extension(backend),
			TowerRingSwitchEqInd::B32(rs_eq) => rs_eq.multilinear_extension(backend),
			TowerRingSwitchEqInd::B64(rs_eq) => rs_eq.multilinear_extension(backend),
			TowerRingSwitchEqInd::B128(rs_eq) => rs_eq.multilinear_extension(backend),
		}
	}

	fn evaluate(&self, query: &[Tower::B128]) -> Result<Tower::B128, Error> {
		match self {
			TowerRingSwitchEqInd::B1(rs_eq) => rs_eq.evaluate(query),
			TowerRingSwitchEqInd::B8(rs_eq) => rs_eq.evaluate(query),
			TowerRingSwitchEqInd::B16(rs_eq) => rs_eq.evaluate(query),
			TowerRingSwitchEqInd::B32(rs_eq) => rs_eq.evaluate(query),
			TowerRingSwitchEqInd::B64(rs_eq) => rs_eq.evaluate(query),
			TowerRingSwitchEqInd::B128(rs_eq) => rs_eq.evaluate(query),
		}
	}
}

impl<Tower> MultivariatePoly<Tower::B128> for TowerRingSwitchEqInd<Tower>
where
	Tower: TowerFamily + Debug,
	Tower::B128: PackedField<Scalar = Tower::B128>
		+ PackedExtension<Tower::B1>
		+ PackedExtension<Tower::B8>
		+ PackedExtension<Tower::B16>
		+ PackedExtension<Tower::B32>
		+ PackedExtension<Tower::B64>
		+ PackedExtension<Tower::B128>,
{
	fn n_vars(&self) -> usize {
		self.n_vars()
	}

	fn degree(&self) -> usize {
		self.n_vars()
	}

	fn evaluate(&self, query: &[Tower::B128]) -> Result<Tower::B128, Error> {
		// query is typically going to be `r_sumcheck_challenges`
		let n_vars = MultivariatePoly::<Tower::B128>::n_vars(self);
		if query.len() != n_vars {
			bail!(Error::IncorrectQuerySize { expected: n_vars });
		};

		self.evaluate(query)
	}

	fn binary_tower_level(&self) -> usize {
		Tower::B128::TOWER_LEVEL
	}
}

/// This struct provides functionality for the multilinear function $A$ from [DP24] Section 5.
///
/// The function $A$ is $\ell':= \ell - \kappa$-variate and depends on the last $\ell'$ coordinates
/// of the evaluation point as well as the $\kappa$ mixing challenges. The struct takes as generics both
/// a small and a big field.
///
/// [DP24]: <https://eprint.iacr.org/2024/504>
#[derive(Debug)]
pub struct RingSwitchEqInd<FS, F>
where
	FS: Field,
	F: ExtensionField<FS>,
{
	n_vars: usize,
	r_evals: Vec<F>, // r_{\kappa}, \ldots, r_{\ell-1} (in particular, we forget about r_0, \ldots, r_{\kappa-1})
	r_mixing_challenges: Vec<F>, // r''_0, \ldots, r''_{\kappa-1}
	_phantom: PhantomData<FS>,
}

impl<FS, F> RingSwitchEqInd<FS, F>
where
	FS: Field,
	F: ExtensionField<FS> + PackedField<Scalar = F> + PackedExtension<FS>,
{
	pub fn new(r_evals: Vec<F>, r_mixing_challenges: Vec<F>) -> Result<Self, Error> {
		let n_vars = r_evals.len();

		if r_mixing_challenges.len() != <TensorAlgebra<FS, F>>::kappa() {
			bail!(Error::RingSwitchWrongLength {
				expected: <TensorAlgebra<FS, F>>::kappa(),
				actual: r_mixing_challenges.len()
			});
		}

		Ok(Self {
			n_vars,
			r_evals,
			r_mixing_challenges,
			_phantom: PhantomData,
		})
	}

	#[instrument("RingSwitchEqInd::multilinear_extension", skip_all, level = "trace")]
	pub fn multilinear_extension<P, Backend>(
		&self,
		backend: &Backend,
	) -> Result<MultilinearExtension<P, Backend::Vec<P>>, Error>
	where
		P: PackedFieldIndexable<Scalar = F>,
		Backend: ComputationBackend,
	{
		let r_evals = &self.r_evals;
		let r_mixing_challenges = &self.r_mixing_challenges;
		let expanded_mixing_coeffs = backend.multilinear_query(r_mixing_challenges)?;
		let mut evals = backend.tensor_product_full_query(r_evals)?;
		P::unpack_scalars_mut(&mut evals)
			.par_iter_mut()
			.for_each(|val| {
				let vert = *val;
				*val = inner_product_unchecked(
					expanded_mixing_coeffs.expansion().iter().copied(),
					ExtensionField::<FS>::iter_bases(&vert),
				);
			});
		Ok(MultilinearExtension::from_values_generic(evals)?)
	}
}

impl<FS, F> MultivariatePoly<F> for RingSwitchEqInd<FS, F>
where
	FS: TowerField,
	F: ExtensionField<FS> + PackedField<Scalar = F> + PackedExtension<FS> + TowerField,
{
	fn n_vars(&self) -> usize {
		self.n_vars
	}

	fn degree(&self) -> usize {
		self.n_vars
	}

	fn evaluate(&self, query: &[F]) -> Result<F, Error> {
		// query is typically going to be `r_sumcheck_challenges`
		let n_vars = MultivariatePoly::<F>::n_vars(self);
		if query.len() != n_vars {
			bail!(Error::IncorrectQuerySize { expected: n_vars });
		};
		let r_evals = &self.r_evals;
		let r_mixing_challenges = &self.r_mixing_challenges;

		let tensor_eval = iter::zip(r_evals.iter().copied(), query.iter().copied()).fold(
			TensorAlgebra::one(),
			|eval, (vert_i, hztl_i)| {
				// This formula is specific to characteristic 2 fields
				// Here we know that $h v + (1 - h) (1 - v) = 1 + h + v$.
				let vert_scaled = eval.clone().scale_vertical(vert_i);
				let hztl_scaled = eval.clone().scale_horizontal(hztl_i);
				eval + &vert_scaled + &hztl_scaled
			},
		);
		// Use the portable CPU backend because the size of the hypercube is small.
		let backend = make_portable_backend();
		let expanded_mixing_coeffs = &backend
			.tensor_product_full_query(r_mixing_challenges)
			.expect("F extension degree is less than 2^31");
		let folded_eval = inner_product_unchecked::<F, _>(
			tensor_eval.transpose().vertical_elems().iter().copied(),
			expanded_mixing_coeffs.iter().copied(),
		);
		Ok(folded_eval)
	}

	// realistically this will be 7.
	fn binary_tower_level(&self) -> usize {
		F::TOWER_LEVEL
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::tower::{self, AESTowerFamily};
	use binius_field::{BinaryField128b, BinaryField8b};
	use iter::repeat_with;
	use rand::{prelude::StdRng, SeedableRng};

	#[test]
	fn test_ring_switch_eq_ind() {
		type FS = BinaryField8b;
		type F = BinaryField128b;
		let kappa = <TensorAlgebra<FS, F>>::kappa();
		let ell = 10;
		let mut rng = StdRng::seed_from_u64(0);

		let n_vars = ell - kappa;
		let r_evals = repeat_with(|| <F as Field>::random(&mut rng))
			.take(n_vars)
			.collect::<Vec<_>>();

		let r_mixing_challenges = repeat_with(|| <F as Field>::random(&mut rng))
			.take(kappa)
			.collect::<Vec<_>>();
		let backend = make_portable_backend();

		let r_sumcheck_challenges = repeat_with(|| <F as Field>::random(&mut rng))
			.take(n_vars)
			.collect::<Vec<_>>();

		let rs_eq =
			RingSwitchEqInd::<FS, _>::new(r_evals.clone(), r_mixing_challenges.clone()).unwrap();

		let val1 = rs_eq.evaluate(&r_sumcheck_challenges).unwrap();

		let partial_evals = rs_eq.multilinear_extension::<F, _>(&backend).unwrap();
		let val2 = partial_evals
			.evaluate(
				&backend
					.multilinear_query::<F>(&r_sumcheck_challenges)
					.unwrap(),
			)
			.unwrap();

		assert_eq!(val1, val2);
	}

	#[test]
	fn test_tower_ring_switch_eq_ind() {
		type F = <tower::AESTowerFamily as tower::TowerFamily>::B128;
		let tower_height = 4;
		type FS = <tower::AESTowerFamily as tower::TowerFamily>::B16;
		let kappa = 7 - tower_height;
		let ell = 10;
		let mut rng = StdRng::seed_from_u64(0);

		let n_vars = ell - kappa;
		let r_evals = repeat_with(|| <F as Field>::random(&mut rng))
			.take(n_vars)
			.collect::<Vec<_>>();

		let r_mixing_challenges = repeat_with(|| <F as Field>::random(&mut rng))
			.take(kappa)
			.collect::<Vec<_>>();

		let tower_rs_eq = TowerRingSwitchEqInd::<AESTowerFamily>::new(
			tower_height,
			r_evals.clone(),
			r_mixing_challenges.clone(),
		)
		.unwrap();

		let backend = make_portable_backend();

		let r_sumcheck_challenges = repeat_with(|| <F as Field>::random(&mut rng))
			.take(n_vars)
			.collect::<Vec<_>>();

		let rs_eq: RingSwitchEqInd<FS, F> =
			RingSwitchEqInd::new(r_evals.clone(), r_mixing_challenges.clone()).unwrap();

		let val1 = tower_rs_eq.evaluate(&r_sumcheck_challenges).unwrap();
		// we run a similar test to our usual ring_switch_eq_ind, where we first build the `MultilinearExtension` and
		// then run `.evaluate()`.
		let partial_evals: MultilinearExtension<F> = rs_eq.multilinear_extension(&backend).unwrap();
		let val2 = partial_evals
			.evaluate(
				&backend
					.multilinear_query::<F>(&r_sumcheck_challenges)
					.unwrap(),
			)
			.unwrap();

		assert_eq!(val1, val2);
	}
}