Skip to content

Commit

Permalink
[chore] Optimize reduce_32 (#918)
Browse files Browse the repository at this point in the history
* Optimize reduce_32

* safety: static compiler CastFV max_bits bound

* opt: handle equal bits case

---------

Co-authored-by: Jonathan Wang <[email protected]>
  • Loading branch information
nyunyunyunyu and jonathanpwang authored Dec 3, 2024
1 parent fe7d376 commit 187ecd6
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
2 changes: 1 addition & 1 deletion extensions/native/compiler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ rand = "0.8.5"
axvm-circuit = { workspace = true, features = ["test-utils"] }

[features]
default = ["parallel"]
default = ["parallel", "halo2-compiler"]
halo2-compiler = ["dep:snark-verifier-sdk"]
parallel = ["axvm-circuit/parallel"]
bench-metrics = ["dep:metrics", "axvm-circuit/bench-metrics"]
18 changes: 15 additions & 3 deletions extensions/native/compiler/src/constraints/halo2/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ use axvm_circuit::metrics::cycle_tracker::CycleTracker;
use itertools::Itertools;
use p3_baby_bear::BabyBear;
use p3_bn254_fr::Bn254Fr;
use p3_field::{ExtensionField, PrimeField};
use p3_field::{ExtensionField, PrimeField, PrimeField32};
use snark_verifier_sdk::snark_verifier::{
halo2_base::{
gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip},
gates::{
circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip, RangeInstructions,
},
halo2_proofs::halo2curves::bn256::Fr,
utils::{biguint_to_fe, ScalarField},
Context,
Context, QuantumCell,
},
util::arithmetic::PrimeField as _,
};
Expand Down Expand Up @@ -249,8 +251,18 @@ impl<C: Config + Debug> Halo2ConstraintCompiler<C> {
}
DslIr::CastFV(a, b) => {
let felt = felts[&b.0];
#[allow(clippy::comparison_chain)]
let reduced_felt = if felt.max_bits > BABYBEAR_MAX_BITS {
f_chip.reduce(ctx, felt)
} else if felt.max_bits == BABYBEAR_MAX_BITS {
// Ensure cast is canonical
f_chip.range.check_less_than(
ctx,
felt.value,
QuantumCell::Constant(Fr::from(BabyBear::ORDER_U32 as u64)),
BABYBEAR_MAX_BITS,
);
felt
} else {
felt
};
Expand Down
3 changes: 1 addition & 2 deletions extensions/native/recursion/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ pub fn reduce_32<C: Config>(builder: &mut Builder<C>, vals: &[Felt<C::F>]) -> Va
let mut power = C::N::ONE;
let result: Var<C::N> = builder.eval(C::N::ZERO);
for val in vals.iter() {
let bits = builder.num2bits_f_circuit(*val);
let val = builder.bits2num_v_circuit(&bits);
let val = builder.cast_felt_to_var(*val);
builder.assign(&result, result + val * power);
power *= C::N::from_canonical_usize(1usize << 32);
}
Expand Down

0 comments on commit 187ecd6

Please sign in to comment.