Skip to content

Commit

Permalink
Merge pull request #10 from taikoxyz/fix-0-poly
Browse files Browse the repository at this point in the history
fix poly degree 0 underflow
  • Loading branch information
smtmfft authored Oct 22, 2023
2 parents 9eaccbb + 43d1379 commit fb69aa2
Show file tree
Hide file tree
Showing 34 changed files with 225 additions and 155 deletions.
2 changes: 1 addition & 1 deletion halo2_gadgets/benches/poseidon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl<const WIDTH: usize, const RATE: usize> Spec<Fp, WIDTH, RATE> for MySpec<WID
}

fn sbox(val: Fp) -> Fp {
val.pow_vartime(&[5])
val.pow_vartime([5])
}

fn secure_mds() -> usize {
Expand Down
12 changes: 6 additions & 6 deletions halo2_gadgets/benches/sha256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,18 @@ fn bench(name: &str, k: u32, c: &mut Criterion) {

// Initialize the polynomial commitment parameters
let params_path = Path::new("./benches/sha256_assets/sha256_params");
if File::open(&params_path).is_err() {
if File::open(params_path).is_err() {
let params: ParamsIPA<EqAffine> = ParamsIPA::new(k);
let mut buf = Vec::new();

params.write(&mut buf).expect("Failed to write params");
let mut file = File::create(&params_path).expect("Failed to create sha256_params");
let mut file = File::create(params_path).expect("Failed to create sha256_params");

file.write_all(&buf[..])
.expect("Failed to write params to file");
}

let params_fs = File::open(&params_path).expect("couldn't load sha256_params");
let params_fs = File::open(params_path).expect("couldn't load sha256_params");
let params: ParamsIPA<EqAffine> =
ParamsIPA::read::<_>(&mut BufReader::new(params_fs)).expect("Failed to read params");

Expand All @@ -128,7 +128,7 @@ fn bench(name: &str, k: u32, c: &mut Criterion) {

// Create a proof
let proof_path = Path::new("./benches/sha256_assets/sha256_proof");
if File::open(&proof_path).is_err() {
if File::open(proof_path).is_err() {
let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]);
create_proof::<IPACommitmentScheme<_>, ProverIPA<_>, _, _, _, _>(
&params,
Expand All @@ -140,11 +140,11 @@ fn bench(name: &str, k: u32, c: &mut Criterion) {
)
.expect("proof generation should not fail");
let proof: Vec<u8> = transcript.finalize();
let mut file = File::create(&proof_path).expect("Failed to create sha256_proof");
let mut file = File::create(proof_path).expect("Failed to create sha256_proof");
file.write_all(&proof[..]).expect("Failed to write proof");
}

let mut proof_fs = File::open(&proof_path).expect("couldn't load sha256_proof");
let mut proof_fs = File::open(proof_path).expect("couldn't load sha256_proof");
let mut proof = Vec::<u8>::new();
proof_fs
.read_to_end(&mut proof)
Expand Down
12 changes: 6 additions & 6 deletions halo2_gadgets/src/ecc/chip/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn compute_window_table<C: CurveAffine>(base: C, num_windows: usize) -> Vec<[C;
.map(|k| {
// scalar = (k+2)*(8^w)
let scalar = C::Scalar::from(k as u64 + 2)
* C::Scalar::from(H as u64).pow(&[w as u64, 0, 0, 0]);
* C::Scalar::from(H as u64).pow([w as u64, 0, 0, 0]);
(base * scalar).to_affine()
})
.collect::<ArrayVec<C, H>>()
Expand All @@ -62,14 +62,14 @@ fn compute_window_table<C: CurveAffine>(base: C, num_windows: usize) -> Vec<[C;
// For the last window, we compute [k * (2^3)^w - sum]B, where sum is defined
// as sum = \sum_{j = 0}^{`num_windows - 2`} 2^{3j+1}
let sum = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, j| {
acc + C::Scalar::from(2).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * j as u64 + 1, 0, 0, 0])
acc + C::Scalar::from(2).pow([FIXED_BASE_WINDOW_SIZE as u64 * j as u64 + 1, 0, 0, 0])
});
window_table.push(
(0..H)
.map(|k| {
// scalar = k * (2^3)^w - sum, where w = `num_windows - 1`
let scalar = C::Scalar::from(k as u64)
* C::Scalar::from(H as u64).pow(&[(num_windows - 1) as u64, 0, 0, 0])
* C::Scalar::from(H as u64).pow([(num_windows - 1) as u64, 0, 0, 0])
- sum;
(base * scalar).to_affine()
})
Expand Down Expand Up @@ -197,7 +197,7 @@ pub fn test_lagrange_coeffs<C: CurveAffine>(base: C, num_windows: usize) {
// Compute the actual x-coordinate of the multiple [(k+2)*(8^w)]B.
let point = base
* C::Scalar::from(bits as u64 + 2)
* C::Scalar::from(H as u64).pow(&[idx as u64, 0, 0, 0]);
* C::Scalar::from(H as u64).pow([idx as u64, 0, 0, 0]);
let x = *point.to_affine().coordinates().unwrap().x();

// Check that the interpolated x-coordinate matches the actual one.
Expand All @@ -214,10 +214,10 @@ pub fn test_lagrange_coeffs<C: CurveAffine>(base: C, num_windows: usize) {
// Compute the actual x-coordinate of the multiple [k * (8^84) - offset]B,
// where offset = \sum_{j = 0}^{83} 2^{3j+1}
let offset = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, w| {
acc + C::Scalar::from(2).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0])
acc + C::Scalar::from(2).pow([FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0])
});
let scalar = C::Scalar::from(bits as u64)
* C::Scalar::from(H as u64).pow(&[(num_windows - 1) as u64, 0, 0, 0])
* C::Scalar::from(H as u64).pow([(num_windows - 1) as u64, 0, 0, 0])
- offset;
let point = base * scalar;
let x = *point.to_affine().coordinates().unwrap().x();
Expand Down
8 changes: 4 additions & 4 deletions halo2_gadgets/src/ecc/chip/mul_fixed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ impl<FixedPoints: super::FixedPoints<pallas::Affine>> Config<FixedPoints> {
base: &F,
) -> Result<NonIdentityEccPoint, Error> {
// `scalar = [(k_w + 2) ⋅ 8^w]
let scalar = k.map(|k| (k + *TWO_SCALAR) * (*H_SCALAR).pow(&[w as u64, 0, 0, 0]));
let scalar = k.map(|k| (k + *TWO_SCALAR) * (*H_SCALAR).pow([w as u64, 0, 0, 0]));

self.process_window::<_, NUM_WINDOWS>(region, offset, w, k_usize, scalar, base)
}
Expand All @@ -389,12 +389,12 @@ impl<FixedPoints: super::FixedPoints<pallas::Affine>> Config<FixedPoints> {

// offset_acc = \sum_{j = 0}^{NUM_WINDOWS - 2} 2^{FIXED_BASE_WINDOW_SIZE*j + 1}
let offset_acc = (0..(NUM_WINDOWS - 1)).fold(pallas::Scalar::zero(), |acc, w| {
acc + (*TWO_SCALAR).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0])
acc + (*TWO_SCALAR).pow([FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0])
});

// `scalar = [k * 8^(NUM_WINDOWS - 1) - offset_acc]`.
let scalar = scalar.windows_field()[scalar.windows_field().len() - 1]
.map(|k| k * (*H_SCALAR).pow(&[(NUM_WINDOWS - 1) as u64, 0, 0, 0]) - offset_acc);
.map(|k| k * (*H_SCALAR).pow([(NUM_WINDOWS - 1) as u64, 0, 0, 0]) - offset_acc);

self.process_window::<_, NUM_WINDOWS>(
region,
Expand Down Expand Up @@ -490,7 +490,7 @@ impl ScalarFixed {
.by_vals()
.take(FIXED_BASE_WINDOW_SIZE)
.rev()
.fold(0, |acc, b| 2 * acc + if b { 1 } else { 0 })
.fold(0, |acc, b| 2 * acc + usize::from(b))
})
})
.collect::<Vec<_>>()
Expand Down
6 changes: 3 additions & 3 deletions halo2_gadgets/src/poseidon/pow5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ impl<F: Field, const WIDTH: usize> Pow5State<F, WIDTH> {
.value()
.map(|v| *v + config.round_constants[round][idx])
});
let r: Value<Vec<F>> = q.map(|q| q.map(|q| q.pow(&config.alpha))).collect();
let r: Value<Vec<F>> = q.map(|q| q.map(|q| q.pow(config.alpha))).collect();
let m = &config.m_reg;
let state = m.iter().map(|m_i| {
r.as_ref().map(|r| {
Expand All @@ -470,7 +470,7 @@ impl<F: Field, const WIDTH: usize> Pow5State<F, WIDTH> {
let p: Value<Vec<_>> = self.0.iter().map(|word| word.0.value().cloned()).collect();

let r: Value<Vec<_>> = p.map(|p| {
let r_0 = (p[0] + config.round_constants[round][0]).pow(&config.alpha);
let r_0 = (p[0] + config.round_constants[round][0]).pow(config.alpha);
let r_i = p[1..]
.iter()
.enumerate()
Expand Down Expand Up @@ -510,7 +510,7 @@ impl<F: Field, const WIDTH: usize> Pow5State<F, WIDTH> {
}

let r_mid: Value<Vec<_>> = p_mid.map(|p| {
let r_0 = (p[0] + config.round_constants[round + 1][0]).pow(&config.alpha);
let r_0 = (p[0] + config.round_constants[round + 1][0]).pow(config.alpha);
let r_i = p[1..]
.iter()
.enumerate()
Expand Down
4 changes: 2 additions & 2 deletions halo2_gadgets/src/poseidon/primitives/p128pow5t3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl Spec<Fp, 3, 2> for P128Pow5T3 {
}

fn sbox(val: Fp) -> Fp {
val.pow_vartime(&[5])
val.pow_vartime([5])
}

fn secure_mds() -> usize {
Expand All @@ -48,7 +48,7 @@ impl Spec<Fq, 3, 2> for P128Pow5T3 {
}

fn sbox(val: Fq) -> Fq {
val.pow_vartime(&[5])
val.pow_vartime([5])
}

fn secure_mds() -> usize {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub fn get_round_row(round_idx: RoundIdx) -> usize {
RoundIdx::Init => 0,
RoundIdx::Main(MainRoundIdx(idx)) => {
assert!(idx < 64);
(idx as usize) * SUBREGION_MAIN_WORD
idx * SUBREGION_MAIN_WORD
}
}
}
Expand Down Expand Up @@ -783,7 +783,7 @@ impl CompressionConfig {
|| "h_prime_carry",
a_9,
row + 1,
|| h_prime_carry.map(|value| pallas::Base::from(value as u64)),
|| h_prime_carry.map(pallas::Base::from),
)?;

let h_prime: Value<[bool; 32]> = h_prime.map(|w| i2lebsp(w.into()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,17 @@ pub fn get_word_row(word_idx: usize) -> usize {
if word_idx == 0 {
0
} else if (1..=13).contains(&word_idx) {
SUBREGION_0_ROWS + SUBREGION_1_WORD * (word_idx - 1) as usize
SUBREGION_0_ROWS + SUBREGION_1_WORD * (word_idx - 1)
} else if (14..=48).contains(&word_idx) {
SUBREGION_0_ROWS + SUBREGION_1_ROWS + SUBREGION_2_WORD * (word_idx - 14) + 1
} else if (49..=61).contains(&word_idx) {
SUBREGION_0_ROWS
+ SUBREGION_1_ROWS
+ SUBREGION_2_ROWS
+ SUBREGION_3_WORD * (word_idx - 49) as usize
SUBREGION_0_ROWS + SUBREGION_1_ROWS + SUBREGION_2_ROWS + SUBREGION_3_WORD * (word_idx - 49)
} else {
SUBREGION_0_ROWS
+ SUBREGION_1_ROWS
+ SUBREGION_2_ROWS
+ SUBREGION_3_ROWS
+ DECOMPOSE_0_ROWS * (word_idx - 62) as usize
+ DECOMPOSE_0_ROWS * (word_idx - 62)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ impl MessageScheduleConfig {
|| format!("carry_{}", new_word_idx),
a_9,
get_word_row(new_word_idx - 16) + 1,
|| carry.map(|carry| pallas::Base::from(carry as u64)),
|| carry.map(pallas::Base::from),
)?;
let (word, halves) = self.assign_word_and_halves(region, word, new_word_idx)?;
w.push(MessageWord(word));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl MessageScheduleConfig {
|| format!("carry_{}", new_word_idx),
a_9,
get_word_row(new_word_idx - 16) + 1,
|| carry.map(|carry| pallas::Base::from(carry as u64)),
|| carry.map(pallas::Base::from),
)?;
let (word, halves) = self.assign_word_and_halves(region, word, new_word_idx)?;
w.push(MessageWord(word));
Expand Down
2 changes: 1 addition & 1 deletion halo2_gadgets/src/sha256/table16/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ pub fn sum_with_carry(words: Vec<(Value<u16>, Value<u16>)>) -> (Value<u32>, Valu
sum_lo.zip(sum_hi).map(|(lo, hi)| lo + (1 << 16) * hi)
};

let carry = sum.map(|sum| (sum >> 32) as u64);
let carry = sum.map(|sum| (sum >> 32));
let sum = sum.map(|sum| sum as u32);

(sum, carry)
Expand Down
2 changes: 1 addition & 1 deletion halo2_gadgets/src/sinsemilla.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ where
// Each message piece must have at most `floor(C::Base::CAPACITY / K)` words.
// This ensures that the all-ones bitstring is canonical in the field.
let piece_max_num_words = C::Base::CAPACITY as usize / K;
assert!(num_words <= piece_max_num_words as usize);
assert!(num_words <= piece_max_num_words);

// Closure to parse a bitstring (little-endian) into a base field element.
let to_base_field = |bits: &[Value<bool>]| -> Value<C::Base> {
Expand Down
2 changes: 1 addition & 1 deletion halo2_proofs/benches/commit_zk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn rand_poly_par(mut rng: ChaCha20Rng, domain: usize) -> Vec<Scalar> {
// Sample a random polynomial of degree n - 1
let n_threads = current_num_threads();
let n = 1usize << domain;
let n_chunks = n_threads + if n % n_threads != 0 { 1 } else { 0 };
let n_chunks = n_threads + usize::from(n % n_threads != 0);
let mut rand_vec = vec![Scalar::zero(); n];

let mut thread_seeds: Vec<ChaCha20Rng> = (0..n_chunks)
Expand Down
12 changes: 7 additions & 5 deletions halo2_proofs/benches/fft.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#[macro_use]
extern crate criterion;

use halo2_proofs::{arithmetic::best_fft, poly::EvaluationDomain};
use group::ff::Field;
use halo2_proofs::{arithmetic::best_fft, poly::EvaluationDomain};
use halo2curves::bn256::Fr as Scalar;

use criterion::{BenchmarkId, Criterion};
Expand All @@ -12,16 +12,18 @@ fn criterion_benchmark(c: &mut Criterion) {
let j = 5;
let mut group = c.benchmark_group("fft");
for k in 3..19 {
let domain = EvaluationDomain::new(j,k);
let domain = EvaluationDomain::new(j, k);
let omega = domain.get_omega();
let l = 1<<k;
let l = 1 << k;
let data = domain.get_fft_data(l);

group.bench_function(BenchmarkId::new("k", k), |b| {
let mut a = (0..(1 << k)).map(|_| Scalar::random(OsRng)).collect::<Vec<_>>();
let mut a = (0..(1 << k))
.map(|_| Scalar::random(OsRng))
.collect::<Vec<_>>();

b.iter(|| {
best_fft(&mut a, omega, k as u32, data, false);
best_fft(&mut a, omega, k, data, false);
});
});
}
Expand Down
14 changes: 4 additions & 10 deletions halo2_proofs/src/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ pub fn best_fft<Scalar: Field, G: FftGroup<Scalar>>(

/// Convert coefficient bases group elements to lagrange basis by inverse FFT.
pub fn g_to_lagrange<C: CurveAffine>(g_projective: Vec<C::Curve>, k: u32) -> Vec<C> {
let n_inv = C::Scalar::TWO_INV.pow_vartime(&[k as u64, 0, 0, 0]);
let n_inv = C::Scalar::TWO_INV.pow_vartime([k as u64, 0, 0, 0]);
let omega = C::Scalar::ROOT_OF_UNITY;
let mut omega_inv = C::Scalar::ROOT_OF_UNITY_INV;
for _ in k..C::Scalar::S {
Expand All @@ -221,13 +221,7 @@ pub fn g_to_lagrange<C: CurveAffine>(g_projective: Vec<C::Curve>, k: u32) -> Vec
let n = g_lagrange_projective.len();
let fft_data = FFTData::new(n, omega, omega_inv);

best_fft(
&mut g_lagrange_projective,
omega_inv,
k,
&fft_data,
false,
);
best_fft(&mut g_lagrange_projective, omega_inv, k, &fft_data, false);
parallelize(&mut g_lagrange_projective, |g, _| {
for g in g.iter_mut() {
*g *= n_inv;
Expand Down Expand Up @@ -265,7 +259,7 @@ pub fn eval_polynomial<F: Field>(poly: &[F], point: F) -> F {
{
scope.spawn(move |_| {
let start = chunk_idx * chunk_size;
out[0] = evaluate(poly, point) * point.pow_vartime(&[start as u64, 0, 0, 0]);
out[0] = evaluate(poly, point) * point.pow_vartime([start as u64, 0, 0, 0]);
});
}
});
Expand Down Expand Up @@ -316,7 +310,7 @@ where
pub fn parallelize<T: Send, F: Fn(&mut [T], usize) + Send + Sync + Clone>(v: &mut [T], f: F) {
let n = v.len();
let num_threads = multicore::current_num_threads();
let mut chunk = (n as usize) / num_threads;
let mut chunk = n / num_threads;
if chunk < num_threads {
chunk = 1;
}
Expand Down
4 changes: 2 additions & 2 deletions halo2_proofs/src/circuit/floor_planner/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ impl FloorPlanner for V1 {

// - Determine how many rows our planned circuit will require.
let first_unassigned_row = column_allocations
.iter()
.map(|(_, a)| a.unbounded_interval_start())
.values()
.map(|a| a.unbounded_interval_start())
.max()
.unwrap_or(0);

Expand Down
4 changes: 2 additions & 2 deletions halo2_proofs/src/dev/graph/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ impl CircuitLayout {

root.draw(&Rectangle::new(
[(0, 0), (total_columns, view_bottom)],
&BLACK,
BLACK,
))?;

let draw_region = |root: &DrawingArea<_, _>, top_left, bottom_right| {
Expand All @@ -200,7 +200,7 @@ impl CircuitLayout {
[top_left, bottom_right],
ShapeStyle::from(&GREEN.mix(0.2)).filled(),
))?;
root.draw(&Rectangle::new([top_left, bottom_right], &BLACK))?;
root.draw(&Rectangle::new([top_left, bottom_right], BLACK))?;
Ok(())
};

Expand Down
Loading

0 comments on commit fb69aa2

Please sign in to comment.