Skip to content

Commit

Permalink
Solving some issues with features
Browse files Browse the repository at this point in the history
  • Loading branch information
iquerejeta committed Dec 20, 2024
1 parent 21e14bb commit 3474084
Show file tree
Hide file tree
Showing 22 changed files with 107 additions and 99 deletions.
4 changes: 0 additions & 4 deletions benches/plonk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@ use halo2_proofs::utils::rational::Rational;
use halo2curves::bn256::Bn256;

fn criterion_benchmark(c: &mut Criterion) {
/// This represents an advice column at a certain row in the ConstraintSystem
#[derive(Copy, Clone, Debug)]
pub struct Variable(Column<Advice>, usize);

#[derive(Clone)]
struct PlonkConfig {
a: Column<Advice>,
Expand Down
17 changes: 7 additions & 10 deletions examples/circuit-layout.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
use ff::Field;
use halo2_proofs::utils::rational::Rational;
use halo2_proofs::{
circuit::{Cell, Layouter, Region, SimpleFloorPlanner, Value},
plonk::{Advice, Assigned, Circuit, Column, ConstraintSystem, Error, Fixed, TableColumn},
plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, TableColumn},
poly::Rotation,
};
use halo2curves::pasta::Fp;
use rand_core::OsRng;
use std::marker::PhantomData;

/// This represents an advice column at a certain row in the ConstraintSystem
#[derive(Copy, Clone, Debug)]
pub struct Variable(Column<Advice>, usize);

#[derive(Clone)]
struct PlonkConfig {
a: Column<Advice>,
Expand All @@ -30,10 +27,10 @@ struct PlonkConfig {
trait StandardCs<FF: Field> {
fn raw_multiply<F>(&self, region: &mut Region<FF>, f: F) -> Result<(Cell, Cell, Cell), Error>
where
F: FnMut() -> Value<(Assigned<FF>, Assigned<FF>, Assigned<FF>)>;
F: FnMut() -> Value<(Rational<FF>, Rational<FF>, Rational<FF>)>;
fn raw_add<F>(&self, region: &mut Region<FF>, f: F) -> Result<(Cell, Cell, Cell), Error>
where
F: FnMut() -> Value<(Assigned<FF>, Assigned<FF>, Assigned<FF>)>;
F: FnMut() -> Value<(Rational<FF>, Rational<FF>, Rational<FF>)>;
fn copy(&self, region: &mut Region<FF>, a: Cell, b: Cell) -> Result<(), Error>;
fn lookup_table(&self, layouter: &mut impl Layouter<FF>, values: &[FF]) -> Result<(), Error>;
}
Expand Down Expand Up @@ -64,7 +61,7 @@ impl<FF: Field> StandardCs<FF> for StandardPlonk<FF> {
mut f: F,
) -> Result<(Cell, Cell, Cell), Error>
where
F: FnMut() -> Value<(Assigned<FF>, Assigned<FF>, Assigned<FF>)>,
F: FnMut() -> Value<(Rational<FF>, Rational<FF>, Rational<FF>)>,
{
let mut value = None;
let lhs = region.assign_advice(
Expand Down Expand Up @@ -101,7 +98,7 @@ impl<FF: Field> StandardCs<FF> for StandardPlonk<FF> {
}
fn raw_add<F>(&self, region: &mut Region<FF>, mut f: F) -> Result<(Cell, Cell, Cell), Error>
where
F: FnMut() -> Value<(Assigned<FF>, Assigned<FF>, Assigned<FF>)>,
F: FnMut() -> Value<(Rational<FF>, Rational<FF>, Rational<FF>)>,
{
let mut value = None;
let lhs = region.assign_advice(
Expand Down Expand Up @@ -247,7 +244,7 @@ impl<F: Field> Circuit<F> for MyCircuit<F> {
layouter.assign_region(
|| format!("region_{i}"),
|mut region| {
let a: Value<Assigned<_>> = self.a.into();
let a: Value<Rational<_>> = self.a.into();
let mut a_squared = Value::unknown();
let (a0, _, c0) = cs.raw_multiply(&mut region, || {
a_squared = a.square();
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.76.0
1.80.0
2 changes: 1 addition & 1 deletion src/dev/cost_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ fn run_mock_prover_with_fallback<F: Ord + Field + FromUniformBytes<64>, C: Circu
circuit: &C,
instances: Vec<Vec<F>>,
) -> MockProver<F> {
(5..25)
(1..25)
.find_map(|k| {
panic::catch_unwind(AssertUnwindSafe(|| {
MockProver::run(k, circuit, instances.clone()).unwrap()
Expand Down
11 changes: 6 additions & 5 deletions src/dev/graph.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use ff::Field;
use tabbycat::{AttrList, Edge, GraphBuilder, GraphType, Identity, StmtList};

use crate::utils::rational::Rational;
use crate::{
circuit::Value,
plonk::{
Advice, Any, Assigned, Assignment, Challenge, Circuit, Column, ConstraintSystem, Error,
Fixed, FloorPlanner, Instance, Selector,
Advice, Any, Assignment, Challenge, Circuit, Column, ConstraintSystem, Error, Fixed,
FloorPlanner, Instance, Selector,
},
};

Expand Down Expand Up @@ -123,7 +124,7 @@ impl<F: Field> Assignment<F> for Graph {
) -> Result<(), Error>
where
V: FnOnce() -> Value<VR>,
VR: Into<Assigned<F>>,
VR: Into<Rational<F>>,
A: FnOnce() -> AR,
AR: Into<String>,
{
Expand All @@ -140,7 +141,7 @@ impl<F: Field> Assignment<F> for Graph {
) -> Result<(), Error>
where
V: FnOnce() -> Value<VR>,
VR: Into<Assigned<F>>,
VR: Into<Rational<F>>,
A: FnOnce() -> AR,
AR: Into<String>,
{
Expand All @@ -163,7 +164,7 @@ impl<F: Field> Assignment<F> for Graph {
&mut self,
_: Column<Fixed>,
_: usize,
_: Value<Assigned<F>>,
_: Value<Rational<F>>,
) -> Result<(), Error> {
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions src/dev/graph/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl CircuitLayout {
cs.constants.clone(),
)
.unwrap();
let (cs, selector_polys) = cs.compress_selectors(layout.selectors);
let (cs, selector_polys) = cs.directly_convert_selectors_to_fixed(layout.selectors.clone());
let non_selector_fixed_columns = cs.num_fixed_columns - selector_polys.len();

// Figure out what order to render the columns in.
Expand All @@ -115,7 +115,7 @@ impl CircuitLayout {
let column_index = |cs: &ConstraintSystem<F>, column: RegionColumn| {
let column: Column<Any> = match column {
RegionColumn::Column(col) => col,
RegionColumn::Selector(selector) => cs.selector_map[selector.0].into(),
RegionColumn::Selector(_) => panic!("We shouldn't have selectors by now"),
};
column.index()
+ match column.column_type() {
Expand Down
14 changes: 8 additions & 6 deletions src/dev/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ use crate::{
},
};

use crate::utils::multicore::{
IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator,
ParallelSliceMut,
use rayon::{
iter::{
IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator,
},
slice::ParallelSliceMut,
};

pub mod metadata;
Expand Down Expand Up @@ -912,9 +914,9 @@ impl<F: FromUniformBytes<64> + Ord> MockProver<F> {
cell_values: util::cell_values(
gate,
poly,
&util::load(n, row, &self.cs.fixed_queries, &self.fixed),
&util::load(n, row, &self.cs.advice_queries, &self.advice),
&util::load_instance(
util::load(n, row, &self.cs.fixed_queries, &self.fixed),
util::load(n, row, &self.cs.advice_queries, &self.advice),
util::load_instance(
n,
row,
&self.cs.instance_queries,
Expand Down
8 changes: 4 additions & 4 deletions src/plonk/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1338,10 +1338,10 @@ impl<F: Field> Product<Self> for Expression<F> {
}
}

/// Represents an index into a vector where each entry corresponds to a distinct
/// point that polynomials are queried at.
#[derive(Copy, Clone, Debug)]
pub(crate) struct PointIndex(pub usize);
// /// Represents an index into a vector where each entry corresponds to a distinct
// /// point that polynomials are queried at.
// #[derive(Copy, Clone, Debug)]
// pub(crate) struct PointIndex(pub usize);

/// A "virtual cell" is a PLONK cell that has been queried at a particular relative offset
/// within a custom gate.
Expand Down
7 changes: 2 additions & 5 deletions src/plonk/evaluation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::plonk::{lookup, permutation, Any, ProvingKey};
use crate::poly::commitment::PolynomialCommitmentScheme;
use crate::poly::Basis;
use crate::utils::multicore;
use crate::{
poly::{Coeff, ExtendedLagrangeCoeff, Polynomial, Rotation},
utils::arithmetic::parallelize,
Expand Down Expand Up @@ -171,8 +170,6 @@ pub struct Evaluator<F: PrimeField> {
pub custom_gates: GraphEvaluator<F>,
/// Lookups evalution
pub lookups: Vec<GraphEvaluator<F>>,
/// Shuffle evalution
pub shuffles: Vec<GraphEvaluator<F>>,
}

/// GraphEvaluator
Expand Down Expand Up @@ -313,15 +310,15 @@ impl<F: WithSmallOrderMulGroup<3>> Evaluator<F> {
let mut values = domain.empty_extended();

// Core expression evaluations
let num_threads = multicore::current_num_threads();
let num_threads = rayon::current_num_threads();
for (((advice, instance), lookups), permutation) in advice
.iter()
.zip(instance.iter())
.zip(lookups.iter())
.zip(permutations.iter())
{
// Custom gates
multicore::scope(|scope| {
rayon::scope(|scope| {
let chunk_size = (size + num_threads - 1) / num_threads;
for (thread_idx, values) in values.chunks_mut(chunk_size).enumerate() {
let start = thread_idx * chunk_size;
Expand Down
11 changes: 9 additions & 2 deletions src/plonk/keygen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use super::{
};
use crate::circuit::Value;
use crate::poly::batch_invert_rational;
use crate::poly::commitment::PolynomialCommitmentScheme;
use crate::poly::commitment::{Params, PolynomialCommitmentScheme};
use crate::utils::rational::Rational;
use crate::{poly::EvaluationDomain, utils::arithmetic::parallelize};

Expand Down Expand Up @@ -253,8 +253,15 @@ where
CS: PolynomialCommitmentScheme<F>,
ConcreteCircuit: Circuit<F>,
{
let k = k_from_circuit(circuit);
if params.max_k() < k {
return Err(Error::NotEnoughRowsAvailable {
current_k: params.max_k(),
});
}

let (domain, cs, config) = create_domain::<F, ConcreteCircuit>(
k_from_circuit(circuit),
k,
#[cfg(feature = "circuit-params")]
circuit.params(),
);
Expand Down
20 changes: 9 additions & 11 deletions src/plonk/lookup/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ impl<F: WithSmallOrderMulGroup<3> + Ord> Argument<F> {
/// obtaining A' and S', and
/// - constructs Permuted<C> struct using permuted_input_value = A', and

Check warning on line 44 in src/plonk/lookup/prover.rs

View workflow job for this annotation

GitHub Actions / Intra-doc links

unclosed HTML tag `C`
/// permuted_table_expression = S'.
///
/// The Permuted<C> struct is used to update the Lookup, and is then returned.

Check warning on line 47 in src/plonk/lookup/prover.rs

View workflow job for this annotation

GitHub Actions / Intra-doc links

unclosed HTML tag `C`
#[allow(clippy::too_many_arguments)]
pub(in crate::plonk) fn commit_permuted<
Expand Down Expand Up @@ -230,7 +231,7 @@ impl<F: WithSmallOrderMulGroup<3>> Permuted<F> {
// It can be used for debugging purposes.
{
// While in Lagrange basis, check that product is correctly constructed
let u = (params.n() as usize) - (blinding_factors + 1);
let u = (pk.vk.n() as usize) - (blinding_factors + 1);

// l_0(X) * (1 - z(X)) = 0
assert_eq!(z[0], F::ONE);
Expand All @@ -243,15 +244,15 @@ impl<F: WithSmallOrderMulGroup<3>> Permuted<F> {

let permuted_table_value = &self.permuted_table_expression[i];

left *= &(*beta + permuted_input_value);
left *= &(*gamma + permuted_table_value);
left *= &(beta + permuted_input_value);
left *= &(gamma + permuted_table_value);

let mut right = z[i];
let mut input_term = self.compressed_input_expression[i];
let mut table_term = self.compressed_table_expression[i];

input_term += &(*beta);
table_term += &(*gamma);
input_term += &(beta);
table_term += &(gamma);
right *= &(input_term * &table_term);

assert_eq!(left, right);
Expand Down Expand Up @@ -357,20 +358,17 @@ type ExpressionPair<F> = (Polynomial<F, LagrangeCoeff>, Polynomial<F, LagrangeCo
/// - like values in A' are vertically adjacent to each other; and
/// - the first row in a sequence of like values in A' is the row
/// that has the corresponding value in S'.
///
/// This method returns (A', S') if no errors are encountered.
fn permute_expression_pair<
F: WithSmallOrderMulGroup<3> + Ord,
CS: PolynomialCommitmentScheme<F>,
R: RngCore,
>(
fn permute_expression_pair<F, CS: PolynomialCommitmentScheme<F>, R: RngCore>(
pk: &ProvingKey<F, CS>,
domain: &EvaluationDomain<F>,
mut rng: R,
input_expression: &Polynomial<F, LagrangeCoeff>,
table_expression: &Polynomial<F, LagrangeCoeff>,
) -> Result<ExpressionPair<F>, Error>
where
F: FromUniformBytes<64> + SerdeObject,
F: WithSmallOrderMulGroup<3> + Ord + FromUniformBytes<64> + SerdeObject,
{
let blinding_factors = pk.vk.cs.blinding_factors();
let usable_rows = pk.vk.n() as usize - (blinding_factors + 1);
Expand Down
10 changes: 5 additions & 5 deletions src/plonk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ where
///
/// Writes a curve element according to `format`:
/// - `Processed`: Writes a compressed curve element with coordinates in standard form.
/// Writes a field element in standard form, with endianness specified by the
/// `PrimeField` implementation.
/// Writes a field element in standard form, with endianness specified by the
/// `PrimeField` implementation.
/// - Otherwise: Writes an uncompressed curve element with coordinates in Montgomery form
/// Writes a field element into raw bytes in its internal Montgomery representation,
/// WITHOUT performing the expensive Montgomery reduction.
/// Writes a field element into raw bytes in its internal Montgomery representation,
/// WITHOUT performing the expensive Montgomery reduction.
pub fn write<W: io::Write>(&self, writer: &mut W, format: SerdeFormat) -> io::Result<()> {
// Version byte that will be checked on read.
writer.write_all(&[VERSION])?;
Expand Down Expand Up @@ -337,7 +337,7 @@ where
/// Writes a curve element according to `format`:
/// - `Processed`: Writes a compressed curve element with coordinates in standard form.
/// Writes a field element in standard form, with endianness specified by the
/// `PrimeField` implementation.
/// `PrimeField` implementation.
/// - Otherwise: Writes an uncompressed curve element with coordinates in Montgomery form
/// Writes a field element into raw bytes in its internal Montgomery representation,
/// WITHOUT performing the expensive Montgomery reduction.
Expand Down
21 changes: 12 additions & 9 deletions src/plonk/permutation/keygen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ use crate::{
};

#[cfg(feature = "thread-safe-region")]
use crate::utils::multicore::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator};
use {
ff::PrimeField,
rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator},
};

#[cfg(not(feature = "thread-safe-region"))]
use crate::utils::multicore::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};

use crate::poly::commitment::PolynomialCommitmentScheme;
use rayon::iter::IntoParallelRefMutIterator;
Expand Down Expand Up @@ -239,8 +242,6 @@ impl Assembly {
/// Builds the ordered mapping of the cycles.
/// This will only get executed once.
pub fn build_ordered_mapping(&mut self) {
use crate::multicore::IntoParallelRefMutIterator;

// will only get called once
if self.ordered_cycles.is_empty() && !self.cycles.is_empty() {
self.ordered_cycles = self
Expand Down Expand Up @@ -281,24 +282,26 @@ impl Assembly {
}
}

pub(crate) fn build_vk<F: PrimeField, CS: PolynomialCommitmentScheme<F>>(
pub(crate) fn build_vk<
F: PrimeField + WithSmallOrderMulGroup<3>,
CS: PolynomialCommitmentScheme<F>,
>(
&mut self,
params: &CS::VerifierParameters,
params: &CS::Parameters,
domain: &EvaluationDomain<F>,
p: &Argument,
) -> VerifyingKey<F, CS> {
self.build_ordered_mapping();
build_vk(params, domain, p, |i, j| self.mapping_at_idx(i, j))
}

pub(crate) fn build_pk<F: PrimeField, CS: PolynomialCommitmentScheme<F>>(
pub(crate) fn build_pk<F: PrimeField + WithSmallOrderMulGroup<3>>(
&mut self,
params: &CS::Parameters,
domain: &EvaluationDomain<F>,
p: &Argument,
) -> ProvingKey<F> {
self.build_ordered_mapping();
build_pk(params, domain, p, |i, j| self.mapping_at_idx(i, j))
build_pk(domain, p, |i, j| self.mapping_at_idx(i, j))
}

/// Returns columns that participate in the permutation argument.
Expand Down
Loading

0 comments on commit 3474084

Please sign in to comment.