From c7324887c46544f2a77a14e8d81fc2a617d646d5 Mon Sep 17 00:00:00 2001 From: Gabriel Barreto Date: Tue, 20 Oct 2026 22:20:36 +0000 Subject: [PATCH 01/28] Expose mutable lookup slots for direct witness population --- src/lookup.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/lookup.rs b/src/lookup.rs index 6456f9e..43edb19 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -908,6 +908,22 @@ pub struct LookupRowMut<'a, F> { } impl LookupRowMut<'_, F> { + /// Returns mutable views of a slot's multiplicity and full argument buffer. + /// + /// This allows a witness generator to populate arguments directly, without + /// first collecting them into a temporary slice. Fresh builder storage is + /// zeroed; revisiting a slot preserves its existing contents. A negative + /// multiplicity has "pull" semantics, as in [`Self::pull`]. + /// + /// # Panics + /// Panics if `slot` is outside this row's lookup slots. + #[inline] + pub fn slot_mut(&mut self, slot: usize) -> (&mut F, &mut [F]) { + let start = self.arg_offsets[slot]; + let end = self.arg_offsets[slot + 1]; + (&mut self.multiplicities[slot], &mut self.args[start..end]) + } + /// Writes lookup slot `slot` with "push" semantics (adds a claim). /// Fewer arguments than the slot's width leave zero padding. /// @@ -1309,6 +1325,43 @@ mod tests { assert_eq!(a.args, b.args); } + #[test] + fn direct_slots_match_from_rows() { + let f = Val::from_u32; + let expected = LookupValues::from_rows(vec![ + vec![ + Lookup::push(f(2), vec![]), + Lookup::pull(f(3), vec![f(4), f(5)]), + ], + vec![Lookup::empty(), Lookup::push(f(6), vec![f(7)])], + ]); + let mut builder = LookupValues::builder(2, &[0, 2]); + { + let mut rows = builder.rows_mut(); + let (count, args) = rows[0].slot_mut(0); + assert_eq!(*count, Val::ZERO); + assert!(args.is_empty()); + *count = f(2); + let (count, args) = rows[0].slot_mut(1); + *count = -f(3); + args.copy_from_slice(&[f(4), f(5)]); + // A second view exposes the existing buffer, without resetting it. + let (count, args) = rows[0].slot_mut(1); + assert_eq!(*count, -f(3)); + assert_eq!(args, &[f(4), f(5)]); + let (count, args) = rows[1].slot_mut(1); + *count = f(6); + args[0] = f(7); + assert_eq!(args[1], Val::ZERO); + } + let actual = builder.finish(); + assert_eq!(expected.height, actual.height); + assert_eq!(expected.num_lookups, actual.num_lookups); + assert_eq!(expected.arg_offsets, actual.arg_offsets); + assert_eq!(expected.multiplicities, actual.multiplicities); + assert_eq!(expected.args, actual.args); + } + #[test] fn lookup_test() { let (system, key) = system(); From ed65a7c5927df519b6de9df91a3061b99e67697d Mon Sep 17 00:00:00 2001 From: Gabriel Barreto Date: Sat, 31 Oct 2026 18:35:26 +0000 Subject: [PATCH 02/28] Rebuild shape-only lookup witnesses from the committed trace A shape-only lookup witness (`LookupValues::shape_only`) carries dimensions for a prover that derives every lookup message from the committed trace on the device. When device memory pressure keeps a commitment off the device, the CUDA lookup commit takes its direct path, or the prover falls back to the CPU stage-two path, and both read lookup values on the host: with a shape-only witness they hit an assertion and the prover aborted. Those paths now rebuild the omitted values instead. The trace is the retained host trace when the commitment kept one; otherwise it is interpolated from the committed LDE (its evaluations on gH give the coefficients, evaluated back on H), reading only that matrix back from the device. The lookup evaluator, now parallel over rows, derives the values, so proofs are identical to those of a materialized witness. Also make `cuda::configured_device` public for callers resolving the default device, and test that shape-only witnesses prove byte-identically, including preprocessed columns and two-shard batches under both retention policies. Co-Authored-By: Claude Opus 5.5 --- src/batch.rs | 22 ++++++++ src/cuda/mmcs.rs | 79 ++++++++++++++++++++++++++++ src/cuda/mod.rs | 4 +- src/lookup.rs | 40 +++++++++++++- src/prover.rs | 59 +++++++++++++++++++++ src/system.rs | 69 ++++++++++++------------ src/test_circuits/byte_operations.rs | 10 +++- src/types.rs | 20 +++++-- 8 files changed, 262 insertions(+), 41 deletions(-) diff --git a/src/batch.rs b/src/batch.rs index 54b6da7..f357225 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -788,6 +788,28 @@ mod tests { system.verify_batch(®enerated).unwrap(); } + #[test] + fn shape_only_shards_prove_the_same_batch() { + let (system, key) = byte_system(config()); + let expected = system.prove_batch(&key, two_shards(&system), vec![]); + let claims: Vec<_> = two_shards(&system).into_iter().map(|s| s.claims).collect(); + let shape = |shard: usize| { + let witness = two_shards(&system).swap_remove(shard).witness; + SystemWitness { + lookups: witness + .lookups + .iter() + .map(crate::lookup::LookupValues::shape) + .collect(), + traces: witness.traces, + } + }; + for retention in [Retention::Retain, Retention::Regenerate] { + let actual = system.prove_batch_with(&key, &claims, vec![], retention, shape); + assert_eq!(actual.to_bytes().unwrap(), expected.to_bytes().unwrap()); + } + } + #[test] fn positive_proof_of_work_batches_are_reproducible() { // With a grind in every shard's opening, the proof bytes must still diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index 41e7d7f..37ee91c 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -491,7 +491,86 @@ pub struct CudaMmcs { device_id: i32, } +/// The trace a committed LDE extends: the bit-reversed LDE over `gK` starts +/// with the bit-reversed evaluations on `gH`, which interpolate the trace +/// polynomial back onto `H`. Computed on the host, so a device under memory +/// pressure is not asked for transform workspace. +fn trace_from_lde( + lde: &RowMajorMatrix, + log_blowup: usize, +) -> RowMajorMatrix { + use p3_dft::TwoAdicSubgroupDft; + use p3_field::Field; + use p3_matrix::bitrev::BitReversibleMatrix; + let degree = lde.height() >> log_blowup; + let evaluations = lde + .split_rows(degree) + .0 + .as_cow() + .bit_reverse_rows() + .to_row_major_matrix(); + let dft = p3_dft::Radix2DitParallel::::default(); + let coefficients = dft.coset_idft_batch(evaluations, Goldilocks::GENERATOR); + dft.dft_batch(coefficients).to_row_major_matrix() +} + impl CudaMmcs { + /// The stage-one trace of committed matrix `index`, for evaluating the + /// lookups a shape-only witness omitted: the retained host trace when + /// the commitment kept one, otherwise rebuilt from the committed LDE, + /// read back from the device if necessary. Only that matrix is read and + /// nothing is cached in `data`. + pub(crate) fn committed_trace( + &self, + data: &CudaMmcsData>, + index: usize, + log_blowup: usize, + ) -> RowMajorMatrix { + match data { + CudaMmcsData::Cpu(data) => { + trace_from_lde(self.cpu.get_matrices(data)[index], log_blowup) + } + CudaMmcsData::Hybrid { + resident, + resident_active, + committed_matrices, + deferred_matrices, + retained_traces, + .. + } => { + if let Some(trace) = &retained_traces[index] { + return trace.clone(); + } + if let Some(lde) = committed_matrices[index].get() { + return trace_from_lde(lde, log_blowup); + } + if let Some(lde) = resident[index].as_ref() + && resident_active[index].load(std::sync::atomic::Ordering::Acquire) + { + return trace_from_lde(&lde.to_row_major_matrix(), log_blowup); + } + trace_from_lde( + hybrid_matrix(committed_matrices, deferred_matrices, index), + log_blowup, + ) + } + CudaMmcsData::Cuda { + resident, + committed_matrices, + retained_traces, + .. + } => { + if let Some(trace) = retained_traces.get().and_then(|traces| traces.get(index)) { + return trace.clone(); + } + if let Some(ldes) = committed_matrices.get() { + return trace_from_lde(&ldes[index], log_blowup); + } + trace_from_lde(&resident[index].to_row_major_matrix(), log_blowup) + } + } + } + /// A commitment scheme resident on the given CUDA device. Every kernel /// it launches, allocation it makes and buffer it stages through belongs /// to that device, so several of these in one process can each own a diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 4d12da4..77d5d2e 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -47,7 +47,9 @@ impl Default for CudaDft { } } -pub(crate) fn configured_device() -> i32 { +/// The device a prover uses when none is requested: +/// `MULTI_STARK_CUDA_DEVICE`, otherwise zero. +pub fn configured_device() -> i32 { std::env::var("MULTI_STARK_CUDA_DEVICE").map_or(0, |value| { value .parse() diff --git a/src/lookup.rs b/src/lookup.rs index 43edb19..e83b696 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -602,10 +602,12 @@ impl LookupValues { } } - /// Returns an allocation-free builder; see [`LookupValuesBuilder`]. /// A witness of the right shape with no payload, for a prover that /// derives every lookup message from the committed trace (the CUDA - /// graph path). Reading its multiplicities or arguments panics. + /// graph path). Prover paths that read lookup values on the host + /// instead, such as the fallbacks taken under device memory pressure, + /// first rebuild them from the committed stage-one trace; the proof is + /// identical either way. pub fn shape_only(height: usize, slot_arg_widths: &[usize]) -> Self { let num_lookups = slot_arg_widths.len(); let mut arg_offsets = Vec::with_capacity(num_lookups + 1); @@ -623,6 +625,19 @@ impl LookupValues { } } + /// Whether the multiplicities and arguments are present, as opposed to a + /// [`Self::shape_only`] witness. + pub fn is_materialized(&self) -> bool { + self.materialized + } + + /// The shape-only witness with this witness's dimensions. + #[cfg(test)] + pub(crate) fn shape(&self) -> Self { + let widths: Vec = self.arg_offsets.windows(2).map(|w| w[1] - w[0]).collect(); + Self::shape_only(self.height, &widths) + } + /// Panics unless the witness payload is present. fn require_payload(&self) { assert!( @@ -631,6 +646,7 @@ impl LookupValues { ); } + /// Returns an allocation-free builder; see [`LookupValuesBuilder`]. pub fn builder(height: usize, slot_arg_widths: &[usize]) -> LookupValuesBuilder { LookupValuesBuilder::new(height, slot_arg_widths) } @@ -1372,6 +1388,26 @@ mod tests { system.verify(claim, &proof).unwrap(); } + /// A shape-only witness proves the same bytes as the materialized one: + /// the host lookup path rebuilds the omitted values from the committed + /// stage-one traces. + #[test] + fn shape_only_witness_proves_identically() { + let (system, key) = system(); + let witness = witness(&system); + let shape = SystemWitness { + traces: witness.traces.clone(), + lookups: witness.lookups.iter().map(LookupValues::shape).collect(), + }; + assert!(shape.lookups.iter().all(|l| !l.is_materialized())); + let f = Val::from_u32; + let claim = &[f(0), f(4), f(1)]; + let expected = system.prove(&key, claim, witness); + let actual = system.prove(&key, claim, shape); + assert_eq!(expected.to_bytes().unwrap(), actual.to_bytes().unwrap()); + system.verify(claim, &actual).unwrap(); + } + /// A three-circuit system where the third circuit (`Dead`, its own /// channel, referenced by nothing) gets an empty trace: the prover must /// deactivate it, the proof must carry per-circuit data for the two diff --git a/src/prover.rs b/src/prover.rs index 4bf1f01..10b1999 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -349,6 +349,56 @@ where Val: TwoAdicField, SC::Dft: TwoAdicSubgroupDft>, { + /// A stage-one trace rebuilt from its commitment. The committed LDE holds + /// the trace polynomial's evaluations on a coset `gK`; those on `gH` give + /// its coefficients, which are evaluated back on the trace domain `H`. + /// Only prover paths that must read the lookup values a shape-only + /// witness omitted ([`LookupValues::shape_only`]) rebuild traces. + pub(crate) fn committed_trace( + &self, + data: &PcsData, + index: usize, + degree: usize, + ) -> RowMajorMatrix> { + let pcs = self.config.pcs(); + let coset = pcs + .natural_domain_for_degree(degree) + .create_disjoint_domain(degree); + let evaluations = pcs + .get_evaluations_on_domain(data, index, coset) + .to_row_major_matrix(); + let dft = self.config.dft(); + let coefficients = dft.coset_idft_batch(evaluations, coset.first_point()); + dft.dft_batch(coefficients).to_row_major_matrix() + } + + /// Fills every shape-only lookup witness of the active circuits from the + /// committed stage-one traces, for prover paths that read lookup values + /// on the host. Materialized witnesses pass through unchanged. + fn materialize_lookups( + &self, + data: &PcsData, + active_indices: &[usize], + log_degrees: &[usize], + lookups: Vec>>, + ) -> Vec>> { + lookups + .into_iter() + .enumerate() + .map(|(position, values)| { + if values.is_materialized() { + return values; + } + let _g = tracing::info_span!("stark/materialize_lookups", position).entered(); + let trace = self.committed_trace(data, position, 1 << log_degrees[position]); + crate::system::compute_lookup_values( + &self.circuits[active_indices[position]], + &trace, + ) + }) + .collect() + } + /// Generates a STARK proof for the system with a single claim. /// /// This is a convenience wrapper around [`Self::prove_multiple_claims`]. @@ -564,6 +614,15 @@ where drop(_g); result } else { + // Host paths read every lookup value; derive any a shape-only + // witness omitted from the committed stage-one traces. + drop(lookup_inputs); + let active_lookups = self.materialize_lookups( + &stage_1_trace_data, + &active_indices, + &log_degrees, + active_lookups, + ); let (stage_2_traces, intermediate_accumulators) = self .config .accelerated_lookup_traces( diff --git a/src/system.rs b/src/system.rs index 0923ecb..2f8dc14 100644 --- a/src/system.rs +++ b/src/system.rs @@ -13,6 +13,7 @@ use p3_challenger::CanObserve; use p3_commit::{Pcs, PolynomialSpace}; use p3_field::{BasedVectorSpace, Field, PrimeCharacteristicRing}; use p3_matrix::{Matrix, dense::RowMajorMatrix}; +use p3_maybe_rayon::prelude::*; use crate::config::{Com, PcsData, StarkGenericConfig, Val}; use crate::lookup::LookupValues; @@ -299,7 +300,8 @@ impl SystemWitness { /// Computes a circuit's concrete lookup values by sweeping the compiled /// lookup prefix over each row (with wrap-around for the next-row window). -fn compute_lookup_values( +/// Rows are independent, so they are swept in parallel. +pub(crate) fn compute_lookup_values( circuit: &Circuit, trace: &RowMajorMatrix, ) -> LookupValues { @@ -316,40 +318,41 @@ fn compute_lookup_values( } let preprocessed = circuit.preprocessed.as_ref(); - let empty: [F; 0] = []; let mut builder = LookupValues::builder(height, &slot_widths); - let mut buf = Vec::new(); - let mut args = Vec::new(); let mut writers = builder.rows_mut(); - for (r, writer) in writers.iter_mut().enumerate() { - let r_next = (r + 1) % height; - let main_cur = trace.row_slice(r).unwrap(); - let main_next = trace.row_slice(r_next).unwrap(); - let preprocessed_rows = - preprocessed.map(|pp| (pp.row_slice(r).unwrap(), pp.row_slice(r_next).unwrap())); - let (pp_cur, pp_next): (&[F], &[F]) = match &preprocessed_rows { - Some((cur, next)) => (cur, next), - None => (&empty, &empty), - }; - let view = VarValues { - preprocessed: [pp_cur, pp_next], - main: [&main_cur, &main_next], - stage2: [&empty, &empty], - publics: &empty, - is_first_row: if r == 0 { F::ONE } else { F::ZERO }, - is_last_row: if r == height - 1 { F::ONE } else { F::ZERO }, - is_transition: if r == height - 1 { F::ZERO } else { F::ONE }, - }; - circuit.graph.sweep_lookup_prefix(&view, &mut buf); - for (slot, lookup) in circuit.graph.lookups.iter().enumerate() { - let multiplicity = buf[lookup.multiplicity.index()]; - args.clear(); - args.extend(lookup.args.iter().map(|a| buf[a.index()])); - // The multiplicity expression already carries its sign, so store - // it as-is (push semantics). - writer.push(slot, multiplicity, &args); - } - } + writers.par_iter_mut().enumerate().for_each_init( + || (Vec::new(), Vec::new()), + |(buf, args), (r, writer)| { + let empty: [F; 0] = []; + let r_next = (r + 1) % height; + let main_cur = trace.row_slice(r).unwrap(); + let main_next = trace.row_slice(r_next).unwrap(); + let preprocessed_rows = + preprocessed.map(|pp| (pp.row_slice(r).unwrap(), pp.row_slice(r_next).unwrap())); + let (pp_cur, pp_next): (&[F], &[F]) = match &preprocessed_rows { + Some((cur, next)) => (cur, next), + None => (&empty, &empty), + }; + let view = VarValues { + preprocessed: [pp_cur, pp_next], + main: [&main_cur, &main_next], + stage2: [&empty, &empty], + publics: &empty, + is_first_row: if r == 0 { F::ONE } else { F::ZERO }, + is_last_row: if r == height - 1 { F::ONE } else { F::ZERO }, + is_transition: if r == height - 1 { F::ZERO } else { F::ONE }, + }; + circuit.graph.sweep_lookup_prefix(&view, buf); + for (slot, lookup) in circuit.graph.lookups.iter().enumerate() { + let multiplicity = buf[lookup.multiplicity.index()]; + args.clear(); + args.extend(lookup.args.iter().map(|a| buf[a.index()])); + // The multiplicity expression already carries its sign, so + // store it as-is (push semantics). + writer.push(slot, multiplicity, args); + } + }, + ); drop(writers); builder.finish() } diff --git a/src/test_circuits/byte_operations.rs b/src/test_circuits/byte_operations.rs index 58238ac..91efe03 100644 --- a/src/test_circuits/byte_operations.rs +++ b/src/test_circuits/byte_operations.rs @@ -1,6 +1,6 @@ #[cfg(test)] mod tests { - use crate::lookup::Lookup; + use crate::lookup::{Lookup, LookupValues}; use crate::p3_adapter::{LookupAir, preprocessed_var, var}; use crate::system::{System, SystemWitness}; use crate::test_circuits::SymbExpr; @@ -153,7 +153,15 @@ mod tests { let claim3 = &[f(2), f(100), f(40), f(100 | 40)]; let claim4 = &[f(3), f(200), f(100)]; let claims: &[&[Val]] = &[claim1, claim2, claim3, claim4]; + let shape = SystemWitness { + traces: witness.traces.clone(), + lookups: witness.lookups.iter().map(LookupValues::shape).collect(), + }; let proof = system.prove_multiple_claims(&key, claims, witness); system.verify_multiple_claims(claims, &proof).unwrap(); + // Lookups over preprocessed columns rebuild from the committed trace + // and the circuit's preprocessed table alike. + let rebuilt = system.prove_multiple_claims(&key, claims, shape); + assert_eq!(proof.to_bytes().unwrap(), rebuilt.to_bytes().unwrap()); } } diff --git a/src/types.rs b/src/types.rs index 10ad8bc..3053210 100644 --- a/src/types.rs +++ b/src/types.rs @@ -899,10 +899,10 @@ impl StarkGenericConfig for GoldilocksBlake3Config { // kernel from the same residency predicate; the kernel must not be // re-chosen here or it can run under the other path's budget. let evaluate = |input: &crate::config::LookupCommitInput<'_, Self>, + values: &crate::lookup::LookupValues, graph_path: bool, cooperative: bool| { - let (height, num_lookups, multiplicities, args, arg_offsets) = - input.lookup_values.cuda_parts(); + let (height, num_lookups, multiplicities, args, arg_offsets) = values.cuda_parts(); let group_size = input.circuit.lookup_group_size.max(1); let main = graph_path.then(|| { input @@ -944,7 +944,7 @@ impl StarkGenericConfig for GoldilocksBlake3Config { self.log_blowup, move |rows| { pool.install(|| { - input.lookup_values.cuda_stage_2_deltas::( + values.cuda_stage_2_deltas::( rows, group_size, lookup_challenge, @@ -1049,7 +1049,19 @@ impl StarkGenericConfig for GoldilocksBlake3Config { && output_bytes >= (8usize << 30) && num_lookups >= 64 && arg_offsets.last().copied().unwrap_or(0) >= 256; - results[index] = Some(evaluate(&inputs[index], graph_path, cooperative)?); + // The direct paths read lookup values on the host. A shape-only + // witness gets them from the committed stage-one trace here. + let materialized = (!graph_path && !input.lookup_values.is_materialized()).then(|| { + let _g = tracing::info_span!("cuda/materialize_lookups", index).entered(); + let trace = self.pcs.mmcs.committed_trace( + input.stage_1.0, + input.stage_1.1, + self.log_blowup, + ); + crate::system::compute_lookup_values(input.circuit, &trace) + }); + let values = materialized.as_ref().unwrap_or(input.lookup_values); + results[index] = Some(evaluate(input, values, graph_path, cooperative)?); if crate::cuda::memory_diagnostics_enabled() { eprintln!( "[multi-stark/cuda] lookup job {index} complete: {:.3}s", From d13dc8d28f93c106c9bc2260f6f6d935cc1ef193 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:57:16 +0000 Subject: [PATCH 03/28] Read spilled preprocessed traces from host in the CUDA lookup graph Large commitments release device traces during construction or proactive spilling, keeping only retained host copies. Lookup admission accepted a preprocessed LDE once its values were resident, but the graph kernel required its device trace and failed with cudaErrorInvalidValue, which broke the KZG compression of formal Aiur aggregate roots. The graph kernel now stages preprocessed rows from the retained host trace in 2^16-row chunks, as it already does for stage-1 traces. The host copy is passed explicitly rather than attached, since preprocessed data is shared across proofs. Admission uses the same availability predicate and budgets the extra staging chunk. --- cuda/kernels.cu | 48 ++++++++++++------- src/cuda/mmcs.rs | 34 ++++++++++++++ src/cuda/mod.rs | 29 +++++++++--- src/cuda/tests/lookup_graph.rs | 85 ++++++++++++++++++++++++++++++++++ src/types.rs | 30 ++++++++---- 5 files changed, 195 insertions(+), 31 deletions(-) create mode 100644 src/cuda/tests/lookup_graph.rs diff --git a/cuda/kernels.cu b/cuda/kernels.cu index ec114ea..f8eec6b 100644 --- a/cuda/kernels.cu +++ b/cuda/kernels.cu @@ -986,14 +986,16 @@ __global__ void lookup_messages(Ext2* conjugates,uint64_t* norms,const uint64_t* } } // Evaluate the lookup-only prefix of a circuit DAG against the original -// row-major witness retained by the stage-1 LDE. This avoids materializing -// and uploading the much wider concrete LookupValues buffer. +// row-major witnesses retained by the preprocessed and stage-1 LDEs. This +// avoids materializing and uploading the much wider concrete LookupValues +// buffer. A trace flagged as a chunk holds rows [row_start, row_start+row_count) +// followed by the wrapped successor of its last row. __global__ void lookup_messages_graph( Ext2* conjugates,uint64_t* norms,uint64_t* multiplicities, const ConstraintNode* nodes,size_t node_count,size_t slot_count, const ConstraintLookup* lookups,size_t lookup_count,const uint32_t* lookup_args, - const ResidentLde* preprocessed,const uint64_t* main_trace,size_t main_width, - bool main_trace_is_chunk, + const uint64_t* prep_trace,size_t prep_width,bool prep_trace_is_chunk, + const uint64_t* main_trace,size_t main_width,bool main_trace_is_chunk, Ext2 beta,Ext2 gamma,uint64_t ext_w,size_t height,size_t row_start, size_t row_count,uint64_t* global_scratch){ extern __shared__ uint64_t shared_values[]; @@ -1009,9 +1011,9 @@ __global__ void lookup_messages_graph( switch(n.op){ case 0:v=n.value;break; case 1:{const bool prep_column=n.aux<2; - const size_t r=prep_column?((n.aux&1U)?next:row): - (main_trace_is_chunk?((n.aux&1U)?local_row+1:local_row):((n.aux&1U)?next:row)); - v=n.aux<2?preprocessed->trace_values[r*preprocessed->width+n.a]:main_trace[r*main_width+n.a];break;} + const bool chunk=prep_column?prep_trace_is_chunk:main_trace_is_chunk; + const size_t r=chunk?((n.aux&1U)?local_row+1:local_row):((n.aux&1U)?next:row); + v=prep_column?prep_trace[r*prep_width+n.a]:main_trace[r*main_width+n.a];break;} case 2:v=0;break; case 3:v=static_cast(row==0);break; case 4:v=static_cast(row+1==height);break; @@ -2141,6 +2143,10 @@ extern "C" int multi_stark_cuda_coset_lde_generate( return status; } +extern "C" bool multi_stark_cuda_lde_has_device_trace(const void* handle) { + return handle && static_cast(handle)->trace_values; +} + extern "C" bool multi_stark_cuda_lde_has_generator(const void* handle) { return handle && static_cast(handle)->trace_writer; } @@ -3025,7 +3031,7 @@ extern "C" int multi_stark_cuda_lookup_trace(int device_id,uint64_t* output,uint extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_handle,uint64_t* total, const void* nodes,size_t node_count,size_t slot_count,const void* lookups,size_t lookup_count, const uint32_t* lookup_args,size_t lookup_arg_count,const void* preprocessed_handle, - const void* main_handle,size_t group_size,const uint64_t* beta,const uint64_t* gamma, + const uint64_t* preprocessed_host,const void* main_handle,size_t group_size,const uint64_t* beta,const uint64_t* gamma, uint64_t ext_w,size_t added_bits,const MultiStarkNttPlan* plan){ auto* main=const_cast(static_cast(main_handle)); auto* prep=static_cast(preprocessed_handle); @@ -3034,7 +3040,8 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han (!main->trace_values&&!main->host_trace_values&&!main->trace_writer)||!main->trace_height|| !group_size||!beta||!gamma||(!plan || !plan->shift_powers)|| !is_power_of_two(main->trace_height)||added_bits>=sizeof(size_t)*8|| - main->trace_height>(SIZE_MAX>>added_bits)||(prep&&!prep->trace_values)) { + main->trace_height>(SIZE_MAX>>added_bits)|| + (prep&&!prep->trace_values&&!preprocessed_host)) { return static_cast(cudaErrorInvalidValue); } *output_handle=nullptr;const size_t height=main->trace_height; @@ -3054,7 +3061,7 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han auto cp=[&](size_t at,const void* src,size_t n){if(status==cudaSuccess)status=cudaMemcpy(metadata+at,src,n,cudaMemcpyHostToDevice);}; cp(on,nodes,node_count*sizeof(ConstraintNode));cp(ol,lookups,lookup_count*sizeof(ConstraintLookup));cp(oa,lookup_args,lookup_arg_count*sizeof(uint32_t)); auto* dn=reinterpret_cast(metadata+on);auto* dl=reinterpret_cast(metadata+ol);auto* da=reinterpret_cast(metadata+oa); - Ext2 *conjugates=nullptr,*deltas=nullptr;uint64_t *norms=nullptr,*norm_inverses=nullptr,*multiplicities=nullptr,*scratch=nullptr,*trace_chunk=nullptr;ResidentLde* lde=nullptr; + Ext2 *conjugates=nullptr,*deltas=nullptr;uint64_t *norms=nullptr,*norm_inverses=nullptr,*multiplicities=nullptr,*scratch=nullptr,*trace_chunk=nullptr,*prep_chunk=nullptr;ResidentLde* lde=nullptr; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext2)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norms),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norm_inverses),message_count*sizeof(uint64_t)); @@ -3069,6 +3076,15 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han const bool generated = !main->trace_values && main->trace_writer; const bool tiled = main->host_trace_values || generated; if(status==cudaSuccess&&tiled)status=cudaMalloc(reinterpret_cast(&trace_chunk),(chunk_rows+1)*main->width*sizeof(uint64_t)); + // Preprocessed data is shared across proofs, so a host copy is read in + // place instead of being attached to the LDE. + const bool prep_tiled=prep&&!prep->trace_values; + if(status==cudaSuccess&&prep_tiled)status=cudaMalloc(reinterpret_cast(&prep_chunk),(chunk_rows+1)*prep->width*sizeof(uint64_t)); + auto upload_rows=[&](uint64_t* chunk,const uint64_t* host,size_t width,size_t row_start,size_t rows){ + cudaError_t result=cudaMemcpy(chunk,host+row_start*width,rows*width*sizeof(uint64_t),cudaMemcpyHostToDevice); + const size_t next_row=(row_start+rows)&(height-1); + if(result==cudaSuccess)result=cudaMemcpy(chunk+rows*width,host+next_row*width,width*sizeof(uint64_t),cudaMemcpyHostToDevice); + return result;}; for(size_t row_start=0;status==cudaSuccess&&row_start(main->trace_writer(main->trace_context,device_id,trace_chunk,row_start,rows+1)); active_trace=trace_chunk; } else if(main->host_trace_values){ - status=cudaMemcpy(trace_chunk,main->host_trace_values+row_start*main->width,rows*main->width*sizeof(uint64_t),cudaMemcpyHostToDevice); - const size_t next_row=(row_start+rows)&(height-1); - if(status==cudaSuccess)status=cudaMemcpy(trace_chunk+rows*main->width,main->host_trace_values+next_row*main->width,main->width*sizeof(uint64_t),cudaMemcpyHostToDevice); + status=upload_rows(trace_chunk,main->host_trace_values,main->width,row_start,rows); active_trace=trace_chunk; } + if(status==cudaSuccess&&prep_tiled)status=upload_rows(prep_chunk,preprocessed_host,prep->width,row_start,rows); if(status==cudaSuccess){lookup_messages_graph<<(chunk_blocks),static_cast(tile),global?0:slot_count*tile*sizeof(uint64_t)>>>( - conjugates,norms,multiplicities,dn,node_count,slot_count,dl,lookup_count,da,prep,active_trace,main->width, - tiled,{beta[0],beta[1]},{gamma[0],gamma[1]},ext_w,height,row_start,rows,scratch);status=cudaGetLastError();} + conjugates,norms,multiplicities,dn,node_count,slot_count,dl,lookup_count,da, + prep_tiled?prep_chunk:(prep?prep->trace_values:nullptr),prep?prep->width:0,prep_tiled, + active_trace,main->width,tiled,{beta[0],beta[1]},{gamma[0],gamma[1]},ext_w,height,row_start,rows,scratch);status=cudaGetLastError();} if(status==cudaSuccess)status=batch_inverse_norms(norm_inverses,norms,messages); if(status==cudaSuccess){lookup_group_deltas_batched<<>>( deltas+row_start*groups,multiplicities,conjugates,norm_inverses,rows,lookup_count,group_size,ext_w);status=cudaGetLastError();} @@ -3097,7 +3113,7 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han if(status==cudaSuccess)status=coset_lde(device_id,lde->values,lde->values,height,width,extended_height,plan); if(status==cudaSuccess)status=cudaStreamSynchronize(0); if(status==cudaSuccess)*output_handle=lde;else destroy_resident_lde(lde); - cudaFree(trace_chunk);cudaFree(scratch);cudaFree(deltas);cudaFree(multiplicities);cudaFree(norm_inverses);cudaFree(norms);cudaFree(conjugates);cudaFree(metadata); + cudaFree(prep_chunk);cudaFree(trace_chunk);cudaFree(scratch);cudaFree(deltas);cudaFree(multiplicities);cudaFree(norm_inverses);cudaFree(norms);cudaFree(conjugates);cudaFree(metadata); return static_cast(status); } diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index 37ee91c..245c0e1 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -230,6 +230,40 @@ impl CudaMmcsData> { } } + /// The resident LDE together with a retained host copy of its trace, if + /// any, for readers that take the original trace without attaching it to + /// the LDE. Unlike [`Self::resident_with_trace`] this never mutates the + /// LDE, so it is safe on data shared across concurrent proofs, such as a + /// preprocessed commitment. Returns `None` unless the trace is available + /// on the device or as that host copy. + pub(crate) fn resident_with_host_trace( + &self, + index: usize, + ) -> Option<(&CudaLde, Option<&RowMajorMatrix>)> { + let (lde, host) = match self { + Self::Cuda { + resident, + retained_traces, + .. + } => ( + resident.get(index)?, + retained_traces + .get() + .and_then(|retained| retained.get(index)), + ), + Self::Hybrid { + resident, + retained_traces, + .. + } => ( + resident.get(index)?.as_ref()?, + retained_traces.get(index)?.as_ref(), + ), + Self::Cpu(_) => return None, + }; + (lde.has_device_trace() || host.is_some()).then_some((lde, host)) + } + pub(crate) fn resident_with_trace(&self, index: usize) -> Option<&CudaLde> { match self { Self::Cuda { diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 4b2cf5a..19d8d00 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -357,6 +357,7 @@ unsafe extern "C" { writer: unsafe extern "C" fn(*mut c_void, i32, *mut u64, usize, usize) -> i32, destroy: unsafe extern "C" fn(*mut c_void), ) -> i32; + fn multi_stark_cuda_lde_has_device_trace(handle: *const c_void) -> bool; fn multi_stark_cuda_lde_has_generator(handle: *const c_void) -> bool; fn multi_stark_cuda_lde_generator_context(handle: *const c_void) -> *mut c_void; } @@ -374,6 +375,11 @@ unsafe impl Send for CudaLde {} unsafe impl Sync for CudaLde {} impl CudaLde { + /// Whether the original trace is still resident on the device. + pub(crate) fn has_device_trace(&self) -> bool { + unsafe { multi_stark_cuda_lde_has_device_trace(self.raw_handle()) } + } + pub(crate) fn has_generator(&self) -> bool { unsafe { multi_stark_cuda_lde_has_generator(self.raw_handle()) } } @@ -947,6 +953,7 @@ pub(crate) fn lookup_graph_lde_memory_upper_bound( graph: &ConstraintGraph, height: usize, main_width: usize, + preprocessed_width: usize, group_size: usize, log_blowup: usize, ) -> Option<(usize, usize)> { @@ -989,12 +996,13 @@ pub(crate) fn lookup_graph_lde_memory_upper_bound( } else { 0 }; - // Some stage-1 policies retain the original trace in pinned host memory. - // Charge one bounded staging chunk even when this particular LDE still - // owns a device trace, keeping admission safe across both representations. + // Some commitment policies retain the original preprocessed and stage-1 + // traces only in host memory. Charge one bounded staging chunk for each + // even when the LDE still owns a device trace, keeping admission safe + // across both representations. let trace_chunk_bytes = chunk_rows .saturating_add(1) - .saturating_mul(main_width) + .saturating_mul(main_width.saturating_add(preprocessed_width)) .saturating_mul(size_of::()); Some(( output_bytes, @@ -1999,7 +2007,7 @@ pub(crate) fn lookup_lde_resident_partitioned( pub(crate) fn lookup_graph_lde_resident( dft: &CudaDft, graph: &ConstraintGraph, - preprocessed: Option<&CudaLde>, + preprocessed: Option<(&CudaLde, Option<&RowMajorMatrix>)>, main: &CudaLde, height: usize, group_size: usize, @@ -2019,6 +2027,10 @@ pub(crate) fn lookup_graph_lde_resident( added_bits = log_blowup ) .entered(); + if let Some((lde, Some(host))) = preprocessed { + assert_eq!(host.height(), height, "preprocessed host trace height"); + assert_eq!(host.width(), lde.width, "preprocessed host trace width"); + } let (nodes, slot_count, lookups, args) = encode_lookup_nodes(graph)?; let num_lookups = lookups.len(); let groups = num_lookups.div_ceil(group_size.max(1)); @@ -2043,7 +2055,10 @@ pub(crate) fn lookup_graph_lde_resident( lookups.len(), args.as_ptr(), args.len(), - preprocessed.map_or(core::ptr::null(), CudaLde::raw_handle), + preprocessed.map_or(core::ptr::null(), |(lde, _)| lde.raw_handle()), + preprocessed + .and_then(|(_, host)| host) + .map_or(core::ptr::null(), |host| host.values.as_ptr().cast()), main.raw_handle(), group_size.max(1), beta.as_ptr().cast(), @@ -3229,6 +3244,7 @@ unsafe extern "C" { lookup_args: *const u32, lookup_arg_count: usize, preprocessed_handle: *const c_void, + preprocessed_host: *const u64, main_handle: *const c_void, group_size: usize, beta: *const u64, @@ -3463,6 +3479,7 @@ mod tests { use p3_symmetric::CryptographicHasher; use rand::{RngExt, SeedableRng, rngs::SmallRng}; + mod lookup_graph; mod quotient; #[test] diff --git a/src/cuda/tests/lookup_graph.rs b/src/cuda/tests/lookup_graph.rs new file mode 100644 index 0000000..b2791f2 --- /dev/null +++ b/src/cuda/tests/lookup_graph.rs @@ -0,0 +1,85 @@ +use super::*; +use crate::expr::{CircuitSpec, Expr}; +use crate::graph::compile; +use crate::lookup::{Lookup, stage2_width}; +use crate::types::GoldilocksBlake3Config; + +#[test] +#[ignore = "requires a CUDA GPU; compares graph lookup LDEs over device and host-only traces"] +fn graph_lookup_reads_host_preprocessed_trace() { + let gpu = CudaDft::without_auxiliary_devices(configured_device()); + let ext = crate::system::extension_params::(); + let (lookup_count, group_size, log_blowup) = (5, 2, 1); + let spec = CircuitSpec { + main_width: 3, + preprocessed_width: 2, + stage2_width: stage2_width(lookup_count, group_size, 2), + num_publics: 0, + constraints: vec![], + ext_constraints: vec![], + lookups: (0..lookup_count) + .map(|index| { + Lookup::push( + Expr::preprocessed(0) - Expr::constant(Goldilocks::from_usize(index)), + vec![ + Expr::main_next(0), + Expr::preprocessed_next(1), + Expr::main(2) * Expr::preprocessed(1), + ], + ) + }) + .collect(), + }; + let graph = compile(&spec, &ext).unwrap(); + // Several 2^16-row kernel chunks, so tiled next-row reads cross chunk + // boundaries and wrap around the last row. + let n = 1 << 18; + let trace = |width: usize, seed: usize| { + RowMajorMatrix::new( + (0..n * width) + .map(|index| Goldilocks::from_usize((index * index + 17 * index + seed) % 1009)) + .collect(), + width, + ) + }; + let prep_trace = trace(2, 41); + let main_trace = trace(3, 7); + let prep = gpu.coset_lde_batch_resident(&prep_trace, log_blowup, Goldilocks::GENERATOR); + let main = gpu.coset_lde_batch_resident(&main_trace, log_blowup, Goldilocks::GENERATOR); + let beta = [Goldilocks::from_u8(3), Goldilocks::from_u8(5)]; + let gamma = [Goldilocks::from_u8(7), Goldilocks::from_u8(11)]; + let run = |prep_host: Option<&RowMajorMatrix>| { + let (lde, total) = lookup_graph_lde_resident( + &gpu, + &graph, + Some((&prep, prep_host)), + &main, + n, + group_size, + beta, + gamma, + ext.w, + log_blowup, + ) + .expect("graph lookup encoding"); + (lde.to_row_major_matrix().values, total) + }; + + let expected = run(None); + // SAFETY: no CUDA work is in flight on these LDEs. + unsafe { prep.release_trace() }; + assert!(!prep.has_device_trace()); + assert!( + run(Some(&prep_trace)) == expected, + "host preprocessed trace" + ); + // SAFETY: as above; `main_trace` outlives every later use of `main`. + unsafe { + main.release_trace(); + main.attach_trace(&main_trace); + } + assert!( + run(Some(&prep_trace)) == expected, + "host preprocessed and main traces" + ); +} diff --git a/src/types.rs b/src/types.rs index 362c284..fdfa447 100644 --- a/src/types.rs +++ b/src/types.rs @@ -870,12 +870,21 @@ impl ProofConfig for GoldilocksBlake3Config { .get(input.stage_1.1) .expect("stage-1 matrix index out of bounds") .width; + let preprocessed_width = input.preprocessed.map_or(0, |(data, matrix)| { + self.pcs + .mmcs + .matrix_dimensions(data) + .get(matrix) + .expect("preprocessed matrix index out of bounds") + .width + }); let graph_memory = (num_lookups != 0) .then(|| { crate::cuda::lookup_graph_lde_memory_upper_bound( &input.circuit.graph, height, main_width, + preprocessed_width, group_size, self.log_blowup, ) @@ -962,8 +971,9 @@ impl ProofConfig for GoldilocksBlake3Config { }); let result = if let Some(main) = main { let preprocessed = input.preprocessed.map(|(data, index)| { - data.resident(index) - .expect("lookup graph admission requires a resident preprocessed LDE") + data.resident_with_host_trace(index).expect( + "lookup graph admission requires a trace-backed resident preprocessed LDE", + ) }); crate::cuda::lookup_graph_lde_resident( &self.pcs.dft, @@ -1029,16 +1039,18 @@ impl ProofConfig for GoldilocksBlake3Config { for (index, output_bytes, direct_temporary_bytes, graph_temporary_bytes, _) in lookup_jobs { let job_started = std::time::Instant::now(); let input = &inputs[index]; - // The graph kernel reads the trace through `resident_with_trace`, - // which also serves spilled LDEs that regenerate from a generator - // or a retained host trace. Admit it under the same predicate so - // the budget matches the kernel that runs. + // The graph kernel reads the stage-1 trace through + // `resident_with_trace`, which also serves spilled LDEs that + // regenerate from a generator or a retained host trace, and the + // preprocessed trace through `resident_with_host_trace`. Admit it + // under the same predicates so the budget matches the kernel that + // runs. let admits_graph = || { graph_temporary_bytes.is_some() && input.stage_1.0.has_resident_with_trace(input.stage_1.1) - && input - .preprocessed - .is_none_or(|(data, matrix)| data.resident(matrix).is_some()) + && input.preprocessed.is_none_or(|(data, matrix)| { + data.resident_with_host_trace(matrix).is_some() + }) }; let target_for = |graph_path: bool| { let temporary_bytes = if graph_path { From 0e662c50725c525424a816d1df75cfa07cb1fecd Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:14:49 +0000 Subject: [PATCH 04/28] Read fixed matrices from the preprocessed commitment for shape-only lookups A system built without its fixed matrices can now prove with shape-only lookup witnesses: lookup materialization rebuilds each circuit's fixed matrix from the preprocessed commitment, on both the host and CUDA paths. Proofs are byte-identical to fully materialized witnesses. --- src/plonkish/tests.rs | 46 +++++++++++++++++++++++++++++++++++++++++++ src/prover.rs | 25 +++++++++++++++++++++-- src/types.rs | 17 +++++++++++++++- 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/src/plonkish/tests.rs b/src/plonkish/tests.rs index 6cf6ddb..01fed5b 100644 --- a/src/plonkish/tests.rs +++ b/src/plonkish/tests.rs @@ -404,3 +404,49 @@ fn plonkish_public_count_and_foreign_assignment_are_checked() { Err(WitnessError::ForeignAssignment) )); } + +#[test] +fn shape_only_lookups_read_fixed_matrices_from_the_commitment() { + let f = Val::from_u32; + let mut builder = CircuitBuilder::::new(); + let a = builder.public_input("a"); + let b = builder.input("b"); + let sum = builder.add(a, b); + let product = builder.mul(a, b); + builder.expose_public(sum); + let table = builder.fixed_table( + "tuples", + vec![vec![f(1), f(2), f(2), f(3)], vec![f(2), f(3), f(6), f(5)]], + ); + builder.lookup(table, &[a, b, product, sum]); + let compiled = builder.finish().lower_to_multi_stark(f(17)).unwrap(); + let mut witness = compiled.witness(); + witness.set(a, f(2)).unwrap(); + witness.set(b, f(3)).unwrap(); + let assignment = witness.generate().unwrap(); + let publics = assignment.public_values().to_vec(); + let traces = compiled.traces(&assignment).unwrap(); + let claims = compiled.claims(&publics).unwrap(); + let refs: Vec<_> = claims.iter().map(Vec::as_slice).collect(); + + let (system, key) = System::new(config(), compiled.circuit_inputs()); + let expected = system.prove_multiple_claims( + &key, + &refs, + SystemWitness::from_stage_1(traces.clone(), &system), + ); + + let (lean, lean_key) = System::new_without_preprocessed(config(), compiled.circuit_inputs()); + assert!(lean.circuits.iter().all(|c| c.preprocessed.is_none())); + let lookups = traces + .iter() + .zip(&lean.circuits) + .map(|(trace, circuit)| { + let widths: Vec<_> = circuit.graph.lookups.iter().map(|l| l.args.len()).collect(); + crate::lookup::LookupValues::shape_only(trace.height(), &widths) + }) + .collect(); + let actual = lean.prove_multiple_claims(&lean_key, &refs, SystemWitness { traces, lookups }); + assert_eq!(expected.to_bytes().unwrap(), actual.to_bytes().unwrap()); + lean.verify_multiple_claims(&refs, &actual).unwrap(); +} diff --git a/src/prover.rs b/src/prover.rs index 6de1a6e..3693207 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -332,6 +332,7 @@ where /// on the host. Materialized witnesses pass through unchanged. fn materialize_lookups( &self, + key: &ProverKey, data: &PcsData, active_indices: &[usize], log_degrees: &[usize], @@ -349,9 +350,28 @@ where .config .committed_trace(data, position, 1 << log_degrees[position]) .expect("shape-only lookup witnesses need a configuration that rebuilds committed traces"); - crate::system::compute_lookup_values( - &self.circuits[active_indices[position]], + let circuit_index = active_indices[position]; + let circuit = &self.circuits[circuit_index]; + // A system built without its fixed matrices reads each one + // back from the preprocessed commitment when it is needed. + let fixed = circuit + .preprocessed + .is_none() + .then(|| { + key.preprocessed_data + .as_ref() + .zip(self.preprocessed_indices[circuit_index]) + }) + .flatten() + .map(|(fixed, index)| { + self.config + .committed_trace(fixed, index, 1 << log_degrees[position]) + .expect("shape-only lookup witnesses need a configuration that rebuilds committed traces") + }); + crate::system::compute_lookup_values_with_fixed( + circuit, &trace, + circuit.preprocessed.as_ref().or(fixed.as_ref()), ) }) .collect() @@ -590,6 +610,7 @@ where // witness omitted from the committed stage-one traces. drop(lookup_inputs); let active_lookups = self.materialize_lookups( + key, &stage_1_trace_data, &active_indices, &log_degrees, diff --git a/src/types.rs b/src/types.rs index fdfa447..567451e 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1119,7 +1119,22 @@ impl ProofConfig for GoldilocksBlake3Config { input.stage_1.1, self.log_blowup, ); - crate::system::compute_lookup_values(input.circuit, &trace) + // A system built without its fixed matrices reads each one + // back from the preprocessed commitment when it is needed. + let fixed = input + .circuit + .preprocessed + .is_none() + .then_some(input.preprocessed) + .flatten() + .map(|(data, matrix)| { + self.pcs.mmcs.committed_trace(data, matrix, self.log_blowup) + }); + crate::system::compute_lookup_values_with_fixed( + input.circuit, + &trace, + input.circuit.preprocessed.as_ref().or(fixed.as_ref()), + ) }); let values = materialized.as_ref().unwrap_or(input.lookup_values); results[index] = Some(evaluate(input, values, graph_path, cooperative)?); From b895ab48482ceda785ec6b16fee9ae73b2b00e44 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:20:03 +0000 Subject: [PATCH 05/28] Build host stage-two lookup traces one circuit at a time When the fused CUDA lookup commitment declines, the host fallback materialized every circuit's shape-only lookup witness up front and then computed messages and inverses for all circuits in one pass. On the Ix compression root this held every circuit's lookup values plus the joint message and inverse vectors at once and set the process peak (233.8 GB). Circuits interact only through the accumulator chain, so materialize, evaluate and free one circuit at a time, carrying the accumulator. The stage-two traces, accumulators and proof bytes are unchanged. --- src/prover.rs | 167 ++++++++++++++++++------------ src/system/tests/lookup_values.rs | 40 +++++++ 2 files changed, 143 insertions(+), 64 deletions(-) diff --git a/src/prover.rs b/src/prover.rs index 3693207..823f7ea 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -327,54 +327,112 @@ where // FRI-based config is two-adic anyway. Val: TwoAdicField + Ord, { - /// Fills every shape-only lookup witness of the active circuits from the - /// committed stage-one traces, for prover paths that read lookup values - /// on the host. Materialized witnesses pass through unchanged. - fn materialize_lookups( + /// Builds the stage-two traces and intermediate accumulators on the host, + /// one circuit at a time. A shape-only witness is filled from the + /// committed stage-one trace just before its circuit is processed and + /// freed right after, so at most one circuit's lookup values (and its + /// messages and their inverses) are live at once. Circuits only interact + /// through the accumulator chain, which is carried between iterations, + /// so the traces equal those of a single pass over every circuit. + #[allow(clippy::too_many_arguments)] + fn host_lookup_traces( &self, key: &ProverKey, data: &PcsData, active_indices: &[usize], log_degrees: &[usize], lookups: Vec>>, - ) -> Vec>> { - lookups - .into_iter() - .enumerate() - .map(|(position, values)| { - if values.is_materialized() { - return values; - } - let _g = tracing::info_span!("stark/materialize_lookups", position).entered(); - let trace = self - .config - .committed_trace(data, position, 1 << log_degrees[position]) - .expect("shape-only lookup witnesses need a configuration that rebuilds committed traces"); - let circuit_index = active_indices[position]; - let circuit = &self.circuits[circuit_index]; - // A system built without its fixed matrices reads each one - // back from the preprocessed commitment when it is needed. - let fixed = circuit - .preprocessed - .is_none() - .then(|| { - key.preprocessed_data - .as_ref() - .zip(self.preprocessed_indices[circuit_index]) - }) - .flatten() - .map(|(fixed, index)| { - self.config - .committed_trace(fixed, index, 1 << log_degrees[position]) - .expect("shape-only lookup witnesses need a configuration that rebuilds committed traces") - }); - crate::system::compute_lookup_values_with_fixed( - circuit, - &trace, - circuit.preprocessed.as_ref().or(fixed.as_ref()), + group_sizes: &[usize], + lookup_argument_challenge: SC::Challenge, + fingerprint_challenge: SC::Challenge, + mut acc: SC::Challenge, + ) -> (Vec>, Vec) { + let mut traces = Vec::with_capacity(lookups.len()); + let mut intermediate_accumulators = Vec::with_capacity(lookups.len()); + for (position, values) in lookups.into_iter().enumerate() { + let values = + [ + self.materialize_lookup( + key, + data, + active_indices, + log_degrees, + position, + values, + ), + ]; + let group_size = &group_sizes[position..=position]; + let (circuit_traces, accumulators) = self + .config + .accelerated_lookup_traces( + &values, + group_size, + lookup_argument_challenge, + fingerprint_challenge, + acc, ) + .unwrap_or_else(|| { + LookupValues::stage_2_traces( + &values, + group_size, + lookup_argument_challenge, + &fingerprint_challenge, + acc, + ) + }); + drop(values); + acc = *accumulators.last().expect("one accumulator per circuit"); + traces.extend(circuit_traces); + intermediate_accumulators.extend(accumulators); + } + (traces, intermediate_accumulators) + } + + /// Fills a shape-only lookup witness of the circuit at an active position + /// from its committed stage-one trace. A materialized witness passes + /// through unchanged. + fn materialize_lookup( + &self, + key: &ProverKey, + data: &PcsData, + active_indices: &[usize], + log_degrees: &[usize], + position: usize, + values: LookupValues>, + ) -> LookupValues> { + if values.is_materialized() { + return values; + } + let _g = tracing::info_span!("stark/materialize_lookups", position).entered(); + let trace = self + .config + .committed_trace(data, position, 1 << log_degrees[position]) + .expect( + "shape-only lookup witnesses need a configuration that rebuilds committed traces", + ); + let circuit_index = active_indices[position]; + let circuit = &self.circuits[circuit_index]; + // A system built without its fixed matrices reads each one + // back from the preprocessed commitment when it is needed. + let fixed = circuit + .preprocessed + .is_none() + .then(|| { + key.preprocessed_data + .as_ref() + .zip(self.preprocessed_indices[circuit_index]) }) - .collect() + .flatten() + .map(|(fixed, index)| { + self.config + .committed_trace(fixed, index, 1 << log_degrees[position]) + .expect("shape-only lookup witnesses need a configuration that rebuilds committed traces") + }); + crate::system::compute_lookup_values_with_fixed( + circuit, + &trace, + circuit.preprocessed.as_ref().or(fixed.as_ref()), + ) } /// Generates a STARK proof for the system with a single claim. @@ -606,37 +664,18 @@ where drop(_g); result } else { - // Host paths read every lookup value; derive any a shape-only - // witness omitted from the committed stage-one traces. drop(lookup_inputs); - let active_lookups = self.materialize_lookups( + let (stage_2_traces, intermediate_accumulators) = self.host_lookup_traces( key, &stage_1_trace_data, &active_indices, &log_degrees, active_lookups, + &group_sizes, + lookup_argument_challenge, + fingerprint_challenge, + acc, ); - let (stage_2_traces, intermediate_accumulators) = self - .config - .accelerated_lookup_traces( - &active_lookups, - &group_sizes, - lookup_argument_challenge, - fingerprint_challenge, - acc, - ) - .unwrap_or_else(|| { - LookupValues::stage_2_traces( - &active_lookups, - &group_sizes, - lookup_argument_challenge, - &fingerprint_challenge, - acc, - ) - }); - // The lookup witness can be as large as the traces themselves; free it - // now instead of holding it through the commit/quotient/FRI stages. - drop(active_lookups); drop(_g); // Cost: "Stage 2 commit" — LDE + Merkle for flattened extension traces. diff --git a/src/system/tests/lookup_values.rs b/src/system/tests/lookup_values.rs index 82201bd..5bf797e 100644 --- a/src/system/tests/lookup_values.rs +++ b/src/system/tests/lookup_values.rs @@ -281,6 +281,46 @@ fn witness_circuit_order_and_lookup_totals() { } } +#[test] +fn per_circuit_stage_2_traces_chain_like_a_joint_pass() { + let (circuits, traces): (Vec<_>, Vec<_>) = [65, 0, 513, 64] + .into_iter() + .map(|height| fixture::(height, true)) + .unzip(); + let lookups: Vec<_> = traces + .iter() + .zip(&circuits) + .map(|(trace, circuit)| compute_lookup_values(circuit, trace)) + .collect(); + let group_sizes = [2, 1, 3, 1]; + let challenges = [ + ExtVal::from_u8(29), + ExtVal::from_u8(31), + ExtVal::from_u8(37), + ]; + let (joint_traces, joint_totals) = LookupValues::stage_2_traces( + &lookups, + &group_sizes, + challenges[0], + &challenges[1], + challenges[2], + ); + let mut acc = challenges[2]; + for (position, values) in lookups.iter().enumerate() { + let (traces, totals) = LookupValues::stage_2_traces( + std::slice::from_ref(values), + &group_sizes[position..=position], + challenges[0], + &challenges[1], + acc, + ); + assert_eq!(totals, [joint_totals[position]]); + assert_eq!(traces[0].dimensions(), joint_traces[position].dimensions()); + assert_eq!(traces[0].values, joint_traces[position].values); + acc = totals[0]; + } +} + #[test] fn lookup_witness_preserves_proof_bytes() { let inputs = [false, true].map(|pull| CircuitInputs { From c7fe4900d3d64009627a518e113227a02703b04f Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:46:52 +0000 Subject: [PATCH 06/28] Keep generated-trace commitments resident and concurrent when memory allows A main commitment with any generated source took a serial path that released every device trace right after its LDE, so the lookup pass had to re-upload host traces or regenerate generated ones, and no matrix's LDE overlapped another's. When the whole batch fits beside the minimum free headroom, the prepared path now builds its LDEs in the same bounded concurrent waves as the all-host path, keeps device traces resident under the same release policy, and retains host traces as recovery sources. The serial, spilling construction remains for batches that do not fit. Lookups no longer release a generator's device cache unconditionally after each matrix; admission already releases those caches first whenever a later phase is short of memory. --- cuda/kernels.cu | 14 ++ src/cuda/mod.rs | 9 ++ src/cuda/tests/witness.rs | 157 ++++++++++++++++++++ src/cuda/witness.rs | 305 +++++++++++++++++++++++++++++--------- src/types.rs | 5 +- 5 files changed, 420 insertions(+), 70 deletions(-) create mode 100644 src/cuda/tests/witness.rs diff --git a/cuda/kernels.cu b/cuda/kernels.cu index f8eec6b..61c0389 100644 --- a/cuda/kernels.cu +++ b/cuda/kernels.cu @@ -2239,6 +2239,20 @@ extern "C" int multi_stark_cuda_lde_copy_to_host(int device_id, return static_cast(status); } +extern "C" int multi_stark_cuda_copy_to_device(int device_id, uint64_t* output, + const uint64_t* input, size_t words) { + if ((output == nullptr || input == nullptr) && words != 0) { + return static_cast(cudaErrorInvalidValue); + } + cudaError_t status = cudaSetDevice(device_id); + if (status == cudaSuccess && words != 0) { + status = cudaMemcpyAsync(output, input, words * sizeof(uint64_t), + cudaMemcpyHostToDevice, cudaStreamPerThread); + } + if (status == cudaSuccess) status = cudaStreamSynchronize(cudaStreamPerThread); + return static_cast(status); +} + extern "C" int multi_stark_cuda_lde_copy_row(int device_id, const void* handle, size_t row, diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 19d8d00..b98ef5a 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -3014,6 +3014,14 @@ unsafe extern "C" { width: usize, ) -> i32; + #[cfg(test)] + fn multi_stark_cuda_copy_to_device( + device_id: i32, + output: *mut u64, + input: *const u64, + words: usize, + ) -> i32; + #[cfg(test)] fn multi_stark_cuda_lde_copy_row( device_id: i32, @@ -3481,6 +3489,7 @@ mod tests { mod lookup_graph; mod quotient; + mod witness; #[test] fn device_coset_selectors_match_cpu() { diff --git a/src/cuda/tests/witness.rs b/src/cuda/tests/witness.rs new file mode 100644 index 0000000..d2bfebf --- /dev/null +++ b/src/cuda/tests/witness.rs @@ -0,0 +1,157 @@ +use super::*; +use crate::config::ProofConfig; +use crate::cuda::witness::commit_with; +use crate::types::{CommitmentParameters, FriParameters, GoldilocksBlake3Config}; +use crate::witness::{TraceGenerator, TraceSource}; +use p3_field::coset::TwoAdicMultiplicativeCoset; + +/// A generated source serving the rows of a host matrix. +struct HostRows(RowMajorMatrix); + +impl HostRows { + fn runs( + &self, + first: usize, + rows: usize, + mut copy: impl FnMut(usize, &[Goldilocks]) -> Result<(), String>, + ) -> Result<(), String> { + let (width, height) = (self.0.width(), self.0.height()); + let mut done = 0; + while done < rows { + let row = (first + done) % height; + let run = (height - row).min(rows - done); + copy( + done * width, + &self.0.values[row * width..(row + run) * width], + )?; + done += run; + } + Ok(()) + } +} + +impl TraceGenerator for HostRows { + fn height(&self) -> usize { + self.0.height() + } + + fn width(&self) -> usize { + self.0.width() + } + + fn write_rows(&self, first: usize, output: &mut [Goldilocks]) { + self.runs(first, output.len() / self.0.width(), |offset, values| { + output[offset..offset + values.len()].copy_from_slice(values); + Ok(()) + }) + .unwrap(); + } + + fn write_device_rows(&self, view: DeviceTraceView<'_>) -> Result<(), String> { + self.runs(view.first_row(), view.rows(), |offset, values| { + // SAFETY: the tile holds `rows * width` words from `as_mut_ptr`, + // and `offset + values.len()` stays within it. + let status = unsafe { + multi_stark_cuda_copy_to_device( + view.device_id(), + view.as_mut_ptr().add(offset), + values.as_ptr().cast(), + values.len(), + ) + }; + if status == 0 { + Ok(()) + } else { + Err(format!("tile upload failed with CUDA status {status}")) + } + }) + } +} + +#[test] +#[ignore = "requires a CUDA GPU; commits generated and host sources through both prepared constructions"] +fn generated_sources_commit_like_host_matrices() { + let config = GoldilocksBlake3Config::with_device( + CommitmentParameters { + log_blowup: 1, + cap_height: 0, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 8, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + Some(configured_device()), + ); + let pcs: &crate::types::InnerPcs = config.pcs(); + // Without an override the batch fits resident on any CUDA device. + // Heights repeat so that height groups mix both kinds of source. The + // 2^20 x 10 matrix puts the batch over the concurrent-construction + // threshold, and the 4100-column group is hashed on the host. + let shapes = [ + (1 << 4, 3), + (1 << 10, 7), + (1 << 10, 2), + (1 << 6, 4100), + (1 << 16, 5), + (1 << 20, 10), + (1 << 12, 1), + ]; + let matrices: Vec<_> = shapes + .iter() + .enumerate() + .map(|(seed, &(height, width))| { + RowMajorMatrix::new( + (0..height * width) + .map(|index| Goldilocks::from_u64((index as u64 * 0x9e37_79b9) ^ seed as u64)) + .collect(), + width, + ) + }) + .collect(); + let evaluations = |generated: &dyn Fn(usize) -> bool| { + matrices + .iter() + .enumerate() + .map(|(index, matrix)| { + let domain = TwoAdicMultiplicativeCoset::new( + Goldilocks::ONE, + log2_strict_usize(matrix.height()), + ) + .unwrap(); + let source = if generated(index) { + TraceSource::Generated(Arc::new(HostRows(matrix.clone()))) + } else { + TraceSource::Host(matrix.clone()) + }; + (domain, source) + }) + .collect::>() + }; + let (expected, _) = commit_with(pcs, evaluations(&|_| false), None); + let patterns: [&dyn Fn(usize) -> bool; 3] = + [&|index| index % 2 == 0, &|index| index % 2 == 1, &|_| true]; + for keep_traces in [None, Some(true), Some(false)] { + for generated in patterns { + let (commitment, data) = commit_with(pcs, evaluations(generated), keep_traces); + assert_eq!(commitment, expected, "keep_traces={keep_traces:?}"); + for (index, &(height, width)) in shapes.iter().enumerate() { + let host_hashed = width * size_of::() > mmcs::MAX_DEVICE_LEAF_ROW_BYTES; + let Some(lde) = data.resident(index) else { + assert!( + host_hashed, + "matrix {index} of height {height} left the device" + ); + continue; + }; + assert_eq!( + lde.has_device_trace(), + keep_traces != Some(false), + "matrix {index}: device trace residency" + ); + } + } + } +} diff --git a/src/cuda/witness.rs b/src/cuda/witness.rs index a7e4bad..29eb78e 100644 --- a/src/cuda/witness.rs +++ b/src/cuda/witness.rs @@ -5,6 +5,7 @@ use std::sync::{OnceLock, atomic::AtomicBool}; use p3_commit::Pcs; use p3_field::Field; use p3_matrix::{Dimensions, dense::RowMajorMatrix}; +use p3_maybe_rayon::prelude::*; use p3_symmetric::MerkleCap; use super::mmcs::CudaMmcsData; @@ -28,6 +29,23 @@ fn spill_lde(lde: &CudaLde) -> RowMajorMatrix { pub(crate) fn commit( pcs: &CudaPcs, evaluations: Vec<(Domain, TraceSource)>, +) -> (Com, PcsData) { + commit_with(pcs, evaluations, None) +} + +/// Stage-one LDEs with the per-matrix storage the Merkle tree is built over. +struct Constructed { + resident: Vec>, + host: Vec>>, + retained: Vec>>, +} + +/// `keep_traces` overrides the memory-derived choice between the resident +/// and the bounded construction, so tests can exercise both. +pub(crate) fn commit_with( + pcs: &CudaPcs, + evaluations: Vec<(Domain, TraceSource)>, + keep_traces: Option, ) -> (Com, PcsData) { if evaluations .iter() @@ -64,74 +82,54 @@ pub(crate) fn commit( ); } let max_height = dimensions.iter().map(|d| d.height).max().unwrap(); - let (_, total) = device_memory_info(device); - let reserve = super::minimum_free_bytes(total).saturating_add(128 << 20); - let mut resident: Vec> = Vec::with_capacity(evaluations.len()); - let mut host: Vec>> = Vec::with_capacity(evaluations.len()); - let mut retained = Vec::with_capacity(evaluations.len()); - for (domain, source) in evaluations { - let shift = Val::GENERATOR / domain.shift(); - let plan = pcs - .dft - .lde_plan(source.height(), source.width(), blowup, shift); - let needed = source - .height() - .saturating_mul(source.width()) - .saturating_mul(8) - .saturating_mul((1 << blowup) + 1) - .saturating_add(plan.scratch_bytes()) - .saturating_add(plan.constant_bytes()) - .saturating_add(reserve); - // Generator caches go before any LDE spills: they are rebuilt from - // host seeds on demand, a spilled LDE is uploaded again. - for slot in resident.iter() { - if device_memory_info(device).0 >= needed { - break; - } - slot.as_ref().unwrap().release_generator_device(); - } - for index in 0..resident.len() { - if device_memory_info(device).0 >= needed { - break; - } - if host[index].is_none() { - let lde = resident[index].as_ref().unwrap(); - host[index] = Some(spill_lde(lde)); - } - } - assert!( - device_memory_info(device).0 >= needed, - "generated trace commitment exceeds device admission; reduce the shard cell budget" - ); - let source_span = tracing::info_span!( - "stark/commit_source", - kind = match &source { - TraceSource::Host(_) => "host", - TraceSource::Generated(_) => "generated", - }, - height = source.height(), - width = source.width() - ) - .entered(); - pcs.dft - .prepare_coset_lde_constants(source.height(), blowup, shift); - let (lde, trace) = match source { - TraceSource::Host(matrix) => ( - pcs.dft.coset_lde_batch_resident(&matrix, blowup, shift), - Some(matrix), - ), - TraceSource::Generated(source) => { - (pcs.dft.generate_coset_lde(source, blowup, shift), None) - } - }; - // Both kinds retain a bounded recovery source. Raw device rows need - // not coexist with later lookup/quotient workspace. - unsafe { lde.release_trace() }; - resident.push(Some(lde)); - host.push(None); - retained.push(trace); - drop(source_span); - } + let (initial_free, total) = device_memory_info(device); + let minimum_free = super::minimum_free_bytes(total); + let reserve = minimum_free.saturating_add(128 << 20); + let source_bytes = evaluations + .iter() + .map(|(_, m)| m.height().saturating_mul(m.width())) + .sum::() + .saturating_mul(size_of::()); + let lde_bytes = source_bytes + .checked_shl(blowup.try_into().expect("LDE blowup exceeds u32")) + .unwrap_or(usize::MAX); + let max_workspace = evaluations + .iter() + .map(|(domain, source)| { + let plan = pcs.dft.lde_plan( + source.height(), + source.width(), + blowup, + Val::GENERATOR / domain.shift(), + ); + plan.scratch_bytes().saturating_add(plan.constant_bytes()) + }) + .max() + .unwrap_or(0); + // Every trace and LDE stays resident through the tree build, as on the + // all-host path when its batch fits beside the minimum free headroom. + let resident_footprint = source_bytes + .saturating_add(lde_bytes) + .saturating_add(max_workspace) + .saturating_add(max_height.saturating_mul(96)) + .saturating_add(reserve); + let keep_traces = keep_traces.unwrap_or(resident_footprint <= initial_free); + let Constructed { + resident, + mut host, + retained, + } = if keep_traces { + let wave_size = initial_free + .saturating_sub(source_bytes) + .saturating_sub(lde_bytes) + .saturating_sub(reserve) + .checked_div(max_workspace.max(1)) + .unwrap_or(1) + .clamp(1, CUDA_LDE_WAVE); + construct_resident(pcs, evaluations, source_bytes, total, wave_size) + } else { + construct_bounded(pcs, evaluations, reserve) + }; let _merkle_span = tracing::info_span!("stark/commit_merkle").entered(); let needed = max_height.saturating_mul(96).saturating_add(reserve); for index in 0..resident.len() { @@ -202,3 +200,174 @@ pub(crate) fn commit( }, ) } + +/// Concurrent LDE construction, bounded by the device's transform workspace, +/// as the all-host path admits it. +const CUDA_LDE_WAVE: usize = 16; + +fn lde_of(pcs: &CudaPcs, domain: &Domain, source: &TraceSource) -> CudaLde { + let blowup = pcs.fri.log_blowup; + let shift = Val::GENERATOR / domain.shift(); + let _source_span = tracing::info_span!( + "stark/commit_source", + kind = match source { + TraceSource::Host(_) => "host", + TraceSource::Generated(_) => "generated", + }, + height = source.height(), + width = source.width() + ) + .entered(); + match source { + TraceSource::Host(matrix) => pcs.dft.coset_lde_batch_resident(matrix, blowup, shift), + TraceSource::Generated(generator) => { + pcs.dft + .generate_coset_lde(std::sync::Arc::clone(generator), blowup, shift) + } + } +} + +/// Builds every LDE in concurrent waves and keeps each device trace for the +/// lookup pass, releasing traces only where the all-host path would: when +/// this commitment is large enough to crowd later stages, or free memory +/// falls below the minimum headroom. +fn construct_resident( + pcs: &CudaPcs, + evaluations: Vec<(Domain, TraceSource)>, + source_bytes: usize, + total_bytes: usize, + wave_size: usize, +) -> Constructed { + let device = pcs.dft.device_id(); + let blowup = pcs.fri.log_blowup; + for (domain, source) in &evaluations { + pcs.dft.prepare_coset_lde_constants( + source.height(), + blowup, + Val::GENERATOR / domain.shift(), + ); + } + // Small batches of many tiny matrices lose more to concurrent CUDA entry + // than they gain from overlap. + let parallel = source_bytes >= 10_000_000 * size_of::(); + let mut ldes = Vec::with_capacity(evaluations.len()); + for wave in evaluations.chunks(wave_size) { + let transform = + |(domain, source): &(Domain, TraceSource)| lde_of(pcs, domain, source); + let wave_ldes: Vec<_> = if parallel { + wave.par_iter().map(transform).collect() + } else { + wave.iter().map(transform).collect() + }; + ldes.extend(wave_ldes); + } + let (free_bytes, _) = device_memory_info(device); + let minimum_free = super::minimum_free_bytes(total_bytes); + let proactive_spill = source_bytes >= total_bytes / 12; + let large_matrix = total_bytes / 120; + let mut projected_free = free_bytes; + let mut by_size: Vec<_> = evaluations + .iter() + .enumerate() + .map(|(index, (_, source))| { + ( + index, + source + .height() + .saturating_mul(source.width()) + .saturating_mul(size_of::()), + ) + }) + .collect(); + by_size.sort_unstable_by_key(|&(_, bytes)| core::cmp::Reverse(bytes)); + for (index, bytes) in by_size { + let needs_headroom = projected_free < minimum_free; + let crowds_later_stages = proactive_spill && bytes >= large_matrix; + if !needs_headroom && !crowds_later_stages { + break; + } + // SAFETY: construction is synchronous and complete; a host source + // stays retained below and a generated one regenerates its rows. + unsafe { ldes[index].release_trace() }; + projected_free = projected_free.saturating_add(bytes); + } + let count = ldes.len(); + Constructed { + resident: ldes.into_iter().map(Some).collect(), + host: (0..count).map(|_| None).collect(), + retained: evaluations + .into_iter() + .map(|(_, source)| match source { + TraceSource::Host(matrix) => Some(matrix), + TraceSource::Generated(_) => None, + }) + .collect(), + } +} + +/// Builds one LDE at a time when the batch does not fit resident. Each +/// device trace is released after its LDE, and earlier LDEs spill to the +/// host whenever the next one would leave less than `reserve` free. +fn construct_bounded( + pcs: &CudaPcs, + evaluations: Vec<(Domain, TraceSource)>, + reserve: usize, +) -> Constructed { + let device = pcs.dft.device_id(); + let blowup = pcs.fri.log_blowup; + let mut resident: Vec> = Vec::with_capacity(evaluations.len()); + let mut host: Vec>> = Vec::with_capacity(evaluations.len()); + let mut retained = Vec::with_capacity(evaluations.len()); + for (domain, source) in evaluations { + let shift = Val::GENERATOR / domain.shift(); + let plan = pcs + .dft + .lde_plan(source.height(), source.width(), blowup, shift); + let needed = source + .height() + .saturating_mul(source.width()) + .saturating_mul(8) + .saturating_mul((1 << blowup) + 1) + .saturating_add(plan.scratch_bytes()) + .saturating_add(plan.constant_bytes()) + .saturating_add(reserve); + // Generator caches go before any LDE spills: they are rebuilt from + // host seeds on demand, a spilled LDE is uploaded again. + for slot in resident.iter() { + if device_memory_info(device).0 >= needed { + break; + } + slot.as_ref().unwrap().release_generator_device(); + } + for index in 0..resident.len() { + if device_memory_info(device).0 >= needed { + break; + } + if host[index].is_none() { + let lde = resident[index].as_ref().unwrap(); + host[index] = Some(spill_lde(lde)); + } + } + assert!( + device_memory_info(device).0 >= needed, + "generated trace commitment exceeds device admission; reduce the shard cell budget" + ); + pcs.dft + .prepare_coset_lde_constants(source.height(), blowup, shift); + let lde = lde_of(pcs, &domain, &source); + // Both kinds retain a bounded recovery source. Raw device rows need + // not coexist with later lookup/quotient workspace. + unsafe { lde.release_trace() }; + resident.push(Some(lde)); + host.push(None); + retained.push(match source { + TraceSource::Host(matrix) => Some(matrix), + TraceSource::Generated(_) => None, + }); + } + Constructed { + resident, + host, + retained, + } +} diff --git a/src/types.rs b/src/types.rs index 567451e..fe109ac 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1028,10 +1028,11 @@ impl ProofConfig for GoldilocksBlake3Config { )) }; // SAFETY: evaluation is synchronous and complete, while the - // retained matrix remains owned by the prover data. + // retained matrix remains owned by the prover data. A generator's + // device cache stays: admission releases it under memory pressure, + // and later lookups over the same record would otherwise rebuild it. if let Some(main) = main { unsafe { main.release_trace() }; - main.release_generator_device(); } result }; From 3de4ed54a8cc3298962953f629327f92c35470b9 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:37:34 +0000 Subject: [PATCH 07/28] Reserve trace writers' device workspace in commitment admission A generated source may allocate device scratch for each tile it writes, and the resident construction runs up to MAX_CONCURRENT_LDES of them at once. TraceGenerator::device_workspace_bytes declares that scratch; both constructions add it to each matrix's transform workspace, so the resident wave size and the bounded path's admission reserve it per concurrent writer. MAX_CONCURRENT_LDES is public so a producer can plan for the same bound. --- src/cuda/mod.rs | 6 ++++++ src/cuda/pcs.rs | 3 +-- src/cuda/tests/witness.rs | 4 ++++ src/cuda/witness.rs | 16 +++++++++++----- src/witness.rs | 12 +++++++++++- 5 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index b98ef5a..83d06af 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2248,6 +2248,12 @@ fn raw_u64(value: Goldilocks) -> u64 { value.as_canonical_u64() } +/// The most stage-one LDEs a commitment builds concurrently, each on its own +/// Rayon worker stream. The bound keeps pageable upload staging within the +/// driver's reliable concurrency range while retaining substantial overlap; +/// it also bounds how many trace writers run at once. +pub const MAX_CONCURRENT_LDES: usize = 16; + pub(crate) fn device_memory_info(device_id: i32) -> (usize, usize) { let mut free_bytes = 0; let mut total_bytes = 0; diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index a5ea164..b04688c 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -1070,7 +1070,6 @@ where // Each Rayon worker uses its own per-thread CUDA stream. A bounded // admission window keeps pageable upload staging within the driver's // reliable concurrency range while retaining substantial overlap. - const CUDA_LDE_WAVE: usize = 16; let mut ldes = Vec::with_capacity(evaluations.len()); let wave_size = if release_traces_during_construction { 1 @@ -1079,7 +1078,7 @@ where .saturating_sub(source_bytes) .saturating_sub(lde_bytes) .saturating_sub(minimum_free); - (workspace_budget / max_transform_workspace.max(1)).clamp(1, CUDA_LDE_WAVE) + (workspace_budget / max_transform_workspace.max(1)).clamp(1, super::MAX_CONCURRENT_LDES) }; for wave in evaluations.chunks(wave_size) { let transform = diff --git a/src/cuda/tests/witness.rs b/src/cuda/tests/witness.rs index d2bfebf..0bb652b 100644 --- a/src/cuda/tests/witness.rs +++ b/src/cuda/tests/witness.rs @@ -47,6 +47,10 @@ impl TraceGenerator for HostRows { .unwrap(); } + fn device_workspace_bytes(&self) -> usize { + 1 << 20 + } + fn write_device_rows(&self, view: DeviceTraceView<'_>) -> Result<(), String> { self.runs(view.first_row(), view.rows(), |offset, values| { // SAFETY: the tile holds `rows * width` words from `as_mut_ptr`, diff --git a/src/cuda/witness.rs b/src/cuda/witness.rs index 29eb78e..98dd94c 100644 --- a/src/cuda/witness.rs +++ b/src/cuda/witness.rs @@ -102,7 +102,9 @@ pub(crate) fn commit_with( blowup, Val::GENERATOR / domain.shift(), ); - plan.scratch_bytes().saturating_add(plan.constant_bytes()) + plan.scratch_bytes() + .saturating_add(plan.constant_bytes()) + .saturating_add(writer_workspace(source)) }) .max() .unwrap_or(0); @@ -125,7 +127,7 @@ pub(crate) fn commit_with( .saturating_sub(reserve) .checked_div(max_workspace.max(1)) .unwrap_or(1) - .clamp(1, CUDA_LDE_WAVE); + .clamp(1, super::MAX_CONCURRENT_LDES); construct_resident(pcs, evaluations, source_bytes, total, wave_size) } else { construct_bounded(pcs, evaluations, reserve) @@ -201,9 +203,12 @@ pub(crate) fn commit_with( ) } -/// Concurrent LDE construction, bounded by the device's transform workspace, -/// as the all-host path admits it. -const CUDA_LDE_WAVE: usize = 16; +fn writer_workspace(source: &TraceSource) -> usize { + match source { + TraceSource::Host(_) => 0, + TraceSource::Generated(generator) => generator.device_workspace_bytes(), + } +} fn lde_of(pcs: &CudaPcs, domain: &Domain, source: &TraceSource) -> CudaLde { let blowup = pcs.fri.log_blowup; @@ -330,6 +335,7 @@ fn construct_bounded( .saturating_mul((1 << blowup) + 1) .saturating_add(plan.scratch_bytes()) .saturating_add(plan.constant_bytes()) + .saturating_add(writer_workspace(&source)) .saturating_add(reserve); // Generator caches go before any LDE spills: they are rebuilt from // host seeds on demand, a spilled LDE is uploaded again. diff --git a/src/witness.rs b/src/witness.rs index 1b99ce8..2ddc54e 100644 --- a/src/witness.rs +++ b/src/witness.rs @@ -1,4 +1,5 @@ -//! Owned, deterministic main-trace sources. Producers do not allocate device memory. +//! Owned, deterministic main-trace sources. A producer allocates device memory +//! only for the workspace it declares to commitment admission. use std::sync::Arc; @@ -16,6 +17,15 @@ pub trait TraceGenerator: Send + Sync { #[cfg(feature = "cuda")] fn write_device_rows(&self, output: crate::cuda::DeviceTraceView<'_>) -> Result<(), String>; + /// Device scratch one `write_device_rows` call may allocate besides its + /// output tile. Up to [`crate::cuda::MAX_CONCURRENT_LDES`] calls on + /// different sources can run at once, and commitment admission reserves + /// this for each. + #[cfg(feature = "cuda")] + fn device_workspace_bytes(&self) -> usize { + 0 + } + /// Free whatever the source keeps on `device_id` to serve tiles faster, /// such as seeds left resident between a commitment and the lookup pass /// that regenerates rows from them. Tiles must still be served afterwards. From f120089a81c8b3f73ab15e9be7e26d9b30f95274 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:18:40 +0000 Subject: [PATCH 08/28] Admit restoring released generator state before it is rebuilt A generated source's cached device state (Aiur's population record) can be released by admission and is allocated again by the next tile it writes, but no admission counted that allocation. A graph lookup whose trace must be regenerated could therefore run out of memory after its own admission released the state, and the bounded and resident commitment paths could start a generated source whose released state did not fit. TraceGenerator gains device_state_bytes and device_state_resident. A lookup that regenerates its trace now admits the state's full size plus one write workspace, so releasing it during the same admission cannot leave too little room. Commitment admission adds the state when a generated source must restore it, the bounded path no longer releases generator caches just before a generated source, and the resident path reserves the restore beside its waves. The commitment test's generators allocate the workspace they declare and share releasable state. A new test fills the device so that lookup admission releases that state while both traces need regenerating; it fails with an out-of-memory panic without the lookup change and proves host population's bytes with it. Both tests need a CUDA device and are ignored by default like the crate's other device tests; the new one also needs the device to itself. --- src/cuda/mmcs.rs | 12 +++ src/cuda/mod.rs | 28 ++++- src/cuda/tests/witness.rs | 213 +++++++++++++++++++++++++++++++++++--- src/cuda/witness.rs | 32 +++++- src/types.rs | 6 +- src/witness.rs | 16 +++ 6 files changed, 284 insertions(+), 23 deletions(-) diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index 245c0e1..442c2fe 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -230,6 +230,18 @@ impl CudaMmcsData> { } } + /// Device bytes the graph lookup over matrix `index` may allocate to + /// regenerate its trace; see [`CudaLde::regeneration_bytes`]. A spilled + /// hybrid LDE keeps its generator and counts too. + pub(crate) fn regeneration_bytes(&self, index: usize) -> usize { + let lde = match self { + Self::Cuda { resident, .. } => resident.get(index), + Self::Hybrid { resident, .. } => resident.get(index).and_then(Option::as_ref), + Self::Cpu(_) => None, + }; + lde.map_or(0, CudaLde::regeneration_bytes) + } + /// The resident LDE together with a retained host copy of its trace, if /// any, for readers that take the original trace without attaching it to /// the LDE. Unlike [`Self::resident_with_trace`] this never mutates the diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 83d06af..815727e 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -387,14 +387,32 @@ impl CudaLde { /// Frees what the trace generator, if any, caches on this device. The /// generator stays attached and keeps serving tiles from the host. pub(crate) fn release_generator_device(&self) { - let context = unsafe { multi_stark_cuda_lde_generator_context(self.raw_handle()) }; - if context.is_null() { - return; + if let Some(generator) = self.generator() { + generator.release_device(self.device_id); + } + } + + /// Device bytes regenerating this LDE's trace may allocate: its + /// generator's releasable state, whether or not it is resident now, since + /// admission can release it before the regeneration runs, plus one write + /// workspace. Zero while the trace is on the device or without a + /// generator. + pub(crate) fn regeneration_bytes(&self) -> usize { + if self.has_device_trace() { + return 0; } + self.generator().map_or(0, |generator| { + generator + .device_state_bytes() + .saturating_add(generator.device_workspace_bytes()) + }) + } + + fn generator(&self) -> Option<&Generator> { + let context = unsafe { multi_stark_cuda_lde_generator_context(self.raw_handle()) }; // SAFETY: the handle owns the boxed generator until it is destroyed, // and the box holds exactly the `Generator` the LDE was created with. - let generator = unsafe { &*context.cast::() }; - generator.release_device(self.device_id); + (!context.is_null()).then(|| unsafe { &*context.cast::() }) } pub(crate) const fn raw_handle(&self) -> *const c_void { diff --git a/src/cuda/tests/witness.rs b/src/cuda/tests/witness.rs index 0bb652b..2d152d5 100644 --- a/src/cuda/tests/witness.rs +++ b/src/cuda/tests/witness.rs @@ -5,24 +5,70 @@ use crate::types::{CommitmentParameters, FriParameters, GoldilocksBlake3Config}; use crate::witness::{TraceGenerator, TraceSource}; use p3_field::coset::TwoAdicMultiplicativeCoset; -/// A generated source serving the rows of a host matrix. -struct HostRows(RowMajorMatrix); +/// Device memory owned by a test, freed on drop. +fn device_allocation(bytes: usize) -> CudaLde { + let width = 2; + let height = (bytes / (8 * width)).next_power_of_two(); + let device = configured_device(); + let mut handle = core::ptr::null_mut(); + // SAFETY: the out-pointer is valid for writing; success transfers the + // allocation to the returned handle. + let status = unsafe { multi_stark_cuda_zero_lde_create(device, &mut handle, height, width) }; + check_cuda(status, "test device allocation"); + CudaLde { + device_id: device, + handle: NonNull::new(handle).expect("null test allocation"), + height, + width, + } +} + +/// Device state several generated sources share, released on request and +/// allocated again by the next tile, as a population record is. +struct SharedState { + bytes: usize, + resident: std::sync::Mutex>, + releases: std::sync::atomic::AtomicUsize, +} + +impl SharedState { + fn new(bytes: usize) -> Arc { + Arc::new(Self { + bytes, + resident: std::sync::Mutex::new(None), + releases: std::sync::atomic::AtomicUsize::new(0), + }) + } +} + +/// A generated source serving the rows of a host matrix. Each tile write +/// allocates the workspace it declares, and the shared state if released. +struct HostRows { + matrix: RowMajorMatrix, + state: Option>, +} + +const WRITER_WORKSPACE: usize = 1 << 20; impl HostRows { + fn new(matrix: RowMajorMatrix, state: Option>) -> Self { + Self { matrix, state } + } + fn runs( &self, first: usize, rows: usize, mut copy: impl FnMut(usize, &[Goldilocks]) -> Result<(), String>, ) -> Result<(), String> { - let (width, height) = (self.0.width(), self.0.height()); + let (width, height) = (self.matrix.width(), self.matrix.height()); let mut done = 0; while done < rows { let row = (first + done) % height; let run = (height - row).min(rows - done); copy( done * width, - &self.0.values[row * width..(row + run) * width], + &self.matrix.values[row * width..(row + run) * width], )?; done += run; } @@ -32,26 +78,57 @@ impl HostRows { impl TraceGenerator for HostRows { fn height(&self) -> usize { - self.0.height() + self.matrix.height() } fn width(&self) -> usize { - self.0.width() + self.matrix.width() } fn write_rows(&self, first: usize, output: &mut [Goldilocks]) { - self.runs(first, output.len() / self.0.width(), |offset, values| { - output[offset..offset + values.len()].copy_from_slice(values); - Ok(()) - }) + self.runs( + first, + output.len() / self.matrix.width(), + |offset, values| { + output[offset..offset + values.len()].copy_from_slice(values); + Ok(()) + }, + ) .unwrap(); } fn device_workspace_bytes(&self) -> usize { - 1 << 20 + WRITER_WORKSPACE + } + + fn device_state_bytes(&self) -> usize { + self.state.as_ref().map_or(0, |state| state.bytes) + } + + fn device_state_resident(&self) -> bool { + self.state + .as_ref() + .is_none_or(|state| state.resident.lock().unwrap().is_some()) + } + + fn release_device(&self, _device_id: i32) { + if let Some(state) = &self.state + && state.resident.lock().unwrap().take().is_some() + { + state + .releases + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } } fn write_device_rows(&self, view: DeviceTraceView<'_>) -> Result<(), String> { + if let Some(state) = &self.state { + let mut resident = state.resident.lock().unwrap(); + if resident.is_none() { + *resident = Some(device_allocation(state.bytes)); + } + } + let _workspace = device_allocation(WRITER_WORKSPACE); self.runs(view.first_row(), view.rows(), |offset, values| { // SAFETY: the tile holds `rows * width` words from `as_mut_ptr`, // and `offset + values.len()` stays within it. @@ -115,6 +192,8 @@ fn generated_sources_commit_like_host_matrices() { ) }) .collect(); + const STATE: usize = 8 << 20; + let state = SharedState::new(STATE); let evaluations = |generated: &dyn Fn(usize) -> bool| { matrices .iter() @@ -126,7 +205,10 @@ fn generated_sources_commit_like_host_matrices() { ) .unwrap(); let source = if generated(index) { - TraceSource::Generated(Arc::new(HostRows(matrix.clone()))) + TraceSource::Generated(Arc::new(HostRows::new( + matrix.clone(), + Some(Arc::clone(&state)), + ))) } else { TraceSource::Host(matrix.clone()) }; @@ -155,7 +237,114 @@ fn generated_sources_commit_like_host_matrices() { keep_traces != Some(false), "matrix {index}: device trace residency" ); + // A released trace regenerates through its generator, which + // may first have to restore the shared state. + let regeneration = if keep_traces == Some(false) && generated(index) { + STATE + WRITER_WORKSPACE + } else { + 0 + }; + assert_eq!(data.regeneration_bytes(index), regeneration); } + // Releasing the shared state makes the next generated commitment + // restore it. + data.resident(0) + .into_iter() + .chain(data.resident(1)) + .for_each(CudaLde::release_generator_device); } } + assert!(state.releases.load(std::sync::atomic::Ordering::Relaxed) > 0); +} + +/// A batch whose lookups run short of device memory releases the generators' +/// shared state during lookup admission. Lookups that then regenerate a +/// trace must admit restoring that state, or fall back to the host, rather +/// than fail to allocate it; the proof must equal host population's. +#[test] +#[ignore = "requires exclusive access to a CUDA device: fills most of its memory"] +fn generated_traces_prove_identically_under_lookup_pressure() { + use crate::expr::Expr; + use crate::lookup::Lookup; + use crate::system::{CircuitInputs, System, SystemWitness}; + use crate::witness::PreparedWitness; + let config = GoldilocksBlake3Config::with_device( + CommitmentParameters { + log_blowup: 1, + cap_height: 0, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 8, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + Some(configured_device()), + ); + let inputs = [false, true].map(|pull| { + let args = vec![Expr::main(0), Expr::main_next(1)]; + CircuitInputs { + main_width: 2, + lookups: vec![if pull { + Lookup::pull(Expr::constant(Goldilocks::ONE), args) + } else { + Lookup::push(Expr::constant(Goldilocks::ONE), args) + }], + ..Default::default() + } + }); + let (system, key) = System::new(config, inputs); + let height: usize = 1 << 20; + let trace = RowMajorMatrix::new( + (0..2 * height) + .map(|index| Goldilocks::from_u64(index as u64 * 0x9e37_79b9)) + .collect(), + 2, + ); + let traces = vec![trace.clone(), trace]; + let no_claims: &[&[Goldilocks]] = &[]; + let host = SystemWitness::from_stage_1(traces.clone(), &system); + let lookups = host.lookups.clone(); + let expected = system.prove_multiple_claims(&key, no_claims, host); + + let (_, total) = device_memory_info(configured_device()); + let state = SharedState::new(total / 32); + let witness = PreparedWitness { + traces: traces + .into_iter() + .map(|trace| { + TraceSource::Generated(Arc::new(HostRows::new(trace, Some(Arc::clone(&state))))) + }) + .collect(), + lookups, + }; + let stage_1 = system.prove_stage_1(witness); + // Without their device traces the graph lookups regenerate rows, which + // restores the shared state once lookup admission has released it. + for index in 0..2 { + let lde = stage_1.stage_1_trace_data.resident(index).unwrap(); + // SAFETY: commitment is complete and nothing reads the trace until + // the lookups regenerate it. + unsafe { lde.release_trace() }; + } + // Leave less free than one lookup job's output and temporaries, so that + // admission releases the state and restoring it could not fit. + let (free, _) = device_memory_info(configured_device()); + let mut ballast = Vec::new(); + let mut remaining = free.saturating_sub(total / 4096); + while remaining >= 1 << 20 { + let chunk = (remaining / 2 + 1).next_power_of_two() / 2; + let chunk = chunk.min(1 << 30); + ballast.push(device_allocation(chunk)); + remaining -= chunk; + } + let proof = system.prove_committed(&key, no_claims, stage_1); + drop(ballast); + assert!(state.releases.load(std::sync::atomic::Ordering::Relaxed) > 0); + system.verify_multiple_claims(no_claims, &proof).unwrap(); + assert_eq!( + bincode::serde::encode_to_vec(&proof, bincode::config::standard()).unwrap(), + bincode::serde::encode_to_vec(&expected, bincode::config::standard()).unwrap() + ); } diff --git a/src/cuda/witness.rs b/src/cuda/witness.rs index 98dd94c..99e1176 100644 --- a/src/cuda/witness.rs +++ b/src/cuda/witness.rs @@ -108,11 +108,17 @@ pub(crate) fn commit_with( }) .max() .unwrap_or(0); + let restore = evaluations + .iter() + .map(|(_, source)| state_restore_bytes(source)) + .max() + .unwrap_or(0); // Every trace and LDE stays resident through the tree build, as on the // all-host path when its batch fits beside the minimum free headroom. let resident_footprint = source_bytes .saturating_add(lde_bytes) .saturating_add(max_workspace) + .saturating_add(restore) .saturating_add(max_height.saturating_mul(96)) .saturating_add(reserve); let keep_traces = keep_traces.unwrap_or(resident_footprint <= initial_free); @@ -124,6 +130,7 @@ pub(crate) fn commit_with( let wave_size = initial_free .saturating_sub(source_bytes) .saturating_sub(lde_bytes) + .saturating_sub(restore) .saturating_sub(reserve) .checked_div(max_workspace.max(1)) .unwrap_or(1) @@ -210,6 +217,17 @@ fn writer_workspace(source: &TraceSource) -> usize { } } +/// Device bytes a generated source allocates to restore released state +/// before its first tile. +fn state_restore_bytes(source: &TraceSource) -> usize { + match source { + TraceSource::Generated(generator) if !generator.device_state_resident() => { + generator.device_state_bytes() + } + _ => 0, + } +} + fn lde_of(pcs: &CudaPcs, domain: &Domain, source: &TraceSource) -> CudaLde { let blowup = pcs.fri.log_blowup; let shift = Val::GENERATOR / domain.shift(); @@ -336,14 +354,18 @@ fn construct_bounded( .saturating_add(plan.scratch_bytes()) .saturating_add(plan.constant_bytes()) .saturating_add(writer_workspace(&source)) + .saturating_add(state_restore_bytes(&source)) .saturating_add(reserve); // Generator caches go before any LDE spills: they are rebuilt from - // host seeds on demand, a spilled LDE is uploaded again. - for slot in resident.iter() { - if device_memory_info(device).0 >= needed { - break; + // host seeds on demand, a spilled LDE is uploaded again. A generated + // source would rebuild a released cache at once, so it releases none. + if matches!(source, TraceSource::Host(_)) { + for slot in resident.iter() { + if device_memory_info(device).0 >= needed { + break; + } + slot.as_ref().unwrap().release_generator_device(); } - slot.as_ref().unwrap().release_generator_device(); } for index in 0..resident.len() { if device_memory_info(device).0 >= needed { diff --git a/src/types.rs b/src/types.rs index fe109ac..db71e5c 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1053,9 +1053,13 @@ impl ProofConfig for GoldilocksBlake3Config { data.resident_with_host_trace(matrix).is_some() }) }; + // A graph lookup over a trace no longer on the device regenerates + // it, which can re-upload generator state that admission released. let target_for = |graph_path: bool| { let temporary_bytes = if graph_path { - graph_temporary_bytes.unwrap() + graph_temporary_bytes + .unwrap() + .saturating_add(input.stage_1.0.regeneration_bytes(input.stage_1.1)) } else { direct_temporary_bytes }; diff --git a/src/witness.rs b/src/witness.rs index 2ddc54e..ed864f7 100644 --- a/src/witness.rs +++ b/src/witness.rs @@ -26,6 +26,22 @@ pub trait TraceGenerator: Send + Sync { 0 } + /// Device bytes of the state [`Self::release_device`] frees, such as + /// uploaded seeds; the next tile allocates it again. Generated sources of + /// one batch are taken to share this state, so admission reserves the + /// largest of them once rather than their sum. + #[cfg(feature = "cuda")] + fn device_state_bytes(&self) -> usize { + 0 + } + + /// Whether the state [`Self::device_state_bytes`] counts is on the + /// device now, so that writing a tile allocates none of it. + #[cfg(feature = "cuda")] + fn device_state_resident(&self) -> bool { + true + } + /// Free whatever the source keeps on `device_id` to serve tiles faster, /// such as seeds left resident between a commitment and the lookup pass /// that regenerates rows from them. Tiles must still be served afterwards. From 03483016b6c0bf1361c54dd4d9dde093c105ef80 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:08:02 +0000 Subject: [PATCH 09/28] Build stage-one LDEs in a sliding window instead of fixed waves Prepared and host stage-one commitments split their matrices into waves of the admitted concurrency and joined each wave before starting the next. A wave mixes multi-gigabyte host uploads with tiny or device-built matrices, so it ended on one long upload or transform while the GPU sat idle, and every host LDE uploads its whole trace before its first kernel. Start each LDE as soon as any earlier one finishes, keeping the same bound on concurrent LDEs (and so on transform workspace), the same results in matrix order, and the serial path for small batches. On Init leaf 0 with pipelined population, stage-one GPU idle drops from ~1.0 s to ~0.6 s per proof; commitments are unchanged. --- src/cuda/mod.rs | 46 +++++++++++++++++++++++++++++++++++++++++++++ src/cuda/pcs.rs | 41 ++++++++++++++++++---------------------- src/cuda/witness.rs | 19 +++++++------------ 3 files changed, 71 insertions(+), 35 deletions(-) diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 815727e..ba1921f 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2272,6 +2272,33 @@ fn raw_u64(value: Goldilocks) -> u64 { /// it also bounds how many trace writers run at once. pub const MAX_CONCURRENT_LDES: usize = 16; +/// Maps `items` in order with at most `concurrency` calls in flight, each on +/// a Rayon worker. A call starts as soon as any earlier one finishes rather +/// than with a fixed wave, so one long transform, or one long host upload, +/// no longer holds back the calls behind it while the device idles. +pub(crate) fn bounded_parallel_map( + items: &[T], + concurrency: usize, + transform: impl Fn(&T) -> R + Sync, +) -> Vec { + use rayon::prelude::*; + let next = std::sync::atomic::AtomicUsize::new(0); + let mut results: Vec<(usize, R)> = (0..concurrency.clamp(1, items.len().max(1))) + .into_par_iter() + .flat_map_iter(|_| { + let mut done = Vec::new(); + loop { + let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some(item) = items.get(index) else { break }; + done.push((index, transform(item))); + } + done + }) + .collect(); + results.sort_unstable_by_key(|&(index, _)| index); + results.into_iter().map(|(_, result)| result).collect() +} + pub(crate) fn device_memory_info(device_id: i32) -> (usize, usize) { let mut free_bytes = 0; let mut total_bytes = 0; @@ -3515,6 +3542,25 @@ mod tests { mod quotient; mod witness; + #[test] + fn bounded_parallel_map_keeps_order_and_bounds_calls_in_flight() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let items: Vec = (0..200).collect(); + for concurrency in [1, 3, 16, 400] { + let (running, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mapped = bounded_parallel_map(&items, concurrency, |&item| { + let now = running.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(now, Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_micros(200)); + running.fetch_sub(1, Ordering::SeqCst); + item * 2 + }); + assert_eq!(mapped, items.iter().map(|i| i * 2).collect::>()); + assert!(peak.load(Ordering::SeqCst) <= concurrency); + } + assert!(bounded_parallel_map(&[] as &[usize], 4, |&i| i).is_empty()); + } + #[test] fn device_coset_selectors_match_cpu() { use p3_commit::PolynomialSpace; diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index b04688c..196fea5 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -1070,7 +1070,6 @@ where // Each Rayon worker uses its own per-thread CUDA stream. A bounded // admission window keeps pageable upload staging within the driver's // reliable concurrency range while retaining substantial overlap. - let mut ldes = Vec::with_capacity(evaluations.len()); let wave_size = if release_traces_during_construction { 1 } else { @@ -1080,31 +1079,27 @@ where .saturating_sub(minimum_free); (workspace_budget / max_transform_workspace.max(1)).clamp(1, super::MAX_CONCURRENT_LDES) }; - for wave in evaluations.chunks(wave_size) { - let transform = - |(domain, evals): &(TwoAdicMultiplicativeCoset, RowMajorMatrix)| { - assert_eq!(domain.size(), evals.height()); - let shift = Val::GENERATOR / domain.shift(); - dft.coset_lde_batch_resident(evals, log_blowup, shift) - }; - // Ix's inner proof contains hundreds of tiny matrices. Entering - // CUDA concurrently for that low-volume batch costs more than it - // saves and can exhaust driver-side pageable-copy workers. - let wave_ldes: Vec<_> = if source_cells < 10_000_000 { - wave.iter().map(transform).collect() - } else { - wave.par_iter().map(transform).collect() - }; - if release_traces_during_construction { - for lde in &wave_ldes { - // SAFETY: this wave has completed synchronously. The host - // matrices remain owned below and are retained for every + let transform = + |(domain, evals): &(TwoAdicMultiplicativeCoset, RowMajorMatrix)| { + assert_eq!(domain.size(), evals.height()); + let shift = Val::GENERATOR / domain.shift(); + let lde = dft.coset_lde_batch_resident(evals, log_blowup, shift); + if release_traces_during_construction { + // SAFETY: the LDE has completed synchronously. The host + // matrix remains owned below and is retained for every // later consumer of the original trace. unsafe { lde.release_trace() }; } - } - ldes.extend(wave_ldes); - } + lde + }; + // Ix's inner proof contains hundreds of tiny matrices. Entering + // CUDA concurrently for that low-volume batch costs more than it + // saves and can exhaust driver-side pageable-copy workers. + let ldes: Vec<_> = if source_cells < 10_000_000 { + evaluations.iter().map(transform).collect() + } else { + super::bounded_parallel_map(&evaluations, wave_size, transform) + }; // Preserve enough device headroom for lookup, quotient, and FRI // allocations. Spill the largest retained traces first, deriving the // policy from this device rather than a 96-GiB development machine. diff --git a/src/cuda/witness.rs b/src/cuda/witness.rs index 99e1176..7728552 100644 --- a/src/cuda/witness.rs +++ b/src/cuda/witness.rs @@ -5,7 +5,6 @@ use std::sync::{OnceLock, atomic::AtomicBool}; use p3_commit::Pcs; use p3_field::Field; use p3_matrix::{Dimensions, dense::RowMajorMatrix}; -use p3_maybe_rayon::prelude::*; use p3_symmetric::MerkleCap; use super::mmcs::CudaMmcsData; @@ -273,17 +272,13 @@ fn construct_resident( // Small batches of many tiny matrices lose more to concurrent CUDA entry // than they gain from overlap. let parallel = source_bytes >= 10_000_000 * size_of::(); - let mut ldes = Vec::with_capacity(evaluations.len()); - for wave in evaluations.chunks(wave_size) { - let transform = - |(domain, source): &(Domain, TraceSource)| lde_of(pcs, domain, source); - let wave_ldes: Vec<_> = if parallel { - wave.par_iter().map(transform).collect() - } else { - wave.iter().map(transform).collect() - }; - ldes.extend(wave_ldes); - } + let transform = + |(domain, source): &(Domain, TraceSource)| lde_of(pcs, domain, source); + let ldes = if parallel { + super::bounded_parallel_map(&evaluations, wave_size, transform) + } else { + evaluations.iter().map(transform).collect() + }; let (free_bytes, _) = device_memory_info(device); let minimum_free = super::minimum_free_bytes(total_bytes); let proactive_spill = source_bytes >= total_bytes / 12; From bcf3fc8e902b1f7176254f6e87a1101ed785248f Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:56:50 +0000 Subject: [PATCH 10/28] Stop the LDE window on a panic and keep it serial without parallel bounded_parallel_map called rayon directly, so a CUDA build without the parallel feature ran stage-one LDEs concurrently where the fixed waves it replaced (p3_maybe_rayon) ran them serially; it now runs serially there. After one call panicked, the other workers kept taking and transforming every remaining matrix before the panic propagated; a shared stop flag, set while unwinding, now ends them at their next item. --- src/cuda/mod.rs | 71 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index ba1921f..fd4296a 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2275,28 +2275,49 @@ pub const MAX_CONCURRENT_LDES: usize = 16; /// Maps `items` in order with at most `concurrency` calls in flight, each on /// a Rayon worker. A call starts as soon as any earlier one finishes rather /// than with a fixed wave, so one long transform, or one long host upload, -/// no longer holds back the calls behind it while the device idles. +/// no longer holds back the calls behind it while the device idles. A +/// panicking call stops the others from taking further items before the +/// panic propagates. Without the `parallel` feature the calls run serially. pub(crate) fn bounded_parallel_map( items: &[T], concurrency: usize, transform: impl Fn(&T) -> R + Sync, ) -> Vec { - use rayon::prelude::*; - let next = std::sync::atomic::AtomicUsize::new(0); - let mut results: Vec<(usize, R)> = (0..concurrency.clamp(1, items.len().max(1))) - .into_par_iter() - .flat_map_iter(|_| { - let mut done = Vec::new(); - loop { - let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let Some(item) = items.get(index) else { break }; - done.push((index, transform(item))); + #[cfg(feature = "parallel")] + { + use rayon::prelude::*; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + struct StopOnPanic<'a>(&'a AtomicBool); + impl Drop for StopOnPanic<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + self.0.store(true, Ordering::Relaxed); + } } - done - }) - .collect(); - results.sort_unstable_by_key(|&(index, _)| index); - results.into_iter().map(|(_, result)| result).collect() + } + let next = AtomicUsize::new(0); + let stop = AtomicBool::new(false); + let mut results: Vec<(usize, R)> = (0..concurrency.clamp(1, items.len().max(1))) + .into_par_iter() + .flat_map_iter(|_| { + let _guard = StopOnPanic(&stop); + let mut done = Vec::new(); + while !stop.load(Ordering::Relaxed) { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(item) = items.get(index) else { break }; + done.push((index, transform(item))); + } + done + }) + .collect(); + results.sort_unstable_by_key(|&(index, _)| index); + results.into_iter().map(|(_, result)| result).collect() + } + #[cfg(not(feature = "parallel"))] + { + let _ = concurrency; + items.iter().map(transform).collect() + } } pub(crate) fn device_memory_info(device_id: i32) -> (usize, usize) { @@ -3561,6 +3582,24 @@ mod tests { assert!(bounded_parallel_map(&[] as &[usize], 4, |&i| i).is_empty()); } + #[cfg(feature = "parallel")] + #[test] + fn bounded_parallel_map_stops_taking_items_after_a_panic() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let items: Vec = (0..10_000).collect(); + let calls = AtomicUsize::new(0); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + bounded_parallel_map(&items, 4, |&item| { + calls.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_micros(50)); + assert_ne!(item, 10, "injected"); + item + }) + })); + assert!(result.is_err()); + assert!(calls.load(Ordering::SeqCst) < 100); + } + #[test] fn device_coset_selectors_match_cpu() { use p3_commit::PolynomialSpace; From 648fb13a9fcf3ede4393cab5aa21b3ab6af975f9 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:35:47 +0000 Subject: [PATCH 11/28] Drop the standing quarter-device CUDA memory reserve Every phase already admits its allocations against the device's current free memory and spills source traces to the host when they do not fit, so keeping a quarter of the device free on top of that only shrank what each phase could hold. MULTI_STARK_CUDA_MIN_FREE_BYTES now defaults to zero. LDE offload keeps a fixed 128 MiB for lazy sppark device parameters, as witness construction already does. --- cuda/README.md | 2 +- src/cuda/mod.rs | 10 ++++++---- src/cuda/offload.rs | 7 ++++--- src/cuda/pcs.rs | 2 +- src/cuda/witness.rs | 4 ++-- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/cuda/README.md b/cuda/README.md index d3aed31..98ef665 100644 --- a/cuda/README.md +++ b/cuda/README.md @@ -61,7 +61,7 @@ Useful environment variables: - `MULTI_STARK_CUDA_DEVICE`: device used by the prover and microbenchmarks (default: `0`; `CUDA_VISIBLE_DEVICES` remapping is also honored) - `MULTI_STARK_CUDA_MIN_FREE_BYTES`: device headroom retained by spilling - source traces (default: one quarter of total device memory) + source traces (default: none) Only native cubins are emitted. This avoids a newer toolkit's PTX being chosen by a slightly older driver instead of a compatible native cubin. diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index fd4296a..771c00f 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2338,13 +2338,15 @@ pub fn release_device_memory() { check_cuda(status, "CUDA memory release"); } -/// Device bytes the prover keeps free for its later stages: a quarter of the -/// device unless `MULTI_STARK_CUDA_MIN_FREE_BYTES` says otherwise. -pub(crate) fn minimum_free_bytes(total_bytes: usize) -> usize { +/// Device bytes admission keeps free beyond what a phase needs: +/// `MULTI_STARK_CUDA_MIN_FREE_BYTES`, by default none. Every phase admits +/// its own allocations against the device's current free memory and spills +/// to the host when they do not fit, so no standing reserve is needed. +pub(crate) fn minimum_free_bytes() -> usize { std::env::var("MULTI_STARK_CUDA_MIN_FREE_BYTES") .ok() .and_then(|value| value.parse().ok()) - .unwrap_or(total_bytes / 4) + .unwrap_or(0) } pub(crate) fn memory_diagnostics_enabled() -> bool { diff --git a/src/cuda/offload.rs b/src/cuda/offload.rs index 080d081..95e4b2e 100644 --- a/src/cuda/offload.rs +++ b/src/cuda/offload.rs @@ -148,15 +148,16 @@ fn try_worker( let input_bytes = matrix.values.len().checked_mul(size_of::())?; let blowup = 1usize.checked_shl(u32::try_from(added_bits).ok()?)?; let output_bytes = input_bytes.checked_mul(blowup)?; - let (free_bytes, total_bytes) = device_memory_info(worker.device_id); + let (free_bytes, _) = device_memory_info(worker.device_id); // Constants are counted even if their cached allocation is already included - // in the snapshot. The reserve also covers lazy sppark device parameters. + // in the snapshot. The fixed 128 MiB covers lazy sppark device parameters, + // as in witness construction. let required_bytes = admitted_bytes( input_bytes, output_bytes, plan.scratch_bytes(), plan.constant_bytes(), - minimum_free_bytes(total_bytes), + minimum_free_bytes().saturating_add(128 << 20), )?; if required_bytes > free_bytes { return None; diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index 196fea5..f8ee762 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -651,7 +651,7 @@ where let max_transform_workspace = transform_workspaces.iter().copied().max().unwrap_or(0); let (initial_free, total_bytes) = crate::cuda::device_memory_info(self.mmcs.cuda_device_id()); - let minimum_free = crate::cuda::minimum_free_bytes(total_bytes); + let minimum_free = crate::cuda::minimum_free_bytes(); let source_bytes = source_cells.saturating_mul(size_of::()); let lde_bytes = source_bytes .checked_shl(u32::try_from(log_blowup).expect("LDE blowup exceeds u32")) diff --git a/src/cuda/witness.rs b/src/cuda/witness.rs index 7728552..f388b1b 100644 --- a/src/cuda/witness.rs +++ b/src/cuda/witness.rs @@ -82,7 +82,7 @@ pub(crate) fn commit_with( } let max_height = dimensions.iter().map(|d| d.height).max().unwrap(); let (initial_free, total) = device_memory_info(device); - let minimum_free = super::minimum_free_bytes(total); + let minimum_free = super::minimum_free_bytes(); let reserve = minimum_free.saturating_add(128 << 20); let source_bytes = evaluations .iter() @@ -280,7 +280,7 @@ fn construct_resident( evaluations.iter().map(transform).collect() }; let (free_bytes, _) = device_memory_info(device); - let minimum_free = super::minimum_free_bytes(total_bytes); + let minimum_free = super::minimum_free_bytes(); let proactive_spill = source_bytes >= total_bytes / 12; let large_matrix = total_bytes / 120; let mut projected_free = free_bytes; From 0797a0f3e1e87431ea16e46cd208d292e48e8755 Mon Sep 17 00:00:00 2001 From: Gabriel Barreto Date: Fri, 20 Nov 2026 11:50:59 -0300 Subject: [PATCH 12/28] fix: Reject public values in lookup expressions at compile time `compile_expr` accepted `Expr::Public` in lookup multiplicities and arguments, but the lookup witness is built before the public values (the lookup challenges and accumulators) exist: the witness sweep runs with no publics, so such a circuit compiled and then panicked with an out-of-bounds index in `SystemWitness::from_stage_1`. Compile lookups, base constraints and extension-constraint coordinates under an explicit context, and return the new `CompileError::PublicInLookup` for a public value in a lookup. Base and extension constraints may still read public values. The verifier and the proof format are unchanged. Claude-Session: https://claude.ai/code/session_011m6Jd9eHKVucLbm7ZHHMmd --- src/graph.rs | 47 +++++++++++++++++++++++++++++++++-------------- src/system.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 14 deletions(-) diff --git a/src/graph.rs b/src/graph.rs index 5184e70..0659c02 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -96,6 +96,10 @@ pub enum CompileError { /// Stage-2 columns are extension coordinates; base constraints and /// lookup expressions must not touch them. Stage2InBaseContext, + /// Public values are the coordinates of the lookup challenges and + /// accumulators, which do not exist yet when the lookup witness is + /// built; lookup expressions must not touch them. + PublicInLookup, /// A fully base-field extension constraint: state it as a base /// constraint instead. PurelyBaseExtConstraint { @@ -111,6 +115,18 @@ pub enum CompileError { }, } +/// Where an expression occurs, which decides the leaves it may read. +#[derive(Copy, Clone, PartialEq, Eq)] +enum Context { + /// A lookup multiplicity or argument: evaluated on the trace rows when + /// the lookup witness is built, before any challenge is sampled. + Lookup, + /// A base constraint. + Base, + /// A coordinate of an extension constraint. + Extension, +} + /// Compiles a circuit spec. Interning order: lookups first (they form the /// prefix), then base constraints, then expanded extension constraints. /// @@ -127,11 +143,11 @@ pub(crate) fn compile( let mut lookups = Vec::with_capacity(spec.lookups.len()); for lookup in &spec.lookups { - let multiplicity = interner.compile_expr(&lookup.multiplicity, spec, false)?; + let multiplicity = interner.compile_expr(&lookup.multiplicity, spec, Context::Lookup)?; let args = lookup .args .iter() - .map(|arg| interner.compile_expr(arg, spec, false)) + .map(|arg| interner.compile_expr(arg, spec, Context::Lookup)) .collect::, _>>()?; lookups.push(Lookup { multiplicity, args }); } @@ -139,7 +155,7 @@ pub(crate) fn compile( let mut zeros = Vec::new(); for (i, constraint) in spec.constraints.iter().enumerate() { - let root = interner.compile_expr(constraint, spec, false)?; + let root = interner.compile_expr(constraint, spec, Context::Base)?; record_zero(&interner, &mut zeros, root, i, None)?; } for (i, constraint) in spec.ext_constraints.iter().enumerate() { @@ -329,7 +345,7 @@ impl Interner { &mut self, expr: &Expr, spec: &CircuitSpec, - allow_stage2: bool, + context: Context, ) -> Result { Ok(match expr { Expr::Const(c) => self.constant(*c), @@ -338,7 +354,7 @@ impl Interner { Source::Preprocessed => spec.preprocessed_width, Source::Main => spec.main_width, Source::Stage2 => { - if !allow_stage2 { + if context != Context::Extension { return Err(CompileError::Stage2InBaseContext); } spec.stage2_width @@ -354,6 +370,9 @@ impl Interner { self.intern(Node::Var(*col)) } Expr::Public(index) => { + if context == Context::Lookup { + return Err(CompileError::PublicInLookup); + } if *index as usize >= spec.num_publics { return Err(CompileError::PublicOutOfRange { index: *index, @@ -366,22 +385,22 @@ impl Interner { Expr::IsLastRow => self.intern(Node::IsLastRow), Expr::IsTransition => self.intern(Node::IsTransition), Expr::Add(a, b) => { - let a = self.compile_expr(a, spec, allow_stage2)?; - let b = self.compile_expr(b, spec, allow_stage2)?; + let a = self.compile_expr(a, spec, context)?; + let b = self.compile_expr(b, spec, context)?; self.add(a, b) } Expr::Sub(a, b) => { - let a = self.compile_expr(a, spec, allow_stage2)?; - let b = self.compile_expr(b, spec, allow_stage2)?; + let a = self.compile_expr(a, spec, context)?; + let b = self.compile_expr(b, spec, context)?; self.sub(a, b) } Expr::Mul(a, b) => { - let a = self.compile_expr(a, spec, allow_stage2)?; - let b = self.compile_expr(b, spec, allow_stage2)?; + let a = self.compile_expr(a, spec, context)?; + let b = self.compile_expr(b, spec, context)?; self.mul(a, b) } Expr::Neg(a) => { - let a = self.compile_expr(a, spec, allow_stage2)?; + let a = self.compile_expr(a, spec, context)?; self.neg(a) } }) @@ -408,13 +427,13 @@ impl Interner { } coords .iter() - .map(|c| self.compile_expr(c, spec, true)) + .map(|c| self.compile_expr(c, spec, Context::Extension)) .collect::, _>>()? } ExtExpr::Base(base) => { let zero = self.constant(F::ZERO); let mut coords = vec![zero; d]; - coords[0] = self.compile_expr(base, spec, true)?; + coords[0] = self.compile_expr(base, spec, Context::Extension)?; coords } ExtExpr::Add(a, b) => { diff --git a/src/system.rs b/src/system.rs index c33c9bb..74277a3 100644 --- a/src/system.rs +++ b/src/system.rs @@ -33,6 +33,11 @@ pub struct CircuitInputs { pub preprocessed: Option>, pub constraints: Vec>, pub ext_constraints: Vec>, + /// Lookup multiplicities and arguments are evaluated on the trace rows + /// when the lookup witness is built, so they may read only the + /// preprocessed and main traces: stage-2 columns and public values (the + /// lookup challenges and accumulators, which do not exist yet) are + /// rejected at compile time. pub lookups: Vec>>, /// How many logUp messages share one chained-accumulator step (and one /// committed accumulator column): stage-2 width becomes `⌈L/k⌉·D` at @@ -456,6 +461,7 @@ mod tests { mod lookup_values; use super::*; + use crate::graph::CompileError; use crate::p3_adapter::LookupAir; use crate::types::{CommitmentParameters, FriParameters, GoldilocksBlake3Config, Val}; use p3_air::{Air, AirBuilder, BaseAir, WindowAccess}; @@ -549,6 +555,37 @@ mod tests { system.verify_multiple_claims(no_claims, &proof).unwrap(); } + /// Public values are the coordinates of the lookup challenges and + /// accumulators, which do not exist when the lookup witness is built. A + /// lookup reading one used to compile and then panic (index out of + /// bounds) in `SystemWitness::from_stage_1`; it must be rejected at + /// compile time. Base constraints may still read public values. + #[test] + fn public_in_lookup_rejected() { + let params = extension_params::(); + let public = || Expr::::public(0); + for lookup in [ + Lookup::push(public(), vec![Expr::main(0)]), + Lookup::push(Expr::main(0), vec![Expr::main(0) * public()]), + ] { + let inputs = CircuitInputs { + main_width: 1, + lookups: vec![lookup], + ..Default::default() + }; + assert_eq!( + inputs.compile_graph(¶ms).unwrap_err(), + CompileError::PublicInLookup + ); + } + let inputs = CircuitInputs { + main_width: 1, + constraints: vec![Expr::main(0) * public()], + ..Default::default() + }; + assert!(inputs.compile_graph(¶ms).is_ok()); + } + #[test] #[should_panic(expected = "preprocessed trace height")] fn mismatched_preprocessed_height_panics() { From a4518bd9a80bbb0950eb17e601a7b00f3620c541 Mon Sep 17 00:00:00 2001 From: Gabriel Barreto Date: Fri, 20 Nov 2026 20:35:57 -0300 Subject: [PATCH 13/28] fix: Reject row selectors in lookup expressions at compile time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `compile_expr` accepted `Expr::IsFirstRow`, `Expr::IsLastRow` and `Expr::IsTransition` in lookup multiplicities and arguments. The lookup witness evaluates a selector as a 0/1 indicator of the row, while the constraints (prover quotient and verifier) see Plonky3's unnormalised selectors: on a trace of n rows with generator g, n on the first row, n·g on the last row and g^r − g⁻¹ on row r. Such a circuit compiled and then produced a proof that the crate's own verifier rejects. Return the new `CompileError::SelectorInLookup`, which names the selector, for a selector at any depth of a lookup expression. Base and extension constraints may still use selectors. The verifier and the proof format are unchanged. Document the rule on `CircuitInputs::lookups` together with what to use instead (a 0/1 column of the preprocessed trace, or a main column pinned to the first-row indicator), and test that both replacements prove and verify. The lookup-witness tests now read their row indicators from trace columns, with the expected payloads unchanged. The 0/1 selector values in `compute_lookup_values_range` and in the CUDA lookup kernel stay in place; no compiled circuit reaches them. Claude-Session: https://claude.ai/code/session_011m6Jd9eHKVucLbm7ZHHMmd --- docs/pcs-abstraction.md | 8 ++ src/graph.rs | 44 +++++++- src/p3_adapter/air.rs | 5 + src/system.rs | 166 +++++++++++++++++++++++++++++- src/system/tests/lookup_values.rs | 69 ++++++++++--- 5 files changed, 270 insertions(+), 22 deletions(-) diff --git a/docs/pcs-abstraction.md b/docs/pcs-abstraction.md index 96eb73c..64a7636 100644 --- a/docs/pcs-abstraction.md +++ b/docs/pcs-abstraction.md @@ -14,6 +14,14 @@ The domain and quotient limits must match the backend's actual capabilities. - `ProofConfig` has optional fused lookup and quotient commitment hooks; they must preserve the portable path's constraints, ordering and commitments. - `compute_lookup_values_range` evaluates chunks with full-trace row semantics. +- Lookup multiplicities and arguments read only the preprocessed and main + traces. The compiler rejects stage-2 columns, public values and the built-in + row selectors (`IsFirstRow`, `IsLastRow`, `IsTransition`) in them. On the + trace rows a selector is not 0/1 and its value depends on the trace height, + so a lookup reads a 0/1 column instead: one of the preprocessed trace, or a + main-trace column `s` pinned by `IsFirstRow * (s − 1) = 0` and + `IsTransition * s_next = 0` (see `CircuitInputs::lookups`). A fused lookup + hook therefore never evaluates a selector for a compiled circuit. - `observe_claims` and `sample_lookup_challenges` share transcript conventions with external verifier implementations; neither verifies a proof. diff --git a/src/graph.rs b/src/graph.rs index 0659c02..bf2af3a 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -100,6 +100,14 @@ pub enum CompileError { /// accumulators, which do not exist yet when the lookup witness is /// built; lookup expressions must not touch them. PublicInLookup, + /// The built-in row selectors are not 0/1 indicators: the constraints + /// see Plonky3's unnormalised selectors, whose values on the trace rows + /// depend on the trace height (`IsFirstRow` is `n` on the first of `n` + /// rows). Lookup expressions must not touch them; read a 0/1 column + /// instead (see [`crate::system::CircuitInputs::lookups`]). + SelectorInLookup { + selector: RowSelector, + }, /// A fully base-field extension constraint: state it as a base /// constraint instead. PurelyBaseExtConstraint { @@ -115,11 +123,21 @@ pub enum CompileError { }, } +/// A built-in row selector, named by the frontend leaf that reads it +/// ([`Expr::IsFirstRow`], [`Expr::IsLastRow`], [`Expr::IsTransition`]). +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum RowSelector { + IsFirstRow, + IsLastRow, + IsTransition, +} + /// Where an expression occurs, which decides the leaves it may read. #[derive(Copy, Clone, PartialEq, Eq)] enum Context { /// A lookup multiplicity or argument: evaluated on the trace rows when - /// the lookup witness is built, before any challenge is sampled. + /// the lookup witness is built, before any challenge is sampled. It + /// reads the preprocessed and main traces only. Lookup, /// A base constraint. Base, @@ -341,6 +359,24 @@ impl Interner { self.intern(Node::Neg(a)) } + /// Interns a row selector. Constraints may gate on it; a lookup may not + /// read it, because the lookup witness would need its value as a 0/1 + /// indicator while the constraints see the unnormalised selector. + fn selector( + &mut self, + selector: RowSelector, + context: Context, + ) -> Result { + if context == Context::Lookup { + return Err(CompileError::SelectorInLookup { selector }); + } + Ok(self.intern(match selector { + RowSelector::IsFirstRow => Node::IsFirstRow, + RowSelector::IsLastRow => Node::IsLastRow, + RowSelector::IsTransition => Node::IsTransition, + })) + } + fn compile_expr( &mut self, expr: &Expr, @@ -381,9 +417,9 @@ impl Interner { } self.intern(Node::Public(*index)) } - Expr::IsFirstRow => self.intern(Node::IsFirstRow), - Expr::IsLastRow => self.intern(Node::IsLastRow), - Expr::IsTransition => self.intern(Node::IsTransition), + Expr::IsFirstRow => self.selector(RowSelector::IsFirstRow, context)?, + Expr::IsLastRow => self.selector(RowSelector::IsLastRow, context)?, + Expr::IsTransition => self.selector(RowSelector::IsTransition, context)?, Expr::Add(a, b) => { let a = self.compile_expr(a, spec, context)?; let b = self.compile_expr(b, spec, context)?; diff --git a/src/p3_adapter/air.rs b/src/p3_adapter/air.rs index 8dc7c94..4765cfd 100644 --- a/src/p3_adapter/air.rs +++ b/src/p3_adapter/air.rs @@ -306,6 +306,11 @@ impl AirBuilder for P3AirBuilder { /// This is the unit `System::new` accepts for AIR-authored circuits: it /// converts into [`CircuitInputs`] by evaluating the AIR (see /// [`circuit_inputs_from_air`]) and attaching the lookups. +/// +/// The lookups read trace columns only: the builder's row selectors +/// (`is_first_row`, `is_last_row`, `is_transition`) are for the AIR's +/// constraints and are rejected in a lookup when the circuit is compiled +/// (see [`CircuitInputs::lookups`]). pub struct LookupAir { pub inner_air: A, pub lookups: Vec>>, diff --git a/src/system.rs b/src/system.rs index 74277a3..6a2aa45 100644 --- a/src/system.rs +++ b/src/system.rs @@ -38,6 +38,22 @@ pub struct CircuitInputs { /// preprocessed and main traces: stage-2 columns and public values (the /// lookup challenges and accumulators, which do not exist yet) are /// rejected at compile time. + /// + /// The built-in row selectors (`IsFirstRow`, `IsLastRow`, + /// `IsTransition`) are rejected too, anywhere in a multiplicity or an + /// argument ([`CompileError::SelectorInLookup`]). They are not 0/1 + /// indicators: on a trace of `n` rows with generator `g`, the + /// constraints see `IsFirstRow = n` on the first row, `IsLastRow = n·g` + /// on the last row and `IsTransition = g^r − g⁻¹` on row `r`, so their + /// values depend on the trace height. That is harmless when a selector + /// gates an ordinary constraint, where only the rows on which it is zero + /// matter, but a lookup would take those values as multiplicities or + /// message entries. Read a 0/1 column instead: a column of the + /// preprocessed trace, or a main-trace column `s` pinned to the + /// first-row indicator by the constraints `IsFirstRow * (s − 1) = 0` and + /// `IsTransition * s_next = 0`. + /// + /// [`CompileError::SelectorInLookup`]: crate::graph::CompileError::SelectorInLookup pub lookups: Vec>>, /// How many logUp messages share one chained-accumulator step (and one /// committed accumulator column): stage-2 width becomes `⌈L/k⌉·D` at @@ -383,8 +399,14 @@ pub(crate) fn compute_lookup_values_with_fixed( compute_lookup_values_range(&circuit.graph, trace, preprocessed, 0..trace.height()) } -/// Evaluate lookup messages for a row range. Selectors and next-row reads use -/// the full trace height, including wraparound at its last row. +/// Evaluate lookup messages for a row range. Next-row reads use the full +/// trace height, including wraparound at its last row. +/// +/// Compiled lookups never contain row selectors +/// ([`crate::graph::CompileError::SelectorInLookup`]). In a graph that was +/// not produced by the compiler, a selector in the lookup prefix evaluates +/// here as a 0/1 indicator of the full trace, which is NOT the value the +/// constraints give it. pub fn compute_lookup_values_range( graph: &ConstraintGraph, trace: &RowMajorMatrix, @@ -412,8 +434,8 @@ pub fn compute_lookup_values_range( .for_each_init( || (Vec::new(), Vec::new()), |(buf, args), (offset, mut writer)| { - // Selectors and the next-row window refer to the full trace, - // even when only a range of lookup rows is materialized. + // The next-row window refers to the full trace, even when + // only a range of lookup rows is materialized. let r = rows.start + offset; let r_next = (r + 1) % height; let main_cur = trace.row_slice(r).unwrap(); @@ -429,6 +451,8 @@ pub fn compute_lookup_values_range( main: [&main_cur, &main_next], stage2: [&empty, &empty], publics: &empty, + // Never read for a compiled circuit: the compiler + // rejects selectors in lookup expressions. is_first_row: if r == 0 { F::ONE } else { F::ZERO }, is_last_row: if r == height - 1 { F::ONE } else { F::ZERO }, is_transition: if r == height - 1 { F::ZERO } else { F::ONE }, @@ -586,6 +610,140 @@ mod tests { assert!(inputs.compile_graph(¶ms).is_ok()); } + /// The built-in row selectors are not 0/1 indicators on the trace rows: + /// the constraints see Plonky3's unnormalised selectors, while the lookup + /// witness evaluates a selector as an indicator. A lookup reading one + /// used to compile and then yield a proof that the verifier rejects; it + /// must be rejected at compile time, at any depth of a multiplicity or + /// of an argument. Base and extension constraints may still use them. + #[test] + fn selector_in_lookup_rejected() { + use crate::expr::RowOffset; + use crate::graph::{Node, RowSelector}; + + let params = extension_params::(); + let d = u32::try_from(params.degree).unwrap(); + let x = || Expr::::main(0); + let y = || Expr::::main(1); + let two = || Expr::constant(Val::from_u32(2)); + for (expr, selector, node) in [ + (Expr::IsFirstRow, RowSelector::IsFirstRow, Node::IsFirstRow), + (Expr::IsLastRow, RowSelector::IsLastRow, Node::IsLastRow), + ( + Expr::IsTransition, + RowSelector::IsTransition, + Node::IsTransition, + ), + ] { + let sel = || expr.clone(); + for lookup in [ + // The multiplicity: bare, negated, inside an expression. + Lookup::push(sel(), vec![x()]), + Lookup::pull(sel(), vec![x()]), + Lookup::push(x() * (y() - two() * sel()), vec![x()]), + // An argument: bare, inside an expression. + Lookup::push(x(), vec![y(), sel()]), + Lookup::push(x(), vec![y() + x() * -(sel() - two())]), + ] { + let inputs = CircuitInputs { + main_width: 2, + lookups: vec![lookup], + ..Default::default() + }; + assert_eq!( + inputs.compile_graph(¶ms).unwrap_err(), + CompileError::SelectorInLookup { selector } + ); + } + // Next to a selector-free lookup, a base constraint and an + // extension constraint keep the selector. + let stage2 = |offset| ExtExpr::stage2(0, d, offset); + let inputs = CircuitInputs { + main_width: 2, + constraints: vec![sel() * (x() - y())], + ext_constraints: vec![ + sel() * (stage2(RowOffset::Next) - stage2(RowOffset::Current)), + ], + lookups: vec![Lookup::push(x(), vec![y()])], + ..Default::default() + }; + let graph = inputs.compile_graph(¶ms).unwrap(); + assert!(graph.nodes[graph.lookup_prefix_len..].contains(&node)); + assert!(!graph.nodes[..graph.lookup_prefix_len].contains(&node)); + } + } + + /// What `CircuitInputs::lookups` documents in place of a selector: a 0/1 + /// column of the preprocessed trace, or a main column `s` pinned to the + /// first-row indicator by `IsFirstRow * (s − 1) = 0` and + /// `IsTransition * s_next = 0`. Each gates a pull that happens once, on + /// the first row, whatever the trace height; a main column marking + /// another row violates the pinning constraints. + #[test] + fn indicator_columns_replace_selectors_in_lookups() { + let config = || { + GoldilocksBlake3Config::new( + CommitmentParameters { + log_blowup: 1, + cap_height: 0, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 64, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + ) + }; + let f = Val::from_usize; + let one = Expr::constant(f(1)); + for n in [4usize, 32] { + // Main columns `[x, s]`, with `s` the pinned indicator. + let pinned = CircuitInputs { + main_width: 2, + constraints: vec![ + Expr::IsFirstRow * (Expr::main(1) - one.clone()), + Expr::IsTransition * Expr::main_next(1), + ], + lookups: vec![Lookup::pull(Expr::main(1), vec![Expr::main(0)])], + ..Default::default() + }; + // Main column `[x]`, with the indicator in the preprocessed trace. + let fixed = CircuitInputs { + main_width: 1, + preprocessed: Some(RowMajorMatrix::new_col( + (0..n).map(|r| f(usize::from(r == 0))).collect(), + )), + lookups: vec![Lookup::pull(Expr::preprocessed(0), vec![Expr::main(0)])], + ..Default::default() + }; + let (system, key) = System::new(config(), [pinned, fixed]); + let pinned_trace = |marked: usize| { + RowMajorMatrix::new( + (0..n) + .flat_map(|r| [f(100 + r), f(usize::from(r == marked))]) + .collect(), + 2, + ) + }; + let fixed_trace = RowMajorMatrix::new_col((0..n).map(|r| f(200 + r)).collect()); + let run = |marked: usize| { + let witness = SystemWitness::from_stage_1( + vec![pinned_trace(marked), fixed_trace.clone()], + &system, + ); + // One claim per pull: the row the indicator marks. + let claims = [[f(100 + marked)], [f(200)]]; + let claims: Vec<&[Val]> = claims.iter().map(|c| c.as_slice()).collect(); + let proof = system.prove_multiple_claims(&key, &claims, witness); + system.verify_multiple_claims(&claims, &proof) + }; + run(0).unwrap(); + assert!(run(1).is_err(), "height {n}"); + } + } + #[test] #[should_panic(expected = "preprocessed trace height")] fn mismatched_preprocessed_height_panics() { diff --git a/src/system/tests/lookup_values.rs b/src/system/tests/lookup_values.rs index 82201bd..02de935 100644 --- a/src/system/tests/lookup_values.rs +++ b/src/system/tests/lookup_values.rs @@ -33,6 +33,7 @@ fn serial_values( main: [&main_cur, &main_next], stage2: [&[], &[]], publics: &[], + // Never read: compiled lookups contain no selectors. is_first_row: F::from_bool(r == 0), is_last_row: F::from_bool(r == height - 1), is_transition: F::from_bool(r != height - 1), @@ -48,25 +49,65 @@ fn serial_values( builder.finish() } -fn fixture(height: usize, fixed: bool) -> (Circuit, RowMajorMatrix) { - let trace = RowMajorMatrix::new( +/// Main columns `[x, y]`, distinct on every row. +fn xy_trace(height: usize) -> RowMajorMatrix { + RowMajorMatrix::new( (0..height * 2).map(|i| F::from_usize(i * 13 + 7)).collect(), 2, - ); - let preprocessed = fixed.then(|| { - RowMajorMatrix::new( + ) +} + +/// Appends the 0/1 row-indicator columns `[first, last, transition]`. +fn with_row_indicators(matrix: &RowMajorMatrix) -> RowMajorMatrix { + let (height, width) = (matrix.height(), matrix.width()); + RowMajorMatrix::new( + matrix + .values + .chunks(width) + .enumerate() + .flat_map(|(r, row)| { + row.iter().copied().chain([ + F::from_bool(r == 0), + F::from_bool(r + 1 == height), + F::from_bool(r + 1 != height), + ]) + }) + .collect(), + width + 3, + ) +} + +/// Lookup expressions may not use the built-in row selectors +/// (`CompileError::SelectorInLookup`), so the lookups below read the row +/// position from 0/1 indicator columns instead: of the preprocessed trace +/// when `fixed`, of the main trace otherwise. +fn fixture(height: usize, fixed: bool) -> (Circuit, RowMajorMatrix) { + let (trace, preprocessed) = if fixed { + let preprocessed = RowMajorMatrix::new( (0..height * 2) .map(|i| F::from_usize(i * 17 + 11)) .collect(), 2, - ) - }); + ); + (xy_trace(height), Some(with_row_indicators(&preprocessed))) + } else { + (with_row_indicators(&xy_trace(height)), None) + }; + let indicator = |i: u32| { + if fixed { + Expr::preprocessed(2 + i) + } else { + Expr::main(2 + i) + } + }; + let (is_first, is_last, is_transition) = (indicator(0), indicator(1), indicator(2)); + let main_width = trace.width(); let spec = CircuitSpec { - main_width: 2, - preprocessed_width: usize::from(fixed) * 2, + main_width, + preprocessed_width: preprocessed.as_ref().map_or(0, |p| p.width()), lookups: vec![ Lookup::push( - Expr::IsFirstRow + Expr::main(0), + is_first.clone() + Expr::main(0), vec![ Expr::main_next(1), if fixed { @@ -82,8 +123,8 @@ fn fixture(height: usize, fixed: bool) -> (Circuit, RowMajorMatrix< }, ], ), - Lookup::pull(Expr::IsTransition, vec![Expr::IsLastRow, Expr::main(1)]), - Lookup::push(Expr::IsLastRow - Expr::IsFirstRow, vec![]), + Lookup::pull(is_transition, vec![is_last.clone(), Expr::main(1)]), + Lookup::push(is_last - is_first, vec![]), ], ..Default::default() }; @@ -98,7 +139,7 @@ fn fixture(height: usize, fixed: bool) -> (Circuit, RowMajorMatrix< .unwrap(); let circuit = Circuit { graph, - main_width: 2, + main_width, preprocessed, preprocessed_width: spec.preprocessed_width, preprocessed_height: if fixed { height } else { 0 }, @@ -299,7 +340,7 @@ fn lookup_witness_preserves_proof_bytes() { ..Default::default() }); let (system, key) = System::new(config(), inputs); - let (_, trace) = fixture::(64, false); + let trace = xy_trace::(64); let traces = vec![trace.clone(), trace]; let serial_lookups = traces .iter() From fc4336bd71e4e3a64e636044983003e508b99a62 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Fri, 20 Nov 2026 22:01:48 -0500 Subject: [PATCH 14/28] A5: streaming stage-2 lookup evaluation and CPU disk-backed LDE spilling --- src/config.rs | 59 + src/graph.rs | 10 + src/lookup.rs | 406 +++++- src/p3_adapter/mod.rs | 2 + src/p3_adapter/pcs.rs | 14 +- src/p3_adapter/spill.rs | 1870 +++++++++++++++++++++++++ src/prover.rs | 243 +++- src/system.rs | 97 +- src/test_circuits/baby_bear_config.rs | 36 + src/types.rs | 322 ++++- src/witness.rs | 56 + tests/streaming_spill.rs | 823 +++++++++++ 12 files changed, 3805 insertions(+), 133 deletions(-) create mode 100644 src/p3_adapter/spill.rs create mode 100644 tests/streaming_spill.rs diff --git a/src/config.rs b/src/config.rs index d135f42..8e18245 100644 --- a/src/config.rs +++ b/src/config.rs @@ -154,6 +154,65 @@ pub trait ProofConfig { ) } + /// Commit preprocessed evaluation matrices from a streaming iterator. + /// + /// Each item is `(domain, matrix, retain_1x_for_lookups)`, where + /// `retain_1x_for_lookups` is `true` when the system does not retain + /// `circuit.preprocessed` in RAM and the circuit's lookup expressions read + /// preprocessed columns. + /// + /// Backends that spill LDEs to disk can process one matrix at a time so + /// all preprocessed matrices never coexist in RAM simultaneously. Returns + /// `None` if the iterator yields no matrices. + fn commit_preprocessed( + &self, + evaluations: &mut dyn Iterator< + Item = ( + Domain, + p3_matrix::dense::RowMajorMatrix>, + bool, + ), + >, + ) -> Option<(Com, PcsData)> + where + Self: Sized, + { + let evals: Vec<_> = evaluations + .map(|(domain, matrix, _retain_1x)| (domain, matrix)) + .collect(); + if evals.is_empty() { + None + } else { + Some(self.pcs().commit(evals)) + } + } + + /// Commit deterministic main-trace sources from a streaming iterator. + /// + /// Each item is `(domain, trace_source, retain_1x_for_lookups)`, where + /// `retain_1x_for_lookups` is `true` when the circuit's lookup witness is + /// unmaterialized (`shape_only`) and the circuit has at least one lookup. + /// + /// Returns `None` if the iterator yields no active traces. + fn commit_main_streaming( + &self, + evaluations: &mut dyn Iterator< + Item = (Domain, crate::witness::TraceSource>, bool), + >, + ) -> Option<(Com, PcsData)> + where + Self: Sized, + { + let evals: Vec<_> = evaluations + .map(|(domain, trace, _retain_1x)| (domain, trace)) + .collect(); + if evals.is_empty() { + None + } else { + Some(self.commit_main(evals)) + } + } + /// Normalize any backend-dependent field representatives before proof /// serialization. Most fields have canonical in-memory representations; /// configurations whose field permits lazy reduction can override this. diff --git a/src/graph.rs b/src/graph.rs index 5184e70..5253bae 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -77,6 +77,16 @@ pub struct ConstraintGraph { pub max_constraint_degree: u32, } +impl ConstraintGraph { + /// Returns `true` if any lookup expression (multiplicity or argument) + /// reads at least one preprocessed column. + pub fn lookup_prefix_uses_preprocessed(&self) -> bool { + self.nodes[..self.lookup_prefix_len] + .iter() + .any(|node| matches!(node, Node::Var(col) if col.source == Source::Preprocessed)) + } +} + #[derive(Clone, PartialEq, Eq, Debug)] pub enum CompileError { CoordsLength { diff --git a/src/lookup.rs b/src/lookup.rs index 3e5b7c9..ff9ee25 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -45,8 +45,9 @@ //! [`MAX_LOOKUP_GROUP`] so the evaluator's scratch space stays on the //! stack. +use crate::eval::VarValues; use crate::traits::{Algebra, ExtensionOf, Field, batch_inverse}; -use p3_matrix::dense::RowMajorMatrix; +use p3_matrix::{Matrix, dense::RowMajorMatrix}; use p3_maybe_rayon::prelude::*; use crate::expr::{Expr, ExtExpr, RowOffset}; @@ -684,6 +685,27 @@ impl LookupValues { } } + /// Whether the concrete `multiplicities` and `args` payload is materialized. + /// + /// Returns `false` for [`Self::shape_only`] witnesses whose lookup messages + /// are evaluated on demand from the committed traces. + #[inline] + pub const fn is_materialized(&self) -> bool { + self.materialized + } + + /// Number of trace rows represented by this lookup witness. + #[inline] + pub const fn height(&self) -> usize { + self.height + } + + /// Number of lookups per row. + #[inline] + pub const fn num_lookups(&self) -> usize { + self.num_lookups + } + /// Panics unless the witness payload is present. fn require_payload(&self) { assert!( @@ -703,6 +725,79 @@ impl LookupValues { &self.args[start + self.arg_offsets[lookup]..start + self.arg_offsets[lookup + 1]] } + /// Computes a single circuit's stage-2 lookup trace and total accumulator + /// contribution in bounded row chunks, keeping temporary message and + /// inverse buffers small regardless of trace height. + pub fn stage_2_trace>( + &self, + group_size: usize, + lookup_challenge: EF, + fingerprint_challenge: &EF, + ) -> (RowMajorMatrix, EF) { + self.require_payload(); + let group_size = group_size.max(1); + let num_slots = lookup_groups(self.num_lookups, group_size); + let zero = >::ZERO; + if self.num_lookups == 0 || self.height == 0 { + return ( + RowMajorMatrix::new(vec![zero; self.height * num_slots], num_slots), + zero, + ); + } + + let chunk_rows = stage_2_chunk_rows(self.height, self.num_lookups); + let mut vec = vec![zero; self.height * num_slots]; + let mut running = zero; + + for row_start in (0..self.height).step_by(chunk_rows) { + let n_rows = (self.height - row_start).min(chunk_rows); + let num_chunk_messages = n_rows * self.num_lookups; + let messages: Vec = (0..num_chunk_messages) + .into_par_iter() + .map(|idx| { + let local_row = idx / self.num_lookups; + let lookup = idx % self.num_lookups; + let args = self.args_at(row_start + local_row, lookup); + lookup_challenge + fingerprint(fingerprint_challenge, args.iter().copied()) + }) + .collect(); + let inverses = batch_inverse(&messages); + drop(messages); + + let chunk_out = &mut vec[row_start * num_slots..(row_start + n_rows) * num_slots]; + let chunk_mults = &self.multiplicities + [row_start * self.num_lookups..(row_start + n_rows) * self.num_lookups]; + chunk_out + .par_chunks_exact_mut(num_slots) + .zip(chunk_mults.par_chunks_exact(self.num_lookups)) + .zip(inverses.par_chunks_exact(self.num_lookups)) + .for_each(|((out_row, row_mults), row_invs)| { + for (slot_out, (group_mults, group_invs)) in out_row.iter_mut().zip( + row_mults + .chunks(group_size) + .zip(row_invs.chunks(group_size)), + ) { + let mut delta = zero; + for (&multiplicity, &message_inverse) in group_mults.iter().zip(group_invs) + { + delta += EF::from(multiplicity) * message_inverse; + } + *slot_out = delta; + } + }); + drop(inverses); + + // Exclusive prefix scan over this chunk's group deltas. + for cell in chunk_out.iter_mut() { + let delta = *cell; + *cell = running; + running += delta; + } + } + + (RowMajorMatrix::new(vec, num_slots), running) + } + /// Computes the stage 2 traces and the intermediate accumulators for each /// circuit given a lookup challenge, a fingerprint challenge and the current /// accumulator value (computed from the initial claims). @@ -716,84 +811,13 @@ impl LookupValues { for circuit in circuits { circuit.require_payload(); } - // Compute the message for each lookup, in flat circuit-major order. - let _g = tracing::info_span!("stark/lookup_messages").entered(); - let num_messages = circuits - .iter() - .map(|circuit| circuit.height * circuit.num_lookups) - .sum(); - let mut messages: Vec = Vec::with_capacity(num_messages); - for circuit in circuits { - messages.extend( - (0..circuit.height * circuit.num_lookups) - .into_par_iter() - .map(|idx| { - let (row, lookup) = (idx / circuit.num_lookups, idx % circuit.num_lookups); - let args = circuit.args_at(row, lookup); - lookup_challenge + fingerprint(fingerprint_challenge, args.iter().cloned()) - }) - .collect::>(), - ); - } - drop(_g); - - // Compute the inverses of all messages in batch. - let messages_inverses = - tracing::info_span!("stark/batch_inverse").in_scope(|| batch_inverse(&messages)); - // Only the inverses are consumed below. - drop(messages); - - // Compute and collect intermediate accumulators and traces. let _g = tracing::info_span!("stark/lookup_traces").entered(); let mut intermediate_accumulators = Vec::with_capacity(circuits.len()); let mut traces = Vec::with_capacity(circuits.len()); - let mut offset = 0; for (circuit, &group_size) in circuits.iter().zip(group_sizes) { - let group_size = group_size.max(1); - // Get the slice containing the messages inverses for the current circuit. - let num_circuit_messages = circuit.height * circuit.num_lookups; - let circuit_messages_inverses = - &messages_inverses[offset..offset + num_circuit_messages]; - offset += num_circuit_messages; - - let num_slots = lookup_groups(circuit.num_lookups, group_size); - let vec = if circuit.num_lookups == 0 { - // Pass-through accumulator column; the committed values are - // gauge-free (only differences are constrained), zero by - // convention. - vec![>::ZERO; circuit.height] - } else { - // One partial accumulator per lookup GROUP: `acc_g` is the - // running sum ENTERING group g's step; the last group's - // result carries into the next row's slot 0. Single pass, - // one multiply-add per (row, lookup). The column is - // gauge-free, so it starts at zero regardless of the global - // accumulator; the circuit's total contribution is added to - // the global chain at the end. - let mut vec = Vec::with_capacity(circuit.height * num_slots); - let mut local = >::ZERO; - for (row_multiplicities, row_messages_inverses) in circuit - .multiplicities - .chunks_exact(circuit.num_lookups) - .zip(circuit_messages_inverses.chunks_exact(circuit.num_lookups)) - { - for (group_mults, group_invs) in row_multiplicities - .chunks(group_size) - .zip(row_messages_inverses.chunks(group_size)) - { - vec.push(local); - for (&multiplicity, &message_inverse) in group_mults.iter().zip(group_invs) - { - local += EF::from(multiplicity) * message_inverse; - } - } - } - accumulator += local; - vec - }; - let width = num_slots; - debug_assert_eq!(vec.len() % width, 0); - let trace = RowMajorMatrix::new(vec, width); + let (trace, delta) = + circuit.stage_2_trace(group_size, lookup_challenge, fingerprint_challenge); + accumulator += delta; intermediate_accumulators.push(accumulator); traces.push(trace); } @@ -802,6 +826,238 @@ impl LookupValues { } } +/// Target number of lookup messages per chunk (~8 MiB at 16 bytes/EF). +const STAGE_2_TARGET_CHUNK_MESSAGES: usize = 1 << 19; + +fn stage_2_chunk_rows(height: usize, num_lookups: usize) -> usize { + (STAGE_2_TARGET_CHUNK_MESSAGES / num_lookups.max(1)) + .clamp(1, 1 << 12) + .min(height.max(1)) +} + +/// Row-window view over a chunk of rows of a 1× trace, providing each row and +/// its cyclic successor without copying in-memory traces. +pub(crate) trait TraceRowChunk: Sync { + fn row_pair(&self, local_row: usize) -> (&[F], &[F]); +} + +/// Zero-copy row-window view backed by a resident [`RowMajorMatrix`]. +pub(crate) struct InMemoryChunk<'a, F> { + matrix: &'a RowMajorMatrix, + start: usize, + height: usize, + width: usize, +} + +impl<'a, F: Field> InMemoryChunk<'a, F> { + pub(crate) fn new(matrix: &'a RowMajorMatrix, start: usize) -> Self { + Self { + matrix, + start, + height: matrix.height(), + width: matrix.width(), + } + } +} + +impl TraceRowChunk for InMemoryChunk<'_, F> { + #[inline] + fn row_pair(&self, local_row: usize) -> (&[F], &[F]) { + if self.width == 0 { + return (&[], &[]); + } + let r = self.start + local_row; + let r_next = (r + 1) % self.height; + ( + &self.matrix.values[r * self.width..(r + 1) * self.width], + &self.matrix.values[r_next * self.width..(r_next + 1) * self.width], + ) + } +} + +/// Owned row-window chunk holding `n_rows + 1` rows (the chunk plus one +/// wrap-around halo row), used when streaming chunks from disk. +#[cfg(not(feature = "cuda"))] +pub(crate) struct OwnedWindowChunk { + rows: RowMajorMatrix, +} + +#[cfg(not(feature = "cuda"))] +impl OwnedWindowChunk { + pub(crate) fn new(rows: RowMajorMatrix) -> Self { + Self { rows } + } +} + +#[cfg(not(feature = "cuda"))] +impl TraceRowChunk for OwnedWindowChunk { + #[inline] + fn row_pair(&self, local_row: usize) -> (&[F], &[F]) { + let w = self.rows.width(); + if w == 0 { + return (&[], &[]); + } + ( + &self.rows.values[local_row * w..(local_row + 1) * w], + &self.rows.values[(local_row + 1) * w..(local_row + 2) * w], + ) + } +} + +/// Builds a single circuit's stage-2 lookup trace directly from chunked 1× +/// main (and optional preprocessed) row windows, without materializing +/// [`LookupValues`]. +/// +/// Returns `(stage_2_trace, circuit_total_delta)`. +pub(crate) fn stage_2_trace_chunked( + circuit: &crate::system::Circuit, + height: usize, + lookup_challenge: EF, + fingerprint_challenge: &EF, + mut load_main_chunk: impl FnMut(usize, usize) -> MainChunk, + mut load_prep_chunk: Option PrepChunk>, +) -> (RowMajorMatrix, EF) +where + F: Field, + EF: ExtensionOf, + MainChunk: TraceRowChunk, + PrepChunk: TraceRowChunk, +{ + let num_lookups = circuit.graph.lookups.len(); + let group_size = circuit.lookup_group_size.max(1); + let num_slots = lookup_groups(num_lookups, group_size); + let zero = >::ZERO; + if num_lookups == 0 || height == 0 { + return ( + RowMajorMatrix::new(vec![zero; height * num_slots], num_slots), + zero, + ); + } + + let uses_preprocessed = circuit.graph.lookup_prefix_uses_preprocessed(); + assert!( + !uses_preprocessed || load_prep_chunk.is_some(), + "circuit lookup expressions read preprocessed columns, but no preprocessed trace was supplied" + ); + + let chunk_rows = stage_2_chunk_rows(height, num_lookups); + let mut vec = vec![zero; height * num_slots]; + let mut running = zero; + let empty: [F; 0] = []; + + for row_start in (0..height).step_by(chunk_rows) { + let n_rows = (height - row_start).min(chunk_rows); + let main_chunk = load_main_chunk(row_start, n_rows); + let prep_chunk = if uses_preprocessed { + load_prep_chunk + .as_mut() + .map(|loader| loader(row_start, n_rows)) + } else { + None + }; + + let mut multiplicities = F::zero_vec(n_rows * num_lookups); + let mut messages = vec![zero; n_rows * num_lookups]; + + multiplicities + .par_chunks_exact_mut(num_lookups) + .zip(messages.par_chunks_exact_mut(num_lookups)) + .enumerate() + .for_each_init(Vec::new, |buf, (local_row, (row_mults, row_msgs))| { + let r = row_start + local_row; + let (main_cur, main_next) = main_chunk.row_pair(local_row); + let (pp_cur, pp_next) = match &prep_chunk { + Some(prep) => prep.row_pair(local_row), + None => (&empty[..], &empty[..]), + }; + let view = VarValues { + preprocessed: [pp_cur, pp_next], + main: [main_cur, main_next], + stage2: [&empty, &empty], + publics: &empty, + is_first_row: if r == 0 { F::ONE } else { F::ZERO }, + is_last_row: if r == height - 1 { F::ONE } else { F::ZERO }, + is_transition: if r == height - 1 { F::ZERO } else { F::ONE }, + }; + circuit.graph.sweep_lookup_prefix(&view, buf); + for (slot, lookup) in circuit.graph.lookups.iter().enumerate() { + row_mults[slot] = buf[lookup.multiplicity.index()]; + let fp = fingerprint( + fingerprint_challenge, + lookup.args.iter().map(|arg| buf[arg.index()]), + ); + row_msgs[slot] = lookup_challenge + fp; + } + }); + drop(main_chunk); + drop(prep_chunk); + + let inverses = batch_inverse(&messages); + drop(messages); + + let chunk_out = &mut vec[row_start * num_slots..(row_start + n_rows) * num_slots]; + chunk_out + .par_chunks_exact_mut(num_slots) + .zip(multiplicities.par_chunks_exact(num_lookups)) + .zip(inverses.par_chunks_exact(num_lookups)) + .for_each(|((out_row, row_mults), row_invs)| { + for (slot_out, (group_mults, group_invs)) in out_row.iter_mut().zip( + row_mults + .chunks(group_size) + .zip(row_invs.chunks(group_size)), + ) { + let mut delta = zero; + for (&multiplicity, &message_inverse) in group_mults.iter().zip(group_invs) { + delta += EF::from(multiplicity) * message_inverse; + } + *slot_out = delta; + } + }); + drop(multiplicities); + drop(inverses); + + for cell in chunk_out.iter_mut() { + let delta = *cell; + *cell = running; + running += delta; + } + } + + (RowMajorMatrix::new(vec, num_slots), running) +} + +/// Builds a single circuit's stage-2 lookup trace directly from its 1× main +/// trace (and optional 1× preprocessed trace) in bounded row chunks, without +/// materializing [`LookupValues`]. +/// +/// Returns `(stage_2_trace, circuit_total_delta)`. +pub fn stage_2_trace_from_trace>( + circuit: &crate::system::Circuit, + main_trace: &RowMajorMatrix, + preprocessed: Option<&RowMajorMatrix>, + lookup_challenge: EF, + fingerprint_challenge: &EF, +) -> (RowMajorMatrix, EF) { + let height = main_trace.height(); + if let Some(pp) = preprocessed + && height > 0 + { + assert_eq!( + pp.height(), + height, + "preprocessed trace height must equal main trace height" + ); + } + stage_2_trace_chunked( + circuit, + height, + lookup_challenge, + fingerprint_challenge, + |start, _len| InMemoryChunk::new(main_trace, start), + preprocessed.map(|pp| move |start, _len| InMemoryChunk::new(pp, start)), + ) +} + #[cfg(feature = "cuda")] impl LookupValues { pub(crate) fn cuda_stage_2_deltas>( diff --git a/src/p3_adapter/mod.rs b/src/p3_adapter/mod.rs index fa54760..2d5f917 100644 --- a/src/p3_adapter/mod.rs +++ b/src/p3_adapter/mod.rs @@ -6,5 +6,7 @@ pub mod challenger; pub mod domain; pub mod field; pub mod pcs; +#[cfg(not(feature = "cuda"))] +pub mod spill; pub use air::*; diff --git a/src/p3_adapter/pcs.rs b/src/p3_adapter/pcs.rs index 375f5a8..cd42f9e 100644 --- a/src/p3_adapter/pcs.rs +++ b/src/p3_adapter/pcs.rs @@ -69,6 +69,16 @@ impl pub fn fri_parameters(&self) -> FriParameters { self.fri_parameters } + + #[cfg(not(feature = "cuda"))] + pub(crate) fn inner_mut(&mut self) -> &mut Inner { + &mut self.inner + } + + #[cfg(not(feature = "cuda"))] + pub(crate) fn quotient_dft(&self) -> &Dft { + &self.quotient_dft + } } impl Pcs @@ -195,7 +205,7 @@ where /// natural trace domain guarantees it). What survives is a single parallel /// gather off the DFT storage with ONE constant weight per slice: /// `wₖ = N⁻¹ · GENERATOR^{−k·n}`. -fn shifted_quotient_slices( +pub(crate) fn shifted_quotient_slices( dft: &impl TwoAdicSubgroupDft, quotient_evals: RowMajorMatrix, domain_shift: F, @@ -276,7 +286,7 @@ fn shifted_quotient_slices( /// `coset_dft_batch`, no reassembly copies, and `Radix2DitParallel`'s /// native output order is already the bit-reversed storage order, so the /// final unwrap is copy-free. -fn lde_from_shifted_coefficients( +pub(crate) fn lde_from_shifted_coefficients( dft: &impl TwoAdicSubgroupDft, mut coefficients: RowMajorMatrix, log_blowup: usize, diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs new file mode 100644 index 0000000..48e6e72 --- /dev/null +++ b/src/p3_adapter/spill.rs @@ -0,0 +1,1870 @@ +//! Disk-backed spilling and streaming commitment/opening support for the CPU +//! two-adic FRI PCS. +//! +//! When disk spilling is enabled on [`crate::types::GoldilocksBlake3Config`], +//! committed 4× LDE leaf matrices are streamed to unlinked temporary files +//! instead of remaining resident in RAM across commitment, quotient evaluation, +//! and FRI opening. Compact Merkle `digest_layers` stay in memory; leaf hashing, +//! barycentric interpolation, reduced-opening compression, and Merkle query +//! openings stream bounded row blocks directly from disk. +//! +//! All operations produce commitments and proofs byte-identical to Plonky3's +//! in-memory [`MerkleTreeMmcs`] and [`p3_fri::TwoAdicFriPcs`]. + +use std::borrow::Cow; +use std::cmp::Reverse; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufWriter, Write}; +use std::marker::PhantomData; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use p3_blake3::Blake3; +use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; +use p3_commit::{BatchOpening, BatchOpeningRef, Mmcs, OpenedValues, Pcs, PeriodicLdeTable}; +use p3_dft::TwoAdicSubgroupDft; +use p3_field::coset::TwoAdicMultiplicativeCoset; +use p3_field::{ + ExtensionField, Field, PackedFieldExtension, PrimeCharacteristicRing, PrimeField64, + TwoAdicField, batch_multiplicative_inverse, dot_product, scale_slice_in_place_single_core, +}; +use p3_fri::verifier::{self, FriError}; +use p3_fri::{ + BatchMultiOpening, CommitmentWithOpeningPoints, FriParameters, FriProof, + ProverDataWithOpeningPoints, TwoAdicFriFolding, TwoAdicFriFoldingForMmcs, + build_periodic_lde_table_two_adic, prover, +}; +use p3_goldilocks::Goldilocks; +use p3_matrix::bitrev::{BitReversedMatrixView, BitReversibleMatrix}; +use p3_matrix::dense::{RowMajorMatrix, RowMajorMatrixCow}; +use p3_matrix::interpolation::{Interpolate, compute_adjusted_weights}; +use p3_matrix::{Dimensions, Matrix}; +use p3_maybe_rayon::prelude::*; +use p3_merkle_tree::{MerkleTreeMmcs, PrunedMerklePaths}; +use p3_symmetric::{CryptographicHasher, MerkleCap, PseudoCompressionFunction, SerializingHasher}; +use p3_util::linear_map::LinearMap; +use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_slice_index_bits}; +use tracing::debug_span; + +use crate::types::{Blake3CompressionFunction, ExtVal, Val}; + +/// CPU reference MMCS used for in-memory commitments and verification. +pub type CpuMmcs = + MerkleTreeMmcs, Blake3CompressionFunction, 2, 32>; +type CpuData = >::ProverData; +type SpillCommitResult = ( + >::Commitment, + SpillableMmcsData>, +); + +/// Target memory budget per streamed row block during Merkle hashing and FRI +/// opening passes (64 MiB). +const STREAM_BLOCK_BYTES: usize = 64 << 20; + +/// Write buffer size for sequential spill-file packing (1 MiB of field elements). +const SPILL_WRITE_CHUNK_ELEMS: usize = 1 << 17; + +static SPILL_FILE_SEQ: AtomicU64 = AtomicU64::new(0); +static ACTIVE_SPILL_FILES: AtomicUsize = AtomicUsize::new(0); +static TOTAL_SPILLED_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Number of currently open temporary spill files across this process. +pub fn active_spill_files() -> usize { + ACTIVE_SPILL_FILES.load(Ordering::Relaxed) +} + +/// Cumulative bytes written to spill files across this process. +pub fn total_spilled_bytes() -> u64 { + TOTAL_SPILLED_BYTES.load(Ordering::Relaxed) +} + +/// An owned temporary spill file. On Unix the directory entry is unlinked +/// immediately after creation so disk space is automatically reclaimed by the +/// kernel on drop, panic, or abnormal termination. +pub(crate) struct SpillFile { + file: File, + #[cfg(not(unix))] + remove_on_drop: Option, + #[cfg(not(unix))] + io_lock: Mutex<()>, +} + +impl SpillFile { + pub(crate) fn create(dir: &Path) -> Arc { + fs::create_dir_all(dir) + .unwrap_or_else(|err| panic!("failed to create spill directory {dir:?}: {err}")); + let pid = std::process::id(); + loop { + let seq = SPILL_FILE_SEQ.fetch_add(1, Ordering::Relaxed); + let path = dir.join(format!("multi-stark-spill-{pid}-{seq}.bin")); + match OpenOptions::new() + .create_new(true) + .read(true) + .write(true) + .open(&path) + { + Ok(file) => { + #[cfg(unix)] + { + // Unlink immediately so no stale files remain even on + // panic or SIGKILL. + let _ = fs::remove_file(&path); + } + ACTIVE_SPILL_FILES.fetch_add(1, Ordering::Relaxed); + return Arc::new(Self { + file, + #[cfg(not(unix))] + remove_on_drop: Some(path), + #[cfg(not(unix))] + io_lock: Mutex::new(()), + }); + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(err) => { + panic!("failed to create spill file {path:?}: {err}"); + } + } + } + } + + fn read_exact_at(&self, offset: u64, buf: &mut [u8]) { + if buf.is_empty() { + return; + } + #[cfg(unix)] + { + use std::os::unix::fs::FileExt; + self.file.read_exact_at(buf, offset).unwrap_or_else(|err| { + panic!("failed to read spill file at offset {offset}: {err}") + }); + } + #[cfg(not(unix))] + { + use std::io::{Read, Seek, SeekFrom}; + let _guard = self.io_lock.lock().expect("spill file lock poisoned"); + let mut handle = &self.file; + handle + .seek(SeekFrom::Start(offset)) + .unwrap_or_else(|err| panic!("failed to seek spill file to {offset}: {err}")); + handle.read_exact(buf).unwrap_or_else(|err| { + panic!("failed to read spill file at offset {offset}: {err}") + }); + } + } +} + +impl Drop for SpillFile { + fn drop(&mut self) { + ACTIVE_SPILL_FILES.fetch_sub(1, Ordering::Relaxed); + #[cfg(not(unix))] + if let Some(path) = self.remove_on_drop.take() { + let _ = fs::remove_file(path); + } + } +} + +/// Packs multiple spilled matrices sequentially into a single [`SpillFile`] so +/// even hundreds of circuits consume only one file descriptor per commitment +/// round. +pub(crate) struct SpillPackWriter { + spill: Arc, + writer: BufWriter, + next_offset: u64, + scratch: Vec, +} + +impl SpillPackWriter { + pub(crate) fn create(dir: &Path) -> Self { + let spill = SpillFile::create(dir); + let write_handle = spill + .file + .try_clone() + .expect("failed to clone spill file handle for writing"); + Self { + spill, + writer: BufWriter::with_capacity(1 << 20, write_handle), + next_offset: 0, + scratch: Vec::with_capacity(SPILL_WRITE_CHUNK_ELEMS * size_of::()), + } + } + + /// Appends `mat` in canonical little-endian `u64` row-major order and + /// returns a lightweight handle to its byte range in the pack file. + pub(crate) fn append_matrix(&mut self, mat: &RowMajorMatrix) -> SpilledMatrix { + let height = mat.height(); + let width = mat.width(); + let offset = self.next_offset; + let total_elems = mat.values.len(); + for chunk in mat.values.chunks(SPILL_WRITE_CHUNK_ELEMS) { + self.scratch.clear(); + for elem in chunk { + self.scratch + .extend_from_slice(&elem.as_canonical_u64().to_le_bytes()); + } + self.writer + .write_all(&self.scratch) + .expect("failed to write matrix chunk to spill file"); + } + let bytes = u64::try_from(total_elems) + .expect("matrix element count exceeds u64") + .checked_mul(u64::try_from(size_of::()).unwrap()) + .expect("matrix byte length overflow"); + self.next_offset = self + .next_offset + .checked_add(bytes) + .expect("spill pack offset overflow"); + TOTAL_SPILLED_BYTES.fetch_add(bytes, Ordering::Relaxed); + SpilledMatrix { + file: Arc::clone(&self.spill), + offset, + height, + width, + } + } + + /// Flushes all buffered writes to the OS file before positional reads. + pub(crate) fn flush(&mut self) { + self.writer.flush().expect("failed to flush spill file"); + } +} + +/// Handle to a row-major [`Goldilocks`] matrix stored in canonical little-endian +/// `u64` bytes inside a [`SpillFile`]. +#[derive(Clone)] +pub(crate) struct SpilledMatrix { + file: Arc, + offset: u64, + height: usize, + width: usize, +} + +impl SpilledMatrix { + #[inline] + pub(crate) const fn height(&self) -> usize { + self.height + } + + #[inline] + pub(crate) const fn width(&self) -> usize { + self.width + } + + #[inline] + pub(crate) const fn dimensions(&self) -> Dimensions { + Dimensions { + width: self.width, + height: self.height, + } + } + + #[inline] + const fn row_bytes(&self) -> usize { + self.width * size_of::() + } + + /// Reads `num_rows` contiguous rows starting at `start_row` as raw + /// canonical little-endian bytes (identical to `Goldilocks::into_byte_stream`). + pub(crate) fn read_raw_rows(&self, start_row: usize, num_rows: usize) -> Vec { + assert!( + start_row.saturating_add(num_rows) <= self.height, + "spilled read out of bounds: {start_row}..{} > {}", + start_row.saturating_add(num_rows), + self.height + ); + let row_bytes = self.row_bytes(); + let byte_len = num_rows + .checked_mul(row_bytes) + .expect("spilled read byte length overflow"); + let byte_offset = self + .offset + .checked_add( + u64::try_from(start_row) + .expect("start_row exceeds u64") + .checked_mul(u64::try_from(row_bytes).expect("row_bytes exceeds u64")) + .expect("spilled byte offset overflow"), + ) + .expect("spilled offset overflow"); + let mut buf = vec![0u8; byte_len]; + self.file.read_exact_at(byte_offset, &mut buf); + buf + } + + /// Reads `num_rows` contiguous rows starting at `start_row` into a + /// [`RowMajorMatrix`]. + pub(crate) fn read_rows(&self, start_row: usize, num_rows: usize) -> RowMajorMatrix { + if self.width == 0 { + return RowMajorMatrix::new(Vec::new(), 0); + } + let raw = self.read_raw_rows(start_row, num_rows); + RowMajorMatrix::new(bytes_to_goldilocks(&raw), self.width) + } + + /// Reads a single row (for FRI query openings). + pub(crate) fn read_row(&self, row: usize) -> Vec { + if self.width == 0 { + return Vec::new(); + } + let raw = self.read_raw_rows(row, 1); + bytes_to_goldilocks(&raw) + } + + /// Reads `num_rows` rows starting at `start_row` PLUS one cyclic halo row + /// `(start_row + num_rows) % self.height`, returning a `(num_rows + 1)`-row + /// matrix for chunked lookup evaluation. + pub(crate) fn read_window_with_wrap( + &self, + start_row: usize, + num_rows: usize, + ) -> RowMajorMatrix { + assert!(num_rows > 0 && start_row + num_rows <= self.height); + if self.width == 0 { + return RowMajorMatrix::new(Vec::new(), 0); + } + if start_row + num_rows < self.height { + self.read_rows(start_row, num_rows + 1) + } else { + let mut mat = self.read_rows(start_row, num_rows); + mat.values.extend_from_slice(&self.read_row(0)); + mat + } + } + + /// Reads the entire matrix back into RAM. + pub(crate) fn read_all(&self) -> RowMajorMatrix { + self.read_rows(0, self.height) + } +} + +#[inline] +fn bytes_to_goldilocks(raw: &[u8]) -> Vec { + let (chunks, remainder) = raw.as_chunks::<8>(); + debug_assert!(remainder.is_empty()); + chunks + .iter() + .map(|&chunk| Goldilocks::new(u64::from_le_bytes(chunk))) + .collect() +} + +/// Binary Merkle-tree padded layer length (matching `p3_merkle_tree::padded_len(raw_len, 2)`). +#[inline] +const fn padded_len_binary(raw_len: usize) -> usize { + if raw_len <= 1 { + raw_len + } else { + raw_len.div_ceil(2) * 2 + } +} + +/// Validates that every matrix height sits on the `ceil(max_height / 2^k)` +/// ladder anchored at the tallest matrix (matching `p3_merkle_tree`). +fn validate_reachable_heights(matrices: &[SpilledMatrix]) -> usize { + let max_height = matrices + .iter() + .map(SpilledMatrix::height) + .max() + .filter(|&h| h > 0) + .expect("all matrices have height 0"); + let log_max_height = log2_ceil_usize(max_height); + for m in matrices { + let h = m.height(); + let bits_reduced = log_max_height - log2_ceil_usize(h); + let expected_height = ((max_height - 1) >> bits_reduced) + 1; + assert_eq!( + h, expected_height, + "matrix height {h} incompatible with tallest height {max_height} (expected {expected_height})" + ); + } + max_height +} + +/// A binary Blake3 Merkle tree whose leaf matrices reside on disk in +/// [`SpilledMatrix`] handles, while only the compact internal `digest_layers` +/// remain in RAM. +pub(crate) struct SpilledMerkleTree { + matrices: Vec, + digest_layers: Vec>, + arity_schedule: Vec, + /// Optional spilled 1× original traces retained for zero-FFT on-demand + /// lookup evaluation; released once stage-2 completes for stage-1 data, + /// or retained for the lifetime of `ProverKey` for preprocessed data. + original_traces: Mutex>>, +} + +impl SpilledMerkleTree { + pub(crate) fn build( + matrices: Vec, + original_traces: Vec>, + compress: &Blake3CompressionFunction, + ) -> Self { + assert!(!matrices.is_empty(), "No matrices given?"); + let max_height = validate_reachable_heights(&matrices); + + // Stable sort tallest-first to match `MerkleTree::new` insertion order + // within each height group. + let mut order: Vec = (0..matrices.len()).collect(); + order.sort_by_key(|&idx| Reverse(matrices[idx].height())); + + let tallest_end = order + .iter() + .take_while(|&&idx| matrices[idx].height() == max_height) + .count(); + let tallest = &order[..tallest_end]; + let mut cursor = tallest_end; + + let first_layer = hash_leaf_group_streaming(&matrices, tallest, max_height); + let mut digest_layers = vec![first_layer]; + let mut arity_schedule = Vec::new(); + + loop { + let prev_layer = digest_layers.last().unwrap().as_slice(); + if prev_layer.len() <= 1 { + break; + } + let step = 2usize; + let raw_next = prev_layer.len() / step; + let next_layer_len = raw_next.next_power_of_two(); + + let inject_start = cursor; + while cursor < order.len() + && matrices[order[cursor]].height().next_power_of_two() == next_layer_len + { + cursor += 1; + } + let inject_group = &order[inject_start..cursor]; + + let next_digests = if inject_group.is_empty() { + compress_layer_binary(prev_layer, compress) + } else { + compress_and_inject_streaming(prev_layer, &matrices, inject_group, compress) + }; + arity_schedule.push(step); + digest_layers.push(next_digests); + } + + Self { + matrices, + digest_layers, + arity_schedule, + original_traces: Mutex::new(original_traces), + } + } + + pub(crate) fn cap(&self, cap_height: usize) -> MerkleCap { + let num_layers = self.digest_layers.len(); + let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); + let layer_idx = num_layers - 1 - effective_cap_height; + let layer = &self.digest_layers[layer_idx]; + let cap_len: usize = self.arity_schedule[layer_idx..].iter().product(); + let cap_len = cap_len.min(layer.len()); + MerkleCap::new(layer[..cap_len].to_vec()) + } + + pub(crate) fn max_height(&self) -> usize { + self.matrices + .iter() + .map(SpilledMatrix::height) + .max() + .expect("No committed matrices?") + } + + pub(crate) fn matrix_heights(&self) -> Vec { + self.matrices.iter().map(SpilledMatrix::height).collect() + } + + pub(crate) fn dimensions(&self) -> Vec { + self.matrices + .iter() + .map(SpilledMatrix::dimensions) + .collect() + } + + pub(crate) fn open_batch( + &self, + index: usize, + cap_height: usize, + ) -> (Vec>, Vec<[u8; 32]>) { + let max_height = self.max_height(); + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + let log_max_height = log2_ceil_usize(max_height); + + let openings: Vec> = self + .matrices + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.read_row(reduced_index) + }) + .collect(); + + let num_layers = self.digest_layers.len(); + let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); + let proof_levels = num_layers + .saturating_sub(1) + .saturating_sub(effective_cap_height); + + let mut proof = Vec::with_capacity(proof_levels); + let mut idx = index; + for layer_idx in 0..proof_levels { + let step = self.arity_schedule[layer_idx]; + let group_start = (idx / step) * step; + let pos_in_group = idx % step; + for k in 0..step { + if k != pos_in_group { + proof.push(self.digest_layers[layer_idx][group_start + k]); + } + } + idx /= step; + } + (openings, proof) + } + + pub(crate) fn open_multi_batch( + &self, + indices: &[usize], + cap_height: usize, + ) -> (Vec>>, PrunedMerklePaths) { + let max_height = self.max_height(); + let log_max_height = log2_ceil_usize(max_height); + let num_layers = self.digest_layers.len(); + let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); + let proof_levels = num_layers + .saturating_sub(1) + .saturating_sub(effective_cap_height); + + let opened_values: Vec>> = indices + .iter() + .map(|&index| { + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + self.matrices + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.read_row(reduced_index) + }) + .collect() + }) + .collect(); + + // Walk the pruned frontier bottom-up in the exact wire order defined by + // `p3_merkle_tree::pruning::walk_frontier`: + // - sorted unique leaf indices + // - level 0 .. proof_levels + // - ascending parent groups, emitting missing child positions ascending. + let mut nodes: Vec = indices.to_vec(); + nodes.sort_unstable(); + nodes.dedup(); + + let mut sibling_hashes = Vec::new(); + if !nodes.is_empty() { + let mut parents: Vec = Vec::with_capacity(nodes.len()); + for (level, &arity) in self.arity_schedule[..proof_levels].iter().enumerate() { + parents.clear(); + let mut i = 0; + while i < nodes.len() { + let group = nodes[i] / arity; + let group_start = group * arity; + let mut member = i; + for k in 0..arity { + if member < nodes.len() && nodes[member] == group_start + k { + member += 1; + } else { + sibling_hashes.push(self.digest_layers[level][group_start + k]); + } + } + parents.push(group); + i = member; + } + core::mem::swap(&mut nodes, &mut parents); + } + } + + (opened_values, PrunedMerklePaths { sibling_hashes }) + } + + pub(crate) fn spilled_original_trace(&self, idx: usize) -> Option { + let guard = self + .original_traces + .lock() + .expect("original_traces lock poisoned"); + guard.get(idx).and_then(Clone::clone) + } + + pub(crate) fn release_original_traces(&self) { + let mut guard = self + .original_traces + .lock() + .expect("original_traces lock poisoned"); + guard.clear(); + } +} + +fn block_rows_for_group(matrices: &[SpilledMatrix], group: &[usize], height: usize) -> usize { + let total_row_bytes: usize = group + .iter() + .map(|&idx| matrices[idx].row_bytes()) + .sum::() + .max(size_of::()); + (STREAM_BLOCK_BYTES / total_row_bytes) + .clamp(1, 1 << 14) + .min(height.max(1)) +} + +fn hash_leaf_group_streaming( + matrices: &[SpilledMatrix], + group: &[usize], + max_height: usize, +) -> Vec<[u8; 32]> { + let padded = padded_len_binary(max_height); + let mut digests = vec![[0u8; 32]; padded]; + let block_rows = block_rows_for_group(matrices, group, max_height); + let hasher = Blake3; + + for start in (0..max_height).step_by(block_rows) { + let n_rows = (max_height - start).min(block_rows); + let blocks: Vec<(Vec, usize)> = group + .iter() + .map(|&idx| { + let m = &matrices[idx]; + (m.read_raw_rows(start, n_rows), m.row_bytes()) + }) + .collect(); + digests[start..start + n_rows] + .par_iter_mut() + .enumerate() + .for_each(|(local_row, digest)| { + *digest = if let [(buf, row_bytes)] = blocks.as_slice() { + hasher.hash_slice(&buf[local_row * *row_bytes..(local_row + 1) * *row_bytes]) + } else { + hasher.hash_iter_slices(blocks.iter().map(|(buf, row_bytes)| { + &buf[local_row * *row_bytes..(local_row + 1) * *row_bytes] + })) + }; + }); + } + digests +} + +fn compress_layer_binary( + prev_layer: &[[u8; 32]], + compress: &Blake3CompressionFunction, +) -> Vec<[u8; 32]> { + let raw_next = prev_layer.len() / 2; + let next_len_padded = padded_len_binary(raw_next); + let mut next_digests = vec![[0u8; 32]; next_len_padded]; + next_digests[..raw_next] + .par_iter_mut() + .enumerate() + .for_each(|(i, digest)| { + *digest = compress.compress([prev_layer[2 * i], prev_layer[2 * i + 1]]); + }); + next_digests +} + +fn compress_and_inject_streaming( + prev_layer: &[[u8; 32]], + matrices: &[SpilledMatrix], + inject_group: &[usize], + compress: &Blake3CompressionFunction, +) -> Vec<[u8; 32]> { + let next_len = matrices[inject_group[0]].height(); + let raw_next = prev_layer.len() / 2; + let next_len_padded = padded_len_binary(raw_next); + let mut next_digests = vec![[0u8; 32]; next_len_padded]; + let block_rows = block_rows_for_group(matrices, inject_group, next_len); + let hasher = Blake3; + + for start in (0..next_len).step_by(block_rows) { + let n_rows = (next_len - start).min(block_rows); + let blocks: Vec<(Vec, usize)> = inject_group + .iter() + .map(|&idx| { + let m = &matrices[idx]; + (m.read_raw_rows(start, n_rows), m.row_bytes()) + }) + .collect(); + next_digests[start..start + n_rows] + .par_iter_mut() + .enumerate() + .for_each(|(local_row, out)| { + let i = start + local_row; + let digest = compress.compress([prev_layer[2 * i], prev_layer[2 * i + 1]]); + let rows_digest = if let [(buf, row_bytes)] = blocks.as_slice() { + hasher.hash_slice(&buf[local_row * *row_bytes..(local_row + 1) * *row_bytes]) + } else { + hasher.hash_iter_slices(blocks.iter().map(|(buf, row_bytes)| { + &buf[local_row * *row_bytes..(local_row + 1) * *row_bytes] + })) + }; + *out = compress.compress([digest, rows_digest]); + }); + } + + for (i, out) in next_digests[next_len..raw_next].iter_mut().enumerate() { + let idx = next_len + i; + let digest = compress.compress([prev_layer[2 * idx], prev_layer[2 * idx + 1]]); + *out = compress.compress([digest, [0u8; 32]]); + } + + next_digests +} + +/// Prover data for [`SpillableMmcs`]: either Plonky3's standard in-memory +/// [`p3_merkle_tree::MerkleTree`] or a disk-spilled [`SpilledMerkleTree`]. +pub struct SpillableMmcsData(SpillableMmcsDataInner); + +enum SpillableMmcsDataInner { + InMemory { + tree: CpuData, + /// Optional 1× original traces retained for zero-FFT lazy lookup + /// evaluation in in-memory mode; released once stage-2 completes. + retained_traces: Mutex>>>, + }, + Spilled { + tree: SpilledMerkleTree, + /// Lazy fallback cache used ONLY if external code calls + /// [`Mmcs::get_matrices`] directly on spilled prover data. + materialized: Vec>, + materialize: fn(&SpilledMatrix) -> M, + }, +} + +impl SpillableMmcsData { + /// Returns `true` if the LDE leaf matrices are backed by temporary disk + /// spill files rather than resident in memory. + pub const fn is_spilled(&self) -> bool { + matches!(self.0, SpillableMmcsDataInner::Spilled { .. }) + } + + /// Number of spilled matrices that were materialized back into memory via + /// [`Mmcs::get_matrices`]. On the streaming prover path this stays 0. + pub fn materialized_spilled_count(&self) -> usize { + match &self.0 { + SpillableMmcsDataInner::InMemory { .. } => 0, + SpillableMmcsDataInner::Spilled { materialized, .. } => materialized + .iter() + .filter(|slot| slot.get().is_some()) + .count(), + } + } + + pub(crate) fn spilled_original_trace(&self, idx: usize) -> Option { + match &self.0 { + SpillableMmcsDataInner::InMemory { .. } => None, + SpillableMmcsDataInner::Spilled { tree, .. } => tree.spilled_original_trace(idx), + } + } + + pub(crate) fn take_in_memory_original_trace(&self, idx: usize) -> Option> { + match &self.0 { + SpillableMmcsDataInner::InMemory { + retained_traces, .. + } => { + let mut guard = retained_traces + .lock() + .expect("retained_traces lock poisoned"); + guard.get_mut(idx).and_then(Option::take) + } + SpillableMmcsDataInner::Spilled { .. } => None, + } + } + + pub(crate) fn release_original_traces(&self) { + match &self.0 { + SpillableMmcsDataInner::InMemory { + retained_traces, .. + } => { + let mut guard = retained_traces + .lock() + .expect("retained_traces lock poisoned"); + guard.clear(); + } + SpillableMmcsDataInner::Spilled { tree, .. } => tree.release_original_traces(), + } + } +} + +/// CPU MMCS supporting both in-memory commitments (default, zero overhead) and +/// disk-spilled commitments with identical commitments and opening proofs. +#[derive(Clone, Debug)] +pub struct SpillableMmcs { + cpu: CpuMmcs, + compress: Blake3CompressionFunction, +} + +impl SpillableMmcs { + pub fn new( + hash: SerializingHasher, + compress: Blake3CompressionFunction, + cap_height: usize, + ) -> Self { + Self { + cpu: CpuMmcs::new(hash, compress.clone(), cap_height), + compress, + } + } + + pub const fn cap_height(&self) -> usize { + self.cpu.cap_height() + } + + pub(crate) fn commit_in_memory_with_originals( + &self, + ldes: Vec>, + original_traces: Vec>>, + ) -> SpillCommitResult { + let (commitment, tree) = self.cpu.commit(ldes); + ( + commitment, + SpillableMmcsData(SpillableMmcsDataInner::InMemory { + tree, + retained_traces: Mutex::new(original_traces), + }), + ) + } + + pub(crate) fn commit_spilled( + &self, + matrices: Vec, + original_traces: Vec>, + ) -> SpillCommitResult { + let count = matrices.len(); + let tree = SpilledMerkleTree::build(matrices, original_traces, &self.compress); + let cap = tree.cap(self.cap_height()); + let materialized = (0..count).map(|_| OnceLock::new()).collect(); + ( + cap, + SpillableMmcsData(SpillableMmcsDataInner::Spilled { + tree, + materialized, + materialize: SpilledMatrix::read_all, + }), + ) + } + + pub(crate) fn matrix_dimensions>( + &self, + prover_data: &SpillableMmcsData, + ) -> Vec { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => self + .cpu + .get_matrices(tree) + .into_iter() + .map(Matrix::dimensions) + .collect(), + SpillableMmcsDataInner::Spilled { tree, .. } => tree.dimensions(), + } + } +} + +impl Mmcs for SpillableMmcs { + type ProverData = SpillableMmcsData; + type Commitment = >::Commitment; + type Proof = >::Proof; + type MultiProof = >::MultiProof; + type Error = >::Error; + + fn commit>(&self, inputs: Vec) -> (Self::Commitment, Self::ProverData) { + let (commitment, tree) = self.cpu.commit(inputs); + ( + commitment, + SpillableMmcsData(SpillableMmcsDataInner::InMemory { + tree, + retained_traces: Mutex::new(Vec::new()), + }), + ) + } + + fn open_batch>( + &self, + index: usize, + prover_data: &Self::ProverData, + ) -> BatchOpening { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => { + let (opened_values, opening_proof) = self.cpu.open_batch(index, tree).unpack(); + BatchOpening::new(opened_values, opening_proof) + } + SpillableMmcsDataInner::Spilled { tree, .. } => { + let (opened_values, opening_proof) = tree.open_batch(index, self.cap_height()); + BatchOpening::new(opened_values, opening_proof) + } + } + } + + fn get_matrices<'a, M: Matrix>(&self, prover_data: &'a Self::ProverData) -> Vec<&'a M> { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => self.cpu.get_matrices(tree), + SpillableMmcsDataInner::Spilled { + tree, + materialized, + materialize, + } => tree + .matrices + .iter() + .zip(materialized) + .map(|(spilled, slot)| slot.get_or_init(|| materialize(spilled))) + .collect(), + } + } + + fn get_matrix_heights>(&self, prover_data: &Self::ProverData) -> Vec { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => self.cpu.get_matrix_heights(tree), + SpillableMmcsDataInner::Spilled { tree, .. } => tree.matrix_heights(), + } + } + + fn get_max_height>(&self, prover_data: &Self::ProverData) -> usize { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => self.cpu.get_max_height(tree), + SpillableMmcsDataInner::Spilled { tree, .. } => tree.max_height(), + } + } + + fn verify_batch( + &self, + commit: &Self::Commitment, + dimensions: &[Dimensions], + index: usize, + batch_opening: BatchOpeningRef<'_, Val, Self>, + ) -> Result<(), Self::Error> { + let (opened_values, opening_proof) = batch_opening.unpack(); + self.cpu.verify_batch( + commit, + dimensions, + index, + BatchOpeningRef::new(opened_values, opening_proof), + ) + } + + fn open_multi_batch>( + &self, + indices: &[usize], + prover_data: &Self::ProverData, + ) -> (Vec>>, Self::MultiProof) { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => { + self.cpu.open_multi_batch(indices, tree) + } + SpillableMmcsDataInner::Spilled { tree, .. } => { + tree.open_multi_batch(indices, self.cap_height()) + } + } + } + + fn verify_multi_batch + PartialEq>( + &self, + commit: &Self::Commitment, + dimensions: &[Dimensions], + indices: &[usize], + opened_values: &[Vec], + proof: &Self::MultiProof, + ) -> Result<(), Self::Error> { + self.cpu + .verify_multi_batch(commit, dimensions, indices, opened_values, proof) + } +} + +/// CPU two-adic FRI PCS supporting optional disk-backed LDE spilling with +/// streaming commitment, quotient-domain slicing, and FRI opening. +/// +/// When `spill_dir` is `None`, all operations run in memory identically to +/// Plonky3's [`p3_fri::TwoAdicFriPcs`]. When `spill_dir` is `Some(dir)`, LDE +/// matrices are spilled one by one into `dir`, keeping resident memory bounded +/// to compact Merkle digest layers and a single streaming work chunk. +#[derive(Clone, Debug)] +pub struct SpillableTwoAdicFriPcs { + dft: Dft, + mmcs: SpillableMmcs, + fri: FriParameters, + spill_dir: Option, +} + +impl SpillableTwoAdicFriPcs { + pub const fn new(dft: Dft, mmcs: SpillableMmcs, fri: FriParameters) -> Self { + Self { + dft, + mmcs, + fri, + spill_dir: None, + } + } + + pub fn set_spill_dir(&mut self, spill_dir: Option) { + self.spill_dir = spill_dir; + } + + pub fn spill_dir(&self) -> Option<&Path> { + self.spill_dir.as_deref() + } + + pub(crate) fn compute_lde( + &self, + domain: TwoAdicMultiplicativeCoset, + evals: RowMajorMatrix, + ) -> RowMajorMatrix + where + Dft: TwoAdicSubgroupDft, + { + assert_eq!(domain.size(), evals.height()); + let shift = Val::GENERATOR / domain.shift(); + self.dft + .coset_lde_batch(evals, self.fri.log_blowup, shift) + .bit_reverse_rows() + .to_row_major_matrix() + } + + pub(crate) fn commit_spilled_ldes( + &self, + spilled_ldes: Vec, + original_traces: Option>>, + ) -> SpillCommitResult { + let min_height = 1usize << self.fri.log_blowup; + for lde in &spilled_ldes { + assert!( + lde.height() >= min_height, + "committed LDE height {} is smaller than the blowup factor {min_height}", + lde.height() + ); + } + let originals = original_traces.unwrap_or_default(); + self.mmcs.commit_spilled(spilled_ldes, originals) + } + + pub(crate) fn commit_in_memory_ldes( + &self, + ldes: Vec>, + ) -> SpillCommitResult { + let min_height = 1usize << self.fri.log_blowup; + for lde in &ldes { + assert!( + lde.height() >= min_height, + "committed LDE height {} is smaller than the blowup factor {min_height}", + lde.height() + ); + } + self.mmcs.commit(ldes) + } + + /// Commits a streaming iterator of `(domain, matrix, retain_1x)` items. + /// + /// Returns `None` if the iterator yields no items. When disk spilling is + /// enabled, processes one matrix at a time so neither all 1× traces nor all + /// 4× LDEs coexist in memory simultaneously. + pub(crate) fn commit_streaming_with_originals( + &self, + evaluations: &mut dyn Iterator< + Item = (TwoAdicMultiplicativeCoset, RowMajorMatrix, bool), + >, + ) -> Option + where + Dft: TwoAdicSubgroupDft, + { + if let Some(dir) = &self.spill_dir { + let mut lde_pack: Option = None; + let mut orig_pack: Option = None; + let mut spilled_ldes = Vec::new(); + let mut spilled_originals = Vec::new(); + + for (domain, evals, retain_1x) in evaluations { + if retain_1x { + let writer = orig_pack.get_or_insert_with(|| SpillPackWriter::create(dir)); + spilled_originals.push(Some(writer.append_matrix(&evals))); + } else { + spilled_originals.push(None); + } + let lde = self.compute_lde(domain, evals); + let writer = lde_pack.get_or_insert_with(|| SpillPackWriter::create(dir)); + spilled_ldes.push(writer.append_matrix(&lde)); + // `lde` drops here before pulling the next matrix. + } + + if spilled_ldes.is_empty() { + return None; + } + if let Some(writer) = &mut lde_pack { + writer.flush(); + } + if let Some(writer) = &mut orig_pack { + writer.flush(); + } + let originals = if orig_pack.is_some() { + Some(spilled_originals) + } else { + None + }; + Some(self.commit_spilled_ldes(spilled_ldes, originals)) + } else { + let mut ldes = Vec::new(); + let mut originals = Vec::new(); + let mut any_retained = false; + for (domain, evals, retain_1x) in evaluations { + if retain_1x { + any_retained = true; + originals.push(Some(evals.clone())); + } else { + originals.push(None); + } + ldes.push(self.compute_lde(domain, evals)); + } + if ldes.is_empty() { + return None; + } + if any_retained { + Some(self.mmcs.commit_in_memory_with_originals(ldes, originals)) + } else { + Some(self.mmcs.commit(ldes)) + } + } + } +} + +impl Pcs for SpillableTwoAdicFriPcs +where + Dft: TwoAdicSubgroupDft, + FriMmcs: Mmcs, + Challenger: + FieldChallenger + CanObserve + GrindingChallenger, +{ + type Domain = TwoAdicMultiplicativeCoset; + type Commitment = >::Commitment; + type ProverData = >::ProverData>; + type EvaluationsOnDomain<'a> = BitReversedMatrixView>; + type Proof = FriProof>>; + type Error = FriError>::Error>; + const ZK: bool = false; + + fn natural_domain_for_degree(&self, degree: usize) -> Self::Domain { + TwoAdicMultiplicativeCoset::new(Val::ONE, log2_strict_usize(degree)).unwrap() + } + + fn log_max_lde_height(&self) -> usize { + Val::TWO_ADICITY + } + + fn commit( + &self, + evaluations: impl IntoIterator)>, + ) -> (Self::Commitment, Self::ProverData) { + if let Some(dir) = &self.spill_dir { + let mut pack = SpillPackWriter::create(dir); + let mut spilled_ldes = Vec::new(); + for (domain, evals) in evaluations { + let lde = self.compute_lde(domain, evals); + spilled_ldes.push(pack.append_matrix(&lde)); + } + pack.flush(); + self.commit_spilled_ldes(spilled_ldes, None) + } else { + let ldes: Vec<_> = evaluations + .into_iter() + .map(|(domain, evals)| self.compute_lde(domain, evals)) + .collect(); + self.mmcs.commit(ldes) + } + } + + fn get_quotient_ldes( + &self, + evaluations: impl IntoIterator)>, + _num_chunks: usize, + ) -> Vec> { + evaluations + .into_iter() + .map(|(domain, evals)| self.compute_lde(domain, evals)) + .collect() + } + + fn commit_ldes(&self, ldes: Vec>) -> (Self::Commitment, Self::ProverData) { + let min_height = 1usize << self.fri.log_blowup; + for lde in &ldes { + assert!( + lde.height() >= min_height, + "committed LDE height {} is smaller than the blowup factor {min_height}", + lde.height() + ); + } + if let Some(dir) = &self.spill_dir { + let mut pack = SpillPackWriter::create(dir); + let mut spilled = Vec::with_capacity(ldes.len()); + for lde in ldes { + spilled.push(pack.append_matrix(&lde)); + } + pack.flush(); + self.mmcs.commit_spilled(spilled, Vec::new()) + } else { + self.mmcs.commit(ldes) + } + } + + fn get_evaluations_on_domain<'a>( + &self, + prover_data: &'a Self::ProverData, + idx: usize, + domain: Self::Domain, + ) -> Self::EvaluationsOnDomain<'a> { + match &prover_data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => { + let lde = self.mmcs.cpu.get_matrices(tree)[idx]; + if domain.shift() == Val::GENERATOR && lde.height() >= domain.size() { + return lde.split_rows(domain.size()).0.as_cow().bit_reverse_rows(); + } + let poly_height = lde.height() >> self.fri.log_blowup; + let lde_mat = lde.as_view().bit_reverse_rows().to_row_major_matrix(); + self.re_evaluate_from_lde(lde_mat, poly_height, domain) + } + SpillableMmcsDataInner::Spilled { tree, .. } => { + let spilled = &tree.matrices[idx]; + if domain.shift() == Val::GENERATOR && spilled.height() >= domain.size() { + // Read ONLY the `domain.size()` prefix of the bit-reversed + // LDE (e.g. half the LDE when quotient_degree = 2, blowup = 4). + let prefix = spilled.read_rows(0, domain.size()); + let width = prefix.width(); + return RowMajorMatrixCow::new(Cow::Owned(prefix.values), width) + .bit_reverse_rows(); + } + if domain.shift() == Val::ONE + && let Some(orig) = tree.spilled_original_trace(idx) + && orig.height() == domain.size() + { + let natural = orig.read_all(); + let bitrev = natural.as_view().bit_reverse_rows().to_row_major_matrix(); + let width = bitrev.width(); + return RowMajorMatrixCow::new(Cow::Owned(bitrev.values), width) + .bit_reverse_rows(); + } + let poly_height = spilled.height() >> self.fri.log_blowup; + let lde_mat = spilled + .read_all() + .as_view() + .bit_reverse_rows() + .to_row_major_matrix(); + self.re_evaluate_from_lde(lde_mat, poly_height, domain) + } + } + } + + fn open( + &self, + commitment_data_with_opening_points: Vec< + ProverDataWithOpeningPoints<'_, ExtVal, Self::ProverData>, + >, + challenger: &mut Challenger, + ) -> (OpenedValues, Self::Proof) { + let dims_and_points: Vec<(Vec, &Vec>)> = + commitment_data_with_opening_points + .iter() + .map(|(data, points)| { + let dims = self.mmcs.matrix_dimensions(data); + debug_assert_eq!( + dims.len(), + points.len(), + "each matrix should have a corresponding set of evaluation points" + ); + (dims, points) + }) + .collect(); + + let (global_max_height, global_max_width) = dims_and_points + .iter() + .flat_map(|(dims, _)| dims.iter().map(|d| (d.height, d.width))) + .reduce(|(hmax, wmax), (h, w)| (hmax.max(h), wmax.max(w))) + .expect("No Matrices Supplied?"); + let log_global_max_height = log2_strict_usize(global_max_height); + + let coset = { + let coset = + TwoAdicMultiplicativeCoset::new(Val::GENERATOR, log_global_max_height).unwrap(); + let mut coset_points: Vec = coset.iter().collect(); + reverse_slice_index_bits(&mut coset_points); + coset_points + }; + + let inv_denoms = compute_inverse_denominators_from_dims(&dims_and_points, &coset); + drop(coset); + + let adjusted_weights: LinearMap> = inv_denoms + .iter() + .map(|(point, denoms)| (*point, compute_adjusted_weights(*point, denoms))) + .collect(); + + // Pass 1: Barycentric interpolation at each opening point, streaming + // only the first `h = height >> log_blowup` rows of spilled matrices in + // bounded chunks (and reading each matrix once across all its opening + // points). + let all_opened_values: OpenedValues = commitment_data_with_opening_points + .iter() + .zip(&dims_and_points) + .map(|((data, points), (dims, _))| { + points + .iter() + .enumerate() + .map(|(mat_idx, points_for_mat)| { + let dim = dims[mat_idx]; + let h = dim.height >> self.fri.log_blowup; + if points_for_mat.is_empty() { + return Vec::new(); + } + match &data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => { + let mat = self.mmcs.cpu.get_matrices(tree)[mat_idx]; + let mat_view = mat.as_view(); + let (low_coset, _) = mat_view.split_rows(h); + points_for_mat + .iter() + .map(|&point| { + let _guard = debug_span!( + "evaluate matrix", + dims = %mat.dimensions() + ) + .entered(); + let adj = &adjusted_weights.get(&point).unwrap()[..h]; + let ys = low_coset.interpolate_coset_with_precomputation( + Val::GENERATOR, + point, + adj, + ); + challenger.observe_algebra_slice(&ys); + ys + }) + .collect() + } + SpillableMmcsDataInner::Spilled { tree, .. } => { + let spilled = &tree.matrices[mat_idx]; + let _guard = debug_span!( + "evaluate spilled matrix", + dims = %dim + ) + .entered(); + let evals_per_point = interpolate_spilled_coset( + spilled, + h, + points_for_mat, + &adjusted_weights, + ); + for ys in &evals_per_point { + challenger.observe_algebra_slice(ys); + } + evals_per_point + } + } + }) + .collect() + }) + .collect(); + + // Free adjusted_weights before allocating reduced openings. + drop(adjusted_weights); + + let alpha: ExtVal = challenger.sample_algebra_element(); + let packed_alpha_powers: Vec<_> = + >::ExtensionPacking::packed_ext_powers_capped( + alpha, + global_max_width, + ) + .collect(); + + // Pass 2: Build reduced-opening codewords, streaming spilled matrices in + // bounded row blocks. + let mut num_reduced = [0usize; 33]; + let mut reduced_openings: [Option>; 33] = core::array::from_fn(|_| None); + + for (((data, points), (dims, _)), openings_for_round) in commitment_data_with_opening_points + .iter() + .zip(&dims_and_points) + .zip(&all_opened_values) + { + for (mat_idx, (points_for_mat, openings_for_mat)) in + points.iter().zip(openings_for_round).enumerate() + { + let dim = dims[mat_idx]; + let log_height = log2_strict_usize(dim.height); + let _guard = debug_span!("reduce matrix quotient", dims = %dim).entered(); + + let reduced_opening_for_log_height = reduced_openings[log_height] + .get_or_insert_with(|| ExtVal::zero_vec(dim.height)); + debug_assert_eq!(reduced_opening_for_log_height.len(), dim.height); + + let mut point_params = Vec::with_capacity(points_for_mat.len()); + for (&point, openings) in points_for_mat.iter().zip(openings_for_mat) { + let alpha_pow_offset = alpha.exp_u64( + u64::try_from(num_reduced[log_height]) + .expect("reduced column count exceeds u64"), + ); + let reduced_val: ExtVal = dot_product(alpha.powers(), openings.iter().copied()); + let inv_denom = inv_denoms.get(&point).unwrap().as_slice(); + point_params.push((alpha_pow_offset, reduced_val, inv_denom)); + num_reduced[log_height] += dim.width; + } + + if point_params.is_empty() { + continue; + } + + match &data.0 { + SpillableMmcsDataInner::InMemory { tree, .. } => { + let mat = self.mmcs.cpu.get_matrices(tree)[mat_idx]; + let mat_compressed: Vec = mat + .as_view() + .rowwise_packed_dot_product::(&packed_alpha_powers) + .collect(); + for &(alpha_pow_offset, reduced_val, inv_denom) in &point_params { + mat_compressed + .par_iter() + .zip(reduced_opening_for_log_height.par_iter_mut()) + .zip(inv_denom.par_iter()) + .for_each(|((&reduced_row, ro), &inv_d)| { + *ro += alpha_pow_offset * (reduced_val - reduced_row) * inv_d; + }); + } + } + SpillableMmcsDataInner::Spilled { tree, .. } => { + let spilled = &tree.matrices[mat_idx]; + let row_bytes = spilled.row_bytes().max(size_of::()); + let chunk_rows = (STREAM_BLOCK_BYTES / row_bytes) + .clamp(1, 1 << 14) + .min(dim.height); + for row_start in (0..dim.height).step_by(chunk_rows) { + let n_rows = (dim.height - row_start).min(chunk_rows); + let row_end = row_start + n_rows; + let chunk = spilled.read_rows(row_start, n_rows); + let mat_compressed: Vec = chunk + .as_view() + .rowwise_packed_dot_product::(&packed_alpha_powers) + .collect(); + drop(chunk); + for &(alpha_pow_offset, reduced_val, inv_denom) in &point_params { + mat_compressed + .par_iter() + .zip( + reduced_opening_for_log_height[row_start..row_end] + .par_iter_mut(), + ) + .zip(inv_denom[row_start..row_end].par_iter()) + .for_each(|((&reduced_row, ro), &inv_d)| { + *ro += + alpha_pow_offset * (reduced_val - reduced_row) * inv_d; + }); + } + } + } + } + } + } + + // Release opening scratch buffers before FRI commit phase starts. + drop(inv_denoms); + drop(packed_alpha_powers); + + let fri_input: Vec> = reduced_openings.into_iter().rev().flatten().collect(); + let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); + let fri_proof = prover::prove_fri( + &folding, + &self.fri, + fri_input, + challenger, + log_global_max_height, + &commitment_data_with_opening_points, + &self.mmcs, + ); + + (all_opened_values, fri_proof) + } + + fn verify( + &self, + commitments_with_opening_points: Vec< + CommitmentWithOpeningPoints, + >, + proof: &Self::Proof, + challenger: &mut Challenger, + ) -> Result<(), Self::Error> { + for (_, round) in &commitments_with_opening_points { + for (_, mat) in round { + for (_, point) in mat { + challenger.observe_algebra_slice(point); + } + } + } + let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); + verifier::verify_fri( + &folding, + &self.fri, + proof, + challenger, + &commitments_with_opening_points, + &self.mmcs, + )?; + Ok(()) + } + + fn build_periodic_lde_table( + &self, + periodic_cols: &[Vec], + trace_domain: Self::Domain, + quotient_domain: Self::Domain, + ) -> PeriodicLdeTable { + build_periodic_lde_table_two_adic(&self.dft, periodic_cols, &trace_domain, "ient_domain) + } +} + +impl, FriMmcs> SpillableTwoAdicFriPcs { + fn re_evaluate_from_lde<'a>( + &self, + lde_mat: RowMajorMatrix, + poly_height: usize, + domain: TwoAdicMultiplicativeCoset, + ) -> BitReversedMatrixView> { + let mut coeffs = self.dft.coset_idft_batch(lde_mat, Val::GENERATOR); + let width = coeffs.width(); + coeffs.values.truncate(poly_height * width); + coeffs.values.resize(domain.size() * width, Val::ZERO); + let result = self + .dft + .coset_dft_batch(coeffs, domain.shift()) + .bit_reverse_rows() + .to_row_major_matrix(); + let result_width = result.width(); + RowMajorMatrixCow::new(Cow::Owned(result.values), result_width).bit_reverse_rows() + } +} + +fn compute_inverse_denominators_from_dims( + dims_and_points: &[(Vec, &Vec>)], + coset: &[Val], +) -> LinearMap> { + let mut max_log_height_for_point: LinearMap = LinearMap::new(); + for (dims, points) in dims_and_points { + for (dim, points_for_mat) in dims.iter().zip(*points) { + let log_height = log2_strict_usize(dim.height); + for &z in points_for_mat { + if let Some(lh) = max_log_height_for_point.get_mut(&z) { + *lh = (*lh).max(log_height); + } else { + max_log_height_for_point.insert(z, log_height); + } + } + } + } + + max_log_height_for_point + .into_iter() + .map(|(z, log_height)| { + let diffs: Vec = coset[..(1 << log_height)].iter().map(|&x| z - x).collect(); + (z, batch_multiplicative_inverse(&diffs)) + }) + .collect() +} + +/// Streams rows `0..h` of `spilled` once in bounded chunks and computes the +/// exact barycentric interpolation at every point in `points`, matching +/// `Interpolate::interpolate_coset_with_precomputation`. +fn interpolate_spilled_coset( + spilled: &SpilledMatrix, + h: usize, + points: &[ExtVal], + adjusted_weights: &LinearMap>, +) -> Vec> { + let width = spilled.width(); + let mut accumulators: Vec> = + (0..points.len()).map(|_| ExtVal::zero_vec(width)).collect(); + let row_bytes = spilled.row_bytes().max(size_of::()); + let chunk_rows = (STREAM_BLOCK_BYTES / row_bytes).clamp(1, 1 << 14).min(h); + + for row_start in (0..h).step_by(chunk_rows) { + let n_rows = (h - row_start).min(chunk_rows); + let chunk = spilled.read_rows(row_start, n_rows); + for (acc, &point) in accumulators.iter_mut().zip(points) { + let adj_slice = &adjusted_weights.get(&point).unwrap()[row_start..row_start + n_rows]; + let partial = chunk.as_view().columnwise_dot_product(adj_slice); + for (dst, src) in acc.iter_mut().zip(partial) { + *dst += src; + } + } + } + + let log_h = log2_strict_usize(h); + let g_pow_n = Val::GENERATOR.exp_power_of_2(log_h); + let denom_inv = g_pow_n + .mul_2exp_u64(u64::try_from(log_h).expect("log_h exceeds u64")) + .inverse(); + + for (evals, &point) in accumulators.iter_mut().zip(points) { + let z_pow_n = point.exp_power_of_2(log_h); + let scaling_factor = point * (z_pow_n - g_pow_n) * denom_inv; + scale_slice_in_place_single_core(evals, scaling_factor); + } + + accumulators +} + +#[cfg(test)] +mod tests { + use super::*; + use rand::rngs::SmallRng; + use rand::{RngExt, SeedableRng}; + + fn make_mmcs(cap_height: usize) -> (CpuMmcs, SpillableMmcs) { + let byte_hash = Blake3; + let field_hash = SerializingHasher::new(byte_hash); + let compress = Blake3CompressionFunction::new(byte_hash); + ( + CpuMmcs::new(field_hash, compress.clone(), cap_height), + SpillableMmcs::new(field_hash, compress, cap_height), + ) + } + + fn temp_spill_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!( + "multi-stark-spill-test-{tag}-{}-{nanos}", + std::process::id() + )) + } + + fn assert_spilled_matches_cpu( + mats: &[RowMajorMatrix], + cap_height: usize, + query_indices: &[usize], + tag: &str, + ) { + let dir = temp_spill_dir(tag); + let (cpu, spillable) = make_mmcs(cap_height); + let (cpu_com, cpu_data) = cpu.commit(mats.to_vec()); + + let mut pack = SpillPackWriter::create(&dir); + let spilled_mats: Vec<_> = mats.iter().map(|m| pack.append_matrix(m)).collect(); + pack.flush(); + let (spilled_com, spilled_data) = spillable.commit_spilled(spilled_mats, Vec::new()); + + assert_eq!( + spilled_com.roots(), + cpu_com.roots(), + "cap mismatch for {tag} (cap_height={cap_height})" + ); + assert!(spilled_data.is_spilled()); + assert_eq!( + spillable.get_matrix_heights(&spilled_data), + cpu.get_matrix_heights(&cpu_data) + ); + assert_eq!( + spillable.get_max_height(&spilled_data), + cpu.get_max_height(&cpu_data) + ); + + let dims: Vec = mats.iter().map(Matrix::dimensions).collect(); + for &idx in query_indices { + let cpu_open = cpu.open_batch(idx, &cpu_data); + let spilled_open = spillable.open_batch(idx, &spilled_data); + assert_eq!(spilled_open.opened_values, cpu_open.opened_values); + assert_eq!(spilled_open.opening_proof, cpu_open.opening_proof); + cpu.verify_batch( + &spilled_com, + &dims, + idx, + BatchOpeningRef::new(&spilled_open.opened_values, &spilled_open.opening_proof), + ) + .expect("CpuMmcs must accept spilled single opening"); + } + + let (cpu_vals, cpu_multi) = cpu.open_multi_batch(query_indices, &cpu_data); + let (spilled_vals, spilled_multi) = + spillable.open_multi_batch(query_indices, &spilled_data); + assert_eq!(spilled_vals, cpu_vals); + assert_eq!(spilled_multi.sibling_hashes, cpu_multi.sibling_hashes); + cpu.verify_multi_batch( + &spilled_com, + &dims, + query_indices, + &spilled_vals, + &spilled_multi, + ) + .expect("CpuMmcs must accept spilled multi-batch opening"); + + // Ensure nothing materialized the spilled matrices back into RAM. + assert_eq!(spilled_data.materialized_spilled_count(), 0); + drop(spilled_data); + drop(pack); + let remaining = fs::read_dir(&dir).unwrap().count(); + assert_eq!( + remaining, 0, + "spill directory must have zero leftover files" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn spilled_merkle_matches_cpu_across_shapes_and_caps() { + let mut rng = SmallRng::seed_from_u64(42); + let rand_mat = |rng: &mut SmallRng, h: usize, w: usize| { + RowMajorMatrix::new( + (0..h * w).map(|_| Goldilocks::new(rng.random())).collect(), + w, + ) + }; + + // Single matrix, power-of-two height, multiple cap heights + unsorted/duplicate queries. + let single = vec![rand_mat(&mut rng, 32, 7)]; + for cap_height in [0, 1, 2, 5] { + assert_spilled_matches_cpu( + &single, + cap_height, + &[17, 0, 31, 17, 4, 5, 0], + &format!("single-cap{cap_height}"), + ); + } + + // Height = 1 edge case. + let unit = vec![rand_mat(&mut rng, 1, 5), rand_mat(&mut rng, 1, 3)]; + for cap_height in [0, 1, 2] { + assert_spilled_matches_cpu( + &unit, + cap_height, + &[0, 0], + &format!("unit-cap{cap_height}"), + ); + } + + // Mixed heights with gaps and multiple matrices at identical heights (insertion order matters!). + let mixed = vec![ + rand_mat(&mut rng, 16, 4), + rand_mat(&mut rng, 64, 3), + rand_mat(&mut rng, 4, 9), + rand_mat(&mut rng, 64, 5), + rand_mat(&mut rng, 16, 2), + rand_mat(&mut rng, 1, 6), + ]; + for cap_height in [0, 1, 2] { + assert_spilled_matches_cpu( + &mixed, + cap_height, + &[63, 12, 0, 12, 41, 7, 13, 62], + &format!("mixed-cap{cap_height}"), + ); + } + + // Non-power-of-two heights on the ceil(max_height / 2^k) ladder. + let non_pow2 = vec![ + rand_mat(&mut rng, 11, 3), + rand_mat(&mut rng, 6, 4), + rand_mat(&mut rng, 3, 2), + rand_mat(&mut rng, 2, 5), + rand_mat(&mut rng, 1, 1), + ]; + for cap_height in [0, 1, 2] { + assert_spilled_matches_cpu( + &non_pow2, + cap_height, + &[10, 0, 5, 10, 3], + &format!("nonpow2-cap{cap_height}"), + ); + } + } + + #[test] + fn spilled_window_wrap_and_interpolation_match_in_memory() { + let mut rng = SmallRng::seed_from_u64(99); + let dir = temp_spill_dir("window-interp"); + let mut pack = SpillPackWriter::create(&dir); + + // Height = 1 wraparound edge case. + let mat1 = RowMajorMatrix::new(vec![Goldilocks::new(11), Goldilocks::new(22)], 2); + let sp1 = pack.append_matrix(&mat1); + + // Height = 16 matrix for interior + final wraparound chunks and coset interpolation. + let h = 16usize; + let w = 7usize; + let mat16 = RowMajorMatrix::new( + (0..h * w).map(|_| Goldilocks::new(rng.random())).collect(), + w, + ); + let sp16 = pack.append_matrix(&mat16); + pack.flush(); + + // Height = 1 window: row 0 followed by cyclic row 0. + let win1 = sp1.read_window_with_wrap(0, 1); + assert_eq!(win1.height(), 2); + assert_eq!( + win1.row_slice(0).unwrap().as_ref(), + &[Goldilocks::new(11), Goldilocks::new(22)] + ); + assert_eq!( + win1.row_slice(1).unwrap().as_ref(), + &[Goldilocks::new(11), Goldilocks::new(22)] + ); + + // Interior chunk [0..5) -> rows 0..6 (halo is row 5). + let win_mid = sp16.read_window_with_wrap(0, 5); + assert_eq!(win_mid.height(), 6); + for r in 0..6 { + assert_eq!( + win_mid.row_slice(r).unwrap().as_ref(), + mat16.row_slice(r).unwrap().as_ref() + ); + } + + // Final chunk [12..16) -> rows 12, 13, 14, 15, 0 (halo wraps to row 0). + let win_end = sp16.read_window_with_wrap(12, 4); + assert_eq!(win_end.height(), 5); + for local in 0..4 { + assert_eq!( + win_end.row_slice(local).unwrap().as_ref(), + mat16.row_slice(12 + local).unwrap().as_ref() + ); + } + assert_eq!( + win_end.row_slice(4).unwrap().as_ref(), + mat16.row_slice(0).unwrap().as_ref() + ); + + // Compare `interpolate_spilled_coset` against `Interpolate::interpolate_coset_with_precomputation`. + let log_h = log2_strict_usize(h); + let coset: Vec = { + let mut pts: Vec = TwoAdicMultiplicativeCoset::new(Val::GENERATOR, log_h) + .unwrap() + .iter() + .collect(); + reverse_slice_index_bits(&mut pts); + pts + }; + let p1 = ExtVal::new([Goldilocks::new(12345), Goldilocks::new(67890)]); + let p2 = ExtVal::new([Goldilocks::new(54321), Goldilocks::new(9876)]); + let mut adjusted = LinearMap::new(); + for p in [p1, p2] { + let diffs: Vec = coset.iter().map(|&x| p - x).collect(); + let invs = batch_multiplicative_inverse(&diffs); + adjusted.insert(p, compute_adjusted_weights(p, &invs)); + } + + let got = interpolate_spilled_coset(&sp16, h, &[p1, p2], &adjusted); + for (idx, p) in [p1, p2].into_iter().enumerate() { + let expected = mat16.interpolate_coset_with_precomputation( + Val::GENERATOR, + p, + adjusted.get(&p).unwrap(), + ); + assert_eq!(got[idx], expected); + } + + drop(sp1); + drop(sp16); + drop(pack); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 0); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/src/prover.rs b/src/prover.rs index 29065a4..eeeefbd 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -363,6 +363,37 @@ where self.prove_committed(key, claims, stage_1) } + /// Generates a STARK proof with a single claim by streaming stage-1 traces + /// lazily and evaluating lookups on demand. + /// + /// Produces proofs byte-identical to [`Self::prove`]. + pub fn prove_streaming(&self, key: &ProverKey, claim: &[Val], traces: I) -> Proof + where + I: IntoIterator, + I::Item: Into>>, + { + self.prove_multiple_claims_streaming(key, &[claim], traces) + } + + /// Generates a STARK proof with multiple claims by streaming stage-1 traces + /// lazily without materializing [`LookupValues`] upfront. + /// + /// Produces proofs byte-identical to [`Self::prove_multiple_claims`]. + #[tracing::instrument(level = "info", skip_all, name = "stark/prove_streaming")] + pub fn prove_multiple_claims_streaming( + &self, + key: &ProverKey, + claims: &[&[Val]], + traces: I, + ) -> Proof + where + I: IntoIterator, + I::Item: Into>>, + { + let stage_1 = self.prove_stage_1_streaming(traces); + self.prove_committed(key, claims, stage_1) + } + /// Continue an ordinary proof from independently prepared stage-one data. /// /// # Panics @@ -454,33 +485,116 @@ where "cannot prove with every circuit deactivated (all traces empty)" ); + // Only active circuits enter the accumulator chain; the chain (and + // `intermediate_accumulators`) is indexed by active position. + let lookups: Vec<_> = witness + .lookups + .into_iter() + .zip(&active) + .filter_map(|(l, &is_active)| is_active.then_some(l)) + .collect(); + // Cost: "Stage 1 commit" — coset LDE (FFT) of each trace from n_i to // n_i·B rows (an iDFT plus B coset DFTs per column), then Merkle // tree. FFT work: Σ w_i · (B+1) · n_i · log₂(n_i). - let mut log_degrees = vec![]; - let evaluations = witness + let mut log_degrees = Vec::with_capacity(active_indices.len()); + let mut evaluations = witness .traces .into_iter() - .zip(active.clone()) - .filter_map(|(trace, is_active)| is_active.then_some(trace)) - .map(|trace| { + .enumerate() + .zip(&active) + .filter_map(|((ci, trace), &is_active)| is_active.then_some((ci, trace))) + .zip(&lookups) + .map(|((ci, trace), lookup)| { let degree = trace.height(); let log_degree = log2_strict_usize(degree); let trace_domain = pcs.natural_domain_for_degree(degree); log_degrees.push(log_degree); - (trace_domain, trace) + let retain_1x = !lookup.is_materialized() && self.circuits[ci].num_lookups > 0; + (trace_domain, trace, retain_1x) }); - let (stage_1_trace_commit, stage_1_trace_data) = - self.config.commit_main(evaluations.collect()); + let (stage_1_trace_commit, stage_1_trace_data) = self + .config + .commit_main_streaming(&mut evaluations) + .expect("cannot prove with every circuit deactivated (all traces empty)"); - // Only active circuits enter the accumulator chain; the chain (and - // `intermediate_accumulators`) is indexed by active position. - let lookups: Vec<_> = witness - .lookups - .into_iter() - .zip(&active) - .filter_map(|(l, &is_active)| is_active.then_some(l)) - .collect(); + Stage1 { + active, + active_indices, + log_degrees, + stage_1_trace_commit, + stage_1_trace_data, + lookups, + } + } + + /// Streaming round one of a proof: pulls each circuit's stage-1 trace + /// lazily from `traces` without holding all traces or [`LookupValues`] in + /// memory simultaneously. + /// + /// Lookup expressions are evaluated on demand in bounded row chunks during + /// stage-2 trace construction. Produces proofs byte-identical to + /// [`Self::prove_stage_1`] with [`SystemWitness::from_stage_1`]. + /// + /// # Panics + /// Panics if `traces` does not yield one trace per circuit, if an active + /// circuit's height disagrees with its preprocessed trace height, or if + /// every circuit's trace is empty. + #[tracing::instrument(level = "info", skip_all, name = "stark/stage1_commit_streaming")] + pub fn prove_stage_1_streaming(&self, traces: I) -> Stage1 + where + I: IntoIterator, + I::Item: Into>>, + { + let pcs = self.config.pcs(); + let mut active = Vec::with_capacity(self.circuits.len()); + let mut active_indices = Vec::new(); + let mut log_degrees = Vec::new(); + let mut lookups = Vec::new(); + + let mut evaluations = traces.into_iter().enumerate().filter_map(|(ci, trace)| { + assert!( + ci < self.circuits.len(), + "expected one trace per circuit (got more than {})", + self.circuits.len() + ); + let trace: crate::witness::TraceSource> = trace.into(); + let height = trace.height(); + let circuit = &self.circuits[ci]; + if height == 0 { + active.push(false); + return None; + } + if circuit.preprocessed_height != 0 { + assert_eq!( + height, circuit.preprocessed_height, + "circuit {ci}: main trace height must equal preprocessed trace height" + ); + } + active.push(true); + active_indices.push(ci); + log_degrees.push(log2_strict_usize(height)); + let slot_widths: Vec = circuit + .graph + .lookups + .iter() + .map(|lookup| lookup.args.len()) + .collect(); + lookups.push(LookupValues::shape_only(height, &slot_widths)); + let trace_domain = pcs.natural_domain_for_degree(height); + let retain_1x = circuit.num_lookups > 0; + Some((trace_domain, trace, retain_1x)) + }); + + let committed = self.config.commit_main_streaming(&mut evaluations); + for _ in evaluations {} + assert_eq!( + active.len(), + self.circuits.len(), + "expected one trace per circuit" + ); + let (stage_1_trace_commit, stage_1_trace_data) = + committed.expect("cannot prove with every circuit deactivated (all traces empty)"); Stage1 { active, @@ -556,24 +670,95 @@ where drop(_g); result } else { - let (stage_2_traces, intermediate_accumulators) = self - .config - .accelerated_lookup_traces( - &active_lookups, - &group_sizes, - lookup_argument_challenge, - fingerprint_challenge, - acc, - ) - .unwrap_or_else(|| { - LookupValues::stage_2_traces( + let any_unmaterialized = active_lookups.iter().any(|l| !l.is_materialized()); + let (stage_2_traces, intermediate_accumulators) = if any_unmaterialized { + let mut traces = Vec::with_capacity(active_indices.len()); + let mut intermediates = Vec::with_capacity(active_indices.len()); + let mut running = acc; + for ((pos, &ci), (lookup_values, &log_degree)) in active_indices + .iter() + .enumerate() + .zip(active_lookups.iter().zip(&log_degrees)) + { + let circuit = &self.circuits[ci]; + let (trace, delta) = if lookup_values.is_materialized() { + lookup_values.stage_2_trace( + circuit.lookup_group_size, + lookup_argument_challenge, + &fingerprint_challenge, + ) + } else if circuit.graph.lookups.is_empty() { + ( + RowMajorMatrix::new( + vec![ + >::ZERO; + 1 << log_degree + ], + 1, + ), + >::ZERO, + ) + } else { + let trace_domain = pcs.natural_domain_for_degree(1 << log_degree); + let main_trace = pcs + .get_evaluations_on_domain(&stage_1_trace_data, pos, trace_domain) + .to_row_major_matrix(); + let owned_prep; + let prep_ref = if circuit.graph.lookup_prefix_uses_preprocessed() { + if let Some(pp) = circuit.preprocessed.as_ref() { + Some(pp) + } else { + let (prep_data, prep_idx) = key + .preprocessed_data + .as_ref() + .zip(self.preprocessed_indices[ci]) + .expect( + "circuit lookup expressions require preprocessed trace", + ); + owned_prep = pcs + .get_evaluations_on_domain( + prep_data, + prep_idx, + trace_domain, + ) + .to_row_major_matrix(); + Some(&owned_prep) + } + } else { + None + }; + crate::lookup::stage_2_trace_from_trace( + circuit, + &main_trace, + prep_ref, + lookup_argument_challenge, + &fingerprint_challenge, + ) + }; + running += delta; + intermediates.push(running); + traces.push(trace); + } + (traces, intermediates) + } else { + self.config + .accelerated_lookup_traces( &active_lookups, &group_sizes, lookup_argument_challenge, - &fingerprint_challenge, + fingerprint_challenge, acc, ) - }); + .unwrap_or_else(|| { + LookupValues::stage_2_traces( + &active_lookups, + &group_sizes, + lookup_argument_challenge, + &fingerprint_challenge, + acc, + ) + }) + }; // The lookup witness can be as large as the traces themselves; free it // now instead of holding it through the commit/quotient/FRI stages. drop(active_lookups); diff --git a/src/system.rs b/src/system.rs index c33c9bb..8fc7bff 100644 --- a/src/system.rs +++ b/src/system.rs @@ -167,9 +167,15 @@ impl System { Self::new_inner(config, inputs, true) } - /// Commit preprocessing without retaining its evaluation matrices in the system. - /// Use with `prove_committed` and a backend that reconstructs lookup traces from - /// committed data. Ordinary witness construction may need those matrices. + /// Commit preprocessing without retaining its evaluation matrices in the + /// system. + /// + /// When disk spilling is enabled on the configuration, preprocessed traces + /// are streamed one circuit at a time through commitment without holding + /// all preprocessed matrices in memory simultaneously. Works with both + /// lazy lookup evaluation ([`SystemWitness::from_stage_1_lazy`], + /// [`crate::witness::PreparedWitness::from_stage_1_lazy`], + /// [`Self::prove_stage_1_streaming`]) and `prove_committed`. pub fn new_without_preprocessed( config: SC, inputs: impl IntoIterator>>>, @@ -183,13 +189,15 @@ impl System { retain_preprocessed: bool, ) -> (Self, ProverKey) { let pcs = config.pcs(); + let max_quotient_degree = config.max_quotient_degree(); let params = extension_params::(); let d = params.degree; let mut circuits = vec![]; - let mut preprocessed_traces = vec![]; let mut preprocessed_indices = vec![]; - for (i, input) in inputs.into_iter().enumerate() { + let mut next_preprocessed_index = 0usize; + + let mut prep_iter = inputs.into_iter().enumerate().filter_map(|(i, input)| { let input = input.into(); let num_lookups = input.lookups.len(); let group_size = input.lookup_group_size.max(1); @@ -244,33 +252,40 @@ impl System { // factor for FRI). Beyond that, proving would silently produce // invalid proofs, so reject the circuit upfront. assert!( - circuit.quotient_degree() <= config.max_quotient_degree(), + circuit.quotient_degree() <= max_quotient_degree, "circuit {i}: constraint degree {} needs quotient degree {}, but the PCS only \ supports {}; increase log_blowup or lower the constraint degree", circuit.max_constraint_degree(), circuit.quotient_degree(), - config.max_quotient_degree(), + max_quotient_degree, ); - if let Some(preprocessed) = circuit.preprocessed.take() { - preprocessed_indices.push(Some(preprocessed_traces.len())); + let item = if let Some(preprocessed) = circuit.preprocessed.take() { + preprocessed_indices.push(Some(next_preprocessed_index)); + next_preprocessed_index += 1; let domain = pcs.natural_domain_for_degree(preprocessed.height()); + let retain_1x = + !retain_preprocessed && circuit.graph.lookup_prefix_uses_preprocessed(); if retain_preprocessed { circuit.preprocessed = Some(preprocessed.clone()); } - preprocessed_traces.push((domain, preprocessed)); + Some((domain, preprocessed, retain_1x)) } else { preprocessed_indices.push(None); - } + None + }; circuits.push(circuit); - } + item + }); + + let (preprocessed_commit, preprocessed_data) = + match config.commit_preprocessed(&mut prep_iter) { + Some((commit, data)) => (Some(commit), Some(data)), + None => (None, None), + }; + // Ensure all inputs are drained even if a custom backend stopped early. + for _ in prep_iter {} - let (preprocessed_commit, preprocessed_data) = if preprocessed_traces.is_empty() { - (None, None) - } else { - let (commit, data) = pcs.commit(preprocessed_traces); - (Some(commit), Some(data)) - }; let system = Self { config, circuits, @@ -359,6 +374,52 @@ impl SystemWitness { ); Self { traces, lookups } } + + /// Builds a lazy witness from the stage-1 traces without materializing + /// [`LookupValues`] upfront. + /// + /// Lookup expressions are evaluated on demand in bounded row chunks during + /// stage-2 trace construction instead of holding concrete lookup arguments + /// and multiplicities in RAM alongside the traces and LDEs. Produces proofs + /// byte-identical to [`Self::from_stage_1`]. + /// + /// # Panics + /// Panics under the same shape checks as [`Self::from_stage_1`]: trace + /// count must match circuit count, and any active circuit with a + /// preprocessed trace must match its preprocessed height. + pub fn from_stage_1_lazy(traces: Vec>, system: &System) -> Self + where + SC: ProofConfig, + SC::Pcs: Pcs, + { + assert_eq!( + traces.len(), + system.circuits.len(), + "expected one trace per circuit" + ); + let lookups = traces + .iter() + .zip(&system.circuits) + .enumerate() + .map(|(i, (trace, circuit))| { + let height = trace.height(); + if circuit.preprocessed_height != 0 && height != 0 { + assert_eq!( + height, circuit.preprocessed_height, + "circuit {i}: main trace height must equal preprocessed trace height" + ); + } + let slot_widths: Vec = circuit + .graph + .lookups + .iter() + .map(|lookup| lookup.args.len()) + .collect(); + LookupValues::shape_only(height, &slot_widths) + }) + .collect(); + Self { traces, lookups } + } } /// Computes a circuit's concrete lookup values by sweeping the compiled diff --git a/src/test_circuits/baby_bear_config.rs b/src/test_circuits/baby_bear_config.rs index fc80279..d5ce290 100644 --- a/src/test_circuits/baby_bear_config.rs +++ b/src/test_circuits/baby_bear_config.rs @@ -265,6 +265,42 @@ fn plonkish_baby_bear_native_field_proof() { let witness = SystemWitness::from_stage_1(circuit.traces(&assignment).unwrap(), &system); let proof = system.prove_multiple_claims(&key, &claims, witness); system.verify_multiple_claims(&claims, &proof).unwrap(); + + // Verify generic ProofConfig portable fallback for lazy lookups and + // `new_without_preprocessed` produces byte-identical proofs. + let lazy_witness = + SystemWitness::from_stage_1_lazy(circuit.traces(&assignment).unwrap(), &system); + assert!(lazy_witness.lookups.iter().all(|l| !l.is_materialized())); + let lazy_proof = system.prove_multiple_claims(&key, &claims, lazy_witness); + assert_eq!(lazy_proof.to_bytes().unwrap(), proof.to_bytes().unwrap()); + + let config_no_prep = BabyBearPoseidon2Config::new( + CommitmentParameters { + log_blowup: 1, + cap_height: 0, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 20, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + ); + let (system_no_prep, key_no_prep) = + System::new_without_preprocessed(config_no_prep, circuit.circuit_inputs()); + let streamed_proof = system_no_prep.prove_multiple_claims_streaming( + &key_no_prep, + &claims, + circuit.traces(&assignment).unwrap(), + ); + system_no_prep + .verify_multiple_claims(&claims, &streamed_proof) + .unwrap(); + assert_eq!( + streamed_proof.to_bytes().unwrap(), + proof.to_bytes().unwrap() + ); } impl BaseAir for MulAir { diff --git a/src/types.rs b/src/types.rs index 60b71b8..d4dccd2 100644 --- a/src/types.rs +++ b/src/types.rs @@ -19,12 +19,12 @@ use p3_field::{ extension::BinomialExtensionField, }; use p3_fri::FriParameters as InnerFriParameters; -#[cfg(not(feature = "cuda"))] -use p3_fri::TwoAdicFriPcs; use p3_goldilocks::Goldilocks; -#[cfg(feature = "cuda")] +#[cfg(not(feature = "cuda"))] +use p3_matrix::Matrix; use p3_matrix::dense::RowMajorMatrix; use p3_maybe_rayon::prelude::*; +#[cfg(feature = "cuda")] use p3_merkle_tree::MerkleTreeMmcs; use p3_symmetric::{CompressionFunctionFromHasher, SerializingHasher}; @@ -182,14 +182,15 @@ mod grind_tests { } } } +#[cfg(feature = "cuda")] type CpuMmcs = MerkleTreeMmcs, Blake3CompressionFunction, 2, 32>; #[cfg(not(feature = "cuda"))] -pub type Mmcs = CpuMmcs; +pub type Mmcs = crate::p3_adapter::spill::SpillableMmcs; #[cfg(feature = "cuda")] pub type Mmcs = crate::cuda::mmcs::CudaMmcs; pub type ExtMmcs = ExtensionMmcs; #[cfg(not(feature = "cuda"))] -pub type InnerPcs = TwoAdicFriPcs; +pub type InnerPcs = crate::p3_adapter::spill::SpillableTwoAdicFriPcs; #[cfg(feature = "cuda")] pub type InnerPcs = crate::cuda::pcs::CudaTwoAdicFriPcs; @@ -293,6 +294,45 @@ impl GoldilocksBlake3Config { self.fri_parameters } + /// Enables disk-backed spilling of committed LDE matrices on the CPU + /// prover, writing temporary spill files into `dir`. + /// + /// On Unix, spill files are unlinked immediately upon creation so their + /// disk space is reclaimed automatically on drop, panic, or abnormal + /// termination. Proofs produced with disk spilling enabled are + /// byte-identical to proofs produced in memory. + /// + /// On CUDA builds this is a no-op (CUDA manages its own device offload). + #[cfg_attr(feature = "cuda", allow(unused_mut))] + pub fn with_disk_spill(mut self, dir: impl Into) -> Self { + #[cfg(not(feature = "cuda"))] + self.pcs.inner_mut().set_spill_dir(Some(dir.into())); + #[cfg(feature = "cuda")] + let _ = dir.into(); + self + } + + /// Disables disk spilling (forces in-memory LDE storage on CPU). + #[cfg_attr(feature = "cuda", allow(unused_mut))] + pub fn without_disk_spill(mut self) -> Self { + #[cfg(not(feature = "cuda"))] + self.pcs.inner_mut().set_spill_dir(None); + self + } + + /// Returns the configured disk-spill directory, if disk spilling is + /// enabled on the CPU backend. + pub fn spill_dir(&self) -> Option<&std::path::Path> { + #[cfg(not(feature = "cuda"))] + { + self.pcs.spill_dir() + } + #[cfg(feature = "cuda")] + { + None + } + } + pub fn new(commitment_parameters: CommitmentParameters, fri_parameters: FriParameters) -> Self { Self::with_device(commitment_parameters, fri_parameters, None) } @@ -301,6 +341,10 @@ impl GoldilocksBlake3Config { /// the device `MULTI_STARK_CUDA_DEVICE` names, or 0). Without the /// `cuda` feature only device 0 exists. Configurations on distinct /// devices prove concurrently in one process. + /// + /// On CPU builds, setting `MULTI_STARK_SPILL_DIR` to a non-empty path + /// enables disk-backed LDE spilling by default; call + /// [`Self::with_disk_spill`] or [`Self::without_disk_spill`] to override. pub fn with_device( commitment_parameters: CommitmentParameters, fri_parameters: FriParameters, @@ -324,13 +368,19 @@ impl GoldilocksBlake3Config { device_id.unwrap_or_else(crate::cuda::configured_device), ); #[cfg(not(feature = "cuda"))] - let (pcs, _dft) = { + let (mut pcs, _dft) = { assert!( device_id.is_none_or(|device| device == 0), "no CUDA backend to place a prover on device {device_id:?}" ); new_pcs(commitment_parameters, fri_parameters) }; + #[cfg(not(feature = "cuda"))] + if let Some(dir) = std::env::var_os("MULTI_STARK_SPILL_DIR") + && !dir.is_empty() + { + pcs.set_spill_dir(Some(std::path::PathBuf::from(dir))); + } // Seed the challenger with a protocol tag for domain separation, // followed by every protocol parameter. Binding the parameters into // the seed means transcripts produced under different parameters @@ -399,6 +449,253 @@ impl ProofConfig for GoldilocksBlake3Config { crate::cuda::witness::commit(&self.pcs, evaluations) } + #[cfg(not(feature = "cuda"))] + fn commit_preprocessed( + &self, + evaluations: &mut dyn Iterator< + Item = (crate::config::Domain, RowMajorMatrix, bool), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + self.pcs.commit_streaming_with_originals(evaluations) + } + + #[cfg(not(feature = "cuda"))] + fn commit_main_streaming( + &self, + evaluations: &mut dyn Iterator< + Item = ( + crate::config::Domain, + crate::witness::TraceSource, + bool, + ), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let mut materialized = + evaluations.map(|(domain, trace, retain_1x)| (domain, trace.materialize(), retain_1x)); + self.pcs.commit_streaming_with_originals(&mut materialized) + } + + #[cfg(not(feature = "cuda"))] + fn accelerated_lookup_commit( + &self, + inputs: &[crate::config::LookupCommitInput<'_, Self>], + lookup_challenge: ExtVal, + fingerprint_challenge: ExtVal, + mut accumulator: ExtVal, + ) -> Option> { + use crate::lookup::{ + InMemoryChunk, OwnedWindowChunk, TraceRowChunk, stage_2_trace_chunked, + }; + use crate::p3_adapter::spill::{SpillPackWriter, SpilledMatrix}; + use crate::traits::{Pcs as _, flatten_to_base}; + + enum CpuRowChunk<'a> { + InMemory(InMemoryChunk<'a, Val>), + Spilled(OwnedWindowChunk), + } + + impl TraceRowChunk for CpuRowChunk<'_> { + #[inline] + fn row_pair(&self, local_row: usize) -> (&[Val], &[Val]) { + match self { + Self::InMemory(chunk) => chunk.row_pair(local_row), + Self::Spilled(chunk) => chunk.row_pair(local_row), + } + } + } + + enum TraceBacking<'a> { + Borrowed(&'a RowMajorMatrix), + Owned(RowMajorMatrix), + Spilled(SpilledMatrix), + } + + impl TraceBacking<'_> { + fn load_chunk(&self, start: usize, len: usize) -> CpuRowChunk<'_> { + match self { + Self::Borrowed(mat) => CpuRowChunk::InMemory(InMemoryChunk::new(mat, start)), + Self::Owned(mat) => CpuRowChunk::InMemory(InMemoryChunk::new(mat, start)), + Self::Spilled(spilled) => CpuRowChunk::Spilled(OwnedWindowChunk::new( + spilled.read_window_with_wrap(start, len), + )), + } + } + } + + let spill_dir = self.spill_dir(); + let any_unmaterialized = inputs + .iter() + .any(|input| !input.lookup_values.is_materialized()); + if spill_dir.is_none() && !any_unmaterialized { + return None; + } + + let mut spill_pack = spill_dir.map(SpillPackWriter::create); + let mut spilled_ldes = + Vec::with_capacity(if spill_dir.is_some() { inputs.len() } else { 0 }); + let mut in_memory_ldes = + Vec::with_capacity(if spill_dir.is_none() { inputs.len() } else { 0 }); + let mut intermediates = Vec::with_capacity(inputs.len()); + + for input in inputs { + let circuit = input.circuit; + let height = input.lookup_values.height(); + let (stage_2_ext, delta) = if input.lookup_values.is_materialized() { + input.lookup_values.stage_2_trace( + circuit.lookup_group_size, + lookup_challenge, + &fingerprint_challenge, + ) + } else if circuit.graph.lookups.is_empty() { + ( + RowMajorMatrix::new(vec![ExtVal::ZERO; height], 1), + ExtVal::ZERO, + ) + } else { + let (s1_data, s1_idx) = input.stage_1; + let main_backing = if let Some(spilled) = s1_data.spilled_original_trace(s1_idx) { + TraceBacking::Spilled(spilled) + } else if let Some(owned) = s1_data.take_in_memory_original_trace(s1_idx) { + TraceBacking::Owned(owned) + } else { + let trace_domain = self.pcs.natural_domain_for_degree(height); + TraceBacking::Owned( + self.pcs + .get_evaluations_on_domain(s1_data, s1_idx, trace_domain) + .to_row_major_matrix(), + ) + }; + + let prep_backing = if circuit.graph.lookup_prefix_uses_preprocessed() { + if let Some(pp) = circuit.preprocessed.as_ref() { + Some(TraceBacking::Borrowed(pp)) + } else if let Some((prep_data, prep_idx)) = input.preprocessed { + if let Some(spilled) = prep_data.spilled_original_trace(prep_idx) { + Some(TraceBacking::Spilled(spilled)) + } else { + let trace_domain = self.pcs.natural_domain_for_degree(height); + Some(TraceBacking::Owned( + self.pcs + .get_evaluations_on_domain(prep_data, prep_idx, trace_domain) + .to_row_major_matrix(), + )) + } + } else { + panic!( + "circuit lookup expressions read preprocessed columns, but no preprocessed trace is available" + ); + } + } else { + None + }; + + stage_2_trace_chunked( + circuit, + height, + lookup_challenge, + &fingerprint_challenge, + |start, len| main_backing.load_chunk(start, len), + prep_backing + .as_ref() + .map(|prep| move |start, len| prep.load_chunk(start, len)), + ) + }; + + accumulator += delta; + intermediates.push(accumulator); + + let stage_2_base = flatten_to_base::(stage_2_ext); + let domain = self.pcs.natural_domain_for_degree(stage_2_base.height()); + let lde = self.pcs.compute_lde(domain, stage_2_base); + if let Some(pack) = &mut spill_pack { + spilled_ldes.push(pack.append_matrix(&lde)); + // Drop `lde` immediately before building the next circuit's stage-2 trace. + } else { + in_memory_ldes.push(lde); + } + } + + // Release retained/spilled 1× main traces now that stage-2 is complete. + // Preprocessed 1× traces stay attached to `ProverKey` for reuse across + // proofs/shards. + if let Some(first) = inputs.first() { + first.stage_1.0.release_original_traces(); + } + + let (commitment, data) = if let Some(mut pack) = spill_pack { + pack.flush(); + self.pcs.commit_spilled_ldes(spilled_ldes, None) + } else { + self.pcs.commit_in_memory_ldes(in_memory_ldes) + }; + Some((commitment, data, intermediates)) + } + + #[cfg(not(feature = "cuda"))] + fn accelerated_quotient_commit( + &self, + inputs: &[crate::config::QuotientCommitInput<'_, Self>], + alpha: ExtVal, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + use crate::p3_adapter::pcs::{lde_from_shifted_coefficients, shifted_quotient_slices}; + use crate::p3_adapter::spill::SpillPackWriter; + use crate::traits::{EvaluationDomain, Pcs as _, flatten_to_base}; + + let spill_dir = self.spill_dir()?; + let mut pack = SpillPackWriter::create(spill_dir); + let mut spilled_ldes = Vec::with_capacity(inputs.len()); + let dft = self.pcs.quotient_dft(); + let log_blowup = self.log_blowup; + + for input in inputs { + let circuit = input.circuit; + let quotient_degree = circuit.quotient_degree(); + let preprocessed_evals = input.preprocessed.map(|(data, idx)| { + self.pcs + .get_evaluations_on_domain(data, idx, input.quotient_domain) + }); + let stage_1_evals = self.pcs.get_evaluations_on_domain( + input.stage_1.0, + input.stage_1.1, + input.quotient_domain, + ); + let stage_2_evals = self.pcs.get_evaluations_on_domain( + input.stage_2.0, + input.stage_2.1, + input.quotient_domain, + ); + let q_vals = crate::prover::quotient_values::( + circuit, + &input.lookup_publics, + input.trace_domain, + input.quotient_domain, + &preprocessed_evals, + &stage_1_evals, + &stage_2_evals, + alpha, + input.constraint_count, + ); + // Release this circuit's trace evaluations before running quotient + // DFTs and LDE expansion. + drop(preprocessed_evals); + drop(stage_1_evals); + drop(stage_2_evals); + + let quotient_flat = flatten_to_base::(RowMajorMatrix::new_col(q_vals)); + let sliced = shifted_quotient_slices( + dft, + quotient_flat, + EvaluationDomain::first_point(&input.quotient_domain), + quotient_degree, + ); + let lde = lde_from_shifted_coefficients(dft, sliced, log_blowup); + spilled_ldes.push(pack.append_matrix(&lde)); + } + + pack.flush(); + Some(self.pcs.commit_spilled_ldes(spilled_ldes, None)) + } + fn canonicalize_proof(proof: &mut crate::prover::Proof) { fn canonical_base(value: &mut Val) { *value = Val::from_u64(value.as_canonical_u64()); @@ -1064,6 +1361,9 @@ impl ProofConfig for GoldilocksBlake3Config { if free_bytes < target { return None; } + if !graph_path && !input.lookup_values.is_materialized() { + return None; + } if crate::cuda::memory_diagnostics_enabled() { eprintln!( "[multi-stark/cuda] lookup job {index}: graph={graph_path} output={output_bytes} temporary={temporary_bytes} target={target} free={free_bytes}" @@ -1190,11 +1490,15 @@ fn new_mmcs(cap_height: usize, #[cfg(feature = "cuda")] device_id: i32) -> Mmcs let byte_hash = Blake3; let field_hash = SerializingHasher::new(byte_hash); let compress = Blake3CompressionFunction::new(byte_hash); - let cpu = CpuMmcs::new(field_hash, compress, cap_height); #[cfg(not(feature = "cuda"))] - return cpu; + { + crate::p3_adapter::spill::SpillableMmcs::new(field_hash, compress, cap_height) + } #[cfg(feature = "cuda")] - crate::cuda::mmcs::CudaMmcs::with_device(cpu, device_id) + { + let cpu = CpuMmcs::new(field_hash, compress, cap_height); + crate::cuda::mmcs::CudaMmcs::with_device(cpu, device_id) + } } fn new_pcs( diff --git a/src/witness.rs b/src/witness.rs index 1b99ce8..8e37c7b 100644 --- a/src/witness.rs +++ b/src/witness.rs @@ -61,12 +61,68 @@ impl TraceSource { } } +impl From> for TraceSource { + fn from(matrix: RowMajorMatrix) -> Self { + Self::Host(matrix) + } +} + #[derive(Clone)] pub struct PreparedWitness { pub traces: Vec>, pub lookups: Vec>, } +impl PreparedWitness { + /// Builds a lazy prepared witness from stage-1 trace sources without + /// materializing [`crate::lookup::LookupValues`] upfront. + /// + /// Lookup expressions are evaluated on demand in bounded row chunks during + /// stage-2 trace construction, producing proofs byte-identical to + /// [`crate::system::SystemWitness::from_stage_1`]. + /// + /// # Panics + /// Panics if the number of traces differs from the number of circuits, or + /// if an active circuit with a preprocessed trace receives a trace of a + /// different height. + pub fn from_stage_1_lazy( + traces: Vec>, + system: &crate::system::System, + ) -> Self + where + SC: crate::config::ProofConfig, + SC::Pcs: crate::traits::Pcs, + { + assert_eq!( + traces.len(), + system.circuits.len(), + "expected one trace per circuit" + ); + let lookups = traces + .iter() + .zip(&system.circuits) + .enumerate() + .map(|(i, (trace, circuit))| { + let height = trace.height(); + if circuit.preprocessed_height != 0 && height != 0 { + assert_eq!( + height, circuit.preprocessed_height, + "circuit {i}: main trace height must equal preprocessed trace height" + ); + } + let slot_widths: Vec = circuit + .graph + .lookups + .iter() + .map(|lookup| lookup.args.len()) + .collect(); + crate::lookup::LookupValues::shape_only(height, &slot_widths) + }) + .collect(); + Self { traces, lookups } + } +} + impl From> for PreparedWitness { fn from(witness: crate::system::SystemWitness) -> Self { Self { diff --git a/tests/streaming_spill.rs b/tests/streaming_spill.rs new file mode 100644 index 0000000..b8a867d --- /dev/null +++ b/tests/streaming_spill.rs @@ -0,0 +1,823 @@ +//! End-to-end verification of A5 streaming/lazy lookup evaluation and +//! disk-backed LDE spilling: +//! - 100% byte-identical `Proof::to_bytes()` and `BatchProof::to_bytes()` across +//! in-memory, lazy-lookup, `new_without_preprocessed`, and disk-spilled paths. +//! - Coverage of preprocessed circuits (used in constraints and lookups), sparse +//! activation (including inactive preprocessed circuits), lookup groups `k > 1`, +//! `log_blowup = 1, 2`, `cap_height = 0, 1, 2`, `max_log_arity = 1, 2`, positive +//! PoW, `TraceSource::Generated`, manual `Stage1` construction, and multi-shard +//! batches (`Retain` + `Regenerate` + `BatchMessage`s). +//! - Verification of zero upfront `LookupValues` payloads, zero unintended +//! re-materialization of spilled LDEs, and automatic cleanup on drop and panic. + +use std::fs; +use std::path::PathBuf; +#[cfg(not(feature = "cuda"))] +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use multi_stark::batch::{BatchMessage, BatchProof, Retention, ShardInput}; +use multi_stark::config::ProofConfig; +use multi_stark::expr::Expr; +use multi_stark::lookup::{Lookup, LookupValues}; +use multi_stark::prover::{Proof, Stage1}; +use multi_stark::system::{CircuitInputs, System, SystemWitness}; +use multi_stark::traits::Pcs as _; +use multi_stark::types::{CommitmentParameters, FriParameters, GoldilocksBlake3Config, Val}; +#[cfg(not(feature = "cuda"))] +use multi_stark::witness::TraceGenerator; +use multi_stark::witness::{PreparedWitness, TraceSource}; +use p3_field::PrimeCharacteristicRing; +use p3_matrix::Matrix; +use p3_matrix::dense::RowMajorMatrix; + +static DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +fn fresh_spill_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let seq = DIR_SEQ.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!( + "multi-stark-a5-{tag}-{}-{nanos}-{seq}", + std::process::id() + )) +} + +fn f(v: u32) -> Val { + Val::from_u32(v) +} + +/// Deterministic `TraceGenerator` wrapping a frozen row-major matrix, used to +/// verify `TraceSource::Generated` on both lazy and disk-spilled paths. +#[cfg(not(feature = "cuda"))] +struct MatrixGenerator { + matrix: RowMajorMatrix, +} + +#[cfg(not(feature = "cuda"))] +impl TraceGenerator for MatrixGenerator { + fn height(&self) -> usize { + self.matrix.height() + } + + fn width(&self) -> usize { + self.matrix.width() + } + + fn write_rows(&self, first: usize, output: &mut [Val]) { + let width = self.width(); + let height = self.height(); + let rows = output.len() / width; + for local in 0..rows { + let src = (first + local) % height; + output[local * width..(local + 1) * width] + .copy_from_slice(&self.matrix.values[src * width..(src + 1) * width]); + } + } +} + +/// Builds a 4-circuit system exercising: +/// - Circuit 0: Preprocessed 256-row byte table (`prep[0] = 0..255`, `main[0] = mult`) +/// whose preprocessed column is directly read by its lookup expression. +/// - Circuit 1: Preprocessed 16-row auxiliary table (`prep[0] = 100..116`, `main[0] = mult`) +/// that can be left INACTIVE to exercise sparse activation of preprocessed circuits. +/// - Circuit 2: Active arithmetic + multi-lookup circuit with configurable +/// `lookup_group_size`, a next-row transition constraint (`main[0]' == main[0] + 1` +/// on transitions), a preprocessed selector column (`prep[0] = row_idx`), and +/// 5 lookups per row (1 claim pull + 4 byte-table pushes, exercising partial +/// and full lookup groups across `k = 1..=4`). +/// - Circuit 3: Zero-lookup active circuit (pass-through accumulator) with a +/// degree-2 constraint (`main[0]^2 == main[1]`). +fn multi_circuit_inputs(lookup_group_size: usize, work_rows: usize) -> Vec> { + assert!(work_rows.is_power_of_two() && work_rows >= 4); + + // Circuit 0: preprocessed byte table (height 256). + let byte_prep = RowMajorMatrix::new((0..256u32).map(f).collect(), 1); + let byte_table = CircuitInputs { + main_width: 1, + preprocessed: Some(byte_prep), + constraints: vec![], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(10)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + // Circuit 1: optional preprocessed table (height 16), left inactive in sparse tests. + let aux_prep = RowMajorMatrix::new((100..116u32).map(f).collect(), 1); + let aux_table = CircuitInputs { + main_width: 1, + preprocessed: Some(aux_prep), + constraints: vec![ + // Simple constraint referencing preprocessed column. + Expr::main(0) * (Expr::preprocessed(0) - Expr::preprocessed(0)), + ], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(20)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + // Circuit 2: arithmetic + 5 lookups per row (cols: a, b, c, d, sum, mult). + // Preprocessed col 0 holds a row tag `tag_r = r + 1`, read in BOTH a + // constraint and the claim lookup (including next-row wrap-around!). + let work_prep = RowMajorMatrix::new( + (0..u32::try_from(work_rows).unwrap()) + .map(|r| f(r + 1)) + .collect(), + 1, + ); + let a = Expr::main(0); + let b = Expr::main(1); + let c = Expr::main(2); + let d = Expr::main(3); + let sum = Expr::main(4); + let mult = Expr::main(5); + let tag = Expr::preprocessed(0); + let tag_next = Expr::preprocessed_next(0); + let a_next = Expr::main_next(0); + + let work_constraints = vec![ + // sum == a + b + c + d + tag + sum.clone() - (a.clone() + b.clone() + c.clone() + d.clone() + tag.clone()), + // Transition constraint using Next row: on transitions, a' == a + 1. + Expr::IsTransition * (a_next.clone() - (a.clone() + Expr::constant(Val::ONE))), + ]; + let work_lookups = vec![ + // Pull public claim: [30, tag, tag_next, sum, a_next] — exercises both + // current and next-row wraparound for main AND preprocessed columns! + Lookup::pull( + mult, + vec![Expr::constant(f(30)), tag, tag_next, sum, a_next], + ), + // Push 4 bytes into Circuit 0's byte table. + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), a]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), b]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), c]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), d]), + ]; + let work_circuit = CircuitInputs { + main_width: 6, + preprocessed: Some(work_prep), + constraints: work_constraints, + ext_constraints: vec![], + lookups: work_lookups, + lookup_group_size, + }; + + // Circuit 3: zero-lookup active circuit (x, x^2). + let x = Expr::main(0); + let x2 = Expr::main(1); + let no_lookup_circuit = CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![x.clone() * x - x2], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + + vec![byte_table, aux_table, work_circuit, no_lookup_circuit] +} + +/// Builds traces and matching public claims for `multi_circuit_inputs`. +/// Circuit 1 (preprocessed) is deliberately deactivated (`height == 0`) when +/// `activate_aux == false`, and Circuit 3 is deactivated when `activate_no_lookup == false`. +fn build_traces_and_claims( + work_rows: usize, + seed: u32, + activate_aux: bool, + activate_no_lookup: bool, +) -> (Vec>, Vec>) { + let mut byte_counts = vec![0u32; 256]; + let mut work_vals = Vec::with_capacity(work_rows * 6); + let mut claims = Vec::with_capacity(work_rows); + + let work_rows_u32 = u32::try_from(work_rows).unwrap(); + for r in 0..work_rows_u32 { + let a = seed + r; + assert!(a < 256); + let a_next = seed + ((r + 1) % work_rows_u32); + let b = (seed * 3 + r * 7 + 11) % 256; + let c = (seed * 5 + r * 13 + 29) % 256; + let d = (seed * 7 + r * 17 + 43) % 256; + let tag = r + 1; + let tag_next = ((r + 1) % work_rows_u32) + 1; + let sum = a + b + c + d + tag; + byte_counts[a as usize] += 1; + byte_counts[b as usize] += 1; + byte_counts[c as usize] += 1; + byte_counts[d as usize] += 1; + work_vals.extend_from_slice(&[f(a), f(b), f(c), f(d), f(sum), Val::ONE]); + claims.push(vec![f(30), f(tag), f(tag_next), f(sum), f(a_next)]); + } + + let byte_trace = RowMajorMatrix::new(byte_counts.into_iter().map(f).collect(), 1); + let aux_trace = if activate_aux { + let mut aux_vals = vec![Val::ZERO; 16]; + aux_vals[3] = Val::ONE; + claims.push(vec![f(20), f(103)]); + RowMajorMatrix::new(aux_vals, 1) + } else { + RowMajorMatrix::new(vec![], 1) + }; + let work_trace = RowMajorMatrix::new(work_vals, 6); + let no_lookup_trace = if activate_no_lookup { + RowMajorMatrix::new( + (0..8u32) + .flat_map(|v| [f(v + 2), f((v + 2) * (v + 2))]) + .collect(), + 2, + ) + } else { + RowMajorMatrix::new(vec![], 2) + }; + + ( + vec![byte_trace, aux_trace, work_trace, no_lookup_trace], + claims, + ) +} + +fn make_config( + log_blowup: usize, + cap_height: usize, + max_log_arity: usize, + pow_bits: usize, +) -> GoldilocksBlake3Config { + GoldilocksBlake3Config::new( + CommitmentParameters { + log_blowup, + cap_height, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity, + num_queries: 16, + commit_proof_of_work_bits: pow_bits, + query_proof_of_work_bits: pow_bits, + }, + ) +} + +#[test] +fn streaming_and_spilled_proofs_are_byte_identical_across_configs() { + // Test matrix: + // (lookup_group_size, log_blowup, cap_height, max_log_arity, pow_bits, work_rows, activate_aux) + let cases = [ + // Default ungrouped lookups, blowup 2, cap 0, binary FRI, sparse inactive preprocessed circuit. + (1usize, 1usize, 0usize, 1usize, 0usize, 16usize, false), + // Grouped lookups k = 2, blowup 4 (q=4 supported), cap 1, higher arity, positive PoW. + (2, 2, 1, 2, 4, 32, false), + // Grouped lookups k = 3, blowup 2 (q=4 -> log_blowup=2), cap 2, all circuits active. + (3, 2, 2, 1, 0, 16, true), + // Grouped lookups k = 4 (5 lookups => groups of 4 and 1!), blowup 2, cap 0. + (4, 2, 0, 2, 3, 16, false), + ]; + + for ( + case_idx, + &(k, log_blowup, cap_height, max_log_arity, pow_bits, work_rows, activate_aux), + ) in cases.iter().enumerate() + { + #[cfg(feature = "cuda")] + if cap_height != 0 || max_log_arity > 1 { + continue; + } + let inputs = multi_circuit_inputs(k, work_rows); + let (traces, claims_owned) = build_traces_and_claims(work_rows, 5, activate_aux, true); + let claim_slices: Vec<&[Val]> = claims_owned.iter().map(Vec::as_slice).collect(); + + // 1. Baseline: System::new + SystemWitness::from_stage_1 + in-memory config. + let cfg_base = make_config(log_blowup, cap_height, max_log_arity, pow_bits); + let (sys_base, key_base) = System::new(cfg_base, inputs.clone()); + let wit_base = SystemWitness::from_stage_1(traces.clone(), &sys_base); + let proof_base = sys_base.prove_multiple_claims(&key_base, &claim_slices, wit_base); + sys_base + .verify_multiple_claims(&claim_slices, &proof_base) + .expect("baseline proof must verify"); + let expected_bytes = proof_base.to_bytes().unwrap(); + + // 2. Lazy lookups in-memory (System::new + SystemWitness::from_stage_1_lazy). + let wit_lazy = SystemWitness::from_stage_1_lazy(traces.clone(), &sys_base); + assert!( + wit_lazy.lookups.iter().all(|l| !l.is_materialized()), + "lazy witness must not materialize lookup payloads" + ); + let proof_lazy = sys_base.prove_multiple_claims(&key_base, &claim_slices, wit_lazy); + assert_eq!( + proof_lazy.to_bytes().unwrap(), + expected_bytes, + "case {case_idx}: lazy in-memory proof bytes must match baseline" + ); + + // 3. System::new_without_preprocessed + lazy in-memory. + let cfg_no_prep = make_config(log_blowup, cap_height, max_log_arity, pow_bits); + let (sys_no_prep, key_no_prep) = + System::new_without_preprocessed(cfg_no_prep, inputs.clone()); + assert!( + sys_no_prep + .circuits + .iter() + .all(|c| c.preprocessed.is_none()) + ); + let wit_no_prep = SystemWitness::from_stage_1_lazy(traces.clone(), &sys_no_prep); + let proof_no_prep = + sys_no_prep.prove_multiple_claims(&key_no_prep, &claim_slices, wit_no_prep); + assert_eq!( + proof_no_prep.to_bytes().unwrap(), + expected_bytes, + "case {case_idx}: new_without_preprocessed lazy in-memory proof bytes must match" + ); + + // 4. Full disk-spilled + materialized SystemWitness::from_stage_1. + let spill_dir = fresh_spill_dir(&format!("case-{case_idx}")); + let cfg_spilled = make_config(log_blowup, cap_height, max_log_arity, pow_bits) + .with_disk_spill(&spill_dir); + #[cfg(not(feature = "cuda"))] + assert_eq!(cfg_spilled.spill_dir(), Some(spill_dir.as_path())); + #[cfg(feature = "cuda")] + assert!(cfg_spilled.spill_dir().is_none()); + let (sys_spilled, key_spilled) = + System::new_without_preprocessed(cfg_spilled, inputs.clone()); + #[cfg(not(feature = "cuda"))] + { + let prep_data = key_spilled.preprocessed_data.as_ref().unwrap(); + assert!(prep_data.is_spilled(), "preprocessed LDEs must be spilled"); + assert_eq!(prep_data.materialized_spilled_count(), 0); + } + let wit_mat_spilled = SystemWitness::from_stage_1(traces.clone(), &sys_base); + let proof_mat_spilled = + sys_spilled.prove_multiple_claims(&key_spilled, &claim_slices, wit_mat_spilled); + assert_eq!( + proof_mat_spilled.to_bytes().unwrap(), + expected_bytes, + "case {case_idx}: spilled materialized proof bytes must match" + ); + + // 5. Full disk-spilled + PreparedWitness::from_stage_1_lazy (mixing Host + Generated). + let mixed_sources: Vec> = traces + .iter() + .enumerate() + .map(|(idx, mat)| { + #[cfg(not(feature = "cuda"))] + if idx == 2 { + return TraceSource::Generated(Arc::new(MatrixGenerator { + matrix: mat.clone(), + })); + } + let _ = idx; + TraceSource::Host(mat.clone()) + }) + .collect(); + let prep_wit = PreparedWitness::from_stage_1_lazy(mixed_sources, &sys_spilled); + assert!(prep_wit.lookups.iter().all(|l| !l.is_materialized())); + let stage_1 = sys_spilled.prove_stage_1(prep_wit); + #[cfg(not(feature = "cuda"))] + { + assert!(stage_1.stage_1_trace_data.is_spilled()); + assert_eq!(stage_1.stage_1_trace_data.materialized_spilled_count(), 0); + } + let proof_prep_spilled = sys_spilled.prove_committed(&key_spilled, &claim_slices, stage_1); + assert_eq!( + proof_prep_spilled.to_bytes().unwrap(), + expected_bytes, + "case {case_idx}: spilled PreparedWitness::from_stage_1_lazy proof bytes must match" + ); + + // 6. Full disk-spilled + streaming iterator (`prove_multiple_claims_streaming`). + let proof_streamed = sys_spilled.prove_multiple_claims_streaming( + &key_spilled, + &claim_slices, + traces.clone(), + ); + sys_base + .verify_multiple_claims(&claim_slices, &proof_streamed) + .expect("baseline verifier must accept disk-spilled streamed proof"); + assert_eq!( + proof_streamed.to_bytes().unwrap(), + expected_bytes, + "case {case_idx}: spilled streaming proof bytes must match" + ); + + // 7. Manual `Stage1 { ... }` construction with shape-only lookups (matching Ix's + // `proof-compression/src/pipeline/prover.rs` pattern) on spilled config. + let pcs = sys_spilled.config.pcs(); + let active: Vec = traces.iter().map(|t| t.height() > 0).collect(); + let active_indices: Vec = active + .iter() + .enumerate() + .filter_map(|(i, &a)| a.then_some(i)) + .collect(); + let mut log_degrees = Vec::new(); + let evals: Vec<_> = active_indices + .iter() + .map(|&ci| { + let mat = traces[ci].clone(); + let h = mat.height(); + log_degrees.push(h.ilog2() as usize); + (pcs.natural_domain_for_degree(h), mat) + }) + .collect(); + let (s1_commit, s1_data) = pcs.commit(evals); + let shape_lookups: Vec> = active_indices + .iter() + .map(|&ci| { + let slot_widths: Vec = sys_spilled.circuits[ci] + .graph + .lookups + .iter() + .map(|l| l.args.len()) + .collect(); + LookupValues::shape_only(traces[ci].height(), &slot_widths) + }) + .collect(); + let manual_stage_1 = Stage1 { + active, + active_indices, + log_degrees, + stage_1_trace_commit: s1_commit, + stage_1_trace_data: s1_data, + lookups: shape_lookups, + }; + let proof_manual = sys_spilled.prove_committed(&key_spilled, &claim_slices, manual_stage_1); + assert_eq!( + proof_manual.to_bytes().unwrap(), + expected_bytes, + "case {case_idx}: manual Stage1 with shape_only lookups must match baseline" + ); + + #[cfg(not(feature = "cuda"))] + { + let prep_data = key_spilled.preprocessed_data.as_ref().unwrap(); + assert_eq!( + prep_data.materialized_spilled_count(), + 0, + "case {case_idx}: spilled preprocessed LDEs must never materialize into RAM" + ); + } + + // Drop prover key and verify zero lingering files in spill_dir. + drop(key_spilled); + drop(sys_spilled); + #[cfg(not(feature = "cuda"))] + assert_eq!( + fs::read_dir(&spill_dir).unwrap().count(), + 0, + "case {case_idx}: spill_dir must contain zero leftover files after drop" + ); + let _ = fs::remove_dir_all(&spill_dir); + + // Round-trip serialization check. + let decoded = Proof::::from_bytes(&expected_bytes).unwrap(); + sys_base + .verify_multiple_claims(&claim_slices, &decoded) + .unwrap(); + } +} + +/// Verifies multi-shard batch proving (`prove_batch`, `Retention::Retain`, +/// `Retention::Regenerate`, `batch_round_one`/`batch_round_two`, cross-shard +/// byte table sharing, sparse activation, `BatchMessage`s, and positive PoW) +/// produces 100% byte-identical `BatchProof::to_bytes()` under lazy lookups and +/// disk spilling. +#[test] +fn streaming_and_spilled_batches_are_byte_identical() { + let work_rows = 8usize; + let inputs = multi_circuit_inputs(2, work_rows); + + // Build 3 shards whose work circuits ALL push into shard 0's byte table! + // Shards 1 and 2 deactivate the byte table (sparse preprocessed activation). + // Shard 2 also exercises a BatchMessage balance pair with the preamble. + let mut byte_counts = vec![0u32; 256]; + let mut shard_work_traces = Vec::new(); + let mut shard_claims: Vec>> = Vec::new(); + + let work_rows_u32 = u32::try_from(work_rows).unwrap(); + for shard in 0..3u32 { + let mut work_vals = Vec::with_capacity(work_rows * 6); + let mut claims = Vec::with_capacity(work_rows); + for r in 0..work_rows_u32 { + let a = shard * 20 + r; + let a_next = shard * 20 + ((r + 1) % work_rows_u32); + let b = (shard * 31 + r * 7 + 5) % 256; + let c = (shard * 47 + r * 11 + 19) % 256; + let d = (shard * 59 + r * 13 + 37) % 256; + let tag = r + 1; + let tag_next = ((r + 1) % work_rows_u32) + 1; + let sum = a + b + c + d + tag; + byte_counts[a as usize] += 1; + byte_counts[b as usize] += 1; + byte_counts[c as usize] += 1; + byte_counts[d as usize] += 1; + work_vals.extend_from_slice(&[f(a), f(b), f(c), f(d), f(sum), Val::ONE]); + claims.push(vec![f(30), f(tag), f(tag_next), f(sum), f(a_next)]); + } + shard_work_traces.push(RowMajorMatrix::new(work_vals, 6)); + shard_claims.push(claims); + } + + // Add one extra byte lookup pulled by shard 0's byte table and pushed by a + // batch message, plus a matching push/pull pair on channel 99. + byte_counts[77] += 1; + let batch_messages = vec![ + BatchMessage::push(vec![f(10), f(77)]), + BatchMessage::push(vec![f(99), f(1234)]), + BatchMessage::pull(vec![f(99), f(1234)]), + ]; + + let byte_trace_full = RowMajorMatrix::new(byte_counts.into_iter().map(f).collect(), 1); + let empty_byte = RowMajorMatrix::new(vec![], 1); + let empty_aux = RowMajorMatrix::new(vec![], 1); + let no_lookup_trace = RowMajorMatrix::new( + (0..4u32) + .flat_map(|v| [f(v + 1), f((v + 1) * (v + 1))]) + .collect(), + 2, + ); + + let shard_traces = |shard: usize| -> Vec> { + let bt = if shard == 0 { + byte_trace_full.clone() + } else { + empty_byte.clone() + }; + let nl = if shard == 1 { + RowMajorMatrix::new(vec![], 2) + } else { + no_lookup_trace.clone() + }; + vec![bt, empty_aux.clone(), shard_work_traces[shard].clone(), nl] + }; + + // Baseline in-memory materialized batch. + let batch_cap_height = if cfg!(feature = "cuda") { 0 } else { 1 }; + let cfg_base = make_config(2, batch_cap_height, 1, 3); + let (sys_base, key_base) = System::new(cfg_base, inputs.clone()); + let base_shards: Vec> = (0..3) + .map(|shard| ShardInput { + claims: shard_claims[shard].clone(), + witness: SystemWitness::from_stage_1(shard_traces(shard), &sys_base), + }) + .collect(); + let batch_base = sys_base.prove_batch(&key_base, base_shards, batch_messages.clone()); + sys_base + .verify_batch(&batch_base) + .expect("baseline batch must verify"); + let expected_bytes = batch_base.to_bytes().unwrap(); + + // Disk-spilled + lazy lookups under BOTH Retention::Retain and Retention::Regenerate. + let spill_dir = fresh_spill_dir("batch"); + let cfg_spilled = make_config(2, batch_cap_height, 1, 3).with_disk_spill(&spill_dir); + let (sys_spilled, key_spilled) = System::new_without_preprocessed(cfg_spilled, inputs.clone()); + + // Retention::Retain with SystemWitness::from_stage_1_lazy. + let lazy_shards: Vec> = (0..3) + .map(|shard| { + let wit = SystemWitness::from_stage_1_lazy(shard_traces(shard), &sys_spilled); + assert!(wit.lookups.iter().all(|l| !l.is_materialized())); + ShardInput { + claims: shard_claims[shard].clone(), + witness: wit, + } + }) + .collect(); + let batch_retain = sys_spilled.prove_batch(&key_spilled, lazy_shards, batch_messages.clone()); + sys_base + .verify_batch(&batch_retain) + .expect("baseline verifier must accept spilled Retain batch"); + assert_eq!(batch_retain.to_bytes().unwrap(), expected_bytes); + + // Retention::Regenerate with PreparedWitness::from_stage_1_lazy. + let mut builds = 0usize; + let batch_regen = sys_spilled.prove_batch_with( + &key_spilled, + &shard_claims, + batch_messages.clone(), + Retention::Regenerate, + |shard| { + builds += 1; + let sources = shard_traces(shard) + .into_iter() + .map(TraceSource::Host) + .collect(); + PreparedWitness::from_stage_1_lazy(sources, &sys_spilled) + }, + ); + assert_eq!(builds, 6, "3 shards × 2 rounds under Retention::Regenerate"); + assert_eq!(batch_regen.to_bytes().unwrap(), expected_bytes); + + // Explicit batch_round_one + batch_round_two with streaming iterator. + let barrier = sys_spilled.batch_round_one( + (0..3).map(|shard| { + let wit = SystemWitness::from_stage_1_lazy(shard_traces(shard), &sys_spilled); + (shard_claims[shard].clone(), wit) + }), + Retention::Regenerate, + ); + assert_eq!(barrier.shards(), 3); + let batch_two_step = + sys_spilled.batch_round_two(&key_spilled, barrier, batch_messages, |shard| { + SystemWitness::from_stage_1_lazy(shard_traces(shard), &sys_spilled) + }); + assert_eq!(batch_two_step.to_bytes().unwrap(), expected_bytes); + + // Round-trip decode & verify. + let decoded = BatchProof::::from_bytes(&expected_bytes).unwrap(); + sys_base.verify_batch(&decoded).unwrap(); + + #[cfg(not(feature = "cuda"))] + { + let prep_data = key_spilled.preprocessed_data.as_ref().unwrap(); + assert_eq!(prep_data.materialized_spilled_count(), 0); + } + + drop(key_spilled); + drop(sys_spilled); + #[cfg(not(feature = "cuda"))] + assert_eq!( + fs::read_dir(&spill_dir).unwrap().count(), + 0, + "batch spill_dir must contain zero leftover files after drop" + ); + let _ = fs::remove_dir_all(&spill_dir); +} + +#[cfg(not(feature = "cuda"))] +#[test] +fn spill_files_are_used_and_cleaned_up_on_drop_and_panic() { + use multi_stark::p3_adapter::spill::{active_spill_files, total_spilled_bytes}; + + let spill_dir = fresh_spill_dir("cleanup-panic"); + let bytes_before = total_spilled_bytes(); + + let inputs = multi_circuit_inputs(2, 16); + let (traces, claims_owned) = build_traces_and_claims(16, 11, false, true); + let claim_slices: Vec<&[Val]> = claims_owned.iter().map(Vec::as_slice).collect(); + + // Verify spill creation, non-zero spilled bytes, and cleanup on normal drop. + { + let cfg = make_config(2, 0, 1, 0).with_disk_spill(&spill_dir); + let (sys, key) = System::new_without_preprocessed(cfg, inputs.clone()); + let stage_1 = sys.prove_stage_1_streaming(traces.clone()); + assert!(active_spill_files() > 0, "spill files must be active"); + assert!( + total_spilled_bytes() > bytes_before, + "spilling must write LDE bytes to temporary files" + ); + let proof = sys.prove_committed(&key, &claim_slices, stage_1); + sys.verify_multiple_claims(&claim_slices, &proof).unwrap(); + } + assert_eq!( + fs::read_dir(&spill_dir).unwrap().count(), + 0, + "normal drop must leave zero files in spill_dir" + ); + + // Verify cleanup even when unwinding from a panic while ProverKey + Stage1 + // hold open spill files. + let panic_dir = fresh_spill_dir("panic-unwind"); + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let cfg = make_config(2, 0, 1, 0).with_disk_spill(&panic_dir); + let (sys, key) = System::new_without_preprocessed(cfg, inputs); + let stage_1 = sys.prove_stage_1_streaming(traces); + assert!(key.preprocessed_data.as_ref().unwrap().is_spilled()); + assert!(stage_1.stage_1_trace_data.is_spilled()); + panic!("simulated failure during proving"); + })); + assert!(panicked.is_err()); + assert_eq!( + fs::read_dir(&panic_dir).unwrap().count(), + 0, + "panic unwind must leave zero files in spill_dir" + ); + + // Verify `.without_disk_spill()` disables spilling cleanly. + let cfg_disabled = make_config(1, 0, 1, 0) + .with_disk_spill(&spill_dir) + .without_disk_spill(); + assert!(cfg_disabled.spill_dir().is_none()); + + let _ = fs::remove_dir_all(&spill_dir); + let _ = fs::remove_dir_all(&panic_dir); +} + +#[test] +#[should_panic(expected = "preprocessed trace height")] +fn lazy_witness_rejects_mismatched_preprocessed_height() { + let inputs = multi_circuit_inputs(1, 8); + let cfg = make_config(1, 0, 1, 0); + let (sys, _key) = System::new_without_preprocessed(cfg, inputs); + // Byte table expects height 256, supply height 16 instead. + let bad_traces = vec![ + RowMajorMatrix::new(vec![Val::ZERO; 16], 1), + RowMajorMatrix::new(vec![], 1), + RowMajorMatrix::new(vec![], 6), + RowMajorMatrix::new(vec![], 2), + ]; + let _ = SystemWitness::from_stage_1_lazy(bad_traces, &sys); +} + +#[test] +#[should_panic(expected = "cannot prove with every circuit deactivated")] +fn streaming_stage_1_rejects_all_empty_traces() { + let inputs = multi_circuit_inputs(1, 8); + let cfg = make_config(1, 0, 1, 0); + let (sys, _key) = System::new_without_preprocessed(cfg, inputs); + let empty_traces = vec![ + RowMajorMatrix::new(vec![], 1), + RowMajorMatrix::new(vec![], 1), + RowMajorMatrix::new(vec![], 6), + RowMajorMatrix::new(vec![], 2), + ]; + let _ = sys.prove_stage_1_streaming(empty_traces); +} + +/// Exercises multi-chunk stage-2 evaluation (`height = 8192 > chunk_rows = 4096`) +/// with next-row lookup wraparound crossing chunk boundaries (row 4095 -> 4096 +/// and row 8191 -> 0) and grouped lookups (`k = 2`), verifying 100% byte-identical +/// proofs across baseline, lazy in-memory, and disk-spilled paths. +#[test] +fn multi_chunk_stage_2_crosses_chunk_boundaries_byte_identically() { + let work_rows = 8192usize; + let work_rows_u32 = u32::try_from(work_rows).unwrap(); + let prep = RowMajorMatrix::new((0..work_rows_u32).map(|r| f(r + 1)).collect(), 1); + let a = Expr::main(0); + let a_next = Expr::main_next(0); + let b = Expr::main(1); + let tag = Expr::preprocessed(0); + let tag_next = Expr::preprocessed_next(0); + + // Self-canceling push/pull lookups per row that read BOTH current and next + // main & preprocessed rows, crossing the 4096-row stage-2 chunk boundary! + let circuit = CircuitInputs { + main_width: 2, + preprocessed: Some(prep), + constraints: vec![ + Expr::IsTransition * (a_next.clone() - (a.clone() + Expr::constant(Val::ONE))), + ], + ext_constraints: vec![], + lookups: vec![ + Lookup::push( + Expr::constant(Val::ONE), + vec![tag.clone(), a.clone(), b.clone()], + ), + Lookup::pull( + Expr::constant(Val::ONE), + vec![tag_next.clone(), a_next.clone(), b.clone()], + ), + Lookup::push(Expr::constant(Val::ONE), vec![tag_next, a_next, b.clone()]), + Lookup::pull(Expr::constant(Val::ONE), vec![tag, a, b]), + ], + lookup_group_size: 2, + }; + + let trace = RowMajorMatrix::new( + (0..work_rows_u32) + .flat_map(|r| [f(r + 10), f((r * 17 + 3) % 1000)]) + .collect(), + 2, + ); + let no_claims: &[&[Val]] = &[]; + + let (sys_base, key_base) = System::new(make_config(2, 0, 1, 0), [circuit.clone()]); + let wit_base = SystemWitness::from_stage_1(vec![trace.clone()], &sys_base); + let proof_base = sys_base.prove_multiple_claims(&key_base, no_claims, wit_base); + sys_base + .verify_multiple_claims(no_claims, &proof_base) + .unwrap(); + let expected_bytes = proof_base.to_bytes().unwrap(); + + let wit_lazy = SystemWitness::from_stage_1_lazy(vec![trace.clone()], &sys_base); + let proof_lazy = sys_base.prove_multiple_claims(&key_base, no_claims, wit_lazy); + assert_eq!(proof_lazy.to_bytes().unwrap(), expected_bytes); + + let spill_dir = fresh_spill_dir("multi-chunk"); + let (sys_spilled, key_spilled) = System::new_without_preprocessed( + make_config(2, 0, 1, 0).with_disk_spill(&spill_dir), + [circuit], + ); + let proof_spilled = + sys_spilled.prove_multiple_claims_streaming(&key_spilled, no_claims, [trace]); + assert_eq!(proof_spilled.to_bytes().unwrap(), expected_bytes); + #[cfg(not(feature = "cuda"))] + assert_eq!( + key_spilled + .preprocessed_data + .as_ref() + .unwrap() + .materialized_spilled_count(), + 0 + ); + drop(key_spilled); + drop(sys_spilled); + #[cfg(not(feature = "cuda"))] + assert_eq!(fs::read_dir(&spill_dir).unwrap().count(), 0); + let _ = fs::remove_dir_all(&spill_dir); +} From 5b4f87abece26c83749a82c212450f484d53dbca Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sat, 21 Nov 2026 09:22:54 -0500 Subject: [PATCH 15/28] S0-1: alloc-free chunked quotient_values, unused row skip, fused alpha fold, and zero-copy flatten_to_base --- src/eval.rs | 60 +++++++ src/graph.rs | 9 +- src/lookup.rs | 55 +++++-- src/p3_adapter/field.rs | 112 ++++++++++++- src/prover.rs | 339 +++++++++++++++++++++++++++------------- src/system.rs | 10 +- src/traits/field.rs | 38 ++++- 7 files changed, 487 insertions(+), 136 deletions(-) diff --git a/src/eval.rs b/src/eval.rs index 07777d7..de40b05 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -101,6 +101,66 @@ impl ConstraintGraph { self.zeros.iter().map(|z| buf[z.index()]).collect() } + /// Folds the user-constraint roots (`self.zeros`) with interleaved degree-2 + /// alpha-power pairs `[c0, c1]` directly off the sweep buffer, avoiding any + /// intermediate `constraint_values` allocation. + #[inline] + pub fn fold_constraints_d2>(&self, buf: &[W], alpha_pairs: &[[F; 2]]) -> (W, W) { + debug_assert!(alpha_pairs.len() >= self.zeros.len()); + let mut a0 = W::ZERO; + let mut a1 = W::ZERO; + let mut a2 = W::ZERO; + let mut a3 = W::ZERO; + let mut b0 = W::ZERO; + let mut b1 = W::ZERO; + let mut b2 = W::ZERO; + let mut b3 = W::ZERO; + + let (z_chunks, z_rem) = self.zeros.as_chunks::<4>(); + let (p_chunks, p_rem) = alpha_pairs[..self.zeros.len()].as_chunks::<4>(); + for (zc, pc) in z_chunks.iter().zip(p_chunks) { + let v0 = buf[zc[0].index()]; + let v1 = buf[zc[1].index()]; + let v2 = buf[zc[2].index()]; + let v3 = buf[zc[3].index()]; + a0 += v0 * pc[0][0]; + b0 += v0 * pc[0][1]; + a1 += v1 * pc[1][0]; + b1 += v1 * pc[1][1]; + a2 += v2 * pc[2][0]; + b2 += v2 * pc[2][1]; + a3 += v3 * pc[3][0]; + b3 += v3 * pc[3][1]; + } + let mut acc0 = (a0 + a1) + (a2 + a3); + let mut acc1 = (b0 + b1) + (b2 + b3); + for (z, p) in z_rem.iter().zip(p_rem) { + let v = buf[z.index()]; + acc0 += v * p[0]; + acc1 += v * p[1]; + } + (acc0, acc1) + } + + /// Folds the user-constraint roots (`self.zeros`) with decomposed alpha + /// powers into `acc` (one accumulator per basis coordinate), avoiding any + /// intermediate `constraint_values` allocation. + #[inline] + pub fn fold_constraints>( + &self, + buf: &[W], + decomposed_alpha_powers: &[Vec], + acc: &mut [W], + ) { + debug_assert_eq!(acc.len(), decomposed_alpha_powers.len()); + for (idx, z) in self.zeros.iter().enumerate() { + let v = buf[z.index()]; + for (slot, coeffs) in acc.iter_mut().zip(decomposed_alpha_powers) { + *slot += v * coeffs[idx]; + } + } + } + /// The concrete lookup values, read off a (prefix or full) sweep buffer. pub fn lookup_values(&self, buf: &[W]) -> Vec> { self.lookups diff --git a/src/graph.rs b/src/graph.rs index 5253bae..96df8df 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -15,7 +15,7 @@ use std::collections::HashMap; use crate::traits::Field; -use crate::expr::{CircuitSpec, ColRef, Expr, ExtExpr, Source}; +use crate::expr::{CircuitSpec, ColRef, Expr, ExtExpr, RowOffset, Source}; use crate::lookup::Lookup; /// Index of a node in the compiled vector. @@ -85,6 +85,13 @@ impl ConstraintGraph { .iter() .any(|node| matches!(node, Node::Var(col) if col.source == Source::Preprocessed)) } + + /// Returns `true` if any node in the graph reads a column from `source` at `offset`. + pub fn uses_row(&self, source: Source, offset: RowOffset) -> bool { + self.nodes.iter().any( + |node| matches!(node, Node::Var(col) if col.source == source && col.offset == offset), + ) + } } #[derive(Clone, PartialEq, Eq, Debug)] diff --git a/src/lookup.rs b/src/lookup.rs index ff9ee25..78a2a26 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -190,6 +190,39 @@ pub fn logup_constraint_values + Copy>( d: usize, group_size: usize, out: &mut Vec, +) { + for_each_logup_constraint_value( + lookups, + node_vals, + stage2, + stage2_next, + publics, + delta_scaled, + is_last_row, + w, + d, + group_size, + |val| out.push(val), + ); +} + +/// Evaluates the logUp constraint values in canonical protocol order and passes +/// each base-field constraint value directly to `emit`, allowing callers such +/// as `quotient_values` to fuse alpha-power accumulation with zero allocation. +#[inline] +#[allow(clippy::too_many_arguments)] +pub(crate) fn for_each_logup_constraint_value + Copy>( + lookups: &[Lookup], + node_vals: &[A], + stage2: &[A], + stage2_next: &[A], + publics: &[A], + delta_scaled: &[A], + is_last_row: A, + w: F, + d: usize, + group_size: usize, + mut emit: impl FnMut(A), ) { let group_size = group_size.max(1); debug_assert!(group_size <= MAX_LOOKUP_GROUP); @@ -198,7 +231,7 @@ pub fn logup_constraint_values + Copy>( if d == 1 { let injection = is_last_row * delta_scaled[0]; if lookups.is_empty() { - out.push(stage2_next[0] - stage2[0] + injection); + emit(stage2_next[0] - stage2[0] + injection); return; } let last_group = lookups.len().div_ceil(group_size) - 1; @@ -230,7 +263,7 @@ pub fn logup_constraint_values + Copy>( for (j, lookup) in chunk.iter().enumerate() { value -= prefix[j] * suffix[j + 1] * node_vals[lookup.multiplicity.index()]; } - out.push(value); + emit(value); } return; } @@ -250,8 +283,8 @@ pub fn logup_constraint_values + Copy>( if lookups.is_empty() { // Pass-through accumulator: acc′ − acc + is_last_row·Δ = 0. - out.push(stage2_next[0] - stage2[0] + inj.0); - out.push(stage2_next[1] - stage2[1] + inj.1); + emit(stage2_next[0] - stage2[0] + inj.0); + emit(stage2_next[1] - stage2[1] + inj.1); return; } @@ -282,8 +315,8 @@ pub fn logup_constraint_values + Copy>( // machinery on the default path. let c = mul2(msgs[0], (target.0 - source.0, target.1 - source.1), w); let mv = nv(chunk[0].multiplicity); - out.push(c.0 - mv); - out.push(c.1); + emit(c.0 - mv); + emit(c.1); continue; } @@ -317,8 +350,8 @@ pub fn logup_constraint_values + Copy>( rhs.0 += others.0 * mv; rhs.1 += others.1 * mv; } - out.push(c.0 - rhs.0); - out.push(c.1 - rhs.1); + emit(c.0 - rhs.0); + emit(c.1 - rhs.1); } return; } @@ -331,7 +364,7 @@ pub fn logup_constraint_values + Copy>( if lookups.is_empty() { for k in 0..d { - out.push(stage2_next[k] - stage2[k] + inj[k]); + emit(stage2_next[k] - stage2[k] + inj[k]); } return; } @@ -387,7 +420,9 @@ pub fn logup_constraint_values + Copy>( *c -= o * mv; } } - out.extend_from_slice(&constraint); + for c in constraint { + emit(c); + } } } diff --git a/src/p3_adapter/field.rs b/src/p3_adapter/field.rs index 9f99d55..2575c91 100644 --- a/src/p3_adapter/field.rs +++ b/src/p3_adapter/field.rs @@ -115,11 +115,67 @@ impl Packed for P3Packing { #[inline] fn packed_row_pair>(matrix: &M, i: usize, step: usize) -> Vec { - matrix - .vertically_packed_row_pair::<::Packing>(i, step) - .into_iter() - .map(Self) - .collect() + let width = matrix.width(); + let mut out = vec![Self::ZERO; 2 * width]; + Self::fill_packed_row(matrix, i, &mut out[..width]); + Self::fill_packed_row(matrix, i + step, &mut out[width..]); + out + } + + #[inline] + fn fill_packed_row>(matrix: &M, i: usize, out: &mut [Self]) { + let cols = out.len(); + debug_assert!(cols <= matrix.width()); + if cols == 0 { + return; + } + match Self::WIDTH { + 1 => fill_packed_row_fixed::(matrix, i, out), + 2 => fill_packed_row_fixed::(matrix, i, out), + 4 => fill_packed_row_fixed::(matrix, i, out), + 8 => fill_packed_row_fixed::(matrix, i, out), + 16 => fill_packed_row_fixed::(matrix, i, out), + 32 => fill_packed_row_fixed::(matrix, i, out), + _ => { + let rows = matrix.wrapping_row_slices(i, Self::WIDTH); + for (c, dst) in out.iter_mut().enumerate() { + *dst = Self(<::Packing as PackedValue>::from_fn(|lane| { + rows[lane][c] + })); + } + } + } + } +} + +#[inline] +fn fill_packed_row_fixed, const W: usize>( + matrix: &M, + i: usize, + out: &mut [P3Packing], +) { + debug_assert_eq!(W, P3Packing::::WIDTH); + let cols = out.len(); + let height = matrix.height(); + let mask = height.is_power_of_two().then_some(height - 1); + let rows = core::array::from_fn::<_, W, _>(|lane| { + let r = match mask { + Some(m) => (i + lane) & m, + None => (i + lane) % height, + }; + // SAFETY: `r < height` and `cols <= matrix.width()`. + unsafe { matrix.row_subslice_unchecked(r, 0, cols) } + }); + let slices: [&[F]; W] = core::array::from_fn(|lane| { + let slice: &[F] = &rows[lane]; + assert!(slice.len() >= cols); + slice + }); + for (c, dst) in out.iter_mut().enumerate() { + // SAFETY: `c < cols <= slices[lane].len()` for all `lane < W == WIDTH`. + *dst = P3Packing(<::Packing as PackedValue>::from_fn( + |lane| unsafe { *slices[lane].get_unchecked(c) }, + )); } } @@ -255,6 +311,11 @@ macro_rules! impl_extension_via_p3 { fn from_basis_coefficients_fn(f: impl FnMut(usize) -> $base) -> Self { <$ext as p3_field::BasedVectorSpace<$base>>::from_basis_coefficients_fn(f) } + + #[inline] + fn flatten_vec_to_base(values: Vec) -> Vec<$base> { + <$ext as p3_field::BasedVectorSpace<$base>>::flatten_to_base(values) + } } }; } @@ -279,3 +340,44 @@ impl crate::traits::PrimeField for p3_goldilocks::Goldilocks { Some(::ORDER_U64) } } + +#[cfg(test)] +mod tests { + use super::*; + use p3_goldilocks::Goldilocks; + use p3_matrix::dense::RowMajorMatrix; + + #[test] + fn fill_packed_row_matches_vertically_packed_row_pair() { + type P = P3Packing; + for (height, width) in [(1usize, 5usize), (4, 7), (7, 9), (16, 11)] { + let values: Vec = (0..height * width) + .map(|i| Goldilocks::new((i * 37 + 13) as u64)) + .collect(); + let mat = RowMajorMatrix::new(values, width); + for i in [0usize, 1, height / 2, height - 1] { + for step in [1usize, 2, height] { + let expected: Vec = mat + .vertically_packed_row_pair::<::Packing>(i, step) + .into_iter() + .flat_map(|p| p.as_slice().to_vec()) + .collect(); + let pair = P::packed_row_pair(&mat, i, step); + let got_pair: Vec = pair + .iter() + .flat_map(|p| p.as_slice().iter().copied()) + .collect(); + assert_eq!(got_pair, expected); + + // Verify prefix fill (`cols < width`) matches the first `cols` columns. + let prefix_cols = 2.min(width); + let mut prefix = vec![P::ZERO; prefix_cols]; + P::fill_packed_row(&mat, i + step, &mut prefix); + for (got, exp) in prefix.iter().zip(&pair[width..width + prefix_cols]) { + assert_eq!(got.as_slice(), exp.as_slice()); + } + } + } + } + } +} diff --git a/src/prover.rs b/src/prover.rs index eeeefbd..6e1f2b5 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -1034,7 +1034,9 @@ where let qdb = log2_strict_usize(quotient_domain.size()) - log2_strict_usize(trace_domain.size()); let next_step = 1 << qdb; - for _ in quotient_size..PackedVal::::WIDTH { + let width = PackedVal::::WIDTH; + let padded_len = quotient_size.next_multiple_of(width); + for _ in quotient_size..padded_len { sels.is_first_row.push(Val::::ZERO); sels.is_last_row.push(Val::::ZERO); sels.is_transition.push(Val::::ZERO); @@ -1042,18 +1044,31 @@ where } // α powers in reverse (constraint i of k weighted by α^{k-1-i}), - // decomposed per basis coordinate for the batched base-field fold. + // decomposed per basis coordinate for the fused base-field fold. + let ext_d = >>::D; let mut alpha_powers: Vec = alpha.powers().take(constraint_count).collect(); alpha_powers.reverse(); - let decomposed_alpha_powers: Vec>> = (0 - ..>>::D) - .map(|i| { - alpha_powers - .iter() - .map(|x| x.as_basis_coefficients_slice()[i]) - .collect() - }) - .collect(); + let alpha_table = if ext_d == 2 { + let pairs: Vec<[Val; 2]> = alpha_powers + .iter() + .map(|x| { + let coords = x.as_basis_coefficients_slice(); + [coords[0], coords[1]] + }) + .collect(); + AlphaTable::Degree2(pairs) + } else { + let decomposed: Vec>> = (0..ext_d) + .map(|i| { + alpha_powers + .iter() + .map(|x| x.as_basis_coefficients_slice()[i]) + .collect() + }) + .collect(); + AlphaTable::Generic(decomposed) + }; + drop(alpha_powers); // Public coordinates broadcast to packed base values. let publics_packed: Vec> = lookup_publics @@ -1063,7 +1078,6 @@ where // Δ/(n·g) per coordinate, broadcast: the logUp boundary injection with // the last-row selector's normalization constant pre-absorbed. - let ext_d = >>::D; let delta_scaled: Vec> = (0..ext_d) .map(|k| { PackedVal::::from( @@ -1073,63 +1087,127 @@ where .collect(); let ext_params = crate::system::extension_params::(); - let inner = |i_start: usize| { - quotient_values_inner::( - circuit, - &sels, - quotient_size, - preprocessed_on_quotient_domain, - stage_1_on_quotient_domain, - stage_2_on_quotient_domain, - main_width, - stage_2_width, - preprocessed_width, - &publics_packed, - &delta_scaled, - &decomposed_alpha_powers, - next_step, - i_start, - ext_params.w, - ext_params.degree, - ) + + // Determine once per circuit which row slices are actually referenced, + // skipping `next` (and any unused `current`) row gathers inside the hot loop. + let has_prep = preprocessed_on_quotient_domain.is_some(); + let prep_cur_len = if has_prep + && circuit.uses_row( + crate::expr::Source::Preprocessed, + crate::expr::RowOffset::Current, + ) { + preprocessed_width + } else { + 0 + }; + let prep_next_len = if has_prep + && circuit.uses_row( + crate::expr::Source::Preprocessed, + crate::expr::RowOffset::Next, + ) { + preprocessed_width + } else { + 0 }; - #[cfg(feature = "parallel")] + let main_cur_len = + if circuit.uses_row(crate::expr::Source::Main, crate::expr::RowOffset::Current) { + main_width + } else { + 0 + }; + let main_next_len = if circuit.uses_row(crate::expr::Source::Main, crate::expr::RowOffset::Next) { - (0..quotient_size) - .into_par_iter() - .step_by(PackedVal::::WIDTH) - .flat_map_iter(inner) - .collect() - } - #[cfg(not(feature = "parallel"))] + main_width + } else { + 0 + }; + let s2_next_len = if circuit.uses_row(crate::expr::Source::Stage2, crate::expr::RowOffset::Next) { - (0..quotient_size) - .step_by(PackedVal::::WIDTH) - .flat_map_iter(inner) - .collect() - } + stage_2_width + } else { + // `logup_constraint_values` only reads the wrap slot `stage_2_next[0..ext_d]`. + ext_d.min(stage_2_width) + }; + let node_count = circuit.graph.nodes.len(); + let accs_len = if ext_d == 2 { 0 } else { ext_d }; + + const PACKS_PER_CHUNK: usize = 16; + let chunk_rows = PACKS_PER_CHUNK * width; + let mut out = vec![>::ZERO; quotient_size]; + + out.par_chunks_mut(chunk_rows).enumerate().for_each_init( + || QuotientScratch { + prep_cur: vec![PackedVal::::ZERO; prep_cur_len], + prep_next: vec![PackedVal::::ZERO; prep_next_len], + main_cur: vec![PackedVal::::ZERO; main_cur_len], + main_next: vec![PackedVal::::ZERO; main_next_len], + s2_cur: vec![PackedVal::::ZERO; stage_2_width], + s2_next: vec![PackedVal::::ZERO; s2_next_len], + buf: Vec::with_capacity(node_count), + accs: vec![PackedVal::::ZERO; accs_len], + }, + |scratch, (chunk_idx, chunk_out)| { + let chunk_start = chunk_idx * chunk_rows; + for (pack_idx, pack_out) in chunk_out.chunks_mut(width).enumerate() { + let i_start = chunk_start + pack_idx * width; + eval_quotient_pack::( + circuit, + &sels, + preprocessed_on_quotient_domain, + stage_1_on_quotient_domain, + stage_2_on_quotient_domain, + &publics_packed, + &delta_scaled, + &alpha_table, + next_step, + i_start, + ext_params.w, + ext_params.degree, + constraint_count, + scratch, + pack_out, + ); + } + }, + ); + out +} + +enum AlphaTable { + Degree2(Vec<[F; 2]>), + Generic(Vec>), +} + +struct QuotientScratch

{ + prep_cur: Vec

, + prep_next: Vec

, + main_cur: Vec

, + main_next: Vec

, + s2_cur: Vec

, + s2_next: Vec

, + buf: Vec

, + accs: Vec

, } #[allow(clippy::too_many_arguments)] -fn quotient_values_inner( +#[inline] +fn eval_quotient_pack( circuit: &crate::system::Circuit>, sels: &LagrangeSelectors>>, - quotient_size: usize, preprocessed_on_quotient_domain: &Option>, stage_1_on_quotient_domain: &EvaluationsOnDomain<'_, SC>, stage_2_on_quotient_domain: &EvaluationsOnDomain<'_, SC>, - main_width: usize, - stage_2_width: usize, - preprocessed_width: usize, publics_packed: &[PackedVal], delta_scaled: &[PackedVal], - decomposed_alpha_powers: &[Vec>], + alpha_table: &AlphaTable>, next_step: usize, i_start: usize, ext_w: Val, ext_degree: usize, -) -> impl Iterator -where + constraint_count: usize, + scratch: &mut QuotientScratch>, + pack_out: &mut [SC::Challenge], +) where SC: ProofConfig, Val: TwoAdicField + Ord, { @@ -1139,72 +1217,111 @@ where let is_transition = *PackedVal::::from_slice(&sels.is_transition[i_range.clone()]); let inv_vanishing = *PackedVal::::from_slice(&sels.inv_vanishing[i_range]); - // Packed two-row windows of each trace, as base columns. - let preprocessed_pair: Option>> = preprocessed_on_quotient_domain - .as_ref() - .map(|m| PackedVal::::packed_row_pair(m, i_start, next_step)); - let stage_1_pair = - PackedVal::::packed_row_pair(stage_1_on_quotient_domain, i_start, next_step); - let stage_2_pair = - PackedVal::::packed_row_pair(stage_2_on_quotient_domain, i_start, next_step); - - let (stage_1_cur, stage_1_next) = stage_1_pair.split_at(main_width); - let (stage_2_cur, stage_2_next) = stage_2_pair.split_at(stage_2_width); - let (preprocessed_cur, preprocessed_next): (&[PackedVal], &[PackedVal]) = - match &preprocessed_pair { - Some(pair) => pair.split_at(preprocessed_width), - None => (&[], &[]), - }; + if let Some(prep) = preprocessed_on_quotient_domain.as_ref() { + if !scratch.prep_cur.is_empty() { + PackedVal::::fill_packed_row(prep, i_start, &mut scratch.prep_cur); + } + if !scratch.prep_next.is_empty() { + PackedVal::::fill_packed_row(prep, i_start + next_step, &mut scratch.prep_next); + } + } + if !scratch.main_cur.is_empty() { + PackedVal::::fill_packed_row( + stage_1_on_quotient_domain, + i_start, + &mut scratch.main_cur, + ); + } + if !scratch.main_next.is_empty() { + PackedVal::::fill_packed_row( + stage_1_on_quotient_domain, + i_start + next_step, + &mut scratch.main_next, + ); + } + PackedVal::::fill_packed_row(stage_2_on_quotient_domain, i_start, &mut scratch.s2_cur); + PackedVal::::fill_packed_row( + stage_2_on_quotient_domain, + i_start + next_step, + &mut scratch.s2_next, + ); let view = VarValues { - preprocessed: [preprocessed_cur, preprocessed_next], - main: [stage_1_cur, stage_1_next], - stage2: [stage_2_cur, stage_2_next], + preprocessed: [&scratch.prep_cur, &scratch.prep_next], + main: [&scratch.main_cur, &scratch.main_next], + stage2: [&scratch.s2_cur, &scratch.s2_next], publics: publics_packed, is_first_row, is_last_row, is_transition, }; - let mut buf = Vec::new(); - circuit.graph.sweep(&view, &mut buf); - let mut constraint_values = circuit.graph.constraint_values(&buf); - // The logUp constraint values are evaluated directly (they are not - // compiled into the graph), appended after the user roots in the - // canonical protocol order. Coordinate-expanded logUp constraints are - // base-field-only, so they evaluate in `PackedVal` like everything else; - // the lookup expressions are read straight out of the sweep buffer. - crate::lookup::logup_constraint_values( - &circuit.graph.lookups, - &buf, - stage_2_cur, - stage_2_next, - publics_packed, - delta_scaled, - // p3's (unnormalized) last-row selector; the normalization - // constant is pre-absorbed into `delta_scaled`. - is_last_row, - ext_w, - ext_degree, - circuit.lookup_group_size, - &mut constraint_values, - ); - debug_assert_eq!(constraint_values.len(), circuit.constraint_count()); + circuit.graph.sweep(&view, &mut scratch.buf); - // Fold the base constraint values with α through the decomposed path, - // reassembling one packed extension accumulator. - let accumulator = PackedChallenge::::from_basis_coefficients_fn(|coeff_idx| { - PackedVal::::batched_linear_combination( - &constraint_values, - &decomposed_alpha_powers[coeff_idx], - ) - }); - let quotient = accumulator * inv_vanishing; + // Fuse user-constraint and logUp-constraint α folding directly without + // allocating a per-pack `constraint_values` vector. + let accumulator = match alpha_table { + AlphaTable::Degree2(alpha_pairs) => { + let (mut acc0, mut acc1) = circuit.graph.fold_constraints_d2(&scratch.buf, alpha_pairs); + let mut idx = circuit.graph.zeros.len(); + crate::lookup::for_each_logup_constraint_value( + &circuit.graph.lookups, + &scratch.buf, + &scratch.s2_cur, + &scratch.s2_next, + publics_packed, + delta_scaled, + is_last_row, + ext_w, + ext_degree, + circuit.lookup_group_size, + |val| { + let pair = alpha_pairs[idx]; + acc0 += val * pair[0]; + acc1 += val * pair[1]; + idx += 1; + }, + ); + debug_assert_eq!(idx, constraint_count); + PackedChallenge::::from_basis_coefficients_fn(|coeff_idx| { + if coeff_idx == 0 { acc0 } else { acc1 } + }) + } + AlphaTable::Generic(decomposed_alpha_powers) => { + scratch.accs.fill(PackedVal::::ZERO); + circuit.graph.fold_constraints( + &scratch.buf, + decomposed_alpha_powers, + &mut scratch.accs, + ); + let mut idx = circuit.graph.zeros.len(); + crate::lookup::for_each_logup_constraint_value( + &circuit.graph.lookups, + &scratch.buf, + &scratch.s2_cur, + &scratch.s2_next, + publics_packed, + delta_scaled, + is_last_row, + ext_w, + ext_degree, + circuit.lookup_group_size, + |val| { + for (acc, coeffs) in scratch.accs.iter_mut().zip(decomposed_alpha_powers) { + *acc += val * coeffs[idx]; + } + idx += 1; + }, + ); + debug_assert_eq!(idx, constraint_count); + PackedChallenge::::from_basis_coefficients_fn(|coeff_idx| scratch.accs[coeff_idx]) + } + }; - (0..quotient_size.min(PackedVal::::WIDTH)).map(move |idx_in_packing| { - SC::Challenge::from_basis_coefficients_fn(|coeff_idx| { - PackedExtension::, SC::Challenge>::as_basis_coefficients_slice("ient) - [coeff_idx] - .as_slice()[idx_in_packing] - }) - }) + let quotient = accumulator * inv_vanishing; + let basis = PackedExtension::, SC::Challenge>::as_basis_coefficients_slice("ient); + for (idx_in_packing, slot) in pack_out.iter_mut().enumerate() { + *slot = SC::Challenge::from_basis_coefficients_fn(|coeff_idx| { + basis[coeff_idx].as_slice()[idx_in_packing] + }); + } } diff --git a/src/system.rs b/src/system.rs index 8fc7bff..a4cdce7 100644 --- a/src/system.rs +++ b/src/system.rs @@ -127,6 +127,11 @@ impl Circuit { pub fn quotient_degree(&self) -> usize { (self.max_constraint_degree().max(2) - 1).next_power_of_two() } + + /// Returns `true` if any compiled node reads a column from `source` at `offset`. + pub fn uses_row(&self, source: crate::expr::Source, offset: crate::expr::RowOffset) -> bool { + self.graph.uses_row(source, offset) + } } /// A multi-circuit STARK system over compiled constraint circuits. Contains @@ -150,9 +155,8 @@ pub struct ProverKey { impl System { pub fn opens_next_row(&self, circuit: usize, source: crate::expr::Source) -> bool { - !self.config.omit_unused_next_row_openings() || self.circuits[circuit].graph.nodes.iter().any(|node| { - matches!(node, crate::graph::Node::Var(col) if col.source == source && col.offset == crate::expr::RowOffset::Next) - }) + !self.config.omit_unused_next_row_openings() + || self.circuits[circuit].uses_row(source, crate::expr::RowOffset::Next) } /// Builds the system from per-circuit inputs. diff --git a/src/traits/field.rs b/src/traits/field.rs index 368aba4..6760441 100644 --- a/src/traits/field.rs +++ b/src/traits/field.rs @@ -160,6 +160,17 @@ pub trait Packed: Algebra { /// matrix, `WIDTH` vertically adjacent rows per packet — the sweep's /// input gather. Row indices wrap modulo the height. fn packed_row_pair>(matrix: &M, i: usize, step: usize) -> Vec; + + /// Fill `out` (`out.len() <= matrix.width()`) with the first `out.len()` + /// columns of vertically packed rows `i..i + WIDTH` (wrapping modulo + /// `matrix.height()`), reusing caller-owned scratch memory. + fn fill_packed_row>(matrix: &M, i: usize, out: &mut [Self]) { + if out.is_empty() { + return; + } + let pair = Self::packed_row_pair(matrix, i, 0); + out.copy_from_slice(&pair[..out.len()]); + } } /// The challenge field as a binomial extension `X^D = W` of the base @@ -175,6 +186,17 @@ pub trait ExtensionOf: Field + Algebra { fn as_basis_coefficients_slice(&self) -> &[F]; fn from_basis_coefficients_fn(f: impl FnMut(usize) -> F) -> Self; + + /// Flatten a vector of extension elements into contiguous base-field + /// basis coordinates. Extensions laid out as `[F; D]` override this to + /// reinterpret the backing allocation in place with zero copies. + fn flatten_vec_to_base(values: Vec) -> Vec { + let mut out = F::zero_vec(values.len() * Self::D); + out.par_chunks_exact_mut(Self::D) + .zip(values.par_iter()) + .for_each(|(dst, src)| dst.copy_from_slice(src.as_basis_coefficients_slice())); + out + } } /// Packed challenge values: `D` base packets, used to reassemble the @@ -192,10 +214,7 @@ pub fn flatten_to_base>( m: p3_matrix::dense::RowMajorMatrix, ) -> p3_matrix::dense::RowMajorMatrix { let width = m.width * EF::D; - let mut values = Vec::with_capacity(m.values.len() * EF::D); - for value in m.values { - values.extend_from_slice(value.as_basis_coefficients_slice()); - } + let values = EF::flatten_vec_to_base(m.values); p3_matrix::dense::RowMajorMatrix::new(values, width) } @@ -252,10 +271,17 @@ mod tests { }) }) .collect(); - let flat = flatten_to_base::(RowMajorMatrix::new(values.clone(), 3)); + let expected = values.clone(); + let original_ptr = values.as_ptr().cast::(); + let flat = flatten_to_base::(RowMajorMatrix::new(values, 3)); + assert_eq!( + flat.values.as_ptr(), + original_ptr, + "p3 binomial extension flatten_to_base must be zero-copy" + ); assert_eq!(flat.width, 6); assert_eq!(flat.values.len(), 12); - for (i, value) in values.iter().enumerate() { + for (i, value) in expected.iter().enumerate() { assert_eq!( &flat.values[2 * i..2 * i + 2], value.as_basis_coefficients_slice() From cc4f748855265669d4d767df3e0acbd71fbffda9 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sat, 21 Nov 2026 10:04:02 -0500 Subject: [PATCH 16/28] S0/S1-3: multi-buffer SIMD BLAKE3 Merkle, hash-before-spill, parallel norm-trick FRI open, and masked/parallel stage-2 lookup --- src/lookup.rs | 300 +++++- src/p3_adapter/blake3_simd.rs | 1715 +++++++++++++++++++++++++++++++++ src/p3_adapter/mod.rs | 2 + src/p3_adapter/spill.rs | 1021 +++++++++++++++----- src/types.rs | 44 +- tests/streaming_spill.rs | 61 +- 6 files changed, 2883 insertions(+), 260 deletions(-) create mode 100644 src/p3_adapter/blake3_simd.rs diff --git a/src/lookup.rs b/src/lookup.rs index 78a2a26..b7be228 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -46,7 +46,7 @@ //! stack. use crate::eval::VarValues; -use crate::traits::{Algebra, ExtensionOf, Field, batch_inverse}; +use crate::traits::{Algebra, ExtensionOf, Field}; use p3_matrix::{Matrix, dense::RowMajorMatrix}; use p3_maybe_rayon::prelude::*; @@ -598,6 +598,28 @@ where .fold(F::ZERO, |acc, coeff| acc * *r + coeff.into()) } +/// Fast Horner fingerprint for base-field coefficients into an extension field: +/// skips the vacuous `0 * r` multiply and uses scalar-by-extension scaling for +/// the leading term (3× fewer base muls on 2-arg byte-table lookups). +#[inline] +fn fingerprint_base>( + r: &EF, + coeffs: impl DoubleEndedIterator, +) -> EF { + let mut rev = coeffs.rev(); + let Some(last) = rev.next() else { + return >::ZERO; + }; + let Some(second) = rev.next() else { + return EF::from(last); + }; + let mut acc = *r * last + EF::from(second); + for coeff in rev { + acc = acc * *r + EF::from(coeff); + } + acc +} + pub(crate) fn try_claims_accumulator>( beta: EF, gamma: &EF, @@ -784,24 +806,33 @@ impl LookupValues { let mut vec = vec![zero; self.height * num_slots]; let mut running = zero; + let one = >::ONE; for row_start in (0..self.height).step_by(chunk_rows) { let n_rows = (self.height - row_start).min(chunk_rows); let num_chunk_messages = n_rows * self.num_lookups; - let messages: Vec = (0..num_chunk_messages) - .into_par_iter() - .map(|idx| { - let local_row = idx / self.num_lookups; - let lookup = idx % self.num_lookups; - let args = self.args_at(row_start + local_row, lookup); - lookup_challenge + fingerprint(fingerprint_challenge, args.iter().copied()) - }) - .collect(); - let inverses = batch_inverse(&messages); + let chunk_mults = &self.multiplicities + [row_start * self.num_lookups..(row_start + n_rows) * self.num_lookups]; + let mut messages = vec![one; num_chunk_messages]; + messages + .par_chunks_exact_mut(self.num_lookups) + .zip(chunk_mults.par_chunks_exact(self.num_lookups)) + .enumerate() + .for_each(|(local_row, (row_msgs, row_mults))| { + let row = row_start + local_row; + for (lookup, (msg_slot, &mult)) in + row_msgs.iter_mut().zip(row_mults).enumerate() + { + if !mult.is_zero() { + let args = self.args_at(row, lookup); + *msg_slot = lookup_challenge + + fingerprint_base(fingerprint_challenge, args.iter().copied()); + } + } + }); + let inverses = batch_inverse_masked(&messages, chunk_mults); drop(messages); let chunk_out = &mut vec[row_start * num_slots..(row_start + n_rows) * num_slots]; - let chunk_mults = &self.multiplicities - [row_start * self.num_lookups..(row_start + n_rows) * self.num_lookups]; chunk_out .par_chunks_exact_mut(num_slots) .zip(chunk_mults.par_chunks_exact(self.num_lookups)) @@ -815,19 +846,23 @@ impl LookupValues { let mut delta = zero; for (&multiplicity, &message_inverse) in group_mults.iter().zip(group_invs) { - delta += EF::from(multiplicity) * message_inverse; + if !multiplicity.is_zero() { + if multiplicity == F::ONE { + delta += message_inverse; + } else if multiplicity == F::NEG_ONE { + delta -= message_inverse; + } else { + delta += message_inverse * multiplicity; + } + } } *slot_out = delta; } }); drop(inverses); - // Exclusive prefix scan over this chunk's group deltas. - for cell in chunk_out.iter_mut() { - let delta = *cell; - *cell = running; - running += delta; - } + // Parallel exclusive prefix scan over this chunk's group deltas. + running = parallel_exclusive_prefix_scan::(chunk_out, running); } (RowMajorMatrix::new(vec, num_slots), running) @@ -861,6 +896,130 @@ impl LookupValues { } } +/// Batch inversion restricted to entries where `multiplicities[i] != 0`. +/// Entries with zero multiplicity are skipped during both Montgomery passes +/// (saving 3 extension multiplications per padding/inactive lookup) and their +/// output slots are left at zero (never read by the masked delta accumulator). +/// Uses 4 independent interleaved Montgomery chains per chunk to hide +/// extension-field multiplication latency. +fn batch_inverse_masked>( + messages: &[EF], + multiplicities: &[F], +) -> Vec { + debug_assert_eq!(messages.len(), multiplicities.len()); + const CHUNK: usize = 1 << 10; + let zero = >::ZERO; + let one = >::ONE; + let mut out = vec![zero; messages.len()]; + out.par_chunks_mut(CHUNK) + .zip(messages.par_chunks(CHUNK)) + .zip(multiplicities.par_chunks(CHUNK)) + .for_each(|((out_chunk, msg_chunk), mult_chunk)| { + let (m_chunks, m_rem) = msg_chunk.as_chunks::<4>(); + let (mu_chunks, mu_rem) = mult_chunk.as_chunks::<4>(); + let (o_chunks, o_rem) = out_chunk.as_chunks_mut::<4>(); + + let mut acc = [one; 4]; + for ((oc, mc), muc) in o_chunks.iter_mut().zip(m_chunks).zip(mu_chunks) { + for k in 0..4 { + if !muc[k].is_zero() { + oc[k] = acc[k]; + acc[k] *= mc[k]; + } + } + } + for ((slot, &v), &m) in o_rem.iter_mut().zip(m_rem).zip(mu_rem) { + if !m.is_zero() { + *slot = acc[0]; + acc[0] *= v; + } + } + + let p01 = acc[0] * acc[1]; + let p23 = acc[2] * acc[3]; + let total = p01 * p23; + assert!(!total.is_zero(), "batch_inverse: zero input"); + let inv_total = total.inverse(); + let inv01 = p23 * inv_total; + let inv23 = p01 * inv_total; + let mut inv = [ + acc[1] * inv01, + acc[0] * inv01, + acc[3] * inv23, + acc[2] * inv23, + ]; + + for i in (0..m_rem.len()).rev() { + if !mu_rem[i].is_zero() { + o_rem[i] *= inv[0]; + inv[0] *= m_rem[i]; + } + } + for ((oc, mc), muc) in o_chunks.iter_mut().zip(m_chunks).zip(mu_chunks).rev() { + for k in 0..4 { + if !muc[k].is_zero() { + oc[k] *= inv[k]; + inv[k] *= mc[k]; + } + } + } + }); + out +} + +/// In-place exclusive prefix scan over `slice` starting from `running`, +/// returning the updated running total. Parallelized in two block passes +/// for large chunks. +fn parallel_exclusive_prefix_scan>( + slice: &mut [EF], + running: EF, +) -> EF { + const MIN_PARALLEL_LEN: usize = 1 << 13; + const BLOCK_LEN: usize = 1 << 12; + if slice.len() < MIN_PARALLEL_LEN { + let mut acc = running; + for cell in slice.iter_mut() { + let delta = *cell; + *cell = acc; + acc += delta; + } + return acc; + } + + let zero = >::ZERO; + let block_sums: Vec = slice + .par_chunks(BLOCK_LEN) + .map(|block| { + let mut sum = zero; + for &v in block { + sum += v; + } + sum + }) + .collect(); + + let mut block_offsets = Vec::with_capacity(block_sums.len()); + let mut acc = running; + for sum in block_sums { + block_offsets.push(acc); + acc += sum; + } + + slice + .par_chunks_mut(BLOCK_LEN) + .zip(block_offsets.par_iter()) + .for_each(|(block, &offset)| { + let mut local = offset; + for cell in block.iter_mut() { + let delta = *cell; + *cell = local; + local += delta; + } + }); + + acc +} + /// Target number of lookup messages per chunk (~8 MiB at 16 bytes/EF). const STAGE_2_TARGET_CHUNK_MESSAGES: usize = 1 << 19; @@ -991,8 +1150,9 @@ where None }; + let one = >::ONE; let mut multiplicities = F::zero_vec(n_rows * num_lookups); - let mut messages = vec![zero; n_rows * num_lookups]; + let mut messages = vec![one; n_rows * num_lookups]; multiplicities .par_chunks_exact_mut(num_lookups) @@ -1016,18 +1176,23 @@ where }; circuit.graph.sweep_lookup_prefix(&view, buf); for (slot, lookup) in circuit.graph.lookups.iter().enumerate() { - row_mults[slot] = buf[lookup.multiplicity.index()]; - let fp = fingerprint( - fingerprint_challenge, - lookup.args.iter().map(|arg| buf[arg.index()]), - ); - row_msgs[slot] = lookup_challenge + fp; + let mult = buf[lookup.multiplicity.index()]; + row_mults[slot] = mult; + if mult.is_zero() { + row_msgs[slot] = one; + } else { + let fp = fingerprint_base( + fingerprint_challenge, + lookup.args.iter().map(|arg| buf[arg.index()]), + ); + row_msgs[slot] = lookup_challenge + fp; + } } }); drop(main_chunk); drop(prep_chunk); - let inverses = batch_inverse(&messages); + let inverses = batch_inverse_masked(&messages, &multiplicities); drop(messages); let chunk_out = &mut vec[row_start * num_slots..(row_start + n_rows) * num_slots]; @@ -1043,7 +1208,15 @@ where ) { let mut delta = zero; for (&multiplicity, &message_inverse) in group_mults.iter().zip(group_invs) { - delta += EF::from(multiplicity) * message_inverse; + if !multiplicity.is_zero() { + if multiplicity == F::ONE { + delta += message_inverse; + } else if multiplicity == F::NEG_ONE { + delta -= message_inverse; + } else { + delta += message_inverse * multiplicity; + } + } } *slot_out = delta; } @@ -1051,11 +1224,7 @@ where drop(multiplicities); drop(inverses); - for cell in chunk_out.iter_mut() { - let delta = *cell; - *cell = running; - running += delta; - } + running = parallel_exclusive_prefix_scan::(chunk_out, running); } (RowMajorMatrix::new(vec, num_slots), running) @@ -1122,7 +1291,7 @@ impl LookupValues { ) }) .collect::>(); - let inverses = batch_inverse(&messages); + let inverses = crate::traits::batch_inverse(&messages); drop(messages); (0..(rows.end - rows.start) * slots) .into_par_iter() @@ -1820,4 +1989,65 @@ mod tests { let result = system.verify_multiple_claims(split_claims, &proof); assert!(result.is_err()); } + + #[test] + fn parallel_prefix_scan_and_masked_batch_inverse_match_serial() { + use crate::types::ExtVal; + + let f = Val::from_u64; + let ef = |a: u64, b: u64| ExtVal::new([f(a), f(b)]); + + for len in [0usize, 1, 17, 4096, 8192, 20_000] { + let input: Vec = (0..len) + .map(|i| ef((i as u64) * 37 + 5, (i as u64) * 19 + 11)) + .collect(); + let init = ef(1234, 5678); + + let mut expected = input.clone(); + let mut exp_total = init; + for cell in &mut expected { + let d = *cell; + *cell = exp_total; + exp_total += d; + } + + let mut got = input; + let got_total = parallel_exclusive_prefix_scan::(&mut got, init); + assert_eq!(got, expected, "prefix scan mismatch at len={len}"); + assert_eq!(got_total, exp_total, "prefix total mismatch at len={len}"); + } + + // Masked batch inverse with zero multiplicities and even zero-valued skipped messages. + let n = 9000usize; + let mults: Vec = (0..n) + .map(|i| { + if i % 3 == 0 { + Val::ZERO + } else if i % 3 == 1 { + Val::ONE + } else { + f(u64::try_from(i).unwrap() + 2) + } + }) + .collect(); + let msgs: Vec = (0..n) + .map(|i| { + if mults[i].is_zero() { + // Even a zero dummy must be safely skipped when multiplicity is zero. + >::ZERO + } else { + ef( + u64::try_from(i).unwrap() * 13 + 7, + u64::try_from(i).unwrap() * 5 + 3, + ) + } + }) + .collect(); + let invs = batch_inverse_masked::(&msgs, &mults); + for i in 0..n { + if !mults[i].is_zero() { + assert_eq!(msgs[i] * invs[i], >::ONE); + } + } + } } diff --git a/src/p3_adapter/blake3_simd.rs b/src/p3_adapter/blake3_simd.rs new file mode 100644 index 0000000..80fc295 --- /dev/null +++ b/src/p3_adapter/blake3_simd.rs @@ -0,0 +1,1715 @@ +//! Multi-buffer SIMD BLAKE3 hashing for CPU Merkle trees. +//! +//! Plonky3's `MerkleTreeMmcs` with `SerializingHasher` and +//! `CompressionFunctionFromHasher` hashes one row and compresses +//! one 64-byte internal node pair at a time. Because BLAKE3's built-in SIMD +//! only parallelizes *across 1 KiB chunks of a single message*, single-block +//! internal compressions (64 bytes) and small-to-medium leaf rows (≤ 16 KiB) +//! run completely scalar. +//! +//! This module implements 16-way AVX-512 (`avx512f`) and 8-way AVX2 (`avx2`) +//! multi-buffer BLAKE3 kernels with runtime CPU feature detection and a clean +//! scalar fallback, producing digests 100% bit-for-bit identical to +//! `p3_blake3::Blake3`. + +use core::mem::MaybeUninit; + +use p3_blake3::Blake3; +use p3_field::PrimeField64; +use p3_matrix::Matrix; +use p3_maybe_rayon::prelude::*; +use p3_symmetric::CryptographicHasher; + +use crate::types::Val; + +const BLOCK_LEN: usize = 64; +const CHUNK_LEN: usize = 1024; +/// Maximum row byte length handled by the multi-buffer SIMD path (16 chunks = 16 KiB). +/// Beyond 16 KiB, `blake3::Hasher` already saturates 16-chunk AVX-512 within each single row. +const MAX_MULTIBUF_ROW_BYTES: usize = 16 * CHUNK_LEN; + +const CHUNK_START: u32 = 1 << 0; +const CHUNK_END: u32 = 1 << 1; +const PARENT: u32 = 1 << 2; +const ROOT: u32 = 1 << 3; + +const IV: [u32; 8] = [ + 0x6A09_E667, + 0xBB67_AE85, + 0x3C6E_F372, + 0xA54F_F53A, + 0x510E_527F, + 0x9B05_688C, + 0x1F83_D9AB, + 0x5BE0_CD19, +]; + +const MSG_SCHEDULE: [[usize; 16]; 7] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8], + [3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1], + [10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6], + [12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4], + [9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7], + [11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13], +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SimdBackend { + #[cfg(target_arch = "x86_64")] + Avx512, + #[cfg(target_arch = "x86_64")] + Avx2, + Scalar, +} + +#[inline] +fn detect_backend() -> SimdBackend { + #[cfg(target_arch = "x86_64")] + { + if std::arch::is_x86_feature_detected!("avx512f") { + return SimdBackend::Avx512; + } + if std::arch::is_x86_feature_detected!("avx2") { + return SimdBackend::Avx2; + } + } + SimdBackend::Scalar +} + +#[inline] +fn compress_pair_scalar(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] { + let mut block = [0u8; 64]; + block[..32].copy_from_slice(left); + block[32..].copy_from_slice(right); + compress_64_root_scalar(&block) +} + +#[inline] +fn compress_64_root_scalar(block: &[u8; 64]) -> [u8; 32] { + let mut msg = [0u32; 16]; + let (chunks, _) = block.as_chunks::<4>(); + for (w, &bytes) in msg.iter_mut().zip(chunks) { + *w = u32::from_le_bytes(bytes); + } + let mut state = [ + IV[0], + IV[1], + IV[2], + IV[3], + IV[4], + IV[5], + IV[6], + IV[7], + IV[0], + IV[1], + IV[2], + IV[3], + 0, + 0, + 64, + CHUNK_START | CHUNK_END | ROOT, + ]; + for schedule in &MSG_SCHEDULE { + g_scalar(&mut state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]); + g_scalar(&mut state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]); + g_scalar(&mut state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]); + g_scalar(&mut state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]); + g_scalar(&mut state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]); + g_scalar( + &mut state, + 1, + 6, + 11, + 12, + msg[schedule[10]], + msg[schedule[11]], + ); + g_scalar( + &mut state, + 2, + 7, + 8, + 13, + msg[schedule[12]], + msg[schedule[13]], + ); + g_scalar( + &mut state, + 3, + 4, + 9, + 14, + msg[schedule[14]], + msg[schedule[15]], + ); + } + let mut out = [0u8; 32]; + for i in 0..8 { + out[4 * i..4 * i + 4].copy_from_slice(&(state[i] ^ state[i + 8]).to_le_bytes()); + } + out +} + +#[inline(always)] +fn g_scalar(state: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize, x: u32, y: u32) { + state[a] = state[a].wrapping_add(state[b]).wrapping_add(x); + state[d] = (state[d] ^ state[a]).rotate_right(16); + state[c] = state[c].wrapping_add(state[d]); + state[b] = (state[b] ^ state[c]).rotate_right(12); + state[a] = state[a].wrapping_add(state[b]).wrapping_add(y); + state[d] = (state[d] ^ state[a]).rotate_right(8); + state[c] = state[c].wrapping_add(state[d]); + state[b] = (state[b] ^ state[c]).rotate_right(7); +} + +/// Allocates a `Vec<[u8; 32]>` of length `padded`, initializes `0..active` via +/// `fill` (without any upfront single-threaded zero-fill), zero-fills the +/// padding tail `active..padded`, and returns the initialized `Vec`. +/// +/// # Safety +/// `fill` MUST initialize every element of the `&mut [MaybeUninit<[u8; 32]>]` +/// slice it receives before returning. +pub(crate) unsafe fn alloc_and_fill_digests( + padded: usize, + active: usize, + fill: impl FnOnce(&mut [MaybeUninit<[u8; 32]>]), +) -> Vec<[u8; 32]> { + debug_assert!(active <= padded); + let mut vec: Vec<[u8; 32]> = Vec::with_capacity(padded); + let spare = &mut vec.spare_capacity_mut()[..padded]; + fill(&mut spare[..active]); + for slot in &mut spare[active..padded] { + slot.write([0u8; 32]); + } + // SAFETY: Caller guarantees `fill` initialized every element of + // `spare[..active]`, and the loop above initialized `spare[active..padded]`. + unsafe { + vec.set_len(padded); + } + vec +} + +#[inline] +fn compress_pairs_slice( + prev_layer: &[[u8; 32]], + out: &mut [MaybeUninit<[u8; 32]>], + backend: SimdBackend, +) { + debug_assert!(prev_layer.len() >= 2 * out.len()); + let mut i = 0; + #[cfg(target_arch = "x86_64")] + { + if backend == SimdBackend::Avx512 { + while i + 16 <= out.len() { + // SAFETY: `avx512f` detected at runtime; `out[i..i+16]` has 16 writable slots. + unsafe { + avx512::compress_16_pairs( + &prev_layer[2 * i..2 * i + 32], + out[i..].as_mut_ptr().cast(), + ); + } + i += 16; + } + if i + 8 <= out.len() { + // SAFETY: `avx512f` implies `avx2`; `out[i..i+8]` has 8 writable slots. + unsafe { + avx2::compress_8_pairs( + &prev_layer[2 * i..2 * i + 16], + out[i..].as_mut_ptr().cast(), + ); + } + i += 8; + } + } else if backend == SimdBackend::Avx2 { + while i + 8 <= out.len() { + // SAFETY: `avx2` detected at runtime; `out[i..i+8]` has 8 writable slots. + unsafe { + avx2::compress_8_pairs( + &prev_layer[2 * i..2 * i + 16], + out[i..].as_mut_ptr().cast(), + ); + } + i += 8; + } + } + } + let _ = backend; + while i < out.len() { + out[i].write(compress_pair_scalar( + &prev_layer[2 * i], + &prev_layer[2 * i + 1], + )); + i += 1; + } +} + +/// Compresses `out.len()` adjacent 32-byte digest pairs from `prev_layer` +/// (`out[i] = BLAKE3(prev_layer[2*i] || prev_layer[2*i + 1])`) in parallel +/// using multi-buffer SIMD BLAKE3. +pub(crate) fn compress_pairs_uninit(prev_layer: &[[u8; 32]], out: &mut [MaybeUninit<[u8; 32]>]) { + assert!(prev_layer.len() >= 2 * out.len()); + if out.is_empty() { + return; + } + let backend = detect_backend(); + const PAR_THRESHOLD: usize = 128; + const CHUNK_PAIRS: usize = 128; + if out.len() < PAR_THRESHOLD { + compress_pairs_slice(prev_layer, out, backend); + } else { + out.par_chunks_mut(CHUNK_PAIRS) + .enumerate() + .for_each(|(chunk_idx, dst)| { + let start = chunk_idx * CHUNK_PAIRS; + compress_pairs_slice(&prev_layer[2 * start..], dst, backend); + }); + } +} + +#[inline] +fn compress_and_inject_slice( + prev_layer: &[[u8; 32]], + rows_digests: &[[u8; 32]], + out: &mut [MaybeUninit<[u8; 32]>], + backend: SimdBackend, +) { + debug_assert_eq!(rows_digests.len(), out.len()); + debug_assert!(prev_layer.len() >= 2 * out.len()); + let mut i = 0; + #[cfg(target_arch = "x86_64")] + { + if backend == SimdBackend::Avx512 { + while i + 16 <= out.len() { + // SAFETY: `avx512f` detected at runtime; `out[i..i+16]` has 16 writable slots. + unsafe { + avx512::compress_16_pairs_and_inject( + &prev_layer[2 * i..2 * i + 32], + (&rows_digests[i..i + 16]).try_into().unwrap(), + out[i..].as_mut_ptr().cast(), + ); + } + i += 16; + } + if i + 8 <= out.len() { + // SAFETY: `avx512f` implies `avx2`; `out[i..i+8]` has 8 writable slots. + unsafe { + avx2::compress_8_pairs_and_inject( + &prev_layer[2 * i..2 * i + 16], + (&rows_digests[i..i + 8]).try_into().unwrap(), + out[i..].as_mut_ptr().cast(), + ); + } + i += 8; + } + } else if backend == SimdBackend::Avx2 { + while i + 8 <= out.len() { + // SAFETY: `avx2` detected at runtime; `out[i..i+8]` has 8 writable slots. + unsafe { + avx2::compress_8_pairs_and_inject( + &prev_layer[2 * i..2 * i + 16], + (&rows_digests[i..i + 8]).try_into().unwrap(), + out[i..].as_mut_ptr().cast(), + ); + } + i += 8; + } + } + } + let _ = backend; + while i < out.len() { + let parent = compress_pair_scalar(&prev_layer[2 * i], &prev_layer[2 * i + 1]); + out[i].write(compress_pair_scalar(&parent, &rows_digests[i])); + i += 1; + } +} + +/// Fused binary compress + leaf-digest injection into uninitialized output: +/// `out[i] = BLAKE3(BLAKE3(prev_layer[2*i] || prev_layer[2*i + 1]) || rows_digests[i])`. +pub(crate) fn compress_and_inject_from_digests_uninit( + prev_layer: &[[u8; 32]], + rows_digests: &[[u8; 32]], + out: &mut [MaybeUninit<[u8; 32]>], +) { + assert_eq!(rows_digests.len(), out.len()); + assert!(prev_layer.len() >= 2 * out.len()); + if out.is_empty() { + return; + } + let backend = detect_backend(); + const PAR_THRESHOLD: usize = 128; + const CHUNK_PAIRS: usize = 256; + if out.len() < PAR_THRESHOLD { + compress_and_inject_slice(prev_layer, rows_digests, out, backend); + } else { + out.par_chunks_mut(CHUNK_PAIRS) + .zip(rows_digests.par_chunks(CHUNK_PAIRS)) + .enumerate() + .for_each(|(chunk_idx, (dst, row_chunk))| { + let start = chunk_idx * CHUNK_PAIRS; + compress_and_inject_slice(&prev_layer[2 * start..], row_chunk, dst, backend); + }); + } +} + +#[inline] +fn hash_raw_rows_slice( + raw: &[u8], + row_bytes: usize, + out: &mut [MaybeUninit<[u8; 32]>], + backend: SimdBackend, +) { + debug_assert_eq!(raw.len(), out.len() * row_bytes); + if out.is_empty() { + return; + } + let mut i = 0; + #[cfg(target_arch = "x86_64")] + { + if row_bytes <= MAX_MULTIBUF_ROW_BYTES { + if backend == SimdBackend::Avx512 { + while i + 16 <= out.len() { + let ptrs: [*const u8; 16] = + core::array::from_fn(|lane| raw[(i + lane) * row_bytes..].as_ptr()); + // SAFETY: `avx512f` detected at runtime; each pointer has `row_bytes` readable bytes + // and `out[i..i+16]` has 16 writable slots. + unsafe { + avx512::hash_16_fixed_len(&ptrs, row_bytes, out[i..].as_mut_ptr().cast()); + } + i += 16; + } + if i + 8 <= out.len() { + let ptrs: [*const u8; 8] = + core::array::from_fn(|lane| raw[(i + lane) * row_bytes..].as_ptr()); + // SAFETY: `avx512f` implies `avx2`; each pointer has `row_bytes` readable bytes. + unsafe { + avx2::hash_8_fixed_len(&ptrs, row_bytes, out[i..].as_mut_ptr().cast()); + } + i += 8; + } + } else if backend == SimdBackend::Avx2 { + while i + 8 <= out.len() { + let ptrs: [*const u8; 8] = + core::array::from_fn(|lane| raw[(i + lane) * row_bytes..].as_ptr()); + // SAFETY: `avx2` detected at runtime; each pointer has `row_bytes` readable bytes. + unsafe { + avx2::hash_8_fixed_len(&ptrs, row_bytes, out[i..].as_mut_ptr().cast()); + } + i += 8; + } + } + } + } + let _ = backend; + let hasher = Blake3; + while i < out.len() { + out[i].write(hasher.hash_slice(&raw[i * row_bytes..(i + 1) * row_bytes])); + i += 1; + } +} + +/// Hashes `out.len()` contiguous fixed-length rows of `row_bytes` bytes each +/// directly into uninitialized digest slots. +pub(crate) fn hash_raw_rows_uninit( + raw: &[u8], + row_bytes: usize, + out: &mut [MaybeUninit<[u8; 32]>], +) { + assert_eq!(raw.len(), out.len() * row_bytes); + if out.is_empty() { + return; + } + let backend = detect_backend(); + if row_bytes > MAX_MULTIBUF_ROW_BYTES { + let hasher = Blake3; + out.par_iter_mut().enumerate().for_each(|(row, digest)| { + digest.write(hasher.hash_slice(&raw[row * row_bytes..(row + 1) * row_bytes])); + }); + return; + } + let chunk_rows = (65_536 / row_bytes.max(64)) + .clamp(16, 256) + .next_multiple_of(16); + if out.len() <= chunk_rows { + hash_raw_rows_slice(raw, row_bytes, out, backend); + } else { + out.par_chunks_mut(chunk_rows) + .enumerate() + .for_each(|(chunk_idx, dst)| { + let start = chunk_idx * chunk_rows; + let byte_start = start * row_bytes; + let byte_end = (start + dst.len()) * row_bytes; + hash_raw_rows_slice(&raw[byte_start..byte_end], row_bytes, dst, backend); + }); + } +} + +/// Hashes `out.len()` rows formed by concatenating the corresponding row slices +/// across `blocks` (each `(raw_bytes, row_bytes)`). +pub(crate) fn hash_raw_multi_rows_uninit( + blocks: &[(Vec, usize)], + out: &mut [MaybeUninit<[u8; 32]>], +) { + if out.is_empty() { + return; + } + if let [(buf, row_bytes)] = blocks { + hash_raw_rows_uninit(buf, *row_bytes, out); + return; + } + let total_row_bytes: usize = blocks.iter().map(|(_, rb)| *rb).sum(); + if total_row_bytes > MAX_MULTIBUF_ROW_BYTES { + let hasher = Blake3; + out.par_iter_mut() + .enumerate() + .for_each(|(local_row, digest)| { + digest.write( + hasher.hash_iter_slices( + blocks + .iter() + .map(|(buf, rb)| &buf[local_row * *rb..(local_row + 1) * *rb]), + ), + ); + }); + return; + } + let backend = detect_backend(); + let batch = match backend { + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx512 => 16usize, + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx2 => 8usize, + SimdBackend::Scalar => 1usize, + }; + if batch == 1 { + let hasher = Blake3; + out.par_iter_mut() + .enumerate() + .for_each(|(local_row, digest)| { + digest.write( + hasher.hash_iter_slices( + blocks + .iter() + .map(|(buf, rb)| &buf[local_row * *rb..(local_row + 1) * *rb]), + ), + ); + }); + return; + } + let chunk_rows = (65_536 / total_row_bytes.max(64)) + .clamp(batch, 256) + .next_multiple_of(batch); + out.par_chunks_mut(chunk_rows).enumerate().for_each_init( + || vec![0u8; batch * total_row_bytes], + |scratch, (chunk_idx, dst)| { + let chunk_start = chunk_idx * chunk_rows; + let mut offset = 0; + while offset < dst.len() { + let take = (dst.len() - offset).min(batch); + for lane in 0..take { + let row = chunk_start + offset + lane; + let mut pos = lane * total_row_bytes; + for (buf, rb) in blocks { + if *rb > 0 { + scratch[pos..pos + *rb] + .copy_from_slice(&buf[row * *rb..(row + 1) * *rb]); + pos += *rb; + } + } + } + hash_raw_rows_slice( + &scratch[..take * total_row_bytes], + total_row_bytes, + &mut dst[offset..offset + take], + backend, + ); + offset += take; + } + }, + ); +} + +/// Hashes `out.len()` rows starting at `start_row` across one or more in-memory +/// Goldilocks matrices (`Matrix`) directly into uninitialized digest slots. +pub(crate) fn hash_matrix_rows_uninit>( + matrices: &[&M], + start_row: usize, + out: &mut [MaybeUninit<[u8; 32]>], +) { + if out.is_empty() { + return; + } + let total_width: usize = matrices.iter().map(|m| m.width()).sum(); + let total_row_bytes = total_width * size_of::(); + let backend = detect_backend(); + + if total_row_bytes == 0 { + let empty_digest = Blake3.hash_slice(&[]); + for slot in out { + slot.write(empty_digest); + } + return; + } + + if total_row_bytes > MAX_MULTIBUF_ROW_BYTES { + let hasher = Blake3; + out.par_iter_mut().enumerate().for_each_init( + || vec![0u8; total_row_bytes], + |scratch, (local_row, digest)| { + let r = start_row + local_row; + let mut pos = 0; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + scratch[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + digest.write(hasher.hash_slice(scratch)); + }, + ); + return; + } + + let batch = match backend { + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx512 => 16usize, + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx2 => 8usize, + SimdBackend::Scalar => 1usize, + }; + + // Fast path for rows fitting in a single 64-byte BLAKE3 block (<= 8 + // Goldilocks columns: covers all FRI layers and quotient LDEs): serialize + // directly into a 1 KiB zero-padded stack block array with zero heap scratch. + #[cfg(target_arch = "x86_64")] + if total_row_bytes <= BLOCK_LEN && batch > 1 { + let block_len_u32 = u32::try_from(total_row_bytes).unwrap(); + let chunk_rows = 256usize; + let process_small = |chunk_start: usize, dst: &mut [MaybeUninit<[u8; 32]>]| { + let mut offset = 0; + while offset + batch <= dst.len() { + let mut blocks = [[0u8; BLOCK_LEN]; 16]; + for (lane, block) in blocks[..batch].iter_mut().enumerate() { + let r = chunk_start + offset + lane; + let mut pos = 0; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + block[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + } + if backend == SimdBackend::Avx512 { + // SAFETY: `avx512f` detected at runtime; `dst[offset..offset+16]` has 16 slots. + unsafe { + avx512::hash_16_single_block( + &blocks, + block_len_u32, + dst[offset..].as_mut_ptr().cast(), + ); + } + } else { + // SAFETY: `avx2` detected at runtime; `dst[offset..offset+8]` has 8 slots. + unsafe { + avx2::hash_8_single_block( + (&blocks[..8]).try_into().unwrap(), + block_len_u32, + dst[offset..].as_mut_ptr().cast(), + ); + } + } + offset += batch; + } + if offset < dst.len() { + let hasher = Blake3; + let mut block = [0u8; BLOCK_LEN]; + while offset < dst.len() { + let r = chunk_start + offset; + let mut pos = 0; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + block[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + dst[offset].write(hasher.hash_slice(&block[..total_row_bytes])); + offset += 1; + } + } + }; + if out.len() <= chunk_rows { + process_small(start_row, out); + } else { + out.par_chunks_mut(chunk_rows) + .enumerate() + .for_each(|(chunk_idx, dst)| { + process_small(start_row + chunk_idx * chunk_rows, dst); + }); + } + return; + } + + let chunk_rows = (65_536 / total_row_bytes.max(64)) + .clamp(batch, 256) + .next_multiple_of(batch); + + let process_chunk = + |scratch: &mut Vec, chunk_start: usize, dst: &mut [MaybeUninit<[u8; 32]>]| { + let mut offset = 0; + while offset < dst.len() { + let take = (dst.len() - offset).min(batch); + for lane in 0..take { + let r = chunk_start + offset + lane; + let mut pos = lane * total_row_bytes; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + scratch[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + } + hash_raw_rows_slice( + &scratch[..take * total_row_bytes], + total_row_bytes, + &mut dst[offset..offset + take], + backend, + ); + offset += take; + } + }; + + if out.len() <= chunk_rows { + let mut scratch = vec![0u8; batch * total_row_bytes]; + process_chunk(&mut scratch, start_row, out); + } else { + out.par_chunks_mut(chunk_rows).enumerate().for_each_init( + || vec![0u8; batch * total_row_bytes], + |scratch, (chunk_idx, dst)| { + process_chunk(scratch, start_row + chunk_idx * chunk_rows, dst); + }, + ); + } +} + +/// Reinterprets an initialized digest slice as `&mut [MaybeUninit<[u8; 32]>]`. +/// +/// # Safety +/// The caller must never write uninitialized data into the returned slice. +#[inline] +unsafe fn as_uninit_slice(slice: &mut [[u8; 32]]) -> &mut [MaybeUninit<[u8; 32]>] { + // SAFETY: `MaybeUninit<[u8; 32]>` has identical layout to `[u8; 32]`, and + // callers guarantee they only write initialized `[u8; 32]` values. + unsafe { core::slice::from_raw_parts_mut(slice.as_mut_ptr().cast(), slice.len()) } +} + +/// Safe wrapper over [`hash_raw_multi_rows_uninit`] writing into an existing +/// initialized digest buffer. +pub(crate) fn hash_raw_multi_rows(blocks: &[(Vec, usize)], out: &mut [[u8; 32]]) { + // SAFETY: `hash_raw_multi_rows_uninit` only writes initialized `[u8; 32]` values. + let uninit = unsafe { as_uninit_slice(out) }; + hash_raw_multi_rows_uninit(blocks, uninit); +} + +/// Safe wrapper over [`hash_matrix_rows_uninit`] writing into an existing +/// initialized digest buffer. +pub(crate) fn hash_matrix_rows>( + matrices: &[&M], + start_row: usize, + out: &mut [[u8; 32]], +) { + // SAFETY: `hash_matrix_rows_uninit` only writes initialized `[u8; 32]` values. + let uninit = unsafe { as_uninit_slice(out) }; + hash_matrix_rows_uninit(matrices, start_row, uninit); +} + +#[cfg(target_arch = "x86_64")] +mod avx512 { + use core::arch::x86_64::*; + + use super::{BLOCK_LEN, CHUNK_END, CHUNK_LEN, CHUNK_START, IV, MSG_SCHEDULE, PARENT, ROOT}; + + #[target_feature(enable = "avx512f")] + #[inline] + fn splat_u32(v: u32) -> __m512i { + _mm512_set1_epi32(v.cast_signed()) + } + + #[target_feature(enable = "avx512f")] + #[inline] + fn iv_vecs() -> [__m512i; 8] { + [ + splat_u32(IV[0]), + splat_u32(IV[1]), + splat_u32(IV[2]), + splat_u32(IV[3]), + splat_u32(IV[4]), + splat_u32(IV[5]), + splat_u32(IV[6]), + splat_u32(IV[7]), + ] + } + + #[target_feature(enable = "avx512f")] + #[inline] + fn g_16( + v: &mut [__m512i; 16], + a: usize, + b: usize, + c: usize, + d: usize, + mx: __m512i, + my: __m512i, + ) { + v[a] = _mm512_add_epi32(_mm512_add_epi32(v[a], v[b]), mx); + v[d] = _mm512_ror_epi32::<16>(_mm512_xor_si512(v[d], v[a])); + v[c] = _mm512_add_epi32(v[c], v[d]); + v[b] = _mm512_ror_epi32::<12>(_mm512_xor_si512(v[b], v[c])); + v[a] = _mm512_add_epi32(_mm512_add_epi32(v[a], v[b]), my); + v[d] = _mm512_ror_epi32::<8>(_mm512_xor_si512(v[d], v[a])); + v[c] = _mm512_add_epi32(v[c], v[d]); + v[b] = _mm512_ror_epi32::<7>(_mm512_xor_si512(v[b], v[c])); + } + + #[target_feature(enable = "avx512f")] + #[inline] + fn compress_block_16( + cv: &mut [__m512i; 8], + msg: &[__m512i; 16], + block_len: u32, + counter: u64, + flags: u32, + ) { + let counter_lo = u32::try_from(counter & 0xFFFF_FFFF).unwrap(); + let counter_hi = u32::try_from(counter >> 32).unwrap(); + let mut v = [ + cv[0], + cv[1], + cv[2], + cv[3], + cv[4], + cv[5], + cv[6], + cv[7], + splat_u32(IV[0]), + splat_u32(IV[1]), + splat_u32(IV[2]), + splat_u32(IV[3]), + splat_u32(counter_lo), + splat_u32(counter_hi), + splat_u32(block_len), + splat_u32(flags), + ]; + for s in &MSG_SCHEDULE { + g_16(&mut v, 0, 4, 8, 12, msg[s[0]], msg[s[1]]); + g_16(&mut v, 1, 5, 9, 13, msg[s[2]], msg[s[3]]); + g_16(&mut v, 2, 6, 10, 14, msg[s[4]], msg[s[5]]); + g_16(&mut v, 3, 7, 11, 15, msg[s[6]], msg[s[7]]); + g_16(&mut v, 0, 5, 10, 15, msg[s[8]], msg[s[9]]); + g_16(&mut v, 1, 6, 11, 12, msg[s[10]], msg[s[11]]); + g_16(&mut v, 2, 7, 8, 13, msg[s[12]], msg[s[13]]); + g_16(&mut v, 3, 4, 9, 14, msg[s[14]], msg[s[15]]); + } + for i in 0..8 { + cv[i] = _mm512_xor_si512(v[i], v[i + 8]); + } + } + + #[target_feature(enable = "avx512f")] + #[inline] + fn transpose_16x16(rows: &[__m512i; 16]) -> [__m512i; 16] { + let mut t0 = [_mm512_setzero_si512(); 16]; + for k in 0..8 { + t0[2 * k] = _mm512_unpacklo_epi32(rows[2 * k], rows[2 * k + 1]); + t0[2 * k + 1] = _mm512_unpackhi_epi32(rows[2 * k], rows[2 * k + 1]); + } + let mut t1 = [_mm512_setzero_si512(); 16]; + for j in 0..4 { + let g = 4 * j; + t1[g] = _mm512_unpacklo_epi64(t0[g], t0[g + 2]); + t1[g + 1] = _mm512_unpackhi_epi64(t0[g], t0[g + 2]); + t1[g + 2] = _mm512_unpacklo_epi64(t0[g + 1], t0[g + 3]); + t1[g + 3] = _mm512_unpackhi_epi64(t0[g + 1], t0[g + 3]); + } + let mut out = [_mm512_setzero_si512(); 16]; + for m in 0..4 { + let lo0 = _mm512_shuffle_i32x4::<0x44>(t1[m], t1[4 + m]); + let hi0 = _mm512_shuffle_i32x4::<0xEE>(t1[m], t1[4 + m]); + let lo1 = _mm512_shuffle_i32x4::<0x44>(t1[8 + m], t1[12 + m]); + let hi1 = _mm512_shuffle_i32x4::<0xEE>(t1[8 + m], t1[12 + m]); + out[m] = _mm512_shuffle_i32x4::<0x88>(lo0, lo1); + out[4 + m] = _mm512_shuffle_i32x4::<0xDD>(lo0, lo1); + out[8 + m] = _mm512_shuffle_i32x4::<0x88>(hi0, hi1); + out[12 + m] = _mm512_shuffle_i32x4::<0xDD>(hi0, hi1); + } + out + } + + /// Transposes 16 digests of 8 `u32` words each into 8 AVX-512 word vectors. + #[target_feature(enable = "avx512f")] + #[inline] + fn load_16_digests_transposed(digests: &[[u8; 32]; 16]) -> [__m512i; 8] { + let mut lo = [_mm256_setzero_si256(); 8]; + let mut hi = [_mm256_setzero_si256(); 8]; + // SAFETY: `digests` holds 16 valid 32-byte arrays. + unsafe { + for k in 0..8 { + lo[k] = _mm256_loadu_si256(digests[k].as_ptr().cast()); + hi[k] = _mm256_loadu_si256(digests[8 + k].as_ptr().cast()); + } + } + let lo_t = super::avx2::transpose_8x8(&lo); + let hi_t = super::avx2::transpose_8x8(&hi); + core::array::from_fn(|w| _mm512_inserti64x4::<1>(_mm512_castsi256_si512(lo_t[w]), hi_t[w])) + } + + #[target_feature(enable = "avx512f")] + #[inline] + unsafe fn unpack_cv_16(cv: &[__m512i; 8], out: *mut [u8; 32]) { + let mut a = [_mm512_setzero_si512(); 8]; + for k in 0..4 { + a[2 * k] = _mm512_unpacklo_epi32(cv[2 * k], cv[2 * k + 1]); + a[2 * k + 1] = _mm512_unpackhi_epi32(cv[2 * k], cv[2 * k + 1]); + } + let b = [ + _mm512_unpacklo_epi64(a[0], a[2]), + _mm512_unpackhi_epi64(a[0], a[2]), + _mm512_unpacklo_epi64(a[1], a[3]), + _mm512_unpackhi_epi64(a[1], a[3]), + _mm512_unpacklo_epi64(a[4], a[6]), + _mm512_unpackhi_epi64(a[4], a[6]), + _mm512_unpacklo_epi64(a[5], a[7]), + _mm512_unpackhi_epi64(a[5], a[7]), + ]; + for r in 0..4 { + let lo_tmp = _mm512_shuffle_i32x4::<0x44>(b[r], b[4 + r]); + let lo_pair = _mm512_shuffle_i32x4::<0xD8>(lo_tmp, lo_tmp); + let hi_tmp = _mm512_shuffle_i32x4::<0xEE>(b[r], b[4 + r]); + let hi_pair = _mm512_shuffle_i32x4::<0xD8>(hi_tmp, hi_tmp); + // SAFETY: caller guarantees `out` points to 16 writable 32-byte slots. + unsafe { + _mm256_storeu_si256(out.add(r).cast(), _mm512_castsi512_si256(lo_pair)); + _mm256_storeu_si256( + out.add(4 + r).cast(), + _mm512_extracti64x4_epi64::<1>(lo_pair), + ); + _mm256_storeu_si256(out.add(8 + r).cast(), _mm512_castsi512_si256(hi_pair)); + _mm256_storeu_si256( + out.add(12 + r).cast(), + _mm512_extracti64x4_epi64::<1>(hi_pair), + ); + } + } + } + + #[target_feature(enable = "avx512f")] + pub(super) unsafe fn hash_16_single_block( + blocks: &[[u8; BLOCK_LEN]; 16], + block_len: u32, + out: *mut [u8; 32], + ) { + let mut rows = [_mm512_setzero_si512(); 16]; + // SAFETY: `blocks` holds 16 contiguous 64-byte arrays. + unsafe { + for (lane, row) in rows.iter_mut().enumerate() { + *row = _mm512_loadu_si512(blocks[lane].as_ptr().cast()); + } + } + let msg = transpose_16x16(&rows); + let mut cv = iv_vecs(); + compress_block_16(&mut cv, &msg, block_len, 0, CHUNK_START | CHUNK_END | ROOT); + // SAFETY: caller guarantees `out` points to 16 writable slots. + unsafe { unpack_cv_16(&cv, out) }; + } + + #[target_feature(enable = "avx512f")] + pub(super) unsafe fn compress_16_pairs(prev_32: &[[u8; 32]], out: *mut [u8; 32]) { + debug_assert!(prev_32.len() >= 32); + let mut rows = [_mm512_setzero_si512(); 16]; + let base = prev_32.as_ptr().cast::(); + // SAFETY: `prev_32` has 32 contiguous 32-byte elements = 16 contiguous 64-byte blocks. + unsafe { + for (lane, row) in rows.iter_mut().enumerate() { + *row = _mm512_loadu_si512(base.add(lane * 64).cast()); + } + } + let msg = transpose_16x16(&rows); + let mut cv = iv_vecs(); + compress_block_16(&mut cv, &msg, 64, 0, CHUNK_START | CHUNK_END | ROOT); + // SAFETY: caller guarantees `out` points to 16 writable slots. + unsafe { unpack_cv_16(&cv, out) }; + } + + #[target_feature(enable = "avx512f")] + pub(super) unsafe fn compress_16_pairs_and_inject( + prev_32: &[[u8; 32]], + rows_digests: &[[u8; 32]; 16], + out: *mut [u8; 32], + ) { + debug_assert!(prev_32.len() >= 32); + let mut rows = [_mm512_setzero_si512(); 16]; + let base = prev_32.as_ptr().cast::(); + // SAFETY: `prev_32` has 32 contiguous 32-byte elements = 16 contiguous 64-byte blocks. + unsafe { + for (lane, row) in rows.iter_mut().enumerate() { + *row = _mm512_loadu_si512(base.add(lane * 64).cast()); + } + } + let msg1 = transpose_16x16(&rows); + let mut parent_cv = iv_vecs(); + compress_block_16(&mut parent_cv, &msg1, 64, 0, CHUNK_START | CHUNK_END | ROOT); + + let right_cv = load_16_digests_transposed(rows_digests); + let msg2 = [ + parent_cv[0], + parent_cv[1], + parent_cv[2], + parent_cv[3], + parent_cv[4], + parent_cv[5], + parent_cv[6], + parent_cv[7], + right_cv[0], + right_cv[1], + right_cv[2], + right_cv[3], + right_cv[4], + right_cv[5], + right_cv[6], + right_cv[7], + ]; + let mut final_cv = iv_vecs(); + compress_block_16(&mut final_cv, &msg2, 64, 0, CHUNK_START | CHUNK_END | ROOT); + // SAFETY: caller guarantees `out` points to 16 writable slots. + unsafe { unpack_cv_16(&final_cv, out) }; + } + + #[target_feature(enable = "avx512f")] + #[inline] + unsafe fn hash_chunk_16( + ptrs: &[*const u8; 16], + chunk_offset: usize, + chunk_len: usize, + counter: u64, + is_root: bool, + ) -> [__m512i; 8] { + let mut cv = iv_vecs(); + let num_blocks = chunk_len.div_ceil(BLOCK_LEN).max(1); + for b in 0..num_blocks { + let block_offset = chunk_offset + b * BLOCK_LEN; + let rem = chunk_len.saturating_sub(b * BLOCK_LEN); + let block_len = rem.min(BLOCK_LEN); + let mut rows = [_mm512_setzero_si512(); 16]; + // SAFETY: caller guarantees each `ptrs[lane]` has `chunk_offset + chunk_len` readable bytes. + unsafe { + if block_len == BLOCK_LEN { + for lane in 0..16 { + rows[lane] = _mm512_loadu_si512(ptrs[lane].add(block_offset).cast()); + } + } else { + for lane in 0..16 { + let mut tmp = [0u8; BLOCK_LEN]; + if block_len > 0 { + core::ptr::copy_nonoverlapping( + ptrs[lane].add(block_offset), + tmp.as_mut_ptr(), + block_len, + ); + } + rows[lane] = _mm512_loadu_si512(tmp.as_ptr().cast()); + } + } + } + let msg = transpose_16x16(&rows); + let mut flags = 0u32; + if b == 0 { + flags |= CHUNK_START; + } + if b + 1 == num_blocks { + flags |= CHUNK_END; + if is_root { + flags |= ROOT; + } + } + compress_block_16( + &mut cv, + &msg, + u32::try_from(block_len).unwrap(), + counter, + flags, + ); + } + cv + } + + #[target_feature(enable = "avx512f")] + #[inline] + fn compress_parent_16( + left: &[__m512i; 8], + right: &[__m512i; 8], + is_root: bool, + ) -> [__m512i; 8] { + let msg = [ + left[0], left[1], left[2], left[3], left[4], left[5], left[6], left[7], right[0], + right[1], right[2], right[3], right[4], right[5], right[6], right[7], + ]; + let mut cv = iv_vecs(); + let flags = if is_root { PARENT | ROOT } else { PARENT }; + compress_block_16(&mut cv, &msg, 64, 0, flags); + cv + } + + #[target_feature(enable = "avx512f")] + pub(super) unsafe fn hash_16_fixed_len( + ptrs: &[*const u8; 16], + row_bytes: usize, + out: *mut [u8; 32], + ) { + debug_assert!(row_bytes <= super::MAX_MULTIBUF_ROW_BYTES); + if row_bytes <= CHUNK_LEN { + // SAFETY: caller guarantees `ptrs` validity for `row_bytes` and `out` has 16 slots. + unsafe { + let cv = hash_chunk_16(ptrs, 0, row_bytes, 0, true); + unpack_cv_16(&cv, out); + } + return; + } + let num_chunks = row_bytes.div_ceil(CHUNK_LEN); + // Max `num_chunks` is 16 -> max CV stack depth is 5. + let mut cv_stack = [[_mm512_setzero_si512(); 8]; 6]; + let mut stack_len = 0usize; + for c in 0..num_chunks { + let chunk_offset = c * CHUNK_LEN; + let chunk_len = (row_bytes - chunk_offset).min(CHUNK_LEN); + // SAFETY: caller guarantees `ptrs` validity for `row_bytes`. + let mut new_cv = unsafe { + hash_chunk_16( + ptrs, + chunk_offset, + chunk_len, + u64::try_from(c).unwrap(), + false, + ) + }; + if c + 1 < num_chunks { + let mut total_chunks = c + 1; + while total_chunks & 1 == 0 { + stack_len -= 1; + new_cv = compress_parent_16(&cv_stack[stack_len], &new_cv, false); + total_chunks >>= 1; + } + cv_stack[stack_len] = new_cv; + stack_len += 1; + } else { + while stack_len > 1 { + stack_len -= 1; + new_cv = compress_parent_16(&cv_stack[stack_len], &new_cv, false); + } + stack_len -= 1; + let root_cv = compress_parent_16(&cv_stack[stack_len], &new_cv, true); + // SAFETY: caller guarantees `out` has 16 writable slots. + unsafe { unpack_cv_16(&root_cv, out) }; + } + } + } +} + +#[cfg(target_arch = "x86_64")] +mod avx2 { + use core::arch::x86_64::*; + + use super::{BLOCK_LEN, CHUNK_END, CHUNK_LEN, CHUNK_START, IV, MSG_SCHEDULE, PARENT, ROOT}; + + #[target_feature(enable = "avx2")] + #[inline] + fn splat_u32(v: u32) -> __m256i { + _mm256_set1_epi32(v.cast_signed()) + } + + #[target_feature(enable = "avx2")] + #[inline] + fn iv_vecs() -> [__m256i; 8] { + [ + splat_u32(IV[0]), + splat_u32(IV[1]), + splat_u32(IV[2]), + splat_u32(IV[3]), + splat_u32(IV[4]), + splat_u32(IV[5]), + splat_u32(IV[6]), + splat_u32(IV[7]), + ] + } + + #[target_feature(enable = "avx2")] + #[inline] + fn rot16(x: __m256i) -> __m256i { + let mask = _mm256_setr_epi8( + 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13, 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, + 8, 9, 14, 15, 12, 13, + ); + _mm256_shuffle_epi8(x, mask) + } + + #[target_feature(enable = "avx2")] + #[inline] + fn rot8(x: __m256i) -> __m256i { + let mask = _mm256_setr_epi8( + 1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12, 1, 2, 3, 0, 5, 6, 7, 4, 9, 10, + 11, 8, 13, 14, 15, 12, + ); + _mm256_shuffle_epi8(x, mask) + } + + #[target_feature(enable = "avx2")] + #[inline] + fn rot12(x: __m256i) -> __m256i { + _mm256_or_si256(_mm256_srli_epi32::<12>(x), _mm256_slli_epi32::<20>(x)) + } + + #[target_feature(enable = "avx2")] + #[inline] + fn rot7(x: __m256i) -> __m256i { + _mm256_or_si256(_mm256_srli_epi32::<7>(x), _mm256_slli_epi32::<25>(x)) + } + + #[target_feature(enable = "avx2")] + #[inline] + fn g_8( + v: &mut [__m256i; 16], + a: usize, + b: usize, + c: usize, + d: usize, + mx: __m256i, + my: __m256i, + ) { + v[a] = _mm256_add_epi32(_mm256_add_epi32(v[a], v[b]), mx); + v[d] = rot16(_mm256_xor_si256(v[d], v[a])); + v[c] = _mm256_add_epi32(v[c], v[d]); + v[b] = rot12(_mm256_xor_si256(v[b], v[c])); + v[a] = _mm256_add_epi32(_mm256_add_epi32(v[a], v[b]), my); + v[d] = rot8(_mm256_xor_si256(v[d], v[a])); + v[c] = _mm256_add_epi32(v[c], v[d]); + v[b] = rot7(_mm256_xor_si256(v[b], v[c])); + } + + #[target_feature(enable = "avx2")] + #[inline] + fn compress_block_8( + cv: &mut [__m256i; 8], + msg: &[__m256i; 16], + block_len: u32, + counter: u64, + flags: u32, + ) { + let counter_lo = u32::try_from(counter & 0xFFFF_FFFF).unwrap(); + let counter_hi = u32::try_from(counter >> 32).unwrap(); + let mut v = [ + cv[0], + cv[1], + cv[2], + cv[3], + cv[4], + cv[5], + cv[6], + cv[7], + splat_u32(IV[0]), + splat_u32(IV[1]), + splat_u32(IV[2]), + splat_u32(IV[3]), + splat_u32(counter_lo), + splat_u32(counter_hi), + splat_u32(block_len), + splat_u32(flags), + ]; + for s in &MSG_SCHEDULE { + g_8(&mut v, 0, 4, 8, 12, msg[s[0]], msg[s[1]]); + g_8(&mut v, 1, 5, 9, 13, msg[s[2]], msg[s[3]]); + g_8(&mut v, 2, 6, 10, 14, msg[s[4]], msg[s[5]]); + g_8(&mut v, 3, 7, 11, 15, msg[s[6]], msg[s[7]]); + g_8(&mut v, 0, 5, 10, 15, msg[s[8]], msg[s[9]]); + g_8(&mut v, 1, 6, 11, 12, msg[s[10]], msg[s[11]]); + g_8(&mut v, 2, 7, 8, 13, msg[s[12]], msg[s[13]]); + g_8(&mut v, 3, 4, 9, 14, msg[s[14]], msg[s[15]]); + } + for i in 0..8 { + cv[i] = _mm256_xor_si256(v[i], v[i + 8]); + } + } + + #[target_feature(enable = "avx2")] + #[inline] + pub(super) fn transpose_8x8(rows: &[__m256i; 8]) -> [__m256i; 8] { + let t0 = [ + _mm256_unpacklo_epi32(rows[0], rows[1]), + _mm256_unpackhi_epi32(rows[0], rows[1]), + _mm256_unpacklo_epi32(rows[2], rows[3]), + _mm256_unpackhi_epi32(rows[2], rows[3]), + _mm256_unpacklo_epi32(rows[4], rows[5]), + _mm256_unpackhi_epi32(rows[4], rows[5]), + _mm256_unpacklo_epi32(rows[6], rows[7]), + _mm256_unpackhi_epi32(rows[6], rows[7]), + ]; + let t1 = [ + _mm256_unpacklo_epi64(t0[0], t0[2]), + _mm256_unpackhi_epi64(t0[0], t0[2]), + _mm256_unpacklo_epi64(t0[1], t0[3]), + _mm256_unpackhi_epi64(t0[1], t0[3]), + _mm256_unpacklo_epi64(t0[4], t0[6]), + _mm256_unpackhi_epi64(t0[4], t0[6]), + _mm256_unpacklo_epi64(t0[5], t0[7]), + _mm256_unpackhi_epi64(t0[5], t0[7]), + ]; + [ + _mm256_permute2x128_si256::<0x20>(t1[0], t1[4]), + _mm256_permute2x128_si256::<0x20>(t1[1], t1[5]), + _mm256_permute2x128_si256::<0x20>(t1[2], t1[6]), + _mm256_permute2x128_si256::<0x20>(t1[3], t1[7]), + _mm256_permute2x128_si256::<0x31>(t1[0], t1[4]), + _mm256_permute2x128_si256::<0x31>(t1[1], t1[5]), + _mm256_permute2x128_si256::<0x31>(t1[2], t1[6]), + _mm256_permute2x128_si256::<0x31>(t1[3], t1[7]), + ] + } + + #[target_feature(enable = "avx2")] + #[inline] + unsafe fn unpack_cv_8(cv: &[__m256i; 8], out: *mut [u8; 32]) { + let rows = transpose_8x8(cv); + // SAFETY: caller guarantees `out` points to 8 writable 32-byte slots. + unsafe { + for (lane, row) in rows.iter().enumerate() { + _mm256_storeu_si256(out.add(lane).cast(), *row); + } + } + } + + #[target_feature(enable = "avx2")] + pub(super) unsafe fn hash_8_single_block( + blocks: &[[u8; BLOCK_LEN]; 8], + block_len: u32, + out: *mut [u8; 32], + ) { + let mut left = [_mm256_setzero_si256(); 8]; + let mut right = [_mm256_setzero_si256(); 8]; + // SAFETY: `blocks` holds 8 contiguous 64-byte arrays. + unsafe { + for lane in 0..8 { + let p = blocks[lane].as_ptr(); + left[lane] = _mm256_loadu_si256(p.cast()); + right[lane] = _mm256_loadu_si256(p.add(32).cast()); + } + } + let lo = transpose_8x8(&left); + let hi = transpose_8x8(&right); + let msg = [ + lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], + hi[4], hi[5], hi[6], hi[7], + ]; + let mut cv = iv_vecs(); + compress_block_8(&mut cv, &msg, block_len, 0, CHUNK_START | CHUNK_END | ROOT); + // SAFETY: caller guarantees `out` points to 8 writable slots. + unsafe { unpack_cv_8(&cv, out) }; + } + + #[target_feature(enable = "avx2")] + pub(super) unsafe fn compress_8_pairs(prev_16: &[[u8; 32]], out: *mut [u8; 32]) { + debug_assert!(prev_16.len() >= 16); + let mut left = [_mm256_setzero_si256(); 8]; + let mut right = [_mm256_setzero_si256(); 8]; + // SAFETY: `prev_16` has 16 contiguous 32-byte digests. + unsafe { + for lane in 0..8 { + left[lane] = _mm256_loadu_si256(prev_16[2 * lane].as_ptr().cast()); + right[lane] = _mm256_loadu_si256(prev_16[2 * lane + 1].as_ptr().cast()); + } + } + let lo = transpose_8x8(&left); + let hi = transpose_8x8(&right); + let msg = [ + lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], + hi[4], hi[5], hi[6], hi[7], + ]; + let mut cv = iv_vecs(); + compress_block_8(&mut cv, &msg, 64, 0, CHUNK_START | CHUNK_END | ROOT); + // SAFETY: caller guarantees `out` points to 8 writable slots. + unsafe { unpack_cv_8(&cv, out) }; + } + + #[target_feature(enable = "avx2")] + pub(super) unsafe fn compress_8_pairs_and_inject( + prev_16: &[[u8; 32]], + rows_digests: &[[u8; 32]; 8], + out: *mut [u8; 32], + ) { + debug_assert!(prev_16.len() >= 16); + let mut left = [_mm256_setzero_si256(); 8]; + let mut right = [_mm256_setzero_si256(); 8]; + let mut row_vecs = [_mm256_setzero_si256(); 8]; + // SAFETY: `prev_16` has 16 digests and `rows_digests` has 8 digests. + unsafe { + for lane in 0..8 { + left[lane] = _mm256_loadu_si256(prev_16[2 * lane].as_ptr().cast()); + right[lane] = _mm256_loadu_si256(prev_16[2 * lane + 1].as_ptr().cast()); + row_vecs[lane] = _mm256_loadu_si256(rows_digests[lane].as_ptr().cast()); + } + } + let lo = transpose_8x8(&left); + let hi = transpose_8x8(&right); + let msg1 = [ + lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], + hi[4], hi[5], hi[6], hi[7], + ]; + let mut parent_cv = iv_vecs(); + compress_block_8(&mut parent_cv, &msg1, 64, 0, CHUNK_START | CHUNK_END | ROOT); + + let right_cv = transpose_8x8(&row_vecs); + let msg2 = [ + parent_cv[0], + parent_cv[1], + parent_cv[2], + parent_cv[3], + parent_cv[4], + parent_cv[5], + parent_cv[6], + parent_cv[7], + right_cv[0], + right_cv[1], + right_cv[2], + right_cv[3], + right_cv[4], + right_cv[5], + right_cv[6], + right_cv[7], + ]; + let mut final_cv = iv_vecs(); + compress_block_8(&mut final_cv, &msg2, 64, 0, CHUNK_START | CHUNK_END | ROOT); + // SAFETY: caller guarantees `out` points to 8 writable slots. + unsafe { unpack_cv_8(&final_cv, out) }; + } + + #[target_feature(enable = "avx2")] + #[inline] + unsafe fn hash_chunk_8( + ptrs: &[*const u8; 8], + chunk_offset: usize, + chunk_len: usize, + counter: u64, + is_root: bool, + ) -> [__m256i; 8] { + let mut cv = iv_vecs(); + let num_blocks = chunk_len.div_ceil(BLOCK_LEN).max(1); + for b in 0..num_blocks { + let block_offset = chunk_offset + b * BLOCK_LEN; + let rem = chunk_len.saturating_sub(b * BLOCK_LEN); + let block_len = rem.min(BLOCK_LEN); + let mut left = [_mm256_setzero_si256(); 8]; + let mut right = [_mm256_setzero_si256(); 8]; + // SAFETY: caller guarantees each `ptrs[lane]` has `chunk_offset + chunk_len` readable bytes. + unsafe { + if block_len == BLOCK_LEN { + for lane in 0..8 { + let p = ptrs[lane].add(block_offset); + left[lane] = _mm256_loadu_si256(p.cast()); + right[lane] = _mm256_loadu_si256(p.add(32).cast()); + } + } else { + for lane in 0..8 { + let mut tmp = [0u8; BLOCK_LEN]; + if block_len > 0 { + core::ptr::copy_nonoverlapping( + ptrs[lane].add(block_offset), + tmp.as_mut_ptr(), + block_len, + ); + } + left[lane] = _mm256_loadu_si256(tmp.as_ptr().cast()); + right[lane] = _mm256_loadu_si256(tmp.as_ptr().add(32).cast()); + } + } + } + let lo = transpose_8x8(&left); + let hi = transpose_8x8(&right); + let msg = [ + lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], + hi[4], hi[5], hi[6], hi[7], + ]; + let mut flags = 0u32; + if b == 0 { + flags |= CHUNK_START; + } + if b + 1 == num_blocks { + flags |= CHUNK_END; + if is_root { + flags |= ROOT; + } + } + compress_block_8( + &mut cv, + &msg, + u32::try_from(block_len).unwrap(), + counter, + flags, + ); + } + cv + } + + #[target_feature(enable = "avx2")] + #[inline] + fn compress_parent_8(left: &[__m256i; 8], right: &[__m256i; 8], is_root: bool) -> [__m256i; 8] { + let msg = [ + left[0], left[1], left[2], left[3], left[4], left[5], left[6], left[7], right[0], + right[1], right[2], right[3], right[4], right[5], right[6], right[7], + ]; + let mut cv = iv_vecs(); + let flags = if is_root { PARENT | ROOT } else { PARENT }; + compress_block_8(&mut cv, &msg, 64, 0, flags); + cv + } + + #[target_feature(enable = "avx2")] + pub(super) unsafe fn hash_8_fixed_len( + ptrs: &[*const u8; 8], + row_bytes: usize, + out: *mut [u8; 32], + ) { + debug_assert!(row_bytes <= super::MAX_MULTIBUF_ROW_BYTES); + if row_bytes <= CHUNK_LEN { + // SAFETY: caller guarantees `ptrs` validity for `row_bytes` and `out` has 8 slots. + unsafe { + let cv = hash_chunk_8(ptrs, 0, row_bytes, 0, true); + unpack_cv_8(&cv, out); + } + return; + } + let num_chunks = row_bytes.div_ceil(CHUNK_LEN); + let mut cv_stack = [[_mm256_setzero_si256(); 8]; 6]; + let mut stack_len = 0usize; + for c in 0..num_chunks { + let chunk_offset = c * CHUNK_LEN; + let chunk_len = (row_bytes - chunk_offset).min(CHUNK_LEN); + // SAFETY: caller guarantees `ptrs` validity for `row_bytes`. + let mut new_cv = unsafe { + hash_chunk_8( + ptrs, + chunk_offset, + chunk_len, + u64::try_from(c).unwrap(), + false, + ) + }; + if c + 1 < num_chunks { + let mut total_chunks = c + 1; + while total_chunks & 1 == 0 { + stack_len -= 1; + new_cv = compress_parent_8(&cv_stack[stack_len], &new_cv, false); + total_chunks >>= 1; + } + cv_stack[stack_len] = new_cv; + stack_len += 1; + } else { + while stack_len > 1 { + stack_len -= 1; + new_cv = compress_parent_8(&cv_stack[stack_len], &new_cv, false); + } + stack_len -= 1; + let root_cv = compress_parent_8(&cv_stack[stack_len], &new_cv, true); + // SAFETY: caller guarantees `out` has 8 writable slots. + unsafe { unpack_cv_8(&root_cv, out) }; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::Blake3CompressionFunction; + use p3_goldilocks::Goldilocks; + use p3_matrix::dense::RowMajorMatrix; + use p3_symmetric::{PseudoCompressionFunction, SerializingHasher}; + use rand::rngs::SmallRng; + use rand::{RngExt, SeedableRng}; + + fn available_backends() -> Vec { + let mut backends = vec![SimdBackend::Scalar]; + #[cfg(target_arch = "x86_64")] + { + if std::arch::is_x86_feature_detected!("avx2") { + backends.push(SimdBackend::Avx2); + } + if std::arch::is_x86_feature_detected!("avx512f") { + backends.push(SimdBackend::Avx512); + } + } + backends + } + + #[test] + fn compress_pairs_matches_p3_blake3_all_backends() { + let mut rng = SmallRng::seed_from_u64(0xB1A3_0001); + let ref_compress = Blake3CompressionFunction::new(Blake3); + for count in [ + 0usize, 1, 2, 7, 8, 9, 15, 16, 17, 31, 32, 33, 255, 256, 257, 600, + ] { + let prev: Vec<[u8; 32]> = (0..2 * count).map(|_| rng.random()).collect(); + let expected: Vec<[u8; 32]> = (0..count) + .map(|i| ref_compress.compress([prev[2 * i], prev[2 * i + 1]])) + .collect(); + + for backend in available_backends() { + // SAFETY: `compress_pairs_slice` initializes all `count` slots. + let got = unsafe { + alloc_and_fill_digests(count, count, |dst| { + compress_pairs_slice(&prev, dst, backend); + }) + }; + assert_eq!( + got, expected, + "compress_pairs_slice mismatch for {backend:?} count={count}" + ); + } + + // SAFETY: `compress_pairs_uninit` initializes all `count` slots. + let got_par = unsafe { + alloc_and_fill_digests(count, count, |dst| { + compress_pairs_uninit(&prev, dst); + }) + }; + assert_eq!(got_par, expected, "compress_pairs mismatch count={count}"); + } + } + + #[test] + fn compress_and_inject_matches_p3_blake3_all_backends() { + let mut rng = SmallRng::seed_from_u64(0xB1A3_0002); + let ref_compress = Blake3CompressionFunction::new(Blake3); + for count in [0usize, 1, 7, 8, 9, 15, 16, 17, 128, 300] { + let prev: Vec<[u8; 32]> = (0..2 * count).map(|_| rng.random()).collect(); + let rows: Vec<[u8; 32]> = (0..count).map(|_| rng.random()).collect(); + let expected: Vec<[u8; 32]> = (0..count) + .map(|i| { + let p = ref_compress.compress([prev[2 * i], prev[2 * i + 1]]); + ref_compress.compress([p, rows[i]]) + }) + .collect(); + + for backend in available_backends() { + // SAFETY: `compress_and_inject_slice` initializes all `count` slots. + let got = unsafe { + alloc_and_fill_digests(count, count, |dst| { + compress_and_inject_slice(&prev, &rows, dst, backend); + }) + }; + assert_eq!( + got, expected, + "compress_and_inject_slice mismatch for {backend:?} count={count}" + ); + } + + // SAFETY: `compress_and_inject_from_digests_uninit` initializes all `count` slots. + let got_par = unsafe { + alloc_and_fill_digests(count, count, |dst| { + compress_and_inject_from_digests_uninit(&prev, &rows, dst); + }) + }; + assert_eq!(got_par, expected); + } + } + + #[test] + fn hash_raw_rows_matches_p3_blake3_across_chunk_boundaries() { + let mut rng = SmallRng::seed_from_u64(0xB1A3_0003); + let ref_hasher = Blake3; + let lengths = [ + 0usize, 1, 7, 8, 32, 56, 63, 64, 65, 72, 128, 512, 960, 1016, 1024, 1025, 1032, 2048, + 2056, 3072, 4096, 5120, 6144, 7168, 8192, 16384, 16392, + ]; + for &row_bytes in &lengths { + for &num_rows in &[0usize, 1, 8, 16, 25] { + let mut raw = vec![0u8; num_rows * row_bytes]; + rng.fill(&mut raw[..]); + let expected: Vec<[u8; 32]> = (0..num_rows) + .map(|r| ref_hasher.hash_slice(&raw[r * row_bytes..(r + 1) * row_bytes])) + .collect(); + + for backend in available_backends() { + // SAFETY: `hash_raw_rows_slice` initializes all `num_rows` slots. + let got = unsafe { + alloc_and_fill_digests(num_rows, num_rows, |dst| { + hash_raw_rows_slice(&raw, row_bytes, dst, backend); + }) + }; + assert_eq!( + got, expected, + "hash_raw_rows_slice mismatch for {backend:?} row_bytes={row_bytes} num_rows={num_rows}" + ); + } + + // SAFETY: `hash_raw_rows_uninit` initializes all `num_rows` slots. + let got_par = unsafe { + alloc_and_fill_digests(num_rows, num_rows, |dst| { + hash_raw_rows_uninit(&raw, row_bytes, dst); + }) + }; + assert_eq!(got_par, expected); + } + } + } + + #[test] + fn hash_matrix_rows_matches_serializing_hasher_including_non_canonical_values() { + let mut rng = SmallRng::seed_from_u64(0xB1A3_0004); + let ref_hasher = SerializingHasher::new(Blake3); + let height = 35usize; + // Include non-canonical Goldilocks representations (>= ORDER_U64) to verify canonicalization. + let m1 = RowMajorMatrix::new( + (0..height * 5) + .map(|i| { + if i % 7 == 0 { + Goldilocks::new(u64::MAX - u64::try_from(i).unwrap()) + } else { + Goldilocks::new(rng.random()) + } + }) + .collect(), + 5, + ); + let m2 = RowMajorMatrix::new( + (0..height * 130) + .map(|_| Goldilocks::new(rng.random())) + .collect(), + 130, + ); + let expected_single: Vec<[u8; 32]> = (0..height) + .map(|r| ref_hasher.hash_iter(m1.row_slice(r).unwrap().iter().copied())) + .collect(); + let mut got_single = vec![[0u8; 32]; height]; + hash_matrix_rows(&[&m1], 0, &mut got_single); + assert_eq!(got_single, expected_single); + + let expected_multi: Vec<[u8; 32]> = (0..height) + .map(|r| { + ref_hasher.hash_iter( + m1.row_slice(r) + .unwrap() + .iter() + .chain(m2.row_slice(r).unwrap().iter()) + .copied(), + ) + }) + .collect(); + let mut got_multi = vec![[0u8; 32]; height]; + hash_matrix_rows(&[&m1, &m2], 0, &mut got_multi); + assert_eq!(got_multi, expected_multi); + } +} diff --git a/src/p3_adapter/mod.rs b/src/p3_adapter/mod.rs index 2d5f917..aed6546 100644 --- a/src/p3_adapter/mod.rs +++ b/src/p3_adapter/mod.rs @@ -2,6 +2,8 @@ //! AIR helpers are re-exported here for compatibility. mod air; +#[cfg(not(feature = "cuda"))] +pub(crate) mod blake3_simd; pub mod challenger; pub mod domain; pub mod field; diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs index 48e6e72..4620c79 100644 --- a/src/p3_adapter/spill.rs +++ b/src/p3_adapter/spill.rs @@ -13,6 +13,7 @@ use std::borrow::Cow; use std::cmp::Reverse; +use std::collections::HashMap; use std::fs::{self, File, OpenOptions}; use std::io::{BufWriter, Write}; use std::marker::PhantomData; @@ -26,8 +27,9 @@ use p3_commit::{BatchOpening, BatchOpeningRef, Mmcs, OpenedValues, Pcs, Periodic use p3_dft::TwoAdicSubgroupDft; use p3_field::coset::TwoAdicMultiplicativeCoset; use p3_field::{ - ExtensionField, Field, PackedFieldExtension, PrimeCharacteristicRing, PrimeField64, - TwoAdicField, batch_multiplicative_inverse, dot_product, scale_slice_in_place_single_core, + BasedVectorSpace, ExtensionField, Field, PackedFieldExtension, PackedValue, + PrimeCharacteristicRing, PrimeField64, TwoAdicField, dot_product, + scale_slice_in_place_single_core, }; use p3_fri::verifier::{self, FriError}; use p3_fri::{ @@ -42,17 +44,17 @@ use p3_matrix::interpolation::{Interpolate, compute_adjusted_weights}; use p3_matrix::{Dimensions, Matrix}; use p3_maybe_rayon::prelude::*; use p3_merkle_tree::{MerkleTreeMmcs, PrunedMerklePaths}; -use p3_symmetric::{CryptographicHasher, MerkleCap, PseudoCompressionFunction, SerializingHasher}; +use p3_symmetric::{CryptographicHasher, MerkleCap, SerializingHasher}; use p3_util::linear_map::LinearMap; use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_slice_index_bits}; use tracing::debug_span; -use crate::types::{Blake3CompressionFunction, ExtVal, Val}; +use super::blake3_simd; +use crate::types::{Blake3CompressionFunction, ExtVal, PackedVal, Val}; -/// CPU reference MMCS used for in-memory commitments and verification. +/// CPU reference MMCS used for verification and reference tests. pub type CpuMmcs = MerkleTreeMmcs, Blake3CompressionFunction, 2, 32>; -type CpuData = >::ProverData; type SpillCommitResult = ( >::Commitment, SpillableMmcsData>, @@ -62,8 +64,8 @@ type SpillCommitResult = ( /// opening passes (64 MiB). const STREAM_BLOCK_BYTES: usize = 64 << 20; -/// Write buffer size for sequential spill-file packing (1 MiB of field elements). -const SPILL_WRITE_CHUNK_ELEMS: usize = 1 << 17; +/// Write buffer size for sequential spill-file packing (8 MiB = 1M field elements). +const SPILL_WRITE_CHUNK_ELEMS: usize = 1 << 20; static SPILL_FILE_SEQ: AtomicU64 = AtomicU64::new(0); static ACTIVE_SPILL_FILES: AtomicUsize = AtomicUsize::new(0); @@ -183,12 +185,34 @@ impl SpillPackWriter { .expect("failed to clone spill file handle for writing"); Self { spill, - writer: BufWriter::with_capacity(1 << 20, write_handle), + writer: BufWriter::with_capacity(4 << 20, write_handle), next_offset: 0, - scratch: Vec::with_capacity(SPILL_WRITE_CHUNK_ELEMS * size_of::()), + scratch: Vec::new(), } } + #[inline] + fn pack_chunk_bytes(&mut self, chunk: &[Val]) -> usize { + let byte_len = chunk.len() * size_of::(); + if self.scratch.len() < byte_len { + self.scratch.resize(byte_len, 0); + } + let dst = &mut self.scratch[..byte_len]; + if chunk.len() >= 4096 { + dst.par_chunks_exact_mut(8) + .zip(chunk.par_iter()) + .for_each(|(out, elem)| { + out.copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + }); + } else { + let (out_chunks, _) = dst.as_chunks_mut::<8>(); + for (out, elem) in out_chunks.iter_mut().zip(chunk) { + *out = elem.as_canonical_u64().to_le_bytes(); + } + } + byte_len + } + /// Appends `mat` in canonical little-endian `u64` row-major order and /// returns a lightweight handle to its byte range in the pack file. pub(crate) fn append_matrix(&mut self, mat: &RowMajorMatrix) -> SpilledMatrix { @@ -197,13 +221,9 @@ impl SpillPackWriter { let offset = self.next_offset; let total_elems = mat.values.len(); for chunk in mat.values.chunks(SPILL_WRITE_CHUNK_ELEMS) { - self.scratch.clear(); - for elem in chunk { - self.scratch - .extend_from_slice(&elem.as_canonical_u64().to_le_bytes()); - } + let byte_len = self.pack_chunk_bytes(chunk); self.writer - .write_all(&self.scratch) + .write_all(&self.scratch[..byte_len]) .expect("failed to write matrix chunk to spill file"); } let bytes = u64::try_from(total_elems) @@ -223,6 +243,72 @@ impl SpillPackWriter { } } + /// Appends `mat` to the spill file AND computes each row's BLAKE3 leaf + /// digest from the same cache-hot serialized chunks, eliminating a full + /// disk read pass for single-matrix height groups. + pub(crate) fn append_matrix_and_hash( + &mut self, + mat: &RowMajorMatrix, + ) -> (SpilledMatrix, Vec<[u8; 32]>) { + let height = mat.height(); + let width = mat.width(); + let offset = self.next_offset; + if width == 0 { + let empty_digest = Blake3.hash_slice(&[]); + return ( + SpilledMatrix { + file: Arc::clone(&self.spill), + offset, + height, + width, + }, + vec![empty_digest; height], + ); + } + let row_bytes = width * size_of::(); + let chunk_rows = + ((SPILL_WRITE_CHUNK_ELEMS * size_of::()) / row_bytes).clamp(1, height.max(1)); + // SAFETY: the loop partitions `0..height` into disjoint contiguous chunks + // `row_start..row_start + n_rows` and initializes each via `hash_raw_rows_uninit`. + let digests = unsafe { + blake3_simd::alloc_and_fill_digests(height, height, |dst| { + for row_start in (0..height).step_by(chunk_rows) { + let n_rows = (height - row_start).min(chunk_rows); + let elem_start = row_start * width; + let elem_end = (row_start + n_rows) * width; + let byte_len = self.pack_chunk_bytes(&mat.values[elem_start..elem_end]); + blake3_simd::hash_raw_rows_uninit( + &self.scratch[..byte_len], + row_bytes, + &mut dst[row_start..row_start + n_rows], + ); + self.writer + .write_all(&self.scratch[..byte_len]) + .expect("failed to write matrix chunk to spill file"); + } + }) + }; + let total_elems = mat.values.len(); + let bytes = u64::try_from(total_elems) + .expect("matrix element count exceeds u64") + .checked_mul(u64::try_from(size_of::()).unwrap()) + .expect("matrix byte length overflow"); + self.next_offset = self + .next_offset + .checked_add(bytes) + .expect("spill pack offset overflow"); + TOTAL_SPILLED_BYTES.fetch_add(bytes, Ordering::Relaxed); + ( + SpilledMatrix { + file: Arc::clone(&self.spill), + offset, + height, + width, + }, + digests, + ) + } + /// Flushes all buffered writes to the OS file before positional reads. pub(crate) fn flush(&mut self) { self.writer.flush().expect("failed to flush spill file"); @@ -340,10 +426,17 @@ impl SpilledMatrix { fn bytes_to_goldilocks(raw: &[u8]) -> Vec { let (chunks, remainder) = raw.as_chunks::<8>(); debug_assert!(remainder.is_empty()); - chunks - .iter() - .map(|&chunk| Goldilocks::new(u64::from_le_bytes(chunk))) - .collect() + if chunks.len() >= 4096 { + chunks + .par_iter() + .map(|&chunk| Goldilocks::new(u64::from_le_bytes(chunk))) + .collect() + } else { + chunks + .iter() + .map(|&chunk| Goldilocks::new(u64::from_le_bytes(chunk))) + .collect() + } } /// Binary Merkle-tree padded layer length (matching `p3_merkle_tree::padded_len(raw_len, 2)`). @@ -358,16 +451,18 @@ const fn padded_len_binary(raw_len: usize) -> usize { /// Validates that every matrix height sits on the `ceil(max_height / 2^k)` /// ladder anchored at the tallest matrix (matching `p3_merkle_tree`). -fn validate_reachable_heights(matrices: &[SpilledMatrix]) -> usize { - let max_height = matrices - .iter() - .map(SpilledMatrix::height) +fn validate_reachable_heights_iter(heights: impl Iterator + Clone) -> usize { + let max_height = heights + .clone() .max() .filter(|&h| h > 0) .expect("all matrices have height 0"); let log_max_height = log2_ceil_usize(max_height); - for m in matrices { - let h = m.height(); + for h in heights { + assert!( + h > 0, + "matrix height 0 incompatible with tallest height {max_height}" + ); let bits_reduced = log_max_height - log2_ceil_usize(h); let expected_height = ((max_height - 1) >> bits_reduced) + 1; assert_eq!( @@ -378,13 +473,237 @@ fn validate_reachable_heights(matrices: &[SpilledMatrix]) -> usize { max_height } +/// Shared Merkle digest layers and opening-proof traversal for both in-memory +/// and disk-spilled binary BLAKE3 Merkle trees. +struct MerkleDigests { + digest_layers: Vec>, + arity_schedule: Vec, +} + +impl MerkleDigests { + fn cap(&self, cap_height: usize) -> MerkleCap { + let num_layers = self.digest_layers.len(); + let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); + let layer_idx = num_layers - 1 - effective_cap_height; + let layer = &self.digest_layers[layer_idx]; + let cap_len: usize = self.arity_schedule[layer_idx..].iter().product(); + let cap_len = cap_len.min(layer.len()); + MerkleCap::new(layer[..cap_len].to_vec()) + } + + fn open_single_proof(&self, index: usize, cap_height: usize) -> Vec<[u8; 32]> { + let num_layers = self.digest_layers.len(); + let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); + let proof_levels = num_layers + .saturating_sub(1) + .saturating_sub(effective_cap_height); + + let mut proof = Vec::with_capacity(proof_levels); + let mut idx = index; + for layer_idx in 0..proof_levels { + let step = self.arity_schedule[layer_idx]; + let group_start = (idx / step) * step; + let pos_in_group = idx % step; + for k in 0..step { + if k != pos_in_group { + proof.push(self.digest_layers[layer_idx][group_start + k]); + } + } + idx /= step; + } + proof + } + + fn open_multi_proof(&self, indices: &[usize], cap_height: usize) -> PrunedMerklePaths { + let num_layers = self.digest_layers.len(); + let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); + let proof_levels = num_layers + .saturating_sub(1) + .saturating_sub(effective_cap_height); + + // Walk the pruned frontier bottom-up in the exact wire order defined by + // `p3_merkle_tree::pruning::walk_frontier`: + // - sorted unique leaf indices + // - level 0 .. proof_levels + // - ascending parent groups, emitting missing child positions ascending. + let mut nodes: Vec = indices.to_vec(); + nodes.sort_unstable(); + nodes.dedup(); + + let mut sibling_hashes = Vec::new(); + if !nodes.is_empty() { + let mut parents: Vec = Vec::with_capacity(nodes.len()); + for (level, &arity) in self.arity_schedule[..proof_levels].iter().enumerate() { + parents.clear(); + let mut i = 0; + while i < nodes.len() { + let group = nodes[i] / arity; + let group_start = group * arity; + let mut member = i; + for k in 0..arity { + if member < nodes.len() && nodes[member] == group_start + k { + member += 1; + } else { + sibling_hashes.push(self.digest_layers[level][group_start + k]); + } + } + parents.push(group); + i = member; + } + core::mem::swap(&mut nodes, &mut parents); + } + } + + PrunedMerklePaths { sibling_hashes } + } +} + +/// Fast in-memory binary BLAKE3 Merkle tree accelerated with multi-buffer SIMD +/// hashing for both leaf rows and internal 2-to-1 compression layers. +struct FastInMemoryMerkleTree { + leaves: Vec, + digests: MerkleDigests, +} + +impl> FastInMemoryMerkleTree { + fn build(leaves: Vec) -> Self { + assert!(!leaves.is_empty(), "No matrices given?"); + let max_height = validate_reachable_heights_iter(leaves.iter().map(Matrix::height)); + + let mut order: Vec = (0..leaves.len()).collect(); + order.sort_by_key(|&idx| Reverse(leaves[idx].height())); + + let tallest_end = order + .iter() + .take_while(|&&idx| leaves[idx].height() == max_height) + .count(); + let tallest = &order[..tallest_end]; + let mut cursor = tallest_end; + + let tallest_refs: Vec<&M> = tallest.iter().map(|&idx| &leaves[idx]).collect(); + // SAFETY: `hash_matrix_rows_uninit` initializes every element of `dst` (`0..max_height`). + let first_layer = unsafe { + blake3_simd::alloc_and_fill_digests(padded_len_binary(max_height), max_height, |dst| { + blake3_simd::hash_matrix_rows_uninit(&tallest_refs, 0, dst); + }) + }; + + let mut digest_layers = vec![first_layer]; + let mut arity_schedule = Vec::new(); + + loop { + let prev_layer = digest_layers.last().unwrap().as_slice(); + if prev_layer.len() <= 1 { + break; + } + let step = 2usize; + let raw_next = prev_layer.len() / step; + let next_layer_len = raw_next.next_power_of_two(); + + let inject_start = cursor; + while cursor < order.len() + && leaves[order[cursor]].height().next_power_of_two() == next_layer_len + { + cursor += 1; + } + let inject_group = &order[inject_start..cursor]; + + let next_digests = if inject_group.is_empty() { + compress_layer_binary(prev_layer) + } else { + let inject_refs: Vec<&M> = inject_group.iter().map(|&idx| &leaves[idx]).collect(); + compress_and_inject_in_memory(prev_layer, &inject_refs) + }; + arity_schedule.push(step); + digest_layers.push(next_digests); + } + + Self { + leaves, + digests: MerkleDigests { + digest_layers, + arity_schedule, + }, + } + } + + fn cap(&self, cap_height: usize) -> MerkleCap { + self.digests.cap(cap_height) + } + + fn max_height(&self) -> usize { + self.leaves + .iter() + .map(Matrix::height) + .max() + .expect("No committed matrices?") + } + + fn matrix_heights(&self) -> Vec { + self.leaves.iter().map(Matrix::height).collect() + } + + fn dimensions(&self) -> Vec { + self.leaves.iter().map(Matrix::dimensions).collect() + } + + fn open_batch(&self, index: usize, cap_height: usize) -> (Vec>, Vec<[u8; 32]>) { + let max_height = self.max_height(); + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + let log_max_height = log2_ceil_usize(max_height); + let openings: Vec> = self + .leaves + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.row(reduced_index).unwrap().into_iter().collect() + }) + .collect(); + let proof = self.digests.open_single_proof(index, cap_height); + (openings, proof) + } + + fn open_multi_batch( + &self, + indices: &[usize], + cap_height: usize, + ) -> (Vec>>, PrunedMerklePaths) { + let max_height = self.max_height(); + let log_max_height = log2_ceil_usize(max_height); + let opened_values: Vec>> = indices + .iter() + .map(|&index| { + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + self.leaves + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.row(reduced_index).unwrap().into_iter().collect() + }) + .collect() + }) + .collect(); + let proof = self.digests.open_multi_proof(indices, cap_height); + (opened_values, proof) + } +} + /// A binary Blake3 Merkle tree whose leaf matrices reside on disk in /// [`SpilledMatrix`] handles, while only the compact internal `digest_layers` /// remain in RAM. pub(crate) struct SpilledMerkleTree { matrices: Vec, - digest_layers: Vec>, - arity_schedule: Vec, + digests: MerkleDigests, /// Optional spilled 1× original traces retained for zero-FFT on-demand /// lookup evaluation; released once stage-2 completes for stage-1 data, /// or retained for the lifetime of `ProverKey` for preprocessed data. @@ -392,13 +711,14 @@ pub(crate) struct SpilledMerkleTree { } impl SpilledMerkleTree { - pub(crate) fn build( + pub(crate) fn build_with_prehashed( matrices: Vec, original_traces: Vec>, - compress: &Blake3CompressionFunction, + mut prehashed: Vec>>, ) -> Self { assert!(!matrices.is_empty(), "No matrices given?"); - let max_height = validate_reachable_heights(&matrices); + let max_height = + validate_reachable_heights_iter(matrices.iter().map(SpilledMatrix::height)); // Stable sort tallest-first to match `MerkleTree::new` insertion order // within each height group. @@ -412,7 +732,15 @@ impl SpilledMerkleTree { let tallest = &order[..tallest_end]; let mut cursor = tallest_end; - let first_layer = hash_leaf_group_streaming(&matrices, tallest, max_height); + let first_layer = if let &[single_idx] = tallest + && let Some(mut digests) = prehashed.get_mut(single_idx).and_then(Option::take) + { + debug_assert_eq!(digests.len(), max_height); + digests.resize(padded_len_binary(max_height), [0u8; 32]); + digests + } else { + hash_leaf_group_streaming(&matrices, tallest, max_height) + }; let mut digest_layers = vec![first_layer]; let mut arity_schedule = Vec::new(); @@ -434,9 +762,13 @@ impl SpilledMerkleTree { let inject_group = &order[inject_start..cursor]; let next_digests = if inject_group.is_empty() { - compress_layer_binary(prev_layer, compress) + compress_layer_binary(prev_layer) + } else if let &[single_idx] = inject_group + && let Some(rows_digests) = prehashed.get_mut(single_idx).and_then(Option::take) + { + compress_and_inject_prehashed(prev_layer, &rows_digests) } else { - compress_and_inject_streaming(prev_layer, &matrices, inject_group, compress) + compress_and_inject_streaming(prev_layer, &matrices, inject_group) }; arity_schedule.push(step); digest_layers.push(next_digests); @@ -444,20 +776,16 @@ impl SpilledMerkleTree { Self { matrices, - digest_layers, - arity_schedule, + digests: MerkleDigests { + digest_layers, + arity_schedule, + }, original_traces: Mutex::new(original_traces), } } pub(crate) fn cap(&self, cap_height: usize) -> MerkleCap { - let num_layers = self.digest_layers.len(); - let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); - let layer_idx = num_layers - 1 - effective_cap_height; - let layer = &self.digest_layers[layer_idx]; - let cap_len: usize = self.arity_schedule[layer_idx..].iter().product(); - let cap_len = cap_len.min(layer.len()); - MerkleCap::new(layer[..cap_len].to_vec()) + self.digests.cap(cap_height) } pub(crate) fn max_height(&self) -> usize { @@ -502,25 +830,7 @@ impl SpilledMerkleTree { }) .collect(); - let num_layers = self.digest_layers.len(); - let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); - let proof_levels = num_layers - .saturating_sub(1) - .saturating_sub(effective_cap_height); - - let mut proof = Vec::with_capacity(proof_levels); - let mut idx = index; - for layer_idx in 0..proof_levels { - let step = self.arity_schedule[layer_idx]; - let group_start = (idx / step) * step; - let pos_in_group = idx % step; - for k in 0..step { - if k != pos_in_group { - proof.push(self.digest_layers[layer_idx][group_start + k]); - } - } - idx /= step; - } + let proof = self.digests.open_single_proof(index, cap_height); (openings, proof) } @@ -531,11 +841,6 @@ impl SpilledMerkleTree { ) -> (Vec>>, PrunedMerklePaths) { let max_height = self.max_height(); let log_max_height = log2_ceil_usize(max_height); - let num_layers = self.digest_layers.len(); - let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); - let proof_levels = num_layers - .saturating_sub(1) - .saturating_sub(effective_cap_height); let opened_values: Vec>> = indices .iter() @@ -556,40 +861,8 @@ impl SpilledMerkleTree { }) .collect(); - // Walk the pruned frontier bottom-up in the exact wire order defined by - // `p3_merkle_tree::pruning::walk_frontier`: - // - sorted unique leaf indices - // - level 0 .. proof_levels - // - ascending parent groups, emitting missing child positions ascending. - let mut nodes: Vec = indices.to_vec(); - nodes.sort_unstable(); - nodes.dedup(); - - let mut sibling_hashes = Vec::new(); - if !nodes.is_empty() { - let mut parents: Vec = Vec::with_capacity(nodes.len()); - for (level, &arity) in self.arity_schedule[..proof_levels].iter().enumerate() { - parents.clear(); - let mut i = 0; - while i < nodes.len() { - let group = nodes[i] / arity; - let group_start = group * arity; - let mut member = i; - for k in 0..arity { - if member < nodes.len() && nodes[member] == group_start + k { - member += 1; - } else { - sibling_hashes.push(self.digest_layers[level][group_start + k]); - } - } - parents.push(group); - i = member; - } - core::mem::swap(&mut nodes, &mut parents); - } - } - - (opened_values, PrunedMerklePaths { sibling_hashes }) + let proof = self.digests.open_multi_proof(indices, cap_height); + (opened_values, proof) } pub(crate) fn spilled_original_trace(&self, idx: usize) -> Option { @@ -626,106 +899,152 @@ fn hash_leaf_group_streaming( max_height: usize, ) -> Vec<[u8; 32]> { let padded = padded_len_binary(max_height); - let mut digests = vec![[0u8; 32]; padded]; let block_rows = block_rows_for_group(matrices, group, max_height); - let hasher = Blake3; + // SAFETY: the loop covers `0..max_height` in contiguous chunks and initializes + // each via `hash_raw_multi_rows_uninit`. + unsafe { + blake3_simd::alloc_and_fill_digests(padded, max_height, |dst| { + for start in (0..max_height).step_by(block_rows) { + let n_rows = (max_height - start).min(block_rows); + let blocks: Vec<(Vec, usize)> = group + .iter() + .map(|&idx| { + let m = &matrices[idx]; + (m.read_raw_rows(start, n_rows), m.row_bytes()) + }) + .collect(); + blake3_simd::hash_raw_multi_rows_uninit(&blocks, &mut dst[start..start + n_rows]); + } + }) + } +} - for start in (0..max_height).step_by(block_rows) { - let n_rows = (max_height - start).min(block_rows); - let blocks: Vec<(Vec, usize)> = group - .iter() - .map(|&idx| { - let m = &matrices[idx]; - (m.read_raw_rows(start, n_rows), m.row_bytes()) - }) - .collect(); - digests[start..start + n_rows] - .par_iter_mut() - .enumerate() - .for_each(|(local_row, digest)| { - *digest = if let [(buf, row_bytes)] = blocks.as_slice() { - hasher.hash_slice(&buf[local_row * *row_bytes..(local_row + 1) * *row_bytes]) - } else { - hasher.hash_iter_slices(blocks.iter().map(|(buf, row_bytes)| { - &buf[local_row * *row_bytes..(local_row + 1) * *row_bytes] - })) - }; - }); +fn compress_layer_binary(prev_layer: &[[u8; 32]]) -> Vec<[u8; 32]> { + let raw_next = prev_layer.len() / 2; + let next_len_padded = padded_len_binary(raw_next); + // SAFETY: `compress_pairs_uninit` initializes every element of `dst` (`0..raw_next`). + unsafe { + blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { + blake3_simd::compress_pairs_uninit(prev_layer, dst); + }) } - digests } -fn compress_layer_binary( +fn compress_and_inject_prehashed( prev_layer: &[[u8; 32]], - compress: &Blake3CompressionFunction, + rows_digests: &[[u8; 32]], ) -> Vec<[u8; 32]> { + let next_len = rows_digests.len(); let raw_next = prev_layer.len() / 2; let next_len_padded = padded_len_binary(raw_next); - let mut next_digests = vec![[0u8; 32]; next_len_padded]; - next_digests[..raw_next] - .par_iter_mut() - .enumerate() - .for_each(|(i, digest)| { - *digest = compress.compress([prev_layer[2 * i], prev_layer[2 * i + 1]]); - }); - next_digests + // SAFETY: initializes `dst[..next_len]` and (if `raw_next > next_len`) + // `dst[next_len..raw_next]`, covering all of `0..raw_next`. + unsafe { + blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { + blake3_simd::compress_and_inject_from_digests_uninit( + prev_layer, + rows_digests, + &mut dst[..next_len], + ); + if raw_next > next_len { + let zeros = vec![[0u8; 32]; raw_next - next_len]; + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * next_len..], + &zeros, + &mut dst[next_len..raw_next], + ); + } + }) + } +} + +fn compress_and_inject_in_memory>( + prev_layer: &[[u8; 32]], + inject_group: &[&M], +) -> Vec<[u8; 32]> { + let next_len = inject_group[0].height(); + let raw_next = prev_layer.len() / 2; + let next_len_padded = padded_len_binary(raw_next); + const BLOCK_ROWS: usize = 1 << 14; + let mut row_digests = vec![[0u8; 32]; next_len.min(BLOCK_ROWS)]; + + // SAFETY: initializes `dst[..next_len]` in contiguous chunks and (if + // `raw_next > next_len`) `dst[next_len..raw_next]`, covering all of `0..raw_next`. + unsafe { + blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { + for start in (0..next_len).step_by(BLOCK_ROWS) { + let n_rows = (next_len - start).min(BLOCK_ROWS); + blake3_simd::hash_matrix_rows(inject_group, start, &mut row_digests[..n_rows]); + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * start..], + &row_digests[..n_rows], + &mut dst[start..start + n_rows], + ); + } + + if raw_next > next_len { + let zeros = vec![[0u8; 32]; raw_next - next_len]; + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * next_len..], + &zeros, + &mut dst[next_len..raw_next], + ); + } + }) + } } fn compress_and_inject_streaming( prev_layer: &[[u8; 32]], matrices: &[SpilledMatrix], inject_group: &[usize], - compress: &Blake3CompressionFunction, ) -> Vec<[u8; 32]> { let next_len = matrices[inject_group[0]].height(); let raw_next = prev_layer.len() / 2; let next_len_padded = padded_len_binary(raw_next); - let mut next_digests = vec![[0u8; 32]; next_len_padded]; let block_rows = block_rows_for_group(matrices, inject_group, next_len); - let hasher = Blake3; - - for start in (0..next_len).step_by(block_rows) { - let n_rows = (next_len - start).min(block_rows); - let blocks: Vec<(Vec, usize)> = inject_group - .iter() - .map(|&idx| { - let m = &matrices[idx]; - (m.read_raw_rows(start, n_rows), m.row_bytes()) - }) - .collect(); - next_digests[start..start + n_rows] - .par_iter_mut() - .enumerate() - .for_each(|(local_row, out)| { - let i = start + local_row; - let digest = compress.compress([prev_layer[2 * i], prev_layer[2 * i + 1]]); - let rows_digest = if let [(buf, row_bytes)] = blocks.as_slice() { - hasher.hash_slice(&buf[local_row * *row_bytes..(local_row + 1) * *row_bytes]) - } else { - hasher.hash_iter_slices(blocks.iter().map(|(buf, row_bytes)| { - &buf[local_row * *row_bytes..(local_row + 1) * *row_bytes] - })) - }; - *out = compress.compress([digest, rows_digest]); - }); - } + let mut row_digests = vec![[0u8; 32]; block_rows]; + + // SAFETY: initializes `dst[..next_len]` in contiguous chunks and (if + // `raw_next > next_len`) `dst[next_len..raw_next]`, covering all of `0..raw_next`. + unsafe { + blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { + for start in (0..next_len).step_by(block_rows) { + let n_rows = (next_len - start).min(block_rows); + let blocks: Vec<(Vec, usize)> = inject_group + .iter() + .map(|&idx| { + let m = &matrices[idx]; + (m.read_raw_rows(start, n_rows), m.row_bytes()) + }) + .collect(); + blake3_simd::hash_raw_multi_rows(&blocks, &mut row_digests[..n_rows]); + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * start..], + &row_digests[..n_rows], + &mut dst[start..start + n_rows], + ); + } - for (i, out) in next_digests[next_len..raw_next].iter_mut().enumerate() { - let idx = next_len + i; - let digest = compress.compress([prev_layer[2 * idx], prev_layer[2 * idx + 1]]); - *out = compress.compress([digest, [0u8; 32]]); + if raw_next > next_len { + let zeros = vec![[0u8; 32]; raw_next - next_len]; + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * next_len..], + &zeros, + &mut dst[next_len..raw_next], + ); + } + }) } - - next_digests } -/// Prover data for [`SpillableMmcs`]: either Plonky3's standard in-memory -/// [`p3_merkle_tree::MerkleTree`] or a disk-spilled [`SpilledMerkleTree`]. +/// Prover data for [`SpillableMmcs`]: either an in-memory multi-buffer SIMD +/// BLAKE3 Merkle tree or a disk-spilled [`SpilledMerkleTree`]. pub struct SpillableMmcsData(SpillableMmcsDataInner); enum SpillableMmcsDataInner { InMemory { - tree: CpuData, + tree: FastInMemoryMerkleTree, /// Optional 1× original traces retained for zero-FFT lazy lookup /// evaluation in in-memory mode; released once stage-2 completes. retained_traces: Mutex>>>, @@ -794,12 +1113,12 @@ impl SpillableMmcsData { } } -/// CPU MMCS supporting both in-memory commitments (default, zero overhead) and -/// disk-spilled commitments with identical commitments and opening proofs. +/// CPU MMCS supporting both in-memory commitments (default, accelerated via +/// multi-buffer SIMD BLAKE3) and disk-spilled commitments with identical +/// commitments and opening proofs. #[derive(Clone, Debug)] pub struct SpillableMmcs { cpu: CpuMmcs, - compress: Blake3CompressionFunction, } impl SpillableMmcs { @@ -809,8 +1128,7 @@ impl SpillableMmcs { cap_height: usize, ) -> Self { Self { - cpu: CpuMmcs::new(hash, compress.clone(), cap_height), - compress, + cpu: CpuMmcs::new(hash, compress, cap_height), } } @@ -823,7 +1141,8 @@ impl SpillableMmcs { ldes: Vec>, original_traces: Vec>>, ) -> SpillCommitResult { - let (commitment, tree) = self.cpu.commit(ldes); + let tree = FastInMemoryMerkleTree::build(ldes); + let commitment = tree.cap(self.cap_height()); ( commitment, SpillableMmcsData(SpillableMmcsDataInner::InMemory { @@ -833,13 +1152,14 @@ impl SpillableMmcs { ) } - pub(crate) fn commit_spilled( + pub(crate) fn commit_spilled_prehashed( &self, matrices: Vec, original_traces: Vec>, + prehashed: Vec>>, ) -> SpillCommitResult { let count = matrices.len(); - let tree = SpilledMerkleTree::build(matrices, original_traces, &self.compress); + let tree = SpilledMerkleTree::build_with_prehashed(matrices, original_traces, prehashed); let cap = tree.cap(self.cap_height()); let materialized = (0..count).map(|_| OnceLock::new()).collect(); ( @@ -852,17 +1172,21 @@ impl SpillableMmcs { ) } + #[cfg(test)] + pub(crate) fn commit_spilled( + &self, + matrices: Vec, + original_traces: Vec>, + ) -> SpillCommitResult { + self.commit_spilled_prehashed(matrices, original_traces, Vec::new()) + } + pub(crate) fn matrix_dimensions>( &self, prover_data: &SpillableMmcsData, ) -> Vec { match &prover_data.0 { - SpillableMmcsDataInner::InMemory { tree, .. } => self - .cpu - .get_matrices(tree) - .into_iter() - .map(Matrix::dimensions) - .collect(), + SpillableMmcsDataInner::InMemory { tree, .. } => tree.dimensions(), SpillableMmcsDataInner::Spilled { tree, .. } => tree.dimensions(), } } @@ -876,7 +1200,8 @@ impl Mmcs for SpillableMmcs { type Error = >::Error; fn commit>(&self, inputs: Vec) -> (Self::Commitment, Self::ProverData) { - let (commitment, tree) = self.cpu.commit(inputs); + let tree = FastInMemoryMerkleTree::build(inputs); + let commitment = tree.cap(self.cap_height()); ( commitment, SpillableMmcsData(SpillableMmcsDataInner::InMemory { @@ -893,7 +1218,7 @@ impl Mmcs for SpillableMmcs { ) -> BatchOpening { match &prover_data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { - let (opened_values, opening_proof) = self.cpu.open_batch(index, tree).unpack(); + let (opened_values, opening_proof) = tree.open_batch(index, self.cap_height()); BatchOpening::new(opened_values, opening_proof) } SpillableMmcsDataInner::Spilled { tree, .. } => { @@ -905,7 +1230,7 @@ impl Mmcs for SpillableMmcs { fn get_matrices<'a, M: Matrix>(&self, prover_data: &'a Self::ProverData) -> Vec<&'a M> { match &prover_data.0 { - SpillableMmcsDataInner::InMemory { tree, .. } => self.cpu.get_matrices(tree), + SpillableMmcsDataInner::InMemory { tree, .. } => tree.leaves.iter().collect(), SpillableMmcsDataInner::Spilled { tree, materialized, @@ -921,14 +1246,14 @@ impl Mmcs for SpillableMmcs { fn get_matrix_heights>(&self, prover_data: &Self::ProverData) -> Vec { match &prover_data.0 { - SpillableMmcsDataInner::InMemory { tree, .. } => self.cpu.get_matrix_heights(tree), + SpillableMmcsDataInner::InMemory { tree, .. } => tree.matrix_heights(), SpillableMmcsDataInner::Spilled { tree, .. } => tree.matrix_heights(), } } fn get_max_height>(&self, prover_data: &Self::ProverData) -> usize { match &prover_data.0 { - SpillableMmcsDataInner::InMemory { tree, .. } => self.cpu.get_max_height(tree), + SpillableMmcsDataInner::InMemory { tree, .. } => tree.max_height(), SpillableMmcsDataInner::Spilled { tree, .. } => tree.max_height(), } } @@ -956,7 +1281,7 @@ impl Mmcs for SpillableMmcs { ) -> (Vec>>, Self::MultiProof) { match &prover_data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { - self.cpu.open_multi_batch(indices, tree) + tree.open_multi_batch(indices, self.cap_height()) } SpillableMmcsDataInner::Spilled { tree, .. } => { tree.open_multi_batch(indices, self.cap_height()) @@ -1026,10 +1351,11 @@ impl SpillableTwoAdicFriPcs { .to_row_major_matrix() } - pub(crate) fn commit_spilled_ldes( + pub(crate) fn commit_spilled_ldes_prehashed( &self, spilled_ldes: Vec, original_traces: Option>>, + prehashed: Vec>>, ) -> SpillCommitResult { let min_height = 1usize << self.fri.log_blowup; for lde in &spilled_ldes { @@ -1040,7 +1366,8 @@ impl SpillableTwoAdicFriPcs { ); } let originals = original_traces.unwrap_or_default(); - self.mmcs.commit_spilled(spilled_ldes, originals) + self.mmcs + .commit_spilled_prehashed(spilled_ldes, originals, prehashed) } pub(crate) fn commit_in_memory_ldes( @@ -1062,7 +1389,8 @@ impl SpillableTwoAdicFriPcs { /// /// Returns `None` if the iterator yields no items. When disk spilling is /// enabled, processes one matrix at a time so neither all 1× traces nor all - /// 4× LDEs coexist in memory simultaneously. + /// 4× LDEs coexist in memory simultaneously, hashing unique-height matrices + /// in RAM before dropping them to avoid a second disk pass. pub(crate) fn commit_streaming_with_originals( &self, evaluations: &mut dyn Iterator< @@ -1077,6 +1405,8 @@ impl SpillableTwoAdicFriPcs { let mut orig_pack: Option = None; let mut spilled_ldes = Vec::new(); let mut spilled_originals = Vec::new(); + let mut prehashed: Vec>> = Vec::new(); + let mut first_idx_for_height: HashMap> = HashMap::new(); for (domain, evals, retain_1x) in evaluations { if retain_1x { @@ -1086,8 +1416,26 @@ impl SpillableTwoAdicFriPcs { spilled_originals.push(None); } let lde = self.compute_lde(domain, evals); + let lde_height = lde.height(); + let idx = spilled_ldes.len(); let writer = lde_pack.get_or_insert_with(|| SpillPackWriter::create(dir)); - spilled_ldes.push(writer.append_matrix(&lde)); + match first_idx_for_height.get_mut(&lde_height) { + None => { + let (spilled, digests) = writer.append_matrix_and_hash(&lde); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + first_idx_for_height.insert(lde_height, Some(idx)); + } + Some(prev) => { + // A second matrix shares this height; drop the single-matrix + // prehash so this height group streams concatenated rows. + if let Some(prev_idx) = prev.take() { + prehashed[prev_idx] = None; + } + spilled_ldes.push(writer.append_matrix(&lde)); + prehashed.push(None); + } + } // `lde` drops here before pulling the next matrix. } @@ -1105,7 +1453,7 @@ impl SpillableTwoAdicFriPcs { } else { None }; - Some(self.commit_spilled_ldes(spilled_ldes, originals)) + Some(self.commit_spilled_ldes_prehashed(spilled_ldes, originals, prehashed)) } else { let mut ldes = Vec::new(); let mut originals = Vec::new(); @@ -1161,12 +1509,30 @@ where if let Some(dir) = &self.spill_dir { let mut pack = SpillPackWriter::create(dir); let mut spilled_ldes = Vec::new(); + let mut prehashed: Vec>> = Vec::new(); + let mut first_idx_for_height: HashMap> = HashMap::new(); for (domain, evals) in evaluations { let lde = self.compute_lde(domain, evals); - spilled_ldes.push(pack.append_matrix(&lde)); + let h = lde.height(); + let idx = spilled_ldes.len(); + match first_idx_for_height.get_mut(&h) { + None => { + let (spilled, digests) = pack.append_matrix_and_hash(&lde); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + first_idx_for_height.insert(h, Some(idx)); + } + Some(prev) => { + if let Some(prev_idx) = prev.take() { + prehashed[prev_idx] = None; + } + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } + } } pack.flush(); - self.commit_spilled_ldes(spilled_ldes, None) + self.commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed) } else { let ldes: Vec<_> = evaluations .into_iter() @@ -1197,13 +1563,26 @@ where ); } if let Some(dir) = &self.spill_dir { + let mut height_counts: HashMap = HashMap::new(); + for lde in &ldes { + *height_counts.entry(lde.height()).or_insert(0) += 1; + } let mut pack = SpillPackWriter::create(dir); let mut spilled = Vec::with_capacity(ldes.len()); + let mut prehashed = Vec::with_capacity(ldes.len()); for lde in ldes { - spilled.push(pack.append_matrix(&lde)); + if height_counts[&lde.height()] == 1 { + let (sp, digests) = pack.append_matrix_and_hash(&lde); + spilled.push(sp); + prehashed.push(Some(digests)); + } else { + spilled.push(pack.append_matrix(&lde)); + prehashed.push(None); + } } pack.flush(); - self.mmcs.commit_spilled(spilled, Vec::new()) + self.mmcs + .commit_spilled_prehashed(spilled, Vec::new(), prehashed) } else { self.mmcs.commit(ldes) } @@ -1217,7 +1596,7 @@ where ) -> Self::EvaluationsOnDomain<'a> { match &prover_data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { - let lde = self.mmcs.cpu.get_matrices(tree)[idx]; + let lde = &tree.leaves[idx]; if domain.shift() == Val::GENERATOR && lde.height() >= domain.size() { return lde.split_rows(domain.size()).0.as_cow().bit_reverse_rows(); } @@ -1284,13 +1663,7 @@ where .expect("No Matrices Supplied?"); let log_global_max_height = log2_strict_usize(global_max_height); - let coset = { - let coset = - TwoAdicMultiplicativeCoset::new(Val::GENERATOR, log_global_max_height).unwrap(); - let mut coset_points: Vec = coset.iter().collect(); - reverse_slice_index_bits(&mut coset_points); - coset_points - }; + let coset = build_bitrev_coset(log_global_max_height); let inv_denoms = compute_inverse_denominators_from_dims(&dims_and_points, &coset); drop(coset); @@ -1319,7 +1692,7 @@ where } match &data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { - let mat = self.mmcs.cpu.get_matrices(tree)[mat_idx]; + let mat = &tree.leaves[mat_idx]; let mat_view = mat.as_view(); let (low_coset, _) = mat_view.split_rows(h); points_for_mat @@ -1415,7 +1788,7 @@ where match &data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { - let mat = self.mmcs.cpu.get_matrices(tree)[mat_idx]; + let mat = &tree.leaves[mat_idx]; let mat_compressed: Vec = mat .as_view() .rowwise_packed_dot_product::(&packed_alpha_powers) @@ -1541,6 +1914,151 @@ impl, FriMmcs> SpillableTwoAdicFriPcs } } +/// Builds the bit-reversed evaluation coset `GENERATOR * ` of size +/// `1 << log_size` in parallel chunks. +fn build_bitrev_coset(log_size: usize) -> Vec { + let size = 1usize << log_size; + let g = Val::two_adic_generator(log_size); + let mut coset = Val::zero_vec(size); + const CHUNK: usize = 4096; + if size <= CHUNK { + let mut cur = Val::GENERATOR; + for slot in &mut coset { + *slot = cur; + cur *= g; + } + } else { + coset + .par_chunks_mut(CHUNK) + .enumerate() + .for_each(|(chunk_idx, chunk)| { + let mut cur = Val::GENERATOR + * g.exp_u64(u64::try_from(chunk_idx * CHUNK).expect("coset index exceeds u64")); + for slot in chunk { + *slot = cur; + cur *= g; + } + }); + } + reverse_slice_index_bits(&mut coset); + coset +} + +#[inline] +fn invert_lanes_in_place(lanes: &[Val], invs: &mut [Val]) { + let n = lanes.len(); + if n == 0 { + return; + } + let mut acc = Val::ONE; + for (slot, &v) in invs.iter_mut().zip(lanes) { + *slot = acc; + acc *= v; + } + let mut inv = acc.inverse(); + for i in (0..n).rev() { + invs[i] *= inv; + inv *= lanes[i]; + } +} + +struct NormScratch { + reals: Vec, + norms: Vec, + prefixes: Vec, + lane_invs: Vec, +} + +/// Computes `[(z - x)^{-1} for x in coset]` in `Goldilocks[X]/(X^2 - W)` using +/// the base-field norm trick: +/// +/// ```text +/// (z_0 - x + z_1·X)^{-1} = ((z_0 - x) - z_1·X) / ((z_0 - x)^2 - W·z_1^2) +/// ``` +/// +/// Every chunk runs Montgomery batch inversion in the base field `PackedVal` +/// inside L1 cache (3× fewer base multiplications than extension-field batch +/// inversion, SIMD-vectorized across `PackedVal::WIDTH` lanes, parallelized +/// across all cores, and with zero intermediate `diffs` allocation). +fn goldilocks_quadratic_inverse_denominators(z: ExtVal, coset: &[Val]) -> Vec { + const CHUNK: usize = 1024; + let coords = >::as_basis_coefficients_slice(&z); + let z0 = coords[0]; + let z1 = coords[1]; + let neg_z1 = -z1; + let w = >::W; + let w_z1_sq = w * z1 * z1; + + let pw = PackedVal::WIDTH; + let packs_per_chunk = CHUNK / pw; + let mut out = ExtVal::zero_vec(coset.len()); + + let process_chunk = |scratch: &mut NormScratch, x_chunk: &[Val], out_chunk: &mut [ExtVal]| { + let (x_packed, x_tail) = PackedVal::pack_slice_with_suffix(x_chunk); + let n_packs = x_packed.len(); + if n_packs > 0 { + let z0_p = PackedVal::from(z0); + let neg_z1_p = PackedVal::from(neg_z1); + let w_z1_sq_p = PackedVal::from(w_z1_sq); + let mut acc = PackedVal::ONE; + for (i, &xp) in x_packed.iter().enumerate() { + let real = z0_p - xp; + let norm = real * real - w_z1_sq_p; + scratch.reals[i] = real; + scratch.norms[i] = norm; + scratch.prefixes[i] = acc; + acc *= norm; + } + invert_lanes_in_place(acc.as_slice(), &mut scratch.lane_invs); + let mut inv = *PackedVal::from_slice(&scratch.lane_invs); + for i in (0..n_packs).rev() { + let inv_norm = scratch.prefixes[i] * inv; + inv *= scratch.norms[i]; + let c0 = scratch.reals[i] * inv_norm; + let c1 = neg_z1_p * inv_norm; + let c0_s = c0.as_slice(); + let c1_s = c1.as_slice(); + let dst = &mut out_chunk[i * pw..(i + 1) * pw]; + for lane in 0..pw { + dst[lane] = ExtVal::new([c0_s[lane], c1_s[lane]]); + } + } + } + if !x_tail.is_empty() { + let tail_out = &mut out_chunk[n_packs * pw..]; + for (&x, dst) in x_tail.iter().zip(tail_out.iter_mut()) { + let real = z0 - x; + let inv_norm = (real * real - w_z1_sq).inverse(); + *dst = ExtVal::new([real * inv_norm, neg_z1 * inv_norm]); + } + } + }; + + if coset.len() <= CHUNK { + let mut scratch = NormScratch { + reals: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + norms: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + prefixes: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + lane_invs: vec![Val::ZERO; pw], + }; + process_chunk(&mut scratch, coset, &mut out); + } else { + out.par_chunks_mut(CHUNK) + .zip(coset.par_chunks(CHUNK)) + .for_each_init( + || NormScratch { + reals: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + norms: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + prefixes: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + lane_invs: vec![Val::ZERO; pw], + }, + |scratch, (out_chunk, x_chunk)| process_chunk(scratch, x_chunk, out_chunk), + ); + } + + out +} + fn compute_inverse_denominators_from_dims( dims_and_points: &[(Vec, &Vec>)], coset: &[Val], @@ -1562,8 +2080,10 @@ fn compute_inverse_denominators_from_dims( max_log_height_for_point .into_iter() .map(|(z, log_height)| { - let diffs: Vec = coset[..(1 << log_height)].iter().map(|&x| z - x).collect(); - (z, batch_multiplicative_inverse(&diffs)) + ( + z, + goldilocks_quadratic_inverse_denominators(z, &coset[..(1 << log_height)]), + ) }) .collect() } @@ -1613,6 +2133,7 @@ fn interpolate_spilled_coset( #[cfg(test)] mod tests { use super::*; + use p3_field::batch_multiplicative_inverse; use rand::rngs::SmallRng; use rand::{RngExt, SeedableRng}; @@ -1647,6 +2168,19 @@ mod tests { let (cpu, spillable) = make_mmcs(cap_height); let (cpu_com, cpu_data) = cpu.commit(mats.to_vec()); + // Also check our SIMD in-memory MMCS matches `CpuMmcs` bit-for-bit. + let (mem_com, mem_data) = spillable.commit(mats.to_vec()); + assert_eq!( + mem_com.roots(), + cpu_com.roots(), + "in-memory SIMD cap mismatch for {tag} (cap_height={cap_height})" + ); + let (cpu_vals, cpu_multi) = cpu.open_multi_batch(query_indices, &cpu_data); + let (mem_vals, mem_multi) = spillable.open_multi_batch(query_indices, &mem_data); + assert_eq!(mem_vals, cpu_vals); + assert_eq!(mem_multi.sibling_hashes, cpu_multi.sibling_hashes); + + // Check spilled (streaming disk hash) path. let mut pack = SpillPackWriter::create(&dir); let spilled_mats: Vec<_> = mats.iter().map(|m| pack.append_matrix(m)).collect(); pack.flush(); @@ -1682,7 +2216,6 @@ mod tests { .expect("CpuMmcs must accept spilled single opening"); } - let (cpu_vals, cpu_multi) = cpu.open_multi_batch(query_indices, &cpu_data); let (spilled_vals, spilled_multi) = spillable.open_multi_batch(query_indices, &spilled_data); assert_eq!(spilled_vals, cpu_vals); @@ -1696,6 +2229,34 @@ mod tests { ) .expect("CpuMmcs must accept spilled multi-batch opening"); + // Also check hash-before-spill (`append_matrix_and_hash` + `commit_spilled_prehashed`). + let mut height_counts: HashMap = HashMap::new(); + for m in mats { + *height_counts.entry(m.height()).or_insert(0) += 1; + } + let mut pack_pre = SpillPackWriter::create(&dir); + let mut sp_pre = Vec::with_capacity(mats.len()); + let mut prehashed = Vec::with_capacity(mats.len()); + for m in mats { + if height_counts[&m.height()] == 1 { + let (sp, digests) = pack_pre.append_matrix_and_hash(m); + sp_pre.push(sp); + prehashed.push(Some(digests)); + } else { + sp_pre.push(pack_pre.append_matrix(m)); + prehashed.push(None); + } + } + pack_pre.flush(); + let (pre_com, pre_data) = spillable.commit_spilled_prehashed(sp_pre, Vec::new(), prehashed); + assert_eq!(pre_com.roots(), cpu_com.roots()); + let (pre_vals, pre_multi) = spillable.open_multi_batch(query_indices, &pre_data); + assert_eq!(pre_vals, cpu_vals); + assert_eq!(pre_multi.sibling_hashes, cpu_multi.sibling_hashes); + assert_eq!(pre_data.materialized_spilled_count(), 0); + drop(pre_data); + drop(pack_pre); + // Ensure nothing materialized the spilled matrices back into RAM. assert_eq!(spilled_data.materialized_spilled_count(), 0); drop(spilled_data); @@ -1867,4 +2428,34 @@ mod tests { assert_eq!(fs::read_dir(&dir).unwrap().count(), 0); let _ = fs::remove_dir_all(&dir); } + + #[test] + fn parallel_bitrev_coset_and_norm_trick_match_reference() { + for log_size in [0usize, 1, 2, 3, 5, 10, 13] { + let expected_coset: Vec = { + let mut pts: Vec = TwoAdicMultiplicativeCoset::new(Val::GENERATOR, log_size) + .unwrap() + .iter() + .collect(); + reverse_slice_index_bits(&mut pts); + pts + }; + let got_coset = build_bitrev_coset(log_size); + assert_eq!(got_coset, expected_coset, "coset mismatch at 2^{log_size}"); + + for point in [ + ExtVal::new([Goldilocks::new(12345), Goldilocks::new(67890)]), + ExtVal::new([Goldilocks::new(987_654_321), Goldilocks::ZERO]), + ExtVal::new([Goldilocks::ZERO, Goldilocks::new(42)]), + ] { + let diffs: Vec = expected_coset.iter().map(|&x| point - x).collect(); + let expected_invs = batch_multiplicative_inverse(&diffs); + let got_invs = goldilocks_quadratic_inverse_denominators(point, &got_coset); + assert_eq!( + got_invs, expected_invs, + "norm-trick inverse mismatch at 2^{log_size}" + ); + } + } + } } diff --git a/src/types.rs b/src/types.rs index d4dccd2..4bbe999 100644 --- a/src/types.rs +++ b/src/types.rs @@ -533,6 +533,17 @@ impl ProofConfig for GoldilocksBlake3Config { let mut spill_pack = spill_dir.map(SpillPackWriter::create); let mut spilled_ldes = Vec::with_capacity(if spill_dir.is_some() { inputs.len() } else { 0 }); + let mut prehashed = Vec::with_capacity(if spill_dir.is_some() { inputs.len() } else { 0 }); + let height_counts: std::collections::HashMap = if spill_dir.is_some() { + let mut counts = std::collections::HashMap::new(); + for input in inputs { + let lde_height = input.lookup_values.height() << self.log_blowup; + *counts.entry(lde_height).or_insert(0) += 1; + } + counts + } else { + std::collections::HashMap::new() + }; let mut in_memory_ldes = Vec::with_capacity(if spill_dir.is_none() { inputs.len() } else { 0 }); let mut intermediates = Vec::with_capacity(inputs.len()); @@ -608,7 +619,14 @@ impl ProofConfig for GoldilocksBlake3Config { let domain = self.pcs.natural_domain_for_degree(stage_2_base.height()); let lde = self.pcs.compute_lde(domain, stage_2_base); if let Some(pack) = &mut spill_pack { - spilled_ldes.push(pack.append_matrix(&lde)); + if height_counts.get(&lde.height()).copied() == Some(1) { + let (spilled, digests) = pack.append_matrix_and_hash(&lde); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } // Drop `lde` immediately before building the next circuit's stage-2 trace. } else { in_memory_ldes.push(lde); @@ -624,7 +642,8 @@ impl ProofConfig for GoldilocksBlake3Config { let (commitment, data) = if let Some(mut pack) = spill_pack { pack.flush(); - self.pcs.commit_spilled_ldes(spilled_ldes, None) + self.pcs + .commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed) } else { self.pcs.commit_in_memory_ldes(in_memory_ldes) }; @@ -644,8 +663,15 @@ impl ProofConfig for GoldilocksBlake3Config { let spill_dir = self.spill_dir()?; let mut pack = SpillPackWriter::create(spill_dir); let mut spilled_ldes = Vec::with_capacity(inputs.len()); + let mut prehashed = Vec::with_capacity(inputs.len()); let dft = self.pcs.quotient_dft(); let log_blowup = self.log_blowup; + let mut height_counts = std::collections::HashMap::new(); + for input in inputs { + let lde_height = + (input.quotient_domain.size() / input.circuit.quotient_degree()) << log_blowup; + *height_counts.entry(lde_height).or_insert(0) += 1; + } for input in inputs { let circuit = input.circuit; @@ -689,11 +715,21 @@ impl ProofConfig for GoldilocksBlake3Config { quotient_degree, ); let lde = lde_from_shifted_coefficients(dft, sliced, log_blowup); - spilled_ldes.push(pack.append_matrix(&lde)); + if height_counts.get(&lde.height()).copied() == Some(1) { + let (spilled, digests) = pack.append_matrix_and_hash(&lde); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } } pack.flush(); - Some(self.pcs.commit_spilled_ldes(spilled_ldes, None)) + Some( + self.pcs + .commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed), + ) } fn canonicalize_proof(proof: &mut crate::prover::Proof) { diff --git a/tests/streaming_spill.rs b/tests/streaming_spill.rs index b8a867d..74333c5 100644 --- a/tests/streaming_spill.rs +++ b/tests/streaming_spill.rs @@ -269,21 +269,57 @@ fn make_config( #[test] fn streaming_and_spilled_proofs_are_byte_identical_across_configs() { // Test matrix: - // (lookup_group_size, log_blowup, cap_height, max_log_arity, pow_bits, work_rows, activate_aux) + // (lookup_group_size, log_blowup, cap_height, max_log_arity, pow_bits, work_rows, activate_aux, fc4336b_blake3_pin) let cases = [ // Default ungrouped lookups, blowup 2, cap 0, binary FRI, sparse inactive preprocessed circuit. - (1usize, 1usize, 0usize, 1usize, 0usize, 16usize, false), + ( + 1usize, + 1usize, + 0usize, + 1usize, + 0usize, + 16usize, + false, + "f227d2e461a5e8219d53a79add0895d331d772813e7a14782d9d603871b7613d", + ), // Grouped lookups k = 2, blowup 4 (q=4 supported), cap 1, higher arity, positive PoW. - (2, 2, 1, 2, 4, 32, false), + ( + 2, + 2, + 1, + 2, + 4, + 32, + false, + "bbb754d7390697ae17394266c2cb262c5c937a3584d5b56646cbf3a8a3b9b7a5", + ), // Grouped lookups k = 3, blowup 2 (q=4 -> log_blowup=2), cap 2, all circuits active. - (3, 2, 2, 1, 0, 16, true), + ( + 3, + 2, + 2, + 1, + 0, + 16, + true, + "ae7b731bf392f7a6988677261ab4ee30f21cac2ac143d018da2b4141e286ea8e", + ), // Grouped lookups k = 4 (5 lookups => groups of 4 and 1!), blowup 2, cap 0. - (4, 2, 0, 2, 3, 16, false), + ( + 4, + 2, + 0, + 2, + 3, + 16, + false, + "cd603a7772b7df77ab3785ed6db70b16a3011849c4e71a276f8ffed7be51622f", + ), ]; for ( case_idx, - &(k, log_blowup, cap_height, max_log_arity, pow_bits, work_rows, activate_aux), + &(k, log_blowup, cap_height, max_log_arity, pow_bits, work_rows, activate_aux, ref_pin), ) in cases.iter().enumerate() { #[cfg(feature = "cuda")] @@ -303,6 +339,12 @@ fn streaming_and_spilled_proofs_are_byte_identical_across_configs() { .verify_multiple_claims(&claim_slices, &proof_base) .expect("baseline proof must verify"); let expected_bytes = proof_base.to_bytes().unwrap(); + assert_eq!( + blake3::hash(&expected_bytes).to_hex().as_str(), + ref_pin, + "case {case_idx}: proof bytes drifted from fc4336b baseline ({} bytes)", + expected_bytes.len() + ); // 2. Lazy lookups in-memory (System::new + SystemWitness::from_stage_1_lazy). let wit_lazy = SystemWitness::from_stage_1_lazy(traces.clone(), &sys_base); @@ -571,6 +613,13 @@ fn streaming_and_spilled_batches_are_byte_identical() { .verify_batch(&batch_base) .expect("baseline batch must verify"); let expected_bytes = batch_base.to_bytes().unwrap(); + #[cfg(not(feature = "cuda"))] + assert_eq!( + blake3::hash(&expected_bytes).to_hex().as_str(), + "d293d541b35ec6bbfa5e64383cbd0559fa9b341578a710a063d9b7fb42eace53", + "batch proof bytes drifted from fc4336b baseline ({} bytes)", + expected_bytes.len() + ); // Disk-spilled + lazy lookups under BOTH Retention::Retain and Retention::Regenerate. let spill_dir = fresh_spill_dir("batch"); From 58da590c3abc9d10413ca7eda19700457d123481 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sat, 21 Nov 2026 21:43:56 -0500 Subject: [PATCH 17/28] Generalize ExtensionOf/ExtensionParams for stock Plonky3 CubicTrinomialExtensionField (X^3 - X - 1) - Replace binomial-only ExtensionOf::W with ExtensionModulus (Base, Binomial { w }, CubicTrinomial) - Implement Field + Algebra + ExtensionOf for stock p3-goldilocks CubicTrinomialExtensionField - Add 6-mul 0-const-mul Karatsuba & schoolbook X^3 - X - 1 expansion in graph.rs and reference eval in eval.rs - Add allocation-free stack fast path (mul3_trinomial) in lookup.rs and AlphaTable::Degree3 + fold_constraints_d3 in prover.rs/eval.rs - Move blake3 to runtime dependencies (already pinned in Cargo.lock) --- Cargo.toml | 2 +- src/cuda/mod.rs | 6 +- src/eval.rs | 82 ++++++-- src/graph.rs | 299 ++++++++++++++++++++++++------ src/lookup.rs | 201 ++++++++++++++++---- src/p3_adapter/field.rs | 43 ++++- src/p3_adapter/spill.rs | 6 +- src/prover.rs | 51 ++++- src/system.rs | 12 +- src/system/tests/lookup_values.rs | 10 +- src/traits/field.rs | 110 ++++++++++- src/traits/mod.rs | 4 +- src/verifier.rs | 2 +- 13 files changed, 686 insertions(+), 142 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d923195..b88c3de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ links = "multi_stark_cuda" [workspace] [dependencies] +blake3 = "1" tracing = "0.1" itertools = { version = "0.14", optional = true } rayon = { version = "1", optional = true } @@ -42,7 +43,6 @@ optional = true features = ["cuda"] [dev-dependencies] -blake3 = "1" criterion = "0.5" p3-baby-bear = { git = "https://github.com/Plonky3/Plonky3", rev = "3152b14a89067c83775a8076cc262ffc48a1fd7c" } rand = "0.10" diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index b220be0..7f78d8d 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -3541,11 +3541,7 @@ mod tests { }; let graph = compile( &spec, - &ExtensionParams { - degree: 2, - w: Goldilocks::from_u64(7), - karatsuba: true, - }, + &ExtensionParams::binomial(2, Goldilocks::from_u64(7), true), ) .unwrap(); let height = 8; diff --git a/src/eval.rs b/src/eval.rs index de40b05..7b667dd 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -5,7 +5,7 @@ //! trees also get a direct recursive evaluator, used as the reference in //! tests (with genuine extension-field arithmetic for `ExtExpr`). -use crate::traits::{Algebra, Field}; +use crate::traits::{Algebra, ExtensionModulus, Field}; use crate::expr::{ColRef, Expr, ExtExpr, RowOffset, Source}; use crate::graph::{ConstraintGraph, ExtensionParams, Node, NodeId}; @@ -142,6 +142,47 @@ impl ConstraintGraph { (acc0, acc1) } + /// Folds the user-constraint roots (`self.zeros`) with interleaved degree-3 + /// alpha-power triples `[c0, c1, c2]` directly off the sweep buffer, + /// avoiding any intermediate `constraint_values` allocation. + #[inline] + pub fn fold_constraints_d3>( + &self, + buf: &[W], + alpha_triples: &[[F; 3]], + ) -> (W, W, W) { + debug_assert!(alpha_triples.len() >= self.zeros.len()); + let mut a0 = W::ZERO; + let mut a1 = W::ZERO; + let mut b0 = W::ZERO; + let mut b1 = W::ZERO; + let mut c0 = W::ZERO; + let mut c1 = W::ZERO; + + let (z_chunks, z_rem) = self.zeros.as_chunks::<2>(); + let (p_chunks, p_rem) = alpha_triples[..self.zeros.len()].as_chunks::<2>(); + for (zc, pc) in z_chunks.iter().zip(p_chunks) { + let v0 = buf[zc[0].index()]; + let v1 = buf[zc[1].index()]; + a0 += v0 * pc[0][0]; + b0 += v0 * pc[0][1]; + c0 += v0 * pc[0][2]; + a1 += v1 * pc[1][0]; + b1 += v1 * pc[1][1]; + c1 += v1 * pc[1][2]; + } + let mut acc0 = a0 + a1; + let mut acc1 = b0 + b1; + let mut acc2 = c0 + c1; + for (z, p) in z_rem.iter().zip(p_rem) { + let v = buf[z.index()]; + acc0 += v * p[0]; + acc1 += v * p[1]; + acc2 += v * p[2]; + } + (acc0, acc1, acc2) + } + /// Folds the user-constraint roots (`self.zeros`) with decomposed alpha /// powers into `acc` (one accumulator per basis coordinate), avoiding any /// intermediate `constraint_values` allocation. @@ -198,8 +239,8 @@ pub fn eval_expr(expr: &Expr, values: &VarValues<'_, F>) -> F { /// Reference evaluation of a frontend extension expression, in genuine /// extension-field arithmetic: coordinates as `Vec` of length D, -/// products reduced mod `X^D − W` (schoolbook — deliberately independent -/// of the compiled Karatsuba path). +/// products reduced modulo `params.modulus` (schoolbook — deliberately +/// independent of the compiled Karatsuba path). pub fn eval_ext_expr( expr: &ExtExpr, values: &VarValues<'_, F>, @@ -233,18 +274,35 @@ pub fn eval_ext_expr( ExtExpr::Mul(a, b) => { let a = eval_ext_expr(a, values, params); let b = eval_ext_expr(b, values, params); - let mut out = vec![F::ZERO; d]; - for i in 0..d { - for j in 0..d { - let term = a[i] * b[j]; - if i + j < d { - out[i + j] += term; - } else { - out[i + j - d] += params.w * term; + match params.modulus { + ExtensionModulus::Base => { + assert_eq!(d, 1); + vec![a[0] * b[0]] + } + ExtensionModulus::Binomial { w } => { + let mut out = vec![F::ZERO; d]; + for i in 0..d { + for j in 0..d { + let term = a[i] * b[j]; + if i + j < d { + out[i + j] += term; + } else { + out[i + j - d] += w * term; + } + } } + out + } + ExtensionModulus::CubicTrinomial => { + assert_eq!(d, 3); + let t0 = a[0] * b[0]; + let t1 = a[0] * b[1] + a[1] * b[0]; + let t2 = a[0] * b[2] + a[1] * b[1] + a[2] * b[0]; + let t3 = a[1] * b[2] + a[2] * b[1]; + let t4 = a[2] * b[2]; + vec![t0 + t3, t1 + t3 + t4, t2 + t4] } } - out } } } diff --git a/src/graph.rs b/src/graph.rs index 96df8df..4d70ae8 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; -use crate::traits::Field; +use crate::traits::{ExtensionModulus, ExtensionOf, Field}; use crate::expr::{CircuitSpec, ColRef, Expr, ExtExpr, RowOffset, Source}; use crate::lookup::Lookup; @@ -47,17 +47,64 @@ pub enum Node { Neg(NodeId), } -/// Binomial extension parameters: `X^degree = w`. -#[derive(Copy, Clone, Debug)] +/// Extension-field parameters controlling coordinate expansion of [`ExtExpr`]. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct ExtensionParams { pub degree: usize, - pub w: F, - /// Emit the 3-multiplication Karatsuba form for D=2 products - /// (matching native extension-multiplication cost). Schoolbook - /// otherwise; both are exposed so tests can cross-check them. + pub modulus: ExtensionModulus, + /// Emit Karatsuba products for D=2 binomial (3 muls) and D=3 cubic + /// trinomial (6 muls, 0 constant muls). Schoolbook otherwise; both are + /// exposed so tests can cross-check them. pub karatsuba: bool, } +impl ExtensionParams { + /// Degree-1 base-field extension parameters. + pub const fn base() -> Self { + Self { + degree: 1, + modulus: ExtensionModulus::Base, + karatsuba: false, + } + } + + /// Binomial extension `X^degree - w`. + pub const fn binomial(degree: usize, w: F, karatsuba: bool) -> Self { + Self { + degree, + modulus: ExtensionModulus::Binomial { w }, + karatsuba, + } + } + + /// Cubic trinomial extension `X^3 - X - 1`. + pub const fn cubic_trinomial(karatsuba: bool) -> Self { + Self { + degree: 3, + modulus: ExtensionModulus::CubicTrinomial, + karatsuba, + } + } + + /// Read extension parameters from an [`ExtensionOf`] implementation. + pub fn for_extension>() -> Self + where + F: Field, + { + let degree = EF::D; + let modulus = EF::MODULUS; + let karatsuba = matches!( + (degree, modulus), + (2, ExtensionModulus::Binomial { .. }) | (3, ExtensionModulus::CubicTrinomial) + ); + Self { + degree, + modulus, + karatsuba, + } + } +} + /// A compiled constraint graph: the hash-consed DAG of expression nodes /// shared by all constraints and lookups of one circuit. #[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq, Debug)] @@ -474,54 +521,198 @@ impl Interner { if self.is_scalar(b) { return a.iter().map(|&ak| self.mul(b[0], ak)).collect(); } - if d == 2 && params.karatsuba { - // (a0 + a1 X)(b0 + b1 X) mod (X² − W), 3 multiplications: - // c0 = a0 b0 + W · a1 b1 - // c1 = (a0 + a1)(b0 + b1) − a0 b0 − a1 b1 - let p0 = self.mul(a[0], b[0]); - let p1 = self.mul(a[1], b[1]); - let sa = self.add(a[0], a[1]); - let sb = self.add(b[0], b[1]); - let s = self.mul(sa, sb); - let w = self.constant(params.w); - let wp1 = self.mul(w, p1); - let c0 = self.add(p0, wp1); - let t = self.sub(s, p0); - let c1 = self.sub(t, p1); - return vec![c0, c1]; - } - // Schoolbook: c_k = Σ_{i+j=k} a_i b_j + W · Σ_{i+j=k+D} a_i b_j. - let w = self.constant(params.w); - (0..d) - .map(|k| { - let mut low: Option = None; - let mut high: Option = None; - for (i, &ai) in a.iter().enumerate() { - for (j, &bj) in b.iter().enumerate() { - if i + j == k { - let term = self.mul(ai, bj); - low = Some(match low { - Some(acc) => self.add(acc, term), - None => term, - }); - } else if i + j == k + d { - let term = self.mul(ai, bj); - high = Some(match high { - Some(acc) => self.add(acc, term), - None => term, - }); - } - } + match params.modulus { + ExtensionModulus::Base => { + debug_assert_eq!(d, 1); + vec![self.mul(a[0], b[0])] + } + ExtensionModulus::CubicTrinomial => { + debug_assert_eq!(d, 3); + if params.karatsuba { + // (a0 + a1 X + a2 X^2)(b0 + b1 X + b2 X^2) mod (X^3 - X - 1), + // 6 multiplications, 0 constant multiplications: + // v0 = a0 b0, v1 = a1 b1, v2 = a2 b2 + // m01 = (a0 + a1)(b0 + b1) - v0 - v1 + // m02 = (a0 + a2)(b0 + b2) - v0 - v2 + // m12 = (a1 + a2)(b1 + b2) - v1 - v2 + // c0 = v0 + m12 + // c1 = m01 + m12 + v2 + // c2 = m02 + v1 + v2 + let v0 = self.mul(a[0], b[0]); + let v1 = self.mul(a[1], b[1]); + let v2 = self.mul(a[2], b[2]); + + let s01_a = self.add(a[0], a[1]); + let s01_b = self.add(b[0], b[1]); + let p01 = self.mul(s01_a, s01_b); + let t01 = self.sub(p01, v0); + let m01 = self.sub(t01, v1); + + let s02_a = self.add(a[0], a[2]); + let s02_b = self.add(b[0], b[2]); + let p02 = self.mul(s02_a, s02_b); + let t02 = self.sub(p02, v0); + let m02 = self.sub(t02, v2); + + let s12_a = self.add(a[1], a[2]); + let s12_b = self.add(b[1], b[2]); + let p12 = self.mul(s12_a, s12_b); + let t12 = self.sub(p12, v1); + let m12 = self.sub(t12, v2); + + let c0 = self.add(v0, m12); + let c1_0 = self.add(m01, m12); + let c1 = self.add(c1_0, v2); + let c2_0 = self.add(m02, v1); + let c2 = self.add(c2_0, v2); + vec![c0, c1, c2] + } else { + // Schoolbook mod (X^3 - X - 1): X^3 = X + 1, X^4 = X^2 + X. + let t0 = self.mul(a[0], b[0]); + let a0b1 = self.mul(a[0], b[1]); + let a1b0 = self.mul(a[1], b[0]); + let t1 = self.add(a0b1, a1b0); + let a0b2 = self.mul(a[0], b[2]); + let a1b1 = self.mul(a[1], b[1]); + let a2b0 = self.mul(a[2], b[0]); + let t2_0 = self.add(a0b2, a1b1); + let t2 = self.add(t2_0, a2b0); + let a1b2 = self.mul(a[1], b[2]); + let a2b1 = self.mul(a[2], b[1]); + let t3 = self.add(a1b2, a2b1); + let t4 = self.mul(a[2], b[2]); + + let c0 = self.add(t0, t3); + let c1_0 = self.add(t1, t3); + let c1 = self.add(c1_0, t4); + let c2 = self.add(t2, t4); + vec![c0, c1, c2] } - let low = low.expect("k < d always has low terms"); - match high { - Some(high) => { - let high = self.mul(w, high); - self.add(low, high) - } - None => low, + } + ExtensionModulus::Binomial { w: modulus_w } => { + if d == 2 && params.karatsuba { + // (a0 + a1 X)(b0 + b1 X) mod (X² − W), 3 multiplications: + // c0 = a0 b0 + W · a1 b1 + // c1 = (a0 + a1)(b0 + b1) − a0 b0 − a1 b1 + let p0 = self.mul(a[0], b[0]); + let p1 = self.mul(a[1], b[1]); + let sa = self.add(a[0], a[1]); + let sb = self.add(b[0], b[1]); + let s = self.mul(sa, sb); + let w = self.constant(modulus_w); + let wp1 = self.mul(w, p1); + let c0 = self.add(p0, wp1); + let t = self.sub(s, p0); + let c1 = self.sub(t, p1); + return vec![c0, c1]; } - }) - .collect() + // Schoolbook: c_k = Σ_{i+j=k} a_i b_j + W · Σ_{i+j=k+D} a_i b_j. + let w = self.constant(modulus_w); + (0..d) + .map(|k| { + let mut low: Option = None; + let mut high: Option = None; + for (i, &ai) in a.iter().enumerate() { + for (j, &bj) in b.iter().enumerate() { + if i + j == k { + let term = self.mul(ai, bj); + low = Some(match low { + Some(acc) => self.add(acc, term), + None => term, + }); + } else if i + j == k + d { + let term = self.mul(ai, bj); + high = Some(match high { + Some(acc) => self.add(acc, term), + None => term, + }); + } + } + } + let low = low.expect("k < d always has low terms"); + match high { + Some(high) => { + let high = self.mul(w, high); + self.add(low, high) + } + None => low, + } + }) + .collect() + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::eval::{VarValues, eval_ext_expr}; + use crate::traits::{Algebra, ExtensionOf}; + use p3_field::extension::CubicTrinomialExtensionField; + use p3_goldilocks::Goldilocks; + + #[test] + fn cubic_trinomial_graph_compilation_matches_reference_and_p3() { + type Ext3 = CubicTrinomialExtensionField; + + let a = ExtExpr::Coords(vec![Expr::main(0), Expr::main(1), Expr::main(2)]); + let b = ExtExpr::Coords(vec![Expr::main(3), Expr::main(4), Expr::main(5)]); + let c = ExtExpr::Coords(vec![ + Expr::main_next(0), + Expr::main_next(1), + Expr::main_next(2), + ]); + let expr = a * b + c * ExtExpr::from(Expr::main(3)); + + let spec = CircuitSpec { + main_width: 6, + preprocessed_width: 0, + stage2_width: 0, + num_publics: 0, + constraints: vec![], + ext_constraints: vec![expr.clone()], + lookups: vec![], + }; + let karatsuba = compile(&spec, &ExtensionParams::cubic_trinomial(true)).unwrap(); + let schoolbook = compile(&spec, &ExtensionParams::cubic_trinomial(false)).unwrap(); + + let main_cur: Vec = (1..=6u64) + .map(|i| Goldilocks::from_u64(i * 19 + 3)) + .collect(); + let main_next: Vec = (1..=6u64) + .map(|i| Goldilocks::from_u64(i * 31 + 7)) + .collect(); + let empty: [Goldilocks; 0] = []; + let view = VarValues { + preprocessed: [&empty, &empty], + main: [&main_cur, &main_next], + stage2: [&empty, &empty], + publics: &empty, + is_first_row: Goldilocks::ZERO, + is_last_row: Goldilocks::ZERO, + is_transition: Goldilocks::ONE, + }; + + let ref_vals = eval_ext_expr(&expr, &view, &ExtensionParams::cubic_trinomial(false)); + let k_vals = karatsuba.evaluate_constraints(&view); + let s_vals = schoolbook.evaluate_constraints(&view); + + // Compare against native Plonky3 CubicTrinomialExtensionField arithmetic. + let p3_a = Ext3::from_basis_coefficients_fn(|i| main_cur[i]); + let p3_b = Ext3::from_basis_coefficients_fn(|i| main_cur[3 + i]); + let p3_c = Ext3::from_basis_coefficients_fn(|i| main_next[i]); + let p3_res = p3_a * p3_b + p3_c * main_cur[3]; + assert_eq!(ref_vals.as_slice(), p3_res.as_basis_coefficients_slice()); + + // `zeros` are canonicalized (sorted by node id), so compare as sorted sets. + let mut sorted_ref = ref_vals; + let mut sorted_k = k_vals; + let mut sorted_s = s_vals; + sorted_ref.sort(); + sorted_k.sort(); + sorted_s.sort(); + assert_eq!(sorted_k, sorted_ref); + assert_eq!(sorted_s, sorted_ref); } } diff --git a/src/lookup.rs b/src/lookup.rs index b7be228..f7f06d9 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -46,7 +46,7 @@ //! stack. use crate::eval::VarValues; -use crate::traits::{Algebra, ExtensionOf, Field}; +use crate::traits::{Algebra, ExtensionModulus, ExtensionOf, Field}; use p3_matrix::{Matrix, dense::RowMajorMatrix}; use p3_maybe_rayon::prelude::*; @@ -127,23 +127,40 @@ pub fn logup_constraint_count(num_lookups: usize, group_size: usize, d: usize) - lookup_groups(num_lookups, group_size) * d } -/// Coordinate product in the binomial extension `X^d = w`, schoolbook: -/// `out[k] = Σ_{i+j=k} a_i·b_j + w · Σ_{i+j=k+d} a_i·b_j`. Generic-degree -/// fallback; the hot D=2 path uses [`mul2`]. -fn coord_mul + Copy>(a: &[A], b: &[A], w: F) -> Vec { +/// Coordinate product reduced modulo `modulus`, schoolbook. Generic-degree +/// fallback; the hot D=2 binomial and D=3 cubic trinomial paths use [`mul2`] +/// and [`mul3_trinomial`]. +fn coord_mul + Copy>( + a: &[A], + b: &[A], + modulus: ExtensionModulus, +) -> Vec { let d = a.len(); - let mut out = vec![A::ZERO; d]; - for i in 0..d { - for j in 0..d { - let prod = a[i] * b[j]; - if i + j < d { - out[i + j] += prod; - } else { - out[i + j - d] += prod * w; + match modulus { + ExtensionModulus::Base => { + debug_assert_eq!(d, 1); + vec![a[0] * b[0]] + } + ExtensionModulus::Binomial { w } => { + let mut out = vec![A::ZERO; d]; + for i in 0..d { + for j in 0..d { + let prod = a[i] * b[j]; + if i + j < d { + out[i + j] += prod; + } else { + out[i + j - d] += prod * w; + } + } } + out + } + ExtensionModulus::CubicTrinomial => { + debug_assert_eq!(d, 3); + let (c0, c1, c2) = mul3_trinomial((a[0], a[1], a[2]), (b[0], b[1], b[2])); + vec![c0, c1, c2] } } - out } /// Degree-2 coordinate product `X² = w`, Karatsuba (3 multiplications, @@ -156,6 +173,19 @@ fn mul2 + Copy>(a: (A, A), b: (A, A), w: F) -> (A, A) { (v0 + v1 * w, cross) } +/// Degree-3 cubic trinomial coordinate product `X³ = X + 1`, Karatsuba +/// (6 multiplications, 0 constant multiplications): allocation-free. +#[inline] +fn mul3_trinomial + Copy>(a: (A, A, A), b: (A, A, A)) -> (A, A, A) { + let v0 = a.0 * b.0; + let v1 = a.1 * b.1; + let v2 = a.2 * b.2; + let m01 = (a.0 + a.1) * (b.0 + b.1) - v0 - v1; + let m02 = (a.0 + a.2) * (b.0 + b.2) - v0 - v2; + let m12 = (a.1 + a.2) * (b.1 + b.2) - v1 - v2; + (v0 + m12, m01 + m12 + v2, m02 + v1 + v2) +} + /// Directly evaluates the logUp constraint values at one evaluation context, /// in the canonical protocol order: for each lookup (in order) the `d` /// coordinates of its chained-accumulator step — interior steps @@ -186,7 +216,7 @@ pub fn logup_constraint_values + Copy>( publics: &[A], delta_scaled: &[A], is_last_row: A, - w: F, + modulus: ExtensionModulus, d: usize, group_size: usize, out: &mut Vec, @@ -199,7 +229,7 @@ pub fn logup_constraint_values + Copy>( publics, delta_scaled, is_last_row, - w, + modulus, d, group_size, |val| out.push(val), @@ -219,7 +249,7 @@ pub(crate) fn for_each_logup_constraint_value + Copy>( publics: &[A], delta_scaled: &[A], is_last_row: A, - w: F, + modulus: ExtensionModulus, d: usize, group_size: usize, mut emit: impl FnMut(A), @@ -267,11 +297,11 @@ pub(crate) fn for_each_logup_constraint_value + Copy>( } return; } - // Allocation-free Karatsuba fast path for the reference degree-2 + // Allocation-free Karatsuba fast path for the degree-2 binomial // extension; this runs per point-packet on the prover's quotient // domain, so it must not touch the heap. Group products use // prefix/suffix arrays so each Π_{j'≠j} costs one multiplication. - if d == 2 { + if let (2, ExtensionModulus::Binomial { w }) = (d, modulus) { let nv = |id: crate::graph::NodeId| node_vals[id.index()]; let beta = (publics[0], publics[1]); let gamma = (publics[2], publics[3]); @@ -356,6 +386,102 @@ pub(crate) fn for_each_logup_constraint_value + Copy>( return; } + // Allocation-free Karatsuba fast path for the degree-3 cubic trinomial + // extension `X^3 - X - 1` (6 base muls per extension mul, 0 const muls). + if let (3, ExtensionModulus::CubicTrinomial) = (d, modulus) { + let nv = |id: crate::graph::NodeId| node_vals[id.index()]; + let beta = (publics[0], publics[1], publics[2]); + let gamma = (publics[3], publics[4], publics[5]); + let inj = ( + is_last_row * delta_scaled[0], + is_last_row * delta_scaled[1], + is_last_row * delta_scaled[2], + ); + + if lookups.is_empty() { + emit(stage2_next[0] - stage2[0] + inj.0); + emit(stage2_next[1] - stage2[1] + inj.1); + emit(stage2_next[2] - stage2[2] + inj.2); + return; + } + + let last_group = lookups.len().div_ceil(group_size) - 1; + for (g, chunk) in lookups.chunks(group_size).enumerate() { + let source = (stage2[3 * g], stage2[3 * g + 1], stage2[3 * g + 2]); + let target = if g < last_group { + (stage2[3 * g + 3], stage2[3 * g + 4], stage2[3 * g + 5]) + } else { + ( + stage2_next[0] + inj.0, + stage2_next[1] + inj.1, + stage2_next[2] + inj.2, + ) + }; + + let mut msgs = [(A::ZERO, A::ZERO, A::ZERO); MAX_LOOKUP_GROUP]; + let s_len = chunk.len(); + for (j, lookup) in chunk.iter().enumerate() { + let mut f = (A::ZERO, A::ZERO, A::ZERO); + for &arg in lookup.args.iter().rev() { + f = mul3_trinomial(f, gamma); + f.0 += nv(arg); + } + msgs[j] = (f.0 + beta.0, f.1 + beta.1, f.2 + beta.2); + } + + if s_len == 1 { + let diff = ( + target.0 - source.0, + target.1 - source.1, + target.2 - source.2, + ); + let c = mul3_trinomial(msgs[0], diff); + let mv = nv(chunk[0].multiplicity); + emit(c.0 - mv); + emit(c.1); + emit(c.2); + continue; + } + + let one = (A::ONE, A::ZERO, A::ZERO); + let mut prefix = [one; MAX_LOOKUP_GROUP + 1]; + prefix[1] = msgs[0]; + for j in 1..s_len { + prefix[j + 1] = mul3_trinomial(prefix[j], msgs[j]); + } + let mut suffix = [one; MAX_LOOKUP_GROUP + 1]; + suffix[s_len - 1] = msgs[s_len - 1]; + for j in (0..s_len - 1).rev() { + suffix[j] = mul3_trinomial(msgs[j], suffix[j + 1]); + } + + let diff = ( + target.0 - source.0, + target.1 - source.1, + target.2 - source.2, + ); + let c = mul3_trinomial(prefix[s_len], diff); + let mut rhs = (A::ZERO, A::ZERO, A::ZERO); + for (j, lookup) in chunk.iter().enumerate() { + let others = if j == 0 { + suffix[1] + } else if j == s_len - 1 { + prefix[s_len - 1] + } else { + mul3_trinomial(prefix[j], suffix[j + 1]) + }; + let mv = nv(lookup.multiplicity); + rhs.0 += others.0 * mv; + rhs.1 += others.1 * mv; + rhs.2 += others.2 * mv; + } + emit(c.0 - rhs.0); + emit(c.1 - rhs.1); + emit(c.2 - rhs.2); + } + return; + } + let beta = &publics[..d]; let gamma = &publics[d..2 * d]; // The boundary injection: Δ arrives with the normalization constant @@ -390,7 +516,7 @@ pub(crate) fn for_each_logup_constraint_value + Copy>( .map(|lookup| { let mut fingerprint = vec![A::ZERO; d]; for &arg in lookup.args.iter().rev() { - fingerprint = coord_mul(&fingerprint, gamma, w); + fingerprint = coord_mul(&fingerprint, gamma, modulus); fingerprint[0] += node_vals[arg.index()]; } for (m, &b) in fingerprint.iter_mut().zip(beta) { @@ -405,16 +531,16 @@ pub(crate) fn for_each_logup_constraint_value + Copy>( let mut prefix: Vec> = vec![one.clone()]; for m in &messages { let last = prefix.last().unwrap(); - prefix.push(coord_mul(last, m, w)); + prefix.push(coord_mul(last, m, modulus)); } let mut suffix: Vec> = vec![one.clone(); messages.len() + 1]; for j in (0..messages.len()).rev() { - suffix[j] = coord_mul(&messages[j], &suffix[j + 1], w); + suffix[j] = coord_mul(&messages[j], &suffix[j + 1], modulus); } - let mut constraint = coord_mul(&prefix[messages.len()], &target, w); + let mut constraint = coord_mul(&prefix[messages.len()], &target, modulus); for (j, lookup) in chunk.iter().enumerate() { - let others = coord_mul(&prefix[j], &suffix[j + 1], w); + let others = coord_mul(&prefix[j], &suffix[j + 1], modulus); let mv = node_vals[lookup.multiplicity.index()]; for (c, &o) in constraint.iter_mut().zip(&others) { *c -= o * mv; @@ -1611,8 +1737,12 @@ mod tests { use crate::eval::{VarValues, eval_expr, eval_ext_expr}; use crate::graph::ExtensionParams; - let params = crate::system::extension_params::(); - let w = params.w; + let ext_cases = [ + ExtensionParams::base(), + crate::system::extension_params::(), + ExtensionParams::cubic_trinomial(true), + ExtensionParams::binomial(4, Val::from_u64(11), false), + ]; // Lookups with assorted shapes: multi-arg with a product, single // arg, and the degenerate empty-args case. @@ -1631,11 +1761,12 @@ mod tests { args: vec![], }, ]; - // Both native and quadratic fields, empty lookups, uneven groups, - // and the maximum stack-array width. - for (d, group_size, count) in [1, params.degree].into_iter().flat_map(|d| { - (1..=MAX_LOOKUP_GROUP).flat_map(move |g| [0, 3, 9].map(|count| (d, g, count))) + // Native, quadratic binomial, cubic trinomial, and degree-4 generic + // fields; empty lookups, uneven groups, and the maximum stack width. + for (ext_params, group_size, count) in ext_cases.into_iter().flat_map(|ep| { + (1..=MAX_LOOKUP_GROUP).flat_map(move |g| [0, 3, 9].map(|count| (ep, g, count))) }) { + let d = ext_params.degree; let lookups: Vec<_> = lookups.iter().cycle().take(count).cloned().collect(); let synthesized = synthesize_lookups(&lookups, d, group_size); @@ -1674,7 +1805,7 @@ mod tests { let ref_params = ExtensionParams { degree: d, - w, + modulus: ext_params.modulus, karatsuba: false, }; let mut reference: Vec = vec![]; @@ -1713,7 +1844,7 @@ mod tests { &publics, &delta, isl, - w, + ext_params.modulus, d, group_size, &mut direct, @@ -1723,7 +1854,11 @@ mod tests { direct.len(), logup_constraint_count(lookups.len(), group_size, d) ); - assert_eq!(direct, reference, "group_size={group_size}"); + assert_eq!( + direct, reference, + "d={d}, modulus={:?}, group_size={group_size}", + ext_params.modulus + ); } } diff --git a/src/p3_adapter/field.rs b/src/p3_adapter/field.rs index 2575c91..06ea3bb 100644 --- a/src/p3_adapter/field.rs +++ b/src/p3_adapter/field.rs @@ -299,7 +299,43 @@ macro_rules! impl_extension_via_p3 { impl $crate::traits::ExtensionOf<$base> for $ext { const D: usize = $d; - const W: $base = <$base as p3_field::extension::BinomiallyExtendable<$d>>::W; + const MODULUS: $crate::traits::ExtensionModulus<$base> = + $crate::traits::ExtensionModulus::Binomial { + w: <$base as p3_field::extension::BinomiallyExtendable<$d>>::W, + }; + type ExtPacking = $crate::p3_adapter::field::P3ExtPacking<$base, $ext>; + + #[inline] + fn as_basis_coefficients_slice(&self) -> &[$base] { + p3_field::BasedVectorSpace::<$base>::as_basis_coefficients_slice(self) + } + + #[inline] + fn from_basis_coefficients_fn(f: impl FnMut(usize) -> $base) -> Self { + <$ext as p3_field::BasedVectorSpace<$base>>::from_basis_coefficients_fn(f) + } + + #[inline] + fn flatten_vec_to_base(values: Vec) -> Vec<$base> { + <$ext as p3_field::BasedVectorSpace<$base>>::flatten_to_base(values) + } + } + }; +} + +/// Implement [`ExtensionOf`] (and the base-field [`Algebra`]) for a +/// concrete p3 cubic trinomial extension `X^3 - X - 1` over a concrete base. +macro_rules! impl_cubic_trinomial_extension_via_p3 { + ($base:ty, $ext:ty) => { + impl $crate::traits::Algebra<$base> for $ext { + const ZERO: Self = <$ext as p3_field::PrimeCharacteristicRing>::ZERO; + const ONE: Self = <$ext as p3_field::PrimeCharacteristicRing>::ONE; + } + + impl $crate::traits::ExtensionOf<$base> for $ext { + const D: usize = 3; + const MODULUS: $crate::traits::ExtensionModulus<$base> = + $crate::traits::ExtensionModulus::CubicTrinomial; type ExtPacking = $crate::p3_adapter::field::P3ExtPacking<$base, $ext>; #[inline] @@ -331,6 +367,11 @@ impl_extension_via_p3!( p3_field::extension::BinomialExtensionField, 2 ); +impl_field_via_p3!(p3_field::extension::CubicTrinomialExtensionField); +impl_cubic_trinomial_extension_via_p3!( + p3_goldilocks::Goldilocks, + p3_field::extension::CubicTrinomialExtensionField +); impl crate::traits::PrimeField for p3_goldilocks::Goldilocks { fn canonical_u64(self) -> Option { diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs index 4620c79..78fd636 100644 --- a/src/p3_adapter/spill.rs +++ b/src/p3_adapter/spill.rs @@ -1986,7 +1986,11 @@ fn goldilocks_quadratic_inverse_denominators(z: ExtVal, coset: &[Val]) -> Vec>::W; + let crate::traits::ExtensionModulus::Binomial { w } = + >::MODULUS + else { + unreachable!("ExtVal is a binomial quadratic extension") + }; let w_z1_sq = w * z1 * z1; let pw = PackedVal::WIDTH; diff --git a/src/prover.rs b/src/prover.rs index 6e1f2b5..ddea84b 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -1057,6 +1057,15 @@ where }) .collect(); AlphaTable::Degree2(pairs) + } else if ext_d == 3 { + let triples: Vec<[Val; 3]> = alpha_powers + .iter() + .map(|x| { + let coords = x.as_basis_coefficients_slice(); + [coords[0], coords[1], coords[2]] + }) + .collect(); + AlphaTable::Degree3(triples) } else { let decomposed: Vec>> = (0..ext_d) .map(|i| { @@ -1129,7 +1138,7 @@ where ext_d.min(stage_2_width) }; let node_count = circuit.graph.nodes.len(); - let accs_len = if ext_d == 2 { 0 } else { ext_d }; + let accs_len = if ext_d == 2 || ext_d == 3 { 0 } else { ext_d }; const PACKS_PER_CHUNK: usize = 16; let chunk_rows = PACKS_PER_CHUNK * width; @@ -1161,7 +1170,7 @@ where &alpha_table, next_step, i_start, - ext_params.w, + ext_params.modulus, ext_params.degree, constraint_count, scratch, @@ -1175,6 +1184,7 @@ where enum AlphaTable { Degree2(Vec<[F; 2]>), + Degree3(Vec<[F; 3]>), Generic(Vec>), } @@ -1202,7 +1212,7 @@ fn eval_quotient_pack( alpha_table: &AlphaTable>, next_step: usize, i_start: usize, - ext_w: Val, + ext_modulus: crate::traits::ExtensionModulus>, ext_degree: usize, constraint_count: usize, scratch: &mut QuotientScratch>, @@ -1271,7 +1281,7 @@ fn eval_quotient_pack( publics_packed, delta_scaled, is_last_row, - ext_w, + ext_modulus, ext_degree, circuit.lookup_group_size, |val| { @@ -1286,6 +1296,37 @@ fn eval_quotient_pack( if coeff_idx == 0 { acc0 } else { acc1 } }) } + AlphaTable::Degree3(alpha_triples) => { + let (mut acc0, mut acc1, mut acc2) = circuit + .graph + .fold_constraints_d3(&scratch.buf, alpha_triples); + let mut idx = circuit.graph.zeros.len(); + crate::lookup::for_each_logup_constraint_value( + &circuit.graph.lookups, + &scratch.buf, + &scratch.s2_cur, + &scratch.s2_next, + publics_packed, + delta_scaled, + is_last_row, + ext_modulus, + ext_degree, + circuit.lookup_group_size, + |val| { + let triple = alpha_triples[idx]; + acc0 += val * triple[0]; + acc1 += val * triple[1]; + acc2 += val * triple[2]; + idx += 1; + }, + ); + debug_assert_eq!(idx, constraint_count); + PackedChallenge::::from_basis_coefficients_fn(|coeff_idx| match coeff_idx { + 0 => acc0, + 1 => acc1, + _ => acc2, + }) + } AlphaTable::Generic(decomposed_alpha_powers) => { scratch.accs.fill(PackedVal::::ZERO); circuit.graph.fold_constraints( @@ -1302,7 +1343,7 @@ fn eval_quotient_pack( publics_packed, delta_scaled, is_last_row, - ext_w, + ext_modulus, ext_degree, circuit.lookup_group_size, |val| { diff --git a/src/system.rs b/src/system.rs index a4cdce7..903f73b 100644 --- a/src/system.rs +++ b/src/system.rs @@ -9,7 +9,7 @@ //! ([`crate::lookup::logup_constraint_values`]), folding their values after //! the user roots. -use crate::traits::{ExtensionOf, Field}; +use crate::traits::Field; use p3_matrix::{Matrix, dense::RowMajorMatrix}; use p3_maybe_rayon::prelude::*; @@ -505,15 +505,9 @@ pub fn compute_lookup_values_range( builder.finish() } -/// The binomial extension parameters of the challenge field, read off -/// the `ExtensionOf` constants (`X^D = W`; `W` is unused when `D = 1`). +/// The extension parameters of the challenge field, read off [`ExtensionOf`]. pub fn extension_params() -> ExtensionParams> { - let d = >>::D; - ExtensionParams { - degree: d, - w: >>::W, - karatsuba: d == 2, - } + ExtensionParams::for_extension::() } #[cfg(test)] diff --git a/src/system/tests/lookup_values.rs b/src/system/tests/lookup_values.rs index 82201bd..1884239 100644 --- a/src/system/tests/lookup_values.rs +++ b/src/system/tests/lookup_values.rs @@ -87,15 +87,7 @@ fn fixture(height: usize, fixed: bool) -> (Circuit, RowMajorMatrix< ], ..Default::default() }; - let graph = compile( - &spec, - &ExtensionParams { - degree: 1, - w: F::ONE, - karatsuba: false, - }, - ) - .unwrap(); + let graph = compile(&spec, &ExtensionParams::base()).unwrap(); let circuit = Circuit { graph, main_width: 2, diff --git a/src/traits/field.rs b/src/traits/field.rs index 6760441..a1a42c3 100644 --- a/src/traits/field.rs +++ b/src/traits/field.rs @@ -1,6 +1,7 @@ //! Scalar fields, working algebras and SIMD packings used by the protocol. -//! [`ExtensionOf`] describes binomial challenge extensions `X^D = W`, including -//! `D = 1` when the base field is also the challenge field. +//! [`ExtensionOf`] describes challenge extensions over the base field — +//! degree-1 (`Base`), binomial `X^D - W` (`Binomial`), and cubic trinomial +//! `X^3 - X - 1` (`CubicTrinomial`). use core::fmt::Debug; use core::iter::Iterator; @@ -8,8 +9,8 @@ use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; use p3_matrix::Matrix; use p3_maybe_rayon::prelude::*; -use serde::Serialize; use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; /// Ring operations shared by every layer, over `Rhs`. pub trait RingOps: @@ -173,13 +174,40 @@ pub trait Packed: Algebra { } } -/// The challenge field as a binomial extension `X^D = W` of the base -/// field, `D >= 1`. For `D = 1` the field is its own challenge field: -/// `W` is unused and the basis is the identity. +/// Defining irreducible modulus polynomial of a challenge extension over `F`. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ExtensionModulus { + /// Trivial degree-1 extension (`F` itself). + Base, + /// Binomial extension `F[X] / (X^D - w)`. + Binomial { w: F }, + /// Cubic trinomial extension `F[X] / (X^3 - X - 1)`. + CubicTrinomial, +} + +impl ExtensionModulus { + /// Canonical protocol tag identifying the extension modulus family. + /// + /// - `0`: `Base` (`D = 1`) + /// - `1`: `Binomial` (`X^D - w`) + /// - `2`: `CubicTrinomial` (`X^3 - X - 1`) + #[inline] + pub const fn tag(&self) -> u8 { + match self { + Self::Base => 0, + Self::Binomial { .. } => 1, + Self::CubicTrinomial => 2, + } + } +} + +/// The challenge field as a degree-`D` extension (`D >= 1`) of the base +/// field, with defining polynomial [`Self::MODULUS`]. For `D = 1` the field +/// is its own challenge field (`MODULUS = ExtensionModulus::Base`). pub trait ExtensionOf: Field + Algebra { const D: usize; - /// The binomial modulus constant (`X^D = W`); unused when `D = 1`. - const W: F; + /// Defining modulus polynomial of the extension over `F`. + const MODULUS: ExtensionModulus; /// Packed representation: `D` base packings. type ExtPacking: PackedExtension; @@ -256,11 +284,75 @@ pub trait PrimeField: Field { #[cfg(test)] mod tests { use super::*; - use p3_field::extension::BinomialExtensionField; + use p3_field::extension::{BinomialExtensionField, CubicTrinomialExtensionField}; use p3_goldilocks::Goldilocks; use p3_matrix::dense::RowMajorMatrix; type Ext = BinomialExtensionField; + type Ext3 = CubicTrinomialExtensionField; + + #[test] + fn flatten_to_base_cubic_trinomial_is_zero_copy_and_matches_algebra() { + let values: Vec = (0..6u64) + .map(|i| { + Ext3::from_basis_coefficients_fn(|k| { + p3_field::PrimeCharacteristicRing::from_u64(3 * i + k as u64 + 1) + }) + }) + .collect(); + let expected = values.clone(); + let original_ptr = values.as_ptr().cast::(); + let flat = flatten_to_base::(RowMajorMatrix::new(values, 2)); + assert_eq!( + flat.values.as_ptr(), + original_ptr, + "p3 cubic trinomial extension flatten_to_base must be zero-copy" + ); + assert_eq!(flat.width, 6); + assert_eq!(flat.values.len(), 18); + for (i, value) in expected.iter().enumerate() { + assert_eq!( + &flat.values[3 * i..3 * i + 3], + value.as_basis_coefficients_slice() + ); + } + + // Pin X^3 = X + 1 Karatsuba multiplication and adjugate/norm inversion + // formulas against Plonky3's CubicTrinomialExtensionField. + for i in 0..expected.len() { + let a = expected[i]; + let b = expected[(i + 1) % expected.len()]; + let [a0, a1, a2] = *a.as_basis_coefficients_slice() else { + unreachable!() + }; + let [b0, b1, b2] = *b.as_basis_coefficients_slice() else { + unreachable!() + }; + let v0 = a0 * b0; + let v1 = a1 * b1; + let v2 = a2 * b2; + let m01 = (a0 + a1) * (b0 + b1) - v0 - v1; + let m02 = (a0 + a2) * (b0 + b2) - v0 - v2; + let m12 = (a1 + a2) * (b1 + b2) - v1 - v2; + let c0 = v0 + m12; + let c1 = m01 + m12 + v2; + let c2 = m02 + v1 + v2; + let prod = a * b; + assert_eq!(prod.as_basis_coefficients_slice(), &[c0, c1, c2]); + + let s = a0 + a2; + let d0 = s * s - a1 * (a1 + a2); + let d1 = a2 * a2 - a0 * a1; + let d2 = a1 * a1 - a2 * s; + let norm = a0 * d0 + a2 * d1 + a1 * d2; + let inv_norm = norm.inverse(); + let inv = a.inverse(); + assert_eq!( + inv.as_basis_coefficients_slice(), + &[d0 * inv_norm, d1 * inv_norm, d2 * inv_norm] + ); + } + } #[test] fn flatten_to_base_lays_out_basis_coefficients_in_row_order() { diff --git a/src/traits/mod.rs b/src/traits/mod.rs index b647132..0d76eb4 100644 --- a/src/traits/mod.rs +++ b/src/traits/mod.rs @@ -7,8 +7,8 @@ mod transcript; pub use domain::{EvaluationDomain, LagrangeSelectors}; pub use field::{ - Algebra, ExtensionOf, Field, Packed, PackedExtension, Powers, PrimeField, RingOps, - TwoAdicField, batch_inverse, flatten_to_base, + Algebra, ExtensionModulus, ExtensionOf, Field, Packed, PackedExtension, Powers, PrimeField, + RingOps, TwoAdicField, batch_inverse, flatten_to_base, }; pub use pcs::{ OpenedValues, OpenedValuesForMatrix, OpenedValuesForRound, OpeningRounds, Pcs, VerifyRounds, diff --git a/src/verifier.rs b/src/verifier.rs index 8e8c7b2..b23107a 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -540,7 +540,7 @@ impl System { // p3's (unnormalized) last-row selector; the normalization // constant is pre-absorbed into `delta_scaled`. view.is_last_row, - crate::system::extension_params::().w, + crate::system::extension_params::().modulus, extension_d, circuit.lookup_group_size, &mut constraint_values, From 3cedcbf51efcf6a7319d58b1444478c34188ebc7 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sat, 21 Nov 2026 22:12:15 -0500 Subject: [PATCH 18/28] Implement Protocol v6 hardening: BLAKE3 domain separation, VK digest, tensor FRI batching, and Goldilocks F_p^3 config --- src/batch.rs | 53 +- src/config.rs | 38 + src/p3_adapter/blake3_simd.rs | 574 +++++++++----- src/p3_adapter/challenger.rs | 127 ++- src/p3_adapter/domain.rs | 348 ++++++++- src/p3_adapter/domain_blake3.rs | 365 +++++++++ src/p3_adapter/fri_batching.rs | 1217 +++++++++++++++++++++++++++++ src/p3_adapter/mod.rs | 2 + src/p3_adapter/spill.rs | 747 +++++++++++++----- src/prover.rs | 9 +- src/system.rs | 173 +++- src/system/tests/lookup_values.rs | 2 + src/traits/transcript.rs | 15 + src/types.rs | 745 ++++++++++++++++-- src/verifier.rs | 15 +- 15 files changed, 3936 insertions(+), 494 deletions(-) create mode 100644 src/p3_adapter/domain_blake3.rs create mode 100644 src/p3_adapter/fri_batching.rs diff --git a/src/batch.rs b/src/batch.rs index 806203f..8925b3d 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -236,7 +236,10 @@ impl BatchProof { } pub fn from_bytes(bytes: &[u8]) -> Result { - let (batch, _num_bytes) = decode_from_slice(bytes, Proof::::serde_config())?; + let (batch, num_bytes) = decode_from_slice(bytes, Proof::::serde_config())?; + if num_bytes != bytes.len() { + return Err(DecodeError::Other("trailing bytes after batch proof")); + } Ok(batch) } } @@ -273,7 +276,9 @@ impl System { &self, preamble: &BatchPreamble, ) -> (SC::Challenger, SC::Challenge, SC::Challenge) { - let mut challenger = self.config.initialise_challenger(); + let mut challenger = self + .config + .initialise_challenger_for_mode(crate::config::TranscriptMode::Batch); self.observe_shape(&mut challenger); if let Some(commit) = &self.preprocessed_commit { challenger.observe_commitment(commit.clone()); @@ -321,6 +326,48 @@ impl System { .expect("lookup challenge makes a batch message denominator zero") } + fn verify_preamble_headers( + &self, + preamble: &BatchPreamble, + ) -> Result<(), VerificationError>> { + ensure!( + !preamble.headers.is_empty(), + VerificationError::BatchShapeMismatch; + "batch preamble has no shard headers" + ); + let max_log_degree = self.config.max_log_degree(); + for (idx, header) in preamble.headers.iter().enumerate() { + ensure!( + header.active.len() == self.circuits.len(), + VerificationError::BatchShapeMismatch; + shard = idx, + expected = self.circuits.len(), + got = header.active.len(), + "batch preamble header activation bitmap length mismatch" + ); + let active_count = header.active.iter().filter(|&&a| a).count(); + ensure!( + active_count > 0 && header.log_degrees.len() == active_count, + VerificationError::BatchShapeMismatch; + shard = idx, + active_count, + log_degrees_len = header.log_degrees.len(), + "batch preamble header log_degrees count mismatch" + ); + for &log_degree in &header.log_degrees { + ensure!( + usize::from(log_degree) <= max_log_degree, + VerificationError::BatchShapeMismatch; + shard = idx, + log_degree, + max_log_degree, + "batch preamble header log_degree exceeds max_log_degree" + ); + } + } + Ok(()) + } + /// Verifies shard `shard` of a batch and returns its residual (final /// accumulator). The shard's header must describe `proof` exactly. pub fn verify_batch_shard( @@ -333,6 +380,7 @@ impl System { Val: TwoAdicField + Ord, Com: PartialEq, { + self.verify_preamble_headers(preamble)?; let (challenger, lookup_argument_challenge, fingerprint_challenge) = self.batch_challenger(preamble); self.verify_batch_shard_from( @@ -414,6 +462,7 @@ impl System { proof_count = proofs.len(), "invalid batch header/proof counts" ); + self.verify_preamble_headers(preamble)?; let (challenger, lookup_argument_challenge, fingerprint_challenge) = self.batch_challenger(preamble); let mut total = try_messages_accumulator( diff --git a/src/config.rs b/src/config.rs index 8e18245..b07c6b5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -64,6 +64,29 @@ pub type PackedVal = as Field>::Packing; /// Packed (SIMD) representation of the challenge field. pub type PackedChallenge = <::Challenge as ExtensionOf>>::ExtPacking; +/// Protocol wire & cryptographic specification version. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum ProtocolVersion { + /// Legacy `v5` protocol: unkeyed BLAKE3, Horner FRI batching, shape-only + /// transcript binding. + V5, + /// Hardened `v6` protocol: BLAKE3 `derive_key` domain separation across + /// Merkle leaves / compressions / single-vs-batch transcripts / VK digest, + /// canonical VK & constraint-graph digest plus extension degree/modulus + /// bound in the transcript, and configurable multilinear tensor FRI batching. + V6, +} + +/// Transcript mode separating standalone single-proof transcripts from +/// multi-shard batch transcripts. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum TranscriptMode { + /// Standalone single proof (`prove` / `verify`). + Single, + /// Multi-shard batch proof (`batch_challenger` / `prove_batch_shard` / `verify_batch`). + Batch, +} + pub trait ProofConfig { /// The PCS used to commit to trace polynomials. type Pcs: Pcs; @@ -80,6 +103,13 @@ pub trait ProofConfig { /// Returns a reference to the PCS. fn pcs(&self) -> &Self::Pcs; + /// Protocol specification version governing transcript & hash domain + /// separation. Defaults to [`ProtocolVersion::V5`] for backwards + /// compatibility with existing configurations. + fn protocol_version(&self) -> ProtocolVersion { + ProtocolVersion::V5 + } + /// Returns a fresh challenger. /// /// # Transcript contract @@ -90,6 +120,14 @@ pub trait ProofConfig { /// `System::observe_shape`. fn initialise_challenger(&self) -> Self::Challenger; + /// Returns a fresh challenger domain-separated for `mode` (single proof + /// vs batch proof). Legacy `v5` configurations fall back to + /// [`Self::initialise_challenger`]; `v6` configurations use distinct + /// BLAKE3 `derive_key` contexts for `Single` and `Batch`. + fn initialise_challenger_for_mode(&self, _mode: TranscriptMode) -> Self::Challenger { + self.initialise_challenger() + } + /// Largest log2 length of a committed polynomial. fn max_log_degree(&self) -> usize; diff --git a/src/p3_adapter/blake3_simd.rs b/src/p3_adapter/blake3_simd.rs index 80fc295..afc6d54 100644 --- a/src/p3_adapter/blake3_simd.rs +++ b/src/p3_adapter/blake3_simd.rs @@ -14,12 +14,12 @@ use core::mem::MaybeUninit; -use p3_blake3::Blake3; use p3_field::PrimeField64; use p3_matrix::Matrix; use p3_maybe_rayon::prelude::*; use p3_symmetric::CryptographicHasher; +use super::domain_blake3::{BLAKE3_IV as IV, Blake3Domain, DomainBlake3}; use crate::types::Val; const BLOCK_LEN: usize = 64; @@ -33,17 +33,6 @@ const CHUNK_END: u32 = 1 << 1; const PARENT: u32 = 1 << 2; const ROOT: u32 = 1 << 3; -const IV: [u32; 8] = [ - 0x6A09_E667, - 0xBB67_AE85, - 0x3C6E_F372, - 0xA54F_F53A, - 0x510E_527F, - 0x9B05_688C, - 0x1F83_D9AB, - 0x5BE0_CD19, -]; - const MSG_SCHEDULE: [[usize; 16]; 7] = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8], @@ -78,29 +67,30 @@ fn detect_backend() -> SimdBackend { } #[inline] -fn compress_pair_scalar(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] { +fn compress_pair_scalar(left: &[u8; 32], right: &[u8; 32], domain: Blake3Domain) -> [u8; 32] { let mut block = [0u8; 64]; block[..32].copy_from_slice(left); block[32..].copy_from_slice(right); - compress_64_root_scalar(&block) + compress_64_root_scalar(&block, domain) } #[inline] -fn compress_64_root_scalar(block: &[u8; 64]) -> [u8; 32] { +fn compress_64_root_scalar(block: &[u8; 64], domain: Blake3Domain) -> [u8; 32] { let mut msg = [0u32; 16]; let (chunks, _) = block.as_chunks::<4>(); for (w, &bytes) in msg.iter_mut().zip(chunks) { *w = u32::from_le_bytes(bytes); } + let key = domain.key_words(); let mut state = [ - IV[0], - IV[1], - IV[2], - IV[3], - IV[4], - IV[5], - IV[6], - IV[7], + key[0], + key[1], + key[2], + key[3], + key[4], + key[5], + key[6], + key[7], IV[0], IV[1], IV[2], @@ -108,7 +98,7 @@ fn compress_64_root_scalar(block: &[u8; 64]) -> [u8; 32] { 0, 0, 64, - CHUNK_START | CHUNK_END | ROOT, + CHUNK_START | CHUNK_END | ROOT | domain.domain_flags(), ]; for schedule in &MSG_SCHEDULE { g_scalar(&mut state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]); @@ -195,8 +185,11 @@ fn compress_pairs_slice( prev_layer: &[[u8; 32]], out: &mut [MaybeUninit<[u8; 32]>], backend: SimdBackend, + domain: Blake3Domain, ) { debug_assert!(prev_layer.len() >= 2 * out.len()); + let key = domain.key_words(); + let domain_flags = domain.domain_flags(); let mut i = 0; #[cfg(target_arch = "x86_64")] { @@ -207,6 +200,8 @@ fn compress_pairs_slice( avx512::compress_16_pairs( &prev_layer[2 * i..2 * i + 32], out[i..].as_mut_ptr().cast(), + key, + domain_flags, ); } i += 16; @@ -217,6 +212,8 @@ fn compress_pairs_slice( avx2::compress_8_pairs( &prev_layer[2 * i..2 * i + 16], out[i..].as_mut_ptr().cast(), + key, + domain_flags, ); } i += 8; @@ -228,26 +225,33 @@ fn compress_pairs_slice( avx2::compress_8_pairs( &prev_layer[2 * i..2 * i + 16], out[i..].as_mut_ptr().cast(), + key, + domain_flags, ); } i += 8; } } } - let _ = backend; + let _ = (backend, key, domain_flags); while i < out.len() { out[i].write(compress_pair_scalar( &prev_layer[2 * i], &prev_layer[2 * i + 1], + domain, )); i += 1; } } /// Compresses `out.len()` adjacent 32-byte digest pairs from `prev_layer` -/// (`out[i] = BLAKE3(prev_layer[2*i] || prev_layer[2*i + 1])`) in parallel -/// using multi-buffer SIMD BLAKE3. -pub(crate) fn compress_pairs_uninit(prev_layer: &[[u8; 32]], out: &mut [MaybeUninit<[u8; 32]>]) { +/// (`out[i] = BLAKE3_domain(prev_layer[2*i] || prev_layer[2*i + 1])`) in +/// parallel using multi-buffer SIMD BLAKE3. +pub(crate) fn compress_pairs_uninit( + prev_layer: &[[u8; 32]], + out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, +) { assert!(prev_layer.len() >= 2 * out.len()); if out.is_empty() { return; @@ -256,13 +260,13 @@ pub(crate) fn compress_pairs_uninit(prev_layer: &[[u8; 32]], out: &mut [MaybeUni const PAR_THRESHOLD: usize = 128; const CHUNK_PAIRS: usize = 128; if out.len() < PAR_THRESHOLD { - compress_pairs_slice(prev_layer, out, backend); + compress_pairs_slice(prev_layer, out, backend, domain); } else { out.par_chunks_mut(CHUNK_PAIRS) .enumerate() .for_each(|(chunk_idx, dst)| { let start = chunk_idx * CHUNK_PAIRS; - compress_pairs_slice(&prev_layer[2 * start..], dst, backend); + compress_pairs_slice(&prev_layer[2 * start..], dst, backend, domain); }); } } @@ -273,9 +277,12 @@ fn compress_and_inject_slice( rows_digests: &[[u8; 32]], out: &mut [MaybeUninit<[u8; 32]>], backend: SimdBackend, + domain: Blake3Domain, ) { debug_assert_eq!(rows_digests.len(), out.len()); debug_assert!(prev_layer.len() >= 2 * out.len()); + let key = domain.key_words(); + let domain_flags = domain.domain_flags(); let mut i = 0; #[cfg(target_arch = "x86_64")] { @@ -287,6 +294,8 @@ fn compress_and_inject_slice( &prev_layer[2 * i..2 * i + 32], (&rows_digests[i..i + 16]).try_into().unwrap(), out[i..].as_mut_ptr().cast(), + key, + domain_flags, ); } i += 16; @@ -298,6 +307,8 @@ fn compress_and_inject_slice( &prev_layer[2 * i..2 * i + 16], (&rows_digests[i..i + 8]).try_into().unwrap(), out[i..].as_mut_ptr().cast(), + key, + domain_flags, ); } i += 8; @@ -310,26 +321,29 @@ fn compress_and_inject_slice( &prev_layer[2 * i..2 * i + 16], (&rows_digests[i..i + 8]).try_into().unwrap(), out[i..].as_mut_ptr().cast(), + key, + domain_flags, ); } i += 8; } } } - let _ = backend; + let _ = (backend, key, domain_flags); while i < out.len() { - let parent = compress_pair_scalar(&prev_layer[2 * i], &prev_layer[2 * i + 1]); - out[i].write(compress_pair_scalar(&parent, &rows_digests[i])); + let parent = compress_pair_scalar(&prev_layer[2 * i], &prev_layer[2 * i + 1], domain); + out[i].write(compress_pair_scalar(&parent, &rows_digests[i], domain)); i += 1; } } /// Fused binary compress + leaf-digest injection into uninitialized output: -/// `out[i] = BLAKE3(BLAKE3(prev_layer[2*i] || prev_layer[2*i + 1]) || rows_digests[i])`. +/// `out[i] = BLAKE3_d(BLAKE3_d(prev_layer[2*i] || prev_layer[2*i + 1]) || rows_digests[i])`. pub(crate) fn compress_and_inject_from_digests_uninit( prev_layer: &[[u8; 32]], rows_digests: &[[u8; 32]], out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, ) { assert_eq!(rows_digests.len(), out.len()); assert!(prev_layer.len() >= 2 * out.len()); @@ -340,14 +354,20 @@ pub(crate) fn compress_and_inject_from_digests_uninit( const PAR_THRESHOLD: usize = 128; const CHUNK_PAIRS: usize = 256; if out.len() < PAR_THRESHOLD { - compress_and_inject_slice(prev_layer, rows_digests, out, backend); + compress_and_inject_slice(prev_layer, rows_digests, out, backend, domain); } else { out.par_chunks_mut(CHUNK_PAIRS) .zip(rows_digests.par_chunks(CHUNK_PAIRS)) .enumerate() .for_each(|(chunk_idx, (dst, row_chunk))| { let start = chunk_idx * CHUNK_PAIRS; - compress_and_inject_slice(&prev_layer[2 * start..], row_chunk, dst, backend); + compress_and_inject_slice( + &prev_layer[2 * start..], + row_chunk, + dst, + backend, + domain, + ); }); } } @@ -358,11 +378,14 @@ fn hash_raw_rows_slice( row_bytes: usize, out: &mut [MaybeUninit<[u8; 32]>], backend: SimdBackend, + domain: Blake3Domain, ) { debug_assert_eq!(raw.len(), out.len() * row_bytes); if out.is_empty() { return; } + let key = domain.key_words(); + let domain_flags = domain.domain_flags(); let mut i = 0; #[cfg(target_arch = "x86_64")] { @@ -374,7 +397,13 @@ fn hash_raw_rows_slice( // SAFETY: `avx512f` detected at runtime; each pointer has `row_bytes` readable bytes // and `out[i..i+16]` has 16 writable slots. unsafe { - avx512::hash_16_fixed_len(&ptrs, row_bytes, out[i..].as_mut_ptr().cast()); + avx512::hash_16_fixed_len( + &ptrs, + row_bytes, + out[i..].as_mut_ptr().cast(), + key, + domain_flags, + ); } i += 16; } @@ -383,7 +412,13 @@ fn hash_raw_rows_slice( core::array::from_fn(|lane| raw[(i + lane) * row_bytes..].as_ptr()); // SAFETY: `avx512f` implies `avx2`; each pointer has `row_bytes` readable bytes. unsafe { - avx2::hash_8_fixed_len(&ptrs, row_bytes, out[i..].as_mut_ptr().cast()); + avx2::hash_8_fixed_len( + &ptrs, + row_bytes, + out[i..].as_mut_ptr().cast(), + key, + domain_flags, + ); } i += 8; } @@ -393,15 +428,21 @@ fn hash_raw_rows_slice( core::array::from_fn(|lane| raw[(i + lane) * row_bytes..].as_ptr()); // SAFETY: `avx2` detected at runtime; each pointer has `row_bytes` readable bytes. unsafe { - avx2::hash_8_fixed_len(&ptrs, row_bytes, out[i..].as_mut_ptr().cast()); + avx2::hash_8_fixed_len( + &ptrs, + row_bytes, + out[i..].as_mut_ptr().cast(), + key, + domain_flags, + ); } i += 8; } } } } - let _ = backend; - let hasher = Blake3; + let _ = (backend, key, domain_flags); + let hasher = DomainBlake3::new(domain); while i < out.len() { out[i].write(hasher.hash_slice(&raw[i * row_bytes..(i + 1) * row_bytes])); i += 1; @@ -414,6 +455,7 @@ pub(crate) fn hash_raw_rows_uninit( raw: &[u8], row_bytes: usize, out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, ) { assert_eq!(raw.len(), out.len() * row_bytes); if out.is_empty() { @@ -421,7 +463,7 @@ pub(crate) fn hash_raw_rows_uninit( } let backend = detect_backend(); if row_bytes > MAX_MULTIBUF_ROW_BYTES { - let hasher = Blake3; + let hasher = DomainBlake3::new(domain); out.par_iter_mut().enumerate().for_each(|(row, digest)| { digest.write(hasher.hash_slice(&raw[row * row_bytes..(row + 1) * row_bytes])); }); @@ -431,7 +473,7 @@ pub(crate) fn hash_raw_rows_uninit( .clamp(16, 256) .next_multiple_of(16); if out.len() <= chunk_rows { - hash_raw_rows_slice(raw, row_bytes, out, backend); + hash_raw_rows_slice(raw, row_bytes, out, backend, domain); } else { out.par_chunks_mut(chunk_rows) .enumerate() @@ -439,7 +481,7 @@ pub(crate) fn hash_raw_rows_uninit( let start = chunk_idx * chunk_rows; let byte_start = start * row_bytes; let byte_end = (start + dst.len()) * row_bytes; - hash_raw_rows_slice(&raw[byte_start..byte_end], row_bytes, dst, backend); + hash_raw_rows_slice(&raw[byte_start..byte_end], row_bytes, dst, backend, domain); }); } } @@ -449,17 +491,18 @@ pub(crate) fn hash_raw_rows_uninit( pub(crate) fn hash_raw_multi_rows_uninit( blocks: &[(Vec, usize)], out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, ) { if out.is_empty() { return; } if let [(buf, row_bytes)] = blocks { - hash_raw_rows_uninit(buf, *row_bytes, out); + hash_raw_rows_uninit(buf, *row_bytes, out, domain); return; } let total_row_bytes: usize = blocks.iter().map(|(_, rb)| *rb).sum(); if total_row_bytes > MAX_MULTIBUF_ROW_BYTES { - let hasher = Blake3; + let hasher = DomainBlake3::new(domain); out.par_iter_mut() .enumerate() .for_each(|(local_row, digest)| { @@ -482,7 +525,7 @@ pub(crate) fn hash_raw_multi_rows_uninit( SimdBackend::Scalar => 1usize, }; if batch == 1 { - let hasher = Blake3; + let hasher = DomainBlake3::new(domain); out.par_iter_mut() .enumerate() .for_each(|(local_row, digest)| { @@ -522,6 +565,7 @@ pub(crate) fn hash_raw_multi_rows_uninit( total_row_bytes, &mut dst[offset..offset + take], backend, + domain, ); offset += take; } @@ -535,6 +579,7 @@ pub(crate) fn hash_matrix_rows_uninit>( matrices: &[&M], start_row: usize, out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, ) { if out.is_empty() { return; @@ -542,9 +587,10 @@ pub(crate) fn hash_matrix_rows_uninit>( let total_width: usize = matrices.iter().map(|m| m.width()).sum(); let total_row_bytes = total_width * size_of::(); let backend = detect_backend(); + let hasher = DomainBlake3::new(domain); if total_row_bytes == 0 { - let empty_digest = Blake3.hash_slice(&[]); + let empty_digest = hasher.hash_slice(&[]); for slot in out { slot.write(empty_digest); } @@ -552,7 +598,6 @@ pub(crate) fn hash_matrix_rows_uninit>( } if total_row_bytes > MAX_MULTIBUF_ROW_BYTES { - let hasher = Blake3; out.par_iter_mut().enumerate().for_each_init( || vec![0u8; total_row_bytes], |scratch, (local_row, digest)| { @@ -585,6 +630,8 @@ pub(crate) fn hash_matrix_rows_uninit>( // directly into a 1 KiB zero-padded stack block array with zero heap scratch. #[cfg(target_arch = "x86_64")] if total_row_bytes <= BLOCK_LEN && batch > 1 { + let key = domain.key_words(); + let domain_flags = domain.domain_flags(); let block_len_u32 = u32::try_from(total_row_bytes).unwrap(); let chunk_rows = 256usize; let process_small = |chunk_start: usize, dst: &mut [MaybeUninit<[u8; 32]>]| { @@ -610,6 +657,8 @@ pub(crate) fn hash_matrix_rows_uninit>( &blocks, block_len_u32, dst[offset..].as_mut_ptr().cast(), + key, + domain_flags, ); } } else { @@ -619,13 +668,14 @@ pub(crate) fn hash_matrix_rows_uninit>( (&blocks[..8]).try_into().unwrap(), block_len_u32, dst[offset..].as_mut_ptr().cast(), + key, + domain_flags, ); } } offset += batch; } if offset < dst.len() { - let hasher = Blake3; let mut block = [0u8; BLOCK_LEN]; while offset < dst.len() { let r = chunk_start + offset; @@ -681,6 +731,7 @@ pub(crate) fn hash_matrix_rows_uninit>( total_row_bytes, &mut dst[offset..offset + take], backend, + domain, ); offset += take; } @@ -712,10 +763,14 @@ unsafe fn as_uninit_slice(slice: &mut [[u8; 32]]) -> &mut [MaybeUninit<[u8; 32]> /// Safe wrapper over [`hash_raw_multi_rows_uninit`] writing into an existing /// initialized digest buffer. -pub(crate) fn hash_raw_multi_rows(blocks: &[(Vec, usize)], out: &mut [[u8; 32]]) { +pub(crate) fn hash_raw_multi_rows( + blocks: &[(Vec, usize)], + out: &mut [[u8; 32]], + domain: Blake3Domain, +) { // SAFETY: `hash_raw_multi_rows_uninit` only writes initialized `[u8; 32]` values. let uninit = unsafe { as_uninit_slice(out) }; - hash_raw_multi_rows_uninit(blocks, uninit); + hash_raw_multi_rows_uninit(blocks, uninit, domain); } /// Safe wrapper over [`hash_matrix_rows_uninit`] writing into an existing @@ -724,10 +779,11 @@ pub(crate) fn hash_matrix_rows>( matrices: &[&M], start_row: usize, out: &mut [[u8; 32]], + domain: Blake3Domain, ) { // SAFETY: `hash_matrix_rows_uninit` only writes initialized `[u8; 32]` values. let uninit = unsafe { as_uninit_slice(out) }; - hash_matrix_rows_uninit(matrices, start_row, uninit); + hash_matrix_rows_uninit(matrices, start_row, uninit, domain); } #[cfg(target_arch = "x86_64")] @@ -744,16 +800,16 @@ mod avx512 { #[target_feature(enable = "avx512f")] #[inline] - fn iv_vecs() -> [__m512i; 8] { + fn key_vecs(key: [u32; 8]) -> [__m512i; 8] { [ - splat_u32(IV[0]), - splat_u32(IV[1]), - splat_u32(IV[2]), - splat_u32(IV[3]), - splat_u32(IV[4]), - splat_u32(IV[5]), - splat_u32(IV[6]), - splat_u32(IV[7]), + splat_u32(key[0]), + splat_u32(key[1]), + splat_u32(key[2]), + splat_u32(key[3]), + splat_u32(key[4]), + splat_u32(key[5]), + splat_u32(key[6]), + splat_u32(key[7]), ] } @@ -914,6 +970,8 @@ mod avx512 { blocks: &[[u8; BLOCK_LEN]; 16], block_len: u32, out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, ) { let mut rows = [_mm512_setzero_si512(); 16]; // SAFETY: `blocks` holds 16 contiguous 64-byte arrays. @@ -923,14 +981,25 @@ mod avx512 { } } let msg = transpose_16x16(&rows); - let mut cv = iv_vecs(); - compress_block_16(&mut cv, &msg, block_len, 0, CHUNK_START | CHUNK_END | ROOT); + let mut cv = key_vecs(key); + compress_block_16( + &mut cv, + &msg, + block_len, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); // SAFETY: caller guarantees `out` points to 16 writable slots. unsafe { unpack_cv_16(&cv, out) }; } #[target_feature(enable = "avx512f")] - pub(super) unsafe fn compress_16_pairs(prev_32: &[[u8; 32]], out: *mut [u8; 32]) { + pub(super) unsafe fn compress_16_pairs( + prev_32: &[[u8; 32]], + out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, + ) { debug_assert!(prev_32.len() >= 32); let mut rows = [_mm512_setzero_si512(); 16]; let base = prev_32.as_ptr().cast::(); @@ -941,8 +1010,14 @@ mod avx512 { } } let msg = transpose_16x16(&rows); - let mut cv = iv_vecs(); - compress_block_16(&mut cv, &msg, 64, 0, CHUNK_START | CHUNK_END | ROOT); + let mut cv = key_vecs(key); + compress_block_16( + &mut cv, + &msg, + 64, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); // SAFETY: caller guarantees `out` points to 16 writable slots. unsafe { unpack_cv_16(&cv, out) }; } @@ -952,6 +1027,8 @@ mod avx512 { prev_32: &[[u8; 32]], rows_digests: &[[u8; 32]; 16], out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, ) { debug_assert!(prev_32.len() >= 32); let mut rows = [_mm512_setzero_si512(); 16]; @@ -963,8 +1040,14 @@ mod avx512 { } } let msg1 = transpose_16x16(&rows); - let mut parent_cv = iv_vecs(); - compress_block_16(&mut parent_cv, &msg1, 64, 0, CHUNK_START | CHUNK_END | ROOT); + let mut parent_cv = key_vecs(key); + compress_block_16( + &mut parent_cv, + &msg1, + 64, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); let right_cv = load_16_digests_transposed(rows_digests); let msg2 = [ @@ -985,8 +1068,14 @@ mod avx512 { right_cv[6], right_cv[7], ]; - let mut final_cv = iv_vecs(); - compress_block_16(&mut final_cv, &msg2, 64, 0, CHUNK_START | CHUNK_END | ROOT); + let mut final_cv = key_vecs(key); + compress_block_16( + &mut final_cv, + &msg2, + 64, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); // SAFETY: caller guarantees `out` points to 16 writable slots. unsafe { unpack_cv_16(&final_cv, out) }; } @@ -999,8 +1088,10 @@ mod avx512 { chunk_len: usize, counter: u64, is_root: bool, + key: [u32; 8], + domain_flags: u32, ) -> [__m512i; 8] { - let mut cv = iv_vecs(); + let mut cv = key_vecs(key); let num_blocks = chunk_len.div_ceil(BLOCK_LEN).max(1); for b in 0..num_blocks { let block_offset = chunk_offset + b * BLOCK_LEN; @@ -1028,7 +1119,7 @@ mod avx512 { } } let msg = transpose_16x16(&rows); - let mut flags = 0u32; + let mut flags = domain_flags; if b == 0 { flags |= CHUNK_START; } @@ -1055,13 +1146,19 @@ mod avx512 { left: &[__m512i; 8], right: &[__m512i; 8], is_root: bool, + key: [u32; 8], + domain_flags: u32, ) -> [__m512i; 8] { let msg = [ left[0], left[1], left[2], left[3], left[4], left[5], left[6], left[7], right[0], right[1], right[2], right[3], right[4], right[5], right[6], right[7], ]; - let mut cv = iv_vecs(); - let flags = if is_root { PARENT | ROOT } else { PARENT }; + let mut cv = key_vecs(key); + let flags = if is_root { + PARENT | ROOT | domain_flags + } else { + PARENT | domain_flags + }; compress_block_16(&mut cv, &msg, 64, 0, flags); cv } @@ -1071,12 +1168,14 @@ mod avx512 { ptrs: &[*const u8; 16], row_bytes: usize, out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, ) { debug_assert!(row_bytes <= super::MAX_MULTIBUF_ROW_BYTES); if row_bytes <= CHUNK_LEN { // SAFETY: caller guarantees `ptrs` validity for `row_bytes` and `out` has 16 slots. unsafe { - let cv = hash_chunk_16(ptrs, 0, row_bytes, 0, true); + let cv = hash_chunk_16(ptrs, 0, row_bytes, 0, true, key, domain_flags); unpack_cv_16(&cv, out); } return; @@ -1096,13 +1195,16 @@ mod avx512 { chunk_len, u64::try_from(c).unwrap(), false, + key, + domain_flags, ) }; if c + 1 < num_chunks { let mut total_chunks = c + 1; while total_chunks & 1 == 0 { stack_len -= 1; - new_cv = compress_parent_16(&cv_stack[stack_len], &new_cv, false); + new_cv = + compress_parent_16(&cv_stack[stack_len], &new_cv, false, key, domain_flags); total_chunks >>= 1; } cv_stack[stack_len] = new_cv; @@ -1110,10 +1212,12 @@ mod avx512 { } else { while stack_len > 1 { stack_len -= 1; - new_cv = compress_parent_16(&cv_stack[stack_len], &new_cv, false); + new_cv = + compress_parent_16(&cv_stack[stack_len], &new_cv, false, key, domain_flags); } stack_len -= 1; - let root_cv = compress_parent_16(&cv_stack[stack_len], &new_cv, true); + let root_cv = + compress_parent_16(&cv_stack[stack_len], &new_cv, true, key, domain_flags); // SAFETY: caller guarantees `out` has 16 writable slots. unsafe { unpack_cv_16(&root_cv, out) }; } @@ -1135,16 +1239,16 @@ mod avx2 { #[target_feature(enable = "avx2")] #[inline] - fn iv_vecs() -> [__m256i; 8] { + fn key_vecs(key: [u32; 8]) -> [__m256i; 8] { [ - splat_u32(IV[0]), - splat_u32(IV[1]), - splat_u32(IV[2]), - splat_u32(IV[3]), - splat_u32(IV[4]), - splat_u32(IV[5]), - splat_u32(IV[6]), - splat_u32(IV[7]), + splat_u32(key[0]), + splat_u32(key[1]), + splat_u32(key[2]), + splat_u32(key[3]), + splat_u32(key[4]), + splat_u32(key[5]), + splat_u32(key[6]), + splat_u32(key[7]), ] } @@ -1297,6 +1401,8 @@ mod avx2 { blocks: &[[u8; BLOCK_LEN]; 8], block_len: u32, out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, ) { let mut left = [_mm256_setzero_si256(); 8]; let mut right = [_mm256_setzero_si256(); 8]; @@ -1314,14 +1420,25 @@ mod avx2 { lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], hi[4], hi[5], hi[6], hi[7], ]; - let mut cv = iv_vecs(); - compress_block_8(&mut cv, &msg, block_len, 0, CHUNK_START | CHUNK_END | ROOT); + let mut cv = key_vecs(key); + compress_block_8( + &mut cv, + &msg, + block_len, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); // SAFETY: caller guarantees `out` points to 8 writable slots. unsafe { unpack_cv_8(&cv, out) }; } #[target_feature(enable = "avx2")] - pub(super) unsafe fn compress_8_pairs(prev_16: &[[u8; 32]], out: *mut [u8; 32]) { + pub(super) unsafe fn compress_8_pairs( + prev_16: &[[u8; 32]], + out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, + ) { debug_assert!(prev_16.len() >= 16); let mut left = [_mm256_setzero_si256(); 8]; let mut right = [_mm256_setzero_si256(); 8]; @@ -1338,8 +1455,14 @@ mod avx2 { lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], hi[4], hi[5], hi[6], hi[7], ]; - let mut cv = iv_vecs(); - compress_block_8(&mut cv, &msg, 64, 0, CHUNK_START | CHUNK_END | ROOT); + let mut cv = key_vecs(key); + compress_block_8( + &mut cv, + &msg, + 64, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); // SAFETY: caller guarantees `out` points to 8 writable slots. unsafe { unpack_cv_8(&cv, out) }; } @@ -1349,6 +1472,8 @@ mod avx2 { prev_16: &[[u8; 32]], rows_digests: &[[u8; 32]; 8], out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, ) { debug_assert!(prev_16.len() >= 16); let mut left = [_mm256_setzero_si256(); 8]; @@ -1368,8 +1493,14 @@ mod avx2 { lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], hi[4], hi[5], hi[6], hi[7], ]; - let mut parent_cv = iv_vecs(); - compress_block_8(&mut parent_cv, &msg1, 64, 0, CHUNK_START | CHUNK_END | ROOT); + let mut parent_cv = key_vecs(key); + compress_block_8( + &mut parent_cv, + &msg1, + 64, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); let right_cv = transpose_8x8(&row_vecs); let msg2 = [ @@ -1390,8 +1521,14 @@ mod avx2 { right_cv[6], right_cv[7], ]; - let mut final_cv = iv_vecs(); - compress_block_8(&mut final_cv, &msg2, 64, 0, CHUNK_START | CHUNK_END | ROOT); + let mut final_cv = key_vecs(key); + compress_block_8( + &mut final_cv, + &msg2, + 64, + 0, + CHUNK_START | CHUNK_END | ROOT | domain_flags, + ); // SAFETY: caller guarantees `out` points to 8 writable slots. unsafe { unpack_cv_8(&final_cv, out) }; } @@ -1404,8 +1541,10 @@ mod avx2 { chunk_len: usize, counter: u64, is_root: bool, + key: [u32; 8], + domain_flags: u32, ) -> [__m256i; 8] { - let mut cv = iv_vecs(); + let mut cv = key_vecs(key); let num_blocks = chunk_len.div_ceil(BLOCK_LEN).max(1); for b in 0..num_blocks { let block_offset = chunk_offset + b * BLOCK_LEN; @@ -1442,7 +1581,7 @@ mod avx2 { lo[0], lo[1], lo[2], lo[3], lo[4], lo[5], lo[6], lo[7], hi[0], hi[1], hi[2], hi[3], hi[4], hi[5], hi[6], hi[7], ]; - let mut flags = 0u32; + let mut flags = domain_flags; if b == 0 { flags |= CHUNK_START; } @@ -1465,13 +1604,23 @@ mod avx2 { #[target_feature(enable = "avx2")] #[inline] - fn compress_parent_8(left: &[__m256i; 8], right: &[__m256i; 8], is_root: bool) -> [__m256i; 8] { + fn compress_parent_8( + left: &[__m256i; 8], + right: &[__m256i; 8], + is_root: bool, + key: [u32; 8], + domain_flags: u32, + ) -> [__m256i; 8] { let msg = [ left[0], left[1], left[2], left[3], left[4], left[5], left[6], left[7], right[0], right[1], right[2], right[3], right[4], right[5], right[6], right[7], ]; - let mut cv = iv_vecs(); - let flags = if is_root { PARENT | ROOT } else { PARENT }; + let mut cv = key_vecs(key); + let flags = if is_root { + PARENT | ROOT | domain_flags + } else { + PARENT | domain_flags + }; compress_block_8(&mut cv, &msg, 64, 0, flags); cv } @@ -1481,12 +1630,14 @@ mod avx2 { ptrs: &[*const u8; 8], row_bytes: usize, out: *mut [u8; 32], + key: [u32; 8], + domain_flags: u32, ) { debug_assert!(row_bytes <= super::MAX_MULTIBUF_ROW_BYTES); if row_bytes <= CHUNK_LEN { // SAFETY: caller guarantees `ptrs` validity for `row_bytes` and `out` has 8 slots. unsafe { - let cv = hash_chunk_8(ptrs, 0, row_bytes, 0, true); + let cv = hash_chunk_8(ptrs, 0, row_bytes, 0, true, key, domain_flags); unpack_cv_8(&cv, out); } return; @@ -1505,13 +1656,16 @@ mod avx2 { chunk_len, u64::try_from(c).unwrap(), false, + key, + domain_flags, ) }; if c + 1 < num_chunks { let mut total_chunks = c + 1; while total_chunks & 1 == 0 { stack_len -= 1; - new_cv = compress_parent_8(&cv_stack[stack_len], &new_cv, false); + new_cv = + compress_parent_8(&cv_stack[stack_len], &new_cv, false, key, domain_flags); total_chunks >>= 1; } cv_stack[stack_len] = new_cv; @@ -1519,10 +1673,12 @@ mod avx2 { } else { while stack_len > 1 { stack_len -= 1; - new_cv = compress_parent_8(&cv_stack[stack_len], &new_cv, false); + new_cv = + compress_parent_8(&cv_stack[stack_len], &new_cv, false, key, domain_flags); } stack_len -= 1; - let root_cv = compress_parent_8(&cv_stack[stack_len], &new_cv, true); + let root_cv = + compress_parent_8(&cv_stack[stack_len], &new_cv, true, key, domain_flags); // SAFETY: caller guarantees `out` has 8 writable slots. unsafe { unpack_cv_8(&root_cv, out) }; } @@ -1533,10 +1689,11 @@ mod avx2 { #[cfg(test)] mod tests { use super::*; - use crate::types::Blake3CompressionFunction; use p3_goldilocks::Goldilocks; use p3_matrix::dense::RowMajorMatrix; - use p3_symmetric::{PseudoCompressionFunction, SerializingHasher}; + use p3_symmetric::{ + CompressionFunctionFromHasher, PseudoCompressionFunction, SerializingHasher, + }; use rand::rngs::SmallRng; use rand::{RngExt, SeedableRng}; @@ -1557,111 +1714,122 @@ mod tests { #[test] fn compress_pairs_matches_p3_blake3_all_backends() { let mut rng = SmallRng::seed_from_u64(0xB1A3_0001); - let ref_compress = Blake3CompressionFunction::new(Blake3); - for count in [ - 0usize, 1, 2, 7, 8, 9, 15, 16, 17, 31, 32, 33, 255, 256, 257, 600, - ] { - let prev: Vec<[u8; 32]> = (0..2 * count).map(|_| rng.random()).collect(); - let expected: Vec<[u8; 32]> = (0..count) - .map(|i| ref_compress.compress([prev[2 * i], prev[2 * i + 1]])) - .collect(); + for domain in [Blake3Domain::Plain, Blake3Domain::MerkleCompress] { + let ref_compress = + CompressionFunctionFromHasher::<_, 2, 32>::new(DomainBlake3::new(domain)); + for count in [ + 0usize, 1, 2, 7, 8, 9, 15, 16, 17, 31, 32, 33, 255, 256, 257, 600, + ] { + let prev: Vec<[u8; 32]> = (0..2 * count).map(|_| rng.random()).collect(); + let expected: Vec<[u8; 32]> = (0..count) + .map(|i| ref_compress.compress([prev[2 * i], prev[2 * i + 1]])) + .collect(); - for backend in available_backends() { - // SAFETY: `compress_pairs_slice` initializes all `count` slots. - let got = unsafe { + for backend in available_backends() { + // SAFETY: `compress_pairs_slice` initializes all `count` slots. + let got = unsafe { + alloc_and_fill_digests(count, count, |dst| { + compress_pairs_slice(&prev, dst, backend, domain); + }) + }; + assert_eq!( + got, expected, + "compress_pairs_slice mismatch for {backend:?} {domain:?} count={count}" + ); + } + + // SAFETY: `compress_pairs_uninit` initializes all `count` slots. + let got_par = unsafe { alloc_and_fill_digests(count, count, |dst| { - compress_pairs_slice(&prev, dst, backend); + compress_pairs_uninit(&prev, dst, domain); }) }; assert_eq!( - got, expected, - "compress_pairs_slice mismatch for {backend:?} count={count}" + got_par, expected, + "compress_pairs mismatch {domain:?} count={count}" ); } - - // SAFETY: `compress_pairs_uninit` initializes all `count` slots. - let got_par = unsafe { - alloc_and_fill_digests(count, count, |dst| { - compress_pairs_uninit(&prev, dst); - }) - }; - assert_eq!(got_par, expected, "compress_pairs mismatch count={count}"); } } #[test] fn compress_and_inject_matches_p3_blake3_all_backends() { let mut rng = SmallRng::seed_from_u64(0xB1A3_0002); - let ref_compress = Blake3CompressionFunction::new(Blake3); - for count in [0usize, 1, 7, 8, 9, 15, 16, 17, 128, 300] { - let prev: Vec<[u8; 32]> = (0..2 * count).map(|_| rng.random()).collect(); - let rows: Vec<[u8; 32]> = (0..count).map(|_| rng.random()).collect(); - let expected: Vec<[u8; 32]> = (0..count) - .map(|i| { - let p = ref_compress.compress([prev[2 * i], prev[2 * i + 1]]); - ref_compress.compress([p, rows[i]]) - }) - .collect(); + for domain in [Blake3Domain::Plain, Blake3Domain::MerkleCompress] { + let ref_compress = + CompressionFunctionFromHasher::<_, 2, 32>::new(DomainBlake3::new(domain)); + for count in [0usize, 1, 7, 8, 9, 15, 16, 17, 128, 300] { + let prev: Vec<[u8; 32]> = (0..2 * count).map(|_| rng.random()).collect(); + let rows: Vec<[u8; 32]> = (0..count).map(|_| rng.random()).collect(); + let expected: Vec<[u8; 32]> = (0..count) + .map(|i| { + let p = ref_compress.compress([prev[2 * i], prev[2 * i + 1]]); + ref_compress.compress([p, rows[i]]) + }) + .collect(); + + for backend in available_backends() { + // SAFETY: `compress_and_inject_slice` initializes all `count` slots. + let got = unsafe { + alloc_and_fill_digests(count, count, |dst| { + compress_and_inject_slice(&prev, &rows, dst, backend, domain); + }) + }; + assert_eq!( + got, expected, + "compress_and_inject_slice mismatch for {backend:?} {domain:?} count={count}" + ); + } - for backend in available_backends() { - // SAFETY: `compress_and_inject_slice` initializes all `count` slots. - let got = unsafe { + // SAFETY: `compress_and_inject_from_digests_uninit` initializes all `count` slots. + let got_par = unsafe { alloc_and_fill_digests(count, count, |dst| { - compress_and_inject_slice(&prev, &rows, dst, backend); + compress_and_inject_from_digests_uninit(&prev, &rows, dst, domain); }) }; - assert_eq!( - got, expected, - "compress_and_inject_slice mismatch for {backend:?} count={count}" - ); + assert_eq!(got_par, expected); } - - // SAFETY: `compress_and_inject_from_digests_uninit` initializes all `count` slots. - let got_par = unsafe { - alloc_and_fill_digests(count, count, |dst| { - compress_and_inject_from_digests_uninit(&prev, &rows, dst); - }) - }; - assert_eq!(got_par, expected); } } #[test] fn hash_raw_rows_matches_p3_blake3_across_chunk_boundaries() { let mut rng = SmallRng::seed_from_u64(0xB1A3_0003); - let ref_hasher = Blake3; let lengths = [ 0usize, 1, 7, 8, 32, 56, 63, 64, 65, 72, 128, 512, 960, 1016, 1024, 1025, 1032, 2048, 2056, 3072, 4096, 5120, 6144, 7168, 8192, 16384, 16392, ]; - for &row_bytes in &lengths { - for &num_rows in &[0usize, 1, 8, 16, 25] { - let mut raw = vec![0u8; num_rows * row_bytes]; - rng.fill(&mut raw[..]); - let expected: Vec<[u8; 32]> = (0..num_rows) - .map(|r| ref_hasher.hash_slice(&raw[r * row_bytes..(r + 1) * row_bytes])) - .collect(); + for domain in [Blake3Domain::Plain, Blake3Domain::MerkleLeaf] { + let ref_hasher = DomainBlake3::new(domain); + for &row_bytes in &lengths { + for &num_rows in &[0usize, 1, 8, 16, 25] { + let mut raw = vec![0u8; num_rows * row_bytes]; + rng.fill(&mut raw[..]); + let expected: Vec<[u8; 32]> = (0..num_rows) + .map(|r| ref_hasher.hash_slice(&raw[r * row_bytes..(r + 1) * row_bytes])) + .collect(); + + for backend in available_backends() { + // SAFETY: `hash_raw_rows_slice` initializes all `num_rows` slots. + let got = unsafe { + alloc_and_fill_digests(num_rows, num_rows, |dst| { + hash_raw_rows_slice(&raw, row_bytes, dst, backend, domain); + }) + }; + assert_eq!( + got, expected, + "hash_raw_rows_slice mismatch for {backend:?} {domain:?} row_bytes={row_bytes} num_rows={num_rows}" + ); + } - for backend in available_backends() { - // SAFETY: `hash_raw_rows_slice` initializes all `num_rows` slots. - let got = unsafe { + // SAFETY: `hash_raw_rows_uninit` initializes all `num_rows` slots. + let got_par = unsafe { alloc_and_fill_digests(num_rows, num_rows, |dst| { - hash_raw_rows_slice(&raw, row_bytes, dst, backend); + hash_raw_rows_uninit(&raw, row_bytes, dst, domain); }) }; - assert_eq!( - got, expected, - "hash_raw_rows_slice mismatch for {backend:?} row_bytes={row_bytes} num_rows={num_rows}" - ); + assert_eq!(got_par, expected); } - - // SAFETY: `hash_raw_rows_uninit` initializes all `num_rows` slots. - let got_par = unsafe { - alloc_and_fill_digests(num_rows, num_rows, |dst| { - hash_raw_rows_uninit(&raw, row_bytes, dst); - }) - }; - assert_eq!(got_par, expected); } } } @@ -1669,7 +1837,6 @@ mod tests { #[test] fn hash_matrix_rows_matches_serializing_hasher_including_non_canonical_values() { let mut rng = SmallRng::seed_from_u64(0xB1A3_0004); - let ref_hasher = SerializingHasher::new(Blake3); let height = 35usize; // Include non-canonical Goldilocks representations (>= ORDER_U64) to verify canonicalization. let m1 = RowMajorMatrix::new( @@ -1690,26 +1857,29 @@ mod tests { .collect(), 130, ); - let expected_single: Vec<[u8; 32]> = (0..height) - .map(|r| ref_hasher.hash_iter(m1.row_slice(r).unwrap().iter().copied())) - .collect(); - let mut got_single = vec![[0u8; 32]; height]; - hash_matrix_rows(&[&m1], 0, &mut got_single); - assert_eq!(got_single, expected_single); - - let expected_multi: Vec<[u8; 32]> = (0..height) - .map(|r| { - ref_hasher.hash_iter( - m1.row_slice(r) - .unwrap() - .iter() - .chain(m2.row_slice(r).unwrap().iter()) - .copied(), - ) - }) - .collect(); - let mut got_multi = vec![[0u8; 32]; height]; - hash_matrix_rows(&[&m1, &m2], 0, &mut got_multi); - assert_eq!(got_multi, expected_multi); + for domain in [Blake3Domain::Plain, Blake3Domain::MerkleLeaf] { + let ref_hasher = SerializingHasher::new(DomainBlake3::new(domain)); + let expected_single: Vec<[u8; 32]> = (0..height) + .map(|r| ref_hasher.hash_iter(m1.row_slice(r).unwrap().iter().copied())) + .collect(); + let mut got_single = vec![[0u8; 32]; height]; + hash_matrix_rows(&[&m1], 0, &mut got_single, domain); + assert_eq!(got_single, expected_single); + + let expected_multi: Vec<[u8; 32]> = (0..height) + .map(|r| { + ref_hasher.hash_iter( + m1.row_slice(r) + .unwrap() + .iter() + .chain(m2.row_slice(r).unwrap().iter()) + .copied(), + ) + }) + .collect(); + let mut got_multi = vec![[0u8; 32]; height]; + hash_matrix_rows(&[&m1, &m2], 0, &mut got_multi, domain); + assert_eq!(got_multi, expected_multi); + } } } diff --git a/src/p3_adapter/challenger.rs b/src/p3_adapter/challenger.rs index 0be1483..5684b22 100644 --- a/src/p3_adapter/challenger.rs +++ b/src/p3_adapter/challenger.rs @@ -1,13 +1,22 @@ -//! [`Transcript`] for the p3-backed production challenger. +//! [`Transcript`] for the p3-backed production challengers. //! -//! Delegates to the Plonky3 challenger traits the concrete type already -//! implements; the transcript bytes are identical by construction (the -//! `proof_bytes_pin` test enforces it). +//! - [`Challenger`]: legacy `v5` unkeyed BLAKE3 challenger for `ExtVal` (degree-2). +//! - [`DomainChallenger`]: protocol `v6` domain-separated BLAKE3 challenger +//! parameterized over any challenge extension `EF` (supporting both degree-2 +//! and degree-3 cubic trinomial extensions). -use p3_challenger::{CanObserve, FieldChallenger}; +use core::marker::PhantomData; +use p3_challenger::{ + CanObserve, CanSample, CanSampleBits, FieldChallenger, GrindingChallenger, HashChallenger, + SerializingChallenger64, +}; +use p3_field::{BasedVectorSpace, ExtensionField}; +use p3_symmetric::Hash; + +use crate::p3_adapter::domain_blake3::{Blake3Domain, DomainBlake3}; use crate::traits::Transcript; -use crate::types::{Challenger, Commitment, ExtVal, Val}; +use crate::types::{Challenger, Commitment, DeterministicPow, ExtVal, Val}; impl Transcript for Challenger { type F = Val; @@ -34,8 +43,114 @@ impl Transcript for Challenger { self.observe(c); } + #[inline] + fn observe_digest(&mut self, digest: [u8; 32]) { + self.observe(Hash::::from(digest)); + } + #[inline] fn sample_challenge(&mut self) -> ExtVal { self.sample_algebra_element() } } + +/// Protocol `v6` domain-separated Goldilocks/BLAKE3 challenger parameterized +/// by the challenge extension field `EF` (e.g. `ExtVal3` or `ExtVal2`). +#[derive(Clone, Debug)] +pub struct DomainChallenger { + inner: DeterministicPow>>, + _marker: PhantomData, +} + +impl DomainChallenger { + /// Creates a fresh domain-separated challenger initialized with `initial_state` + /// under `domain` (`TranscriptSingle` or `TranscriptBatch`). + pub fn from_domain(initial_state: Vec, domain: Blake3Domain) -> Self { + Self { + inner: DeterministicPow(SerializingChallenger64::from_hasher( + initial_state, + DomainBlake3::new(domain), + )), + _marker: PhantomData, + } + } +} + +impl CanObserve for DomainChallenger +where + DeterministicPow>>: + CanObserve, +{ + #[inline] + fn observe(&mut self, value: T) { + self.inner.observe(value); + } +} + +impl CanSample for DomainChallenger +where + DeterministicPow>>: + CanSample, +{ + #[inline] + fn sample(&mut self) -> T { + self.inner.sample() + } +} + +impl CanSampleBits for DomainChallenger { + #[inline] + fn sample_bits(&mut self, bits: usize) -> usize { + self.inner.sample_bits(bits) + } +} + +impl FieldChallenger for DomainChallenger {} + +impl GrindingChallenger for DomainChallenger { + type Witness = Val; + + #[inline] + fn grind(&mut self, bits: usize) -> Self::Witness { + self.inner.grind(bits) + } +} + +impl Transcript for DomainChallenger +where + EF: ExtensionField + BasedVectorSpace + Clone + Send + Sync, +{ + type F = Val; + type Challenge = EF; + type Commitment = Commitment; + + #[inline] + fn observe_field(&mut self, x: Val) { + self.observe(x); + } + + #[inline] + fn observe_field_slice(&mut self, xs: &[Val]) { + self.observe_slice(xs); + } + + #[inline] + fn observe_challenge(&mut self, x: EF) { + self.observe_algebra_element(x); + } + + #[inline] + fn observe_commitment(&mut self, c: Commitment) { + self.observe(c); + } + + #[inline] + fn observe_digest(&mut self, digest: [u8; 32]) { + self.observe(Hash::::from(digest)); + } + + #[inline] + fn sample_challenge(&mut self) -> EF { + self.sample_algebra_element() + } +} diff --git a/src/p3_adapter/domain.rs b/src/p3_adapter/domain.rs index 56d447f..57f2832 100644 --- a/src/p3_adapter/domain.rs +++ b/src/p3_adapter/domain.rs @@ -1,8 +1,23 @@ -//! [`EvaluationDomain`] for the p3 two-adic coset domain used by the production -//! (Goldilocks/FRI) configuration. +//! [`EvaluationDomain`] for the p3 two-adic coset domains used by the +//! production (Goldilocks/FRI) configurations. +//! +//! - `TwoAdicMultiplicativeCoset` implements [`EvaluationDomain`] with +//! `Challenge = ExtVal` for legacy `v5` [`crate::types::GoldilocksBlake3Config`]. +//! - [`CosetDomain`] wraps `TwoAdicMultiplicativeCoset` transparently +//! so protocol `v6` configurations can instantiate [`EvaluationDomain`] for +//! any challenge extension `EF` (including degree-3 `ExtVal3` and degree-2 +//! `ExtVal2`). -use p3_commit::{LagrangeSelectors as P3LagrangeSelectors, PolynomialSpace}; +use core::marker::PhantomData; +use core::ops::{Deref, DerefMut}; + +use p3_commit::{ + LagrangeSelectors as P3LagrangeSelectors, OpenedValues, Pcs as P3Pcs, PeriodicLdeTable, + PolynomialSpace, +}; use p3_field::coset::TwoAdicMultiplicativeCoset; +use p3_field::{ExtensionField, TwoAdicField}; +use p3_matrix::dense::RowMajorMatrix; use crate::traits::{EvaluationDomain, LagrangeSelectors}; use crate::types::{ExtVal, Val}; @@ -50,3 +65,330 @@ impl EvaluationDomain for TwoAdicMultiplicativeCoset { convert(PolynomialSpace::selectors_on_coset(self, coset)) } } + +/// Extension-parameterized wrapper around [`TwoAdicMultiplicativeCoset`]. +#[derive(Debug)] +#[repr(transparent)] +pub struct CosetDomain { + pub inner: TwoAdicMultiplicativeCoset, + _marker: PhantomData, +} + +impl Copy for CosetDomain {} + +impl Clone for CosetDomain { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl CosetDomain { + #[inline] + pub const fn new(inner: TwoAdicMultiplicativeCoset) -> Self { + Self { + inner, + _marker: PhantomData, + } + } + + #[inline] + pub const fn into_inner(self) -> TwoAdicMultiplicativeCoset { + self.inner + } + + #[inline] + pub const fn log_size(&self) -> usize { + self.inner.log_size() + } + + #[inline] + pub const fn shift(&self) -> F { + self.inner.shift() + } + + #[inline] + pub fn subgroup_generator(&self) -> F { + self.inner.subgroup_generator() + } +} + +impl PolynomialSpace for CosetDomain { + type Val = F; + + #[inline] + fn size(&self) -> usize { + PolynomialSpace::size(&self.inner) + } + + #[inline] + fn first_point(&self) -> Self::Val { + PolynomialSpace::first_point(&self.inner) + } + + #[inline] + fn next_point>(&self, x: Ext) -> Option { + PolynomialSpace::next_point(&self.inner, x) + } + + #[inline] + fn try_create_disjoint_domain(&self, min_size: usize) -> Option { + PolynomialSpace::try_create_disjoint_domain(&self.inner, min_size).map(Self::new) + } + + #[inline] + fn split_domains(&self, num_chunks: usize) -> Vec { + PolynomialSpace::split_domains(&self.inner, num_chunks) + .into_iter() + .map(Self::new) + .collect() + } + + #[inline] + fn split_evals( + &self, + num_chunks: usize, + evals: RowMajorMatrix, + ) -> Vec> { + PolynomialSpace::split_evals(&self.inner, num_chunks, evals) + } + + #[inline] + fn vanishing_poly_at_point>(&self, point: Ext) -> Ext { + PolynomialSpace::vanishing_poly_at_point(&self.inner, point) + } + + #[inline] + fn selectors_at_point>( + &self, + point: Ext, + ) -> P3LagrangeSelectors { + PolynomialSpace::selectors_at_point(&self.inner, point) + } + + #[inline] + fn selectors_on_coset(&self, coset: Self) -> P3LagrangeSelectors> { + PolynomialSpace::selectors_on_coset(&self.inner, coset.inner) + } + + #[inline] + fn evaluate_polynomial_at>( + &self, + evals: &[Self::Val], + point: Ext, + ) -> Ext { + PolynomialSpace::evaluate_polynomial_at(&self.inner, evals, point) + } + + #[inline] + fn evaluate_periodic_column_at>( + &self, + col: &[Self::Val], + point: Ext, + ) -> Ext { + PolynomialSpace::evaluate_periodic_column_at(&self.inner, col, point) + } + + #[inline] + fn evaluate_periodic_columns_at>( + &self, + periodic_columns: &[Vec], + point: Ext, + ) -> Vec { + PolynomialSpace::evaluate_periodic_columns_at(&self.inner, periodic_columns, point) + } +} + +impl> EvaluationDomain for CosetDomain { + type F = F; + type Challenge = EF; + + #[inline] + fn size(&self) -> usize { + PolynomialSpace::size(&self.inner) + } + + #[inline] + fn first_point(&self) -> F { + PolynomialSpace::first_point(&self.inner) + } + + #[inline] + fn next_point(&self, x: EF) -> EF { + PolynomialSpace::next_point(&self.inner, x).expect("two-adic domain has a next point") + } + + #[inline] + fn create_disjoint_domain(&self, min_size: usize) -> Self { + Self::new(PolynomialSpace::create_disjoint_domain( + &self.inner, + min_size, + )) + } + + #[inline] + fn selectors_at_point(&self, point: EF) -> LagrangeSelectors { + convert(PolynomialSpace::selectors_at_point(&self.inner, point)) + } + + #[inline] + fn selectors_on_coset(&self, coset: Self) -> LagrangeSelectors> { + convert(PolynomialSpace::selectors_on_coset( + &self.inner, + coset.inner, + )) + } +} + +/// Transparent PCS adapter mapping `TwoAdicMultiplicativeCoset` domains +/// into [`CosetDomain`], allowing any two-adic PCS backend (CPU +/// `SpillableTwoAdicFriPcs` or CUDA `CudaTwoAdicFriPcs`) to serve multiple +/// challenge extensions (`ExtVal2`, `ExtVal3`) without coherence conflicts. +#[derive(Clone, Debug)] +#[repr(transparent)] +pub struct DomainMappedPcs { + inner: Inner, +} + +impl DomainMappedPcs { + #[inline] + pub const fn new(inner: Inner) -> Self { + Self { inner } + } + + #[inline] + pub const fn inner(&self) -> &Inner { + &self.inner + } + + #[inline] + pub fn inner_mut(&mut self) -> &mut Inner { + &mut self.inner + } +} + +impl Deref for DomainMappedPcs { + type Target = Inner; + #[inline] + fn deref(&self) -> &Inner { + &self.inner + } +} + +impl DerefMut for DomainMappedPcs { + #[inline] + fn deref_mut(&mut self) -> &mut Inner { + &mut self.inner + } +} + +impl P3Pcs for DomainMappedPcs +where + F: TwoAdicField, + EF: ExtensionField, + Inner: P3Pcs>, +{ + type Domain = CosetDomain; + type Commitment = Inner::Commitment; + type ProverData = Inner::ProverData; + type EvaluationsOnDomain<'a> = Inner::EvaluationsOnDomain<'a>; + type Proof = Inner::Proof; + type Error = Inner::Error; + const ZK: bool = Inner::ZK; + + #[inline] + fn natural_domain_for_degree(&self, degree: usize) -> Self::Domain { + CosetDomain::new(self.inner.natural_domain_for_degree(degree)) + } + + #[inline] + fn log_max_lde_height(&self) -> usize { + self.inner.log_max_lde_height() + } + + #[inline] + fn commit( + &self, + evaluations: impl IntoIterator)>, + ) -> (Self::Commitment, Self::ProverData) { + self.inner.commit( + evaluations + .into_iter() + .map(|(domain, evals)| (domain.inner, evals)), + ) + } + + #[inline] + fn get_quotient_ldes( + &self, + evaluations: impl IntoIterator)>, + num_chunks: usize, + ) -> Vec> { + self.inner.get_quotient_ldes( + evaluations + .into_iter() + .map(|(domain, evals)| (domain.inner, evals)), + num_chunks, + ) + } + + #[inline] + fn commit_ldes(&self, ldes: Vec>) -> (Self::Commitment, Self::ProverData) { + self.inner.commit_ldes(ldes) + } + + #[inline] + fn get_evaluations_on_domain<'a>( + &self, + prover_data: &'a Self::ProverData, + idx: usize, + domain: Self::Domain, + ) -> Self::EvaluationsOnDomain<'a> { + self.inner + .get_evaluations_on_domain(prover_data, idx, domain.inner) + } + + #[inline] + fn open( + &self, + rounds: Vec<(&Self::ProverData, Vec>)>, + challenger: &mut Challenger, + ) -> (OpenedValues, Self::Proof) { + self.inner.open(rounds, challenger) + } + + #[inline] + fn verify( + &self, + rounds: Vec<(Self::Commitment, Vec<(Self::Domain, Vec<(EF, Vec)>)>)>, + proof: &Self::Proof, + challenger: &mut Challenger, + ) -> Result<(), Self::Error> { + let mapped = rounds + .into_iter() + .map(|(com, mats)| { + ( + com, + mats.into_iter() + .map(|(domain, pts)| (domain.inner, pts)) + .collect(), + ) + }) + .collect(); + self.inner.verify(mapped, proof, challenger) + } + + #[inline] + fn build_periodic_lde_table( + &self, + periodic_cols: &[Vec], + trace_domain: Self::Domain, + quotient_domain: Self::Domain, + ) -> PeriodicLdeTable { + self.inner.build_periodic_lde_table( + periodic_cols, + trace_domain.inner, + quotient_domain.inner, + ) + } +} diff --git a/src/p3_adapter/domain_blake3.rs b/src/p3_adapter/domain_blake3.rs new file mode 100644 index 0000000..d98e4a1 --- /dev/null +++ b/src/p3_adapter/domain_blake3.rs @@ -0,0 +1,365 @@ +//! Domain-separated BLAKE3 hashing using BLAKE3's native `derive_key` mode. +//! +//! Prepending a byte tag to a 64-byte Merkle internal node (`left || right`) +//! pushes the input from 64 bytes (1 compression) to 65 bytes (2 compressions), +//! doubling Merkle hashing cost on CPU, CUDA, and recursive verifiers. +//! +//! BLAKE3's built-in `derive_key` mode avoids this completely: a context string +//! is hashed once at compile time with `DERIVE_KEY_CONTEXT` (`1 << 5`) into an +//! 8-word `context_key`, which replaces `IV` as the initial chaining value +//! while setting `DERIVE_KEY_MATERIAL` (`1 << 6`) in the block flags. Every +//! 64-byte Merkle compression remains a single BLAKE3 compression with zero +//! extra message bytes and zero performance overhead. + +use p3_symmetric::CryptographicHasher; + +/// Standard BLAKE3 initialization vector. +pub(crate) const BLAKE3_IV: [u32; 8] = [ + 0x6A09_E667, + 0xBB67_AE85, + 0x3C6E_F372, + 0xA54F_F53A, + 0x510E_527F, + 0x9B05_688C, + 0x1F83_D9AB, + 0x5BE0_CD19, +]; + +const CHUNK_START: u32 = 1 << 0; +const CHUNK_END: u32 = 1 << 1; +const ROOT: u32 = 1 << 3; +const DERIVE_KEY_CONTEXT: u32 = 1 << 5; +/// BLAKE3 `DERIVE_KEY_MATERIAL` flag (`1 << 6 = 64`). +pub(crate) const BLAKE3_DERIVE_KEY_MATERIAL: u32 = 1 << 6; + +const MSG_SCHEDULE: [[usize; 16]; 7] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8], + [3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1], + [10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6], + [12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4], + [9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7], + [11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13], +]; + +/// Domain-separation context string for v6 Merkle leaf row hashes. +pub const V6_MERKLE_LEAF_CONTEXT: &str = "multi-stark/v6/merkle/leaf"; +/// Domain-separation context string for v6 Merkle 2-to-1 internal compressions. +pub const V6_MERKLE_COMPRESS_CONTEXT: &str = "multi-stark/v6/merkle/compress"; +/// Domain-separation context string for v6 single-proof Fiat-Shamir transcripts. +pub const V6_TRANSCRIPT_SINGLE_CONTEXT: &str = "multi-stark/v6/transcript/single"; +/// Domain-separation context string for v6 batch-proof Fiat-Shamir transcripts. +pub const V6_TRANSCRIPT_BATCH_CONTEXT: &str = "multi-stark/v6/transcript/batch"; +/// Domain-separation context string for v6 canonical VK / constraint-graph digests. +pub const V6_VK_CONTEXT: &str = "multi-stark/v6/vk"; + +const fn g_const( + mut state: [u32; 16], + a: usize, + b: usize, + c: usize, + d: usize, + x: u32, + y: u32, +) -> [u32; 16] { + state[a] = state[a].wrapping_add(state[b]).wrapping_add(x); + state[d] = (state[d] ^ state[a]).rotate_right(16); + state[c] = state[c].wrapping_add(state[d]); + state[b] = (state[b] ^ state[c]).rotate_right(12); + state[a] = state[a].wrapping_add(state[b]).wrapping_add(y); + state[d] = (state[d] ^ state[a]).rotate_right(8); + state[c] = state[c].wrapping_add(state[d]); + state[b] = (state[b] ^ state[c]).rotate_right(7); + state +} + +/// Computes the 8-word BLAKE3 `derive_key` context key for a context string of +/// at most 64 bytes at compile time. +const fn derive_context_key(ctx: &str) -> [u32; 8] { + let bytes = ctx.as_bytes(); + assert!( + bytes.len() <= 64, + "BLAKE3 context string must be <= 64 bytes" + ); + let mut block = [0u8; 64]; + let mut i = 0; + while i < bytes.len() { + block[i] = bytes[i]; + i += 1; + } + let mut msg = [0u32; 16]; + let mut w = 0; + while w < 16 { + msg[w] = u32::from_le_bytes([ + block[4 * w], + block[4 * w + 1], + block[4 * w + 2], + block[4 * w + 3], + ]); + w += 1; + } + #[allow(clippy::cast_possible_truncation)] + let block_len = bytes.len() as u32; + let mut state = [ + BLAKE3_IV[0], + BLAKE3_IV[1], + BLAKE3_IV[2], + BLAKE3_IV[3], + BLAKE3_IV[4], + BLAKE3_IV[5], + BLAKE3_IV[6], + BLAKE3_IV[7], + BLAKE3_IV[0], + BLAKE3_IV[1], + BLAKE3_IV[2], + BLAKE3_IV[3], + 0, + 0, + block_len, + CHUNK_START | CHUNK_END | ROOT | DERIVE_KEY_CONTEXT, + ]; + let mut r = 0; + while r < 7 { + let s = MSG_SCHEDULE[r]; + state = g_const(state, 0, 4, 8, 12, msg[s[0]], msg[s[1]]); + state = g_const(state, 1, 5, 9, 13, msg[s[2]], msg[s[3]]); + state = g_const(state, 2, 6, 10, 14, msg[s[4]], msg[s[5]]); + state = g_const(state, 3, 7, 11, 15, msg[s[6]], msg[s[7]]); + state = g_const(state, 0, 5, 10, 15, msg[s[8]], msg[s[9]]); + state = g_const(state, 1, 6, 11, 12, msg[s[10]], msg[s[11]]); + state = g_const(state, 2, 7, 8, 13, msg[s[12]], msg[s[13]]); + state = g_const(state, 3, 4, 9, 14, msg[s[14]], msg[s[15]]); + r += 1; + } + [ + state[0] ^ state[8], + state[1] ^ state[9], + state[2] ^ state[10], + state[3] ^ state[11], + state[4] ^ state[12], + state[5] ^ state[13], + state[6] ^ state[14], + state[7] ^ state[15], + ] +} + +const KEY_MERKLE_LEAF: [u32; 8] = derive_context_key(V6_MERKLE_LEAF_CONTEXT); +const KEY_MERKLE_COMPRESS: [u32; 8] = derive_context_key(V6_MERKLE_COMPRESS_CONTEXT); +const KEY_TRANSCRIPT_SINGLE: [u32; 8] = derive_context_key(V6_TRANSCRIPT_SINGLE_CONTEXT); +const KEY_TRANSCRIPT_BATCH: [u32; 8] = derive_context_key(V6_TRANSCRIPT_BATCH_CONTEXT); +const KEY_VK: [u32; 8] = derive_context_key(V6_VK_CONTEXT); + +/// Cryptographic domain for BLAKE3 hashing. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum Blake3Domain { + /// Standard unkeyed BLAKE3 (`IV`, `flags = 0`), used by legacy `v5`. + Plain, + /// Protocol `v6` Merkle leaf row hashing (`derive_key("multi-stark/v6/merkle/leaf")`). + MerkleLeaf, + /// Protocol `v6` Merkle internal 2-to-1 compression (`derive_key("multi-stark/v6/merkle/compress")`). + MerkleCompress, + /// Protocol `v6` single-proof Fiat-Shamir transcript (`derive_key("multi-stark/v6/transcript/single")`). + TranscriptSingle, + /// Protocol `v6` batch-proof Fiat-Shamir transcript (`derive_key("multi-stark/v6/transcript/batch")`). + TranscriptBatch, + /// Protocol `v6` canonical verifying-key / constraint-graph digest (`derive_key("multi-stark/v6/vk")`). + VerifyingKey, +} + +impl Blake3Domain { + /// Returns the `derive_key` context string, or `None` for [`Self::Plain`]. + #[inline] + pub const fn context(self) -> Option<&'static str> { + match self { + Self::Plain => None, + Self::MerkleLeaf => Some(V6_MERKLE_LEAF_CONTEXT), + Self::MerkleCompress => Some(V6_MERKLE_COMPRESS_CONTEXT), + Self::TranscriptSingle => Some(V6_TRANSCRIPT_SINGLE_CONTEXT), + Self::TranscriptBatch => Some(V6_TRANSCRIPT_BATCH_CONTEXT), + Self::VerifyingKey => Some(V6_VK_CONTEXT), + } + } + + /// Initial 8-word chaining value (`BLAKE3_IV` for [`Self::Plain`], or the + /// precomputed `derive_key` context key for domain-separated modes). + #[inline] + pub const fn key_words(self) -> [u32; 8] { + match self { + Self::Plain => BLAKE3_IV, + Self::MerkleLeaf => KEY_MERKLE_LEAF, + Self::MerkleCompress => KEY_MERKLE_COMPRESS, + Self::TranscriptSingle => KEY_TRANSCRIPT_SINGLE, + Self::TranscriptBatch => KEY_TRANSCRIPT_BATCH, + Self::VerifyingKey => KEY_VK, + } + } + + /// Extra domain flags OR'd into every BLAKE3 compression (`0` for + /// [`Self::Plain`], [`BLAKE3_DERIVE_KEY_MATERIAL`] for `derive_key` modes). + #[inline] + pub const fn domain_flags(self) -> u32 { + match self { + Self::Plain => 0, + Self::MerkleLeaf + | Self::MerkleCompress + | Self::TranscriptSingle + | Self::TranscriptBatch + | Self::VerifyingKey => BLAKE3_DERIVE_KEY_MATERIAL, + } + } + + /// Creates a streaming [`blake3::Hasher`] configured for this domain. + #[inline] + pub fn hasher(self) -> blake3::Hasher { + match self.context() { + None => blake3::Hasher::new(), + Some(ctx) => blake3::Hasher::new_derive_key(ctx), + } + } + + /// Hashes a byte slice under this domain. + #[inline] + pub fn hash_bytes(self, input: &[u8]) -> [u8; 32] { + let mut h = self.hasher(); + h.update(input); + h.finalize().into() + } +} + +/// Plonky3 [`CryptographicHasher`] backed by domain-separated BLAKE3. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct DomainBlake3 { + domain: Blake3Domain, +} + +impl DomainBlake3 { + #[inline] + pub const fn new(domain: Blake3Domain) -> Self { + Self { domain } + } + + #[inline] + pub const fn domain(self) -> Blake3Domain { + self.domain + } +} + +impl CryptographicHasher for DomainBlake3 { + fn hash_iter(&self, input: I) -> [u8; 32] + where + I: IntoIterator, + { + const BUFLEN: usize = 512; + let mut hasher = self.domain.hasher(); + p3_util::apply_to_chunks::(input, |buf| { + hasher.update(buf); + }); + hasher.finalize().into() + } + + fn hash_iter_slices<'a, I>(&self, input: I) -> [u8; 32] + where + I: IntoIterator, + { + let mut hasher = self.domain.hasher(); + for chunk in input { + hasher.update(chunk); + } + hasher.finalize().into() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compile_time_context_keys_match_blake3_derive_key() { + let all_domains = [ + Blake3Domain::Plain, + Blake3Domain::MerkleLeaf, + Blake3Domain::MerkleCompress, + Blake3Domain::TranscriptSingle, + Blake3Domain::TranscriptBatch, + Blake3Domain::VerifyingKey, + ]; + // Test empty, 64-byte single-block, and multi-chunk (>1024 B) inputs. + let inputs: Vec> = vec![ + vec![], + (0..64u8).collect(), + (0..2500usize) + .map(|i| u8::try_from(i.wrapping_mul(37) & 0xFF).unwrap()) + .collect(), + ]; + + for input in &inputs { + let mut seen = Vec::new(); + for domain in all_domains { + let got = DomainBlake3::new(domain).hash_slice(input); + let expected: [u8; 32] = match domain.context() { + None => *blake3::hash(input).as_bytes(), + Some(ctx) => blake3::derive_key(ctx, input), + }; + assert_eq!(got, expected, "mismatch for domain {domain:?}"); + + // For single-block inputs (<= 64 bytes), also cross-check our + // compile-time key_words + domain_flags directly via single-block + // compression against blake3::derive_key. + if input.len() <= 64 { + let mut block = [0u8; 64]; + block[..input.len()].copy_from_slice(input); + let mut msg = [0u32; 16]; + for (w, &chunk) in msg.iter_mut().zip(block.as_chunks::<4>().0) { + *w = u32::from_le_bytes(chunk); + } + let kv = domain.key_words(); + let mut state = [ + kv[0], + kv[1], + kv[2], + kv[3], + kv[4], + kv[5], + kv[6], + kv[7], + BLAKE3_IV[0], + BLAKE3_IV[1], + BLAKE3_IV[2], + BLAKE3_IV[3], + 0, + 0, + u32::try_from(input.len()).unwrap(), + CHUNK_START | CHUNK_END | ROOT | domain.domain_flags(), + ]; + for s in &MSG_SCHEDULE { + state = g_const(state, 0, 4, 8, 12, msg[s[0]], msg[s[1]]); + state = g_const(state, 1, 5, 9, 13, msg[s[2]], msg[s[3]]); + state = g_const(state, 2, 6, 10, 14, msg[s[4]], msg[s[5]]); + state = g_const(state, 3, 7, 11, 15, msg[s[6]], msg[s[7]]); + state = g_const(state, 0, 5, 10, 15, msg[s[8]], msg[s[9]]); + state = g_const(state, 1, 6, 11, 12, msg[s[10]], msg[s[11]]); + state = g_const(state, 2, 7, 8, 13, msg[s[12]], msg[s[13]]); + state = g_const(state, 3, 4, 9, 14, msg[s[14]], msg[s[15]]); + } + let mut out = [0u8; 32]; + for i in 0..8 { + out[4 * i..4 * i + 4] + .copy_from_slice(&(state[i] ^ state[i + 8]).to_le_bytes()); + } + assert_eq!(out, expected, "key_words mismatch for {domain:?}"); + } + seen.push((domain, got)); + } + // All 6 domains must produce pairwise distinct digests on the same input. + for i in 0..seen.len() { + for j in (i + 1)..seen.len() { + assert_ne!( + seen[i].1, seen[j].1, + "domain collision between {:?} and {:?}", + seen[i].0, seen[j].0 + ); + } + } + } + } +} diff --git a/src/p3_adapter/fri_batching.rs b/src/p3_adapter/fri_batching.rs new file mode 100644 index 0000000..7ddafd7 --- /dev/null +++ b/src/p3_adapter/fri_batching.rs @@ -0,0 +1,1217 @@ +//! Configurable FRI opening batching: Horner powers (`alpha^i`) and +//! multilinear tensor batching (`col_weights ⊗ open_weights`). +//! +//! Under Horner batching, combining $n_f$ opened functions with powers of a +//! single challenge $\alpha$ has soundness error $n_f / |\mathbb{F}_{\text{ext}}|$. +//! Under multilinear tensor batching, we sample: +//! - $k_{\text{col}} = \lceil \log_2 W_{\max} \rceil$ column challenges +//! $(r^{\text{col}}_0, \dots, r^{\text{col}}_{k_{\text{col}}-1})$, expanding +//! to column weights $w^{\text{col}}_c = \prod_b (r^{\text{col}}_b)^{c_b}$, and +//! - $k_{\text{open}} = \lceil \log_2 M_{\max} \rceil$ opening-pair challenges +//! $(r^{\text{open}}_0, \dots, r^{\text{open}}_{k_{\text{open}}-1})$, expanding +//! to opening weights $w^{\text{open}}_m = \prod_b (r^{\text{open}}_b)^{m_b}$, +//! +//! where $W_{\max}$ is the maximum column width across opened matrices and +//! $M_{\max}$ is the maximum number of `(matrix, point)` opening pairs at any +//! single LDE height. +//! +//! Each column $c$ of opening $m$ at a given height receives weight +//! $w^{\text{open}}_m \cdot w^{\text{col}}_c$ — a distinct multilinear monomial +//! of degree $\le 1$ in every challenge and total degree +//! $\le k_{\text{col}} + k_{\text{open}}$. By Schwartz-Zippel this reduces the +//! batching soundness error from $W_{\max} M_{\max} / |\mathbb{F}_{\text{ext}}|$ +//! to $(k_{\text{col}} + k_{\text{open}}) / |\mathbb{F}_{\text{ext}}|$ (~9–10 +//! extra bits of soundness) at **zero prover overhead**, because each matrix is +//! still compressed once via `rowwise_packed_dot_product(&packed_col_weights)` +//! and reused across all its opening points ($\zeta, \zeta g$). + +use std::collections::BTreeMap; +use std::iter; + +use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; +use p3_commit::Mmcs; +use p3_field::coset::TwoAdicMultiplicativeCoset; +use p3_field::{ + BasedVectorSpace, ExtensionField, Field, HornerIter, PackedValue, TwoAdicField, + batch_multiplicative_inverse, +}; +use p3_fri::verifier::{self, FriError}; +use p3_fri::{ + BatchMultiOpening, CommitPhaseMultiStep, CommitmentWithOpeningPoints, FriFoldingStrategy, + FriParameters, FriProof, +}; +use p3_matrix::Dimensions; +use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_bits_len}; +use serde::{Deserialize, Serialize}; + +/// Batching strategy for reducing opened trace columns and opening points into +/// per-height FRI input codewords. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum FriBatching { + /// Legacy Plonky3 Horner powers `1, α, α^2, ...` from a single challenge `α`. + #[default] + Horner, + /// Protocol `v6` multilinear tensor batching `col_weights ⊗ open_weights` + /// using `⌈log2(max_width)⌉ + ⌈log2(max_openings_per_height)⌉` challenges. + Tensor, +} + +impl FriBatching { + /// Canonical protocol tag bound into the `v6` challenger seed. + #[inline] + pub const fn tag(self) -> u64 { + match self { + Self::Horner => 0, + Self::Tensor => 1, + } + } +} + +/// Number of multilinear tensor challenges required to index `count` items: +/// `0` when `count <= 1`, otherwise `⌈log2(count)⌉`. +#[inline] +pub const fn tensor_num_challenges(count: usize) -> usize { + if count <= 1 { + 0 + } else { + log2_ceil_usize(count) + } +} + +/// Expands `challenges` into `len` multilinear tensor weights where index +/// `j = Σ_b j_b 2^b` gets weight `∏_{b: j_b = 1} challenges[b]`. +/// +/// Requires `len <= (1 << challenges.len())`. Uses exactly `len.saturating_sub(1)` +/// field multiplications (matching `alpha.powers().take(len)`). +pub fn tensor_weights(challenges: &[F], len: usize) -> Vec { + if len == 0 { + return Vec::new(); + } + let capacity_bound = 1usize + .checked_shl(u32::try_from(challenges.len()).expect("too many tensor challenges")) + .unwrap_or(usize::MAX); + assert!( + len <= capacity_bound, + "tensor_weights: len {len} exceeds 2^{}", + challenges.len() + ); + let mut weights = Vec::with_capacity(len); + weights.push(F::ONE); + for &r in challenges { + let prev_len = weights.len(); + for i in 0..prev_len { + if weights.len() == len { + break; + } + let w = weights[i] * r; + weights.push(w); + } + } + debug_assert_eq!(weights.len(), len); + weights +} + +/// Packs a slice of extension-field weights into `EF::ExtensionPacking` SIMD +/// vectors suitable for `Matrix::rowwise_packed_dot_product`. +pub fn pack_ext_weights>( + weights: &[EF], +) -> Vec { + let pw = F::Packing::WIDTH; + weights + .chunks(pw) + .map(|chunk| { + EF::ExtensionPacking::from_basis_coefficients_fn(|c| { + F::Packing::from_fn(|lane| { + chunk + .get(lane) + .map_or(F::ZERO, |w| w.as_basis_coefficients_slice()[c]) + }) + }) + }) + .collect() +} + +/// Sampled batching weights shared between the FRI prover and verifier. +#[derive(Clone, Debug)] +pub enum FriBatchingSchedule { + Horner { + alpha: EF, + }, + Tensor { + col_weights: Vec, + open_weights: Vec, + }, +} + +impl FriBatchingSchedule { + /// Samples batching challenges from `challenger` in canonical protocol order. + pub fn sample( + batching: FriBatching, + max_width: usize, + max_openings_per_height: usize, + challenger: &mut Challenger, + ) -> Self + where + Val: Field, + EF: ExtensionField, + Challenger: FieldChallenger, + { + match batching { + FriBatching::Horner => Self::Horner { + alpha: challenger.sample_algebra_element(), + }, + FriBatching::Tensor => { + let k_col = tensor_num_challenges(max_width); + let col_challenges: Vec = (0..k_col) + .map(|_| challenger.sample_algebra_element()) + .collect(); + let k_open = tensor_num_challenges(max_openings_per_height); + let open_challenges: Vec = (0..k_open) + .map(|_| challenger.sample_algebra_element()) + .collect(); + Self::Tensor { + col_weights: tensor_weights(&col_challenges, max_width), + open_weights: tensor_weights(&open_challenges, max_openings_per_height), + } + } + } + } +} + +type FriOpenings = Vec<(usize, F)>; + +/// Verifies a FRI proof under the requested [`FriBatching`] strategy. +/// +/// For [`FriBatching::Horner`], delegates directly to stock +/// [`p3_fri::verifier::verify_fri`] to guarantee 100% compatibility with +/// Plonky3. For [`FriBatching::Tensor`], performs the identical FRI commit, +/// PoW, Merkle multi-batch, fold, and final-polynomial checks using +/// `col_weights ⊗ open_weights` input reduction. +pub fn verify_fri_with_batching( + folding: &Folding, + params: &FriParameters, + proof: &FriProof, + challenger: &mut Challenger, + commitments_with_opening_points: &[CommitmentWithOpeningPoints< + Challenge, + InputMmcs::Commitment, + TwoAdicMultiplicativeCoset, + >], + input_mmcs: &InputMmcs, + batching: FriBatching, +) -> Result<(), FriError> +where + Val: TwoAdicField, + Challenge: ExtensionField, + InputMmcs: Mmcs, + FriMmcs: Mmcs, + Challenger: FieldChallenger + GrindingChallenger + CanObserve, + Folding: FriFoldingStrategy< + Val, + Challenge, + InputError = InputMmcs::Error, + InputProof = Vec>, + >, +{ + match batching { + FriBatching::Horner => verifier::verify_fri( + folding, + params, + proof, + challenger, + commitments_with_opening_points, + input_mmcs, + ), + FriBatching::Tensor => verify_fri_with_batching_inner( + folding, + params, + proof, + challenger, + commitments_with_opening_points, + input_mmcs, + FriBatching::Tensor, + ), + } +} + +/// Core batching-generic FRI verifier (supports both `Horner` and `Tensor`; +/// exposed to tests so `Horner` is cross-checked against `p3_fri::verifier::verify_fri`). +pub(crate) fn verify_fri_with_batching_inner< + Folding, + Val, + Challenge, + InputMmcs, + FriMmcs, + Challenger, +>( + folding: &Folding, + params: &FriParameters, + proof: &FriProof, + challenger: &mut Challenger, + commitments_with_opening_points: &[CommitmentWithOpeningPoints< + Challenge, + InputMmcs::Commitment, + TwoAdicMultiplicativeCoset, + >], + input_mmcs: &InputMmcs, + batching: FriBatching, +) -> Result<(), FriError> +where + Val: TwoAdicField, + Challenge: ExtensionField, + InputMmcs: Mmcs, + FriMmcs: Mmcs, + Challenger: FieldChallenger + GrindingChallenger + CanObserve, + Folding: FriFoldingStrategy< + Val, + Challenge, + InputError = InputMmcs::Error, + InputProof = Vec>, + >, +{ + if params.num_queries == 0 { + return Err(FriError::ZeroQueries); + } + + // Derive max_width and max_openings_per_height from the authenticated + // opening structure before sampling batching challenges. + let mut max_width = 0usize; + let mut openings_per_height: BTreeMap = BTreeMap::new(); + for (batch, (_, mats)) in commitments_with_opening_points.iter().enumerate() { + for (matrix, (domain, points_and_values)) in mats.iter().enumerate() { + let Some((_, first_vals)) = points_and_values.first() else { + return Err(FriError::MatrixWithoutOpeningPoints { batch, matrix }); + }; + let width = first_vals.len(); + for (point, (_, vals)) in points_and_values.iter().enumerate() { + if vals.len() != width { + return Err(FriError::PointEvaluationCountMismatch { + batch, + matrix, + point, + expected: width, + got: vals.len(), + }); + } + } + max_width = max_width.max(width); + let log_height = log2_strict_usize(domain.size()) + params.log_blowup; + *openings_per_height.entry(log_height).or_insert(0) += points_and_values.len(); + } + } + let max_openings_per_height = openings_per_height.values().copied().max().unwrap_or(0); + + let schedule = FriBatchingSchedule::::sample( + batching, + max_width, + max_openings_per_height, + challenger, + ); + + let expected_rounds = proof.commit_phase_commits.len(); + if proof.commit_phase_openings.len() != expected_rounds { + return Err(FriError::CommitPhaseOpeningsCountMismatch { + expected: expected_rounds, + got: proof.commit_phase_openings.len(), + }); + } + + let log_arities: Vec = proof + .commit_phase_openings + .iter() + .enumerate() + .map(|(round, opening)| { + let log_arity = usize::from(opening.log_arity); + if (1..=params.max_log_arity).contains(&log_arity) { + Ok(log_arity) + } else { + Err(FriError::InvalidLogArity { + round, + log_arity, + max: params.max_log_arity, + }) + } + }) + .collect::, _>>()?; + + for (round, (opening, &log_arity)) in proof + .commit_phase_openings + .iter() + .zip(&log_arities) + .enumerate() + { + if opening.sibling_values.len() != params.num_queries { + return Err(FriError::CommitPhaseQueryCountMismatch { + round, + expected: params.num_queries, + got: opening.sibling_values.len(), + }); + } + let arity = 1usize << log_arity; + for siblings in &opening.sibling_values { + if siblings.len() != arity - 1 { + return Err(FriError::SiblingValuesLengthMismatch { + round, + expected: arity - 1, + got: siblings.len(), + }); + } + } + } + + let total_log_reduction: usize = log_arities.iter().sum(); + let log_global_max_height = total_log_reduction + params.log_blowup + params.log_final_poly_len; + + if log_global_max_height > Val::TWO_ADICITY { + return Err(FriError::GlobalMaxHeightTooLarge { + log_global_max_height, + two_adicity: Val::TWO_ADICITY, + }); + } + + let expected_log_global_max_height = commitments_with_opening_points + .iter() + .flat_map(|(_, mats)| { + mats.iter() + .map(|(domain, _)| log2_strict_usize(domain.size()) + params.log_blowup) + }) + .max(); + if let Some(expected) = expected_log_global_max_height + && log_global_max_height != expected + { + return Err(FriError::GlobalMaxHeightMismatch { + expected, + got: log_global_max_height, + }); + } + + if proof.commit_pow_witnesses.len() != proof.commit_phase_commits.len() { + return Err(FriError::CommitPowWitnessCountMismatch { + expected: proof.commit_phase_commits.len(), + got: proof.commit_pow_witnesses.len(), + }); + } + + let betas: Vec = proof + .commit_phase_commits + .iter() + .zip(&proof.commit_pow_witnesses) + .map(|(comm, witness)| { + challenger.observe(comm.clone()); + if !challenger.check_witness(params.commit_proof_of_work_bits, *witness) { + return Err(FriError::InvalidPowWitness); + } + Ok(challenger.sample_algebra_element()) + }) + .collect::, _>>()?; + + if proof.final_poly.len() != params.final_poly_len() { + return Err(FriError::FinalPolyLengthMismatch { + expected: params.final_poly_len(), + got: proof.final_poly.len(), + }); + } + + challenger.observe_algebra_slice(&proof.final_poly); + + for &log_arity in &log_arities { + challenger.observe(Val::from_usize(log_arity)); + } + + if !challenger.check_witness(params.query_proof_of_work_bits, proof.query_pow_witness) { + return Err(FriError::InvalidPowWitness); + } + + let log_final_height = params.log_blowup + params.log_final_poly_len; + + let indices: Vec = iter::repeat_with(|| { + challenger.sample_bits(log_global_max_height + folding.extra_query_index_bits()) + }) + .take(params.num_queries) + .collect(); + + let reduced_openings = open_inputs_with_schedule( + params, + log_global_max_height, + &indices, + &proof.input_openings, + &schedule, + input_mmcs, + commitments_with_opening_points, + )?; + + let num_rounds = proof.commit_phase_commits.len(); + let mut group_indices_by_round: Vec> = + vec![Vec::with_capacity(params.num_queries); num_rounds]; + let mut rows_by_round: Vec>>> = + vec![Vec::with_capacity(params.num_queries); num_rounds]; + + for (query, (&index, ro)) in indices.iter().zip(reduced_openings).enumerate() { + let mut domain_index = index >> folding.extra_query_index_bits(); + let folded_eval = fold_query( + folding, + query, + &mut domain_index, + &betas, + &log_arities, + &proof.commit_phase_openings, + ro, + log_global_max_height, + log_final_height, + &mut group_indices_by_round, + &mut rows_by_round, + )?; + + let rev_idx = u64::try_from(reverse_bits_len(domain_index, log_global_max_height)) + .expect("query index exceeds u64"); + let x = Val::two_adic_generator(log_global_max_height).exp_u64(rev_idx); + let eval: Challenge = proof.final_poly.iter().copied().horner(x); + if eval != folded_eval { + return Err(FriError::FinalPolyMismatch); + } + } + + let mut log_current_height = log_global_max_height; + for (round, ((commit, opening), &log_arity)) in proof + .commit_phase_commits + .iter() + .zip(&proof.commit_phase_openings) + .zip(&log_arities) + .enumerate() + { + let arity = 1usize << log_arity; + let log_folded_height = log_current_height - log_arity; + let dims = &[Dimensions { + width: arity, + height: 1usize << log_folded_height, + }]; + params + .mmcs + .verify_multi_batch( + commit, + dims, + &group_indices_by_round[round], + &rows_by_round[round], + &opening.opening_proof, + ) + .map_err(FriError::CommitPhaseMmcsError)?; + log_current_height = log_folded_height; + } + + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +#[inline] +fn fold_query( + folding: &Folding, + query: usize, + start_index: &mut usize, + betas: &[EF], + log_arities: &[usize], + commit_phase_openings: &[CommitPhaseMultiStep], + reduced_openings: FriOpenings, + log_global_max_height: usize, + log_final_height: usize, + group_indices_by_round: &mut [Vec], + rows_by_round: &mut [Vec>>], +) -> Result> +where + F: Field, + EF: ExtensionField, + M: Mmcs, + Folding: FriFoldingStrategy, +{ + let mut ro_iter = reduced_openings.into_iter().peekable(); + + let Some((first_log_height, _)) = ro_iter.peek() else { + return Err(FriError::MissingInitialReducedOpening { + expected: log_global_max_height, + }); + }; + if *first_log_height != log_global_max_height { + return Err(FriError::InitialReducedOpeningHeightMismatch { + expected: log_global_max_height, + got: *first_log_height, + }); + } + let mut folded_eval = ro_iter.next().unwrap().1; + let mut log_current_height = log_global_max_height; + + for (round, ((&beta, &log_arity), opening)) in betas + .iter() + .zip(log_arities) + .zip(commit_phase_openings) + .enumerate() + { + let arity = 1usize << log_arity; + let index_in_group = *start_index % arity; + let mut evals = EF::zero_vec(arity); + evals[index_in_group] = folded_eval; + + let siblings = &opening.sibling_values[query]; + let mut sibling_idx = 0; + for (j, eval) in evals.iter_mut().enumerate() { + if j != index_in_group { + *eval = siblings[sibling_idx]; + sibling_idx += 1; + } + } + + let log_folded_height = log_current_height - log_arity; + *start_index >>= log_arity; + + folded_eval = folding.fold_row( + *start_index, + log_folded_height, + log_arity, + beta, + evals.iter().copied(), + ); + + group_indices_by_round[round].push(*start_index); + rows_by_round[round].push(vec![evals]); + log_current_height = log_folded_height; + + if let Some((_, ro)) = ro_iter.next_if(|(lh, _)| *lh == log_folded_height) { + let beta_pow = beta.exp_power_of_2(log_arity); + folded_eval += beta_pow * ro; + } + } + + if log_current_height != log_final_height { + return Err(FriError::FinalFoldHeightMismatch { + expected: log_final_height, + got: log_current_height, + }); + } + + if let Some((next_log_height, _)) = ro_iter.next() { + return Err(FriError::UnconsumedReducedOpenings { + next_log_height, + remaining: 1 + ro_iter.count(), + }); + } + + Ok(folded_eval) +} + +#[allow(clippy::type_complexity)] +fn open_inputs_with_schedule( + params: &FriParameters, + log_global_max_height: usize, + indices: &[usize], + input_openings: &[BatchMultiOpening], + schedule: &FriBatchingSchedule, + input_mmcs: &InputMmcs, + commitments_with_opening_points: &[CommitmentWithOpeningPoints< + Challenge, + InputMmcs::Commitment, + TwoAdicMultiplicativeCoset, + >], +) -> Result>, FriError> +where + Val: TwoAdicField, + Challenge: ExtensionField, + InputMmcs: Mmcs, + FriMmcs: Mmcs, +{ + if input_openings.len() != commitments_with_opening_points.len() { + return Err(FriError::InputProofBatchCountMismatch { + expected: commitments_with_opening_points.len(), + got: input_openings.len(), + }); + } + + for (batch, (batch_opening, (batch_commit, mats))) in input_openings + .iter() + .zip(commitments_with_opening_points.iter()) + .enumerate() + { + if batch_opening.opened_values.len() != indices.len() { + return Err(FriError::InputOpeningsQueryCountMismatch { + batch, + expected: indices.len(), + got: batch_opening.opened_values.len(), + }); + } + for opened_values in &batch_opening.opened_values { + if opened_values.len() != mats.len() { + return Err(FriError::BatchOpenedValuesCountMismatch { + batch, + expected: mats.len(), + got: opened_values.len(), + }); + } + } + let batch_heights: Vec = mats + .iter() + .map(|(domain, _)| domain.size() << params.log_blowup) + .collect(); + let batch_dims: Vec = batch_heights + .iter() + .zip(mats) + .enumerate() + .map(|(matrix, (&height, (_, points_and_values)))| { + let (_, values) = points_and_values + .first() + .ok_or(FriError::MatrixWithoutOpeningPoints { batch, matrix })?; + Ok(Dimensions { + width: values.len(), + height, + }) + }) + .collect::, _>>()?; + + let reduced_indices: Vec = batch_heights.iter().max().map_or_else( + || vec![0; indices.len()], + |&h| { + let bits_reduced = log_global_max_height - log2_strict_usize(h); + indices.iter().map(|&index| index >> bits_reduced).collect() + }, + ); + + input_mmcs + .verify_multi_batch( + batch_commit, + &batch_dims, + &reduced_indices, + &batch_opening.opened_values, + &batch_opening.opening_proof, + ) + .map_err(FriError::InputError)?; + } + + let mut denominators = Vec::new(); + for &index in indices { + for (batch, (_, mats)) in commitments_with_opening_points.iter().enumerate() { + for (matrix, (mat_domain, mat_points_and_values)) in mats.iter().enumerate() { + let log_height = log2_strict_usize(mat_domain.size()) + params.log_blowup; + let bits_reduced = log_global_max_height - log_height; + let rev_reduced_index = + u64::try_from(reverse_bits_len(index >> bits_reduced, log_height)) + .expect("reduced query index exceeds u64"); + let x = + Val::GENERATOR * Val::two_adic_generator(log_height).exp_u64(rev_reduced_index); + + for (point, (z, _)) in mat_points_and_values.iter().enumerate() { + let denominator = *z - x; + if denominator.is_zero() { + return Err(FriError::OpeningPointMatchesQueryPoint { + batch, + matrix, + point, + }); + } + denominators.push(denominator); + } + } + } + } + let mut inverse_denominators = batch_multiplicative_inverse(&denominators).into_iter(); + + indices + .iter() + .enumerate() + .map(|(query, _)| match schedule { + FriBatchingSchedule::Horner { alpha } => { + let mut reduced_openings = BTreeMap::::new(); + for (batch, (batch_opening, (_, mats))) in input_openings + .iter() + .zip(commitments_with_opening_points.iter()) + .enumerate() + { + for (matrix, (mat_opening, (mat_domain, mat_points_and_values))) in + batch_opening.opened_values[query] + .iter() + .zip(mats.iter()) + .enumerate() + { + let log_height = log2_strict_usize(mat_domain.size()) + params.log_blowup; + let (alpha_pow, ro) = reduced_openings + .entry(log_height) + .or_insert((Challenge::ONE, Challenge::ZERO)); + + for (point, (_z, ps_at_z)) in mat_points_and_values.iter().enumerate() { + if mat_opening.len() != ps_at_z.len() { + return Err(FriError::PointEvaluationCountMismatch { + batch, + matrix, + point, + expected: mat_opening.len(), + got: ps_at_z.len(), + }); + } + let inv_denom = inverse_denominators + .next() + .expect("one inverse was precomputed per opening point"); + for (&p_at_x, &p_at_z) in mat_opening.iter().zip(ps_at_z.iter()) { + *ro += *alpha_pow * (p_at_z - p_at_x) * inv_denom; + *alpha_pow *= *alpha; + } + } + } + } + if let Some((_, ro)) = reduced_openings.get(¶ms.log_blowup) + && !ro.is_zero() + { + return Err(FriError::FinalPolyMismatch); + } + Ok(reduced_openings + .into_iter() + .rev() + .map(|(log_height, (_, ro))| (log_height, ro)) + .collect()) + } + FriBatchingSchedule::Tensor { + col_weights, + open_weights, + } => { + let mut reduced_openings = BTreeMap::::new(); + for (batch, (batch_opening, (_, mats))) in input_openings + .iter() + .zip(commitments_with_opening_points.iter()) + .enumerate() + { + for (matrix, (mat_opening, (mat_domain, mat_points_and_values))) in + batch_opening.opened_values[query] + .iter() + .zip(mats.iter()) + .enumerate() + { + let log_height = log2_strict_usize(mat_domain.size()) + params.log_blowup; + let (opening_idx, ro) = reduced_openings + .entry(log_height) + .or_insert((0usize, Challenge::ZERO)); + + for (point, (_z, ps_at_z)) in mat_points_and_values.iter().enumerate() { + if mat_opening.len() != ps_at_z.len() { + return Err(FriError::PointEvaluationCountMismatch { + batch, + matrix, + point, + expected: mat_opening.len(), + got: ps_at_z.len(), + }); + } + let inv_denom = inverse_denominators + .next() + .expect("one inverse was precomputed per opening point"); + let mut col_acc = Challenge::ZERO; + for ((&w_col, &p_at_x), &p_at_z) in col_weights + .iter() + .zip(mat_opening.iter()) + .zip(ps_at_z.iter()) + { + col_acc += w_col * (p_at_z - p_at_x); + } + let w_open = open_weights[*opening_idx]; + *opening_idx += 1; + *ro += w_open * col_acc * inv_denom; + } + } + } + if let Some((_, ro)) = reduced_openings.get(¶ms.log_blowup) + && !ro.is_zero() + { + return Err(FriError::FinalPolyMismatch); + } + Ok(reduced_openings + .into_iter() + .rev() + .map(|(log_height, (_, ro))| (log_height, ro)) + .collect()) + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use p3_field::PrimeCharacteristicRing; + use p3_field::extension::CubicTrinomialExtensionField; + use p3_goldilocks::Goldilocks; + use p3_matrix::Matrix; + use p3_matrix::dense::RowMajorMatrix; + use p3_maybe_rayon::prelude::*; + + type Ext3 = CubicTrinomialExtensionField; + + #[test] + fn tensor_weights_match_explicit_multilinear_monomials() { + let r = [ + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::from_u64(3), + Goldilocks::from_u64(5), + Goldilocks::from_u64(7), + ]) + .unwrap(), + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::from_u64(11), + Goldilocks::from_u64(13), + Goldilocks::from_u64(17), + ]) + .unwrap(), + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::from_u64(19), + Goldilocks::from_u64(23), + Goldilocks::from_u64(29), + ]) + .unwrap(), + ]; + + assert!(tensor_weights::(&[], 0).is_empty()); + assert_eq!(tensor_weights::(&[], 1), vec![Ext3::ONE]); + + for len in 1..=8 { + let k = tensor_num_challenges(len); + let got = tensor_weights(&r[..k], len); + assert_eq!(got.len(), len); + for (j, &w) in got.iter().enumerate() { + let mut expected = Ext3::ONE; + for (bit, &rb) in r[..k].iter().enumerate() { + if (j >> bit) & 1 == 1 { + expected *= rb; + } + } + assert_eq!(w, expected, "len={len} j={j}"); + } + } + } + + #[test] + fn packed_ext_weights_dot_product_matches_scalar_for_cubic_extension() { + let mut challenges = Vec::new(); + for i in 0..5u64 { + challenges.push( + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::from_u64(3 * i + 2), + Goldilocks::from_u64(5 * i + 7), + Goldilocks::from_u64(11 * i + 13), + ]) + .unwrap(), + ); + } + let max_width = 25usize; + let weights = tensor_weights(&challenges, max_width); + let packed = pack_ext_weights::(&weights); + + for width in [1usize, 3, 4, 7, 8, 17, 25] { + let height = 16usize; + let mat = RowMajorMatrix::new( + (0..height * width) + .map(|i| Goldilocks::from_u64(u64::try_from(i * 37 + 11).unwrap())) + .collect(), + width, + ); + let got: Vec = mat + .as_view() + .rowwise_packed_dot_product::(&packed) + .collect(); + for (r, &got_val) in got.iter().enumerate() { + let mut expected = Ext3::ZERO; + for (c, &w) in weights.iter().enumerate().take(width) { + expected += w * mat.values[r * width + c]; + } + assert_eq!(got_val, expected, "width={width} row={r}"); + } + } + } + + fn run_pcs_horner_parity_and_tensor_roundtrip() + where + EF: ExtensionField + crate::traits::ExtensionOf, + { + use crate::p3_adapter::challenger::DomainChallenger; + use crate::p3_adapter::domain_blake3::Blake3Domain; + use crate::p3_adapter::spill::{SpillableMmcs, SpillableTwoAdicFriPcs}; + use p3_commit::{ExtensionMmcs, Pcs, PolynomialSpace}; + use p3_dft::Radix2DitParallel; + use p3_fri::TwoAdicFriFolding; + + type Ch = DomainChallenger; + + let make_pcs = |batching: FriBatching| { + let mmcs = SpillableMmcs::new_v6(1); + let ext_mmcs = ExtensionMmcs::::new(mmcs.clone()); + let fri_params = FriParameters { + log_blowup: 2, + log_final_poly_len: 1, + max_log_arity: 2, + num_queries: 12, + commit_proof_of_work_bits: 2, + query_proof_of_work_bits: 2, + mmcs: ext_mmcs, + }; + SpillableTwoAdicFriPcs::new( + Radix2DitParallel::::default(), + mmcs, + fri_params, + ) + .with_batching(batching) + }; + + let make_mat = |height: usize, width: usize, salt: u64| { + RowMajorMatrix::new( + (0..height * width) + .map(|i| { + Goldilocks::from_u64( + u64::try_from(i).unwrap().wrapping_mul(salt) + 17 + salt, + ) + }) + .collect(), + width, + ) + }; + + // Two batches with distinct heights and widths (including width=1). + let pcs_horner = make_pcs(FriBatching::Horner); + let dom16 = Pcs::>::natural_domain_for_degree(&pcs_horner, 16); + let dom32 = Pcs::>::natural_domain_for_degree(&pcs_horner, 32); + let dom64 = Pcs::>::natural_domain_for_degree(&pcs_horner, 64); + + let batch0 = vec![(dom32, make_mat(32, 5, 31)), (dom16, make_mat(16, 1, 53))]; + let batch1 = vec![(dom64, make_mat(64, 13, 97)), (dom32, make_mat(32, 7, 131))]; + + let zeta: EF = >::from_basis_coefficients_fn(|i| { + Goldilocks::from_u64(1001 + i as u64 * 37) + }); + let zeta_next_32 = zeta * dom32.first_point() * dom32.next_point(Goldilocks::ONE).unwrap(); + let zeta_next_64 = zeta * dom64.next_point(Goldilocks::ONE).unwrap(); + + // 1. Horner parity: verify_fri_with_batching_inner(..., Horner) matches stock p3_fri::verifier::verify_fri + let (c0, d0) = Pcs::>::commit(&pcs_horner, batch0.clone()); + let (c1, d1) = Pcs::>::commit(&pcs_horner, batch1.clone()); + let make_ch = |seed: &[u8], a: &_, b: &_| { + let mut ch = Ch::::from_domain(seed.to_vec(), Blake3Domain::TranscriptSingle); + ch.observe(Clone::clone(a)); + ch.observe(Clone::clone(b)); + ch + }; + let mut p_ch = make_ch(b"fri-parity", &c0, &c1); + + let (opened_h, proof_h) = Pcs::>::open( + &pcs_horner, + vec![ + (&d0, vec![vec![zeta, zeta_next_32], vec![zeta]]), + ( + &d1, + vec![vec![zeta, zeta_next_64], vec![zeta, zeta_next_32]], + ), + ], + &mut p_ch, + ); + + let commit_and_openings = vec![ + ( + c0.clone(), + vec![ + ( + dom32, + vec![ + (zeta, opened_h[0][0][0].clone()), + (zeta_next_32, opened_h[0][0][1].clone()), + ], + ), + (dom16, vec![(zeta, opened_h[0][1][0].clone())]), + ], + ), + ( + c1.clone(), + vec![ + ( + dom64, + vec![ + (zeta, opened_h[1][0][0].clone()), + (zeta_next_64, opened_h[1][0][1].clone()), + ], + ), + ( + dom32, + vec![ + (zeta, opened_h[1][1][0].clone()), + (zeta_next_32, opened_h[1][1][1].clone()), + ], + ), + ], + ), + ]; + + type OpeningSpec = CommitmentWithOpeningPoints< + EF, + p3_merkle_tree::MerkleCap, + TwoAdicMultiplicativeCoset, + >; + let observe_openings = |ch: &mut Ch, openings: &[OpeningSpec]| { + for (_, round) in openings { + for (_, mat) in round { + for (_, vals) in mat { + ch.observe_algebra_slice(vals); + } + } + } + }; + + let mut v_stock = make_ch(b"fri-parity", &c0, &c1); + observe_openings(&mut v_stock, &commit_and_openings); + let mut v_inner = v_stock.clone(); + + let fri_params_ref = FriParameters { + log_blowup: 2, + log_final_poly_len: 1, + max_log_arity: 2, + num_queries: 12, + commit_proof_of_work_bits: 2, + query_proof_of_work_bits: 2, + mmcs: ExtensionMmcs::::new(SpillableMmcs::new_v6(1)), + }; + let input_mmcs = SpillableMmcs::new_v6(1); + + let folding = TwoAdicFriFolding(core::marker::PhantomData); + + verifier::verify_fri( + &folding, + &fri_params_ref, + &proof_h, + &mut v_stock, + &commit_and_openings, + &input_mmcs, + ) + .expect("stock p3_fri::verifier::verify_fri should accept"); + + verify_fri_with_batching_inner( + &folding, + &fri_params_ref, + &proof_h, + &mut v_inner, + &commit_and_openings, + &input_mmcs, + FriBatching::Horner, + ) + .expect("verify_fri_with_batching_inner(Horner) should accept"); + + // Post-verification transcript states must be identical! + let s1: EF = v_stock.sample_algebra_element(); + let s2: EF = v_inner.sample_algebra_element(); + assert_eq!( + s1, s2, + "Horner verifier transcript diverged from stock p3_fri" + ); + + // Tampered opened value must be rejected by both verifiers. + let ef_one = ::ONE; + let mut tampered = commit_and_openings.clone(); + tampered[1].1[0].1[0].1[0] += ef_one; + let mut v_bad1 = make_ch(b"fri-parity", &c0, &c1); + observe_openings(&mut v_bad1, &tampered); + let mut v_bad2 = v_bad1.clone(); + assert!( + verifier::verify_fri( + &folding, + &fri_params_ref, + &proof_h, + &mut v_bad1, + &tampered, + &input_mmcs, + ) + .is_err() + ); + assert!( + verify_fri_with_batching_inner( + &folding, + &fri_params_ref, + &proof_h, + &mut v_bad2, + &tampered, + &input_mmcs, + FriBatching::Horner, + ) + .is_err() + ); + + // Cross-check: Horner proof must fail under Tensor verifier. + let pcs_tensor = make_pcs(FriBatching::Tensor); + let mut v_cross = make_ch(b"fri-parity", &c0, &c1); + assert!( + Pcs::>::verify( + &pcs_tensor, + commit_and_openings.clone(), + &proof_h, + &mut v_cross, + ) + .is_err(), + "Horner proof must not verify under Tensor batching" + ); + + // 2. Tensor roundtrip: prove & verify, reject tampering & Horner cross-verify. + let (tc0, td0) = Pcs::>::commit(&pcs_tensor, batch0); + let (tc1, td1) = Pcs::>::commit(&pcs_tensor, batch1); + assert_eq!(tc0, c0); + assert_eq!(tc1, c1); + + let mut tp_ch = make_ch(b"fri-tensor", &tc0, &tc1); + + let (opened_t, proof_t) = Pcs::>::open( + &pcs_tensor, + vec![ + (&td0, vec![vec![zeta, zeta_next_32], vec![zeta]]), + ( + &td1, + vec![vec![zeta, zeta_next_64], vec![zeta, zeta_next_32]], + ), + ], + &mut tp_ch, + ); + assert_eq!( + opened_t, opened_h, + "opened evaluations are independent of batching" + ); + + let t_commit_and_openings = commit_and_openings; + let mut tv_ch = make_ch(b"fri-tensor", &tc0, &tc1); + Pcs::>::verify( + &pcs_tensor, + t_commit_and_openings.clone(), + &proof_t, + &mut tv_ch, + ) + .expect("Tensor FRI proof should verify"); + + // Tampered opened value fails under Tensor verifier. + let mut tv_bad = make_ch(b"fri-tensor", &tc0, &tc1); + assert!( + Pcs::>::verify(&pcs_tensor, tampered, &proof_t, &mut tv_bad).is_err(), + "Tensor verifier must reject tampered opened value" + ); + + // Tampered final_poly fails under Tensor verifier. + let mut bad_proof = proof_t.clone(); + bad_proof.final_poly[0] += ef_one; + let mut tv_bad2 = make_ch(b"fri-tensor", &tc0, &tc1); + assert!( + Pcs::>::verify( + &pcs_tensor, + t_commit_and_openings.clone(), + &bad_proof, + &mut tv_bad2, + ) + .is_err(), + "Tensor verifier must reject tampered final_poly" + ); + + // Tensor proof fails under Horner verifier. + let mut hv_cross = make_ch(b"fri-tensor", &tc0, &tc1); + assert!( + Pcs::>::verify(&pcs_horner, t_commit_and_openings, &proof_t, &mut hv_cross,) + .is_err(), + "Tensor proof must not verify under Horner batching" + ); + } + + #[test] + fn fri_batching_horner_parity_and_tensor_fp2_and_fp3() { + run_pcs_horner_parity_and_tensor_roundtrip::(); + run_pcs_horner_parity_and_tensor_roundtrip::(); + } +} diff --git a/src/p3_adapter/mod.rs b/src/p3_adapter/mod.rs index aed6546..c12a12a 100644 --- a/src/p3_adapter/mod.rs +++ b/src/p3_adapter/mod.rs @@ -6,7 +6,9 @@ mod air; pub(crate) mod blake3_simd; pub mod challenger; pub mod domain; +pub mod domain_blake3; pub mod field; +pub mod fri_batching; pub mod pcs; #[cfg(not(feature = "cuda"))] pub mod spill; diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs index 78fd636..b3cf06c 100644 --- a/src/p3_adapter/spill.rs +++ b/src/p3_adapter/spill.rs @@ -21,17 +21,16 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; -use p3_blake3::Blake3; use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; use p3_commit::{BatchOpening, BatchOpeningRef, Mmcs, OpenedValues, Pcs, PeriodicLdeTable}; use p3_dft::TwoAdicSubgroupDft; use p3_field::coset::TwoAdicMultiplicativeCoset; use p3_field::{ BasedVectorSpace, ExtensionField, Field, PackedFieldExtension, PackedValue, - PrimeCharacteristicRing, PrimeField64, TwoAdicField, dot_product, + PrimeCharacteristicRing, PrimeField64, TwoAdicField, batch_multiplicative_inverse, dot_product, scale_slice_in_place_single_core, }; -use p3_fri::verifier::{self, FriError}; +use p3_fri::verifier::FriError; use p3_fri::{ BatchMultiOpening, CommitmentWithOpeningPoints, FriParameters, FriProof, ProverDataWithOpeningPoints, TwoAdicFriFolding, TwoAdicFriFoldingForMmcs, @@ -44,17 +43,31 @@ use p3_matrix::interpolation::{Interpolate, compute_adjusted_weights}; use p3_matrix::{Dimensions, Matrix}; use p3_maybe_rayon::prelude::*; use p3_merkle_tree::{MerkleTreeMmcs, PrunedMerklePaths}; -use p3_symmetric::{CryptographicHasher, MerkleCap, SerializingHasher}; +use p3_symmetric::{ + CompressionFunctionFromHasher, CryptographicHasher, MerkleCap, SerializingHasher, +}; use p3_util::linear_map::LinearMap; use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_slice_index_bits}; use tracing::debug_span; use super::blake3_simd; -use crate::types::{Blake3CompressionFunction, ExtVal, PackedVal, Val}; - -/// CPU reference MMCS used for verification and reference tests. -pub type CpuMmcs = - MerkleTreeMmcs, Blake3CompressionFunction, 2, 32>; +use super::domain_blake3::{Blake3Domain, DomainBlake3}; +use super::fri_batching::{ + FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, +}; +use crate::traits::{ExtensionModulus, ExtensionOf}; +use crate::types::{PackedVal, Val}; + +/// CPU reference MMCS supporting both legacy `v5` (plain BLAKE3) and `v6` +/// (domain-separated BLAKE3 `derive_key`) Merkle trees. +pub type CpuMmcs = MerkleTreeMmcs< + Val, + u8, + SerializingHasher, + CompressionFunctionFromHasher, + 2, + 32, +>; type SpillCommitResult = ( >::Commitment, SpillableMmcsData>, @@ -249,12 +262,13 @@ impl SpillPackWriter { pub(crate) fn append_matrix_and_hash( &mut self, mat: &RowMajorMatrix, + leaf_domain: Blake3Domain, ) -> (SpilledMatrix, Vec<[u8; 32]>) { let height = mat.height(); let width = mat.width(); let offset = self.next_offset; if width == 0 { - let empty_digest = Blake3.hash_slice(&[]); + let empty_digest = DomainBlake3::new(leaf_domain).hash_slice(&[]); return ( SpilledMatrix { file: Arc::clone(&self.spill), @@ -281,6 +295,7 @@ impl SpillPackWriter { &self.scratch[..byte_len], row_bytes, &mut dst[row_start..row_start + n_rows], + leaf_domain, ); self.writer .write_all(&self.scratch[..byte_len]) @@ -566,7 +581,7 @@ struct FastInMemoryMerkleTree { } impl> FastInMemoryMerkleTree { - fn build(leaves: Vec) -> Self { + fn build(leaves: Vec, leaf_domain: Blake3Domain, compress_domain: Blake3Domain) -> Self { assert!(!leaves.is_empty(), "No matrices given?"); let max_height = validate_reachable_heights_iter(leaves.iter().map(Matrix::height)); @@ -584,7 +599,7 @@ impl> FastInMemoryMerkleTree { // SAFETY: `hash_matrix_rows_uninit` initializes every element of `dst` (`0..max_height`). let first_layer = unsafe { blake3_simd::alloc_and_fill_digests(padded_len_binary(max_height), max_height, |dst| { - blake3_simd::hash_matrix_rows_uninit(&tallest_refs, 0, dst); + blake3_simd::hash_matrix_rows_uninit(&tallest_refs, 0, dst, leaf_domain); }) }; @@ -609,10 +624,15 @@ impl> FastInMemoryMerkleTree { let inject_group = &order[inject_start..cursor]; let next_digests = if inject_group.is_empty() { - compress_layer_binary(prev_layer) + compress_layer_binary(prev_layer, compress_domain) } else { let inject_refs: Vec<&M> = inject_group.iter().map(|&idx| &leaves[idx]).collect(); - compress_and_inject_in_memory(prev_layer, &inject_refs) + compress_and_inject_in_memory( + prev_layer, + &inject_refs, + leaf_domain, + compress_domain, + ) }; arity_schedule.push(step); digest_layers.push(next_digests); @@ -715,6 +735,8 @@ impl SpilledMerkleTree { matrices: Vec, original_traces: Vec>, mut prehashed: Vec>>, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, ) -> Self { assert!(!matrices.is_empty(), "No matrices given?"); let max_height = @@ -739,7 +761,7 @@ impl SpilledMerkleTree { digests.resize(padded_len_binary(max_height), [0u8; 32]); digests } else { - hash_leaf_group_streaming(&matrices, tallest, max_height) + hash_leaf_group_streaming(&matrices, tallest, max_height, leaf_domain) }; let mut digest_layers = vec![first_layer]; let mut arity_schedule = Vec::new(); @@ -762,13 +784,19 @@ impl SpilledMerkleTree { let inject_group = &order[inject_start..cursor]; let next_digests = if inject_group.is_empty() { - compress_layer_binary(prev_layer) + compress_layer_binary(prev_layer, compress_domain) } else if let &[single_idx] = inject_group && let Some(rows_digests) = prehashed.get_mut(single_idx).and_then(Option::take) { - compress_and_inject_prehashed(prev_layer, &rows_digests) + compress_and_inject_prehashed(prev_layer, &rows_digests, compress_domain) } else { - compress_and_inject_streaming(prev_layer, &matrices, inject_group) + compress_and_inject_streaming( + prev_layer, + &matrices, + inject_group, + leaf_domain, + compress_domain, + ) }; arity_schedule.push(step); digest_layers.push(next_digests); @@ -897,6 +925,7 @@ fn hash_leaf_group_streaming( matrices: &[SpilledMatrix], group: &[usize], max_height: usize, + leaf_domain: Blake3Domain, ) -> Vec<[u8; 32]> { let padded = padded_len_binary(max_height); let block_rows = block_rows_for_group(matrices, group, max_height); @@ -913,19 +942,23 @@ fn hash_leaf_group_streaming( (m.read_raw_rows(start, n_rows), m.row_bytes()) }) .collect(); - blake3_simd::hash_raw_multi_rows_uninit(&blocks, &mut dst[start..start + n_rows]); + blake3_simd::hash_raw_multi_rows_uninit( + &blocks, + &mut dst[start..start + n_rows], + leaf_domain, + ); } }) } } -fn compress_layer_binary(prev_layer: &[[u8; 32]]) -> Vec<[u8; 32]> { +fn compress_layer_binary(prev_layer: &[[u8; 32]], compress_domain: Blake3Domain) -> Vec<[u8; 32]> { let raw_next = prev_layer.len() / 2; let next_len_padded = padded_len_binary(raw_next); // SAFETY: `compress_pairs_uninit` initializes every element of `dst` (`0..raw_next`). unsafe { blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { - blake3_simd::compress_pairs_uninit(prev_layer, dst); + blake3_simd::compress_pairs_uninit(prev_layer, dst, compress_domain); }) } } @@ -933,6 +966,7 @@ fn compress_layer_binary(prev_layer: &[[u8; 32]]) -> Vec<[u8; 32]> { fn compress_and_inject_prehashed( prev_layer: &[[u8; 32]], rows_digests: &[[u8; 32]], + compress_domain: Blake3Domain, ) -> Vec<[u8; 32]> { let next_len = rows_digests.len(); let raw_next = prev_layer.len() / 2; @@ -945,6 +979,7 @@ fn compress_and_inject_prehashed( prev_layer, rows_digests, &mut dst[..next_len], + compress_domain, ); if raw_next > next_len { let zeros = vec![[0u8; 32]; raw_next - next_len]; @@ -952,6 +987,7 @@ fn compress_and_inject_prehashed( &prev_layer[2 * next_len..], &zeros, &mut dst[next_len..raw_next], + compress_domain, ); } }) @@ -961,6 +997,8 @@ fn compress_and_inject_prehashed( fn compress_and_inject_in_memory>( prev_layer: &[[u8; 32]], inject_group: &[&M], + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, ) -> Vec<[u8; 32]> { let next_len = inject_group[0].height(); let raw_next = prev_layer.len() / 2; @@ -974,11 +1012,17 @@ fn compress_and_inject_in_memory>( blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { for start in (0..next_len).step_by(BLOCK_ROWS) { let n_rows = (next_len - start).min(BLOCK_ROWS); - blake3_simd::hash_matrix_rows(inject_group, start, &mut row_digests[..n_rows]); + blake3_simd::hash_matrix_rows( + inject_group, + start, + &mut row_digests[..n_rows], + leaf_domain, + ); blake3_simd::compress_and_inject_from_digests_uninit( &prev_layer[2 * start..], &row_digests[..n_rows], &mut dst[start..start + n_rows], + compress_domain, ); } @@ -988,6 +1032,7 @@ fn compress_and_inject_in_memory>( &prev_layer[2 * next_len..], &zeros, &mut dst[next_len..raw_next], + compress_domain, ); } }) @@ -998,6 +1043,8 @@ fn compress_and_inject_streaming( prev_layer: &[[u8; 32]], matrices: &[SpilledMatrix], inject_group: &[usize], + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, ) -> Vec<[u8; 32]> { let next_len = matrices[inject_group[0]].height(); let raw_next = prev_layer.len() / 2; @@ -1018,11 +1065,12 @@ fn compress_and_inject_streaming( (m.read_raw_rows(start, n_rows), m.row_bytes()) }) .collect(); - blake3_simd::hash_raw_multi_rows(&blocks, &mut row_digests[..n_rows]); + blake3_simd::hash_raw_multi_rows(&blocks, &mut row_digests[..n_rows], leaf_domain); blake3_simd::compress_and_inject_from_digests_uninit( &prev_layer[2 * start..], &row_digests[..n_rows], &mut dst[start..start + n_rows], + compress_domain, ); } @@ -1032,6 +1080,7 @@ fn compress_and_inject_streaming( &prev_layer[2 * next_len..], &zeros, &mut dst[next_len..raw_next], + compress_domain, ); } }) @@ -1115,33 +1164,65 @@ impl SpillableMmcsData { /// CPU MMCS supporting both in-memory commitments (default, accelerated via /// multi-buffer SIMD BLAKE3) and disk-spilled commitments with identical -/// commitments and opening proofs. +/// commitments and opening proofs, in both legacy `v5` (plain BLAKE3) and +/// protocol `v6` (domain-separated `derive_key` BLAKE3) modes. #[derive(Clone, Debug)] pub struct SpillableMmcs { cpu: CpuMmcs, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, } impl SpillableMmcs { - pub fn new( - hash: SerializingHasher, - compress: Blake3CompressionFunction, + /// Creates an MMCS using the given leaf and internal-node BLAKE3 domains. + pub fn new_with_domains( + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, cap_height: usize, ) -> Self { + let field_hash = SerializingHasher::new(DomainBlake3::new(leaf_domain)); + let compress = CompressionFunctionFromHasher::new(DomainBlake3::new(compress_domain)); Self { - cpu: CpuMmcs::new(hash, compress, cap_height), + cpu: CpuMmcs::new(field_hash, compress, cap_height), + leaf_domain, + compress_domain, } } + /// Creates a legacy `v5` plain BLAKE3 MMCS (100% bit-identical to `p3_blake3::Blake3`). + pub fn new_plain(cap_height: usize) -> Self { + Self::new_with_domains(Blake3Domain::Plain, Blake3Domain::Plain, cap_height) + } + + /// Creates a protocol `v6` domain-separated BLAKE3 MMCS separating Merkle + /// leaf row hashes (`MerkleLeaf`) from internal 2-to-1 compressions + /// (`MerkleCompress`). + pub fn new_v6(cap_height: usize) -> Self { + Self::new_with_domains( + Blake3Domain::MerkleLeaf, + Blake3Domain::MerkleCompress, + cap_height, + ) + } + pub const fn cap_height(&self) -> usize { self.cpu.cap_height() } + pub const fn leaf_domain(&self) -> Blake3Domain { + self.leaf_domain + } + + pub const fn compress_domain(&self) -> Blake3Domain { + self.compress_domain + } + pub(crate) fn commit_in_memory_with_originals( &self, ldes: Vec>, original_traces: Vec>>, ) -> SpillCommitResult { - let tree = FastInMemoryMerkleTree::build(ldes); + let tree = FastInMemoryMerkleTree::build(ldes, self.leaf_domain, self.compress_domain); let commitment = tree.cap(self.cap_height()); ( commitment, @@ -1159,7 +1240,13 @@ impl SpillableMmcs { prehashed: Vec>>, ) -> SpillCommitResult { let count = matrices.len(); - let tree = SpilledMerkleTree::build_with_prehashed(matrices, original_traces, prehashed); + let tree = SpilledMerkleTree::build_with_prehashed( + matrices, + original_traces, + prehashed, + self.leaf_domain, + self.compress_domain, + ); let cap = tree.cap(self.cap_height()); let materialized = (0..count).map(|_| OnceLock::new()).collect(); ( @@ -1200,7 +1287,7 @@ impl Mmcs for SpillableMmcs { type Error = >::Error; fn commit>(&self, inputs: Vec) -> (Self::Commitment, Self::ProverData) { - let tree = FastInMemoryMerkleTree::build(inputs); + let tree = FastInMemoryMerkleTree::build(inputs, self.leaf_domain, self.compress_domain); let commitment = tree.cap(self.cap_height()); ( commitment, @@ -1315,6 +1402,7 @@ pub struct SpillableTwoAdicFriPcs { mmcs: SpillableMmcs, fri: FriParameters, spill_dir: Option, + batching: FriBatching, } impl SpillableTwoAdicFriPcs { @@ -1324,9 +1412,23 @@ impl SpillableTwoAdicFriPcs { mmcs, fri, spill_dir: None, + batching: FriBatching::Horner, } } + pub const fn with_batching(mut self, batching: FriBatching) -> Self { + self.batching = batching; + self + } + + pub const fn batching(&self) -> FriBatching { + self.batching + } + + pub const fn leaf_domain(&self) -> Blake3Domain { + self.mmcs.leaf_domain() + } + pub fn set_spill_dir(&mut self, spill_dir: Option) { self.spill_dir = spill_dir; } @@ -1421,7 +1523,8 @@ impl SpillableTwoAdicFriPcs { let writer = lde_pack.get_or_insert_with(|| SpillPackWriter::create(dir)); match first_idx_for_height.get_mut(&lde_height) { None => { - let (spilled, digests) = writer.append_matrix_and_hash(&lde); + let (spilled, digests) = + writer.append_matrix_and_hash(&lde, self.mmcs.leaf_domain()); spilled_ldes.push(spilled); prehashed.push(Some(digests)); first_idx_for_height.insert(lde_height, Some(idx)); @@ -1479,10 +1582,11 @@ impl SpillableTwoAdicFriPcs { } } -impl Pcs for SpillableTwoAdicFriPcs +impl Pcs for SpillableTwoAdicFriPcs where + EF: ExtensionField + ExtensionOf, Dft: TwoAdicSubgroupDft, - FriMmcs: Mmcs, + FriMmcs: Mmcs, Challenger: FieldChallenger + CanObserve + GrindingChallenger, { @@ -1490,7 +1594,7 @@ where type Commitment = >::Commitment; type ProverData = >::ProverData>; type EvaluationsOnDomain<'a> = BitReversedMatrixView>; - type Proof = FriProof>>; + type Proof = FriProof>>; type Error = FriError>::Error>; const ZK: bool = false; @@ -1517,7 +1621,8 @@ where let idx = spilled_ldes.len(); match first_idx_for_height.get_mut(&h) { None => { - let (spilled, digests) = pack.append_matrix_and_hash(&lde); + let (spilled, digests) = + pack.append_matrix_and_hash(&lde, self.mmcs.leaf_domain()); spilled_ldes.push(spilled); prehashed.push(Some(digests)); first_idx_for_height.insert(h, Some(idx)); @@ -1572,7 +1677,7 @@ where let mut prehashed = Vec::with_capacity(ldes.len()); for lde in ldes { if height_counts[&lde.height()] == 1 { - let (sp, digests) = pack.append_matrix_and_hash(&lde); + let (sp, digests) = pack.append_matrix_and_hash(&lde, self.mmcs.leaf_domain()); spilled.push(sp); prehashed.push(Some(digests)); } else { @@ -1638,11 +1743,11 @@ where fn open( &self, commitment_data_with_opening_points: Vec< - ProverDataWithOpeningPoints<'_, ExtVal, Self::ProverData>, + ProverDataWithOpeningPoints<'_, EF, Self::ProverData>, >, challenger: &mut Challenger, - ) -> (OpenedValues, Self::Proof) { - let dims_and_points: Vec<(Vec, &Vec>)> = + ) -> (OpenedValues, Self::Proof) { + let dims_and_points: Vec<(Vec, &Vec>)> = commitment_data_with_opening_points .iter() .map(|(data, points)| { @@ -1656,11 +1761,23 @@ where }) .collect(); - let (global_max_height, global_max_width) = dims_and_points + let global_max_height = dims_and_points .iter() - .flat_map(|(dims, _)| dims.iter().map(|d| (d.height, d.width))) - .reduce(|(hmax, wmax), (h, w)| (hmax.max(h), wmax.max(w))) + .flat_map(|(dims, _)| dims.iter().map(|d| d.height)) + .max() .expect("No Matrices Supplied?"); + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for (dims, points) in &dims_and_points { + for (dim, pts) in dims.iter().zip(*points) { + if !pts.is_empty() { + opened_max_width = opened_max_width.max(dim.width); + let lh = log2_strict_usize(dim.height); + openings_per_height[lh] += pts.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); let log_global_max_height = log2_strict_usize(global_max_height); let coset = build_bitrev_coset(log_global_max_height); @@ -1668,7 +1785,7 @@ where let inv_denoms = compute_inverse_denominators_from_dims(&dims_and_points, &coset); drop(coset); - let adjusted_weights: LinearMap> = inv_denoms + let adjusted_weights: LinearMap> = inv_denoms .iter() .map(|(point, denoms)| (*point, compute_adjusted_weights(*point, denoms))) .collect(); @@ -1677,7 +1794,7 @@ where // only the first `h = height >> log_blowup` rows of spilled matrices in // bounded chunks (and reading each matrix once across all its opening // points). - let all_opened_values: OpenedValues = commitment_data_with_opening_points + let all_opened_values: OpenedValues = commitment_data_with_opening_points .iter() .zip(&dims_and_points) .map(|((data, points), (dims, _))| { @@ -1741,18 +1858,26 @@ where // Free adjusted_weights before allocating reduced openings. drop(adjusted_weights); - let alpha: ExtVal = challenger.sample_algebra_element(); - let packed_alpha_powers: Vec<_> = - >::ExtensionPacking::packed_ext_powers_capped( - alpha, - global_max_width, - ) - .collect(); + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let packed_col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + EF::ExtensionPacking::packed_ext_powers_capped(*alpha, opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => { + pack_ext_weights::(col_weights) + } + }; // Pass 2: Build reduced-opening codewords, streaming spilled matrices in // bounded row blocks. let mut num_reduced = [0usize; 33]; - let mut reduced_openings: [Option>; 33] = core::array::from_fn(|_| None); + let mut opening_idx_by_height = [0usize; 33]; + let mut reduced_openings: [Option>; 33] = core::array::from_fn(|_| None); for (((data, points), (dims, _)), openings_for_round) in commitment_data_with_opening_points .iter() @@ -1767,19 +1892,38 @@ where let _guard = debug_span!("reduce matrix quotient", dims = %dim).entered(); let reduced_opening_for_log_height = reduced_openings[log_height] - .get_or_insert_with(|| ExtVal::zero_vec(dim.height)); + .get_or_insert_with(|| ::zero_vec(dim.height)); debug_assert_eq!(reduced_opening_for_log_height.len(), dim.height); let mut point_params = Vec::with_capacity(points_for_mat.len()); for (&point, openings) in points_for_mat.iter().zip(openings_for_mat) { - let alpha_pow_offset = alpha.exp_u64( - u64::try_from(num_reduced[log_height]) - .expect("reduced column count exceeds u64"), - ); - let reduced_val: ExtVal = dot_product(alpha.powers(), openings.iter().copied()); + let (opening_weight, reduced_val) = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + let w_open = PrimeCharacteristicRing::exp_u64( + alpha, + u64::try_from(num_reduced[log_height]) + .expect("reduced column count exceeds u64"), + ); + let rv: EF = dot_product( + PrimeCharacteristicRing::powers(alpha), + openings.iter().copied(), + ); + num_reduced[log_height] += dim.width; + (w_open, rv) + } + FriBatchingSchedule::Tensor { + col_weights, + open_weights, + } => { + let w_open = open_weights[opening_idx_by_height[log_height]]; + opening_idx_by_height[log_height] += 1; + let rv: EF = + dot_product(col_weights.iter().copied(), openings.iter().copied()); + (w_open, rv) + } + }; let inv_denom = inv_denoms.get(&point).unwrap().as_slice(); - point_params.push((alpha_pow_offset, reduced_val, inv_denom)); - num_reduced[log_height] += dim.width; + point_params.push((opening_weight, reduced_val, inv_denom)); } if point_params.is_empty() { @@ -1789,17 +1933,17 @@ where match &data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { let mat = &tree.leaves[mat_idx]; - let mat_compressed: Vec = mat + let mat_compressed: Vec = mat .as_view() - .rowwise_packed_dot_product::(&packed_alpha_powers) + .rowwise_packed_dot_product::(&packed_col_weights) .collect(); - for &(alpha_pow_offset, reduced_val, inv_denom) in &point_params { + for &(opening_weight, reduced_val, inv_denom) in &point_params { mat_compressed .par_iter() .zip(reduced_opening_for_log_height.par_iter_mut()) .zip(inv_denom.par_iter()) .for_each(|((&reduced_row, ro), &inv_d)| { - *ro += alpha_pow_offset * (reduced_val - reduced_row) * inv_d; + *ro += opening_weight * (reduced_val - reduced_row) * inv_d; }); } } @@ -1813,12 +1957,12 @@ where let n_rows = (dim.height - row_start).min(chunk_rows); let row_end = row_start + n_rows; let chunk = spilled.read_rows(row_start, n_rows); - let mat_compressed: Vec = chunk + let mat_compressed: Vec = chunk .as_view() - .rowwise_packed_dot_product::(&packed_alpha_powers) + .rowwise_packed_dot_product::(&packed_col_weights) .collect(); drop(chunk); - for &(alpha_pow_offset, reduced_val, inv_denom) in &point_params { + for &(opening_weight, reduced_val, inv_denom) in &point_params { mat_compressed .par_iter() .zip( @@ -1827,8 +1971,7 @@ where ) .zip(inv_denom[row_start..row_end].par_iter()) .for_each(|((&reduced_row, ro), &inv_d)| { - *ro += - alpha_pow_offset * (reduced_val - reduced_row) * inv_d; + *ro += opening_weight * (reduced_val - reduced_row) * inv_d; }); } } @@ -1839,9 +1982,9 @@ where // Release opening scratch buffers before FRI commit phase starts. drop(inv_denoms); - drop(packed_alpha_powers); + drop(packed_col_weights); - let fri_input: Vec> = reduced_openings.into_iter().rev().flatten().collect(); + let fri_input: Vec> = reduced_openings.into_iter().rev().flatten().collect(); let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); let fri_proof = prover::prove_fri( &folding, @@ -1859,7 +2002,7 @@ where fn verify( &self, commitments_with_opening_points: Vec< - CommitmentWithOpeningPoints, + CommitmentWithOpeningPoints, >, proof: &Self::Proof, challenger: &mut Challenger, @@ -1872,13 +2015,14 @@ where } } let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); - verifier::verify_fri( + verify_fri_with_batching( &folding, &self.fri, proof, challenger, &commitments_with_opening_points, &self.mmcs, + self.batching, )?; Ok(()) } @@ -1969,35 +2113,38 @@ struct NormScratch { lane_invs: Vec, } -/// Computes `[(z - x)^{-1} for x in coset]` in `Goldilocks[X]/(X^2 - W)` using +struct CubicNormScratch { + d0: Vec, + d1: Vec, + d2: Vec, + norms: Vec, + prefixes: Vec, + lane_invs: Vec, +} + +/// Computes `[(z - x)^{-1} for x in coset]` in `Goldilocks[X]/(X^2 - w)` using /// the base-field norm trick: /// /// ```text -/// (z_0 - x + z_1·X)^{-1} = ((z_0 - x) - z_1·X) / ((z_0 - x)^2 - W·z_1^2) +/// (z_0 - x + z_1·X)^{-1} = ((z_0 - x) - z_1·X) / ((z_0 - x)^2 - w·z_1^2) /// ``` -/// -/// Every chunk runs Montgomery batch inversion in the base field `PackedVal` -/// inside L1 cache (3× fewer base multiplications than extension-field batch -/// inversion, SIMD-vectorized across `PackedVal::WIDTH` lanes, parallelized -/// across all cores, and with zero intermediate `diffs` allocation). -fn goldilocks_quadratic_inverse_denominators(z: ExtVal, coset: &[Val]) -> Vec { +fn goldilocks_quadratic_inverse_denominators>( + z: EF, + w: Val, + coset: &[Val], +) -> Vec { const CHUNK: usize = 1024; - let coords = >::as_basis_coefficients_slice(&z); + let coords = >::as_basis_coefficients_slice(&z); let z0 = coords[0]; let z1 = coords[1]; let neg_z1 = -z1; - let crate::traits::ExtensionModulus::Binomial { w } = - >::MODULUS - else { - unreachable!("ExtVal is a binomial quadratic extension") - }; let w_z1_sq = w * z1 * z1; let pw = PackedVal::WIDTH; let packs_per_chunk = CHUNK / pw; - let mut out = ExtVal::zero_vec(coset.len()); + let mut out = EF::zero_vec(coset.len()); - let process_chunk = |scratch: &mut NormScratch, x_chunk: &[Val], out_chunk: &mut [ExtVal]| { + let process_chunk = |scratch: &mut NormScratch, x_chunk: &[Val], out_chunk: &mut [EF]| { let (x_packed, x_tail) = PackedVal::pack_slice_with_suffix(x_chunk); let n_packs = x_packed.len(); if n_packs > 0 { @@ -2024,7 +2171,8 @@ fn goldilocks_quadratic_inverse_denominators(z: ExtVal, coset: &[Val]) -> Vec Vec Vec, &Vec>)], +/// Computes `[(z - x)^{-1} for x in coset]` in `Goldilocks[X]/(X^3 - X - 1)` +/// using the SIMD base-field adjugate/norm trick: +/// +/// For `a = (z_0 - x) + z_1 X + z_2 X^2` with `s = a_0 + z_2 = (z_0 + z_2) - x`: +/// ```text +/// d_0 = s^2 - z_1(z_1 + z_2) +/// d_1 = z_2^2 - a_0 z_1 +/// d_2 = z_1^2 - z_2 s +/// N = a_0 d_0 + z_2 d_1 + z_1 d_2 +/// a^{-1} = (d_0 / N, d_1 / N, d_2 / N) +/// ``` +/// +/// Runs Montgomery batch inversion on `N` in `PackedVal` inside L1 cache +/// (12 base SIMD muls per point instead of ~110 scalar base muls). +fn goldilocks_cubic_trinomial_inverse_denominators>( + z: EF, coset: &[Val], -) -> LinearMap> { - let mut max_log_height_for_point: LinearMap = LinearMap::new(); +) -> Vec { + const CHUNK: usize = 1024; + let coords = >::as_basis_coefficients_slice(&z); + let z0 = coords[0]; + let z1 = coords[1]; + let z2 = coords[2]; + let z02 = z0 + z2; + let k0 = z1 * (z1 + z2); + let k1 = z2 * z2; + let k2 = z1 * z1; + + let pw = PackedVal::WIDTH; + let packs_per_chunk = CHUNK / pw; + let mut out = EF::zero_vec(coset.len()); + + let process_chunk = |scratch: &mut CubicNormScratch, x_chunk: &[Val], out_chunk: &mut [EF]| { + let (x_packed, x_tail) = PackedVal::pack_slice_with_suffix(x_chunk); + let n_packs = x_packed.len(); + if n_packs > 0 { + let z0_p = PackedVal::from(z0); + let z1_p = PackedVal::from(z1); + let z2_p = PackedVal::from(z2); + let z02_p = PackedVal::from(z02); + let k0_p = PackedVal::from(k0); + let k1_p = PackedVal::from(k1); + let k2_p = PackedVal::from(k2); + let mut acc = PackedVal::ONE; + for (i, &xp) in x_packed.iter().enumerate() { + let a0 = z0_p - xp; + let s = z02_p - xp; + let d0 = s * s - k0_p; + let d1 = k1_p - a0 * z1_p; + let d2 = k2_p - z2_p * s; + let norm = a0 * d0 + z2_p * d1 + z1_p * d2; + scratch.d0[i] = d0; + scratch.d1[i] = d1; + scratch.d2[i] = d2; + scratch.norms[i] = norm; + scratch.prefixes[i] = acc; + acc *= norm; + } + invert_lanes_in_place(acc.as_slice(), &mut scratch.lane_invs); + let mut inv = *PackedVal::from_slice(&scratch.lane_invs); + for i in (0..n_packs).rev() { + let inv_norm = scratch.prefixes[i] * inv; + inv *= scratch.norms[i]; + let c0 = scratch.d0[i] * inv_norm; + let c1 = scratch.d1[i] * inv_norm; + let c2 = scratch.d2[i] * inv_norm; + let c0_s = c0.as_slice(); + let c1_s = c1.as_slice(); + let c2_s = c2.as_slice(); + let dst = &mut out_chunk[i * pw..(i + 1) * pw]; + for lane in 0..pw { + dst[lane] = + EF::from_basis_coefficients_slice(&[c0_s[lane], c1_s[lane], c2_s[lane]]) + .expect("cubic extension element"); + } + } + } + if !x_tail.is_empty() { + let tail_out = &mut out_chunk[n_packs * pw..]; + for (&x, dst) in x_tail.iter().zip(tail_out.iter_mut()) { + let a0 = z0 - x; + let s = z02 - x; + let d0 = s * s - k0; + let d1 = k1 - a0 * z1; + let d2 = k2 - z2 * s; + let inv_norm = (a0 * d0 + z2 * d1 + z1 * d2).inverse(); + *dst = EF::from_basis_coefficients_slice(&[ + d0 * inv_norm, + d1 * inv_norm, + d2 * inv_norm, + ]) + .expect("cubic extension element"); + } + } + }; + + if coset.len() <= CHUNK { + let mut scratch = CubicNormScratch { + d0: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + d1: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + d2: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + norms: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + prefixes: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + lane_invs: vec![Val::ZERO; pw], + }; + process_chunk(&mut scratch, coset, &mut out); + } else { + out.par_chunks_mut(CHUNK) + .zip(coset.par_chunks(CHUNK)) + .for_each_init( + || CubicNormScratch { + d0: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + d1: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + d2: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + norms: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + prefixes: vec![PackedVal::ZERO; packs_per_chunk.max(1)], + lane_invs: vec![Val::ZERO; pw], + }, + |scratch, (out_chunk, x_chunk)| process_chunk(scratch, x_chunk, out_chunk), + ); + } + + out +} + +fn compute_inverse_denominators_for_point + ExtensionOf>( + z: EF, + coset: &[Val], +) -> Vec { + match (EF::D, EF::MODULUS) { + (2, ExtensionModulus::Binomial { w }) => { + goldilocks_quadratic_inverse_denominators(z, w, coset) + } + (3, ExtensionModulus::CubicTrinomial) => { + goldilocks_cubic_trinomial_inverse_denominators(z, coset) + } + _ => { + let diffs: Vec = coset.iter().map(|&x| z - x).collect(); + batch_multiplicative_inverse(&diffs) + } + } +} + +fn compute_inverse_denominators_from_dims + ExtensionOf>( + dims_and_points: &[(Vec, &Vec>)], + coset: &[Val], +) -> LinearMap> { + let mut max_log_height_for_point: LinearMap = LinearMap::new(); for (dims, points) in dims_and_points { for (dim, points_for_mat) in dims.iter().zip(*points) { let log_height = log2_strict_usize(dim.height); @@ -2086,7 +2378,7 @@ fn compute_inverse_denominators_from_dims( .map(|(z, log_height)| { ( z, - goldilocks_quadratic_inverse_denominators(z, &coset[..(1 << log_height)]), + compute_inverse_denominators_for_point(z, &coset[..(1 << log_height)]), ) }) .collect() @@ -2095,15 +2387,14 @@ fn compute_inverse_denominators_from_dims( /// Streams rows `0..h` of `spilled` once in bounded chunks and computes the /// exact barycentric interpolation at every point in `points`, matching /// `Interpolate::interpolate_coset_with_precomputation`. -fn interpolate_spilled_coset( +fn interpolate_spilled_coset>( spilled: &SpilledMatrix, h: usize, - points: &[ExtVal], - adjusted_weights: &LinearMap>, -) -> Vec> { + points: &[EF], + adjusted_weights: &LinearMap>, +) -> Vec> { let width = spilled.width(); - let mut accumulators: Vec> = - (0..points.len()).map(|_| ExtVal::zero_vec(width)).collect(); + let mut accumulators: Vec> = (0..points.len()).map(|_| EF::zero_vec(width)).collect(); let row_bytes = spilled.row_bytes().max(size_of::()); let chunk_rows = (STREAM_BLOCK_BYTES / row_bytes).clamp(1, 1 << 14).min(h); @@ -2137,17 +2428,22 @@ fn interpolate_spilled_coset( #[cfg(test)] mod tests { use super::*; - use p3_field::batch_multiplicative_inverse; + use crate::types::ExtVal; + use p3_field::extension::CubicTrinomialExtensionField; use rand::rngs::SmallRng; use rand::{RngExt, SeedableRng}; - fn make_mmcs(cap_height: usize) -> (CpuMmcs, SpillableMmcs) { - let byte_hash = Blake3; - let field_hash = SerializingHasher::new(byte_hash); - let compress = Blake3CompressionFunction::new(byte_hash); + fn make_mmcs(cap_height: usize, v6: bool) -> (CpuMmcs, SpillableMmcs) { + let (leaf_domain, compress_domain) = if v6 { + (Blake3Domain::MerkleLeaf, Blake3Domain::MerkleCompress) + } else { + (Blake3Domain::Plain, Blake3Domain::Plain) + }; + let field_hash = SerializingHasher::new(DomainBlake3::new(leaf_domain)); + let compress = CompressionFunctionFromHasher::new(DomainBlake3::new(compress_domain)); ( - CpuMmcs::new(field_hash, compress.clone(), cap_height), - SpillableMmcs::new(field_hash, compress, cap_height), + CpuMmcs::new(field_hash, compress, cap_height), + SpillableMmcs::new_with_domains(leaf_domain, compress_domain, cap_height), ) } @@ -2168,109 +2464,112 @@ mod tests { query_indices: &[usize], tag: &str, ) { - let dir = temp_spill_dir(tag); - let (cpu, spillable) = make_mmcs(cap_height); - let (cpu_com, cpu_data) = cpu.commit(mats.to_vec()); + for v6 in [false, true] { + let dir = temp_spill_dir(&format!("{tag}-v{}", if v6 { 6 } else { 5 })); + let (cpu, spillable) = make_mmcs(cap_height, v6); + let (cpu_com, cpu_data) = cpu.commit(mats.to_vec()); - // Also check our SIMD in-memory MMCS matches `CpuMmcs` bit-for-bit. - let (mem_com, mem_data) = spillable.commit(mats.to_vec()); - assert_eq!( - mem_com.roots(), - cpu_com.roots(), - "in-memory SIMD cap mismatch for {tag} (cap_height={cap_height})" - ); - let (cpu_vals, cpu_multi) = cpu.open_multi_batch(query_indices, &cpu_data); - let (mem_vals, mem_multi) = spillable.open_multi_batch(query_indices, &mem_data); - assert_eq!(mem_vals, cpu_vals); - assert_eq!(mem_multi.sibling_hashes, cpu_multi.sibling_hashes); + // Also check our SIMD in-memory MMCS matches `CpuMmcs` bit-for-bit. + let (mem_com, mem_data) = spillable.commit(mats.to_vec()); + assert_eq!( + mem_com.roots(), + cpu_com.roots(), + "in-memory SIMD cap mismatch for {tag} (v6={v6}, cap_height={cap_height})" + ); + let (cpu_vals, cpu_multi) = cpu.open_multi_batch(query_indices, &cpu_data); + let (mem_vals, mem_multi) = spillable.open_multi_batch(query_indices, &mem_data); + assert_eq!(mem_vals, cpu_vals); + assert_eq!(mem_multi.sibling_hashes, cpu_multi.sibling_hashes); + + // Check spilled (streaming disk hash) path. + let mut pack = SpillPackWriter::create(&dir); + let spilled_mats: Vec<_> = mats.iter().map(|m| pack.append_matrix(m)).collect(); + pack.flush(); + let (spilled_com, spilled_data) = spillable.commit_spilled(spilled_mats, Vec::new()); - // Check spilled (streaming disk hash) path. - let mut pack = SpillPackWriter::create(&dir); - let spilled_mats: Vec<_> = mats.iter().map(|m| pack.append_matrix(m)).collect(); - pack.flush(); - let (spilled_com, spilled_data) = spillable.commit_spilled(spilled_mats, Vec::new()); + assert_eq!( + spilled_com.roots(), + cpu_com.roots(), + "cap mismatch for {tag} (v6={v6}, cap_height={cap_height})" + ); + assert!(spilled_data.is_spilled()); + assert_eq!( + spillable.get_matrix_heights(&spilled_data), + cpu.get_matrix_heights(&cpu_data) + ); + assert_eq!( + spillable.get_max_height(&spilled_data), + cpu.get_max_height(&cpu_data) + ); - assert_eq!( - spilled_com.roots(), - cpu_com.roots(), - "cap mismatch for {tag} (cap_height={cap_height})" - ); - assert!(spilled_data.is_spilled()); - assert_eq!( - spillable.get_matrix_heights(&spilled_data), - cpu.get_matrix_heights(&cpu_data) - ); - assert_eq!( - spillable.get_max_height(&spilled_data), - cpu.get_max_height(&cpu_data) - ); + let dims: Vec = mats.iter().map(Matrix::dimensions).collect(); + for &idx in query_indices { + let cpu_open = cpu.open_batch(idx, &cpu_data); + let spilled_open = spillable.open_batch(idx, &spilled_data); + assert_eq!(spilled_open.opened_values, cpu_open.opened_values); + assert_eq!(spilled_open.opening_proof, cpu_open.opening_proof); + cpu.verify_batch( + &spilled_com, + &dims, + idx, + BatchOpeningRef::new(&spilled_open.opened_values, &spilled_open.opening_proof), + ) + .expect("CpuMmcs must accept spilled single opening"); + } - let dims: Vec = mats.iter().map(Matrix::dimensions).collect(); - for &idx in query_indices { - let cpu_open = cpu.open_batch(idx, &cpu_data); - let spilled_open = spillable.open_batch(idx, &spilled_data); - assert_eq!(spilled_open.opened_values, cpu_open.opened_values); - assert_eq!(spilled_open.opening_proof, cpu_open.opening_proof); - cpu.verify_batch( + let (spilled_vals, spilled_multi) = + spillable.open_multi_batch(query_indices, &spilled_data); + assert_eq!(spilled_vals, cpu_vals); + assert_eq!(spilled_multi.sibling_hashes, cpu_multi.sibling_hashes); + cpu.verify_multi_batch( &spilled_com, &dims, - idx, - BatchOpeningRef::new(&spilled_open.opened_values, &spilled_open.opening_proof), + query_indices, + &spilled_vals, + &spilled_multi, ) - .expect("CpuMmcs must accept spilled single opening"); - } - - let (spilled_vals, spilled_multi) = - spillable.open_multi_batch(query_indices, &spilled_data); - assert_eq!(spilled_vals, cpu_vals); - assert_eq!(spilled_multi.sibling_hashes, cpu_multi.sibling_hashes); - cpu.verify_multi_batch( - &spilled_com, - &dims, - query_indices, - &spilled_vals, - &spilled_multi, - ) - .expect("CpuMmcs must accept spilled multi-batch opening"); - - // Also check hash-before-spill (`append_matrix_and_hash` + `commit_spilled_prehashed`). - let mut height_counts: HashMap = HashMap::new(); - for m in mats { - *height_counts.entry(m.height()).or_insert(0) += 1; - } - let mut pack_pre = SpillPackWriter::create(&dir); - let mut sp_pre = Vec::with_capacity(mats.len()); - let mut prehashed = Vec::with_capacity(mats.len()); - for m in mats { - if height_counts[&m.height()] == 1 { - let (sp, digests) = pack_pre.append_matrix_and_hash(m); - sp_pre.push(sp); - prehashed.push(Some(digests)); - } else { - sp_pre.push(pack_pre.append_matrix(m)); - prehashed.push(None); + .expect("CpuMmcs must accept spilled multi-batch opening"); + + // Also check hash-before-spill (`append_matrix_and_hash` + `commit_spilled_prehashed`). + let mut height_counts: HashMap = HashMap::new(); + for m in mats { + *height_counts.entry(m.height()).or_insert(0) += 1; } + let mut pack_pre = SpillPackWriter::create(&dir); + let mut sp_pre = Vec::with_capacity(mats.len()); + let mut prehashed = Vec::with_capacity(mats.len()); + for m in mats { + if height_counts[&m.height()] == 1 { + let (sp, digests) = pack_pre.append_matrix_and_hash(m, spillable.leaf_domain()); + sp_pre.push(sp); + prehashed.push(Some(digests)); + } else { + sp_pre.push(pack_pre.append_matrix(m)); + prehashed.push(None); + } + } + pack_pre.flush(); + let (pre_com, pre_data) = + spillable.commit_spilled_prehashed(sp_pre, Vec::new(), prehashed); + assert_eq!(pre_com.roots(), cpu_com.roots()); + let (pre_vals, pre_multi) = spillable.open_multi_batch(query_indices, &pre_data); + assert_eq!(pre_vals, cpu_vals); + assert_eq!(pre_multi.sibling_hashes, cpu_multi.sibling_hashes); + assert_eq!(pre_data.materialized_spilled_count(), 0); + drop(pre_data); + drop(pack_pre); + + // Ensure nothing materialized the spilled matrices back into RAM. + assert_eq!(spilled_data.materialized_spilled_count(), 0); + drop(spilled_data); + drop(pack); + let remaining = fs::read_dir(&dir).unwrap().count(); + assert_eq!( + remaining, 0, + "spill directory must have zero leftover files" + ); + let _ = fs::remove_dir_all(&dir); } - pack_pre.flush(); - let (pre_com, pre_data) = spillable.commit_spilled_prehashed(sp_pre, Vec::new(), prehashed); - assert_eq!(pre_com.roots(), cpu_com.roots()); - let (pre_vals, pre_multi) = spillable.open_multi_batch(query_indices, &pre_data); - assert_eq!(pre_vals, cpu_vals); - assert_eq!(pre_multi.sibling_hashes, cpu_multi.sibling_hashes); - assert_eq!(pre_data.materialized_spilled_count(), 0); - drop(pre_data); - drop(pack_pre); - - // Ensure nothing materialized the spilled matrices back into RAM. - assert_eq!(spilled_data.materialized_spilled_count(), 0); - drop(spilled_data); - drop(pack); - let remaining = fs::read_dir(&dir).unwrap().count(); - assert_eq!( - remaining, 0, - "spill directory must have zero leftover files" - ); - let _ = fs::remove_dir_all(&dir); } #[test] @@ -2435,6 +2734,7 @@ mod tests { #[test] fn parallel_bitrev_coset_and_norm_trick_match_reference() { + type Ext3 = CubicTrinomialExtensionField; for log_size in [0usize, 1, 2, 3, 5, 10, 13] { let expected_coset: Vec = { let mut pts: Vec = TwoAdicMultiplicativeCoset::new(Val::GENERATOR, log_size) @@ -2454,10 +2754,45 @@ mod tests { ] { let diffs: Vec = expected_coset.iter().map(|&x| point - x).collect(); let expected_invs = batch_multiplicative_inverse(&diffs); - let got_invs = goldilocks_quadratic_inverse_denominators(point, &got_coset); + let got_invs = compute_inverse_denominators_for_point(point, &got_coset); + assert_eq!( + got_invs, expected_invs, + "quadratic norm-trick inverse mismatch at 2^{log_size}" + ); + } + + for point in [ + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::new(12345), + Goldilocks::new(67890), + Goldilocks::new(54321), + ]) + .unwrap(), + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::new(987_654_321), + Goldilocks::ZERO, + Goldilocks::ZERO, + ]) + .unwrap(), + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::ZERO, + Goldilocks::new(42), + Goldilocks::new(99), + ]) + .unwrap(), + Ext3::from_basis_coefficients_slice(&[ + Goldilocks::new(17), + Goldilocks::ZERO, + Goldilocks::new(73), + ]) + .unwrap(), + ] { + let diffs: Vec = expected_coset.iter().map(|&x| point - x).collect(); + let expected_invs = batch_multiplicative_inverse(&diffs); + let got_invs = compute_inverse_denominators_for_point(point, &got_coset); assert_eq!( got_invs, expected_invs, - "norm-trick inverse mismatch at 2^{log_size}" + "cubic trinomial norm-trick inverse mismatch at 2^{log_size}" ); } } diff --git a/src/prover.rs b/src/prover.rs index ddea84b..bfbd520 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -314,7 +314,10 @@ impl Proof { #[inline] pub fn from_bytes(bytes: &[u8]) -> Result { - let (proof, _num_bytes) = decode_from_slice(bytes, Self::serde_config())?; + let (proof, num_bytes) = decode_from_slice(bytes, Self::serde_config())?; + if num_bytes != bytes.len() { + return Err(DecodeError::Other("trailing bytes after proof")); + } Ok(proof) } } @@ -404,7 +407,9 @@ where claims: &[&[Val]], stage_1: Stage1, ) -> Proof { - let mut challenger = self.config.initialise_challenger(); + let mut challenger = self + .config + .initialise_challenger_for_mode(crate::config::TranscriptMode::Single); // Bind the system shape into the transcript. The protocol parameters // are already bound via the challenger seed. diff --git a/src/system.rs b/src/system.rs index 903f73b..fd1ff32 100644 --- a/src/system.rs +++ b/src/system.rs @@ -9,17 +9,18 @@ //! ([`crate::lookup::logup_constraint_values`]), folding their values after //! the user roots. -use crate::traits::Field; +use crate::traits::{ExtensionModulus, ExtensionOf, Field}; use p3_matrix::{Matrix, dense::RowMajorMatrix}; use p3_maybe_rayon::prelude::*; -use crate::config::{Com, PcsData, ProofConfig, Val}; +use crate::config::{Com, PcsData, ProofConfig, ProtocolVersion, Val}; use crate::lookup::LookupValues; use crate::eval::VarValues; -use crate::expr::{CircuitSpec, Expr, ExtExpr}; -use crate::graph::{ConstraintGraph, ExtensionParams, compile}; +use crate::expr::{CircuitSpec, Expr, ExtExpr, RowOffset, Source}; +use crate::graph::{ConstraintGraph, ExtensionParams, Node, compile}; use crate::lookup::{Lookup, logup_constraint_count, logup_max_degree, num_publics, stage2_width}; +use crate::p3_adapter::domain_blake3::Blake3Domain; use crate::traits::{Pcs, Transcript}; /// User-facing definition of one circuit: main-trace width, optional @@ -129,14 +130,14 @@ impl Circuit { } /// Returns `true` if any compiled node reads a column from `source` at `offset`. - pub fn uses_row(&self, source: crate::expr::Source, offset: crate::expr::RowOffset) -> bool { + pub fn uses_row(&self, source: Source, offset: RowOffset) -> bool { self.graph.uses_row(source, offset) } } /// A multi-circuit STARK system over compiled constraint circuits. Contains -/// all circuits together with their shared preprocessed commitment and the -/// protocol configuration. +/// all circuits together with their shared preprocessed commitment, canonical +/// verifying-key / constraint-graph digest, and the protocol configuration. pub struct System { pub config: SC, pub circuits: Vec>>, @@ -145,6 +146,11 @@ pub struct System { /// Maps each circuit index to its position within the preprocessed /// commitment; `None` if that circuit has no preprocessed trace. pub preprocessed_indices: Vec>, + /// Canonical BLAKE3 `derive_key("multi-stark/v6/vk")` digest committing to + /// the extension degree/modulus and every circuit's full constraint DAG, + /// lookup definitions, and metadata (independent of whether preprocessed + /// trace matrices are retained in RAM). + pub vk_digest: [u8; 32], } /// Prover-side data retained between system setup and proving. @@ -154,9 +160,9 @@ pub struct ProverKey { } impl System { - pub fn opens_next_row(&self, circuit: usize, source: crate::expr::Source) -> bool { + pub fn opens_next_row(&self, circuit: usize, source: Source) -> bool { !self.config.omit_unused_next_row_openings() - || self.circuits[circuit].uses_row(source, crate::expr::RowOffset::Next) + || self.circuits[circuit].uses_row(source, RowOffset::Next) } /// Builds the system from per-circuit inputs. @@ -290,22 +296,36 @@ impl System { // Ensure all inputs are drained even if a custom backend stopped early. for _ in prep_iter {} + let vk_digest = compute_vk_digest::, SC::Challenge>(&circuits); let system = Self { config, circuits, preprocessed_commit, preprocessed_indices, + vk_digest, }; (system, ProverKey { preprocessed_data }) } - /// Binds the system shape into the Fiat-Shamir transcript. The prover and - /// the verifier must call this identically, before observing any - /// commitment, so that transcripts of systems with different circuit - /// shapes never collide. The protocol parameters are bound separately, - /// via the challenger seed (see - /// [`ProofConfig::initialise_challenger`]). + /// Binds the system shape (and, under protocol `v6`, the extension + /// degree/modulus and canonical VK / constraint-graph digest) into the + /// Fiat-Shamir transcript. The prover and the verifier must call this + /// identically, before observing any commitment, so that transcripts of + /// systems with different constraint graphs or circuit shapes never + /// collide. The protocol parameters are bound separately via the + /// challenger seed (see [`ProofConfig::initialise_challenger_for_mode`]). pub fn observe_shape(&self, challenger: &mut SC::Challenger) { + if self.config.protocol_version() == ProtocolVersion::V6 { + challenger.observe_field(Val::::from_usize( + >>::D, + )); + let modulus = >>::MODULUS; + challenger.observe_field(Val::::from_u8(modulus.tag())); + if let ExtensionModulus::Binomial { w } = modulus { + challenger.observe_field(w); + } + challenger.observe_digest(self.vk_digest); + } let mut observe = |x: usize| challenger.observe_field(Val::::from_usize(x)); observe(self.circuits.len()); for circuit in &self.circuits { @@ -322,6 +342,129 @@ impl System { } } +/// Computes the canonical protocol-`v6` verifying-key / constraint-graph digest +/// under `BLAKE3_derive_key("multi-stark/v6/vk")`. +/// +/// Commits to the extension degree, extension modulus, and every circuit's +/// metadata, compiled DAG nodes (including canonical field constants), zero +/// constraint roots, and lookup expressions. Intentionally excludes the +/// in-memory `circuit.preprocessed` matrix so `System::new` and +/// `System::new_without_preprocessed` produce identical digests (the +/// preprocessed traces themselves are bound via `preprocessed_commit`). +pub fn compute_vk_digest>(circuits: &[Circuit]) -> [u8; 32] { + let mut hasher = Blake3Domain::VerifyingKey.hasher(); + let bincode_cfg = bincode::config::standard() + .with_little_endian() + .with_fixed_int_encoding(); + + let hash_u32 = |h: &mut blake3::Hasher, x: u32| { + h.update(&x.to_le_bytes()); + }; + let hash_u64 = |h: &mut blake3::Hasher, x: u64| { + h.update(&x.to_le_bytes()); + }; + let hash_usize = |h: &mut blake3::Hasher, x: usize| { + hash_u64(h, u64::try_from(x).expect("usize exceeds u64")); + }; + let hash_field = |h: &mut blake3::Hasher, x: F| { + let bytes = + bincode::serde::encode_to_vec(x, bincode_cfg).expect("field serialization cannot fail"); + h.update(&bytes); + }; + + hash_usize(&mut hasher, EF::D); + hasher.update(&[EF::MODULUS.tag()]); + if let ExtensionModulus::Binomial { w } = EF::MODULUS { + hash_field(&mut hasher, w); + } + + hash_usize(&mut hasher, circuits.len()); + for circuit in circuits { + hash_usize(&mut hasher, circuit.main_width); + hash_usize(&mut hasher, circuit.preprocessed_width); + hash_usize(&mut hasher, circuit.preprocessed_height); + hash_usize(&mut hasher, circuit.num_lookups); + hash_usize(&mut hasher, circuit.stage_2_width); + hash_usize(&mut hasher, circuit.num_publics); + hash_usize(&mut hasher, circuit.lookup_group_size); + hash_usize(&mut hasher, circuit.constraint_count); + hash_usize(&mut hasher, circuit.max_constraint_degree); + hash_usize(&mut hasher, circuit.graph.lookup_prefix_len); + hash_u32(&mut hasher, circuit.graph.max_constraint_degree); + + hash_usize(&mut hasher, circuit.graph.nodes.len()); + for node in &circuit.graph.nodes { + match *node { + Node::Const(c) => { + hasher.update(&[0u8]); + hash_field(&mut hasher, c); + } + Node::Var(col) => { + let src_tag = match col.source { + Source::Preprocessed => 0u8, + Source::Main => 1u8, + Source::Stage2 => 2u8, + }; + let off_tag = match col.offset { + RowOffset::Current => 0u8, + RowOffset::Next => 1u8, + }; + hasher.update(&[1u8, src_tag, off_tag]); + hash_u32(&mut hasher, col.index); + } + Node::Public(idx) => { + hasher.update(&[2u8]); + hash_u32(&mut hasher, idx); + } + Node::IsFirstRow => { + hasher.update(&[3u8]); + } + Node::IsLastRow => { + hasher.update(&[4u8]); + } + Node::IsTransition => { + hasher.update(&[5u8]); + } + Node::Add(a, b) => { + hasher.update(&[6u8]); + hash_u32(&mut hasher, a.0); + hash_u32(&mut hasher, b.0); + } + Node::Sub(a, b) => { + hasher.update(&[7u8]); + hash_u32(&mut hasher, a.0); + hash_u32(&mut hasher, b.0); + } + Node::Mul(a, b) => { + hasher.update(&[8u8]); + hash_u32(&mut hasher, a.0); + hash_u32(&mut hasher, b.0); + } + Node::Neg(a) => { + hasher.update(&[9u8]); + hash_u32(&mut hasher, a.0); + } + } + } + + hash_usize(&mut hasher, circuit.graph.zeros.len()); + for z in &circuit.graph.zeros { + hash_u32(&mut hasher, z.0); + } + + hash_usize(&mut hasher, circuit.graph.lookups.len()); + for lookup in &circuit.graph.lookups { + hash_u32(&mut hasher, lookup.multiplicity.0); + hash_usize(&mut hasher, lookup.args.len()); + for arg in &lookup.args { + hash_u32(&mut hasher, arg.0); + } + } + } + + hasher.finalize().into() +} + /// Witness data for the system: stage-1 traces and the concrete lookup /// values derived from them. #[derive(Clone)] diff --git a/src/system/tests/lookup_values.rs b/src/system/tests/lookup_values.rs index 1884239..a2a6e1a 100644 --- a/src/system/tests/lookup_values.rs +++ b/src/system/tests/lookup_values.rs @@ -223,11 +223,13 @@ fn witness_circuit_order_and_lookup_totals() { .into_iter() .map(|height| fixture::(height, true)) .unzip(); + let vk_digest = compute_vk_digest::(&circuits); let system = System { config: config(), circuits, preprocessed_commit: None, preprocessed_indices: vec![None; 3], + vk_digest, }; let expected: Vec<_> = traces .iter() diff --git a/src/traits/transcript.rs b/src/traits/transcript.rs index bf149cb..33db519 100644 --- a/src/traits/transcript.rs +++ b/src/traits/transcript.rs @@ -32,5 +32,20 @@ pub trait Transcript { fn observe_field_slice(&mut self, xs: &[Self::F]); fn observe_challenge(&mut self, x: Self::Challenge); fn observe_commitment(&mut self, c: Self::Commitment); + /// Absorb a 32-byte digest into the transcript (used in protocol `v6` to + /// bind the canonical verifying-key / constraint-graph digest). + /// + /// Byte-oriented challengers override this to observe the 32 raw bytes + /// directly; algebraic challengers default to observing 16 little-endian + /// `u16` chunks as base-field elements. + fn observe_digest(&mut self, digest: [u8; 32]) + where + Self::F: crate::traits::Field, + { + for &chunk in digest.as_chunks::<2>().0 { + let limb = u16::from_le_bytes(chunk); + self.observe_field(::from_u16(limb)); + } + } fn sample_challenge(&mut self) -> Self::Challenge; } diff --git a/src/types.rs b/src/types.rs index 4bbe999..0514905 100644 --- a/src/types.rs +++ b/src/types.rs @@ -5,7 +5,7 @@ //! [`crate::prover`] and [`crate::verifier`]; this module only provides a //! concrete, batteries-included instantiation. -use crate::config::ProofConfig; +use crate::config::{ProofConfig, ProtocolVersion, TranscriptMode}; use p3_blake3::Blake3; use p3_challenger::{ CanObserve, CanSample, CanSampleBits, FieldChallenger, GrindingChallenger, HashChallenger, @@ -13,10 +13,11 @@ use p3_challenger::{ }; use p3_commit::{ExtensionMmcs, Pcs as PcsTrait}; use p3_dft::Radix2DitParallel; +#[cfg(feature = "cuda")] use p3_field::BasedVectorSpace; use p3_field::{ ExtensionField, Field, PrimeCharacteristicRing, PrimeField64, TwoAdicField, - extension::BinomialExtensionField, + extension::{BinomialExtensionField, CubicTrinomialExtensionField}, }; use p3_fri::FriParameters as InnerFriParameters; use p3_goldilocks::Goldilocks; @@ -26,17 +27,28 @@ use p3_matrix::dense::RowMajorMatrix; use p3_maybe_rayon::prelude::*; #[cfg(feature = "cuda")] use p3_merkle_tree::MerkleTreeMmcs; -use p3_symmetric::{CompressionFunctionFromHasher, SerializingHasher}; +#[cfg(any(feature = "cuda", test))] +use p3_symmetric::CompressionFunctionFromHasher; +#[cfg(any(feature = "cuda", test))] +use p3_symmetric::SerializingHasher; #[cfg(feature = "cuda")] use crate::cuda::CudaDft; #[cfg(feature = "cuda")] use crate::cuda::pcs::CudaPcsDft; +pub use crate::p3_adapter::challenger::DomainChallenger; +pub use crate::p3_adapter::domain::{CosetDomain, DomainMappedPcs}; +pub use crate::p3_adapter::domain_blake3::{Blake3Domain, DomainBlake3}; +pub use crate::p3_adapter::fri_batching::FriBatching; +use crate::traits::ExtensionModulus; pub type Val = Goldilocks; pub type PackedVal = ::Packing; pub type ExtVal = BinomialExtensionField; +pub type ExtVal2 = BinomialExtensionField; +pub type ExtVal3 = CubicTrinomialExtensionField; pub type PackedExtVal = >::ExtensionPacking; +pub type PackedExtVal3 = >::ExtensionPacking; pub type Challenger = DeterministicPow>>; @@ -620,7 +632,8 @@ impl ProofConfig for GoldilocksBlake3Config { let lde = self.pcs.compute_lde(domain, stage_2_base); if let Some(pack) = &mut spill_pack { if height_counts.get(&lde.height()).copied() == Some(1) { - let (spilled, digests) = pack.append_matrix_and_hash(&lde); + let (spilled, digests) = + pack.append_matrix_and_hash(&lde, self.pcs.leaf_domain()); spilled_ldes.push(spilled); prehashed.push(Some(digests)); } else { @@ -716,7 +729,7 @@ impl ProofConfig for GoldilocksBlake3Config { ); let lde = lde_from_shifted_coefficients(dft, sliced, log_blowup); if height_counts.get(&lde.height()).copied() == Some(1) { - let (spilled, digests) = pack.append_matrix_and_hash(&lde); + let (spilled, digests) = pack.append_matrix_and_hash(&lde, self.pcs.leaf_domain()); spilled_ldes.push(spilled); prehashed.push(Some(digests)); } else { @@ -733,54 +746,7 @@ impl ProofConfig for GoldilocksBlake3Config { } fn canonicalize_proof(proof: &mut crate::prover::Proof) { - fn canonical_base(value: &mut Val) { - *value = Val::from_u64(value.as_canonical_u64()); - } - - fn canonical_ext(value: &mut ExtVal) { - let coefficients: &[Val] = value.as_basis_coefficients_slice(); - *value = ExtVal::from_basis_coefficients_slice(&[ - Val::from_u64(coefficients[0].as_canonical_u64()), - Val::from_u64(coefficients[1].as_canonical_u64()), - ]) - .expect("quadratic extension element"); - } - - fn canonical_opened(round: &mut p3_commit::OpenedValuesForRound) { - for matrix in round { - for point in matrix { - point.iter_mut().for_each(canonical_ext); - } - } - } - - proof - .intermediate_accumulators - .iter_mut() - .for_each(canonical_ext); - canonical_opened(&mut proof.quotient_opened_values); - if let Some(round) = &mut proof.preprocessed_opened_values { - canonical_opened(round); - } - canonical_opened(&mut proof.stage_1_opened_values); - canonical_opened(&mut proof.stage_2_opened_values); - - let fri = &mut proof.opening_proof; - fri.commit_pow_witnesses.iter_mut().for_each(canonical_base); - canonical_base(&mut fri.query_pow_witness); - fri.final_poly.iter_mut().for_each(canonical_ext); - for opening in &mut fri.input_openings { - for query in &mut opening.opened_values { - for row in query { - row.iter_mut().for_each(canonical_base); - } - } - } - for step in &mut fri.commit_phase_openings { - for siblings in &mut step.sibling_values { - siblings.iter_mut().for_each(canonical_ext); - } - } + canonicalize_goldilocks_fri_proof::(proof); } #[cfg(feature = "cuda")] @@ -1475,6 +1441,7 @@ pub struct FriParameters { pub query_proof_of_work_bits: usize, } +#[cfg(any(feature = "cuda", test))] pub(crate) type Blake3CompressionFunction = CompressionFunctionFromHasher; #[cfg(feature = "cuda")] @@ -1523,20 +1490,684 @@ type PcsDft = Dft; type PcsDft = CudaDft; fn new_mmcs(cap_height: usize, #[cfg(feature = "cuda")] device_id: i32) -> Mmcs { - let byte_hash = Blake3; - let field_hash = SerializingHasher::new(byte_hash); - let compress = Blake3CompressionFunction::new(byte_hash); #[cfg(not(feature = "cuda"))] { - crate::p3_adapter::spill::SpillableMmcs::new(field_hash, compress, cap_height) + crate::p3_adapter::spill::SpillableMmcs::new_plain(cap_height) } #[cfg(feature = "cuda")] { + let byte_hash = Blake3; + let field_hash = SerializingHasher::new(byte_hash); + let compress = Blake3CompressionFunction::new(byte_hash); let cpu = CpuMmcs::new(field_hash, compress, cap_height); crate::cuda::mmcs::CudaMmcs::with_device(cpu, device_id) } } +fn canonicalize_goldilocks_fri_proof(proof: &mut crate::prover::Proof) +where + EF: ExtensionField + crate::traits::ExtensionOf, + FriMmcs: p3_commit::Mmcs, + SC: ProofConfig, + SC::Pcs: crate::traits::Pcs< + F = Val, + Challenge = EF, + Proof = p3_fri::FriProof>>, + >, +{ + fn canonical_base(value: &mut Val) { + *value = Val::from_u64(value.as_canonical_u64()); + } + + fn canonical_ext + crate::traits::ExtensionOf>(value: &mut EF) { + let coefficients: &[Val] = + >::as_basis_coefficients_slice(value); + *value = >::from_basis_coefficients_fn(|i| { + Val::from_u64(coefficients[i].as_canonical_u64()) + }); + } + + fn canonical_opened + crate::traits::ExtensionOf>( + round: &mut p3_commit::OpenedValuesForRound, + ) { + for matrix in round { + for point in matrix { + point.iter_mut().for_each(canonical_ext::); + } + } + } + + proof + .intermediate_accumulators + .iter_mut() + .for_each(canonical_ext::); + canonical_opened(&mut proof.quotient_opened_values); + if let Some(round) = &mut proof.preprocessed_opened_values { + canonical_opened(round); + } + canonical_opened(&mut proof.stage_1_opened_values); + canonical_opened(&mut proof.stage_2_opened_values); + + let fri = &mut proof.opening_proof; + fri.commit_pow_witnesses.iter_mut().for_each(canonical_base); + canonical_base(&mut fri.query_pow_witness); + fri.final_poly.iter_mut().for_each(canonical_ext::); + for opening in &mut fri.input_openings { + for query in &mut opening.opened_values { + for row in query { + row.iter_mut().for_each(canonical_base); + } + } + } + for step in &mut fri.commit_phase_openings { + for siblings in &mut step.sibling_values { + siblings.iter_mut().for_each(canonical_ext::); + } + } +} + +/// Extension MMCS for Protocol `v6` over any challenge extension `EF`. +pub type V6ExtMmcs = ExtensionMmcs; + +/// Inner PCS for Protocol `v6` over any challenge extension `EF` (CPU). +#[cfg(not(feature = "cuda"))] +pub type V6InnerPcs = + DomainMappedPcs>>; +/// Inner PCS for Protocol `v6` over any challenge extension `EF` (CUDA). +#[cfg(feature = "cuda")] +pub type V6InnerPcs = + DomainMappedPcs>>; + +/// Protocol `v6` FRI PCS parameterized over any Goldilocks challenge extension +/// `EF` (degree-3 cubic trinomial [`ExtVal3`] or degree-2 binomial [`ExtVal2`]). +pub type V6Pcs = crate::p3_adapter::pcs::FriPcs< + Val, + EF, + DomainChallenger, + Dft, + Mmcs, + V6ExtMmcs, + V6InnerPcs, +>; + +/// Protocol `v6` Goldilocks/BLAKE3 configuration over the degree-3 cubic +/// trinomial extension $\mathbb{F}_{p^3} = \mathbb{F}_p[X]/(X^3 - X - 1)$ +/// (192-bit field, 128-bit conjectured / 100+ bit provable soundness with +/// multilinear tensor FRI batching and domain-separated BLAKE3). +pub type GoldilocksBlake3V6Config = GoldilocksV6Config; + +/// Protocol `v6` Goldilocks/BLAKE3 configuration over the degree-2 binomial +/// extension $\mathbb{F}_{p^2} = \mathbb{F}_p[X]/(X^2 - 7)$ (same hardened `v6` +/// transcript, VK digest, domain-separated BLAKE3, and tensor FRI batching as +/// [`GoldilocksBlake3V6Config`], useful for apples-to-apples benchmarking). +pub type GoldilocksBlake3V6Fp2Config = GoldilocksV6Config; + +/// Hardened Protocol `v6` [`ProofConfig`] parameterized by Goldilocks +/// challenge extension `EF`. +/// +/// Protocol `v6` cryptographic guarantees: +/// - Zero-overhead BLAKE3 `derive_key` domain separation across Merkle leaves +/// (`"multi-stark/v6/merkle/leaf"`), Merkle internal 2-to-1 compressions +/// (`"multi-stark/v6/merkle/compress"`), single-proof transcripts +/// (`"multi-stark/v6/transcript/single"`), batch-proof transcripts +/// (`"multi-stark/v6/transcript/batch"`), and VK/constraint-graph digests +/// (`"multi-stark/v6/vk"`). +/// - Explicit extension degree, extension modulus, FRI batching mode, and full +/// canonical VK/constraint-graph digest bound into the transcript. +/// - Multilinear tensor FRI batching (`FriBatching::Tensor`, default) or +/// Horner batching (`FriBatching::Horner`). +pub struct GoldilocksV6Config +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + pcs: V6Pcs, + challenger_seed: Vec, + max_log_degree: usize, + max_quotient_degree: usize, + log_blowup: usize, + cap_height: usize, + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, +} + +fn build_v6_challenger_seed>( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, +) -> Vec { + let modulus = EF::MODULUS; + let modulus_param = match modulus { + ExtensionModulus::Binomial { w } => w.as_canonical_u64(), + ExtensionModulus::Base | ExtensionModulus::CubicTrinomial => 0u64, + }; + let mut seed = b"multi-stark/v6".to_vec(); + let params = [ + u64::try_from(EF::D).expect("extension degree exceeds u64"), + u64::from(modulus.tag()), + modulus_param, + fri_batching.tag(), + u64::try_from(commitment_parameters.log_blowup).expect("parameter exceeds u64"), + u64::try_from(commitment_parameters.cap_height).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.log_final_poly_len).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.max_log_arity).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.num_queries).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.commit_proof_of_work_bits).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.query_proof_of_work_bits).expect("parameter exceeds u64"), + ]; + for p in params { + seed.extend_from_slice(&p.to_le_bytes()); + } + seed +} + +impl GoldilocksV6Config +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + /// Creates a Protocol `v6` configuration using multilinear tensor FRI + /// batching ([`FriBatching::Tensor`]) by default. + pub fn new(commitment_parameters: CommitmentParameters, fri_parameters: FriParameters) -> Self { + Self::with_device( + commitment_parameters, + fri_parameters, + FriBatching::Tensor, + None, + ) + } + + /// Creates a Protocol `v6` configuration with an explicit [`FriBatching`] + /// strategy (`Tensor` or `Horner`). + pub fn new_with_batching( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, + ) -> Self { + Self::with_device(commitment_parameters, fri_parameters, fri_batching, None) + } + + /// Creates a Protocol `v6` configuration targeting an optional CUDA device. + pub fn with_device( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, + device_id: Option, + ) -> Self { + #[cfg(feature = "cuda")] + { + assert_eq!( + commitment_parameters.cap_height, 0, + "the CUDA backend currently supports only cap_height = 0" + ); + assert!( + fri_parameters.max_log_arity <= 1, + "the CUDA backend currently supports only binary FRI folds" + ); + let _ = device_id; + } + #[cfg(not(feature = "cuda"))] + let pcs = { + assert!( + device_id.is_none_or(|device| device == 0), + "no CUDA backend to place a prover on device {device_id:?}" + ); + let val_mmcs = + crate::p3_adapter::spill::SpillableMmcs::new_v6(commitment_parameters.cap_height); + let ext_mmcs = ExtensionMmcs::new(val_mmcs.clone()); + let inner_parameters = InnerFriParameters { + log_blowup: commitment_parameters.log_blowup, + log_final_poly_len: fri_parameters.log_final_poly_len, + max_log_arity: fri_parameters.max_log_arity, + num_queries: fri_parameters.num_queries, + commit_proof_of_work_bits: fri_parameters.commit_proof_of_work_bits, + query_proof_of_work_bits: fri_parameters.query_proof_of_work_bits, + mmcs: ext_mmcs, + }; + let mut inner = crate::p3_adapter::spill::SpillableTwoAdicFriPcs::new( + PcsDft::default(), + val_mmcs, + inner_parameters, + ) + .with_batching(fri_batching); + if let Some(dir) = std::env::var_os("MULTI_STARK_SPILL_DIR") + && !dir.is_empty() + { + inner.set_spill_dir(Some(std::path::PathBuf::from(dir))); + } + DomainMappedPcs::new(inner) + }; + #[cfg(feature = "cuda")] + let pcs = { + let dev = device_id.unwrap_or_else(crate::cuda::configured_device); + let val_mmcs = new_mmcs(commitment_parameters.cap_height, dev); + let ext_mmcs = ExtensionMmcs::new(val_mmcs.clone()); + let inner_parameters = InnerFriParameters { + log_blowup: commitment_parameters.log_blowup, + log_final_poly_len: fri_parameters.log_final_poly_len, + max_log_arity: fri_parameters.max_log_arity, + num_queries: fri_parameters.num_queries, + commit_proof_of_work_bits: fri_parameters.commit_proof_of_work_bits, + query_proof_of_work_bits: fri_parameters.query_proof_of_work_bits, + mmcs: ext_mmcs, + }; + let pcs_dft = CudaDft::new(dev); + DomainMappedPcs::new(crate::cuda::pcs::CudaTwoAdicFriPcs::new( + pcs_dft, + val_mmcs, + inner_parameters, + )) + }; + + let challenger_seed = + build_v6_challenger_seed::(commitment_parameters, fri_parameters, fri_batching); + let max_log_degree = Val::TWO_ADICITY - commitment_parameters.log_blowup; + let max_quotient_degree = 1 << commitment_parameters.log_blowup; + Self { + pcs: V6Pcs::new(pcs, commitment_parameters, fri_parameters), + challenger_seed, + max_log_degree, + max_quotient_degree, + log_blowup: commitment_parameters.log_blowup, + cap_height: commitment_parameters.cap_height, + commitment_parameters, + fri_parameters, + fri_batching, + } + } + + /// Public protocol-domain seed used by the `v6` challenger. + pub fn challenger_seed(&self) -> &[u8] { + &self.challenger_seed + } + + pub fn cap_height(&self) -> usize { + self.cap_height + } + + pub fn fri_parameters(&self) -> FriParameters { + self.fri_parameters + } + + pub fn fri_batching(&self) -> FriBatching { + self.fri_batching + } + + /// Switches the FRI opening batching mode (`Horner` or `Tensor`), updating + /// both the PCS and the protocol challenger seed. + pub fn with_fri_batching(self, fri_batching: FriBatching) -> Self { + let spill = self.spill_dir().map(std::path::Path::to_path_buf); + let cfg = Self::new_with_batching( + self.commitment_parameters, + self.fri_parameters, + fri_batching, + ); + match spill { + Some(dir) => cfg.with_disk_spill(dir), + None => cfg.without_disk_spill(), + } + } + + /// Enables disk-backed spilling of committed LDE matrices on the CPU prover. + #[cfg_attr(feature = "cuda", allow(unused_mut))] + pub fn with_disk_spill(mut self, dir: impl Into) -> Self { + #[cfg(not(feature = "cuda"))] + self.pcs + .inner_mut() + .inner_mut() + .set_spill_dir(Some(dir.into())); + #[cfg(feature = "cuda")] + let _ = dir.into(); + self + } + + /// Disables disk spilling (forces in-memory LDE storage on CPU). + #[cfg_attr(feature = "cuda", allow(unused_mut))] + pub fn without_disk_spill(mut self) -> Self { + #[cfg(not(feature = "cuda"))] + self.pcs.inner_mut().inner_mut().set_spill_dir(None); + self + } + + /// Returns the configured disk-spill directory, if enabled on the CPU backend. + pub fn spill_dir(&self) -> Option<&std::path::Path> { + #[cfg(not(feature = "cuda"))] + { + self.pcs.spill_dir() + } + #[cfg(feature = "cuda")] + { + None + } + } +} + +impl ProofConfig for GoldilocksV6Config +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + type Pcs = V6Pcs; + type Challenge = EF; + type Challenger = DomainChallenger; + + fn pcs(&self) -> &Self::Pcs { + &self.pcs + } + + fn protocol_version(&self) -> ProtocolVersion { + ProtocolVersion::V6 + } + + fn initialise_challenger(&self) -> Self::Challenger { + self.initialise_challenger_for_mode(TranscriptMode::Single) + } + + fn initialise_challenger_for_mode(&self, mode: TranscriptMode) -> Self::Challenger { + let domain = match mode { + TranscriptMode::Single => Blake3Domain::TranscriptSingle, + TranscriptMode::Batch => Blake3Domain::TranscriptBatch, + }; + DomainChallenger::from_domain(self.challenger_seed.clone(), domain) + } + + fn max_log_degree(&self) -> usize { + self.max_log_degree + } + + fn max_quotient_degree(&self) -> usize { + self.max_quotient_degree + } + + fn log_blowup(&self) -> usize { + self.log_blowup + } + + #[cfg(not(feature = "cuda"))] + fn commit_preprocessed( + &self, + evaluations: &mut dyn Iterator< + Item = (crate::config::Domain, RowMajorMatrix, bool), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let mut inner_evals = + evaluations.map(|(domain, mat, retain_1x)| (domain.into_inner(), mat, retain_1x)); + self.pcs.commit_streaming_with_originals(&mut inner_evals) + } + + #[cfg(not(feature = "cuda"))] + fn commit_main_streaming( + &self, + evaluations: &mut dyn Iterator< + Item = ( + crate::config::Domain, + crate::witness::TraceSource, + bool, + ), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let mut inner_evals = evaluations.map(|(domain, trace, retain_1x)| { + (domain.into_inner(), trace.materialize(), retain_1x) + }); + self.pcs.commit_streaming_with_originals(&mut inner_evals) + } + + #[cfg(not(feature = "cuda"))] + fn accelerated_lookup_commit( + &self, + inputs: &[crate::config::LookupCommitInput<'_, Self>], + lookup_challenge: EF, + fingerprint_challenge: EF, + mut accumulator: EF, + ) -> Option> { + use crate::lookup::{ + InMemoryChunk, OwnedWindowChunk, TraceRowChunk, stage_2_trace_chunked, + }; + use crate::p3_adapter::spill::{SpillPackWriter, SpilledMatrix}; + use crate::traits::{Pcs as _, flatten_to_base}; + + enum CpuRowChunk<'a> { + InMemory(InMemoryChunk<'a, Val>), + Spilled(OwnedWindowChunk), + } + + impl TraceRowChunk for CpuRowChunk<'_> { + #[inline] + fn row_pair(&self, local_row: usize) -> (&[Val], &[Val]) { + match self { + Self::InMemory(chunk) => chunk.row_pair(local_row), + Self::Spilled(chunk) => chunk.row_pair(local_row), + } + } + } + + enum TraceBacking<'a> { + Borrowed(&'a RowMajorMatrix), + Owned(RowMajorMatrix), + Spilled(SpilledMatrix), + } + + impl TraceBacking<'_> { + fn load_chunk(&self, start: usize, len: usize) -> CpuRowChunk<'_> { + match self { + Self::Borrowed(mat) => CpuRowChunk::InMemory(InMemoryChunk::new(mat, start)), + Self::Owned(mat) => CpuRowChunk::InMemory(InMemoryChunk::new(mat, start)), + Self::Spilled(spilled) => CpuRowChunk::Spilled(OwnedWindowChunk::new( + spilled.read_window_with_wrap(start, len), + )), + } + } + } + + let spill_dir = self.spill_dir(); + let any_unmaterialized = inputs + .iter() + .any(|input| !input.lookup_values.is_materialized()); + if spill_dir.is_none() && !any_unmaterialized { + return None; + } + + let mut spill_pack = spill_dir.map(SpillPackWriter::create); + let mut spilled_ldes = + Vec::with_capacity(if spill_dir.is_some() { inputs.len() } else { 0 }); + let mut prehashed = Vec::with_capacity(if spill_dir.is_some() { inputs.len() } else { 0 }); + let height_counts: std::collections::HashMap = if spill_dir.is_some() { + let mut counts = std::collections::HashMap::new(); + for input in inputs { + let lde_height = input.lookup_values.height() << self.log_blowup; + *counts.entry(lde_height).or_insert(0) += 1; + } + counts + } else { + std::collections::HashMap::new() + }; + let mut in_memory_ldes = + Vec::with_capacity(if spill_dir.is_none() { inputs.len() } else { 0 }); + let mut intermediates = Vec::with_capacity(inputs.len()); + let leaf_domain = self.pcs.leaf_domain(); + + for input in inputs { + let circuit = input.circuit; + let height = input.lookup_values.height(); + let (stage_2_ext, delta) = if input.lookup_values.is_materialized() { + input.lookup_values.stage_2_trace( + circuit.lookup_group_size, + lookup_challenge, + &fingerprint_challenge, + ) + } else if circuit.graph.lookups.is_empty() { + ( + RowMajorMatrix::new(vec![::ZERO; height], 1), + ::ZERO, + ) + } else { + let (s1_data, s1_idx) = input.stage_1; + let main_backing = if let Some(spilled) = s1_data.spilled_original_trace(s1_idx) { + TraceBacking::Spilled(spilled) + } else if let Some(owned) = s1_data.take_in_memory_original_trace(s1_idx) { + TraceBacking::Owned(owned) + } else { + let trace_domain = self.pcs.natural_domain_for_degree(height); + TraceBacking::Owned( + self.pcs + .get_evaluations_on_domain(s1_data, s1_idx, trace_domain) + .to_row_major_matrix(), + ) + }; + + let prep_backing = if circuit.graph.lookup_prefix_uses_preprocessed() { + if let Some(pp) = circuit.preprocessed.as_ref() { + Some(TraceBacking::Borrowed(pp)) + } else if let Some((prep_data, prep_idx)) = input.preprocessed { + if let Some(spilled) = prep_data.spilled_original_trace(prep_idx) { + Some(TraceBacking::Spilled(spilled)) + } else { + let trace_domain = self.pcs.natural_domain_for_degree(height); + Some(TraceBacking::Owned( + self.pcs + .get_evaluations_on_domain(prep_data, prep_idx, trace_domain) + .to_row_major_matrix(), + )) + } + } else { + panic!( + "circuit lookup expressions read preprocessed columns, but no preprocessed trace is available" + ); + } + } else { + None + }; + + stage_2_trace_chunked( + circuit, + height, + lookup_challenge, + &fingerprint_challenge, + |start, len| main_backing.load_chunk(start, len), + prep_backing + .as_ref() + .map(|prep| move |start, len| prep.load_chunk(start, len)), + ) + }; + + accumulator += delta; + intermediates.push(accumulator); + + let stage_2_base = flatten_to_base::(stage_2_ext); + let domain = self.pcs.natural_domain_for_degree(stage_2_base.height()); + let lde = self.pcs.compute_lde(domain.into_inner(), stage_2_base); + if let Some(pack) = &mut spill_pack { + if height_counts.get(&lde.height()).copied() == Some(1) { + let (spilled, digests) = pack.append_matrix_and_hash(&lde, leaf_domain); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } + } else { + in_memory_ldes.push(lde); + } + } + + if let Some(first) = inputs.first() { + first.stage_1.0.release_original_traces(); + } + + let (commitment, data) = if let Some(mut pack) = spill_pack { + pack.flush(); + self.pcs + .commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed) + } else { + self.pcs.commit_in_memory_ldes(in_memory_ldes) + }; + Some((commitment, data, intermediates)) + } + + #[cfg(not(feature = "cuda"))] + fn accelerated_quotient_commit( + &self, + inputs: &[crate::config::QuotientCommitInput<'_, Self>], + alpha: EF, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + use crate::p3_adapter::pcs::{lde_from_shifted_coefficients, shifted_quotient_slices}; + use crate::p3_adapter::spill::SpillPackWriter; + use crate::traits::{EvaluationDomain, Pcs as _, flatten_to_base}; + + let spill_dir = self.spill_dir()?; + let mut pack = SpillPackWriter::create(spill_dir); + let mut spilled_ldes = Vec::with_capacity(inputs.len()); + let mut prehashed = Vec::with_capacity(inputs.len()); + let dft = self.pcs.quotient_dft(); + let log_blowup = self.log_blowup; + let leaf_domain = self.pcs.leaf_domain(); + let mut height_counts = std::collections::HashMap::new(); + for input in inputs { + let lde_height = + (input.quotient_domain.size() / input.circuit.quotient_degree()) << log_blowup; + *height_counts.entry(lde_height).or_insert(0) += 1; + } + + for input in inputs { + let circuit = input.circuit; + let quotient_degree = circuit.quotient_degree(); + let preprocessed_evals = input.preprocessed.map(|(data, idx)| { + self.pcs + .get_evaluations_on_domain(data, idx, input.quotient_domain) + }); + let stage_1_evals = self.pcs.get_evaluations_on_domain( + input.stage_1.0, + input.stage_1.1, + input.quotient_domain, + ); + let stage_2_evals = self.pcs.get_evaluations_on_domain( + input.stage_2.0, + input.stage_2.1, + input.quotient_domain, + ); + let q_vals = crate::prover::quotient_values::( + circuit, + &input.lookup_publics, + input.trace_domain, + input.quotient_domain, + &preprocessed_evals, + &stage_1_evals, + &stage_2_evals, + alpha, + input.constraint_count, + ); + drop(preprocessed_evals); + drop(stage_1_evals); + drop(stage_2_evals); + + let quotient_flat = flatten_to_base::(RowMajorMatrix::new_col(q_vals)); + let sliced = shifted_quotient_slices( + dft, + quotient_flat, + EvaluationDomain::first_point(&input.quotient_domain), + quotient_degree, + ); + let lde = lde_from_shifted_coefficients(dft, sliced, log_blowup); + if height_counts.get(&lde.height()).copied() == Some(1) { + let (spilled, digests) = pack.append_matrix_and_hash(&lde, leaf_domain); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } + } + + pack.flush(); + Some( + self.pcs + .commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed), + ) + } + + fn canonicalize_proof(proof: &mut crate::prover::Proof) { + canonicalize_goldilocks_fri_proof::>(proof); + } +} + fn new_pcs( commitment_parameters: CommitmentParameters, fri_parameters: FriParameters, diff --git a/src/verifier.rs b/src/verifier.rs index b23107a..029f420 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -243,7 +243,9 @@ impl System { // observations as the prover, so any divergence (e.g. different // commitments) produces different challenges, making it infeasible for a // cheating prover to predict them. - let mut challenger = self.config.initialise_challenger(); + let mut challenger = self + .config + .initialise_challenger_for_mode(crate::config::TranscriptMode::Single); // Bind the system shape into the transcript. The protocol parameters // are already bound via the challenger seed. @@ -424,6 +426,17 @@ impl System { // the value itself feeds no constraint. let domain = pcs .natural_domain_for_degree(self.circuits[ci].preprocessed_height); + if !self.config.omit_inactive_preprocessed_openings() { + let prep_log_degree = + log2_strict_usize(self.circuits[ci].preprocessed_height); + let unshifted = + zeta * SC::Challenge::from(domain.first_point().inverse()); + crate::ensure!( + unshifted.exp_power_of_2(prep_log_degree) + != >::ONE, + VerificationError::InvalidChallenge + ); + } let preprocessed_opened_values = preprocessed_opened_values.as_ref().unwrap(); preprocessed_trace_evaluations.push(( From 41186715a6a9e5562b4fcf384886e6b2cefc42c0 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sat, 21 Nov 2026 22:55:44 -0500 Subject: [PATCH 19/28] Port CUDA backend to Goldilocks F_p^3 (X^3 - X - 1), Protocol v6 BLAKE3 domains, and Tensor FRI batching --- cuda/goldilocks.cuh | 3 + cuda/kernels.cu | 1721 ++++++++++++++++++++++--------- src/cuda/mmcs.rs | 114 +- src/cuda/mod.rs | 1502 ++++++++++++++++++++++----- src/cuda/pcs.rs | 641 +++++++----- src/cuda/tests/quotient.rs | 10 +- src/cuda/witness.rs | 43 +- src/lookup.rs | 40 +- src/p3_adapter/domain_blake3.rs | 118 +++ src/p3_adapter/fri_batching.rs | 2 + src/types.rs | 1424 +++++++++++++------------ 11 files changed, 3937 insertions(+), 1681 deletions(-) diff --git a/cuda/goldilocks.cuh b/cuda/goldilocks.cuh index abebe64..19c78ab 100644 --- a/cuda/goldilocks.cuh +++ b/cuda/goldilocks.cuh @@ -69,6 +69,9 @@ __device__ __forceinline__ uint64_t canonical_add(uint64_t a,uint64_t b){ if(sum=GOLDILOCKS_P?sum-GOLDILOCKS_P:sum; } +__device__ __forceinline__ uint64_t canonical_sub(uint64_t a,uint64_t b){ + return a>=b?a-b:GOLDILOCKS_P-(b-a); +} __device__ __forceinline__ uint64_t canonical_mul(uint64_t a,uint64_t b){ const uint64_t low=a*b,high=__umul64hi(a,b),high_high=high>>32; uint64_t reduced_low=low-high_high; diff --git a/cuda/kernels.cu b/cuda/kernels.cu index ec114ea..6397ceb 100644 --- a/cuda/kernels.cu +++ b/cuda/kernels.cu @@ -29,6 +29,7 @@ constexpr uint32_t BLAKE3_CHUNK_START = 1U << 0; constexpr uint32_t BLAKE3_CHUNK_END = 1U << 1; constexpr uint32_t BLAKE3_PARENT = 1U << 2; constexpr uint32_t BLAKE3_ROOT = 1U << 3; +constexpr uint32_t BLAKE3_DERIVE_KEY_MATERIAL = 1U << 6; // All work currently uses CUDA's per-thread default stream. Stream-ordered // allocation preserves the same dependency order while avoiding cudaFree's // device-wide synchronization on thousands of short-lived PCS buffers. @@ -72,6 +73,18 @@ __device__ __constant__ uint32_t BLAKE3_IV[8] = { 0x6A09E667U, 0xBB67AE85U, 0x3C6EF372U, 0xA54FF53AU, 0x510E527FU, 0x9B05688CU, 0x1F83D9ABU, 0x5BE0CD19U, }; +// Precomputed BLAKE3 derive_key context keys for Protocol v6 Merkle hashing +// (pinned against Rust's `Blake3Domain::MerkleLeaf` and `Blake3Domain::MerkleCompress`). +// Context "multi-stark/v6/merkle/leaf": +__device__ __constant__ uint32_t BLAKE3_V6_LEAF_CV[8] = { + 0x77042819U, 0x5A1DD04FU, 0x2F8D0BB8U, 0x39D27832U, + 0x552A30F6U, 0x546C9899U, 0x8510A8EFU, 0x83ECCD66U, +}; +// Context "multi-stark/v6/merkle/compress": +__device__ __constant__ uint32_t BLAKE3_V6_COMPRESS_CV[8] = { + 0xCC4D7633U, 0xF8492FECU, 0x5704B1FDU, 0x2D69A6B5U, + 0xA871EBB5U, 0x6439610DU, 0x89E86BE6U, 0x02E22A34U, +}; __device__ __constant__ unsigned int BLAKE3_PERMUTATION[16] = { 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8, }; @@ -160,11 +173,12 @@ __device__ __forceinline__ uint32_t load_u32_le(const uint8_t* bytes, __device__ __forceinline__ void blake3_chunk( const uint8_t* bytes, size_t length, uint64_t chunk_counter, bool root, - uint32_t output[8]) { + uint32_t output[8], bool domain_v6 = false) { uint32_t chaining_value[8]; + const uint32_t domain_flags = domain_v6 ? BLAKE3_DERIVE_KEY_MATERIAL : 0U; #pragma unroll for (unsigned int i = 0; i < 8; ++i) { - chaining_value[i] = BLAKE3_IV[i]; + chaining_value[i] = domain_v6 ? BLAKE3_V6_LEAF_CV[i] : BLAKE3_IV[i]; } const size_t blocks = length == 0 ? 1 : (length + 63) / 64; for (size_t block_index = 0; block_index < blocks; ++block_index) { @@ -179,7 +193,7 @@ __device__ __forceinline__ void blake3_chunk( block[word] = load_u32_le(bytes + block_offset, block_length, static_cast(word) * 4); } - uint32_t flags = block_index == 0 ? BLAKE3_CHUNK_START : 0; + uint32_t flags = domain_flags | (block_index == 0 ? BLAKE3_CHUNK_START : 0U); const bool last = block_index + 1 == blocks; if (last) { flags |= BLAKE3_CHUNK_END; @@ -206,7 +220,8 @@ __device__ __forceinline__ void blake3_chunk( __device__ __forceinline__ void blake3_parent(const uint32_t left[8], const uint32_t right[8], - bool root, uint32_t output[8]) { + bool root, uint32_t output[8], + bool domain_v6 = false) { uint32_t block[16]; #pragma unroll for (unsigned int i = 0; i < 8; ++i) { @@ -214,8 +229,10 @@ __device__ __forceinline__ void blake3_parent(const uint32_t left[8], block[i + 8] = right[i]; } uint32_t compressed[16]; - blake3_compress(BLAKE3_IV, block, 0, 64, - BLAKE3_PARENT | (root ? BLAKE3_ROOT : 0), compressed); + const uint32_t flags = BLAKE3_PARENT | (root ? BLAKE3_ROOT : 0U) | + (domain_v6 ? BLAKE3_DERIVE_KEY_MATERIAL : 0U); + blake3_compress(domain_v6 ? BLAKE3_V6_LEAF_CV : BLAKE3_IV, block, 0, 64, + flags, compressed); #pragma unroll for (unsigned int i = 0; i < 8; ++i) { output[i] = compressed[i]; @@ -223,7 +240,8 @@ __device__ __forceinline__ void blake3_parent(const uint32_t left[8], } __device__ __forceinline__ void blake3_hash_digest_pair( - const uint8_t* left, const uint8_t* right, uint8_t* digest) { + const uint8_t* left, const uint8_t* right, uint8_t* digest, + bool domain_v6 = false) { uint32_t block[16]; #pragma unroll for (unsigned int word = 0; word < 8; ++word) { @@ -232,9 +250,10 @@ __device__ __forceinline__ void blake3_hash_digest_pair( load_u32_le(right, 32, static_cast(word) * 4); } uint32_t compressed[16]; - blake3_compress(BLAKE3_IV, block, 0, 64, - BLAKE3_CHUNK_START | BLAKE3_CHUNK_END | BLAKE3_ROOT, - compressed); + const uint32_t flags = BLAKE3_CHUNK_START | BLAKE3_CHUNK_END | BLAKE3_ROOT | + (domain_v6 ? BLAKE3_DERIVE_KEY_MATERIAL : 0U); + blake3_compress(domain_v6 ? BLAKE3_V6_COMPRESS_CV : BLAKE3_IV, block, 0, 64, + flags, compressed); #pragma unroll for (unsigned int word = 0; word < 8; ++word) { const uint32_t value = compressed[word]; @@ -687,16 +706,17 @@ struct ConstraintLookup { }; struct Ext2 { uint64_t c0; uint64_t c1; }; +struct Ext3 { uint64_t c0; uint64_t c1; uint64_t c2; }; struct PendingLookupLde { ResidentLde* lde = nullptr; - Ext2* deltas = nullptr; + uint64_t* deltas = nullptr; uint64_t* multiplicities = nullptr; uint64_t* args = nullptr; uint64_t* norms = nullptr; uint64_t* norm_inverses = nullptr; size_t* arg_offsets = nullptr; - Ext2* conjugates = nullptr; + uint64_t* conjugates = nullptr; size_t height = 0; size_t slots = 0; size_t extended_height = 0; @@ -704,6 +724,7 @@ struct PendingLookupLde { size_t args_width = 0; size_t group_size = 0; size_t scratch_rows = 0; + size_t ext_degree = 2; ~PendingLookupLde() { if (norm_inverses != nullptr) cudaFree(norm_inverses); @@ -740,18 +761,260 @@ __device__ __forceinline__ Ext2 ext2_mul(Ext2 a, Ext2 b, uint64_t w) { goldilocks_mul(a.c1, b.c0))}; } +// Cubic trinomial extension F_p[X] / (X^3 - X - 1) arithmetic (matches stock +// Plonky3 `CubicTrinomialExtensionField`). +__device__ __forceinline__ Ext3 canonical_ext3_add(Ext3 a, Ext3 b) { + return {canonical_add(a.c0, b.c0), canonical_add(a.c1, b.c1), + canonical_add(a.c2, b.c2)}; +} +__device__ __forceinline__ Ext3 canonical_ext3_mul(Ext3 a, Ext3 b) { + const uint64_t v0 = canonical_mul(a.c0, b.c0); + const uint64_t v1 = canonical_mul(a.c1, b.c1); + const uint64_t v2 = canonical_mul(a.c2, b.c2); + const uint64_t m01 = canonical_sub( + canonical_sub(canonical_mul(canonical_add(a.c0, a.c1), + canonical_add(b.c0, b.c1)), + v0), + v1); + const uint64_t m02 = canonical_sub( + canonical_sub(canonical_mul(canonical_add(a.c0, a.c2), + canonical_add(b.c0, b.c2)), + v0), + v2); + const uint64_t m12 = canonical_sub( + canonical_sub(canonical_mul(canonical_add(a.c1, a.c2), + canonical_add(b.c1, b.c2)), + v1), + v2); + return {canonical_add(v0, m12), + canonical_add(canonical_add(m01, m12), v2), + canonical_add(canonical_add(m02, v1), v2)}; +} +__device__ __forceinline__ Ext3 ext3_add(Ext3 a, Ext3 b) { + return {goldilocks_add(a.c0, b.c0), goldilocks_add(a.c1, b.c1), + goldilocks_add(a.c2, b.c2)}; +} +__device__ __forceinline__ Ext3 ext3_sub(Ext3 a, Ext3 b) { + return {goldilocks_sub(a.c0, b.c0), goldilocks_sub(a.c1, b.c1), + goldilocks_sub(a.c2, b.c2)}; +} +__device__ __forceinline__ Ext3 ext3_mul(Ext3 a, Ext3 b) { + const uint64_t a0 = canonicalize(a.c0), a1 = canonicalize(a.c1), + a2 = canonicalize(a.c2); + const uint64_t b0 = canonicalize(b.c0), b1 = canonicalize(b.c1), + b2 = canonicalize(b.c2); + return canonical_ext3_mul({a0, a1, a2}, {b0, b1, b2}); +} +__device__ __forceinline__ void ext3_adjugate_and_norm( + Ext3 a, Ext3& adj, uint64_t& norm) { + const uint64_t a0 = canonicalize(a.c0), a1 = canonicalize(a.c1), + a2 = canonicalize(a.c2); + const uint64_t s02 = canonical_add(a0, a2); + const uint64_t s12 = canonical_add(a1, a2); + const uint64_t d0 = canonical_sub(canonical_mul(s02, s02), + canonical_mul(a1, s12)); + const uint64_t d1 = canonical_sub(canonical_mul(a2, a2), + canonical_mul(a0, a1)); + const uint64_t d2 = canonical_sub(canonical_mul(a1, a1), + canonical_mul(a2, s02)); + adj = {d0, d1, d2}; + norm = canonical_add(canonical_add(canonical_mul(a0, d0), + canonical_mul(a2, d1)), + canonical_mul(a1, d2)); +} +__device__ __forceinline__ Ext3 ext3_inverse(Ext3 value) { + Ext3 adj; + uint64_t norm = 0; + ext3_adjugate_and_norm(value, adj, norm); + const uint64_t inv = norm == 0 ? 0 : goldilocks_pow(norm, GOLDILOCKS_P - 2); + return {canonical_mul(adj.c0, inv), canonical_mul(adj.c1, inv), + canonical_mul(adj.c2, inv)}; +} + +template +struct ExtOps; + +template <> +struct ExtOps { + static constexpr size_t D = 2; + __device__ __forceinline__ static Ext2 zero() { return {0, 0}; } + __device__ __forceinline__ static Ext2 one() { return {1, 0}; } + __device__ __forceinline__ static Ext2 from_base(uint64_t x) { return {x, 0}; } + __device__ __host__ __forceinline__ static Ext2 load(const uint64_t* p) { + return {p[0], p[1]}; + } + __device__ __host__ __forceinline__ static void store(uint64_t* p, Ext2 v) { + p[0] = v.c0; + p[1] = v.c1; + } + __device__ __forceinline__ static Ext2 add(Ext2 a, Ext2 b) { return ext2_add(a, b); } + __device__ __forceinline__ static Ext2 sub(Ext2 a, Ext2 b) { return ext2_sub(a, b); } + __device__ __forceinline__ static Ext2 mul(Ext2 a, Ext2 b, uint64_t w) { + return ext2_mul(a, b, w); + } + __device__ __forceinline__ static Ext2 canonical_add_ext(Ext2 a, Ext2 b) { + return canonical_ext2_add(a, b); + } + __device__ __forceinline__ static Ext2 canonical_mul_ext(Ext2 a, Ext2 b, uint64_t w) { + return canonical_ext2_mul(a, b, w); + } + __device__ __forceinline__ static Ext2 scale(Ext2 a, uint64_t s) { + return {goldilocks_mul(a.c0, s), goldilocks_mul(a.c1, s)}; + } + __device__ __forceinline__ static Ext2 canonical_scale(Ext2 a, uint64_t s) { + return {canonical_mul(a.c0, s), canonical_mul(a.c1, s)}; + } + __device__ __forceinline__ static Ext2 fmadd_base(Ext2 acc, Ext2 w, uint64_t s) { + return {goldilocks_add(acc.c0, goldilocks_mul(w.c0, s)), + goldilocks_add(acc.c1, goldilocks_mul(w.c1, s))}; + } + __device__ __forceinline__ static Ext2 canonical_fmadd_base(Ext2 acc, Ext2 w, uint64_t s) { + return {canonical_add(acc.c0, canonical_mul(w.c0, s)), + canonical_add(acc.c1, canonical_mul(w.c1, s))}; + } + __device__ __forceinline__ static Ext2 add_base(Ext2 a, uint64_t s) { + return {goldilocks_add(a.c0, s), a.c1}; + } + __device__ __forceinline__ static void adjugate_and_norm( + Ext2 a, uint64_t w, Ext2& adj, uint64_t& norm) { + adj = {a.c0, goldilocks_sub(0, a.c1)}; + norm = goldilocks_sub(goldilocks_mul(a.c0, a.c0), + goldilocks_mul(w, goldilocks_mul(a.c1, a.c1))); + } + __device__ __forceinline__ static uint64_t denom_norm( + Ext2 point, uint64_t x, uint64_t w) { + const uint64_t real = goldilocks_sub(point.c0, x); + return goldilocks_sub(goldilocks_mul(real, real), + goldilocks_mul(w, goldilocks_mul(point.c1, point.c1))); + } + __device__ __forceinline__ static Ext2 denom_adjugate_scaled( + Ext2 point, uint64_t x, uint64_t inv_norm) { + return {goldilocks_mul(goldilocks_sub(point.c0, x), inv_norm), + goldilocks_mul(goldilocks_sub(0, point.c1), inv_norm)}; + } + __device__ __forceinline__ static void accumulate_base_root( + Ext2& acc, uint64_t c, const uint64_t* alpha, size_t total_constraints, size_t ci) { + acc.c0 = goldilocks_add(acc.c0, goldilocks_mul(c, alpha[ci])); + acc.c1 = goldilocks_add(acc.c1, goldilocks_mul(c, alpha[total_constraints + ci])); + } + __device__ __forceinline__ static void accumulate_ext_constraint( + Ext2& acc, Ext2 c, const uint64_t* alpha, size_t total_constraints, size_t ci) { + acc.c0 = goldilocks_add(acc.c0, + goldilocks_add(goldilocks_mul(c.c0, alpha[ci]), + goldilocks_mul(c.c1, alpha[ci + 1]))); + acc.c1 = goldilocks_add(acc.c1, + goldilocks_add(goldilocks_mul(c.c0, alpha[total_constraints + ci]), + goldilocks_mul(c.c1, alpha[total_constraints + ci + 1]))); + } +}; + +template <> +struct ExtOps { + static constexpr size_t D = 3; + __device__ __forceinline__ static Ext3 zero() { return {0, 0, 0}; } + __device__ __forceinline__ static Ext3 one() { return {1, 0, 0}; } + __device__ __forceinline__ static Ext3 from_base(uint64_t x) { return {x, 0, 0}; } + __device__ __host__ __forceinline__ static Ext3 load(const uint64_t* p) { + return {p[0], p[1], p[2]}; + } + __device__ __host__ __forceinline__ static void store(uint64_t* p, Ext3 v) { + p[0] = v.c0; + p[1] = v.c1; + p[2] = v.c2; + } + __device__ __forceinline__ static Ext3 add(Ext3 a, Ext3 b) { return ext3_add(a, b); } + __device__ __forceinline__ static Ext3 sub(Ext3 a, Ext3 b) { return ext3_sub(a, b); } + __device__ __forceinline__ static Ext3 mul(Ext3 a, Ext3 b, uint64_t) { + return ext3_mul(a, b); + } + __device__ __forceinline__ static Ext3 canonical_add_ext(Ext3 a, Ext3 b) { + return canonical_ext3_add(a, b); + } + __device__ __forceinline__ static Ext3 canonical_mul_ext(Ext3 a, Ext3 b, uint64_t) { + return canonical_ext3_mul(a, b); + } + __device__ __forceinline__ static Ext3 scale(Ext3 a, uint64_t s) { + return {goldilocks_mul(a.c0, s), goldilocks_mul(a.c1, s), + goldilocks_mul(a.c2, s)}; + } + __device__ __forceinline__ static Ext3 canonical_scale(Ext3 a, uint64_t s) { + return {canonical_mul(a.c0, s), canonical_mul(a.c1, s), + canonical_mul(a.c2, s)}; + } + __device__ __forceinline__ static Ext3 fmadd_base(Ext3 acc, Ext3 w, uint64_t s) { + return {goldilocks_add(acc.c0, goldilocks_mul(w.c0, s)), + goldilocks_add(acc.c1, goldilocks_mul(w.c1, s)), + goldilocks_add(acc.c2, goldilocks_mul(w.c2, s))}; + } + __device__ __forceinline__ static Ext3 canonical_fmadd_base(Ext3 acc, Ext3 w, uint64_t s) { + return {canonical_add(acc.c0, canonical_mul(w.c0, s)), + canonical_add(acc.c1, canonical_mul(w.c1, s)), + canonical_add(acc.c2, canonical_mul(w.c2, s))}; + } + __device__ __forceinline__ static Ext3 add_base(Ext3 a, uint64_t s) { + return {goldilocks_add(a.c0, s), a.c1, a.c2}; + } + __device__ __forceinline__ static void adjugate_and_norm( + Ext3 a, uint64_t, Ext3& adj, uint64_t& norm) { + ext3_adjugate_and_norm(a, adj, norm); + } + __device__ __forceinline__ static uint64_t denom_norm( + Ext3 point, uint64_t x, uint64_t) { + Ext3 adj; + uint64_t norm = 0; + ext3_adjugate_and_norm({goldilocks_sub(point.c0, x), point.c1, point.c2}, + adj, norm); + return norm; + } + __device__ __forceinline__ static Ext3 denom_adjugate_scaled( + Ext3 point, uint64_t x, uint64_t inv_norm) { + Ext3 adj; + uint64_t norm = 0; + ext3_adjugate_and_norm({goldilocks_sub(point.c0, x), point.c1, point.c2}, + adj, norm); + const uint64_t inv = canonicalize(inv_norm); + return {canonical_mul(adj.c0, inv), canonical_mul(adj.c1, inv), + canonical_mul(adj.c2, inv)}; + } + __device__ __forceinline__ static void accumulate_base_root( + Ext3& acc, uint64_t c, const uint64_t* alpha, size_t total_constraints, size_t ci) { + acc.c0 = goldilocks_add(acc.c0, goldilocks_mul(c, alpha[ci])); + acc.c1 = goldilocks_add(acc.c1, goldilocks_mul(c, alpha[total_constraints + ci])); + acc.c2 = goldilocks_add(acc.c2, goldilocks_mul(c, alpha[2 * total_constraints + ci])); + } + __device__ __forceinline__ static void accumulate_ext_constraint( + Ext3& acc, Ext3 c, const uint64_t* alpha, size_t total_constraints, size_t ci) { + acc.c0 = goldilocks_add(acc.c0, + goldilocks_add(goldilocks_add(goldilocks_mul(c.c0, alpha[ci]), + goldilocks_mul(c.c1, alpha[ci + 1])), + goldilocks_mul(c.c2, alpha[ci + 2]))); + const size_t o1 = total_constraints + ci; + acc.c1 = goldilocks_add(acc.c1, + goldilocks_add(goldilocks_add(goldilocks_mul(c.c0, alpha[o1]), + goldilocks_mul(c.c1, alpha[o1 + 1])), + goldilocks_mul(c.c2, alpha[o1 + 2]))); + const size_t o2 = 2 * total_constraints + ci; + acc.c2 = goldilocks_add(acc.c2, + goldilocks_add(goldilocks_add(goldilocks_mul(c.c0, alpha[o2]), + goldilocks_mul(c.c1, alpha[o2 + 1])), + goldilocks_mul(c.c2, alpha[o2 + 2]))); + } +}; + struct ResidentReducedOpening { - Ext2* values=nullptr; uint8_t* scratch=nullptr; size_t scratch_bytes=0; size_t height=0; + uint64_t* values=nullptr; uint8_t* scratch=nullptr; size_t scratch_bytes=0; + size_t height=0; size_t ext_degree=2; ~ResidentReducedOpening(){if(values)cudaFree(values);if(scratch)cudaFree(scratch);} }; struct ResidentFriWorkspace { // The coset is a process-wide device constant shared by every workspace // of its size; the workspace does not own it. - Ext2* inv_denoms=nullptr; const uint64_t* coset=nullptr; Ext2* output=nullptr; - Ext2* alpha=nullptr; Ext2* interpolation_partials=nullptr; + uint64_t* inv_denoms=nullptr; const uint64_t* coset=nullptr; uint64_t* output=nullptr; + uint64_t* alpha=nullptr; uint64_t* interpolation_partials=nullptr; size_t inv_count=0; size_t coset_count=0; size_t output_capacity=0; size_t alpha_capacity=0,partial_capacity=0; + size_t ext_degree=2; ~ResidentFriWorkspace(){if(inv_denoms)cudaFree(inv_denoms);if(output)cudaFree(output);if(alpha)cudaFree(alpha);if(interpolation_partials)cudaFree(interpolation_partials);} }; @@ -760,165 +1023,108 @@ struct InterpolationTask { uint64_t scale0; uint64_t scale1; }; +struct InterpolationTaskExt3 { + const void* lde; size_t height; size_t inv_offset; size_t output_offset; + uint64_t scale0; uint64_t scale1; uint64_t scale2; +}; + struct ReductionTask { void* reduced; const void* lde; size_t height; size_t inv_offset; uint64_t y0; uint64_t y1; uint64_t offset0; uint64_t offset1; }; -__global__ void interpolate_lde_columns(Ext2* output, const ResidentLde* lde, - const Ext2* inv_denoms, const uint64_t* coset, size_t height, Ext2 scale, - uint64_t ext_w) { - extern __shared__ Ext2 sums[]; const size_t column=blockIdx.x; Ext2 sum{0,0}; - for(size_t row=threadIdx.x;rowvalues[row*lde->width+column]),goldilocks_mul(weight.c1,lde->values[row*lde->width+column])}; - sum=ext2_add(sum,term); - } sums[threadIdx.x]=sum;__syncthreads(); - for(unsigned int stride=blockDim.x/2;stride;stride>>=1){if(threadIdx.x(blockIdx.x)*INTERPOLATION_COLUMNS+threadIdx.x; - const size_t row_begin=static_cast(blockIdx.y)*INTERPOLATION_ROWS; - const size_t row_end=row_begin+INTERPOLATION_ROWSwidth){ - for(size_t row=row_begin+threadIdx.y;rowvalues[row*lde->width+column]; - sum.c0=canonical_add(sum.c0,canonical_mul(weight.c0,value)); - sum.c1=canonical_add(sum.c1,canonical_mul(weight.c1,value)); - } - } - sums[threadIdx.y][threadIdx.x]=sum;__syncthreads(); - for(unsigned int stride=INTERPOLATION_LANES/2;stride;stride>>=1){ - if(threadIdx.ywidth) - partials[static_cast(blockIdx.y)*lde->width+column]=sums[0][threadIdx.x]; -} +inline Ext2 task_scale(const InterpolationTask& t) { return {t.scale0, t.scale1}; } +inline Ext3 task_scale(const InterpolationTaskExt3& t) { return {t.scale0, t.scale1, t.scale2}; } +inline Ext2 task_y(const ReductionTask& t) { return {t.y0, t.y1}; } +inline Ext3 task_y(const ReductionTaskExt3& t) { return {t.y0, t.y1, t.y2}; } +inline Ext2 task_offset(const ReductionTask& t) { return {t.offset0, t.offset1}; } +inline Ext3 task_offset(const ReductionTaskExt3& t) { return {t.offset0, t.offset1, t.offset2}; } -__global__ void interpolate_lde_partials2(Ext2* partials0,Ext2* partials1, - const ResidentLde* lde,const Ext2* inv0,const Ext2* inv1, - const uint64_t* coset,size_t height,uint64_t ext_w){ - __shared__ Ext2 sums0[INTERPOLATION_LANES][INTERPOLATION_COLUMNS]; - __shared__ Ext2 sums1[INTERPOLATION_LANES][INTERPOLATION_COLUMNS]; - __shared__ Ext2 weights0[INTERPOLATION_ROWS]; - __shared__ Ext2 weights1[INTERPOLATION_ROWS]; - const size_t column=static_cast(blockIdx.x)*INTERPOLATION_COLUMNS+threadIdx.x; - const size_t row_begin=static_cast(blockIdx.y)*INTERPOLATION_ROWS; - const size_t row_end=row_begin+INTERPOLATION_ROWSwidth){ - for(size_t row=row_begin+threadIdx.y;rowvalues[row*lde->width+column]; - const Ext2 w0=weights0[row-row_begin],w1=weights1[row-row_begin]; - sum0.c0=canonical_add(sum0.c0,canonical_mul(w0.c0,value)); - sum0.c1=canonical_add(sum0.c1,canonical_mul(w0.c1,value)); - sum1.c0=canonical_add(sum1.c0,canonical_mul(w1.c0,value)); - sum1.c1=canonical_add(sum1.c1,canonical_mul(w1.c1,value)); - } - } - sums0[threadIdx.y][threadIdx.x]=sum0;sums1[threadIdx.y][threadIdx.x]=sum1; - __syncthreads(); - for(unsigned int stride=INTERPOLATION_LANES/2;stride;stride>>=1){ - if(threadIdx.y +__global__ void interpolate_lde_columns_t(Ext* output, const ResidentLde* lde, + const Ext* inv_denoms, const uint64_t* coset, size_t height, Ext scale, + uint64_t ext_w) { + using Ops = ExtOps; + extern __shared__ uint64_t shared_raw[]; + Ext* sums = reinterpret_cast(shared_raw); + const size_t column=blockIdx.x; Ext sum=Ops::zero(); + for(size_t row=threadIdx.x;rowvalues[row*lde->width+column]); } - if(threadIdx.y==0&&columnwidth){const size_t at=static_cast(blockIdx.y)*lde->width+column; - partials0[at]=sums0[0][threadIdx.x];partials1[at]=sums1[0][threadIdx.x];} -} - -__global__ void finish_lde_interpolation(Ext2* output,const Ext2* partials, - size_t partial_rows,size_t width,Ext2 scale,uint64_t ext_w){ - extern __shared__ Ext2 sums[];const size_t column=blockIdx.x;Ext2 sum{0,0}; - for(size_t row=threadIdx.x;row>=1){ - if(threadIdx.x +struct InterpolationBlockDescT { const uint64_t* values; const uint64_t* coset; - const Ext2* inv0; - const Ext2* inv1; - Ext2* partial0; - Ext2* partial1; + const Ext* inv0; + const Ext* inv1; + Ext* partial0; + Ext* partial1; size_t width; size_t column_begin; size_t row_begin; size_t row_end; }; -struct InterpolationFinishDesc { - Ext2* output; - const Ext2* partials; +template +struct InterpolationFinishDescT { + Ext* output; + const Ext* partials; size_t partial_rows; size_t width; size_t column; - Ext2 scale; + Ext scale; }; -__global__ void interpolate_lde_blocks(const InterpolationBlockDesc* blocks, - uint64_t ext_w) { - const InterpolationBlockDesc d=blocks[blockIdx.x]; - __shared__ Ext2 sums0[INTERPOLATION_LANES][INTERPOLATION_COLUMNS]; - __shared__ Ext2 sums1[INTERPOLATION_LANES][INTERPOLATION_COLUMNS]; - __shared__ Ext2 weights0[INTERPOLATION_ROWS]; - __shared__ Ext2 weights1[INTERPOLATION_ROWS]; +template +__global__ void interpolate_lde_blocks_t(const InterpolationBlockDescT* blocks, + uint64_t) { + using Ops = ExtOps; + const InterpolationBlockDescT d=blocks[blockIdx.x]; + __shared__ Ext sums0[INTERPOLATION_LANES][INTERPOLATION_COLUMNS]; + __shared__ Ext sums1[INTERPOLATION_LANES][INTERPOLATION_COLUMNS]; + __shared__ Ext weights0[INTERPOLATION_ROWS]; + __shared__ Ext weights1[INTERPOLATION_ROWS]; const size_t column=d.column_begin+threadIdx.x; const size_t linear_thread=threadIdx.y*INTERPOLATION_COLUMNS+threadIdx.x; for(size_t offset=linear_thread;d.row_begin+offset>=1){ if(threadIdx.y +__global__ void finish_lde_interpolation_blocks_t(const InterpolationFinishDescT* finishes, uint64_t ext_w) { - const InterpolationFinishDesc d=finishes[blockIdx.x]; - extern __shared__ Ext2 sums[];Ext2 sum{0,0}; + using Ops = ExtOps; + const InterpolationFinishDescT d=finishes[blockIdx.x]; + extern __shared__ uint64_t shared_raw[]; + Ext* sums = reinterpret_cast(shared_raw); + Ext sum=Ops::zero(); for(size_t row=threadIdx.x;row>=1){ - if(threadIdx.x +__global__ void accumulate_reduced_opening_t(Ext* output,const ResidentLde* lde, + const Ext* inv_denoms,const Ext* alpha_powers,size_t height,Ext reduced_y, + Ext alpha_offset,uint64_t ext_w){ + using Ops = ExtOps; for(size_t row=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;row(gridDim.x)*blockDim.x){ - Ext2 compressed{0,0};for(size_t column=0;columnwidth;++column){const uint64_t v=lde->values[row*lde->width+column];compressed.c0=goldilocks_add(compressed.c0,goldilocks_mul(alpha_powers[column].c0,v));compressed.c1=goldilocks_add(compressed.c1,goldilocks_mul(alpha_powers[column].c1,v));} - const Ext2 term=ext2_mul(alpha_offset,ext2_mul(ext2_sub(reduced_y,compressed),inv_denoms[row],ext_w),ext_w);output[row]=ext2_add(output[row],term); + Ext compressed=Ops::zero(); + for(size_t column=0;columnwidth;++column){ + const uint64_t v=lde->values[row*lde->width+column]; + compressed=Ops::fmadd_base(compressed,alpha_powers[column],v); + } + const Ext term=Ops::mul(alpha_offset,Ops::mul(Ops::sub(reduced_y,compressed),inv_denoms[row],ext_w),ext_w); + output[row]=Ops::add(output[row],term); } } -__global__ void fold_fri_ext2(Ext2* output,const Ext2* input,uint64_t* powers, - size_t height,Ext2 beta,uint64_t ext_w){ +template +__global__ void fold_fri_t(Ext* output,const Ext* input,const uint64_t* powers, + size_t height,Ext beta,uint64_t ext_w){ + using Ops = ExtOps; for(size_t row=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;row(gridDim.x)*blockDim.x){ - const Ext2 lo=input[2*row],hi=input[2*row+1]; - const Ext2 even={goldilocks_mul(goldilocks_add(lo.c0,hi.c0),0x7fffffff80000001ULL),goldilocks_mul(goldilocks_add(lo.c1,hi.c1),0x7fffffff80000001ULL)}; - Ext2 odd=ext2_mul(ext2_sub(lo,hi),beta,ext_w);odd.c0=goldilocks_mul(odd.c0,powers[row]);odd.c1=goldilocks_mul(odd.c1,powers[row]);output[row]=ext2_add(even,odd); + const Ext lo=input[2*row],hi=input[2*row+1]; + const Ext even=Ops::scale(Ops::add(lo,hi),0x7fffffff80000001ULL); + const Ext odd=Ops::scale(Ops::mul(Ops::sub(lo,hi),beta,ext_w),powers[row]); + output[row]=Ops::add(even,odd); } } __global__ void init_fri_powers(uint64_t* powers,size_t height,uint64_t g_inv){ @@ -965,37 +1185,40 @@ __global__ void init_fri_powers(uint64_t* powers,size_t height,uint64_t g_inv){ powers[row]=goldilocks_mul(0x7fffffff80000001ULL,goldilocks_pow(g_inv,exponent)); } } -__global__ void add_scaled_ext2(Ext2* output,const Ext2* input,size_t count,Ext2 scale,uint64_t ext_w){ - for(size_t i=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;i(gridDim.x)*blockDim.x)output[i]=ext2_add(output[i],ext2_mul(scale,input[i],ext_w)); +template +__global__ void add_scaled_t(Ext* output,const Ext* input,size_t count,Ext scale,uint64_t ext_w){ + using Ops = ExtOps; + for(size_t i=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;i(gridDim.x)*blockDim.x) + output[i]=Ops::add(output[i],Ops::mul(scale,input[i],ext_w)); } -__device__ __forceinline__ Ext2 ext2_inverse(Ext2 value,uint64_t ext_w){ - const uint64_t norm=goldilocks_sub(goldilocks_mul(value.c0,value.c0),goldilocks_mul(ext_w,goldilocks_mul(value.c1,value.c1))); - const uint64_t inv=goldilocks_pow(norm,GOLDILOCKS_P-2); - return {goldilocks_mul(value.c0,inv),goldilocks_sub(0,goldilocks_mul(value.c1,inv))}; -} -__global__ void lookup_messages(Ext2* conjugates,uint64_t* norms,const uint64_t* args, +template +__global__ void lookup_messages_t(Ext* conjugates,uint64_t* norms,const uint64_t* args, const size_t* arg_offsets,size_t height,size_t num_lookups,size_t args_width, - Ext2 beta,Ext2 gamma,uint64_t ext_w){ + Ext beta,Ext gamma,uint64_t ext_w){ + using Ops = ExtOps; const size_t count=height*num_lookups; for(size_t index=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;index(gridDim.x)*blockDim.x){ - const size_t row=index/num_lookups,lookup=index%num_lookups;Ext2 fingerprint{0,0}; - for(size_t j=arg_offsets[lookup+1];j>arg_offsets[lookup];--j)fingerprint=ext2_add(ext2_mul(fingerprint,gamma,ext_w),{args[row*args_width+j-1],0}); - const Ext2 message=ext2_add(beta,fingerprint);conjugates[index]={message.c0,goldilocks_sub(0,message.c1)}; - norms[index]=goldilocks_sub(goldilocks_mul(message.c0,message.c0),goldilocks_mul(ext_w,goldilocks_mul(message.c1,message.c1))); + const size_t row=index/num_lookups,lookup=index%num_lookups;Ext fingerprint=Ops::zero(); + for(size_t j=arg_offsets[lookup+1];j>arg_offsets[lookup];--j) + fingerprint=Ops::add_base(Ops::mul(fingerprint,gamma,ext_w),args[row*args_width+j-1]); + const Ext message=Ops::add(beta,fingerprint); + Ops::adjugate_and_norm(message,ext_w,conjugates[index],norms[index]); } } // Evaluate the lookup-only prefix of a circuit DAG against the original // row-major witness retained by the stage-1 LDE. This avoids materializing // and uploading the much wider concrete LookupValues buffer. -__global__ void lookup_messages_graph( - Ext2* conjugates,uint64_t* norms,uint64_t* multiplicities, +template +__global__ void lookup_messages_graph_t( + Ext* conjugates,uint64_t* norms,uint64_t* multiplicities, const ConstraintNode* nodes,size_t node_count,size_t slot_count, const ConstraintLookup* lookups,size_t lookup_count,const uint32_t* lookup_args, const ResidentLde* preprocessed,const uint64_t* main_trace,size_t main_width, bool main_trace_is_chunk, - Ext2 beta,Ext2 gamma,uint64_t ext_w,size_t height,size_t row_start, + Ext beta,Ext gamma,uint64_t ext_w,size_t height,size_t row_start, size_t row_count,uint64_t* global_scratch){ + using Ops = ExtOps; extern __shared__ uint64_t shared_values[]; const size_t lane=threadIdx.x,tile=blockDim.x; uint64_t* values=global_scratch?global_scratch+static_cast(blockIdx.x)*slot_count*tile:shared_values; @@ -1022,26 +1245,27 @@ __global__ void lookup_messages_graph( case 9:v=a==0?0:GOLDILOCKS_P-canonicalize(a);break; }values[n.out*tile+lane]=v; while(next_lookup0;--k)fingerprint=ext2_add(ext2_mul(fingerprint,gamma,ext_w),{values[lookup_args[l.arg_start+k-1]*tile+lane],0}); - const Ext2 message=ext2_add(beta,fingerprint);const size_t index=local_row*lookup_count+l.output; - conjugates[index]={message.c0,goldilocks_sub(0,message.c1)}; - norms[index]=goldilocks_sub(goldilocks_mul(message.c0,message.c0),goldilocks_mul(ext_w,goldilocks_mul(message.c1,message.c1))); + const ConstraintLookup l=lookups[next_lookup++];Ext fingerprint=Ops::zero(); + for(size_t k=l.arg_count;k>0;--k) + fingerprint=Ops::add_base(Ops::mul(fingerprint,gamma,ext_w),values[lookup_args[l.arg_start+k-1]*tile+lane]); + const Ext message=Ops::add(beta,fingerprint);const size_t index=local_row*lookup_count+l.output; + Ops::adjugate_and_norm(message,ext_w,conjugates[index],norms[index]); multiplicities[index]=values[l.multiplicity*tile+lane]; } } } } -__global__ void lookup_group_deltas_batched(Ext2* output,const uint64_t* multiplicities, - const Ext2* conjugates,const uint64_t* norm_inverses, - size_t height,size_t num_lookups,size_t group_size,uint64_t ext_w){ +template +__global__ void lookup_group_deltas_batched_t(Ext* output,const uint64_t* multiplicities, + const Ext* conjugates,const uint64_t* norm_inverses, + size_t height,size_t num_lookups,size_t group_size){ + using Ops = ExtOps; const size_t slots=(num_lookups+group_size-1)/group_size,total=height*slots; for(size_t index=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;index(gridDim.x)*blockDim.x){ - const size_t row=index/slots,slot=index%slots,begin=slot*group_size,end=(begin+group_size(status); } -__global__ void denominator_norms(uint64_t* norms,const uint64_t* coset, - size_t count,Ext2 point,uint64_t ext_w){ +template +__global__ void denominator_norms_t(uint64_t* norms,const uint64_t* coset, + size_t count,Ext point,uint64_t ext_w){ + using Ops = ExtOps; for(size_t i=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;i(gridDim.x)*blockDim.x){ - const uint64_t real=goldilocks_sub(point.c0,coset[i]); - norms[i]=goldilocks_sub(goldilocks_mul(real,real), - goldilocks_mul(ext_w,goldilocks_mul(point.c1,point.c1))); + norms[i]=Ops::denom_norm(point,coset[i],ext_w); } } -__global__ void finish_inverse_denominators(Ext2* output,const uint64_t* inverses, - const uint64_t* coset,size_t count,Ext2 point){ +template +__global__ void finish_inverse_denominators_t(Ext* output,const uint64_t* inverses, + const uint64_t* coset,size_t count,Ext point){ + using Ops = ExtOps; for(size_t i=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;i(gridDim.x)*blockDim.x){ - const uint64_t inverse=inverses[i]; - output[i]={goldilocks_mul(goldilocks_sub(point.c0,coset[i]),inverse), - goldilocks_mul(goldilocks_sub(0,point.c1),inverse)}; + output[i]=Ops::denom_adjugate_scaled(point,coset[i],inverses[i]); } } -__global__ void lookup_group_deltas(Ext2* output,const uint64_t* multiplicities, - const uint64_t* args,const size_t* arg_offsets,size_t height,size_t num_lookups, - size_t args_width,size_t group_size,Ext2 beta,Ext2 gamma,uint64_t ext_w){ - const size_t slots=(num_lookups+group_size-1)/group_size,total=height*slots; - for(size_t index=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;index(gridDim.x)*blockDim.x){ - const size_t row=index/slots,slot=index%slots,begin=slot*group_size,end=(begin+group_sizearg_offsets[lookup];--j)fingerprint=ext2_add(ext2_mul(fingerprint,gamma,ext_w),{args[row*args_width+j-1],0}); - const Ext2 inverse=ext2_inverse(ext2_add(beta,fingerprint),ext_w);const uint64_t multiplicity=multiplicities[row*num_lookups+lookup]; - delta.c0=goldilocks_add(delta.c0,goldilocks_mul(multiplicity,inverse.c0));delta.c1=goldilocks_add(delta.c1,goldilocks_mul(multiplicity,inverse.c1)); - }output[index]=delta; +__global__ void ext3_ops_kernel(Ext3* sums, Ext3* differences, Ext3* products, + Ext3* inverses, const Ext3* left, + const Ext3* right, size_t len) { + const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; + for (size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + index < len; index += grid_stride) { + const Ext3 a = left[index]; + const Ext3 b = right[index]; + sums[index] = ext3_add(a, b); + differences[index] = ext3_sub(a, b); + products[index] = ext3_mul(a, b); + inverses[index] = ext3_inverse(a); } } __global__ void reverse_u64(uint64_t* output,const uint64_t* input,size_t count){const size_t i=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;if(i(blockIdx.x)*blockDim.x+threadIdx.x; - const Ext2 own=index=stride)prior=scan_values[threadIdx.x-stride];__syncthreads();if(threadIdx.x>=stride)scan_values[threadIdx.x]=ext2_add(scan_values[threadIdx.x],prior);__syncthreads();} - if(index(blockIdx.x)*blockDim.x+threadIdx.x;if(index(&sums),blocks*sizeof(Ext2)); - if(status==cudaSuccess){scan_ext2_blocks<<(blocks),THREADS,THREADS*sizeof(Ext2)>>>(output,sums,input,count);status=cudaGetLastError();} - if(status==cudaSuccess&&blocks>1)status=cudaMalloc(reinterpret_cast(&offsets),blocks*sizeof(Ext2)); - if(status==cudaSuccess&&blocks>1)status=exclusive_scan_ext2(offsets,sums,blocks); - if(status==cudaSuccess&&blocks>1){add_scan_block_offsets<<(blocks),THREADS>>>(output,offsets,count);status=cudaGetLastError();} +template +__global__ void scan_ext_blocks_t(Ext* output,Ext* sums,const Ext* input,size_t count){ + using Ops = ExtOps; + extern __shared__ uint64_t shared_raw[]; + Ext* scan_values = reinterpret_cast(shared_raw); + const size_t index=static_cast(blockIdx.x)*blockDim.x+threadIdx.x; + const Ext own=index=stride)prior=scan_values[threadIdx.x-stride]; + __syncthreads(); + if(threadIdx.x>=stride)scan_values[threadIdx.x]=Ops::add(scan_values[threadIdx.x],prior); + __syncthreads(); + } + if(index +__global__ void add_scan_block_offsets_t(Ext* values,const Ext* offsets,size_t count){ + using Ops = ExtOps; + const size_t index=static_cast(blockIdx.x)*blockDim.x+threadIdx.x; + if(index +cudaError_t exclusive_scan_ext_t(Ext* output,const Ext* input,size_t count){ + const size_t blocks=(count+THREADS-1)/THREADS;Ext* sums=nullptr;Ext* offsets=nullptr; + cudaError_t status=cudaMalloc(reinterpret_cast(&sums),blocks*sizeof(Ext)); + if(status==cudaSuccess){scan_ext_blocks_t<<(blocks),THREADS,THREADS*sizeof(Ext)>>>(output,sums,input,count);status=cudaGetLastError();} + if(status==cudaSuccess&&blocks>1)status=cudaMalloc(reinterpret_cast(&offsets),blocks*sizeof(Ext)); + if(status==cudaSuccess&&blocks>1)status=exclusive_scan_ext_t(offsets,sums,blocks); + if(status==cudaSuccess&&blocks>1){add_scan_block_offsets_t<<(blocks),THREADS>>>(output,offsets,count);status=cudaGetLastError();} cudaFree(offsets);cudaFree(sums);return status; } __global__ void scan_mul_blocks(uint64_t* output,uint64_t* sums,const uint64_t* input,size_t count){ @@ -1343,7 +1584,8 @@ static void* pack_quotient_rows(void* opaque) { return nullptr; } -__global__ void evaluate_quotient( +template +__global__ void evaluate_quotient_t( uint64_t* output, const ConstraintNode* nodes, size_t node_count, size_t slot_count, const uint32_t* roots, size_t root_count, const ConstraintLookup* lookups, size_t lookup_count, const uint32_t* lookup_args, size_t group_size, @@ -1353,6 +1595,7 @@ __global__ void evaluate_quotient( uint64_t ext_w, size_t quotient_size, size_t next_step, uint64_t* global_scratch, size_t work_start, size_t work_count, bool storage_order) { + using Ops = ExtOps; extern __shared__ uint64_t shared_values[]; const size_t lane = threadIdx.x, tile = blockDim.x; uint64_t* values=global_scratch ? global_scratch+static_cast(blockIdx.x)*slot_count*tile : shared_values; @@ -1386,49 +1629,57 @@ __global__ void evaluate_quotient( } values[n.out * tile + lane] = v; } - const size_t total_constraints = root_count + - (lookup_count == 0 ? 2 : ((lookup_count + group_size - 1) / group_size) * 2); - Ext2 acc{0,0}; size_t ci = 0; + const size_t groups = lookup_count == 0 ? 1 : (lookup_count + group_size - 1) / group_size; + const size_t total_constraints = root_count + groups * Ops::D; + Ext acc = Ops::zero(); + size_t ci = 0; for (; ci < root_count; ++ci) { const uint64_t c = values[roots[ci] * tile + lane]; - acc.c0 = goldilocks_add(acc.c0, goldilocks_mul(c, alpha[ci])); - acc.c1 = goldilocks_add(acc.c1, goldilocks_mul(c, alpha[total_constraints + ci])); + Ops::accumulate_base_root(acc, c, alpha, total_constraints, ci); } - const Ext2 beta{publics[0], publics[1]}, gamma{publics[2], publics[3]}; - const Ext2 injection{goldilocks_mul(selectors[quotient_size + row], delta[0]), - goldilocks_mul(selectors[quotient_size + row], delta[1])}; - const size_t groups = lookup_count == 0 ? 1 : (lookup_count + group_size - 1) / group_size; + const Ext beta = Ops::load(publics); + const Ext gamma = Ops::load(publics + Ops::D); + const Ext injection = Ops::scale(Ops::load(delta), selectors[quotient_size + row]); for (size_t g = 0; g < groups; ++g) { - Ext2 constraints[8]; size_t count = 0; + Ext c = Ops::zero(); if (lookup_count == 0) { const size_t s2_next = stage2.staged ? 2 * work_row + 1 : nr; const size_t s2_cur = stage2.staged ? 2 * work_row : sr; - constraints[count++] = ext2_add(ext2_sub( - {stage2.values[s2_next * stage2.width], stage2.values[s2_next * stage2.width + 1]}, - {stage2.values[s2_cur * stage2.width], stage2.values[s2_cur * stage2.width + 1]}), injection); + c = Ops::add(Ops::sub( + Ops::load(stage2.values + s2_next * stage2.width), + Ops::load(stage2.values + s2_cur * stage2.width)), injection); } else { const size_t begin = g * group_size; const size_t end = begin + group_size < lookup_count ? begin + group_size : lookup_count; - Ext2 product{1,0}, messages[8]; - for (size_t j=begin;j0;--k) { f=ext2_mul(f,gamma,ext_w); f.c0=goldilocks_add(f.c0,values[lookup_args[l.arg_start+k-1]*tile+lane]); } - messages[j-begin]=ext2_add(f,beta); product=ext2_mul(product,messages[j-begin],ext_w); } + Ext product = Ops::one(), messages[8]; + for (size_t j=begin;j0;--k) { + f = Ops::add_base(Ops::mul(f,gamma,ext_w), values[lookup_args[l.arg_start+k-1]*tile+lane]); + } + messages[j-begin] = Ops::add(f,beta); + product = Ops::mul(product,messages[j-begin],ext_w); + } const size_t s2_cur = stage2.staged ? 2 * work_row : sr; const size_t s2_next = stage2.staged ? 2 * work_row + 1 : nr; - const Ext2 source{stage2.values[s2_cur*stage2.width+2*g],stage2.values[s2_cur*stage2.width+2*g+1]}; - Ext2 target = g+1 +cudaError_t configure_quotient_shared_memory_t(int device_id, size_t bytes) { static volatile int lock = 0; static size_t configured[64] = {}; if (device_id < 0 || device_id >= 64) return cudaErrorInvalidDevice; @@ -1451,7 +1703,7 @@ cudaError_t configure_quotient_shared_memory(int device_id, size_t bytes) { cudaError_t status = cudaSuccess; if (configured[device_id] < bytes) { status = cudaFuncSetAttribute( - evaluate_quotient, cudaFuncAttributeMaxDynamicSharedMemorySize, + evaluate_quotient_t, cudaFuncAttributeMaxDynamicSharedMemorySize, static_cast(bytes)); if (status == cudaSuccess) configured[device_id] = bytes; } @@ -1565,13 +1817,14 @@ __global__ void goldilocks_ops_kernel(uint64_t* sums, uint64_t* differences, __global__ void blake3_hash_short_rows_kernel(uint8_t* digests, const uint8_t* messages, size_t message_bytes, - size_t message_count) { + size_t message_count, + bool domain_v6) { const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; for (size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; index < message_count; index += grid_stride) { uint32_t output[8]; blake3_chunk(messages + index * message_bytes, message_bytes, 0, true, - output); + output, domain_v6); uint8_t* digest = digests + index * 32; #pragma unroll for (unsigned int word = 0; word < 8; ++word) { @@ -1591,7 +1844,8 @@ __global__ void blake3_hash_short_rows_kernel(uint8_t* digests, __global__ void blake3_hash_rows_kernel(uint8_t* digests, const uint8_t* messages, size_t message_bytes, - size_t message_count) { + size_t message_count, + bool domain_v6) { __shared__ uint32_t chunk_values[THREADS / 32][32][8]; const unsigned int lane = threadIdx.x & 31U; const unsigned int warp_in_block = threadIdx.x >> 5; @@ -1614,7 +1868,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, : 0; uint32_t chunk_output[8]; blake3_chunk(message + chunk_offset, chunk_length, lane, - chunks == 1, chunk_output); + chunks == 1, chunk_output, domain_v6); #pragma unroll for (unsigned int word = 0; word < 8; ++word) { chunk_values[warp_in_block][lane][word] = chunk_output[word]; @@ -1631,7 +1885,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, uint32_t parent[8]; blake3_parent(chunk_values[warp_in_block][index], chunk_values[warp_in_block][index + 1], - root_level, parent); + root_level, parent, domain_v6); #pragma unroll for (unsigned int word = 0; word < 8; ++word) { chunk_values[warp_in_block][next_count][word] = parent[word]; @@ -1665,7 +1919,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, __global__ void blake3_hash_digest_pairs_kernel( uint8_t* digests, const uint8_t* left, const uint8_t* right, - size_t count, bool interleaved) { + size_t count, bool interleaved, bool domain_v6) { const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; for (size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; @@ -1675,16 +1929,17 @@ __global__ void blake3_hash_digest_pairs_kernel( const uint8_t* right_digest = right + (interleaved ? 2 * index + 1 : index) * 32; blake3_hash_digest_pair(left_digest, right_digest, - digests + index * 32); + digests + index * 32, domain_v6); } } cudaError_t launch_blake3_rows(uint8_t* digests, const uint8_t* messages, - size_t message_bytes, size_t message_count) { + size_t message_bytes, size_t message_count, + bool domain_v6 = false) { if (message_bytes <= BLAKE3_CHUNK_BYTES) { blake3_hash_short_rows_kernel<<>>( - digests, messages, message_bytes, message_count); + digests, messages, message_bytes, message_count, domain_v6); return cudaGetLastError(); } constexpr unsigned int WARPS_PER_BLOCK = THREADS / 32; @@ -1693,17 +1948,18 @@ cudaError_t launch_blake3_rows(uint8_t* digests, const uint8_t* messages, const unsigned int blocks = static_cast( required < MAX_BLOCKS ? required : MAX_BLOCKS); blake3_hash_rows_kernel<<>>( - digests, messages, message_bytes, message_count); + digests, messages, message_bytes, message_count, domain_v6); return cudaGetLastError(); } cudaError_t launch_blake3_digest_pairs(uint8_t* digests, const uint8_t* left, const uint8_t* right, size_t count, - bool interleaved) { + bool interleaved, + bool domain_v6 = false) { blake3_hash_digest_pairs_kernel<<>>( - digests, left, right, count, interleaved); + digests, left, right, count, interleaved, domain_v6); return cudaGetLastError(); } @@ -1722,7 +1978,8 @@ __global__ void gather_resident_lde_group( cudaError_t hash_resident_lde_group(uint8_t* digests, const void* const* handles, - size_t handle_count, size_t height) { + size_t handle_count, size_t height, + bool domain_v6 = false) { size_t total_width = 0; for (size_t index = 0; index < handle_count; ++index) { const ResidentLde* lde = static_cast(handles[index]); @@ -1801,7 +2058,7 @@ cudaError_t hash_resident_lde_group(uint8_t* digests, status = launch_blake3_rows( digests + row_start * 32, reinterpret_cast(combined_rows.get()), row_bytes, - rows); + rows, domain_v6); } } return status; @@ -1810,7 +2067,8 @@ cudaError_t hash_resident_lde_group(uint8_t* digests, cudaError_t hash_partitioned_lde_group( uint8_t* digests, const void* const* handles, const uint64_t* const* host_values, const size_t* widths, - const size_t* heights, size_t matrix_count, size_t height) { + const size_t* heights, size_t matrix_count, size_t height, + bool domain_v6 = false) { bool has_host = false; bool has_resident = false; size_t total_width = 0; @@ -1826,7 +2084,8 @@ cudaError_t hash_partitioned_lde_group( has_resident = has_resident || handles[index] != nullptr; } if (!has_host) { - return hash_resident_lde_group(digests, handles, matrix_count, height); + return hash_resident_lde_group(digests, handles, matrix_count, height, + domain_v6); } if (!has_resident || total_width == 0 || total_width > (32 * 1024) / sizeof(uint64_t) || @@ -1921,7 +2180,7 @@ cudaError_t hash_partitioned_lde_group( status = launch_blake3_rows( digests + row_start * 32, reinterpret_cast(combined_rows.get()), row_bytes, - rows); + rows, domain_v6); } } if (status == cudaSuccess) { @@ -2417,7 +2676,9 @@ extern "C" int multi_stark_cuda_constraint_graph( return static_cast(status); } -extern "C" int multi_stark_cuda_quotient_values( +namespace { +template +int quotient_values_impl( int device_id, uint64_t* output, const void* nodes, size_t node_count, size_t slot_count, const uint32_t* roots, size_t root_count, const void* lookups, @@ -2429,6 +2690,7 @@ extern "C" int multi_stark_cuda_quotient_values( const uint64_t* alpha, size_t constraint_count, const uint64_t* delta, uint64_t ext_w, size_t quotient_size, size_t next_step) { + constexpr size_t D = ExtOps::D; if (output == nullptr || nodes == nullptr || roots == nullptr || main_handle == nullptr || stage2_handle == nullptr || publics == nullptr || alpha == nullptr || delta == nullptr || @@ -2444,14 +2706,14 @@ extern "C" int multi_stark_cuda_quotient_values( const size_t on=reserve(node_count*sizeof(ConstraintNode)), oroot=reserve(root_count*sizeof(uint32_t)); const size_t ol=reserve(lookup_count*sizeof(ConstraintLookup)), oa=reserve(lookup_arg_count*sizeof(uint32_t)); const size_t op=reserve(public_count*sizeof(uint64_t)), os=reserve(4*quotient_size*sizeof(uint64_t)); - const size_t oalpha=reserve(2*constraint_count*sizeof(uint64_t)), od=reserve(2*sizeof(uint64_t)); - const size_t oo=reserve(2*quotient_size*sizeof(uint64_t)); uint8_t* allocation=nullptr; + const size_t oalpha=reserve(D*constraint_count*sizeof(uint64_t)), od=reserve(D*sizeof(uint64_t)); + const size_t oo=reserve(D*quotient_size*sizeof(uint64_t)); uint8_t* allocation=nullptr; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&allocation),bytes); auto cp=[&](size_t at,const void* src,size_t n){if(status==cudaSuccess&&n!=0)status=cudaMemcpy(allocation+at,src,n,cudaMemcpyHostToDevice);}; cp(on,nodes,node_count*sizeof(ConstraintNode));cp(oroot,roots,root_count*sizeof(uint32_t)); cp(ol,lookups,lookup_count*sizeof(ConstraintLookup));cp(oa,lookup_args,lookup_arg_count*sizeof(uint32_t)); cp(op,publics,public_count*sizeof(uint64_t)); - cp(oalpha,alpha,2*constraint_count*sizeof(uint64_t));cp(od,delta,2*sizeof(uint64_t)); + cp(oalpha,alpha,D*constraint_count*sizeof(uint64_t));cp(od,delta,D*sizeof(uint64_t)); auto* dn=reinterpret_cast(allocation+on);auto* dr=reinterpret_cast(allocation+oroot); auto* dl=reinterpret_cast(allocation+ol);auto* da=reinterpret_cast(allocation+oa); auto* dp=reinterpret_cast(allocation+op);auto* ds=reinterpret_cast(allocation+os); @@ -2465,12 +2727,12 @@ extern "C" int multi_stark_cuda_quotient_values( uint64_t* scratch=nullptr;if(status==cudaSuccess&&global)status=cudaMalloc(reinterpret_cast(&scratch),blocks*slot_count*tile*sizeof(uint64_t)); const size_t dynamic_shared=global?0:slot_count*tile*sizeof(uint64_t); if(status==cudaSuccess&&dynamic_shared>48*1024) - status=configure_quotient_shared_memory(device_id,dynamic_shared); + status=configure_quotient_shared_memory_t(device_id,dynamic_shared); if(status==cudaSuccess) { const auto* prep = static_cast(preprocessed_handle); const auto* main = static_cast(main_handle); const auto* stage2 = static_cast(stage2_handle); - evaluate_quotient<<(blocks),static_cast(tile),dynamic_shared>>>( + evaluate_quotient_t<<(blocks),static_cast(tile),dynamic_shared>>>( dout,dn,node_count,slot_count,dr,root_count,dl,lookup_count,da,group_size, {prep ? prep->values : nullptr, prep ? prep->width : 0, false, false}, {main->values, main->width, false, false}, @@ -2478,13 +2740,14 @@ extern "C" int multi_stark_cuda_quotient_values( dp,ds,dal,dd,ext_w,quotient_size,next_step,scratch,0,quotient_size,false); status=cudaGetLastError(); } - if(status==cudaSuccess) status=cudaMemcpy(output,dout,2*quotient_size*sizeof(uint64_t),cudaMemcpyDeviceToHost); + if(status==cudaSuccess) status=cudaMemcpy(output,dout,D*quotient_size*sizeof(uint64_t),cudaMemcpyDeviceToHost); cudaFree(scratch); cudaFree(allocation); return static_cast(status); } -extern "C" int multi_stark_cuda_quotient_lde( +template +int quotient_lde_impl( int device_id, void** output_handle, const void* nodes, size_t node_count, size_t slot_count, const uint32_t* roots, size_t root_count, const void* lookups, size_t lookup_count, const uint32_t* lookup_args, @@ -2497,6 +2760,7 @@ extern "C" int multi_stark_cuda_quotient_lde( size_t quotient_size, size_t next_step, size_t quotient_degree, size_t log_blowup, const MultiStarkNttPlan* quotient_plan, const MultiStarkNttPlan* lde_plan, const uint64_t* slice_weights) { + constexpr size_t D = ExtOps::D; if (output_handle == nullptr || nodes == nullptr || roots == nullptr || main_handle == nullptr || stage2_handle == nullptr || publics == nullptr || alpha == nullptr || delta == nullptr || @@ -2515,7 +2779,7 @@ extern "C" int multi_stark_cuda_quotient_lde( return static_cast(cudaErrorInvalidValue); } const size_t lde_height = trace_height << log_blowup; - const size_t width = 2 * quotient_degree; + const size_t width = D * quotient_degree; if (!product_fits(lde_height, width)) { return static_cast(cudaErrorInvalidValue); } @@ -2526,14 +2790,14 @@ extern "C" int multi_stark_cuda_quotient_lde( const size_t on=reserve(node_count*sizeof(ConstraintNode)), oroot=reserve(root_count*sizeof(uint32_t)); const size_t ol=reserve(lookup_count*sizeof(ConstraintLookup)), oa=reserve(lookup_arg_count*sizeof(uint32_t)); const size_t op=reserve(public_count*sizeof(uint64_t)), os=reserve(4*quotient_size*sizeof(uint64_t)); - const size_t oalpha=reserve(2*constraint_count*sizeof(uint64_t)), od=reserve(2*sizeof(uint64_t)); - const size_t oo=reserve(2*quotient_size*sizeof(uint64_t)); uint8_t* allocation=nullptr; + const size_t oalpha=reserve(D*constraint_count*sizeof(uint64_t)), od=reserve(D*sizeof(uint64_t)); + const size_t oo=reserve(D*quotient_size*sizeof(uint64_t)); uint8_t* allocation=nullptr; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&allocation),bytes); auto cp=[&](size_t at,const void* src,size_t n){if(status==cudaSuccess&&n!=0)status=cudaMemcpy(allocation+at,src,n,cudaMemcpyHostToDevice);}; cp(on,nodes,node_count*sizeof(ConstraintNode));cp(oroot,roots,root_count*sizeof(uint32_t)); cp(ol,lookups,lookup_count*sizeof(ConstraintLookup));cp(oa,lookup_args,lookup_arg_count*sizeof(uint32_t)); cp(op,publics,public_count*sizeof(uint64_t)); - cp(oalpha,alpha,2*constraint_count*sizeof(uint64_t));cp(od,delta,2*sizeof(uint64_t)); + cp(oalpha,alpha,D*constraint_count*sizeof(uint64_t));cp(od,delta,D*sizeof(uint64_t)); auto* dn=reinterpret_cast(allocation+on);auto* dr=reinterpret_cast(allocation+oroot); auto* dl=reinterpret_cast(allocation+ol);auto* da=reinterpret_cast(allocation+oa); auto* dp=reinterpret_cast(allocation+op);auto* ds=reinterpret_cast(allocation+os); @@ -2552,12 +2816,12 @@ extern "C" int multi_stark_cuda_quotient_lde( uint64_t* scratch=nullptr;if(status==cudaSuccess&&global)status=cudaMalloc(reinterpret_cast(&scratch),blocks*slot_count*tile*sizeof(uint64_t)); const size_t dynamic_shared=global?0:slot_count*tile*sizeof(uint64_t); if(status==cudaSuccess&&dynamic_shared>48*1024) - status=configure_quotient_shared_memory(device_id,dynamic_shared); + status=configure_quotient_shared_memory_t(device_id,dynamic_shared); if(status==cudaSuccess) { const auto* prep = static_cast(preprocessed_handle); const auto* main = static_cast(main_handle); const auto* stage2 = static_cast(stage2_handle); - evaluate_quotient<<(blocks),static_cast(tile),dynamic_shared>>>( + evaluate_quotient_t<<(blocks),static_cast(tile),dynamic_shared>>>( quotient,dn,node_count,slot_count,dr,root_count,dl,lookup_count,da,group_size, {prep ? prep->values : nullptr, prep ? prep->width : 0, false, false}, {main->values, main->width, false, false}, @@ -2565,7 +2829,7 @@ extern "C" int multi_stark_cuda_quotient_lde( dp,ds,dal,dd,ext_w,quotient_size,next_step,scratch,0,quotient_size,false); status=cudaGetLastError(); } - if(status==cudaSuccess)status=forward_in_place(device_id, quotient,quotient_size,2,quotient_plan); + if(status==cudaSuccess)status=forward_in_place(device_id, quotient,quotient_size,D,quotient_plan); ResidentLde* lde = nullptr; if(status==cudaSuccess) { @@ -2579,7 +2843,7 @@ extern "C" int multi_stark_cuda_quotient_lde( if(status==cudaSuccess) { gather_shifted_quotient_slices<<>>( lde->values,quotient,device_weights,quotient_size,trace_height, - quotient_degree,2); + quotient_degree,D); status=cudaGetLastError(); } if(status==cudaSuccess)status=forward_in_place(device_id, lde->values,lde_height,width,lde_plan); @@ -2593,13 +2857,8 @@ extern "C" int multi_stark_cuda_quotient_lde( return static_cast(status); } -// Evaluate a quotient when one or more committed LDEs have been spilled to -// host memory. The quotient rows are independent until the DFT, so bounded -// pairs of current/next trace rows are staged through two buffers while the -// previous buffer executes. Iterating in bit-reversed storage order keeps the -// current-row read contiguous; host workers gather the corresponding next -// rows in parallel. Resident inputs remain in place. -extern "C" int multi_stark_cuda_quotient_lde_mixed( +template +int quotient_lde_mixed_impl( int device_id, void** output_handle, const void* nodes, size_t node_count, size_t slot_count, const uint32_t* roots, size_t root_count, const void* lookups, size_t lookup_count, const uint32_t* lookup_args, @@ -2617,6 +2876,7 @@ extern "C" int multi_stark_cuda_quotient_lde_mixed( size_t quotient_size, size_t next_step, size_t quotient_degree, size_t log_blowup, const MultiStarkNttPlan* quotient_plan, const MultiStarkNttPlan* lde_plan, const uint64_t* slice_weights) { + constexpr size_t D = ExtOps::D; const auto one_source = [](const void* handle, const uint64_t* host) { return (handle != nullptr) != (host != nullptr); }; @@ -2642,7 +2902,7 @@ extern "C" int multi_stark_cuda_quotient_lde_mixed( return static_cast(cudaErrorInvalidValue); } const size_t lde_height = trace_height << log_blowup; - const size_t width = 2 * quotient_degree; + const size_t width = D * quotient_degree; if (!product_fits(lde_height, width)) { return static_cast(cudaErrorInvalidValue); } @@ -2653,14 +2913,14 @@ extern "C" int multi_stark_cuda_quotient_lde_mixed( const size_t on=reserve(node_count*sizeof(ConstraintNode)), oroot=reserve(root_count*sizeof(uint32_t)); const size_t ol=reserve(lookup_count*sizeof(ConstraintLookup)), oa=reserve(lookup_arg_count*sizeof(uint32_t)); const size_t op=reserve(public_count*sizeof(uint64_t)), os=reserve(4*quotient_size*sizeof(uint64_t)); - const size_t oalpha=reserve(2*constraint_count*sizeof(uint64_t)), od=reserve(2*sizeof(uint64_t)); - const size_t oo=reserve(2*quotient_size*sizeof(uint64_t)); uint8_t* allocation=nullptr; + const size_t oalpha=reserve(D*constraint_count*sizeof(uint64_t)), od=reserve(D*sizeof(uint64_t)); + const size_t oo=reserve(D*quotient_size*sizeof(uint64_t)); uint8_t* allocation=nullptr; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&allocation),bytes); auto cp=[&](size_t at,const void* src,size_t n){if(status==cudaSuccess&&n!=0)status=cudaMemcpy(allocation+at,src,n,cudaMemcpyHostToDevice);}; cp(on,nodes,node_count*sizeof(ConstraintNode));cp(oroot,roots,root_count*sizeof(uint32_t)); cp(ol,lookups,lookup_count*sizeof(ConstraintLookup));cp(oa,lookup_args,lookup_arg_count*sizeof(uint32_t)); cp(op,publics,public_count*sizeof(uint64_t)); - cp(oalpha,alpha,2*constraint_count*sizeof(uint64_t));cp(od,delta,2*sizeof(uint64_t)); + cp(oalpha,alpha,D*constraint_count*sizeof(uint64_t));cp(od,delta,D*sizeof(uint64_t)); auto* dn=reinterpret_cast(allocation+on);auto* dr=reinterpret_cast(allocation+oroot); auto* dl=reinterpret_cast(allocation+ol);auto* da=reinterpret_cast(allocation+oa); auto* dp=reinterpret_cast(allocation+op);auto* ds=reinterpret_cast(allocation+os); @@ -2735,10 +2995,8 @@ extern "C" int multi_stark_cuda_quotient_lde_mixed( } const size_t dynamic_shared=global?0:slot_count*tile*sizeof(uint64_t); if(status==cudaSuccess&&dynamic_shared>48*1024) - status=configure_quotient_shared_memory(device_id,dynamic_shared); + status=configure_quotient_shared_memory_t(device_id,dynamic_shared); - // The chunk streams are nonblocking and do not inherit the per-thread - // stream's metadata uploads, async allocation, or selector generation. cudaEvent_t inputs_ready=nullptr; if(status==cudaSuccess)status=cudaEventCreateWithFlags(&inputs_ready,cudaEventDisableTiming); if(status==cudaSuccess)status=cudaEventRecord(inputs_ready,cudaStreamPerThread); @@ -2791,27 +3049,25 @@ extern "C" int multi_stark_cuda_quotient_lde_mixed( const QuotientMatrix main=staged_source(main_host,main_width,main_resident); const QuotientMatrix stage2=staged_source(stage2_host,stage2_width,stage2_resident); size_t blocks=(count+tile-1)/tile;if(blocks>block_cap)blocks=block_cap; - evaluate_quotient<<(blocks),static_cast(tile),dynamic_shared,streams[buffer]>>>( + evaluate_quotient_t<<(blocks),static_cast(tile),dynamic_shared,streams[buffer]>>>( quotient,dn,node_count,slot_count,dr,root_count,dl,lookup_count,da,group_size, prep,main,stage2,dp,ds,dal,dd,ext_w,quotient_size,next_step,scratch[buffer], storage_start,count,true); status=cudaGetLastError();stream_busy[buffer]=status==cudaSuccess; } - // Drain both consumers even when one launch failed before recycling the - // shared metadata and their staging buffers on the producer stream. for(size_t i=0;i<2;++i)if(streams[i]){ const cudaError_t synced=cudaStreamSynchronize(streams[i]); if(status==cudaSuccess)status=synced; } - if(status==cudaSuccess)status=forward_in_place(device_id, quotient,quotient_size,2,quotient_plan); + if(status==cudaSuccess)status=forward_in_place(device_id, quotient,quotient_size,D,quotient_plan); ResidentLde* lde=nullptr; if(status==cudaSuccess)status=create_resident_lde(&lde); if(status==cudaSuccess){lde->height=lde_height;lde->width=width;status=cudaMalloc(reinterpret_cast(&lde->values),lde_height*width*sizeof(uint64_t));} if(status==cudaSuccess)status=cudaMemset(lde->values,0,lde_height*width*sizeof(uint64_t)); if(status==cudaSuccess){ gather_shifted_quotient_slices<<>>( - lde->values,quotient,device_weights,quotient_size,trace_height,quotient_degree,2); + lde->values,quotient,device_weights,quotient_size,trace_height,quotient_degree,D); status=cudaGetLastError(); } if(status==cudaSuccess)status=forward_in_place(device_id, lde->values,lde_height,width,lde_plan); @@ -2826,23 +3082,175 @@ extern "C" int multi_stark_cuda_quotient_lde_mixed( cudaFree(allocation); return static_cast(status); } +} // namespace -extern "C" int multi_stark_cuda_lde_interpolate(int device_id,uint64_t* output,const void* handle, +extern "C" int multi_stark_cuda_quotient_values( + int device_id, uint64_t* output, const void* nodes, size_t node_count, + size_t slot_count, + const uint32_t* roots, size_t root_count, const void* lookups, + size_t lookup_count, const uint32_t* lookup_args, size_t lookup_arg_count, + size_t group_size, const void* preprocessed_handle, const void* main_handle, + const void* stage2_handle, const uint64_t* publics, size_t public_count, + uint64_t coset_shift, uint64_t coset_generator, uint64_t trace_last, + uint64_t vanishing_start, uint64_t vanishing_step, + const uint64_t* alpha, size_t constraint_count, + const uint64_t* delta, uint64_t ext_w, size_t quotient_size, + size_t next_step) { + return quotient_values_impl( + device_id, output, nodes, node_count, slot_count, roots, root_count, + lookups, lookup_count, lookup_args, lookup_arg_count, group_size, + preprocessed_handle, main_handle, stage2_handle, publics, public_count, + coset_shift, coset_generator, trace_last, vanishing_start, + vanishing_step, alpha, constraint_count, delta, ext_w, quotient_size, + next_step); +} + +extern "C" int multi_stark_cuda_quotient_values_ext3( + int device_id, uint64_t* output, const void* nodes, size_t node_count, + size_t slot_count, + const uint32_t* roots, size_t root_count, const void* lookups, + size_t lookup_count, const uint32_t* lookup_args, size_t lookup_arg_count, + size_t group_size, const void* preprocessed_handle, const void* main_handle, + const void* stage2_handle, const uint64_t* publics, size_t public_count, + uint64_t coset_shift, uint64_t coset_generator, uint64_t trace_last, + uint64_t vanishing_start, uint64_t vanishing_step, + const uint64_t* alpha, size_t constraint_count, + const uint64_t* delta, size_t quotient_size, size_t next_step) { + return quotient_values_impl( + device_id, output, nodes, node_count, slot_count, roots, root_count, + lookups, lookup_count, lookup_args, lookup_arg_count, group_size, + preprocessed_handle, main_handle, stage2_handle, publics, public_count, + coset_shift, coset_generator, trace_last, vanishing_start, + vanishing_step, alpha, constraint_count, delta, 0, quotient_size, + next_step); +} + +extern "C" int multi_stark_cuda_quotient_lde( + int device_id, void** output_handle, const void* nodes, size_t node_count, + size_t slot_count, const uint32_t* roots, size_t root_count, + const void* lookups, size_t lookup_count, const uint32_t* lookup_args, + size_t lookup_arg_count, size_t group_size, const void* preprocessed_handle, + const void* main_handle, const void* stage2_handle, const uint64_t* publics, + size_t public_count, uint64_t coset_shift, uint64_t coset_generator, + uint64_t trace_last, uint64_t vanishing_start, uint64_t vanishing_step, + const uint64_t* alpha, + size_t constraint_count, const uint64_t* delta, uint64_t ext_w, + size_t quotient_size, size_t next_step, size_t quotient_degree, + size_t log_blowup, const MultiStarkNttPlan* quotient_plan, + const MultiStarkNttPlan* lde_plan, const uint64_t* slice_weights) { + return quotient_lde_impl( + device_id, output_handle, nodes, node_count, slot_count, roots, + root_count, lookups, lookup_count, lookup_args, lookup_arg_count, + group_size, preprocessed_handle, main_handle, stage2_handle, publics, + public_count, coset_shift, coset_generator, trace_last, vanishing_start, + vanishing_step, alpha, constraint_count, delta, ext_w, quotient_size, + next_step, quotient_degree, log_blowup, quotient_plan, lde_plan, + slice_weights); +} + +extern "C" int multi_stark_cuda_quotient_lde_ext3( + int device_id, void** output_handle, const void* nodes, size_t node_count, + size_t slot_count, const uint32_t* roots, size_t root_count, + const void* lookups, size_t lookup_count, const uint32_t* lookup_args, + size_t lookup_arg_count, size_t group_size, const void* preprocessed_handle, + const void* main_handle, const void* stage2_handle, const uint64_t* publics, + size_t public_count, uint64_t coset_shift, uint64_t coset_generator, + uint64_t trace_last, uint64_t vanishing_start, uint64_t vanishing_step, + const uint64_t* alpha, + size_t constraint_count, const uint64_t* delta, + size_t quotient_size, size_t next_step, size_t quotient_degree, + size_t log_blowup, const MultiStarkNttPlan* quotient_plan, + const MultiStarkNttPlan* lde_plan, const uint64_t* slice_weights) { + return quotient_lde_impl( + device_id, output_handle, nodes, node_count, slot_count, roots, + root_count, lookups, lookup_count, lookup_args, lookup_arg_count, + group_size, preprocessed_handle, main_handle, stage2_handle, publics, + public_count, coset_shift, coset_generator, trace_last, vanishing_start, + vanishing_step, alpha, constraint_count, delta, 0, quotient_size, + next_step, quotient_degree, log_blowup, quotient_plan, lde_plan, + slice_weights); +} + +extern "C" int multi_stark_cuda_quotient_lde_mixed( + int device_id, void** output_handle, const void* nodes, size_t node_count, + size_t slot_count, const uint32_t* roots, size_t root_count, + const void* lookups, size_t lookup_count, const uint32_t* lookup_args, + size_t lookup_arg_count, size_t group_size, + const void* preprocessed_handle, const uint64_t* preprocessed_host, + size_t preprocessed_height, size_t preprocessed_width, + const void* main_handle, const uint64_t* main_host, + size_t main_height, size_t main_width, + const void* stage2_handle, const uint64_t* stage2_host, + size_t stage2_height, size_t stage2_width, + const uint64_t* publics, size_t public_count, + uint64_t coset_shift, uint64_t coset_generator, uint64_t trace_last, + uint64_t vanishing_start, uint64_t vanishing_step, const uint64_t* alpha, + size_t constraint_count, const uint64_t* delta, uint64_t ext_w, + size_t quotient_size, size_t next_step, size_t quotient_degree, + size_t log_blowup, const MultiStarkNttPlan* quotient_plan, + const MultiStarkNttPlan* lde_plan, const uint64_t* slice_weights) { + return quotient_lde_mixed_impl( + device_id, output_handle, nodes, node_count, slot_count, roots, + root_count, lookups, lookup_count, lookup_args, lookup_arg_count, + group_size, preprocessed_handle, preprocessed_host, preprocessed_height, + preprocessed_width, main_handle, main_host, main_height, main_width, + stage2_handle, stage2_host, stage2_height, stage2_width, publics, + public_count, coset_shift, coset_generator, trace_last, vanishing_start, + vanishing_step, alpha, constraint_count, delta, ext_w, quotient_size, + next_step, quotient_degree, log_blowup, quotient_plan, lde_plan, + slice_weights); +} + +extern "C" int multi_stark_cuda_quotient_lde_mixed_ext3( + int device_id, void** output_handle, const void* nodes, size_t node_count, + size_t slot_count, const uint32_t* roots, size_t root_count, + const void* lookups, size_t lookup_count, const uint32_t* lookup_args, + size_t lookup_arg_count, size_t group_size, + const void* preprocessed_handle, const uint64_t* preprocessed_host, + size_t preprocessed_height, size_t preprocessed_width, + const void* main_handle, const uint64_t* main_host, + size_t main_height, size_t main_width, + const void* stage2_handle, const uint64_t* stage2_host, + size_t stage2_height, size_t stage2_width, + const uint64_t* publics, size_t public_count, + uint64_t coset_shift, uint64_t coset_generator, uint64_t trace_last, + uint64_t vanishing_start, uint64_t vanishing_step, const uint64_t* alpha, + size_t constraint_count, const uint64_t* delta, + size_t quotient_size, size_t next_step, size_t quotient_degree, + size_t log_blowup, const MultiStarkNttPlan* quotient_plan, + const MultiStarkNttPlan* lde_plan, const uint64_t* slice_weights) { + return quotient_lde_mixed_impl( + device_id, output_handle, nodes, node_count, slot_count, roots, + root_count, lookups, lookup_count, lookup_args, lookup_arg_count, + group_size, preprocessed_handle, preprocessed_host, preprocessed_height, + preprocessed_width, main_handle, main_host, main_height, main_width, + stage2_handle, stage2_host, stage2_height, stage2_width, publics, + public_count, coset_shift, coset_generator, trace_last, vanishing_start, + vanishing_step, alpha, constraint_count, delta, 0, quotient_size, + next_step, quotient_degree, log_blowup, quotient_plan, lde_plan, + slice_weights); +} + +namespace { +template +int lde_interpolate_impl(int device_id,uint64_t* output,const void* handle, size_t height,const uint64_t* inv_denoms,const uint64_t* coset,const uint64_t* scale,uint64_t ext_w){ if(!output||!handle||!inv_denoms||!coset||!scale)return static_cast(cudaErrorInvalidValue); ResidentLde* l=const_cast(static_cast(handle));if(height==0||height>l->height)return static_cast(cudaErrorInvalidValue); - cudaError_t status=cudaSetDevice(device_id);const size_t ib=height*sizeof(Ext2),cb=height*sizeof(uint64_t),ob=l->width*sizeof(Ext2),needed=ib+cb+ob; + cudaError_t status=cudaSetDevice(device_id);const size_t ib=height*sizeof(Ext),cb=height*sizeof(uint64_t),ob=l->width*sizeof(Ext),needed=ib+cb+ob; if(status==cudaSuccess&&l->interpolation_scratch_bytesinterpolation_scratch)status=cudaFree(l->interpolation_scratch);l->interpolation_scratch=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&l->interpolation_scratch),needed);if(status==cudaSuccess)l->interpolation_scratch_bytes=needed;} uint8_t* mem=l->interpolation_scratch; if(status==cudaSuccess)status=cudaMemcpy(mem,inv_denoms,ib,cudaMemcpyHostToDevice); if(status==cudaSuccess)status=cudaMemcpy(mem+ib,coset,cb,cudaMemcpyHostToDevice); - if(status==cudaSuccess){interpolate_lde_columns<<(l->width),THREADS,THREADS*sizeof(Ext2)>>>(reinterpret_cast(mem+ib+cb),l,reinterpret_cast(mem),reinterpret_cast(mem+ib),height,{scale[0],scale[1]},ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){interpolate_lde_columns_t<<(l->width),THREADS,THREADS*sizeof(Ext)>>>(reinterpret_cast(mem+ib+cb),l,reinterpret_cast(mem),reinterpret_cast(mem+ib),height,ExtOps::load(scale),ext_w);status=cudaGetLastError();} if(status==cudaSuccess)status=cudaMemcpy(output,mem+ib+cb,ob,cudaMemcpyDeviceToHost);return static_cast(status); } -extern "C" int multi_stark_cuda_fri_workspace_create(int device_id,void** handle, +template +int fri_workspace_create_impl(int device_id,void** handle, const uint64_t* points,const size_t* counts,size_t point_count, const uint64_t* coset,size_t coset_count,uint64_t ext_w){ + constexpr size_t D = ExtOps::D; if(!handle||!points||!counts||!point_count||!coset||!coset_count) return static_cast(cudaErrorInvalidValue);*handle=nullptr; size_t inv_count=0,max_count=0; @@ -2852,30 +3260,32 @@ extern "C" int multi_stark_cuda_fri_workspace_create(int device_id,void** handle inv_count+=counts[i];if(counts[i]>max_count)max_count=counts[i]; } cudaError_t status=cudaSetDevice(device_id);auto* w=new(std::nothrow) ResidentFriWorkspace;if(!w)return static_cast(cudaErrorMemoryAllocation); - w->inv_count=inv_count;w->coset_count=coset_count; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->inv_denoms),inv_count*sizeof(Ext2)); - // One upload per device and size: every shard's opening indexes the same - // bit-reversed coset, 512 MiB at 2^26 rows. + w->inv_count=inv_count;w->coset_count=coset_count;w->ext_degree=D; + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->inv_denoms),inv_count*sizeof(Ext)); if(status==cudaSuccess)status=cached_device_constants(device_id,coset,coset_count,5,coset[0],coset_count>1?coset[1]:0,&w->coset); uint64_t *norms=nullptr,*inverses=nullptr; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norms),max_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&inverses),max_count*sizeof(uint64_t)); size_t offset=0; - for(size_t i=0;status==cudaSuccess&&i>>(norms,w->coset,counts[i],point,ext_w);status=cudaGetLastError(); + for(size_t i=0;status==cudaSuccess&&i::load(points+D*i); + denominator_norms_t<<>>(norms,w->coset,counts[i],point,ext_w);status=cudaGetLastError(); if(status==cudaSuccess)status=batch_inverse_norms(inverses,norms,counts[i]); - if(status==cudaSuccess){finish_inverse_denominators<<>>(w->inv_denoms+offset,inverses,w->coset,counts[i],point);status=cudaGetLastError();} + if(status==cudaSuccess){finish_inverse_denominators_t<<>>(reinterpret_cast(w->inv_denoms)+offset,inverses,w->coset,counts[i],point);status=cudaGetLastError();} offset+=counts[i]; } if(inverses)cudaFree(inverses);if(norms)cudaFree(norms); if(status!=cudaSuccess){delete w;return static_cast(status);}*handle=w;return static_cast(cudaSuccess); } -extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_interpolate_batch(int device_id,void* handle,uint64_t* output, - size_t output_count,const InterpolationTask* tasks,size_t task_count,uint64_t ext_w){ +template +int fri_interpolate_batch_impl(int device_id,void* handle,uint64_t* output, + size_t output_count,const Task* tasks,size_t task_count,uint64_t ext_w){ + constexpr size_t D = ExtOps::D; if(!handle||!output||!output_count||!tasks||!task_count)return static_cast(cudaErrorInvalidValue); cudaError_t status=cudaSetDevice(device_id);auto* w=static_cast(handle); - if(status==cudaSuccess&&w->output_capacityoutput)status=cudaFree(w->output);w->output=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->output),output_count*sizeof(Ext2));if(status==cudaSuccess)w->output_capacity=output_count;} + if(w->ext_degree!=D)return static_cast(cudaErrorInvalidValue); + if(status==cudaSuccess&&w->output_capacityoutput)status=cudaFree(w->output);w->output=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->output),output_count*sizeof(Ext));if(status==cudaSuccess)w->output_capacity=output_count;} size_t partial_count=0,block_count=0,finish_count=0; for(size_t i=0;status==cudaSuccess&&i(t.lde); if(!l||!t.height||t.height>l->height||t.inv_offset>w->inv_count-t.height||t.output_offset>output_count-l->width){status=cudaErrorInvalidValue;break;} @@ -2884,104 +3294,109 @@ extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_inter tasks[i+1].inv_offset<=w->inv_count-t.height&&tasks[i+1].output_offset<=output_count-l->width; const size_t columns=(l->width+INTERPOLATION_COLUMNS-1)/INTERPOLATION_COLUMNS; if(partial_rows>SIZE_MAX/l->width||partial_count>SIZE_MAX-partial_rows*l->width*(pair?2:1)|| - columns&&partial_rows>SIZE_MAX/columns||block_count>SIZE_MAX-partial_rows*columns|| + (columns&&partial_rows>SIZE_MAX/columns)||block_count>SIZE_MAX-partial_rows*columns|| finish_count>SIZE_MAX-l->width*(pair?2:1)){status=cudaErrorInvalidValue;break;} partial_count+=partial_rows*l->width*(pair?2:1);block_count+=partial_rows*columns; finish_count+=l->width*(pair?2:1);i+=pair?2:1;} if(status==cudaSuccess&&w->partial_capacityinterpolation_partials)status=cudaFree(w->interpolation_partials);w->interpolation_partials=nullptr; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->interpolation_partials),partial_count*sizeof(Ext2)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->interpolation_partials),partial_count*sizeof(Ext)); if(status==cudaSuccess)w->partial_capacity=partial_count;} - InterpolationBlockDesc* host_blocks=status==cudaSuccess?new(std::nothrow) InterpolationBlockDesc[block_count]:nullptr; - InterpolationFinishDesc* host_finishes=status==cudaSuccess?new(std::nothrow) InterpolationFinishDesc[finish_count]:nullptr; + using BlockDesc = InterpolationBlockDescT; + using FinishDesc = InterpolationFinishDescT; + BlockDesc* host_blocks=status==cudaSuccess?new(std::nothrow) BlockDesc[block_count]:nullptr; + FinishDesc* host_finishes=status==cudaSuccess?new(std::nothrow) FinishDesc[finish_count]:nullptr; if(status==cudaSuccess&&(!host_blocks||!host_finishes))status=cudaErrorMemoryAllocation; + Ext* dev_partials = reinterpret_cast(w->interpolation_partials); + const Ext* dev_inv = reinterpret_cast(w->inv_denoms); + Ext* dev_out = reinterpret_cast(w->output); size_t partial_at=0,block_at=0,finish_at=0; for(size_t i=0;status==cudaSuccess&&i(t.lde); const size_t partial_rows=(t.height+INTERPOLATION_ROWS-1)/INTERPOLATION_ROWS; const size_t one_count=partial_rows*l->width; const bool pair=i+1inv_count-t.height&&tasks[i+1].output_offset<=output_count-l->width; - Ext2* p0=w->interpolation_partials+partial_at;Ext2* p1=pair?p0+one_count:nullptr; + Ext* p0=dev_partials+partial_at;Ext* p1=pair?p0+one_count:nullptr; for(size_t row=0;rowwidth;column+=INTERPOLATION_COLUMNS) - host_blocks[block_at++]={l->values,w->coset,w->inv_denoms+t.inv_offset, - pair?w->inv_denoms+tasks[i+1].inv_offset:nullptr,p0,p1,l->width,column,row, + host_blocks[block_at++]={l->values,w->coset,dev_inv+t.inv_offset, + pair?dev_inv+tasks[i+1].inv_offset:nullptr,p0,p1,l->width,column,row, row+INTERPOLATION_ROWSwidth;++column) - host_finishes[finish_at++]={w->output+t.output_offset+column,p0,partial_rows,l->width,column,{t.scale0,t.scale1}}; + host_finishes[finish_at++]={dev_out+t.output_offset+column,p0,partial_rows,l->width,column,task_scale(t)}; if(pair){const auto& u=tasks[i+1];for(size_t column=0;columnwidth;++column) - host_finishes[finish_at++]={w->output+u.output_offset+column,p1,partial_rows,l->width,column,{u.scale0,u.scale1}};} + host_finishes[finish_at++]={dev_out+u.output_offset+column,p1,partial_rows,l->width,column,task_scale(u)};} partial_at+=one_count*(pair?2:1);i+=pair?2:1;} - InterpolationBlockDesc* device_blocks=nullptr;InterpolationFinishDesc* device_finishes=nullptr; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&device_blocks),block_count*sizeof(InterpolationBlockDesc)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&device_finishes),finish_count*sizeof(InterpolationFinishDesc)); - if(status==cudaSuccess)status=cudaMemcpyAsync(device_blocks,host_blocks,block_count*sizeof(InterpolationBlockDesc),cudaMemcpyHostToDevice,cudaStreamPerThread); - if(status==cudaSuccess)status=cudaMemcpyAsync(device_finishes,host_finishes,finish_count*sizeof(InterpolationFinishDesc),cudaMemcpyHostToDevice,cudaStreamPerThread); + BlockDesc* device_blocks=nullptr;FinishDesc* device_finishes=nullptr; + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&device_blocks),block_count*sizeof(BlockDesc)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&device_finishes),finish_count*sizeof(FinishDesc)); + if(status==cudaSuccess)status=cudaMemcpyAsync(device_blocks,host_blocks,block_count*sizeof(BlockDesc),cudaMemcpyHostToDevice,cudaStreamPerThread); + if(status==cudaSuccess)status=cudaMemcpyAsync(device_finishes,host_finishes,finish_count*sizeof(FinishDesc),cudaMemcpyHostToDevice,cudaStreamPerThread); if(status==cudaSuccess)status=cudaStreamSynchronize(cudaStreamPerThread); delete[] host_finishes;host_finishes=nullptr;delete[] host_blocks;host_blocks=nullptr; if(status==cudaSuccess){const dim3 block(INTERPOLATION_COLUMNS,INTERPOLATION_LANES); - interpolate_lde_blocks<<(block_count),block>>>(device_blocks,ext_w);status=cudaGetLastError();} - if(status==cudaSuccess){finish_lde_interpolation_blocks<<(finish_count),THREADS,THREADS*sizeof(Ext2)>>>(device_finishes,ext_w);status=cudaGetLastError();} + interpolate_lde_blocks_t<<(block_count),block>>>(device_blocks,ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){finish_lde_interpolation_blocks_t<<(finish_count),THREADS,THREADS*sizeof(Ext)>>>(device_finishes,ext_w);status=cudaGetLastError();} if(device_finishes)cudaFree(device_finishes);if(device_blocks)cudaFree(device_blocks); delete[] host_finishes;delete[] host_blocks; - if(status==cudaSuccess)status=cudaMemcpy(output,w->output,output_count*sizeof(Ext2),cudaMemcpyDeviceToHost);return static_cast(status); + if(status==cudaSuccess)status=cudaMemcpy(output,w->output,output_count*sizeof(Ext),cudaMemcpyDeviceToHost);return static_cast(status); } -extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_reduce_batch(int device_id,void* handle, - const ReductionTask* tasks,size_t task_count,const uint64_t* alpha,size_t alpha_count,uint64_t ext_w){ +template +int fri_reduce_batch_impl(int device_id,void* handle, + const Task* tasks,size_t task_count,const uint64_t* alpha,size_t alpha_count,uint64_t ext_w){ + constexpr size_t D = ExtOps::D; if(!handle||!tasks||!task_count||!alpha||!alpha_count)return static_cast(cudaErrorInvalidValue); cudaError_t status=cudaSetDevice(device_id);auto* w=static_cast(handle); - if(status==cudaSuccess&&w->alpha_capacityalpha)status=cudaFree(w->alpha);w->alpha=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->alpha),alpha_count*sizeof(Ext2));if(status==cudaSuccess)w->alpha_capacity=alpha_count;} - if(status==cudaSuccess)status=cudaMemcpy(w->alpha,alpha,alpha_count*sizeof(Ext2),cudaMemcpyHostToDevice); + if(w->ext_degree!=D)return static_cast(cudaErrorInvalidValue); + if(status==cudaSuccess&&w->alpha_capacityalpha)status=cudaFree(w->alpha);w->alpha=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&w->alpha),alpha_count*sizeof(Ext));if(status==cudaSuccess)w->alpha_capacity=alpha_count;} + if(status==cudaSuccess)status=cudaMemcpy(w->alpha,alpha,alpha_count*sizeof(Ext),cudaMemcpyHostToDevice); for(size_t i=0;status==cudaSuccess&&i(t.reduced);auto* l=static_cast(t.lde); - if(!r||!l||t.height!=r->height||t.height>l->height||t.inv_offset+t.height>w->inv_count||l->width>alpha_count){status=cudaErrorInvalidValue;break;} - accumulate_reduced_opening<<>>(r->values,l,w->inv_denoms+t.inv_offset,w->alpha,t.height,{t.y0,t.y1},{t.offset0,t.offset1},ext_w);status=cudaGetLastError();} + if(!r||!l||r->ext_degree!=D||t.height!=r->height||t.height>l->height||t.inv_offset+t.height>w->inv_count||l->width>alpha_count){status=cudaErrorInvalidValue;break;} + accumulate_reduced_opening_t<<>>( + reinterpret_cast(r->values),l,reinterpret_cast(w->inv_denoms)+t.inv_offset, + reinterpret_cast(w->alpha),t.height,task_y(t),task_offset(t),ext_w);status=cudaGetLastError();} return static_cast(status); } -extern "C" int multi_stark_cuda_fri_workspace_destroy(int device_id,void* handle){ - cudaError_t status=cudaSetDevice(device_id);if(status==cudaSuccess)delete static_cast(handle);return static_cast(status); -} - -extern "C" int multi_stark_cuda_reduced_into_lde(int device_id,void** output,void* reduced){ - if(!output||!reduced)return static_cast(cudaErrorInvalidValue);*output=nullptr; - auto* r=static_cast(reduced);cudaError_t status=cudaSetDevice(device_id); - ResidentLde* l=nullptr;if(status==cudaSuccess)status=create_resident_lde(&l);if(status==cudaSuccess){l->height=r->height;l->width=2;} - if(status!=cudaSuccess){destroy_resident_lde(l);return static_cast(status);} - l->values=reinterpret_cast(r->values);r->values=nullptr;*output=l; - return static_cast(cudaSuccess); -} - -extern "C" int multi_stark_cuda_fri_fold_resident(int device_id,void** output,const void* input, - const void* next_reduced,const uint64_t* beta,size_t log_arity,uint64_t beta_power0, - uint64_t beta_power1,uint64_t g_inv,uint64_t ext_w){ +template +int fri_fold_resident_impl(int device_id,void** output,const void* input, + const void* next_reduced,const uint64_t* beta,size_t log_arity, + Ext beta_power,uint64_t g_inv,uint64_t ext_w){ + constexpr size_t D = ExtOps::D; if(!output||!input||!beta||log_arity!=1)return static_cast(cudaErrorInvalidValue);*output=nullptr; - auto* in=static_cast(input);if(in->width!=2||in->height%2)return static_cast(cudaErrorInvalidValue); + auto* in=static_cast(input);if(in->width!=D||in->height%2)return static_cast(cudaErrorInvalidValue); const size_t final_height=in->height>>log_arity;auto* next=static_cast(next_reduced); - if(next&&next->height!=final_height)return static_cast(cudaErrorInvalidValue); - cudaError_t status=cudaSetDevice(device_id);Ext2 *a=reinterpret_cast(in->values),*first=nullptr;uint64_t* powers=nullptr; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&first),(in->height/2)*sizeof(Ext2)); + if(next&&(next->height!=final_height||next->ext_degree!=D))return static_cast(cudaErrorInvalidValue); + cudaError_t status=cudaSetDevice(device_id);Ext *a=reinterpret_cast(in->values),*first=nullptr;uint64_t* powers=nullptr; + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&first),(in->height/2)*sizeof(Ext)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&powers),(in->height/2)*sizeof(uint64_t)); if(status==cudaSuccess){init_fri_powers<<height/2),THREADS>>>(powers,in->height/2,g_inv);status=cudaGetLastError();} - if(status==cudaSuccess){fold_fri_ext2<<>>(first,a,powers,final_height,{beta[0],beta[1]},ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){fold_fri_t<<>>(first,a,powers,final_height,ExtOps::load(beta),ext_w);status=cudaGetLastError();} a=first; - if(status==cudaSuccess&&next){add_scaled_ext2<<>>(a,next->values,final_height,{beta_power0,beta_power1},ext_w);status=cudaGetLastError();} + if(status==cudaSuccess&&next){add_scaled_t<<>>(a,reinterpret_cast(next->values),final_height,beta_power,ext_w);status=cudaGetLastError();} ResidentLde* result=nullptr;if(status==cudaSuccess)status=create_resident_lde(&result); - if(status==cudaSuccess){result->values=reinterpret_cast(a);result->height=final_height;result->width=2;first=nullptr;*output=result;}else destroy_resident_lde(result); + if(status==cudaSuccess){result->values=reinterpret_cast(a);result->height=final_height;result->width=D;first=nullptr;*output=result;}else destroy_resident_lde(result); cudaFree(powers);cudaFree(first);return static_cast(status); } -extern "C" int multi_stark_cuda_reduced_create(int device_id,void** handle,size_t height){ +template +int reduced_create_impl(int device_id,void** handle,size_t height){ + constexpr size_t D = ExtOps::D; if(!handle||!is_power_of_two(height))return static_cast(cudaErrorInvalidValue);*handle=nullptr;cudaError_t status=cudaSetDevice(device_id); - auto* r=new(std::nothrow) ResidentReducedOpening;if(!r)return static_cast(cudaErrorMemoryAllocation);r->height=height; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&r->values),height*sizeof(Ext2));if(status==cudaSuccess)status=cudaMemset(r->values,0,height*sizeof(Ext2)); + auto* r=new(std::nothrow) ResidentReducedOpening;if(!r)return static_cast(cudaErrorMemoryAllocation); + r->height=height;r->ext_degree=D; + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&r->values),height*sizeof(Ext)); + if(status==cudaSuccess)status=cudaMemset(r->values,0,height*sizeof(Ext)); if(status!=cudaSuccess){delete r;return static_cast(status);}*handle=r;return static_cast(cudaSuccess); } -extern "C" int multi_stark_cuda_reduced_add_host(int device_id,void* handle, - const uint64_t* values,size_t height){ + +template +int reduced_add_host_impl(int device_id,void* handle,const uint64_t* values,size_t height){ + constexpr size_t D = ExtOps::D; if(!handle||!values)return static_cast(cudaErrorInvalidValue); auto* r=static_cast(handle); - if(height!=r->height)return static_cast(cudaErrorInvalidValue); - cudaError_t status=cudaSetDevice(device_id);const size_t bytes=height*sizeof(Ext2); + if(height!=r->height||r->ext_degree!=D)return static_cast(cudaErrorInvalidValue); + cudaError_t status=cudaSetDevice(device_id);const size_t bytes=height*sizeof(Ext); if(status==cudaSuccess&&r->scratch_bytesscratch)status=cudaFree(r->scratch);r->scratch=nullptr;r->scratch_bytes=0; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&r->scratch),bytes); @@ -2989,44 +3404,135 @@ extern "C" int multi_stark_cuda_reduced_add_host(int device_id,void* handle, } if(status==cudaSuccess)status=cudaMemcpy(r->scratch,values,bytes,cudaMemcpyHostToDevice); if(status==cudaSuccess){ - add_scaled_ext2<<>>( - r->values,reinterpret_cast(r->scratch),height,{1,0},7); + Ext one = {}; + one.c0 = 1; + add_scaled_t<<>>( + reinterpret_cast(r->values),reinterpret_cast(r->scratch),height,one,7); status=cudaGetLastError(); } return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_trace(int device_id,uint64_t* output,uint64_t* total, +} // namespace + +extern "C" int multi_stark_cuda_lde_interpolate(int device_id,uint64_t* output,const void* handle, + size_t height,const uint64_t* inv_denoms,const uint64_t* coset,const uint64_t* scale,uint64_t ext_w){ + return lde_interpolate_impl(device_id,output,handle,height,inv_denoms,coset,scale,ext_w); +} + +extern "C" int multi_stark_cuda_lde_interpolate_ext3(int device_id,uint64_t* output,const void* handle, + size_t height,const uint64_t* inv_denoms,const uint64_t* coset,const uint64_t* scale){ + return lde_interpolate_impl(device_id,output,handle,height,inv_denoms,coset,scale,0); +} + +extern "C" int multi_stark_cuda_fri_workspace_create(int device_id,void** handle, + const uint64_t* points,const size_t* counts,size_t point_count, + const uint64_t* coset,size_t coset_count,uint64_t ext_w){ + return fri_workspace_create_impl(device_id,handle,points,counts,point_count,coset,coset_count,ext_w); +} + +extern "C" int multi_stark_cuda_fri_workspace_create_ext3(int device_id,void** handle, + const uint64_t* points,const size_t* counts,size_t point_count, + const uint64_t* coset,size_t coset_count){ + return fri_workspace_create_impl(device_id,handle,points,counts,point_count,coset,coset_count,0); +} + +extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_interpolate_batch(int device_id,void* handle,uint64_t* output, + size_t output_count,const InterpolationTask* tasks,size_t task_count,uint64_t ext_w){ + return fri_interpolate_batch_impl(device_id,handle,output,output_count,tasks,task_count,ext_w); +} + +extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_interpolate_batch_ext3(int device_id,void* handle,uint64_t* output, + size_t output_count,const InterpolationTaskExt3* tasks,size_t task_count){ + return fri_interpolate_batch_impl(device_id,handle,output,output_count,tasks,task_count,0); +} + +extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_reduce_batch(int device_id,void* handle, + const ReductionTask* tasks,size_t task_count,const uint64_t* alpha,size_t alpha_count,uint64_t ext_w){ + return fri_reduce_batch_impl(device_id,handle,tasks,task_count,alpha,alpha_count,ext_w); +} + +extern "C" __attribute__((visibility("default"))) int multi_stark_cuda_fri_reduce_batch_ext3(int device_id,void* handle, + const ReductionTaskExt3* tasks,size_t task_count,const uint64_t* alpha,size_t alpha_count){ + return fri_reduce_batch_impl(device_id,handle,tasks,task_count,alpha,alpha_count,0); +} + +extern "C" int multi_stark_cuda_fri_workspace_destroy(int device_id,void* handle){ + cudaError_t status=cudaSetDevice(device_id);if(status==cudaSuccess)delete static_cast(handle);return static_cast(status); +} + +extern "C" int multi_stark_cuda_reduced_into_lde(int device_id,void** output,void* reduced){ + if(!output||!reduced)return static_cast(cudaErrorInvalidValue);*output=nullptr; + auto* r=static_cast(reduced);cudaError_t status=cudaSetDevice(device_id); + ResidentLde* l=nullptr;if(status==cudaSuccess)status=create_resident_lde(&l);if(status==cudaSuccess){l->height=r->height;l->width=r->ext_degree;} + if(status!=cudaSuccess){destroy_resident_lde(l);return static_cast(status);} + l->values=r->values;r->values=nullptr;*output=l; + return static_cast(cudaSuccess); +} + +extern "C" int multi_stark_cuda_fri_fold_resident(int device_id,void** output,const void* input, + const void* next_reduced,const uint64_t* beta,size_t log_arity,uint64_t beta_power0, + uint64_t beta_power1,uint64_t g_inv,uint64_t ext_w){ + return fri_fold_resident_impl(device_id,output,input,next_reduced,beta,log_arity,{beta_power0,beta_power1},g_inv,ext_w); +} + +extern "C" int multi_stark_cuda_fri_fold_resident_ext3(int device_id,void** output,const void* input, + const void* next_reduced,const uint64_t* beta,size_t log_arity,uint64_t beta_power0, + uint64_t beta_power1,uint64_t beta_power2,uint64_t g_inv){ + return fri_fold_resident_impl(device_id,output,input,next_reduced,beta,log_arity,{beta_power0,beta_power1,beta_power2},g_inv,0); +} + +extern "C" int multi_stark_cuda_reduced_create(int device_id,void** handle,size_t height){ + return reduced_create_impl(device_id,handle,height); +} +extern "C" int multi_stark_cuda_reduced_create_ext3(int device_id,void** handle,size_t height){ + return reduced_create_impl(device_id,handle,height); +} +extern "C" int multi_stark_cuda_reduced_add_host(int device_id,void* handle, + const uint64_t* values,size_t height){ + return reduced_add_host_impl(device_id,handle,values,height); +} +extern "C" int multi_stark_cuda_reduced_add_host_ext3(int device_id,void* handle, + const uint64_t* values,size_t height){ + return reduced_add_host_impl(device_id,handle,values,height); +} +namespace { +template +int lookup_trace_impl(int device_id,uint64_t* output,uint64_t* total, const uint64_t* multiplicities,const uint64_t* args,const size_t* arg_offsets, size_t height,size_t num_lookups,size_t args_width,size_t group_size, const uint64_t* beta,const uint64_t* gamma,uint64_t ext_w){ + constexpr size_t D = ExtOps::D; if(!output||!total||!multiplicities||!arg_offsets||!height||!num_lookups||!group_size||!beta||!gamma||(args_width&& !args))return static_cast(cudaErrorInvalidValue); const size_t slots=(num_lookups+group_size-1)/group_size,count=height*slots;cudaError_t status=cudaSetDevice(device_id); - const size_t message_count=height*num_lookups;uint64_t *dm=nullptr,*da=nullptr,*norms=nullptr,*norm_inverses=nullptr;size_t* offsets=nullptr;Ext2 *conjugates=nullptr,*deltas=nullptr,*scan=nullptr; + const size_t message_count=height*num_lookups;uint64_t *dm=nullptr,*da=nullptr,*norms=nullptr,*norm_inverses=nullptr;size_t* offsets=nullptr;Ext *conjugates=nullptr,*deltas=nullptr,*scan=nullptr; if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&dm),height*num_lookups*sizeof(uint64_t)); if(status==cudaSuccess&&args_width)status=cudaMalloc(reinterpret_cast(&da),height*args_width*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&offsets),(num_lookups+1)*sizeof(size_t)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&deltas),count*sizeof(Ext2)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&scan),count*sizeof(Ext2)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext2)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&deltas),count*sizeof(Ext)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&scan),count*sizeof(Ext)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norms),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norm_inverses),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMemcpyAsync(dm,multiplicities,height*num_lookups*sizeof(uint64_t),cudaMemcpyHostToDevice,0); if(status==cudaSuccess&&args_width)status=cudaMemcpyAsync(da,args,height*args_width*sizeof(uint64_t),cudaMemcpyHostToDevice,0); if(status==cudaSuccess)status=cudaMemcpyAsync(offsets,arg_offsets,(num_lookups+1)*sizeof(size_t),cudaMemcpyHostToDevice,0); - if(status==cudaSuccess){lookup_messages<<>>(conjugates,norms,da,offsets,height,num_lookups,args_width,{beta[0],beta[1]},{gamma[0],gamma[1]},ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){lookup_messages_t<<>>(conjugates,norms,da,offsets,height,num_lookups,args_width,ExtOps::load(beta),ExtOps::load(gamma),ext_w);status=cudaGetLastError();} if(status==cudaSuccess)status=batch_inverse_norms(norm_inverses,norms,message_count); - if(status==cudaSuccess){lookup_group_deltas_batched<<>>(deltas,dm,conjugates,norm_inverses,height,num_lookups,group_size,ext_w);status=cudaGetLastError();} - if(status==cudaSuccess)status=exclusive_scan_ext2(scan,deltas,count); - if(status==cudaSuccess)status=cudaMemcpy(output,scan,count*sizeof(Ext2),cudaMemcpyDeviceToHost); - if(status==cudaSuccess)status=cudaMemcpy(total,scan+count-1,sizeof(Ext2),cudaMemcpyDeviceToHost);if(status==cudaSuccess)status=cudaMemcpy(total+2,deltas+count-1,sizeof(Ext2),cudaMemcpyDeviceToHost); + if(status==cudaSuccess){lookup_group_deltas_batched_t<<>>(deltas,dm,conjugates,norm_inverses,height,num_lookups,group_size);status=cudaGetLastError();} + if(status==cudaSuccess)status=exclusive_scan_ext_t(scan,deltas,count); + if(status==cudaSuccess)status=cudaMemcpy(output,scan,count*sizeof(Ext),cudaMemcpyDeviceToHost); + if(status==cudaSuccess)status=cudaMemcpy(total,scan+count-1,sizeof(Ext),cudaMemcpyDeviceToHost); + if(status==cudaSuccess)status=cudaMemcpy(total+D,deltas+count-1,sizeof(Ext),cudaMemcpyDeviceToHost); cudaFree(norm_inverses);cudaFree(norms);cudaFree(conjugates);cudaFree(scan);cudaFree(deltas);cudaFree(offsets);cudaFree(da);cudaFree(dm);return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_handle,uint64_t* total, +template +int lookup_graph_lde_impl(int device_id,void** output_handle,uint64_t* total, const void* nodes,size_t node_count,size_t slot_count,const void* lookups,size_t lookup_count, const uint32_t* lookup_args,size_t lookup_arg_count,const void* preprocessed_handle, const void* main_handle,size_t group_size,const uint64_t* beta,const uint64_t* gamma, uint64_t ext_w,size_t added_bits,const MultiStarkNttPlan* plan){ + constexpr size_t D = ExtOps::D; auto* main=const_cast(static_cast(main_handle)); auto* prep=static_cast(preprocessed_handle); if(!output_handle||!total||!nodes||!node_count||!slot_count||!lookups||!lookup_count|| @@ -3038,7 +3544,7 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han return static_cast(cudaErrorInvalidValue); } *output_handle=nullptr;const size_t height=main->trace_height; - const size_t groups=(lookup_count+group_size-1)/group_size,width=2*groups; + const size_t groups=(lookup_count+group_size-1)/group_size,width=D*groups; const size_t count=height*groups,extended_height=height<(&metadata),bytes); - auto cp=[&](size_t at,const void* src,size_t n){if(status==cudaSuccess)status=cudaMemcpy(metadata+at,src,n,cudaMemcpyHostToDevice);}; + auto cp=[&](size_t at,const void* src,size_t n){if(status==cudaSuccess&&n!=0)status=cudaMemcpy(metadata+at,src,n,cudaMemcpyHostToDevice);}; cp(on,nodes,node_count*sizeof(ConstraintNode));cp(ol,lookups,lookup_count*sizeof(ConstraintLookup));cp(oa,lookup_args,lookup_arg_count*sizeof(uint32_t)); auto* dn=reinterpret_cast(metadata+on);auto* dl=reinterpret_cast(metadata+ol);auto* da=reinterpret_cast(metadata+oa); - Ext2 *conjugates=nullptr,*deltas=nullptr;uint64_t *norms=nullptr,*norm_inverses=nullptr,*multiplicities=nullptr,*scratch=nullptr,*trace_chunk=nullptr;ResidentLde* lde=nullptr; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext2)); + Ext *conjugates=nullptr,*deltas=nullptr;uint64_t *norms=nullptr,*norm_inverses=nullptr,*multiplicities=nullptr,*scratch=nullptr,*trace_chunk=nullptr;ResidentLde* lde=nullptr; + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norms),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norm_inverses),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&multiplicities),message_count*sizeof(uint64_t)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&deltas),count*sizeof(Ext2)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&deltas),count*sizeof(Ext)); if(status==cudaSuccess)status=create_resident_lde(&lde); if(status==cudaSuccess){lde->height=extended_height;lde->width=width;status=cudaMalloc(reinterpret_cast(&lde->values),extended_height*width*sizeof(uint64_t));} if(status==cudaSuccess)status=cudaMemset(lde->values,0,extended_height*width*sizeof(uint64_t)); @@ -3069,6 +3575,8 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han const bool generated = !main->trace_values && main->trace_writer; const bool tiled = main->host_trace_values || generated; if(status==cudaSuccess&&tiled)status=cudaMalloc(reinterpret_cast(&trace_chunk),(chunk_rows+1)*main->width*sizeof(uint64_t)); + const Ext beta_ext = ExtOps::load(beta); + const Ext gamma_ext = ExtOps::load(gamma); for(size_t row_start=0;status==cudaSuccess&&row_startwidth,main->host_trace_values+next_row*main->width,main->width*sizeof(uint64_t),cudaMemcpyHostToDevice); active_trace=trace_chunk; } - if(status==cudaSuccess){lookup_messages_graph<<(chunk_blocks),static_cast(tile),global?0:slot_count*tile*sizeof(uint64_t)>>>( + if(status==cudaSuccess){lookup_messages_graph_t<<(chunk_blocks),static_cast(tile),global?0:slot_count*tile*sizeof(uint64_t)>>>( conjugates,norms,multiplicities,dn,node_count,slot_count,dl,lookup_count,da,prep,active_trace,main->width, - tiled,{beta[0],beta[1]},{gamma[0],gamma[1]},ext_w,height,row_start,rows,scratch);status=cudaGetLastError();} + tiled,beta_ext,gamma_ext,ext_w,height,row_start,rows,scratch);status=cudaGetLastError();} if(status==cudaSuccess)status=batch_inverse_norms(norm_inverses,norms,messages); - if(status==cudaSuccess){lookup_group_deltas_batched<<>>( - deltas+row_start*groups,multiplicities,conjugates,norm_inverses,rows,lookup_count,group_size,ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){lookup_group_deltas_batched_t<<>>( + deltas+row_start*groups,multiplicities,conjugates,norm_inverses,rows,lookup_count,group_size);status=cudaGetLastError();} } - if(status==cudaSuccess)status=exclusive_scan_ext2(reinterpret_cast(lde->values),deltas,count); - if(status==cudaSuccess)status=cudaMemcpy(total,lde->values+2*(count-1),sizeof(Ext2),cudaMemcpyDeviceToHost); - if(status==cudaSuccess)status=cudaMemcpy(total+2,deltas+count-1,sizeof(Ext2),cudaMemcpyDeviceToHost); + if(status==cudaSuccess)status=exclusive_scan_ext_t(reinterpret_cast(lde->values),deltas,count); + if(status==cudaSuccess)status=cudaMemcpy(total,lde->values+D*(count-1),sizeof(Ext),cudaMemcpyDeviceToHost); + if(status==cudaSuccess)status=cudaMemcpy(total+D,deltas+count-1,sizeof(Ext),cudaMemcpyDeviceToHost); if(status==cudaSuccess)status=coset_lde(device_id,lde->values,lde->values,height,width,extended_height,plan); if(status==cudaSuccess)status=cudaStreamSynchronize(0); if(status==cudaSuccess)*output_handle=lde;else destroy_resident_lde(lde); @@ -3101,18 +3609,20 @@ extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_han return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_lde(int device_id,void** output_handle,uint64_t* total, +template +int lookup_lde_impl(int device_id,void** output_handle,uint64_t* total, const uint64_t* multiplicities,const uint64_t* args,const size_t* arg_offsets, size_t height,size_t num_lookups,size_t args_width,size_t group_size, const uint64_t* beta,const uint64_t* gamma,uint64_t ext_w,size_t added_bits, const MultiStarkNttPlan* plan){ + constexpr size_t D = ExtOps::D; if(!output_handle||!total||!multiplicities||!arg_offsets||!height||!num_lookups|| !group_size||!beta||!gamma||(!plan || !plan->shift_powers)|| (args_width&&!args)||!is_power_of_two(height)|| added_bits>=sizeof(size_t)*8||height>(SIZE_MAX>>added_bits)) return static_cast(cudaErrorInvalidValue); *output_handle=nullptr;const size_t slots=(num_lookups+group_size-1)/group_size; - const size_t width=2*slots,count=height*slots,extended_height=height<(cudaErrorInvalidValue); const bool profile=getenv("MULTI_STARK_CUDA_MEMORY_LOG")!=nullptr&& extended_height*width*sizeof(uint64_t)>=(size_t(1)<<30); @@ -3123,13 +3633,13 @@ extern "C" int multi_stark_cuda_lookup_lde(int device_id,void** output_handle,ui const size_t chunk_rows=height(&dm),chunk_rows*num_lookups*sizeof(uint64_t)); if(status==cudaSuccess&&args_width)status=cudaMalloc(reinterpret_cast(&da),chunk_rows*args_width*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&offsets),(num_lookups+1)*sizeof(size_t)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&deltas),count*sizeof(Ext2)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext2)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&deltas),count*sizeof(Ext)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&conjugates),message_count*sizeof(Ext)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norms),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&norm_inverses),message_count*sizeof(uint64_t)); if(status==cudaSuccess)status=create_resident_lde(&lde); @@ -3137,20 +3647,22 @@ extern "C" int multi_stark_cuda_lookup_lde(int device_id,void** output_handle,ui if(status==cudaSuccess)status=cudaMemset(lde->values,0,extended_height*width*sizeof(uint64_t)); if(status==cudaSuccess)status=cudaMemcpy(offsets,arg_offsets,(num_lookups+1)*sizeof(size_t),cudaMemcpyHostToDevice); allocated=now(); + const Ext beta_ext = ExtOps::load(beta); + const Ext gamma_ext = ExtOps::load(gamma); for(size_t row_start=0;status==cudaSuccess&&row_start>>(conjugates,norms,da,offsets,rows,num_lookups,args_width,{beta[0],beta[1]},{gamma[0],gamma[1]},ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){lookup_messages_t<<>>(conjugates,norms,da,offsets,rows,num_lookups,args_width,beta_ext,gamma_ext,ext_w);status=cudaGetLastError();} if(status==cudaSuccess)status=batch_inverse_norms(norm_inverses,norms,messages); - if(status==cudaSuccess){lookup_group_deltas_batched<<>>(deltas+row_start*slots,dm,conjugates,norm_inverses,rows,num_lookups,group_size,ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){lookup_group_deltas_batched_t<<>>(deltas+row_start*slots,dm,conjugates,norm_inverses,rows,num_lookups,group_size);status=cudaGetLastError();} } if(profile&&status==cudaSuccess)status=cudaStreamSynchronize(cudaStreamPerThread); rows_done=now(); - if(status==cudaSuccess)status=exclusive_scan_ext2(reinterpret_cast(lde->values),deltas,count); - if(status==cudaSuccess)status=cudaMemcpy(total,lde->values+2*(count-1),sizeof(Ext2),cudaMemcpyDeviceToHost); - if(status==cudaSuccess)status=cudaMemcpy(total+2,deltas+count-1,sizeof(Ext2),cudaMemcpyDeviceToHost); + if(status==cudaSuccess)status=exclusive_scan_ext_t(reinterpret_cast(lde->values),deltas,count); + if(status==cudaSuccess)status=cudaMemcpy(total,lde->values+D*(count-1),sizeof(Ext),cudaMemcpyDeviceToHost); + if(status==cudaSuccess)status=cudaMemcpy(total+D,deltas+count-1,sizeof(Ext),cudaMemcpyDeviceToHost); scan_done=now(); if(status==cudaSuccess)status=coset_lde(device_id,lde->values,lde->values,height,width,extended_height,plan); if(status==cudaSuccess)status=cudaStreamSynchronize(0); @@ -3163,10 +3675,12 @@ extern "C" int multi_stark_cuda_lookup_lde(int device_id,void** output_handle,ui cudaFree(offsets);cudaFree(da);cudaFree(dm);return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned( +template +int lookup_lde_begin_partitioned_impl( int device_id, void** pending_handle, const size_t* arg_offsets, size_t height, size_t num_lookups, size_t args_width, size_t group_size, size_t added_bits) { + constexpr size_t D = ExtOps::D; if (!pending_handle || !arg_offsets || !height || !num_lookups || !group_size || group_size > 8 || !is_power_of_two(height) || num_lookups > SIZE_MAX - (group_size - 1) || @@ -3175,7 +3689,7 @@ extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned( } *pending_handle = nullptr; const size_t slots = (num_lookups + group_size - 1) / group_size; - const size_t width = 2 * slots; + const size_t width = D * slots; const size_t extended_height = height << added_bits; constexpr size_t LOOKUP_ROWS_PER_CHUNK = size_t(1) << 16; const size_t scratch_rows = std::min(height, LOOKUP_ROWS_PER_CHUNK); @@ -3195,6 +3709,7 @@ extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned( pending->args_width = args_width; pending->group_size = group_size; pending->scratch_rows = scratch_rows; + pending->ext_degree = D; const size_t message_count = scratch_rows * num_lookups; cudaError_t status = cudaSetDevice(device_id); @@ -3209,10 +3724,10 @@ extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned( (num_lookups + 1) * sizeof(size_t)); if (status == cudaSuccess) status = cudaMalloc(reinterpret_cast(&pending->deltas), - height * slots * sizeof(Ext2)); + height * slots * sizeof(Ext)); if (status == cudaSuccess) status = cudaMalloc(reinterpret_cast(&pending->conjugates), - message_count * sizeof(Ext2)); + message_count * sizeof(Ext)); if (status == cudaSuccess) status = cudaMalloc(reinterpret_cast(&pending->norms), message_count * sizeof(uint64_t)); @@ -3242,14 +3757,17 @@ extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned( return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_lde_gpu_rows_partitioned( +template +int lookup_lde_gpu_rows_partitioned_impl( int device_id, void* pending_handle, const uint64_t* multiplicities, const uint64_t* args, size_t row_start, size_t rows, const uint64_t* beta, const uint64_t* gamma, uint64_t ext_w) { + constexpr size_t D = ExtOps::D; auto* pending = static_cast(pending_handle); - if (!pending || !multiplicities || !rows || !beta || !gamma || - (pending->args_width && !args) || rows > pending->scratch_rows || - row_start > pending->height || rows > pending->height - row_start) { + if (!pending || pending->ext_degree != D || !multiplicities || !rows || + !beta || !gamma || (pending->args_width && !args) || + rows > pending->scratch_rows || row_start > pending->height || + rows > pending->height - row_start) { return static_cast(cudaErrorInvalidValue); } const size_t messages = rows * pending->num_lookups; @@ -3264,63 +3782,73 @@ extern "C" int multi_stark_cuda_lookup_lde_gpu_rows_partitioned( rows * pending->args_width * sizeof(uint64_t), cudaMemcpyHostToDevice); if (status == cudaSuccess) { - lookup_messages<<>>( - pending->conjugates, pending->norms, pending->args, - pending->arg_offsets, rows, pending->num_lookups, - pending->args_width, {beta[0], beta[1]}, {gamma[0], gamma[1]}, - ext_w); + lookup_messages_t<<>>( + reinterpret_cast(pending->conjugates), pending->norms, + pending->args, pending->arg_offsets, rows, pending->num_lookups, + pending->args_width, ExtOps::load(beta), + ExtOps::load(gamma), ext_w); status = cudaGetLastError(); } if (status == cudaSuccess) status = batch_inverse_norms(pending->norm_inverses, pending->norms, messages); if (status == cudaSuccess) { - lookup_group_deltas_batched<<slots), THREADS>>>( - pending->deltas + row_start * pending->slots, - pending->multiplicities, pending->conjugates, + lookup_group_deltas_batched_t<<slots), THREADS>>>( + reinterpret_cast(pending->deltas) + row_start * pending->slots, + pending->multiplicities, + reinterpret_cast(pending->conjugates), pending->norm_inverses, rows, pending->num_lookups, - pending->group_size, ext_w); + pending->group_size); status = cudaGetLastError(); } if (status == cudaSuccess) status = cudaStreamSynchronize(cudaStreamPerThread); return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_lde_cpu_rows_partitioned( +template +int lookup_lde_cpu_rows_partitioned_impl( int device_id, void* pending_handle, const uint64_t* deltas, size_t row_start, size_t rows) { + constexpr size_t D = ExtOps::D; auto* pending = static_cast(pending_handle); - if (!pending || !deltas || !rows || row_start > pending->height || - rows > pending->height - row_start) { + if (!pending || pending->ext_degree != D || !deltas || !rows || + row_start > pending->height || rows > pending->height - row_start) { return static_cast(cudaErrorInvalidValue); } cudaError_t status = cudaSetDevice(device_id); if (status == cudaSuccess) - status = cudaMemcpy(pending->deltas + row_start * pending->slots, - deltas, rows * pending->slots * sizeof(Ext2), - cudaMemcpyHostToDevice); + status = cudaMemcpy( + reinterpret_cast(pending->deltas) + row_start * pending->slots, + deltas, rows * pending->slots * sizeof(Ext), + cudaMemcpyHostToDevice); return static_cast(status); } -extern "C" int multi_stark_cuda_lookup_lde_finish_partitioned( +template +int lookup_lde_finish_partitioned_impl( int device_id, void* pending_handle, void** output_handle, uint64_t* total, const MultiStarkNttPlan* plan) { + constexpr size_t D = ExtOps::D; auto* pending = static_cast(pending_handle); - if (!pending || !output_handle || !total || (!plan || !plan->shift_powers)) { + if (!pending || pending->ext_degree != D || !output_handle || !total || + (!plan || !plan->shift_powers)) { return static_cast(cudaErrorInvalidValue); } *output_handle = nullptr; cudaError_t status = cudaSetDevice(device_id); const size_t count = pending->height * pending->slots; if (status == cudaSuccess) - status = exclusive_scan_ext2(reinterpret_cast(pending->lde->values), - pending->deltas, count); + status = exclusive_scan_ext_t( + reinterpret_cast(pending->lde->values), + reinterpret_cast(pending->deltas), count); if (status == cudaSuccess) - status = cudaMemcpy(total, pending->lde->values + 2 * (count - 1), - sizeof(Ext2), cudaMemcpyDeviceToHost); + status = cudaMemcpy(total, pending->lde->values + D * (count - 1), + sizeof(Ext), cudaMemcpyDeviceToHost); if (status == cudaSuccess) - status = cudaMemcpy(total + 2, pending->deltas + count - 1, - sizeof(Ext2), cudaMemcpyDeviceToHost); + status = cudaMemcpy( + total + D, + reinterpret_cast(pending->deltas) + (count - 1), + sizeof(Ext), cudaMemcpyDeviceToHost); if (status == cudaSuccess) status = coset_lde(device_id, pending->lde->values, pending->lde->values, @@ -3334,6 +3862,130 @@ extern "C" int multi_stark_cuda_lookup_lde_finish_partitioned( return static_cast(status); } +template +int reduced_add_impl(int device_id,void* reduced,const void* lde_handle,size_t height, + const uint64_t* inv_denoms,const uint64_t* alpha_powers,const uint64_t* reduced_y,const uint64_t* alpha_offset,uint64_t ext_w){ + constexpr size_t D = ExtOps::D; + if(!reduced||!lde_handle||!inv_denoms||!alpha_powers||!reduced_y||!alpha_offset)return static_cast(cudaErrorInvalidValue); + auto* r=static_cast(reduced);auto* l=static_cast(lde_handle); + if(r->ext_degree!=D||height!=r->height||height>l->height)return static_cast(cudaErrorInvalidValue); + cudaError_t status=cudaSetDevice(device_id);size_t ib=height*sizeof(Ext),ab=l->width*sizeof(Ext),needed=ib+ab; + if(status==cudaSuccess&&r->scratch_bytesscratch)status=cudaFree(r->scratch);r->scratch=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&r->scratch),needed);if(status==cudaSuccess)r->scratch_bytes=needed;} + uint8_t* mem=r->scratch;if(status==cudaSuccess)status=cudaMemcpy(mem,inv_denoms,ib,cudaMemcpyHostToDevice);if(status==cudaSuccess)status=cudaMemcpy(mem+ib,alpha_powers,ab,cudaMemcpyHostToDevice); + if(status==cudaSuccess){accumulate_reduced_opening_t<<>>(reinterpret_cast(r->values),l,reinterpret_cast(mem),reinterpret_cast(mem+ib),height,ExtOps::load(reduced_y),ExtOps::load(alpha_offset),ext_w);status=cudaGetLastError();}return static_cast(status); +} +} // namespace + +extern "C" int multi_stark_cuda_lookup_trace(int device_id,uint64_t* output,uint64_t* total, + const uint64_t* multiplicities,const uint64_t* args,const size_t* arg_offsets, + size_t height,size_t num_lookups,size_t args_width,size_t group_size, + const uint64_t* beta,const uint64_t* gamma,uint64_t ext_w){ + return lookup_trace_impl(device_id,output,total,multiplicities,args,arg_offsets,height,num_lookups,args_width,group_size,beta,gamma,ext_w); +} + +extern "C" int multi_stark_cuda_lookup_trace_ext3(int device_id,uint64_t* output,uint64_t* total, + const uint64_t* multiplicities,const uint64_t* args,const size_t* arg_offsets, + size_t height,size_t num_lookups,size_t args_width,size_t group_size, + const uint64_t* beta,const uint64_t* gamma){ + return lookup_trace_impl(device_id,output,total,multiplicities,args,arg_offsets,height,num_lookups,args_width,group_size,beta,gamma,0); +} + +extern "C" int multi_stark_cuda_lookup_graph_lde(int device_id,void** output_handle,uint64_t* total, + const void* nodes,size_t node_count,size_t slot_count,const void* lookups,size_t lookup_count, + const uint32_t* lookup_args,size_t lookup_arg_count,const void* preprocessed_handle, + const void* main_handle,size_t group_size,const uint64_t* beta,const uint64_t* gamma, + uint64_t ext_w,size_t added_bits,const MultiStarkNttPlan* plan){ + return lookup_graph_lde_impl(device_id,output_handle,total,nodes,node_count,slot_count,lookups,lookup_count,lookup_args,lookup_arg_count,preprocessed_handle,main_handle,group_size,beta,gamma,ext_w,added_bits,plan); +} + +extern "C" int multi_stark_cuda_lookup_graph_lde_ext3(int device_id,void** output_handle,uint64_t* total, + const void* nodes,size_t node_count,size_t slot_count,const void* lookups,size_t lookup_count, + const uint32_t* lookup_args,size_t lookup_arg_count,const void* preprocessed_handle, + const void* main_handle,size_t group_size,const uint64_t* beta,const uint64_t* gamma, + size_t added_bits,const MultiStarkNttPlan* plan){ + return lookup_graph_lde_impl(device_id,output_handle,total,nodes,node_count,slot_count,lookups,lookup_count,lookup_args,lookup_arg_count,preprocessed_handle,main_handle,group_size,beta,gamma,0,added_bits,plan); +} + +extern "C" int multi_stark_cuda_lookup_lde(int device_id,void** output_handle,uint64_t* total, + const uint64_t* multiplicities,const uint64_t* args,const size_t* arg_offsets, + size_t height,size_t num_lookups,size_t args_width,size_t group_size, + const uint64_t* beta,const uint64_t* gamma,uint64_t ext_w,size_t added_bits, + const MultiStarkNttPlan* plan){ + return lookup_lde_impl(device_id,output_handle,total,multiplicities,args,arg_offsets,height,num_lookups,args_width,group_size,beta,gamma,ext_w,added_bits,plan); +} + +extern "C" int multi_stark_cuda_lookup_lde_ext3(int device_id,void** output_handle,uint64_t* total, + const uint64_t* multiplicities,const uint64_t* args,const size_t* arg_offsets, + size_t height,size_t num_lookups,size_t args_width,size_t group_size, + const uint64_t* beta,const uint64_t* gamma,size_t added_bits, + const MultiStarkNttPlan* plan){ + return lookup_lde_impl(device_id,output_handle,total,multiplicities,args,arg_offsets,height,num_lookups,args_width,group_size,beta,gamma,0,added_bits,plan); +} + +extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned( + int device_id, void** pending_handle, const size_t* arg_offsets, + size_t height, size_t num_lookups, size_t args_width, + size_t group_size, size_t added_bits) { + return lookup_lde_begin_partitioned_impl( + device_id, pending_handle, arg_offsets, height, num_lookups, + args_width, group_size, added_bits); +} + +extern "C" int multi_stark_cuda_lookup_lde_begin_partitioned_ext3( + int device_id, void** pending_handle, const size_t* arg_offsets, + size_t height, size_t num_lookups, size_t args_width, + size_t group_size, size_t added_bits) { + return lookup_lde_begin_partitioned_impl( + device_id, pending_handle, arg_offsets, height, num_lookups, + args_width, group_size, added_bits); +} + +extern "C" int multi_stark_cuda_lookup_lde_gpu_rows_partitioned( + int device_id, void* pending_handle, const uint64_t* multiplicities, + const uint64_t* args, size_t row_start, size_t rows, + const uint64_t* beta, const uint64_t* gamma, uint64_t ext_w) { + return lookup_lde_gpu_rows_partitioned_impl( + device_id, pending_handle, multiplicities, args, row_start, rows, + beta, gamma, ext_w); +} + +extern "C" int multi_stark_cuda_lookup_lde_gpu_rows_partitioned_ext3( + int device_id, void* pending_handle, const uint64_t* multiplicities, + const uint64_t* args, size_t row_start, size_t rows, + const uint64_t* beta, const uint64_t* gamma) { + return lookup_lde_gpu_rows_partitioned_impl( + device_id, pending_handle, multiplicities, args, row_start, rows, + beta, gamma, 0); +} + +extern "C" int multi_stark_cuda_lookup_lde_cpu_rows_partitioned( + int device_id, void* pending_handle, const uint64_t* deltas, + size_t row_start, size_t rows) { + return lookup_lde_cpu_rows_partitioned_impl( + device_id, pending_handle, deltas, row_start, rows); +} + +extern "C" int multi_stark_cuda_lookup_lde_cpu_rows_partitioned_ext3( + int device_id, void* pending_handle, const uint64_t* deltas, + size_t row_start, size_t rows) { + return lookup_lde_cpu_rows_partitioned_impl( + device_id, pending_handle, deltas, row_start, rows); +} + +extern "C" int multi_stark_cuda_lookup_lde_finish_partitioned( + int device_id, void* pending_handle, void** output_handle, uint64_t* total, + const MultiStarkNttPlan* plan) { + return lookup_lde_finish_partitioned_impl( + device_id, pending_handle, output_handle, total, plan); +} + +extern "C" int multi_stark_cuda_lookup_lde_finish_partitioned_ext3( + int device_id, void* pending_handle, void** output_handle, uint64_t* total, + const MultiStarkNttPlan* plan) { + return lookup_lde_finish_partitioned_impl( + device_id, pending_handle, output_handle, total, plan); +} + extern "C" int multi_stark_cuda_lookup_lde_cancel_partitioned( int device_id, void* pending_handle) { const cudaError_t status = cudaSetDevice(device_id); @@ -3343,16 +3995,62 @@ extern "C" int multi_stark_cuda_lookup_lde_cancel_partitioned( extern "C" int multi_stark_cuda_reduced_add(int device_id,void* reduced,const void* lde_handle,size_t height, const uint64_t* inv_denoms,const uint64_t* alpha_powers,const uint64_t* reduced_y,const uint64_t* alpha_offset,uint64_t ext_w){ - if(!reduced||!lde_handle||!inv_denoms||!alpha_powers||!reduced_y||!alpha_offset)return static_cast(cudaErrorInvalidValue); - auto* r=static_cast(reduced);auto* l=static_cast(lde_handle);if(height!=r->height||height>l->height)return static_cast(cudaErrorInvalidValue); - cudaError_t status=cudaSetDevice(device_id);size_t ib=height*sizeof(Ext2),ab=l->width*sizeof(Ext2),needed=ib+ab; - if(status==cudaSuccess&&r->scratch_bytesscratch)status=cudaFree(r->scratch);r->scratch=nullptr;if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&r->scratch),needed);if(status==cudaSuccess)r->scratch_bytes=needed;} - uint8_t* mem=r->scratch;if(status==cudaSuccess)status=cudaMemcpy(mem,inv_denoms,ib,cudaMemcpyHostToDevice);if(status==cudaSuccess)status=cudaMemcpy(mem+ib,alpha_powers,ab,cudaMemcpyHostToDevice); - if(status==cudaSuccess){accumulate_reduced_opening<<>>(r->values,l,reinterpret_cast(mem),reinterpret_cast(mem+ib),height,{reduced_y[0],reduced_y[1]},{alpha_offset[0],alpha_offset[1]},ext_w);status=cudaGetLastError();}return static_cast(status); + return reduced_add_impl(device_id,reduced,lde_handle,height,inv_denoms,alpha_powers,reduced_y,alpha_offset,ext_w); +} + +extern "C" int multi_stark_cuda_reduced_add_ext3(int device_id,void* reduced,const void* lde_handle,size_t height, + const uint64_t* inv_denoms,const uint64_t* alpha_powers,const uint64_t* reduced_y,const uint64_t* alpha_offset){ + return reduced_add_impl(device_id,reduced,lde_handle,height,inv_denoms,alpha_powers,reduced_y,alpha_offset,0); +} + +extern "C" int multi_stark_cuda_reduced_copy(int device_id,const void* handle,uint64_t* output){ + if(!handle||!output)return static_cast(cudaErrorInvalidValue); + auto* r=static_cast(handle); + cudaError_t status=cudaSetDevice(device_id); + if(status==cudaSuccess)status=cudaMemcpy(output,r->values,r->height*r->ext_degree*sizeof(uint64_t),cudaMemcpyDeviceToHost); + return static_cast(status); } -extern "C" int multi_stark_cuda_reduced_copy(int device_id,const void* handle,uint64_t* output){if(!handle||!output)return static_cast(cudaErrorInvalidValue);auto* r=static_cast(handle);cudaError_t status=cudaSetDevice(device_id);if(status==cudaSuccess)status=cudaMemcpy(output,r->values,r->height*sizeof(Ext2),cudaMemcpyDeviceToHost);return static_cast(status);} extern "C" int multi_stark_cuda_reduced_destroy(int device_id,void* handle){cudaError_t status=cudaSetDevice(device_id);if(status==cudaSuccess)delete static_cast(handle);return static_cast(status);} +extern "C" int multi_stark_cuda_ext3_ops( + int device_id, uint64_t* sums, uint64_t* differences, uint64_t* products, + uint64_t* inverses, const uint64_t* left, const uint64_t* right, + size_t len) { + if (sums == nullptr || differences == nullptr || products == nullptr || + inverses == nullptr || left == nullptr || right == nullptr || len == 0 || + !product_fits(len, static_cast(3))) { + return static_cast(cudaErrorInvalidValue); + } + cudaError_t status = cudaSetDevice(device_id); + if (status != cudaSuccess) { + return static_cast(status); + } + const size_t words = len * 3; + DeviceBuffer device_left, device_right, device_sums, device_differences, + device_products, device_inverses; + status = copy_to_device(device_left, left, words); + if (status == cudaSuccess) status = copy_to_device(device_right, right, words); + if (status == cudaSuccess) status = device_sums.allocate(words); + if (status == cudaSuccess) status = device_differences.allocate(words); + if (status == cudaSuccess) status = device_products.allocate(words); + if (status == cudaSuccess) status = device_inverses.allocate(words); + if (status == cudaSuccess) { + ext3_ops_kernel<<>>( + reinterpret_cast(device_sums.get()), + reinterpret_cast(device_differences.get()), + reinterpret_cast(device_products.get()), + reinterpret_cast(device_inverses.get()), + reinterpret_cast(device_left.get()), + reinterpret_cast(device_right.get()), len); + status = cudaGetLastError(); + } + if (status == cudaSuccess) status = copy_to_host(sums, device_sums, words); + if (status == cudaSuccess) status = copy_to_host(differences, device_differences, words); + if (status == cudaSuccess) status = copy_to_host(products, device_products, words); + if (status == cudaSuccess) status = copy_to_host(inverses, device_inverses, words); + return static_cast(status); +} + extern "C" int multi_stark_cuda_lde_destroy(int device_id, void* handle) { if (handle == nullptr) { return static_cast(cudaSuccess); @@ -3503,9 +4201,10 @@ extern "C" int multi_stark_cuda_goldilocks_ops( return static_cast(status); } -extern "C" int multi_stark_cuda_blake3_hash_rows( +namespace { +int blake3_hash_rows_impl( int device_id, uint8_t* digests, const uint8_t* messages, - size_t message_bytes, size_t message_count) { + size_t message_bytes, size_t message_count, bool domain_v6) { if (digests == nullptr || messages == nullptr || message_count == 0 || message_bytes == 0 || message_bytes > 32 * 1024 || !product_fits(message_bytes, message_count) || @@ -3533,7 +4232,7 @@ extern "C" int multi_stark_cuda_blake3_hash_rows( status = launch_blake3_rows( reinterpret_cast(device_digests.get()), reinterpret_cast(device_messages.get()), - message_bytes, message_count); + message_bytes, message_count, domain_v6); } if (status == cudaSuccess) { status = cudaMemcpy(digests, device_digests.get(), output_bytes, @@ -3541,6 +4240,21 @@ extern "C" int multi_stark_cuda_blake3_hash_rows( } return static_cast(status); } +} // namespace + +extern "C" int multi_stark_cuda_blake3_hash_rows( + int device_id, uint8_t* digests, const uint8_t* messages, + size_t message_bytes, size_t message_count) { + return blake3_hash_rows_impl(device_id, digests, messages, message_bytes, + message_count, false); +} + +extern "C" int multi_stark_cuda_blake3_hash_rows_v6( + int device_id, uint8_t* digests, const uint8_t* messages, + size_t message_bytes, size_t message_count) { + return blake3_hash_rows_impl(device_id, digests, messages, message_bytes, + message_count, true); +} extern "C" int multi_stark_cuda_blake3_merkle_root( int device_id, uint8_t* root, const uint8_t* rows, size_t row_bytes, @@ -3876,12 +4590,14 @@ extern "C" int multi_stark_cuda_mixed_merkle_destroy(int device_id, return static_cast(cudaGetLastError()); } -extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( +namespace { +int mixed_merkle_create_hybrid_impl( int device_id, void** handle, uint8_t* root, const void* const* lde_handles, const uint64_t* const* host_values, const size_t* widths, const size_t* heights, size_t matrix_count, const uint8_t* const* host_digest_groups, - const size_t* host_digest_heights, size_t host_digest_group_count) { + const size_t* host_digest_heights, size_t host_digest_group_count, + bool domain_v6) { if (handle == nullptr || root == nullptr || matrix_count == 0 || lde_handles == nullptr || host_values == nullptr || widths == nullptr || heights == nullptr || @@ -3968,7 +4684,8 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( } } return hash_partitioned_lde_group(output, lde_handles, host_values, - widths, heights, matrix_count, height); + widths, heights, matrix_count, height, + domain_v6); }; if (status == cudaSuccess) { status = hash_group(tree->digests, max_height); @@ -3982,7 +4699,7 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( count /= 2; uint8_t* next = tree->digests + offset; status = launch_blake3_digest_pairs(next, current, current, count, - true); + true, domain_v6); bool inject = false; for (size_t index = 0; index < matrix_count; ++index) { @@ -3996,7 +4713,7 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( status = launch_blake3_digest_pairs( next, next, reinterpret_cast(injected_digests.get()), - count, false); + count, false, domain_v6); } } if (status == cudaSuccess) { @@ -4011,10 +4728,11 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( return static_cast(cudaSuccess); } -extern "C" int multi_stark_cuda_hash_hybrid_height_group( +int hash_hybrid_height_group_impl( int device_id, uint8_t* host_digests, const void* const* lde_handles, const uint64_t* const* host_values, const size_t* widths, - const size_t* heights, size_t matrix_count, size_t height) { + const size_t* heights, size_t matrix_count, size_t height, + bool domain_v6) { if (device_id < 0 || host_digests == nullptr || lde_handles == nullptr || host_values == nullptr || widths == nullptr || heights == nullptr || matrix_count == 0 || !is_power_of_two(height) || height > SIZE_MAX / 4) { @@ -4044,7 +4762,7 @@ extern "C" int multi_stark_cuda_hash_hybrid_height_group( if (status == cudaSuccess) { status = hash_partitioned_lde_group( reinterpret_cast(device_digests.get()), lde_handles, - host_values, widths, heights, matrix_count, height); + host_values, widths, heights, matrix_count, height, domain_v6); } if (status == cudaSuccess) { status = cudaMemcpy(host_digests, device_digests.get(), height * 32, @@ -4053,9 +4771,9 @@ extern "C" int multi_stark_cuda_hash_hybrid_height_group( return static_cast(status); } -extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes( +int mixed_merkle_create_from_ldes_impl( int device_id, void** handle, uint8_t* root, - const void* const* lde_handles, size_t lde_count) { + const void* const* lde_handles, size_t lde_count, bool domain_v6) { if (lde_handles == nullptr || lde_count == 0) { return static_cast(cudaErrorInvalidValue); } @@ -4081,26 +4799,107 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes( widths[index] = lde->width; heights[index] = lde->height; } - const int status = multi_stark_cuda_mixed_merkle_create_hybrid( + const int status = mixed_merkle_create_hybrid_impl( device_id, handle, root, lde_handles, host_values, widths, heights, - lde_count, nullptr, nullptr, 0); + lde_count, nullptr, nullptr, 0, domain_v6); delete[] host_values; delete[] widths; delete[] heights; return status; } -extern "C" int multi_stark_cuda_fri_merkle_create( - int device_id,void** handle,uint8_t* root,const void* codeword_handle,size_t arity){ - if(!codeword_handle||!is_power_of_two(arity))return static_cast(cudaErrorInvalidValue); - const auto* codeword=static_cast(codeword_handle); - if(codeword->width!=2||codeword->height%arity)return static_cast(cudaErrorInvalidValue); - ResidentLde view;view.values=codeword->values;view.height=codeword->height/arity;view.width=2*arity; - const void* views[1]={&view}; - const int status=multi_stark_cuda_mixed_merkle_create_from_ldes(device_id,handle,root,views,1); - view.values=nullptr; +int fri_merkle_create_impl( + int device_id, void** handle, uint8_t* root, const void* codeword_handle, + size_t arity, bool domain_v6) { + if (!codeword_handle || !is_power_of_two(arity)) { + return static_cast(cudaErrorInvalidValue); + } + const auto* codeword = static_cast(codeword_handle); + if ((codeword->width != 2 && codeword->width != 3) || + codeword->height % arity != 0) { + return static_cast(cudaErrorInvalidValue); + } + ResidentLde view; + view.values = codeword->values; + view.height = codeword->height / arity; + view.width = codeword->width * arity; + const void* views[1] = {&view}; + const int status = mixed_merkle_create_from_ldes_impl( + device_id, handle, root, views, 1, domain_v6); + view.values = nullptr; return status; } +} // namespace + +extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( + int device_id, void** handle, uint8_t* root, + const void* const* lde_handles, const uint64_t* const* host_values, + const size_t* widths, const size_t* heights, size_t matrix_count, + const uint8_t* const* host_digest_groups, + const size_t* host_digest_heights, size_t host_digest_group_count) { + return mixed_merkle_create_hybrid_impl( + device_id, handle, root, lde_handles, host_values, widths, heights, + matrix_count, host_digest_groups, host_digest_heights, + host_digest_group_count, false); +} + +extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid_v6( + int device_id, void** handle, uint8_t* root, + const void* const* lde_handles, const uint64_t* const* host_values, + const size_t* widths, const size_t* heights, size_t matrix_count, + const uint8_t* const* host_digest_groups, + const size_t* host_digest_heights, size_t host_digest_group_count) { + return mixed_merkle_create_hybrid_impl( + device_id, handle, root, lde_handles, host_values, widths, heights, + matrix_count, host_digest_groups, host_digest_heights, + host_digest_group_count, true); +} + +extern "C" int multi_stark_cuda_hash_hybrid_height_group( + int device_id, uint8_t* host_digests, const void* const* lde_handles, + const uint64_t* const* host_values, const size_t* widths, + const size_t* heights, size_t matrix_count, size_t height) { + return hash_hybrid_height_group_impl( + device_id, host_digests, lde_handles, host_values, widths, heights, + matrix_count, height, false); +} + +extern "C" int multi_stark_cuda_hash_hybrid_height_group_v6( + int device_id, uint8_t* host_digests, const void* const* lde_handles, + const uint64_t* const* host_values, const size_t* widths, + const size_t* heights, size_t matrix_count, size_t height) { + return hash_hybrid_height_group_impl( + device_id, host_digests, lde_handles, host_values, widths, heights, + matrix_count, height, true); +} + +extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes( + int device_id, void** handle, uint8_t* root, + const void* const* lde_handles, size_t lde_count) { + return mixed_merkle_create_from_ldes_impl( + device_id, handle, root, lde_handles, lde_count, false); +} + +extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes_v6( + int device_id, void** handle, uint8_t* root, + const void* const* lde_handles, size_t lde_count) { + return mixed_merkle_create_from_ldes_impl( + device_id, handle, root, lde_handles, lde_count, true); +} + +extern "C" int multi_stark_cuda_fri_merkle_create( + int device_id, void** handle, uint8_t* root, const void* codeword_handle, + size_t arity) { + return fri_merkle_create_impl(device_id, handle, root, codeword_handle, + arity, false); +} + +extern "C" int multi_stark_cuda_fri_merkle_create_v6( + int device_id, void** handle, uint8_t* root, const void* codeword_handle, + size_t arity) { + return fri_merkle_create_impl(device_id, handle, root, codeword_handle, + arity, true); +} extern "C" int multi_stark_cuda_mixed_merkle_create_from_host_matrices( int device_id, void** handle, uint8_t* root, diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index 41e7d7f..ee25bf8 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -10,12 +10,18 @@ use super::{ CudaLde, CudaMixedMerkleTree, mixed_lde_open_row, mixed_lde_open_row_at_height, mixed_lde_open_rows, mixed_lde_open_rows_at_height, }; -use crate::types::Blake3CompressionFunction; -use p3_blake3::Blake3; -use p3_symmetric::SerializingHasher; - -type CpuMmcs = - MerkleTreeMmcs, Blake3CompressionFunction, 2, 32>; +use crate::p3_adapter::domain_blake3::{Blake3Domain, DomainBlake3}; +use p3_symmetric::{CompressionFunctionFromHasher, SerializingHasher}; + +type DomainCompressionFunction = CompressionFunctionFromHasher; +type CpuMmcs = MerkleTreeMmcs< + Goldilocks, + u8, + SerializingHasher, + DomainCompressionFunction, + 2, + 32, +>; type CpuData = >::ProverData; pub(crate) type DeferredMatrix = Option<(Dimensions, std::thread::JoinHandle)>; type DeferredWorker = Option>>>; @@ -284,7 +290,7 @@ pub(crate) fn hash_cpu_height_groups( groups .into_iter() .map(|(height, matrices)| { - let hasher = SerializingHasher::new(Blake3); + let hasher = SerializingHasher::new(DomainBlake3::new(Blake3Domain::Plain)); let digests = (0..height) .into_par_iter() .map(|row| { @@ -325,6 +331,7 @@ pub(crate) fn hash_host_only_height_groups( resident: &[Option<&CudaLde>], deferred_dimensions: &[Option], prehashed_heights: &std::collections::BTreeSet, + leaf_domain: Blake3Domain, ) -> Vec<(usize, Vec<[u8; 32]>)> { assert_eq!(matrices.len(), resident.len()); assert_eq!(matrices.len(), deferred_dimensions.len()); @@ -356,7 +363,7 @@ pub(crate) fn hash_host_only_height_groups( groups.entry(height).or_default().push(index); } - let hasher = SerializingHasher::new(Blake3); + let hasher = SerializingHasher::new(DomainBlake3::new(leaf_domain)); groups .into_iter() .filter_map(|(height, indices)| { @@ -488,23 +495,77 @@ fn hybrid_open_rows>( #[derive(Clone, Debug)] pub struct CudaMmcs { cpu: CpuMmcs, + leaf_domain: Blake3Domain, device_id: i32, } impl CudaMmcs { + /// Creates a legacy `v5` plain BLAKE3 CUDA MMCS (bit-identical to stock + /// `p3_blake3::Blake3`). + pub(crate) fn new_plain(cap_height: usize, device_id: i32) -> Self { + let field_hash = SerializingHasher::new(DomainBlake3::new(Blake3Domain::Plain)); + let compress = DomainCompressionFunction::new(DomainBlake3::new(Blake3Domain::Plain)); + let cpu = CpuMmcs::new(field_hash, compress, cap_height); + Self::with_device_and_domain(cpu, Blake3Domain::Plain, device_id) + } + + /// Creates a protocol `v6` domain-separated BLAKE3 CUDA MMCS separating + /// Merkle leaf row hashes (`MerkleLeaf`) from 2-to-1 internal compressions + /// (`MerkleCompress`). + pub(crate) fn new_v6(cap_height: usize, device_id: i32) -> Self { + let field_hash = SerializingHasher::new(DomainBlake3::new(Blake3Domain::MerkleLeaf)); + let compress = + DomainCompressionFunction::new(DomainBlake3::new(Blake3Domain::MerkleCompress)); + let cpu = CpuMmcs::new(field_hash, compress, cap_height); + Self::with_device_and_domain(cpu, Blake3Domain::MerkleLeaf, device_id) + } + /// A commitment scheme resident on the given CUDA device. Every kernel /// it launches, allocation it makes and buffer it stages through belongs /// to that device, so several of these in one process can each own a /// device of their own. - pub(crate) fn with_device(cpu: CpuMmcs, device_id: i32) -> Self { + pub(crate) fn with_device_and_domain( + cpu: CpuMmcs, + leaf_domain: Blake3Domain, + device_id: i32, + ) -> Self { assert!(device_id >= 0, "CUDA device id must be non-negative"); - Self { cpu, device_id } + assert!( + matches!(leaf_domain, Blake3Domain::Plain | Blake3Domain::MerkleLeaf), + "unsupported CUDA Merkle leaf domain: {leaf_domain:?}" + ); + Self { + cpu, + leaf_domain, + device_id, + } + } + + #[cfg(test)] + pub(crate) fn with_device(cpu: CpuMmcs, device_id: i32) -> Self { + Self::with_device_and_domain(cpu, Blake3Domain::Plain, device_id) + } + + #[inline] + pub(crate) const fn leaf_domain(&self) -> Blake3Domain { + self.leaf_domain + } + + #[inline] + pub(crate) const fn is_domain_v6(&self) -> bool { + matches!(self.leaf_domain, Blake3Domain::MerkleLeaf) } } pub trait CudaCommitMmcs: Mmcs { fn cuda_device_id(&self) -> i32; + fn leaf_domain(&self) -> Blake3Domain; + + fn is_domain_v6(&self) -> bool { + matches!(self.leaf_domain(), Blake3Domain::MerkleLeaf) + } + fn hash_cuda_hybrid_height_group( &self, resident: &[Option<&CudaLde>], @@ -613,12 +674,21 @@ impl CudaCommitMmcs for CudaMmcs { self.device_id } + fn leaf_domain(&self) -> Blake3Domain { + self.leaf_domain + } + fn hash_cuda_hybrid_height_group( &self, resident: &[Option<&CudaLde>], host: &[Option<&RowMajorMatrix>], ) -> Vec<[u8; 32]> { - CudaMixedMerkleTree::hash_hybrid_height_group(self.device_id, resident, host) + CudaMixedMerkleTree::hash_hybrid_height_group_with_domain( + self.device_id, + resident, + host, + self.is_domain_v6(), + ) } fn is_cuda_resident>(&self, data: &Self::ProverData) -> bool { @@ -1093,12 +1163,14 @@ impl CudaCommitMmcs for CudaMmcs { &resident.iter().map(Option::as_ref).collect::>(), &deferred_dimensions, &std::collections::BTreeSet::new(), + self.leaf_domain, ); let retained = (0..resident.len()).map(|_| None).collect(); return self.commit_cuda_hybrid(resident, host, deferred, retained, digests); } let ldes = std::sync::Arc::new(ldes); - let tree = CudaMixedMerkleTree::from_ldes(self.device_id, &ldes); + let tree = + CudaMixedMerkleTree::from_ldes_with_domain(self.device_id, &ldes, self.is_domain_v6()); let commitment = MerkleCap::new(vec![tree.root()]); let materialize_ldes = std::sync::Arc::clone(&ldes); ( @@ -1183,12 +1255,13 @@ impl CudaCommitMmcs for CudaMmcs { .collect::>(); let resident_refs = resident.iter().map(Option::as_ref).collect::>(); let host_refs = host_matrices.iter().map(Option::as_ref).collect::>(); - let tree = CudaMixedMerkleTree::from_hybrid( + let tree = CudaMixedMerkleTree::from_hybrid_with_domain( self.device_id, &resident_refs, &host_refs, &deferred_dimensions, &host_digest_groups, + self.is_domain_v6(), ); let commitment = MerkleCap::new(vec![tree.root()]); let committed_matrices = host_matrices @@ -1285,7 +1358,11 @@ impl Mmcs for CudaMmcs { }) .collect(); let resident = std::sync::Arc::new(resident); - let tree = CudaMixedMerkleTree::from_ldes(self.device_id, &resident); + let tree = CudaMixedMerkleTree::from_ldes_with_domain( + self.device_id, + &resident, + self.is_domain_v6(), + ); let commitment = MerkleCap::new(vec![tree.root()]); let committed_matrices = std::sync::OnceLock::new(); committed_matrices @@ -1533,8 +1610,8 @@ mod tests { .map(|(i, &(height, width))| matrix(height, width, 7 * i + 1)) .collect(); let cpu = CpuMmcs::new( - SerializingHasher::new(Blake3), - Blake3CompressionFunction::new(Blake3), + SerializingHasher::new(DomainBlake3::new(Blake3Domain::Plain)), + DomainCompressionFunction::new(DomainBlake3::new(Blake3Domain::Plain)), 0, ); let (expected_commitment, expected_data) = cpu.commit(matrices.clone()); @@ -1560,8 +1637,8 @@ mod tests { fn hybrid_openings_survive_device_spill() { let matrices = vec![matrix(16, 2, 3), matrix(8, 3, 71), matrix(16, 1, 109)]; let cpu = CpuMmcs::new( - SerializingHasher::new(Blake3), - Blake3CompressionFunction::new(Blake3), + SerializingHasher::new(DomainBlake3::new(Blake3Domain::Plain)), + DomainCompressionFunction::new(DomainBlake3::new(Blake3Domain::Plain)), 0, ); let (expected_commitment, expected_data) = cpu.commit(matrices.clone()); @@ -1579,6 +1656,7 @@ mod tests { &resident.iter().map(Option::as_ref).collect::>(), &[None, None, None], &std::collections::BTreeSet::new(), + Blake3Domain::Plain, ); let retained_traces = vec![None, None, None]; let deferred_matrices = vec![None, None, None]; diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 7f78d8d..f96c94f 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -434,36 +434,64 @@ impl CudaLde { check_cuda(status, "resident trace attachment"); } + #[allow(clippy::too_many_arguments)] pub(crate) fn fri_fold( &self, next: Option<&CudaReducedOpening>, - betas: &[[Goldilocks; 2]], - beta_power: [Goldilocks; 2], + betas: &[Goldilocks], + log_arity: usize, + beta_power: &[Goldilocks], g_inv: Goldilocks, ext_w: Goldilocks, + ext_degree: usize, ) -> Self { let _span = tracing::info_span!("cuda/fri_fold").entered(); + assert!(ext_degree == 2 || ext_degree == 3); + assert_eq!(self.width, ext_degree); + assert_eq!(betas.len(), log_arity * ext_degree); + assert_eq!(beta_power.len(), ext_degree); let mut handle = core::ptr::null_mut(); - let status = unsafe { - multi_stark_cuda_fri_fold_resident( - self.device_id, - &mut handle, - self.raw_handle(), - next.map_or(core::ptr::null(), |value| value.handle.as_ptr()), - betas.as_ptr().cast(), - betas.len(), - raw_u64(beta_power[0]), - raw_u64(beta_power[1]), - raw_u64(g_inv), - raw_u64(ext_w), - ) + let next_ptr = next.map_or(core::ptr::null(), |value| { + assert_eq!(value.ext_degree, ext_degree); + value.handle.as_ptr() + }); + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_fri_fold_resident( + self.device_id, + &mut handle, + self.raw_handle(), + next_ptr, + betas.as_ptr().cast(), + log_arity, + raw_u64(beta_power[0]), + raw_u64(beta_power[1]), + raw_u64(g_inv), + raw_u64(ext_w), + ) + }, + 3 => unsafe { + multi_stark_cuda_fri_fold_resident_ext3( + self.device_id, + &mut handle, + self.raw_handle(), + next_ptr, + betas.as_ptr().cast(), + log_arity, + raw_u64(beta_power[0]), + raw_u64(beta_power[1]), + raw_u64(beta_power[2]), + raw_u64(g_inv), + ) + }, + _ => unreachable!(), }; check_cuda(status, "resident CUDA FRI fold"); Self { device_id: self.device_id, handle: NonNull::new(handle).expect("CUDA returned a null folded codeword"), - height: self.height >> betas.len(), - width: 2, + height: self.height >> log_arity, + width: ext_degree, } } /// Uploads an already bit-reversed LDE matrix into resident storage. @@ -761,7 +789,9 @@ pub(crate) fn quotient_lde_memory_upper_bound( quotient_size: usize, quotient_degree: usize, log_blowup: usize, + ext_degree: usize, ) -> (usize, usize) { + assert!(ext_degree == 2 || ext_degree == 3); let (nodes, _, slot_count) = encode_quotient_nodes(graph); let lookup_arg_count = graph .lookups @@ -781,11 +811,11 @@ pub(crate) fn quotient_lde_memory_upper_bound( 4usize .saturating_mul(quotient_size) .saturating_mul(size_of::()), - 2usize + ext_degree .saturating_mul(constraint_count) .saturating_mul(size_of::()), - 2 * size_of::(), - 2usize + ext_degree.saturating_mul(size_of::()), + ext_degree .saturating_mul(quotient_size) .saturating_mul(size_of::()), ] @@ -802,7 +832,7 @@ pub(crate) fn quotient_lde_memory_upper_bound( .checked_shl(u32::try_from(log_blowup).expect("LDE blowup exceeds u32")) .unwrap_or(usize::MAX); let output_bytes = lde_height - .saturating_mul(2) + .saturating_mul(ext_degree) .saturating_mul(quotient_degree) .saturating_mul(size_of::()); (output_bytes, allocation_bytes.saturating_add(scratch_bytes)) @@ -947,7 +977,9 @@ pub(crate) fn lookup_graph_lde_memory_upper_bound( main_width: usize, group_size: usize, log_blowup: usize, + ext_degree: usize, ) -> Option<(usize, usize)> { + assert!(ext_degree == 2 || ext_degree == 3); let (nodes, slot_count, lookups, args) = encode_lookup_nodes(graph)?; let lookup_count = lookups.len(); let groups = lookup_count.div_ceil(group_size.max(1)); @@ -956,7 +988,7 @@ pub(crate) fn lookup_graph_lde_memory_upper_bound( .unwrap_or(usize::MAX); let output_bytes = extended_height .saturating_mul(groups) - .saturating_mul(2 * size_of::()); + .saturating_mul(ext_degree * size_of::()); const LOOKUP_ROWS_PER_CHUNK: usize = 1 << 16; let chunk_rows = height.min(LOOKUP_ROWS_PER_CHUNK); @@ -972,11 +1004,11 @@ pub(crate) fn lookup_graph_lde_memory_upper_bound( .into_iter() .map(align8) .sum::(); - // Per message: conjugate Ext2, norm, inverse norm, multiplicity. - let message_bytes = message_count.saturating_mul(5 * size_of::()); + // Per message: adjugate (ext_degree words), norm, inverse norm, multiplicity. + let message_bytes = message_count.saturating_mul((ext_degree + 3) * size_of::()); let delta_bytes = height .saturating_mul(groups) - .saturating_mul(2 * size_of::()); + .saturating_mul(ext_degree * size_of::()); let shared_tile = (48 * 1024) / slot_count.saturating_mul(size_of::()).max(1); let scratch_bytes = if shared_tile < 32 { chunk_rows @@ -1067,8 +1099,9 @@ pub(crate) fn quotient_values_resident( publics: &[Goldilocks], selectors: CudaCosetSelectors, alpha: &[Goldilocks], - delta: &[Goldilocks; 2], + delta: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, quotient_size: usize, next_step: usize, group_size: usize, @@ -1077,8 +1110,10 @@ pub(crate) fn quotient_values_resident( quotient_graph_supported(graph), "the CUDA quotient evaluator needs a constraint graph with at least one node" ); + assert!(ext_degree == 2 || ext_degree == 3); assert!((1..=8).contains(&group_size)); - assert!(publics.len() >= 4); + assert!(publics.len() >= 2 * ext_degree); + assert_eq!(delta.len(), ext_degree); assert!(next_step.is_power_of_two()); assert!(next_step <= quotient_size); let (nodes, slots, slot_count) = encode_quotient_nodes(graph); @@ -1099,49 +1134,84 @@ pub(crate) fn quotient_values_resident( } }) .collect(); - let constraint_count = alpha.len() / 2; + let constraint_count = alpha.len() / ext_degree; let expected_constraints = roots.len() + if lookups.is_empty() { - 2 + ext_degree } else { - 2 * lookups.len().div_ceil(group_size) + ext_degree * lookups.len().div_ceil(group_size) }; - assert_eq!(alpha.len(), 2 * expected_constraints); - let mut output = Goldilocks::zero_vec(2 * quotient_size); - let status = unsafe { - multi_stark_cuda_quotient_values( - main.device_id, - output.as_mut_ptr().cast(), - nodes.as_ptr().cast(), - nodes.len(), - slot_count, - roots.as_ptr(), - roots.len(), - lookups.as_ptr().cast(), - lookups.len(), - args.as_ptr(), - args.len(), - group_size, - preprocessed.map_or(core::ptr::null(), CudaLde::raw_handle), - main.raw_handle(), - stage2.raw_handle(), - publics.as_ptr().cast(), - publics.len(), - raw_u64(selectors.coset_shift), - raw_u64(selectors.coset_generator), - raw_u64(selectors.trace_last), - raw_u64(selectors.vanishing_start), - raw_u64(selectors.vanishing_step), - alpha.as_ptr().cast(), - constraint_count, - delta.as_ptr().cast(), - raw_u64(ext_w), - quotient_size, - next_step, - ) + assert_eq!(alpha.len(), ext_degree * expected_constraints); + let mut output = Goldilocks::zero_vec(ext_degree * quotient_size); + let preprocessed_ptr = preprocessed.map_or(core::ptr::null(), CudaLde::raw_handle); + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_quotient_values( + main.device_id, + output.as_mut_ptr().cast(), + nodes.as_ptr().cast(), + nodes.len(), + slot_count, + roots.as_ptr(), + roots.len(), + lookups.as_ptr().cast(), + lookups.len(), + args.as_ptr(), + args.len(), + group_size, + preprocessed_ptr, + main.raw_handle(), + stage2.raw_handle(), + publics.as_ptr().cast(), + publics.len(), + raw_u64(selectors.coset_shift), + raw_u64(selectors.coset_generator), + raw_u64(selectors.trace_last), + raw_u64(selectors.vanishing_start), + raw_u64(selectors.vanishing_step), + alpha.as_ptr().cast(), + constraint_count, + delta.as_ptr().cast(), + raw_u64(ext_w), + quotient_size, + next_step, + ) + }, + 3 => unsafe { + multi_stark_cuda_quotient_values_ext3( + main.device_id, + output.as_mut_ptr().cast(), + nodes.as_ptr().cast(), + nodes.len(), + slot_count, + roots.as_ptr(), + roots.len(), + lookups.as_ptr().cast(), + lookups.len(), + args.as_ptr(), + args.len(), + group_size, + preprocessed_ptr, + main.raw_handle(), + stage2.raw_handle(), + publics.as_ptr().cast(), + publics.len(), + raw_u64(selectors.coset_shift), + raw_u64(selectors.coset_generator), + raw_u64(selectors.trace_last), + raw_u64(selectors.vanishing_start), + raw_u64(selectors.vanishing_step), + alpha.as_ptr().cast(), + constraint_count, + delta.as_ptr().cast(), + quotient_size, + next_step, + ) + }, + _ => unreachable!(), }; check_cuda(status, "resident quotient evaluation"); - RowMajorMatrix::new(output, 2) + RowMajorMatrix::new(output, ext_degree) } /// Evaluate a quotient and carry it through coefficient slicing and the @@ -1158,8 +1228,9 @@ pub(crate) fn quotient_lde_mixed( publics: &[Goldilocks], selectors: CudaCosetSelectors, alpha: &[Goldilocks], - delta: &[Goldilocks; 2], + delta: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, quotient_size: usize, next_step: usize, group_size: usize, @@ -1185,6 +1256,7 @@ pub(crate) fn quotient_lde_mixed( alpha, delta, ext_w, + ext_degree, quotient_size, next_step, group_size, @@ -1203,8 +1275,9 @@ fn quotient_lde_sources( publics: &[Goldilocks], selectors: CudaCosetSelectors, alpha: &[Goldilocks], - delta: &[Goldilocks; 2], + delta: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, quotient_size: usize, next_step: usize, group_size: usize, @@ -1215,8 +1288,10 @@ fn quotient_lde_sources( quotient_graph_supported(graph), "the CUDA quotient evaluator needs a constraint graph with at least one node" ); + assert!(ext_degree == 2 || ext_degree == 3); assert!((1..=8).contains(&group_size)); - assert!(publics.len() >= 4); + assert!(publics.len() >= 2 * ext_degree); + assert_eq!(delta.len(), ext_degree); assert!(next_step.is_power_of_two()); assert!(next_step <= quotient_size); assert!(quotient_degree.is_power_of_two()); @@ -1239,18 +1314,18 @@ fn quotient_lde_sources( } }) .collect(); - let constraint_count = alpha.len() / 2; + let constraint_count = alpha.len() / ext_degree; let expected_constraints = roots.len() + if lookups.is_empty() { - 2 + ext_degree } else { - 2 * lookups.len().div_ceil(group_size) + ext_degree * lookups.len().div_ceil(group_size) }; - assert_eq!(alpha.len(), 2 * expected_constraints); + assert_eq!(alpha.len(), ext_degree * expected_constraints); let trace_height = quotient_size / quotient_degree; let lde_height = trace_height << log_blowup; - let quotient_plan = dft.forward_plan(quotient_size, 2); - let lde_plan = dft.forward_plan(lde_height, 2 * quotient_degree); + let quotient_plan = dft.forward_plan(quotient_size, ext_degree); + let lde_plan = dft.forward_plan(lde_height, ext_degree * quotient_degree); let height_inverse = Goldilocks::ONE.div_2exp_u64(log2_strict_usize(quotient_size) as u64); let weight_step = Goldilocks::GENERATOR.exp_u64(trace_height as u64).inverse(); let weights: Vec<_> = weight_step @@ -1282,10 +1357,8 @@ fn quotient_lde_sources( let (stage2_handle, stage2_host, stage2_height, stage2_width) = source_parts(Some(stage2)); let mixed = !preprocessed_host.is_null() || !main_host.is_null() || !stage2_host.is_null(); let mut handle = core::ptr::null_mut(); - let status = if mixed { - // SAFETY: every host matrix and resident handle remains borrowed for - // this synchronous call. The returned LDE owns its device storage. - unsafe { + let status = match (mixed, ext_degree) { + (true, 2) => unsafe { multi_stark_cuda_quotient_lde_mixed( dft.device_id, &mut handle, @@ -1330,11 +1403,53 @@ fn quotient_lde_sources( lde_plan.raw(), weights.as_ptr().cast(), ) - } - } else { - // SAFETY: all resident handles and input slices remain live for this - // synchronous call. The returned LDE owns its device storage. - unsafe { + }, + (true, 3) => unsafe { + multi_stark_cuda_quotient_lde_mixed_ext3( + dft.device_id, + &mut handle, + nodes.as_ptr().cast(), + nodes.len(), + slot_count, + roots.as_ptr(), + roots.len(), + lookups.as_ptr().cast(), + lookups.len(), + args.as_ptr(), + args.len(), + group_size, + preprocessed_handle, + preprocessed_host, + preprocessed_height, + preprocessed_width, + main_handle, + main_host, + main_height, + main_width, + stage2_handle, + stage2_host, + stage2_height, + stage2_width, + publics.as_ptr().cast(), + publics.len(), + raw_u64(selectors.coset_shift), + raw_u64(selectors.coset_generator), + raw_u64(selectors.trace_last), + raw_u64(selectors.vanishing_start), + raw_u64(selectors.vanishing_step), + alpha.as_ptr().cast(), + constraint_count, + delta.as_ptr().cast(), + quotient_size, + next_step, + quotient_degree, + log_blowup, + quotient_plan.raw(), + lde_plan.raw(), + weights.as_ptr().cast(), + ) + }, + (false, 2) => unsafe { multi_stark_cuda_quotient_lde( dft.device_id, &mut handle, @@ -1370,14 +1485,51 @@ fn quotient_lde_sources( lde_plan.raw(), weights.as_ptr().cast(), ) - } + }, + (false, 3) => unsafe { + multi_stark_cuda_quotient_lde_ext3( + dft.device_id, + &mut handle, + nodes.as_ptr().cast(), + nodes.len(), + slot_count, + roots.as_ptr(), + roots.len(), + lookups.as_ptr().cast(), + lookups.len(), + args.as_ptr(), + args.len(), + group_size, + preprocessed_handle, + main_handle, + stage2_handle, + publics.as_ptr().cast(), + publics.len(), + raw_u64(selectors.coset_shift), + raw_u64(selectors.coset_generator), + raw_u64(selectors.trace_last), + raw_u64(selectors.vanishing_start), + raw_u64(selectors.vanishing_step), + alpha.as_ptr().cast(), + constraint_count, + delta.as_ptr().cast(), + quotient_size, + next_step, + quotient_degree, + log_blowup, + quotient_plan.raw(), + lde_plan.raw(), + weights.as_ptr().cast(), + ) + }, + _ => unreachable!(), }; check_cuda(status, "CUDA quotient LDE"); CudaLde { device_id: dft.device_id, handle: NonNull::new(handle).expect("CUDA returned a null quotient LDE"), height: lde_height, - width: 2 * quotient_degree, + width: ext_degree * quotient_degree, } } @@ -1514,31 +1666,61 @@ pub(crate) struct CudaReducedOpening { device_id: i32, handle: NonNull, height: usize, + ext_degree: usize, } impl CudaReducedOpening { + #[cfg(test)] pub(crate) fn new(device_id: i32, height: usize) -> Self { + Self::new_with_degree(device_id, height, 2) + } + + pub(crate) fn new_with_degree(device_id: i32, height: usize, ext_degree: usize) -> Self { + assert!(ext_degree == 2 || ext_degree == 3); let mut handle = core::ptr::null_mut(); - let status = unsafe { multi_stark_cuda_reduced_create(device_id, &mut handle, height) }; + let status = match ext_degree { + 2 => unsafe { multi_stark_cuda_reduced_create(device_id, &mut handle, height) }, + 3 => unsafe { multi_stark_cuda_reduced_create_ext3(device_id, &mut handle, height) }, + _ => unreachable!(), + }; check_cuda(status, "reduced opening allocation"); Self { device_id, handle: NonNull::new(handle).unwrap(), height, + ext_degree, } } + pub(crate) const fn height(&self) -> usize { self.height } + #[cfg(test)] pub(crate) fn add_host(&mut self, values: &[[Goldilocks; 2]]) { - assert_eq!(values.len(), self.height); - let status = unsafe { - multi_stark_cuda_reduced_add_host( - self.device_id, - self.handle.as_ptr(), - values.as_ptr().cast(), - values.len(), - ) + assert_eq!(self.ext_degree, 2); + self.add_host_flat(values.as_flattened()); + } + + pub(crate) fn add_host_flat(&mut self, values: &[Goldilocks]) { + assert_eq!(values.len(), self.height * self.ext_degree); + let status = match self.ext_degree { + 2 => unsafe { + multi_stark_cuda_reduced_add_host( + self.device_id, + self.handle.as_ptr(), + values.as_ptr().cast(), + self.height, + ) + }, + 3 => unsafe { + multi_stark_cuda_reduced_add_host_ext3( + self.device_id, + self.handle.as_ptr(), + values.as_ptr().cast(), + self.height, + ) + }, + _ => unreachable!(), }; check_cuda(status, "host reduced-opening accumulation") } @@ -1552,6 +1734,7 @@ impl CudaReducedOpening { offset: [Goldilocks; 2], ext_w: Goldilocks, ) { + assert_eq!(self.ext_degree, 2); assert_eq!(inv.len(), self.height); assert_eq!(alpha.len(), lde.width()); let status = unsafe { @@ -1571,6 +1754,7 @@ impl CudaReducedOpening { } #[cfg(test)] pub(crate) fn to_host(&self) -> Vec<[Goldilocks; 2]> { + assert_eq!(self.ext_degree, 2); let mut out = vec![[Goldilocks::ZERO; 2]; self.height]; let status = unsafe { multi_stark_cuda_reduced_copy( @@ -1592,7 +1776,7 @@ impl CudaReducedOpening { device_id: self.device_id, handle: NonNull::new(handle).unwrap(), height: self.height, - width: 2, + width: self.ext_degree, } } } @@ -1614,6 +1798,16 @@ pub(crate) struct CudaInterpolationTask { pub(crate) scale1: u64, } #[repr(C)] +pub(crate) struct CudaInterpolationTaskExt3 { + pub(crate) lde: *const c_void, + pub(crate) height: usize, + pub(crate) inv_offset: usize, + pub(crate) output_offset: usize, + pub(crate) scale0: u64, + pub(crate) scale1: u64, + pub(crate) scale2: u64, +} +#[repr(C)] pub(crate) struct CudaReductionTask { pub(crate) reduced: *mut c_void, pub(crate) lde: *const c_void, @@ -1624,56 +1818,196 @@ pub(crate) struct CudaReductionTask { pub(crate) offset0: u64, pub(crate) offset1: u64, } +#[repr(C)] +pub(crate) struct CudaReductionTaskExt3 { + pub(crate) reduced: *mut c_void, + pub(crate) lde: *const c_void, + pub(crate) height: usize, + pub(crate) inv_offset: usize, + pub(crate) y0: u64, + pub(crate) y1: u64, + pub(crate) y2: u64, + pub(crate) offset0: u64, + pub(crate) offset1: u64, + pub(crate) offset2: u64, +} + +pub(crate) enum CudaInterpolationTasks { + Ext2(Vec), + Ext3(Vec), +} +impl CudaInterpolationTasks { + pub(crate) fn new(ext_degree: usize) -> Self { + match ext_degree { + 2 => Self::Ext2(Vec::new()), + 3 => Self::Ext3(Vec::new()), + _ => panic!("CUDA supports extension degrees 2 and 3"), + } + } + pub(crate) fn push( + &mut self, + lde: &CudaLde, + height: usize, + inv_offset: usize, + output_offset: usize, + scale: &[Goldilocks], + ) { + match self { + Self::Ext2(tasks) => { + assert_eq!(scale.len(), 2); + tasks.push(lde.interpolation_task( + height, + inv_offset, + output_offset, + [scale[0], scale[1]], + )); + } + Self::Ext3(tasks) => { + assert_eq!(scale.len(), 3); + tasks.push(lde.interpolation_task_ext3( + height, + inv_offset, + output_offset, + [scale[0], scale[1], scale[2]], + )); + } + } + } +} + +pub(crate) enum CudaReductionTasks { + Ext2(Vec), + Ext3(Vec), +} +impl CudaReductionTasks { + pub(crate) fn new(ext_degree: usize) -> Self { + match ext_degree { + 2 => Self::Ext2(Vec::new()), + 3 => Self::Ext3(Vec::new()), + _ => panic!("CUDA supports extension degrees 2 and 3"), + } + } + pub(crate) fn is_empty(&self) -> bool { + match self { + Self::Ext2(tasks) => tasks.is_empty(), + Self::Ext3(tasks) => tasks.is_empty(), + } + } + pub(crate) fn push( + &mut self, + target: &mut CudaReducedOpening, + lde: &CudaLde, + inv_offset: usize, + y: &[Goldilocks], + offset: &[Goldilocks], + ) { + match self { + Self::Ext2(tasks) => { + assert_eq!(target.ext_degree, 2); + assert_eq!(y.len(), 2); + assert_eq!(offset.len(), 2); + tasks.push(target.reduction_task( + lde, + inv_offset, + [y[0], y[1]], + [offset[0], offset[1]], + )); + } + Self::Ext3(tasks) => { + assert_eq!(target.ext_degree, 3); + assert_eq!(y.len(), 3); + assert_eq!(offset.len(), 3); + tasks.push(target.reduction_task_ext3( + lde, + inv_offset, + [y[0], y[1], y[2]], + [offset[0], offset[1], offset[2]], + )); + } + } + } +} pub(crate) struct CudaFriWorkspace { device_id: i32, handle: NonNull, + ext_degree: usize, } impl CudaFriWorkspace { pub(crate) fn new( device_id: i32, - points: &[[Goldilocks; 2]], + points: &[Goldilocks], counts: &[usize], coset: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, ) -> Self { - assert_eq!(points.len(), counts.len()); + assert!(ext_degree == 2 || ext_degree == 3); + assert_eq!(points.len(), counts.len() * ext_degree); let mut handle = core::ptr::null_mut(); - let status = unsafe { - multi_stark_cuda_fri_workspace_create( - device_id, - &mut handle, - points.as_ptr().cast(), - counts.as_ptr(), - points.len(), - coset.as_ptr().cast(), - coset.len(), - raw_u64(ext_w), - ) + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_fri_workspace_create( + device_id, + &mut handle, + points.as_ptr().cast(), + counts.as_ptr(), + counts.len(), + coset.as_ptr().cast(), + coset.len(), + raw_u64(ext_w), + ) + }, + 3 => unsafe { + multi_stark_cuda_fri_workspace_create_ext3( + device_id, + &mut handle, + points.as_ptr().cast(), + counts.as_ptr(), + counts.len(), + coset.as_ptr().cast(), + coset.len(), + ) + }, + _ => unreachable!(), }; check_cuda(status, "FRI workspace allocation"); Self { device_id, handle: NonNull::new(handle).unwrap(), + ext_degree, } } pub(crate) fn interpolate( &mut self, - tasks: &[CudaInterpolationTask], + tasks: &CudaInterpolationTasks, output_count: usize, ext_w: Goldilocks, - ) -> Vec<[Goldilocks; 2]> { - let mut output = vec![[Goldilocks::ZERO; 2]; output_count]; - let status = unsafe { - multi_stark_cuda_fri_interpolate_batch( - self.device_id, - self.handle.as_ptr(), - output.as_mut_ptr().cast(), - output_count, - tasks.as_ptr().cast(), - tasks.len(), - raw_u64(ext_w), - ) + ) -> Vec { + let mut output = vec![Goldilocks::ZERO; output_count * self.ext_degree]; + let status = match (self.ext_degree, tasks) { + (2, CudaInterpolationTasks::Ext2(tasks)) => unsafe { + multi_stark_cuda_fri_interpolate_batch( + self.device_id, + self.handle.as_ptr(), + output.as_mut_ptr().cast(), + output_count, + tasks.as_ptr().cast(), + tasks.len(), + raw_u64(ext_w), + ) + }, + (3, CudaInterpolationTasks::Ext3(tasks)) => unsafe { + multi_stark_cuda_fri_interpolate_batch_ext3( + self.device_id, + self.handle.as_ptr(), + output.as_mut_ptr().cast(), + output_count, + tasks.as_ptr().cast(), + tasks.len(), + ) + }, + _ => panic!("FRI workspace extension degree mismatch"), }; check_cuda(status, "batched FRI interpolation"); output @@ -1681,23 +2015,38 @@ impl CudaFriWorkspace { pub(crate) fn reduce( &mut self, - tasks: &[CudaReductionTask], - alpha: &[[Goldilocks; 2]], + tasks: &CudaReductionTasks, + alpha: &[Goldilocks], ext_w: Goldilocks, ) { - let status = unsafe { - multi_stark_cuda_fri_reduce_batch( - self.device_id, - self.handle.as_ptr(), - tasks.as_ptr().cast(), - tasks.len(), - alpha.as_ptr().cast(), - alpha.len(), - raw_u64(ext_w), - ) - }; - check_cuda(status, "batched FRI reduction") - } + assert_eq!(alpha.len() % self.ext_degree, 0); + let alpha_count = alpha.len() / self.ext_degree; + let status = match (self.ext_degree, tasks) { + (2, CudaReductionTasks::Ext2(tasks)) => unsafe { + multi_stark_cuda_fri_reduce_batch( + self.device_id, + self.handle.as_ptr(), + tasks.as_ptr().cast(), + tasks.len(), + alpha.as_ptr().cast(), + alpha_count, + raw_u64(ext_w), + ) + }, + (3, CudaReductionTasks::Ext3(tasks)) => unsafe { + multi_stark_cuda_fri_reduce_batch_ext3( + self.device_id, + self.handle.as_ptr(), + tasks.as_ptr().cast(), + tasks.len(), + alpha.as_ptr().cast(), + alpha_count, + ) + }, + _ => panic!("FRI workspace extension degree mismatch"), + }; + check_cuda(status, "batched FRI reduction") + } } impl Drop for CudaFriWorkspace { fn drop(&mut self) { @@ -1716,11 +2065,12 @@ pub(crate) fn lookup_lde_resident( height: usize, num_lookups: usize, group_size: usize, - beta: [Goldilocks; 2], - gamma: [Goldilocks; 2], + beta: &[Goldilocks], + gamma: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, log_blowup: usize, -) -> (CudaLde, [Goldilocks; 2]) { +) -> (CudaLde, Vec) { let _span = tracing::info_span!( "cuda/lookup_lde", path = "direct", @@ -1731,6 +2081,9 @@ pub(crate) fn lookup_lde_resident( added_bits = log_blowup ) .entered(); + assert!(ext_degree == 2 || ext_degree == 3); + assert_eq!(beta.len(), ext_degree); + assert_eq!(gamma.len(), ext_degree); assert!((1..=8).contains(&group_size)); assert_eq!(arg_offsets.len(), num_lookups + 1); assert_eq!(arg_offsets.first(), Some(&0)); @@ -1739,7 +2092,12 @@ pub(crate) fn lookup_lde_resident( let extended_height = height << log_blowup; let mut handle = core::ptr::null_mut(); let status = unsafe { - multi_stark_cuda_zero_lde_create(dft.device_id, &mut handle, extended_height, 2) + multi_stark_cuda_zero_lde_create( + dft.device_id, + &mut handle, + extended_height, + ext_degree, + ) }; check_cuda(status, "zero lookup LDE"); return ( @@ -1747,9 +2105,9 @@ pub(crate) fn lookup_lde_resident( device_id: dft.device_id, handle: NonNull::new(handle).expect("CUDA returned a null zero LDE"), height: extended_height, - width: 2, + width: ext_degree, }, - [Goldilocks::ZERO; 2], + vec![Goldilocks::ZERO; ext_degree], ); } let slots = num_lookups.div_ceil(group_size.max(1)); @@ -1759,40 +2117,64 @@ pub(crate) fn lookup_lde_resident( let extended_height = height << log_blowup; let plan = dft.lde_plan( height, - 2 * num_lookups.div_ceil(group_size), + ext_degree * num_lookups.div_ceil(group_size), log_blowup, Goldilocks::GENERATOR, ); - let mut tail = [Goldilocks::ZERO; 4]; + let mut tail = vec![Goldilocks::ZERO; 2 * ext_degree]; let mut handle = core::ptr::null_mut(); - let status = unsafe { - multi_stark_cuda_lookup_lde( - dft.device_id, - &mut handle, - tail.as_mut_ptr().cast(), - multiplicities.as_ptr().cast(), - args.as_ptr().cast(), - arg_offsets.as_ptr(), - height, - num_lookups, - args_width, - group_size.max(1), - beta.as_ptr().cast(), - gamma.as_ptr().cast(), - raw_u64(ext_w), - log_blowup, - plan.raw(), - ) + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_lookup_lde( + dft.device_id, + &mut handle, + tail.as_mut_ptr().cast(), + multiplicities.as_ptr().cast(), + args.as_ptr().cast(), + arg_offsets.as_ptr(), + height, + num_lookups, + args_width, + group_size.max(1), + beta.as_ptr().cast(), + gamma.as_ptr().cast(), + raw_u64(ext_w), + log_blowup, + plan.raw(), + ) + }, + 3 => unsafe { + multi_stark_cuda_lookup_lde_ext3( + dft.device_id, + &mut handle, + tail.as_mut_ptr().cast(), + multiplicities.as_ptr().cast(), + args.as_ptr().cast(), + arg_offsets.as_ptr(), + height, + num_lookups, + args_width, + group_size.max(1), + beta.as_ptr().cast(), + gamma.as_ptr().cast(), + log_blowup, + plan.raw(), + ) + }, + _ => unreachable!(), }; check_cuda(status, "resident CUDA lookup LDE"); + let total = (0..ext_degree) + .map(|c| tail[c] + tail[ext_degree + c]) + .collect(); ( CudaLde { device_id: dft.device_id, handle: NonNull::new(handle).expect("CUDA returned a null lookup LDE"), height: extended_height, - width: 2 * slots, + width: ext_degree * slots, }, - [tail[0] + tail[2], tail[1] + tail[3]], + total, ) } @@ -1805,12 +2187,13 @@ pub(crate) fn lookup_lde_resident_partitioned( height: usize, num_lookups: usize, group_size: usize, - beta: [Goldilocks; 2], - gamma: [Goldilocks; 2], + beta: &[Goldilocks], + gamma: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, log_blowup: usize, - cpu_deltas: impl Fn(core::ops::Range) -> Vec<[Goldilocks; 2]> + Sync, -) -> (CudaLde, [Goldilocks; 2]) { + cpu_deltas: impl Fn(core::ops::Range) -> Vec + Sync, +) -> (CudaLde, Vec) { let _span = tracing::info_span!( "cuda/lookup_lde", path = "partitioned", @@ -1821,6 +2204,9 @@ pub(crate) fn lookup_lde_resident_partitioned( added_bits = log_blowup ) .entered(); + assert!(ext_degree == 2 || ext_degree == 3); + assert_eq!(beta.len(), ext_degree); + assert_eq!(gamma.len(), ext_degree); assert!((1..=8).contains(&group_size)); assert_eq!(arg_offsets.len(), num_lookups + 1); assert_eq!(arg_offsets.first(), Some(&0)); @@ -1833,24 +2219,39 @@ pub(crate) fn lookup_lde_resident_partitioned( let extended_height = height << log_blowup; let plan = dft.lde_plan( height, - 2 * num_lookups.div_ceil(group_size), + ext_degree * num_lookups.div_ceil(group_size), log_blowup, Goldilocks::GENERATOR, ); let total_started = std::time::Instant::now(); let create_started = std::time::Instant::now(); let mut pending_handle = core::ptr::null_mut(); - let status = unsafe { - multi_stark_cuda_lookup_lde_begin_partitioned( - dft.device_id, - &mut pending_handle, - arg_offsets.as_ptr(), - height, - num_lookups, - args_width, - group_size, - log_blowup, - ) + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_lookup_lde_begin_partitioned( + dft.device_id, + &mut pending_handle, + arg_offsets.as_ptr(), + height, + num_lookups, + args_width, + group_size, + log_blowup, + ) + }, + 3 => unsafe { + multi_stark_cuda_lookup_lde_begin_partitioned_ext3( + dft.device_id, + &mut pending_handle, + arg_offsets.as_ptr(), + height, + num_lookups, + args_width, + group_size, + log_blowup, + ) + }, + _ => unreachable!(), }; check_cuda(status, "create partitioned CUDA lookup"); let create_elapsed = create_started.elapsed(); @@ -1901,18 +2302,33 @@ pub(crate) fn lookup_lde_resident_partitioned( let Some(chunk) = chunk else { break }; let row_start = chunk * ROWS_PER_CHUNK; let rows = (height - row_start).min(ROWS_PER_CHUNK); - let status = unsafe { - multi_stark_cuda_lookup_lde_gpu_rows_partitioned( - device_id, - raw_pending as *mut c_void, - multiplicities.as_ptr().cast(), - args.as_ptr().cast(), - row_start, - rows, - beta.as_ptr().cast(), - gamma.as_ptr().cast(), - ext_w, - ) + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_lookup_lde_gpu_rows_partitioned( + device_id, + raw_pending as *mut c_void, + multiplicities.as_ptr().cast(), + args.as_ptr().cast(), + row_start, + rows, + beta.as_ptr().cast(), + gamma.as_ptr().cast(), + ext_w, + ) + }, + 3 => unsafe { + multi_stark_cuda_lookup_lde_gpu_rows_partitioned_ext3( + device_id, + raw_pending as *mut c_void, + multiplicities.as_ptr().cast(), + args.as_ptr().cast(), + row_start, + rows, + beta.as_ptr().cast(), + gamma.as_ptr().cast(), + ) + }, + _ => unreachable!(), }; check_cuda(status, "partitioned CUDA lookup chunk"); chunks += 1; @@ -1937,15 +2353,27 @@ pub(crate) fn lookup_lde_resident_partitioned( let row_start = chunk * ROWS_PER_CHUNK; let rows = (height - row_start).min(ROWS_PER_CHUNK); let values = cpu_deltas(row_start..row_start + rows); - assert_eq!(values.len(), rows * slots); - let status = unsafe { - multi_stark_cuda_lookup_lde_cpu_rows_partitioned( - dft.device_id, - pending_handle.as_ptr(), - values.as_ptr().cast(), - row_start, - rows, - ) + assert_eq!(values.len(), rows * slots * ext_degree); + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_lookup_lde_cpu_rows_partitioned( + dft.device_id, + pending_handle.as_ptr(), + values.as_ptr().cast(), + row_start, + rows, + ) + }, + 3 => unsafe { + multi_stark_cuda_lookup_lde_cpu_rows_partitioned_ext3( + dft.device_id, + pending_handle.as_ptr(), + values.as_ptr().cast(), + row_start, + rows, + ) + }, + _ => unreachable!(), }; check_cuda(status, "upload partitioned CPU lookup chunk"); cpu_chunks += 1; @@ -1959,26 +2387,41 @@ pub(crate) fn lookup_lde_resident_partitioned( let finish_started = std::time::Instant::now(); let mut handle = core::ptr::null_mut(); - let mut tail = [Goldilocks::ZERO; 4]; - let status = unsafe { - multi_stark_cuda_lookup_lde_finish_partitioned( - dft.device_id, - pending_handle.as_ptr(), - &mut handle, - tail.as_mut_ptr().cast(), - plan.raw(), - ) + let mut tail = vec![Goldilocks::ZERO; 2 * ext_degree]; + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_lookup_lde_finish_partitioned( + dft.device_id, + pending_handle.as_ptr(), + &mut handle, + tail.as_mut_ptr().cast(), + plan.raw(), + ) + }, + 3 => unsafe { + multi_stark_cuda_lookup_lde_finish_partitioned_ext3( + dft.device_id, + pending_handle.as_ptr(), + &mut handle, + tail.as_mut_ptr().cast(), + plan.raw(), + ) + }, + _ => unreachable!(), }; pending.handle = None; check_cuda(status, "partitioned CUDA lookup finish"); + let total = (0..ext_degree) + .map(|c| tail[c] + tail[ext_degree + c]) + .collect(); let result = ( CudaLde { device_id: dft.device_id, handle: NonNull::new(handle).expect("CUDA returned a null lookup LDE"), height: extended_height, - width: 2 * slots, + width: ext_degree * slots, }, - [tail[0] + tail[2], tail[1] + tail[3]], + total, ); if memory_diagnostics_enabled() { eprintln!( @@ -2001,11 +2444,15 @@ pub(crate) fn lookup_graph_lde_resident( main: &CudaLde, height: usize, group_size: usize, - beta: [Goldilocks; 2], - gamma: [Goldilocks; 2], + beta: &[Goldilocks], + gamma: &[Goldilocks], ext_w: Goldilocks, + ext_degree: usize, log_blowup: usize, -) -> Option<(CudaLde, [Goldilocks; 2])> { +) -> Option<(CudaLde, Vec)> { + assert!(ext_degree == 2 || ext_degree == 3); + assert_eq!(beta.len(), ext_degree); + assert_eq!(gamma.len(), ext_degree); assert!((1..=8).contains(&group_size)); let _span = tracing::info_span!( "cuda/lookup_lde", @@ -2023,43 +2470,71 @@ pub(crate) fn lookup_graph_lde_resident( let extended_height = height << log_blowup; let plan = dft.lde_plan( height, - 2 * num_lookups.div_ceil(group_size), + ext_degree * num_lookups.div_ceil(group_size), log_blowup, Goldilocks::GENERATOR, ); - let mut tail = [Goldilocks::ZERO; 4]; + let mut tail = vec![Goldilocks::ZERO; 2 * ext_degree]; let mut handle = core::ptr::null_mut(); - let status = unsafe { - multi_stark_cuda_lookup_graph_lde( - dft.device_id, - &mut handle, - tail.as_mut_ptr().cast(), - nodes.as_ptr().cast(), - nodes.len(), - slot_count, - lookups.as_ptr().cast(), - lookups.len(), - args.as_ptr(), - args.len(), - preprocessed.map_or(core::ptr::null(), CudaLde::raw_handle), - main.raw_handle(), - group_size.max(1), - beta.as_ptr().cast(), - gamma.as_ptr().cast(), - raw_u64(ext_w), - log_blowup, - plan.raw(), - ) + let preprocessed_ptr = preprocessed.map_or(core::ptr::null(), CudaLde::raw_handle); + let status = match ext_degree { + 2 => unsafe { + multi_stark_cuda_lookup_graph_lde( + dft.device_id, + &mut handle, + tail.as_mut_ptr().cast(), + nodes.as_ptr().cast(), + nodes.len(), + slot_count, + lookups.as_ptr().cast(), + lookups.len(), + args.as_ptr(), + args.len(), + preprocessed_ptr, + main.raw_handle(), + group_size.max(1), + beta.as_ptr().cast(), + gamma.as_ptr().cast(), + raw_u64(ext_w), + log_blowup, + plan.raw(), + ) + }, + 3 => unsafe { + multi_stark_cuda_lookup_graph_lde_ext3( + dft.device_id, + &mut handle, + tail.as_mut_ptr().cast(), + nodes.as_ptr().cast(), + nodes.len(), + slot_count, + lookups.as_ptr().cast(), + lookups.len(), + args.as_ptr(), + args.len(), + preprocessed_ptr, + main.raw_handle(), + group_size.max(1), + beta.as_ptr().cast(), + gamma.as_ptr().cast(), + log_blowup, + plan.raw(), + ) + }, + _ => unreachable!(), }; check_cuda(status, "resident CUDA graph lookup LDE"); + let total = (0..ext_degree) + .map(|c| tail[c] + tail[ext_degree + c]) + .collect(); Some(( CudaLde { device_id: dft.device_id, handle: NonNull::new(handle).expect("CUDA returned a null graph lookup LDE"), height: extended_height, - width: 2 * groups, + width: ext_degree * groups, }, - [tail[0] + tail[2], tail[1] + tail[3]], + total, )) } @@ -2080,6 +2555,24 @@ impl CudaLde { scale1: raw_u64(scale[1]), } } + + pub(crate) fn interpolation_task_ext3( + &self, + height: usize, + inv_offset: usize, + output_offset: usize, + scale: [Goldilocks; 3], + ) -> CudaInterpolationTaskExt3 { + CudaInterpolationTaskExt3 { + lde: self.raw_handle(), + height, + inv_offset, + output_offset, + scale0: raw_u64(scale[0]), + scale1: raw_u64(scale[1]), + scale2: raw_u64(scale[2]), + } + } } impl CudaReducedOpening { pub(crate) fn reduction_task( @@ -2100,6 +2593,27 @@ impl CudaReducedOpening { offset1: raw_u64(offset[1]), } } + + pub(crate) fn reduction_task_ext3( + &mut self, + lde: &CudaLde, + inv_offset: usize, + y: [Goldilocks; 3], + offset: [Goldilocks; 3], + ) -> CudaReductionTaskExt3 { + CudaReductionTaskExt3 { + reduced: self.handle.as_ptr(), + lde: lde.raw_handle(), + height: self.height, + inv_offset, + y0: raw_u64(y[0]), + y1: raw_u64(y[1]), + y2: raw_u64(y[2]), + offset0: raw_u64(offset[0]), + offset1: raw_u64(offset[1]), + offset2: raw_u64(offset[2]), + } + } } impl Drop for CudaLde { @@ -2451,10 +2965,11 @@ unsafe impl Sync for CudaMixedMerkleTree {} impl CudaMixedMerkleTree { #[must_use] - pub(crate) fn hash_hybrid_height_group( + pub(crate) fn hash_hybrid_height_group_with_domain( device_id: i32, ldes: &[Option<&CudaLde>], host_matrices: &[Option<&RowMajorMatrix>], + domain_v6: bool, ) -> Vec<[u8; 32]> { assert!(device_id >= 0, "CUDA device id must be non-negative"); assert_eq!(ldes.len(), host_matrices.len()); @@ -2495,17 +3010,32 @@ impl CudaMixedMerkleTree { let mut digests = vec![[0u8; 32]; height]; // SAFETY: every pointer is backed by a matrix or CUDA handle borrowed // for this synchronous call, and `digests` has exactly `height` rows. - let status = unsafe { - multi_stark_cuda_hash_hybrid_height_group( - device_id, - digests.as_mut_ptr().cast(), - handles.as_ptr(), - host_values.as_ptr(), - widths.as_ptr(), - heights.as_ptr(), - handles.len(), - height, - ) + let status = if domain_v6 { + unsafe { + multi_stark_cuda_hash_hybrid_height_group_v6( + device_id, + digests.as_mut_ptr().cast(), + handles.as_ptr(), + host_values.as_ptr(), + widths.as_ptr(), + heights.as_ptr(), + handles.len(), + height, + ) + } + } else { + unsafe { + multi_stark_cuda_hash_hybrid_height_group( + device_id, + digests.as_mut_ptr().cast(), + handles.as_ptr(), + host_values.as_ptr(), + widths.as_ptr(), + heights.as_ptr(), + handles.len(), + height, + ) + } }; check_cuda(status, "hybrid CUDA height-group hashing"); digests @@ -2569,8 +3099,14 @@ impl CudaMixedMerkleTree { /// Builds the exact mixed-height tree directly from resident bit-reversed /// LDE matrices. Matrix rows are concatenated in slice order at each /// height using device-to-device copies. + #[cfg(test)] #[must_use] pub(crate) fn from_ldes(device_id: i32, ldes: &[CudaLde]) -> Self { + Self::from_ldes_with_domain(device_id, ldes, false) + } + + #[must_use] + pub(crate) fn from_ldes_with_domain(device_id: i32, ldes: &[CudaLde], domain_v6: bool) -> Self { assert!(device_id >= 0, "CUDA device id must be non-negative"); assert!(!ldes.is_empty(), "mixed Merkle tree has no resident LDEs"); assert!( @@ -2585,14 +3121,26 @@ impl CudaMixedMerkleTree { let mut root = [0u8; 32]; // SAFETY: every handle is live for the synchronous construction call; // the resulting tree owns only its own digest allocation. - let status = unsafe { - multi_stark_cuda_mixed_merkle_create_from_ldes( - device_id, - &mut handle, - root.as_mut_ptr(), - handles.as_ptr(), - handles.len(), - ) + let status = if domain_v6 { + unsafe { + multi_stark_cuda_mixed_merkle_create_from_ldes_v6( + device_id, + &mut handle, + root.as_mut_ptr(), + handles.as_ptr(), + handles.len(), + ) + } + } else { + unsafe { + multi_stark_cuda_mixed_merkle_create_from_ldes( + device_id, + &mut handle, + root.as_mut_ptr(), + handles.as_ptr(), + handles.len(), + ) + } }; if status != 0 { let dimensions: Vec<(usize, usize)> = @@ -2613,6 +3161,7 @@ impl CudaMixedMerkleTree { /// Builds a mixed-height tree from resident CUDA LDEs, host matrices, and /// pre-hashed height groups. Deferred dimensions are accepted only when a /// pre-hashed group supplies that height's complete digest frontier. + #[cfg(test)] #[must_use] pub(crate) fn from_hybrid( device_id: i32, @@ -2620,6 +3169,25 @@ impl CudaMixedMerkleTree { host_matrices: &[Option<&RowMajorMatrix>], deferred_dimensions: &[Option], host_digest_groups: &[(usize, Vec<[u8; 32]>)], + ) -> Self { + Self::from_hybrid_with_domain( + device_id, + ldes, + host_matrices, + deferred_dimensions, + host_digest_groups, + false, + ) + } + + #[must_use] + pub(crate) fn from_hybrid_with_domain( + device_id: i32, + ldes: &[Option<&CudaLde>], + host_matrices: &[Option<&RowMajorMatrix>], + deferred_dimensions: &[Option], + host_digest_groups: &[(usize, Vec<[u8; 32]>)], + domain_v6: bool, ) -> Self { assert!(device_id >= 0, "CUDA device id must be non-negative"); assert_eq!(ldes.len(), host_matrices.len()); @@ -2702,20 +3270,38 @@ impl CudaMixedMerkleTree { let mut root = [0u8; 32]; // SAFETY: all resident handles and host digest buffers remain live for // this synchronous call; the returned tree owns its digest allocation. - let status = unsafe { - multi_stark_cuda_mixed_merkle_create_hybrid( - device_id, - &mut handle, - root.as_mut_ptr(), - handles.as_ptr(), - host_values.as_ptr(), - widths.as_ptr(), - heights.as_ptr(), - ldes.len(), - host_digest_pointers.as_ptr(), - host_digest_heights.as_ptr(), - host_digest_groups.len(), - ) + let status = if domain_v6 { + unsafe { + multi_stark_cuda_mixed_merkle_create_hybrid_v6( + device_id, + &mut handle, + root.as_mut_ptr(), + handles.as_ptr(), + host_values.as_ptr(), + widths.as_ptr(), + heights.as_ptr(), + ldes.len(), + host_digest_pointers.as_ptr(), + host_digest_heights.as_ptr(), + host_digest_groups.len(), + ) + } + } else { + unsafe { + multi_stark_cuda_mixed_merkle_create_hybrid( + device_id, + &mut handle, + root.as_mut_ptr(), + handles.as_ptr(), + host_values.as_ptr(), + widths.as_ptr(), + heights.as_ptr(), + ldes.len(), + host_digest_pointers.as_ptr(), + host_digest_heights.as_ptr(), + host_digest_groups.len(), + ) + } }; if status != 0 { let dims: Vec> = ldes @@ -2748,20 +3334,36 @@ impl CudaMixedMerkleTree { } } - pub(crate) fn from_fri_codeword(codeword: &CudaLde, arity: usize) -> Self { - assert_eq!(codeword.width, 2); + pub(crate) fn from_fri_codeword_with_domain( + codeword: &CudaLde, + arity: usize, + domain_v6: bool, + ) -> Self { + assert!(codeword.width == 2 || codeword.width == 3); assert!(arity.is_power_of_two()); assert_eq!(codeword.height % arity, 0); let mut handle = core::ptr::null_mut(); let mut root = [0u8; 32]; - let status = unsafe { - multi_stark_cuda_fri_merkle_create( - codeword.device_id, - &mut handle, - root.as_mut_ptr(), - codeword.raw_handle(), - arity, - ) + let status = if domain_v6 { + unsafe { + multi_stark_cuda_fri_merkle_create_v6( + codeword.device_id, + &mut handle, + root.as_mut_ptr(), + codeword.raw_handle(), + arity, + ) + } + } else { + unsafe { + multi_stark_cuda_fri_merkle_create( + codeword.device_id, + &mut handle, + root.as_mut_ptr(), + codeword.raw_handle(), + arity, + ) + } }; check_cuda(status, "resident CUDA FRI Merkle tree creation"); Self { @@ -3427,6 +4029,267 @@ unsafe extern "C" { codeword: *const c_void, arity: usize, ) -> i32; + fn multi_stark_cuda_mixed_merkle_create_from_ldes_v6( + device_id: i32, + handle: *mut *mut c_void, + root: *mut u8, + lde_handles: *const *const c_void, + lde_count: usize, + ) -> i32; + fn multi_stark_cuda_mixed_merkle_create_hybrid_v6( + device_id: i32, + handle: *mut *mut c_void, + root: *mut u8, + lde_handles: *const *const c_void, + host_values: *const *const u64, + widths: *const usize, + heights: *const usize, + matrix_count: usize, + host_digest_groups: *const *const u8, + host_digest_heights: *const usize, + host_digest_group_count: usize, + ) -> i32; + fn multi_stark_cuda_hash_hybrid_height_group_v6( + device_id: i32, + host_digests: *mut u8, + lde_handles: *const *const c_void, + host_values: *const *const u64, + widths: *const usize, + heights: *const usize, + matrix_count: usize, + height: usize, + ) -> i32; + fn multi_stark_cuda_fri_merkle_create_v6( + device_id: i32, + handle: *mut *mut c_void, + root: *mut u8, + codeword: *const c_void, + arity: usize, + ) -> i32; + + fn multi_stark_cuda_quotient_values_ext3( + device_id: i32, + output: *mut u64, + nodes: *const c_void, + node_count: usize, + slot_count: usize, + roots: *const u32, + root_count: usize, + lookups: *const c_void, + lookup_count: usize, + lookup_args: *const u32, + lookup_arg_count: usize, + group_size: usize, + preprocessed_handle: *const c_void, + main_handle: *const c_void, + stage2_handle: *const c_void, + publics: *const u64, + public_count: usize, + coset_shift: u64, + coset_generator: u64, + trace_last: u64, + vanishing_start: u64, + vanishing_step: u64, + alpha: *const u64, + constraint_count: usize, + delta: *const u64, + quotient_size: usize, + next_step: usize, + ) -> i32; + fn multi_stark_cuda_quotient_lde_ext3( + device_id: i32, + output_handle: *mut *mut c_void, + nodes: *const c_void, + node_count: usize, + slot_count: usize, + roots: *const u32, + root_count: usize, + lookups: *const c_void, + lookup_count: usize, + lookup_args: *const u32, + lookup_arg_count: usize, + group_size: usize, + preprocessed_handle: *const c_void, + main_handle: *const c_void, + stage2_handle: *const c_void, + publics: *const u64, + public_count: usize, + coset_shift: u64, + coset_generator: u64, + trace_last: u64, + vanishing_start: u64, + vanishing_step: u64, + alpha: *const u64, + constraint_count: usize, + delta: *const u64, + quotient_size: usize, + next_step: usize, + quotient_degree: usize, + log_blowup: usize, + quotient_plan: *const RawPlan, + lde_plan: *const RawPlan, + slice_weights: *const u64, + ) -> i32; + fn multi_stark_cuda_quotient_lde_mixed_ext3( + device_id: i32, + output_handle: *mut *mut c_void, + nodes: *const c_void, + node_count: usize, + slot_count: usize, + roots: *const u32, + root_count: usize, + lookups: *const c_void, + lookup_count: usize, + lookup_args: *const u32, + lookup_arg_count: usize, + group_size: usize, + preprocessed_handle: *const c_void, + preprocessed_host: *const u64, + preprocessed_height: usize, + preprocessed_width: usize, + main_handle: *const c_void, + main_host: *const u64, + main_height: usize, + main_width: usize, + stage2_handle: *const c_void, + stage2_host: *const u64, + stage2_height: usize, + stage2_width: usize, + publics: *const u64, + public_count: usize, + coset_shift: u64, + coset_generator: u64, + trace_last: u64, + vanishing_start: u64, + vanishing_step: u64, + alpha: *const u64, + constraint_count: usize, + delta: *const u64, + quotient_size: usize, + next_step: usize, + quotient_degree: usize, + log_blowup: usize, + quotient_plan: *const RawPlan, + lde_plan: *const RawPlan, + slice_weights: *const u64, + ) -> i32; + fn multi_stark_cuda_fri_workspace_create_ext3( + device_id: i32, + handle: *mut *mut c_void, + points: *const u64, + counts: *const usize, + point_count: usize, + coset: *const u64, + coset_count: usize, + ) -> i32; + fn multi_stark_cuda_fri_interpolate_batch_ext3( + device_id: i32, + handle: *mut c_void, + output: *mut u64, + output_count: usize, + tasks: *const c_void, + task_count: usize, + ) -> i32; + fn multi_stark_cuda_fri_reduce_batch_ext3( + device_id: i32, + handle: *mut c_void, + tasks: *const c_void, + task_count: usize, + alpha: *const u64, + alpha_count: usize, + ) -> i32; + fn multi_stark_cuda_fri_fold_resident_ext3( + device_id: i32, + output: *mut *mut c_void, + input: *const c_void, + next_reduced: *const c_void, + beta: *const u64, + log_arity: usize, + beta_power0: u64, + beta_power1: u64, + beta_power2: u64, + g_inv: u64, + ) -> i32; + fn multi_stark_cuda_reduced_create_ext3( + device_id: i32, + handle: *mut *mut c_void, + height: usize, + ) -> i32; + fn multi_stark_cuda_reduced_add_host_ext3( + device_id: i32, + handle: *mut c_void, + values: *const u64, + height: usize, + ) -> i32; + fn multi_stark_cuda_lookup_graph_lde_ext3( + device_id: i32, + output_handle: *mut *mut c_void, + total: *mut u64, + nodes: *const c_void, + node_count: usize, + slot_count: usize, + lookups: *const c_void, + lookup_count: usize, + lookup_args: *const u32, + lookup_arg_count: usize, + preprocessed_handle: *const c_void, + main_handle: *const c_void, + group_size: usize, + beta: *const u64, + gamma: *const u64, + added_bits: usize, + plan: *const RawPlan, + ) -> i32; + fn multi_stark_cuda_lookup_lde_ext3( + device_id: i32, + output_handle: *mut *mut c_void, + total: *mut u64, + multiplicities: *const u64, + args: *const u64, + arg_offsets: *const usize, + height: usize, + num_lookups: usize, + args_width: usize, + group_size: usize, + beta: *const u64, + gamma: *const u64, + added_bits: usize, + plan: *const RawPlan, + ) -> i32; + fn multi_stark_cuda_lookup_lde_begin_partitioned_ext3( + device_id: i32, + pending_handle: *mut *mut c_void, + arg_offsets: *const usize, + height: usize, + num_lookups: usize, + args_width: usize, + group_size: usize, + added_bits: usize, + ) -> i32; + fn multi_stark_cuda_lookup_lde_gpu_rows_partitioned_ext3( + device_id: i32, + pending_handle: *mut c_void, + multiplicities: *const u64, + args: *const u64, + row_start: usize, + rows: usize, + beta: *const u64, + gamma: *const u64, + ) -> i32; + fn multi_stark_cuda_lookup_lde_cpu_rows_partitioned_ext3( + device_id: i32, + pending_handle: *mut c_void, + deltas: *const u64, + row_start: usize, + rows: usize, + ) -> i32; + fn multi_stark_cuda_lookup_lde_finish_partitioned_ext3( + device_id: i32, + pending_handle: *mut c_void, + output_handle: *mut *mut c_void, + total: *mut u64, + plan: *const RawPlan, + ) -> i32; #[cfg(test)] fn multi_stark_cuda_mixed_merkle_create_from_host_matrices( @@ -4137,6 +5000,68 @@ mod tests { } } + #[test] + fn ext3_field_kernels_match_cpu() { + use p3_field::BasedVectorSpace; + use p3_field::extension::CubicTrinomialExtensionField; + type Ext3 = CubicTrinomialExtensionField; + + let mut rng = SmallRng::seed_from_u64(0x00c0_dae3); + let mut left = vec![Ext3::ZERO, Ext3::ONE]; + let mut right = vec![Ext3::ONE, Ext3::ZERO]; + left.extend((0..2048).map(|_| { + Ext3::from_basis_coefficients_slice(&[ + rng.random::(), + rng.random::(), + rng.random::(), + ]) + .unwrap() + })); + right.extend((0..2048).map(|_| { + Ext3::from_basis_coefficients_slice(&[ + rng.random::(), + rng.random::(), + rng.random::(), + ]) + .unwrap() + })); + let flatten = |xs: &[Ext3]| -> Vec { + xs.iter() + .flat_map(|x| x.as_basis_coefficients_slice().iter().copied()) + .collect() + }; + let left_flat = flatten(&left); + let right_flat = flatten(&right); + let mut sums = Goldilocks::zero_vec(left_flat.len()); + let mut differences = Goldilocks::zero_vec(left_flat.len()); + let mut products = Goldilocks::zero_vec(left_flat.len()); + let mut inverses = Goldilocks::zero_vec(left_flat.len()); + let status = unsafe { + multi_stark_cuda_ext3_ops( + 0, + sums.as_mut_ptr().cast(), + differences.as_mut_ptr().cast(), + products.as_mut_ptr().cast(), + inverses.as_mut_ptr().cast(), + left_flat.as_ptr().cast(), + right_flat.as_ptr().cast(), + left.len(), + ) + }; + check_cuda(status, "Ext3 arithmetic contract"); + for i in 0..left.len() { + let s = Ext3::from_basis_coefficients_slice(&sums[3 * i..3 * i + 3]).unwrap(); + let d = Ext3::from_basis_coefficients_slice(&differences[3 * i..3 * i + 3]).unwrap(); + let p = Ext3::from_basis_coefficients_slice(&products[3 * i..3 * i + 3]).unwrap(); + let inv = Ext3::from_basis_coefficients_slice(&inverses[3 * i..3 * i + 3]).unwrap(); + assert_eq!(s, left[i] + right[i], "sum {i}"); + assert_eq!(d, left[i] - right[i], "difference {i}"); + assert_eq!(p, left[i] * right[i], "product {i}"); + let expected_inv = left[i].try_inverse().unwrap_or(Ext3::ZERO); + assert_eq!(inv, expected_inv, "inverse {i}"); + } + } + unsafe extern "C" { fn multi_stark_cuda_goldilocks_ops( device_id: i32, @@ -4148,7 +5073,16 @@ mod tests { right: *const u64, len: usize, ) -> i32; - + fn multi_stark_cuda_ext3_ops( + device_id: i32, + sums: *mut u64, + differences: *mut u64, + products: *mut u64, + inverses: *mut u64, + left: *const u64, + right: *const u64, + len: usize, + ) -> i32; } } #[test] diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index a5ea164..096e75b 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -44,7 +44,13 @@ use p3_util::{log2_strict_usize, reverse_slice_index_bits}; use tracing::{debug_span, instrument}; use super::mmcs::{CudaCommitMmcs, hash_host_only_height_groups}; -use super::{CudaFriWorkspace, CudaLde, CudaMixedMerkleTree, CudaReducedOpening}; +use super::{ + CudaFriWorkspace, CudaInterpolationTasks, CudaLde, CudaMixedMerkleTree, CudaReducedOpening, + CudaReductionTasks, +}; +use crate::p3_adapter::fri_batching::{ + FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, +}; use p3_goldilocks::Goldilocks; use p3_symmetric::MerkleCap; @@ -71,6 +77,96 @@ fn goldilocks_quadratic_inverse_denominators( .collect() } +fn goldilocks_cubic_trinomial_inverse_denominators( + point: [Goldilocks; 3], + coset: &[Goldilocks], +) -> Vec<[Goldilocks; 3]> { + let [z0, z1, z2] = point; + let z1_sq = z1 * z1; + let z2_sq = z2 * z2; + let z1_s12 = z1 * (z1 + z2); + let norms = coset + .par_iter() + .map(|&x| { + let a0 = z0 - x; + let s02 = a0 + z2; + let d0 = s02 * s02 - z1_s12; + let d1 = z2_sq - a0 * z1; + let d2 = z1_sq - z2 * s02; + a0 * d0 + z2 * d1 + z1 * d2 + }) + .collect::>(); + let inverse_norms = batch_multiplicative_inverse(&norms); + coset + .par_iter() + .zip(inverse_norms.par_iter()) + .map(|(&x, &inv_norm)| { + let a0 = z0 - x; + let s02 = a0 + z2; + let d0 = s02 * s02 - z1_s12; + let d1 = z2_sq - a0 * z1; + let d2 = z1_sq - z2 * s02; + [d0 * inv_norm, d1 * inv_norm, d2 * inv_norm] + }) + .collect() +} + +fn cuda_ext_degree_and_w>() +-> (usize, Goldilocks) { + let d = >::DIMENSION; + assert!( + d == 2 || d == 3, + "CUDA PCS supports Goldilocks extension degrees 2 and 3, got {d}" + ); + if d == 2 { + let ext_x = Challenge::from_basis_coefficients_slice(&[Val::ZERO, Val::ONE]) + .expect("quadratic extension generator"); + let w = Goldilocks::from_u64( + >::as_basis_coefficients_slice(&(ext_x * ext_x))[0] + .as_canonical_u64(), + ); + assert_eq!(w, Goldilocks::from_u64(7)); + (2, w) + } else { + let ext_x = Challenge::from_basis_coefficients_slice(&[Val::ZERO, Val::ONE, Val::ZERO]) + .expect("cubic extension generator"); + let expected_x3 = + Challenge::from_basis_coefficients_slice(&[Val::ONE, Val::ONE, Val::ZERO]) + .expect("cubic trinomial X + 1"); + assert_eq!( + ext_x * ext_x * ext_x, + expected_x3, + "CUDA degree-3 extension requires X^3 - X - 1" + ); + (3, Goldilocks::ZERO) + } +} + +#[inline] +fn ext_to_goldilocks>( + value: Challenge, + d: usize, +) -> ([Goldilocks; 3], usize) { + let coeffs = >::as_basis_coefficients_slice(&value); + let mut out = [Goldilocks::ZERO; 3]; + for i in 0..d { + out[i] = Goldilocks::from_u64(coeffs[i].as_canonical_u64()); + } + (out, d) +} + +#[inline] +fn ext_from_goldilocks>( + slice: &[Goldilocks], +) -> Challenge { + let mut coeffs = [Val::ZERO; 3]; + let d = slice.len(); + for i in 0..d { + coeffs[i] = Val::from_u64(slice[i].as_canonical_u64()); + } + Challenge::from_basis_coefficients_slice(&coeffs[..d]).expect("extension element") +} + pub trait CudaPcsDft: TwoAdicSubgroupDft + Send + Sync + 'static { fn coset_lde_workspace_bytes( &self, @@ -103,8 +199,7 @@ pub trait CudaPcsDft: TwoAdicSubgroupDft + Send + Sync + 'st use p3_fri::{ BatchMultiOpening, CommitPhaseMultiStep, FriParameters, FriProof, TwoAdicFriFolding, TwoAdicFriFoldingForMmcs, build_periodic_lde_table_two_adic, compute_log_arity_for_round, - prover, - verifier::{self, FriError}, + prover, verifier::FriError, }; struct CudaFriRound { @@ -218,6 +313,7 @@ trait CudaFriMmcs: Mmcs { &self, codeword: CudaLde, log_arity: usize, + domain_v6: bool, ) -> (Self::Commitment, CudaFriRound); fn open_cuda_fri_batch( &self, @@ -235,9 +331,10 @@ where &self, codeword: CudaLde, log_arity: usize, + domain_v6: bool, ) -> (Self::Commitment, CudaFriRound) { let arity = 1 << log_arity; - let tree = CudaMixedMerkleTree::from_fri_codeword(&codeword, arity); + let tree = CudaMixedMerkleTree::from_fri_codeword_with_domain(&codeword, arity, domain_v6); let commitment = MerkleCap::new(vec![tree.root()]); ( commitment, @@ -264,9 +361,8 @@ where .map(|query_rows| { query_rows .iter() - .map(|pair| { - Challenge::from_basis_coefficients_slice(pair) - .expect("quadratic extension row") + .map(|row| { + Challenge::from_basis_coefficients_slice(row).expect("extension row") }) .collect() }) @@ -287,6 +383,7 @@ pub struct CudaTwoAdicFriPcs { pub(crate) dft: Dft, pub(crate) mmcs: InputMmcs, pub(crate) fri: FriParameters, + pub(crate) batching: FriBatching, _phantom: PhantomData, } @@ -343,6 +440,7 @@ fn cache_at_least( .map(std::sync::Arc::clone) } +#[allow(clippy::too_many_arguments)] fn prove_fri_cuda_resident( params: &FriParameters, mut inputs: Vec, @@ -355,6 +453,8 @@ fn prove_fri_cuda_resident( >], input_mmcs: &InputMmcs, ext_w: Goldilocks, + ext_degree: usize, + domain_v6: bool, ) -> FriProof>> where Val: TwoAdicField + PrimeField64 + 'static, @@ -364,6 +464,7 @@ where Challenger: FieldChallenger + GrindingChallenger + CanObserve, { assert!(!inputs.is_empty()); + assert!(ext_degree == 2 || ext_degree == 3); assert!( params.num_queries > 0, "num_queries must be at least 1 for FRI soundness" @@ -387,20 +488,6 @@ where if params.log_final_poly_len > 0 { assert!(log_min_height > params.log_final_poly_len + params.log_blowup); } - let to_pair = |value: Challenge| { - let coefficients = value.as_basis_coefficients_slice(); - [ - Goldilocks::from_u64(coefficients[0].as_canonical_u64()), - Goldilocks::from_u64(coefficients[1].as_canonical_u64()), - ] - }; - let from_pair = |pair: [Goldilocks; 2]| { - Challenge::from_basis_coefficients_slice(&[ - Val::from_u64(pair[0].as_canonical_u64()), - Val::from_u64(pair[1].as_canonical_u64()), - ]) - .expect("quadratic extension element") - }; let mut codeword = inputs.remove(0).into_lde(); let mut commits = Vec::new(); @@ -422,7 +509,7 @@ where ); let arity = 1 << log_arity; let (commitment, round) = tracing::info_span!("stark/fri_round_commit") - .in_scope(|| params.mmcs.commit_cuda_fri(codeword, log_arity)); + .in_scope(|| params.mmcs.commit_cuda_fri(codeword, log_arity, domain_v6)); challenger.observe(commitment.clone()); commits.push(commitment); commit_pow_witnesses.push( @@ -431,18 +518,18 @@ where ); let beta: Challenge = challenger.sample_algebra_element(); let mut beta_step = beta; - let betas = (0..log_arity) - .map(|_| { - let result = to_pair(beta_step); - beta_step = beta_step.square(); - result - }) - .collect_vec(); + let mut betas_flat = Vec::with_capacity(log_arity * ext_degree); + for _ in 0..log_arity { + let (buf, d) = ext_to_goldilocks::(beta_step, ext_degree); + betas_flat.extend_from_slice(&buf[..d]); + beta_step = beta_step.square(); + } let folded_height = round.codeword.height() >> log_arity; let add_next = inputs .first() .is_some_and(|input| input.height() == folded_height); - let beta_power = to_pair(beta.exp_power_of_2(log_arity)); + let (beta_power_buf, _) = + ext_to_goldilocks::(beta.exp_power_of_2(log_arity), ext_degree); let g_inv = Goldilocks::from_u64( Val::two_adic_generator(log_height) .inverse() @@ -450,10 +537,12 @@ where ); codeword = round.codeword.fri_fold( add_next.then(|| &inputs[0]), - &betas, - beta_power, + &betas_flat, + log_arity, + &beta_power_buf[..ext_degree], g_inv, ext_w, + ext_degree, ); if add_next { inputs.remove(0); @@ -467,11 +556,9 @@ where let final_matrix = codeword.to_row_major_matrix(); let mut final_values = final_matrix .values - .as_chunks::<2>() - .0 - .iter() + .chunks_exact(ext_degree) .take(params.final_poly_len()) - .map(|pair| from_pair([pair[0], pair[1]])) + .map(ext_from_goldilocks::) .collect_vec(); reverse_slice_index_bits(&mut final_values); let final_poly = Radix2DFTSmallBatch::default().idft_algebra(final_values); @@ -557,9 +644,16 @@ impl CudaTwoAdicFriPcs Self { + self.batching = batching; + self + } } /// The Prover Data associated to a commitment to a collection of matrices @@ -1022,6 +1116,7 @@ where &resident.iter().map(Option::as_ref).collect::>(), &deferred_dimensions, &prehashed_heights, + self.mmcs.leaf_domain(), )); if crate::cuda::memory_diagnostics_enabled() { eprintln!( @@ -1326,29 +1421,25 @@ where let _resident_guard = tracing::info_span!("stark/fri_resident").entered(); let rounds = resident_rounds; let device_id = self.mmcs.cuda_device_id(); - assert_eq!(>::DIMENSION, 2); - let to_gold = |v: Val| Goldilocks::from_u64(v.as_canonical_u64()); - let to_pair = |v: Challenge| { - let c = >::as_basis_coefficients_slice(&v); - [to_gold(c[0]), to_gold(c[1])] - }; - let from_pair = |v: [Goldilocks; 2]| { - Challenge::from_basis_coefficients_slice(&[ - Val::from_u64(v[0].as_canonical_u64()), - Val::from_u64(v[1].as_canonical_u64()), - ]) - .unwrap() - }; + let domain_v6 = self.mmcs.is_domain_v6(); + let (ext_degree, ext_w) = cuda_ext_degree_and_w::(); let global_max_height = rounds .iter() .flat_map(|(ldes, _)| ldes.iter().map(CudaLde::height)) .max() .unwrap(); - let global_max_width = rounds - .iter() - .flat_map(|(ldes, _)| ldes.iter().map(CudaLde::width)) - .max() - .unwrap(); + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for (ldes, points) in &rounds { + for (lde, ps) in ldes.iter().zip(points.iter()) { + if !ps.is_empty() { + opened_max_width = opened_max_width.max(lde.width()); + let lh = log2_strict_usize(lde.height()); + openings_per_height[lh] += ps.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); let log_global_max_height = log2_strict_usize(global_max_height); let coset_gold = bit_reversed_coset::(log_global_max_height); let mut max_log: LinearMap = LinearMap::new(); @@ -1363,17 +1454,14 @@ where } } } - let ext_x = - Challenge::from_basis_coefficients_slice(&[Val::ZERO, Val::ONE]).unwrap(); - let ext_w = to_pair(ext_x * ext_x)[0]; - assert_eq!(ext_w, Goldilocks::from_u64(7)); let mut inv_offsets = LinearMap::new(); let mut inverse_points = Vec::new(); let mut inverse_counts = Vec::new(); let mut inverse_count = 0usize; for (point, lh) in max_log { inv_offsets.insert(point, inverse_count); - inverse_points.push(to_pair(point)); + let (buf, d) = ext_to_goldilocks::(point, ext_degree); + inverse_points.extend_from_slice(&buf[..d]); let count = 1usize << lh; inverse_counts.push(count); inverse_count += count; @@ -1384,8 +1472,9 @@ where &inverse_counts, &coset_gold, ext_w, + ext_degree, ); - let mut interpolation_tasks = Vec::new(); + let mut interpolation_tasks = CudaInterpolationTasks::new(ext_degree); let mut output_count = 0usize; let layouts = rounds .iter() @@ -1402,12 +1491,15 @@ where let shift_pow = Val::GENERATOR.exp_power_of_2(lh); let scale = (point.exp_power_of_2(lh) - shift_pow) * (Val::from_usize(h) * shift_pow).inverse(); - interpolation_tasks.push(lde.interpolation_task( + let (scale_buf, d) = + ext_to_goldilocks::(scale, ext_degree); + interpolation_tasks.push( + lde, h, *inv_offsets.get(&point).unwrap(), offset, - to_pair(scale), - )); + &scale_buf[..d], + ); (offset, lde.width()) }) .collect_vec() @@ -1426,10 +1518,10 @@ where matrix .into_iter() .map(|(offset, width)| { - interpolated[offset..offset + width] - .iter() - .copied() - .map(from_pair) + interpolated + [offset * ext_degree..(offset + width) * ext_degree] + .chunks_exact(ext_degree) + .map(ext_from_goldilocks::) .collect_vec() }) .collect_vec() @@ -1444,37 +1536,68 @@ where } } } - let alpha: Challenge = challenger.sample_algebra_element(); - let alpha_powers: Vec<_> = alpha.powers().take(global_max_width).collect(); - let alpha_pairs: Vec<_> = alpha_powers.iter().copied().map(to_pair).collect(); + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.powers().take(opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; + let mut col_weights_flat = Vec::with_capacity(col_weights.len() * ext_degree); + for &w in &col_weights { + let (buf, d) = ext_to_goldilocks::(w, ext_degree); + col_weights_flat.extend_from_slice(&buf[..d]); + } let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; let mut reduced: [Option; 33] = core::array::from_fn(|_| None); - let mut reduction_tasks = Vec::new(); + let mut reduction_tasks = CudaReductionTasks::new(ext_degree); for ((ldes, points), openings_round) in rounds.iter().zip(all_opened_values.iter()) { for ((lde, ps), openings) in ldes.iter().zip(points.iter()).zip(openings_round.iter()) { + if ps.is_empty() { + continue; + } let lh = log2_strict_usize(lde.height()); let target = reduced[lh].get_or_insert_with(|| { - CudaReducedOpening::new(device_id, lde.height()) + CudaReducedOpening::new_with_degree(device_id, lde.height(), ext_degree) }); for (&point, ys) in ps.iter().zip(openings.iter()) { - let reduced_y = - dot_product(alpha_powers.iter().copied(), ys.iter().copied()); - let offset = alpha.exp_u64(num_reduced[lh] as u64); - reduction_tasks.push(target.reduction_task( + let reduced_y: Challenge = + dot_product(col_weights.iter().copied(), ys.iter().copied()); + let offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.exp_u64(num_reduced[lh] as u64) + } + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[lh]] + } + }; + let (y_buf, d) = + ext_to_goldilocks::(reduced_y, ext_degree); + let (off_buf, _) = + ext_to_goldilocks::(offset, ext_degree); + reduction_tasks.push( + target, lde, *inv_offsets.get(&point).unwrap(), - to_pair(reduced_y), - to_pair(offset), - )); + &y_buf[..d], + &off_buf[..d], + ); num_reduced[lh] += lde.width(); + opening_idx_by_height[lh] += 1; } } } tracing::info_span!("stark/fri_reduce") - .in_scope(|| workspace.reduce(&reduction_tasks, &alpha_pairs, ext_w)); + .in_scope(|| workspace.reduce(&reduction_tasks, &col_weights_flat, ext_w)); let fri_input = reduced.into_iter().rev().flatten().collect_vec(); let fri_proof = tracing::info_span!("stark/fri_prove").in_scope(|| { prove_fri_cuda_resident( @@ -1485,6 +1608,8 @@ where &commitment_data_with_opening_points, &self.mmcs, ext_w, + ext_degree, + domain_v6, ) }); return (all_opened_values, fri_proof); @@ -1514,32 +1639,35 @@ where .iter() .map(|(_, points)| points) .collect_vec(); - let (cuda_max_height, cuda_max_width) = dimensions + let (cuda_max_height, _) = dimensions .iter() .flatten() .map(|dims| (dims.height, dims.width)) .reduce(|(hmax, wmax), (height, width)| (hmax.max(height), wmax.max(width))) .expect("No Matrices Supplied?"); + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for ((_, points), round_dimensions) in commitment_data_with_opening_points + .iter() + .zip(dimensions.iter()) + { + for (pts, dims) in points.iter().zip(round_dimensions) { + if !pts.is_empty() { + opened_max_width = opened_max_width.max(dims.width); + let lh = log2_strict_usize(dims.height); + openings_per_height[lh] += pts.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); let final_fri_height = self.fri.blowup() * self.fri.final_poly_len(); if cuda_max_height > 1024 && cuda_max_height > final_fri_height { let _resident_guard = tracing::info_span!("stark/fri_streamed").entered(); let prepare_span = tracing::info_span!("stark/fri_prepare").entered(); let phase_started = std::time::Instant::now(); let device_id = self.mmcs.cuda_device_id(); - assert_eq!(>::DIMENSION, 2); - let to_gold = |value: Val| Goldilocks::from_u64(value.as_canonical_u64()); - let to_pair = |value: Challenge| { - let coefficients = - >::as_basis_coefficients_slice(&value); - [to_gold(coefficients[0]), to_gold(coefficients[1])] - }; - let from_pair = |value: [Goldilocks; 2]| { - Challenge::from_basis_coefficients_slice(&[ - Val::from_u64(value[0].as_canonical_u64()), - Val::from_u64(value[1].as_canonical_u64()), - ]) - .expect("quadratic extension element") - }; + let domain_v6 = self.mmcs.is_domain_v6(); + let (ext_degree, ext_w) = cuda_ext_degree_and_w::(); let log_global_max_height = log2_strict_usize(cuda_max_height); let coset_gold = bit_reversed_coset::(log_global_max_height); @@ -1560,10 +1688,6 @@ where } } - let ext_x = Challenge::from_basis_coefficients_slice(&[Val::ZERO, Val::ONE]) - .expect("quadratic extension generator"); - let ext_w = to_pair(ext_x * ext_x)[0]; - assert_eq!(ext_w, Goldilocks::from_u64(7)); let mut inv_offsets = LinearMap::new(); let mut inverse_points = Vec::new(); let mut inverse_counts = Vec::new(); @@ -1587,10 +1711,10 @@ where .into_iter() .sum::(); let fri_workspace_bytes = inverse_elements - .saturating_mul(2 * size_of::()) + .saturating_mul(ext_degree * size_of::()) .saturating_add(cuda_max_height.saturating_mul(size_of::())) - .saturating_add(max_inverse_elements.saturating_mul(2 * size_of::())) - .saturating_add(reduced_elements.saturating_mul(2 * size_of::())) + .saturating_add(max_inverse_elements.saturating_mul(ext_degree * size_of::())) + .saturating_add(reduced_elements.saturating_mul(ext_degree * size_of::())) .saturating_add(total_device_bytes / 64); let admission_started = std::time::Instant::now(); let admission_data = commitment_data_with_opening_points @@ -1607,7 +1731,8 @@ where } for &(point, log_height) in &point_logs { inv_offsets.insert(point, inverse_count); - inverse_points.push(to_pair(point)); + let (buf, d) = ext_to_goldilocks::(point, ext_degree); + inverse_points.extend_from_slice(&buf[..d]); let count = 1usize << log_height; inverse_counts.push(count); inverse_count += count; @@ -1650,14 +1775,27 @@ where .map(|&(point, log_height)| { let count = 1 << log_height; let coset = coset_gold[..count].as_ref(); - let inverses = goldilocks_quadratic_inverse_denominators( - to_pair(point), - coset, - ext_w, - ) - .into_par_iter() - .map(from_pair) - .collect(); + let (buf, _) = + ext_to_goldilocks::(point, ext_degree); + let inverses: Vec = match ext_degree { + 2 => goldilocks_quadratic_inverse_denominators( + [buf[0], buf[1]], + coset, + ext_w, + ) + .into_par_iter() + .map(|pair| ext_from_goldilocks::(&pair)) + .collect(), + 3 => { + goldilocks_cubic_trinomial_inverse_denominators(buf, coset) + .into_par_iter() + .map(|triple| { + ext_from_goldilocks::(&triple) + }) + .collect() + } + _ => unreachable!(), + }; (point, inverses) }) .collect(); @@ -1670,6 +1808,7 @@ where &inverse_counts, &coset_gold, ext_w, + ext_degree, ); let gpu_seconds = gpu_started.elapsed().as_secs_f64(); let cpu_denominators = cpu_denominators.join().unwrap(); @@ -1756,36 +1895,37 @@ where log2_strict_usize(polynomial_height); let shift_power = Val::GENERATOR .exp_power_of_2(log_polynomial_height); - let tasks = points - .iter() - .enumerate() - .map(|(point_index, &point)| { - let scale = (point - .exp_power_of_2(log_polynomial_height) - - shift_power) - * (Val::from_usize(polynomial_height) - * shift_power) - .inverse(); - lde.interpolation_task( - polynomial_height, - *inv_offsets.get(&point).unwrap(), - point_index * lde.width(), - to_pair(scale), - ) - }) - .collect_vec(); + let mut tasks = CudaInterpolationTasks::new(ext_degree); + for (point_index, &point) in points.iter().enumerate() { + let scale = (point + .exp_power_of_2(log_polynomial_height) + - shift_power) + * (Val::from_usize(polynomial_height) + * shift_power) + .inverse(); + let (scale_buf, d) = + ext_to_goldilocks::( + scale, ext_degree, + ); + tasks.push( + lde, + polynomial_height, + *inv_offsets.get(&point).unwrap(), + point_index * lde.width(), + &scale_buf[..d], + ); + } workspace .interpolate( &tasks, points.len() * lde.width(), ext_w, ) - .chunks_exact(lde.width()) + .chunks_exact(lde.width() * ext_degree) .map(|values| { values - .iter() - .copied() - .map(from_pair) + .chunks_exact(ext_degree) + .map(ext_from_goldilocks::) .collect_vec() }) .collect_vec() @@ -1828,14 +1968,35 @@ where } } } - let alpha: Challenge = challenger.sample_algebra_element(); - let alpha_powers: Vec<_> = alpha.powers().take(cuda_max_width).collect(); - let alpha_pairs: Vec<_> = alpha_powers.iter().copied().map(to_pair).collect(); - let packed_alpha_powers = - Challenge::ExtensionPacking::packed_ext_powers_capped(alpha, cuda_max_width) - .collect_vec(); + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.powers().take(opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; + let mut col_weights_flat = Vec::with_capacity(col_weights.len() * ext_degree); + for &w in &col_weights { + let (buf, d) = ext_to_goldilocks::(w, ext_degree); + col_weights_flat.extend_from_slice(&buf[..d]); + } + let packed_col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + Challenge::ExtensionPacking::packed_ext_powers_capped(*alpha, opened_max_width) + .collect_vec() + } + FriBatchingSchedule::Tensor { col_weights, .. } => { + pack_ext_weights::(col_weights) + } + }; let mut num_reduced = [0usize; 33]; - let reduction_offsets = commitment_data_with_opening_points + let mut opening_idx_by_height = [0usize; 33]; + let reduction_offsets: Vec>> = commitment_data_with_opening_points .iter() .zip(dimensions.iter()) .map(|((_, points), round_dimensions)| { @@ -1847,8 +2008,16 @@ where points .iter() .map(|_| { - let offset = num_reduced[log_height]; + let offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.exp_u64(num_reduced[log_height] as u64) + } + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[log_height]] + } + }; num_reduced[log_height] += dims.width; + opening_idx_by_height[log_height] += 1; offset }) .collect_vec() @@ -1894,16 +2063,15 @@ where let target = reduced[log_height] .get_or_insert_with(|| vec![Challenge::ZERO; dims.height]); let compressed = matrix - .rowwise_packed_dot_product::(&packed_alpha_powers) + .rowwise_packed_dot_product::(&packed_col_weights) .collect::>(); - for ((&point, values), &offset) in + for ((&point, values), &alpha_offset) in points.iter().zip(openings).zip(offsets) { let reduced_y: Challenge = dot_product( - alpha_powers.iter().copied(), + col_weights.iter().copied(), values.iter().copied(), ); - let alpha_offset = alpha.exp_u64(offset as u64); compressed .par_iter() .zip(target.par_iter_mut()) @@ -1919,7 +2087,7 @@ where let gpu_started = std::time::Instant::now(); let mut reduced: [Option; 33] = core::array::from_fn(|_| None); - let mut reduction_tasks = Vec::new(); + let mut reduction_tasks = CudaReductionTasks::new(ext_degree); for ((((data, points), round_dimensions), openings_round), offsets_round) in commitment_data_with_opening_points .iter() @@ -1942,30 +2110,37 @@ where } let log_height = log2_strict_usize(dims.height); let target = reduced[log_height].get_or_insert_with(|| { - CudaReducedOpening::new(device_id, dims.height) + CudaReducedOpening::new_with_degree( + device_id, + dims.height, + ext_degree, + ) }); self.mmcs.with_resident_matrix(data, matrix_index, |lde| { - reduction_tasks.extend( - points.iter().zip(openings).zip(offsets).map( - |((&point, values), &offset)| { - let reduced_y = dot_product( - alpha_powers.iter().copied(), - values.iter().copied(), - ); - target.reduction_task( - lde, - *inv_offsets.get(&point).unwrap(), - to_pair(reduced_y), - to_pair(alpha.exp_u64(offset as u64)), - ) - }, - ), - ); + for ((&point, values), &offset) in + points.iter().zip(openings).zip(offsets) + { + let reduced_y: Challenge = dot_product( + col_weights.iter().copied(), + values.iter().copied(), + ); + let (y_buf, d) = + ext_to_goldilocks::(reduced_y, ext_degree); + let (off_buf, _) = + ext_to_goldilocks::(offset, ext_degree); + reduction_tasks.push( + target, + lde, + *inv_offsets.get(&point).unwrap(), + &y_buf[..d], + &off_buf[..d], + ); + } }); } } if !reduction_tasks.is_empty() { - workspace.reduce(&reduction_tasks, &alpha_pairs, ext_w); + workspace.reduce(&reduction_tasks, &col_weights_flat, ext_w); } let gpu_seconds = gpu_started.elapsed().as_secs_f64(); let cpu_reduced = cpu_reduced.join().unwrap(); @@ -1975,10 +2150,17 @@ where for (log_height, cpu_values) in cpu_reduced.into_iter().enumerate() { if let Some(cpu_values) = cpu_values { - let values = cpu_values.into_iter().map(to_pair).collect_vec(); + let count = cpu_values.len(); + let mut flat = Vec::with_capacity(count * ext_degree); + for value in cpu_values { + let (buf, d) = ext_to_goldilocks::(value, ext_degree); + flat.extend_from_slice(&buf[..d]); + } gpu_reduced[log_height] - .get_or_insert_with(|| CudaReducedOpening::new(device_id, values.len())) - .add_host(&values); + .get_or_insert_with(|| { + CudaReducedOpening::new_with_degree(device_id, count, ext_degree) + }) + .add_host_flat(&flat); } } if crate::cuda::memory_diagnostics_enabled() { @@ -2000,6 +2182,8 @@ where &commitment_data_with_opening_points, &self.mmcs, ext_w, + ext_degree, + domain_v6, ) }); if crate::cuda::memory_diagnostics_enabled() { @@ -2032,12 +2216,11 @@ where }) .collect_vec(); - // Find the maximum height and the maximum width of matrices in the batch. - // These do not need to correspond to the same matrix. - let (global_max_height, global_max_width) = mats_and_points + // Find the maximum height of matrices in the batch. + let global_max_height = mats_and_points .iter() - .flat_map(|(mats, _)| mats.iter().map(|m| (m.height(), m.width()))) - .reduce(|(hmax, wmax), (h, w)| (hmax.max(h), wmax.max(w))) + .flat_map(|(mats, _)| mats.iter().map(|m| m.height())) + .max() .expect("No Matrices Supplied?"); let log_global_max_height = log2_strict_usize(global_max_height); @@ -2070,14 +2253,6 @@ where // For each collection of matrices izip!(mats.iter(), points.iter()) .map(|(mat, points_for_mat)| { - // TODO: This assumes that every input matrix has a blowup of at least self.fri.log_blowup. - // If the blow_up factor is smaller than self.fri.log_blowup, this will lead to errors. - // If it is bigger, we shouldn't get any errors but it will be slightly slower. - // Ideally, polynomials could be passed in with their blow_up factors known. - - // The point of this correction is that each column of the matrix corresponds to a low degree polynomial. - // Hence we can save time by restricting the height of the matrix to be the minimal height which - // uniquely identifies the polynomial. let h = mat.height() >> self.fri.log_blowup; // `subgroup` and `mat` are both in bit-reversed order, so we can truncate. @@ -2112,47 +2287,31 @@ where }) .collect_vec(); - // Batch combination challenge - - // Soundness Error: - // See the discussion in the doc comment of [`prove_fri`]. Essentially, the soundness error - // for this sample is tightly tied to the soundness error of the FRI protocol. - // Roughly speaking, at a minimum is it k/|EF| where `k` is the sum of, for each function, the number of - // points it needs to be opened at. This comes from the fact that we are taking a large linear combination - // of `(f(zeta) - f(x))/(zeta - x)` for each function `f` and all of `f`'s opening points. - // In our setup, k is two times the trace width plus the number of quotient polynomials. - let alpha: Challenge = challenger.sample_algebra_element(); - - // We precompute powers of alpha as we need the same powers for each matrix. - // We compute both a vector of unpacked powers and a vector of packed powers. - // TODO: It should be possible to refactor this to only use the packed powers but - // this is not a bottleneck so is not a priority. - let packed_alpha_powers = - Challenge::ExtensionPacking::packed_ext_powers_capped(alpha, global_max_width) - .collect_vec(); - let alpha_powers = - Challenge::ExtensionPacking::to_ext_iter(packed_alpha_powers.iter().copied()) - .collect_vec(); - - // Now that we have sent the openings to the verifier, it remains to prove - // that those openings are correct. - - // Given a low degree polynomial `f(x)` with claimed evaluation `f(zeta)`, we can check - // that `f(zeta)` is correct by doing a low degree test on `(f(zeta) - f(x))/(zeta - x)`. - // We will use `alpha` to batch together both different claimed openings `zeta` and - // different polynomials `f` whose evaluation vectors have the same height. - - // TODO: If we allow different polynomials to have different blow_up factors - // we may need to revisit this and to ensure it is safe to batch them together. - - // num_reduced records the number of (function, opening point) pairs for each `log_height`. - // TODO: This should really be `[0; Val::TWO_ADICITY]` but that runs into issues with generics. - let mut num_reduced = [0; 33]; + // Batch combination schedule (Horner or multilinear Tensor). + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let packed_col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + Challenge::ExtensionPacking::packed_ext_powers_capped(*alpha, opened_max_width) + .collect_vec() + } + FriBatchingSchedule::Tensor { col_weights, .. } => { + pack_ext_weights::(col_weights) + } + }; + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.powers().take(opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; - // For each `log_height` from 2^1 -> 2^32, reduced_openings will contain either `None` - // if there are no matrices of that height, or `Some(vec)` where `vec` is equal to - // a weighted sum of `(f(zeta) - f(x))/(zeta - x)` over all `f`'s of that height and - // for each `f`, all opening points `zeta`. The sum is weighted by powers of the challenge alpha. + let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; let mut reduced_openings: [_; 33] = core::array::from_fn(|_| None); for ((mats, points), openings_for_round) in @@ -2161,54 +2320,45 @@ where for (mat, points_for_mat, openings_for_mat) in izip!(mats.iter(), points.iter(), openings_for_round.iter()) { + if points_for_mat.is_empty() { + continue; + } let _guard = debug_span!("reduce matrix quotient", dims = %mat.dimensions()).entered(); let log_height = log2_strict_usize(mat.height()); - // If this is our first matrix at this height, initialise reduced_openings to zero. - // Otherwise, get a mutable reference to it. let reduced_opening_for_log_height = reduced_openings[log_height] .get_or_insert_with(|| vec![Challenge::ZERO; mat.height()]); debug_assert_eq!(reduced_opening_for_log_height.len(), mat.height()); - // Treating our matrix M as the evaluations of functions f_0, f_1, ... - // Compute the evaluations of `Mred(x) = f_0(x) + alpha*f_1(x) + ...` let mat_compressed = debug_span!("compress mat").in_scope(|| { - // This will be reused for all points z which M is opened at so we collect into a vector. - mat.rowwise_packed_dot_product::(&packed_alpha_powers) + mat.rowwise_packed_dot_product::(&packed_col_weights) .collect::>() }); for (&point, openings) in points_for_mat.iter().zip(openings_for_mat) { - // If we have multiple matrices at the same height, we need to scale alpha to combine them. - // This means that reduced_openings will contain: - // Mred_0(x) + alpha^{M_0.width()}Mred_1(x) + alpha^{M_0.width() + M_1.width()}Mred_2(x) + ... - // Where M_0, M_1, ... are the matrices of the same height. - let alpha_pow_offset = alpha.exp_u64(num_reduced[log_height] as u64); - - // As we have all the openings `f_i(z)`, we can combine them using `alpha` - // in an identical way to before to compute `Mred(z)`. + let alpha_pow_offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.exp_u64(num_reduced[log_height] as u64) + } + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[log_height]] + } + }; + let reduced_openings: Challenge = - dot_product(alpha_powers.iter().copied(), openings.iter().copied()); + dot_product(col_weights.iter().copied(), openings.iter().copied()); mat_compressed .par_iter() .zip(reduced_opening_for_log_height.par_iter_mut()) - // inv_denoms contains `1/(z - x)` for `x` in a coset `gK`. - // If `|K| =/= mat.height()` we actually want a subset of this - // corresponding to the evaluations over `gH` for `|H| = mat.height()`. - // As inv_denoms is bit reversed, the evaluations over `gH` are exactly - // the evaluations over `gK` at the indices `0..mat.height()`. - // So zip will truncate to the desired smaller length. .zip(inv_denoms.get(&point).unwrap().par_iter()) - // Map the function `Mred(x) -> (Mred(z) - Mred(x))/(z - x)` - // across the evaluation vector of `Mred(x)`. Adjust by alpha_pow_offset - // as needed. .for_each(|((&reduced_row, ro), &inv_denom)| { *ro += alpha_pow_offset * (reduced_openings - reduced_row) * inv_denom; }); num_reduced[log_height] += mat.width(); + opening_idx_by_height[log_height] += 1; } } } @@ -2254,13 +2404,14 @@ where let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); - verifier::verify_fri( + verify_fri_with_batching( &folding, &self.fri, proof, challenger, &commitments_with_opening_points, &self.mmcs, + self.batching, )?; Ok(()) diff --git a/src/cuda/tests/quotient.rs b/src/cuda/tests/quotient.rs index df71a0f..ffb2ce2 100644 --- a/src/cuda/tests/quotient.rs +++ b/src/cuda/tests/quotient.rs @@ -281,6 +281,10 @@ fn check_quotient( .collect(), 2, ); + let ext_w = match ext.modulus { + crate::traits::ExtensionModulus::Binomial { w } => w, + _ => Goldilocks::ZERO, + }; let actual_values = quotient_values_resident( &circuit.graph, (circuit.preprocessed_width != 0).then_some(&resident[0]), @@ -290,7 +294,8 @@ fn check_quotient( selectors, &alpha_flat, &delta, - ext.w, + ext_w, + ext.degree, quotient_size, quotient_degree, group_size, @@ -336,7 +341,8 @@ fn check_quotient( selectors, &alpha_flat, &delta, - ext.w, + ext_w, + ext.degree, quotient_size, quotient_degree, group_size, diff --git a/src/cuda/witness.rs b/src/cuda/witness.rs index a7e4bad..480a3cf 100644 --- a/src/cuda/witness.rs +++ b/src/cuda/witness.rs @@ -2,15 +2,16 @@ use std::sync::{OnceLock, atomic::AtomicBool}; -use p3_commit::Pcs; -use p3_field::Field; +use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; +use p3_commit::{ExtensionMmcs, Pcs}; +use p3_field::{ExtensionField, Field, coset::TwoAdicMultiplicativeCoset}; use p3_matrix::{Dimensions, dense::RowMajorMatrix}; use p3_symmetric::MerkleCap; -use super::mmcs::CudaMmcsData; -use super::{CudaLde, CudaMixedMerkleTree, device_memory_info}; -use crate::config::{Com, Domain, PcsData}; -use crate::types::{GoldilocksBlake3Config as Config, InnerPcs as CudaPcs, Val}; +use super::mmcs::{CudaMmcs, CudaMmcsData}; +use super::pcs::CudaTwoAdicFriPcs; +use super::{CudaDft, CudaLde, CudaMixedMerkleTree, device_memory_info}; +use crate::types::Val; use crate::witness::TraceSource; pub(crate) fn record_lde_spill(device: i32, bytes: usize) { @@ -25,10 +26,16 @@ fn spill_lde(lde: &CudaLde) -> RowMajorMatrix { matrix } -pub(crate) fn commit( - pcs: &CudaPcs, - evaluations: Vec<(Domain, TraceSource)>, -) -> (Com, PcsData) { +pub(crate) fn commit( + pcs: &CudaTwoAdicFriPcs>, + evaluations: Vec<(TwoAdicMultiplicativeCoset, TraceSource)>, +) -> (MerkleCap, CudaMmcsData>) +where + EF: ExtensionField, + Ch: FieldChallenger + + CanObserve> + + GrindingChallenger, +{ if evaluations .iter() .all(|(_, m)| matches!(m, TraceSource::Host(_))) @@ -38,7 +45,10 @@ pub(crate) fn commit( path = "host_pcs", "main commitment path" ); - return >::commit( + return > as Pcs< + EF, + Ch, + >>::commit( pcs, evaluations.into_iter().map(|(d, m)| (d, m.materialize())), ); @@ -172,9 +182,16 @@ pub(crate) fn commit( &resident_refs, &deferred, &std::collections::BTreeSet::new(), + pcs.mmcs.leaf_domain(), + ); + let tree = CudaMixedMerkleTree::from_hybrid_with_domain( + device, + &resident_refs, + &host_refs, + &deferred, + &digests, + pcs.mmcs.is_domain_v6(), ); - let tree = - CudaMixedMerkleTree::from_hybrid(device, &resident_refs, &host_refs, &deferred, &digests); let commitment = MerkleCap::new(vec![tree.root()]); let active = host.iter().map(|h| AtomicBool::new(h.is_none())).collect(); let committed = host diff --git a/src/lookup.rs b/src/lookup.rs index f7f06d9..8bbd488 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -1396,11 +1396,12 @@ impl LookupValues { group_size: usize, lookup_challenge: EF, fingerprint_challenge: &EF, - ) -> Vec<[p3_goldilocks::Goldilocks; 2]> { + ) -> Vec { self.require_payload(); assert!(rows.start <= rows.end && rows.end <= self.height); assert!(self.num_lookups != 0); - assert_eq!(>::D, 2); + let d = >::D; + assert!(d == 2 || d == 3, "CUDA supports extension degrees 2 and 3"); let group_size = group_size.max(1); let slots = lookup_groups(self.num_lookups, group_size); let message_start = rows.start * self.num_lookups; @@ -1419,24 +1420,23 @@ impl LookupValues { .collect::>(); let inverses = crate::traits::batch_inverse(&messages); drop(messages); - (0..(rows.end - rows.start) * slots) - .into_par_iter() - .map(|index| { - let local_row = index / slots; - let slot = index % slots; - let begin = slot * group_size; - let end = (begin + group_size).min(self.num_lookups); - let row = rows.start + local_row; - let inverse_row = local_row * self.num_lookups; - let mut delta = >::ZERO; - for lookup in begin..end { - let multiplicity = self.multiplicities[row * self.num_lookups + lookup]; - delta += EF::from(multiplicity) * inverses[inverse_row + lookup]; - } - let coordinates = delta.as_basis_coefficients_slice(); - [coordinates[0], coordinates[1]] - }) - .collect() + let count = (rows.end - rows.start) * slots; + let mut flat = vec![p3_goldilocks::Goldilocks::ZERO; count * d]; + flat.par_chunks_mut(d).enumerate().for_each(|(index, dst)| { + let local_row = index / slots; + let slot = index % slots; + let begin = slot * group_size; + let end = (begin + group_size).min(self.num_lookups); + let row = rows.start + local_row; + let inverse_row = local_row * self.num_lookups; + let mut delta = >::ZERO; + for lookup in begin..end { + let multiplicity = self.multiplicities[row * self.num_lookups + lookup]; + delta += EF::from(multiplicity) * inverses[inverse_row + lookup]; + } + dst.copy_from_slice(delta.as_basis_coefficients_slice()); + }); + flat } pub(crate) fn cuda_parts( diff --git a/src/p3_adapter/domain_blake3.rs b/src/p3_adapter/domain_blake3.rs index d98e4a1..ec28ff3 100644 --- a/src/p3_adapter/domain_blake3.rs +++ b/src/p3_adapter/domain_blake3.rs @@ -362,4 +362,122 @@ mod tests { } } } + + #[test] + fn cuda_v6_context_key_words_match_rust_constants() { + // Pinned constants shared with `cuda/kernels.cu` (`BLAKE3_V6_LEAF_CV` + // and `BLAKE3_V6_COMPRESS_CV`). If any context string ever changes, + // update both Rust and `cuda/kernels.cu` together. + assert_eq!( + Blake3Domain::MerkleLeaf.key_words(), + [ + 0x7704_2819, + 0x5A1D_D04F, + 0x2F8D_0BB8, + 0x39D2_7832, + 0x552A_30F6, + 0x546C_9899, + 0x8510_A8EF, + 0x83EC_CD66, + ] + ); + assert_eq!( + Blake3Domain::MerkleCompress.key_words(), + [ + 0xCC4D_7633, + 0xF849_2FEC, + 0x5704_B1FD, + 0x2D69_A6B5, + 0xA871_EBB5, + 0x6439_610D, + 0x89E8_6BE6, + 0x02E2_2A34, + ] + ); + } + + #[test] + fn cuda_v6_blake3_and_ext3_vectors_match_rust() { + use crate::types::{ExtVal3, Val}; + use p3_field::{BasedVectorSpace, Field, PrimeCharacteristicRing, PrimeField64}; + + // Cross-checked directly against compiled `cuda/goldilocks.cuh` + + // `cuda/kernels.cu` (`ext3_mul`, `ext3_inverse`, `blake3_chunk`, + // `blake3_parent`, `blake3_hash_digest_pair`). + let va = ExtVal3::from_basis_coefficients_slice(&[ + Val::from_u64(0x1234_5678_9abc_def0), + Val::from_u64(0xfedc_ba98_7654_3210), + Val::from_u64(0x0000_0001_0000_0002), + ]) + .unwrap(); + let vb = ExtVal3::from_basis_coefficients_slice(&[ + Val::from_u64(0xffff_ffff_0000_0000), + Val::from_u64(0x1111_2222_3333_4444), + Val::from_u64(0xaaaa_5555_bbbb_6666), + ]) + .unwrap(); + let to_u64s = |x: ExtVal3| -> [u64; 3] { + let c: &[Val] = x.as_basis_coefficients_slice(); + [ + c[0].as_canonical_u64(), + c[1].as_canonical_u64(), + c[2].as_canonical_u64(), + ] + }; + assert_eq!( + to_u64s(va * vb), + [ + 7_455_192_430_764_610_520, + 13_204_415_317_809_093_084, + 11_719_710_893_822_699_134, + ] + ); + assert_eq!( + to_u64s(va.inverse()), + [ + 16_838_335_245_387_560_099, + 15_220_258_529_103_284_997, + 16_044_421_098_862_543_668, + ] + ); + + let to_hex = + |bytes: [u8; 32]| -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() }; + for (len, expected_hex) in [ + ( + 64usize, + "4059736d0564475319baa815a76396039b1922ce8b8c51985ec1489f48e4581a", + ), + ( + 512, + "58ec79936d612be378b23c2cfbb876f93179b825100d3ba77c2a8fd189deae51", + ), + ( + 1024, + "0f237b3cbe5c88760fcf0305435c2b6d762142697aa21133b6508af2bd228e9c", + ), + ( + 1025, + "1efbf193b24ebcabf1c230b0f7f2c30265d0a82272db4a19341767e688849358", + ), + ( + 4264, + "bb19b2a12d999d55cc3bb2caf75c085e201c6b387519dfa2cb25eec6b9b54136", + ), + ] { + let msg: Vec = (0..len) + .map(|i| u8::try_from((i * 37 + 13) & 0xff).unwrap()) + .collect(); + assert_eq!( + to_hex(Blake3Domain::MerkleLeaf.hash_bytes(&msg)), + expected_hex, + "v6 MerkleLeaf mismatch at len={len}" + ); + } + let pair: Vec = (0..64u8).collect(); + assert_eq!( + to_hex(Blake3Domain::MerkleCompress.hash_bytes(&pair)), + "8b14c7db6f612da11fa63c6fbec9783e35f74ab3dedf6f382fff8ace42e1b379" + ); + } } diff --git a/src/p3_adapter/fri_batching.rs b/src/p3_adapter/fri_batching.rs index 7ddafd7..a179663 100644 --- a/src/p3_adapter/fri_batching.rs +++ b/src/p3_adapter/fri_batching.rs @@ -919,6 +919,7 @@ mod tests { } } + #[cfg(not(feature = "cuda"))] fn run_pcs_horner_parity_and_tensor_roundtrip() where EF: ExtensionField + crate::traits::ExtensionOf, @@ -1209,6 +1210,7 @@ mod tests { ); } + #[cfg(not(feature = "cuda"))] #[test] fn fri_batching_horner_parity_and_tensor_fp2_and_fp3() { run_pcs_horner_parity_and_tensor_roundtrip::(); diff --git a/src/types.rs b/src/types.rs index 0514905..1c013f2 100644 --- a/src/types.rs +++ b/src/types.rs @@ -25,11 +25,9 @@ use p3_goldilocks::Goldilocks; use p3_matrix::Matrix; use p3_matrix::dense::RowMajorMatrix; use p3_maybe_rayon::prelude::*; -#[cfg(feature = "cuda")] -use p3_merkle_tree::MerkleTreeMmcs; -#[cfg(any(feature = "cuda", test))] +#[cfg(test)] use p3_symmetric::CompressionFunctionFromHasher; -#[cfg(any(feature = "cuda", test))] +#[cfg(test)] use p3_symmetric::SerializingHasher; #[cfg(feature = "cuda")] @@ -194,8 +192,6 @@ mod grind_tests { } } } -#[cfg(feature = "cuda")] -type CpuMmcs = MerkleTreeMmcs, Blake3CompressionFunction, 2, 32>; #[cfg(not(feature = "cuda"))] pub type Mmcs = crate::p3_adapter::spill::SpillableMmcs; #[cfg(feature = "cuda")] @@ -234,6 +230,639 @@ fn cuda_coset_selectors( } } +#[cfg(feature = "cuda")] +fn cuda_ext_params>() -> (usize, Val) { + let ext_degree = EF::D; + assert!( + ext_degree == 2 || ext_degree == 3, + "CUDA backend supports Goldilocks extension degrees 2 and 3, got {ext_degree}" + ); + let ext_w = match EF::MODULUS { + ExtensionModulus::Binomial { w } => w, + ExtensionModulus::CubicTrinomial => Val::ZERO, + ExtensionModulus::Base => panic!("CUDA backend requires an extension field"), + }; + (ext_degree, ext_w) +} + +#[cfg(feature = "cuda")] +#[allow(clippy::too_many_arguments)] +fn cuda_accelerated_quotient_values( + circuit: &crate::system::Circuit, + lookup_publics: &[Val], + trace_domain: Domain, + quotient_domain: Domain, + preprocessed: Option<(&ProverData, usize)>, + stage_1: (&ProverData, usize), + stage_2: (&ProverData, usize), + alpha: EF, + constraint_count: usize, +) -> Option> +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + if !crate::cuda::quotient_graph_supported(&circuit.graph) { + return None; + } + let main = stage_1.0.resident(stage_1.1)?; + let s2 = stage_2.0.resident(stage_2.1)?; + let prep = match preprocessed { + Some((data, index)) => Some(data.resident(index)?), + None => None, + }; + let (ext_degree, ext_w) = cuda_ext_params::(); + let qsize = quotient_domain.size(); + let selectors = cuda_coset_selectors(trace_domain, quotient_domain); + let mut powers = Vec::with_capacity(constraint_count); + let mut power = ::ONE; + for _ in 0..constraint_count { + powers.push(power); + power *= alpha; + } + powers.reverse(); + let mut alpha_flat = Vec::with_capacity(ext_degree * constraint_count); + for coordinate in 0..ext_degree { + alpha_flat.extend( + powers + .iter() + .map(|x| >::as_basis_coefficients_slice(x)[coordinate]), + ); + } + let n = Val::from_usize(trace_domain.size()); + let g = Val::two_adic_generator(trace_domain.size().ilog2() as usize); + let norm = (n * g).inverse(); + let delta: Vec = (0..ext_degree) + .map(|c| (lookup_publics[3 * ext_degree + c] - lookup_publics[2 * ext_degree + c]) * norm) + .collect(); + let next_step = 1usize << (quotient_domain.size().ilog2() - trace_domain.size().ilog2()); + let flat = crate::cuda::quotient_values_resident( + &circuit.graph, + prep, + main, + s2, + lookup_publics, + selectors, + &alpha_flat, + &delta, + ext_w, + ext_degree, + qsize, + next_step, + circuit.lookup_group_size, + ); + Some( + flat.values + .chunks_exact(ext_degree) + .map(|coords| { + EF::from_basis_coefficients_slice(coords) + .expect("CUDA quotient coordinate count mismatch") + }) + .collect(), + ) +} + +#[cfg(feature = "cuda")] +struct CudaQuotientJob<'a> { + circuit: &'a crate::system::Circuit, + lookup_publics: &'a [Val], + trace_domain: Domain, + quotient_domain: Domain, + preprocessed: Option<(&'a ProverData, usize)>, + stage_1: (&'a ProverData, usize), + stage_2: (&'a ProverData, usize), + constraint_count: usize, +} + +#[cfg(feature = "cuda")] +fn cuda_accelerated_quotient_commit( + dft: &CudaDft, + mmcs: &Mmcs, + log_blowup: usize, + inputs: &[CudaQuotientJob<'_>], + alpha: EF, +) -> Option<(Commitment, ProverData)> +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + use crate::cuda::mmcs::CudaCommitMmcs; + + if inputs + .iter() + .any(|input| !crate::cuda::quotient_graph_supported(&input.circuit.graph)) + { + return None; + } + let (ext_degree, ext_w) = cuda_ext_params::(); + let (_, total_device_bytes) = crate::cuda::device_memory_info(mmcs.cuda_device_id()); + let matrix_width = |data: &ProverData, index: usize| { + let dimensions = mmcs.matrix_dimensions(data); + dimensions + .get(index) + .expect("matrix index out of bounds") + .width + }; + let staging_bytes = |input: &CudaQuotientJob<'_>| { + let mut host_width = 0usize; + for (data, index) in [Some(input.stage_1), Some(input.stage_2), input.preprocessed] + .into_iter() + .flatten() + { + if !mmcs.is_matrix_cuda_resident(data, index) { + host_width = host_width.saturating_add(matrix_width(data, index)); + } + } + if host_width == 0 { + return 0; + } + let row_bytes = host_width + .saturating_mul(2) + .saturating_mul(size_of::()); + let per_buffer = input + .quotient_domain + .size() + .saturating_mul(row_bytes) + .min(512usize << 20); + 2usize.saturating_mul(per_buffer) + }; + let mut quotient_jobs = inputs + .iter() + .enumerate() + .map(|(index, input)| { + let quotient_size = input.quotient_domain.size(); + let quotient_degree = input.circuit.quotient_degree(); + let trace_height = quotient_size / quotient_degree; + let lde_height = trace_height + .checked_shl(u32::try_from(log_blowup).expect("LDE blowup exceeds u32")) + .unwrap_or(usize::MAX); + let (output_bytes, kernel_workspace) = crate::cuda::quotient_lde_memory_upper_bound( + &input.circuit.graph, + input.lookup_publics.len(), + input.constraint_count, + quotient_size, + quotient_degree, + log_blowup, + ext_degree, + ); + let current_staging = staging_bytes(input); + let constant_bytes = quotient_degree.saturating_mul(size_of::()); + let quotient_plan = dft.forward_plan(quotient_size, ext_degree); + let lde_plan = dft.forward_plan(lde_height, ext_degree * quotient_degree); + let kernel_workspace = kernel_workspace + .saturating_add(quotient_plan.scratch_bytes().max(lde_plan.scratch_bytes())); + ( + index, + output_bytes, + kernel_workspace, + constant_bytes, + current_staging + .saturating_add(kernel_workspace) + .saturating_add(output_bytes) + .saturating_add(constant_bytes), + lde_height, + ) + }) + .collect::>(); + quotient_jobs.sort_unstable_by_key(|&(index, _, _, _, peak, _)| { + let input = &inputs[index]; + let ready = [Some(input.stage_1), Some(input.stage_2), input.preprocessed] + .into_iter() + .flatten() + .all(|(data, matrix)| mmcs.is_matrix_source_ready(data, matrix)); + (!ready, core::cmp::Reverse(peak)) + }); + let accumulated_output = quotient_jobs + .iter() + .map(|&(_, output, _, _, _, _)| output) + .sum::(); + let max_lde_height = quotient_jobs + .iter() + .map(|&(_, _, _, _, _, lde_height)| lde_height) + .max() + .unwrap_or(0); + if crate::cuda::memory_diagnostics_enabled() { + eprintln!( + "[multi-stark/cuda] quotient jobs={} output={}", + quotient_jobs.len(), + accumulated_output, + ); + } + + let mut ldes = (0..inputs.len()).map(|_| None).collect::>(); + for (index, output_bytes, kernel_workspace, constant_bytes, _, lde_height) in quotient_jobs { + let job_started = std::time::Instant::now(); + let input = &inputs[index]; + let current_staging = || staging_bytes(input); + let required = || { + current_staging() + .saturating_add(kernel_workspace) + .saturating_add(output_bytes) + .saturating_add(constant_bytes) + .saturating_add(total_device_bytes / 64) + }; + let mut target = required(); + mmcs.ensure_device_headroom(input.stage_1.0, target, Some(input.stage_1.1), "quotient"); + target = required(); + mmcs.ensure_device_headroom(input.stage_2.0, target, Some(input.stage_2.1), "quotient"); + if let Some((data, matrix)) = input.preprocessed { + target = required(); + mmcs.ensure_device_headroom(data, target, Some(matrix), "quotient"); + } + target = required(); + let free_bytes = crate::cuda::device_memory_info(mmcs.cuda_device_id()).0; + if crate::cuda::memory_diagnostics_enabled() { + eprintln!( + "[multi-stark/cuda] quotient job {index}: lde_height={lde_height} output={output_bytes} workspace={kernel_workspace} staging={} target={} free={free_bytes}", + current_staging(), + target + ); + } + if free_bytes < target { + return None; + } + let lde = { + let quotient_size = input.quotient_domain.size(); + let quotient_degree = input.circuit.quotient_degree(); + let selectors = cuda_coset_selectors(input.trace_domain, input.quotient_domain); + + let mut powers = Vec::with_capacity(input.constraint_count); + let mut power = ::ONE; + for _ in 0..input.constraint_count { + powers.push(power); + power *= alpha; + } + powers.reverse(); + let mut alpha_flat = Vec::with_capacity(ext_degree * input.constraint_count); + for coordinate in 0..ext_degree { + alpha_flat.extend(powers.iter().map(|value| { + >::as_basis_coefficients_slice(value)[coordinate] + })); + } + let trace_size = input.trace_domain.size(); + let n = Val::from_usize(trace_size); + let generator = Val::two_adic_generator(trace_size.ilog2() as usize); + let normalization = (n * generator).inverse(); + let delta: Vec = (0..ext_degree) + .map(|c| { + (input.lookup_publics[3 * ext_degree + c] + - input.lookup_publics[2 * ext_degree + c]) + * normalization + }) + .collect(); + let next_step = quotient_size / trace_size; + let evaluate = + |main: crate::cuda::mmcs::CudaMatrixSource<'_>, + stage2: crate::cuda::mmcs::CudaMatrixSource<'_>, + preprocessed: Option>| { + crate::cuda::quotient_lde_mixed( + dft, + &input.circuit.graph, + preprocessed, + main, + stage2, + input.lookup_publics, + selectors, + &alpha_flat, + &delta, + ext_w, + ext_degree, + quotient_size, + next_step, + input.circuit.lookup_group_size, + quotient_degree, + log_blowup, + ) + }; + mmcs.with_matrix_source(input.stage_1.0, input.stage_1.1, |main| { + mmcs.with_matrix_source(input.stage_2.0, input.stage_2.1, |stage2| { + match input.preprocessed { + Some((data, index)) => { + mmcs.with_matrix_source(data, index, |preprocessed| { + evaluate(main, stage2, Some(preprocessed)) + }) + } + None => evaluate(main, stage2, None), + } + }) + }) + }; + ldes[index] = Some(lde); + if crate::cuda::memory_diagnostics_enabled() { + eprintln!( + "[multi-stark/cuda] quotient job {index} complete: {:.3}s", + job_started.elapsed().as_secs_f64() + ); + } + } + let tree_headroom = max_lde_height + .saturating_mul(96) + .saturating_add(total_device_bytes / 64); + if let Some(input) = inputs.first() { + mmcs.ensure_device_headroom(input.stage_1.0, tree_headroom, None, "quotient_tree"); + mmcs.ensure_device_headroom(input.stage_2.0, tree_headroom, None, "quotient_tree"); + } + if let Some((data, _)) = inputs.iter().find_map(|input| input.preprocessed) { + mmcs.ensure_device_headroom(data, tree_headroom, None, "quotient_tree"); + } + if crate::cuda::device_memory_info(mmcs.cuda_device_id()).0 < tree_headroom { + return None; + } + Some( + mmcs.commit_cuda_spillable( + ldes.into_iter() + .map(|lde| lde.expect("quotient job did not run")) + .collect(), + ), + ) +} + +#[cfg(feature = "cuda")] +struct CudaLookupJob<'a> { + circuit: &'a crate::system::Circuit, + lookup_values: &'a crate::lookup::LookupValues, + preprocessed: Option<(&'a ProverData, usize)>, + stage_1: (&'a ProverData, usize), +} + +#[cfg(feature = "cuda")] +fn cuda_accelerated_lookup_commit( + dft: &CudaDft, + mmcs: &Mmcs, + log_blowup: usize, + inputs: &[CudaLookupJob<'_>], + lookup_challenge: EF, + fingerprint_challenge: EF, + mut accumulator: EF, +) -> Option<(Commitment, ProverData, Vec)> +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + use crate::cuda::mmcs::CudaCommitMmcs; + + let (ext_degree, ext_w) = cuda_ext_params::(); + let mut lookup_jobs = inputs + .iter() + .enumerate() + .map(|(index, input)| { + let (height, num_lookups, _, _, arg_offsets) = input.lookup_values.cuda_parts(); + let group_size = input.circuit.lookup_group_size.max(1); + let groups = num_lookups.div_ceil(group_size).max(1); + let extended_height = height + .checked_shl(u32::try_from(log_blowup).expect("LDE blowup exceeds u32")) + .unwrap_or(usize::MAX); + let output_bytes = extended_height + .saturating_mul(ext_degree) + .saturating_mul(groups) + .saturating_mul(size_of::()); + let direct_temporary_bytes = if num_lookups == 0 { + 0 + } else { + let args_width = *arg_offsets.last().expect("lookup offsets are empty"); + let chunk_rows = height.min(1 << 16); + let messages = chunk_rows.saturating_mul(num_lookups); + messages + // Multiplicity, adjugate (ext_degree words), norm, and inverse-norm arrays. + .saturating_mul((ext_degree + 3) * size_of::()) + .saturating_add( + chunk_rows + .saturating_mul(args_width) + .saturating_mul(size_of::()), + ) + // Extension-field deltas before the exclusive scan. + .saturating_add( + height + .saturating_mul(groups) + .saturating_mul(ext_degree * size_of::()), + ) + .saturating_add(arg_offsets.len().saturating_mul(size_of::())) + }; + let main_width = mmcs + .matrix_dimensions(input.stage_1.0) + .get(input.stage_1.1) + .expect("stage-1 matrix index out of bounds") + .width; + let graph_memory = (num_lookups != 0) + .then(|| { + crate::cuda::lookup_graph_lde_memory_upper_bound( + &input.circuit.graph, + height, + main_width, + group_size, + log_blowup, + ext_degree, + ) + }) + .flatten(); + let transform_bytes = if num_lookups == 0 { + 0 + } else { + let plan = dft.lde_plan(height, ext_degree * groups, log_blowup, Val::GENERATOR); + plan.scratch_bytes().saturating_add(plan.constant_bytes()) + }; + ( + index, + output_bytes, + direct_temporary_bytes.saturating_add(transform_bytes), + graph_memory.map(|(_, temporary)| temporary.saturating_add(transform_bytes)), + extended_height, + ) + }) + .collect::>(); + lookup_jobs.sort_unstable_by_key(|&(index, output, direct, graph, _)| { + let temporary = if inputs[index] + .stage_1 + .0 + .has_resident_with_trace(inputs[index].stage_1.1) + { + graph.unwrap_or(direct) + } else { + direct + }; + core::cmp::Reverse(output.saturating_add(temporary)) + }); + let accumulated_output = lookup_jobs + .iter() + .map(|&(_, output, _, _, _)| output) + .sum::(); + let max_lde_height = lookup_jobs + .iter() + .map(|&(_, _, _, _, extended_height)| extended_height) + .max() + .unwrap_or(0); + let (_, total_device_bytes) = crate::cuda::device_memory_info(mmcs.cuda_device_id()); + if crate::cuda::memory_diagnostics_enabled() { + eprintln!( + "[multi-stark/cuda] lookup jobs={} output={}", + lookup_jobs.len(), + accumulated_output, + ); + } + + let beta = >::as_basis_coefficients_slice(&lookup_challenge); + let gamma = >::as_basis_coefficients_slice(&fingerprint_challenge); + let lookup_pool = + std::sync::Arc::new(cuda_host_pool("lookup-rows", cuda_lookup_worker_count())); + let evaluate = |input: &CudaLookupJob<'_>, graph_path: bool, cooperative: bool| { + let (height, num_lookups, multiplicities, args, arg_offsets) = + input.lookup_values.cuda_parts(); + let group_size = input.circuit.lookup_group_size.max(1); + let main = graph_path.then(|| { + input + .stage_1 + .0 + .resident_with_trace(input.stage_1.1) + .expect("lookup graph admission requires a trace-backed resident LDE") + }); + let result = if let Some(main) = main { + let preprocessed = input.preprocessed.map(|(data, index)| { + data.resident(index) + .expect("lookup graph admission requires a resident preprocessed LDE") + }); + crate::cuda::lookup_graph_lde_resident( + dft, + &input.circuit.graph, + preprocessed, + main, + height, + group_size, + beta, + gamma, + ext_w, + ext_degree, + log_blowup, + ) + } else if cooperative { + let pool = std::sync::Arc::clone(&lookup_pool); + Some(crate::cuda::lookup_lde_resident_partitioned( + dft, + multiplicities, + args, + arg_offsets, + height, + num_lookups, + group_size, + beta, + gamma, + ext_w, + ext_degree, + log_blowup, + move |rows| { + pool.install(|| { + input.lookup_values.cuda_stage_2_deltas::( + rows, + group_size, + lookup_challenge, + &fingerprint_challenge, + ) + }) + }, + )) + } else { + Some(crate::cuda::lookup_lde_resident( + dft, + multiplicities, + args, + arg_offsets, + height, + num_lookups, + group_size, + beta, + gamma, + ext_w, + ext_degree, + log_blowup, + )) + }; + if let Some(main) = main { + unsafe { main.release_trace() }; + main.release_generator_device(); + } + result + }; + let mut results = (0..inputs.len()).map(|_| None).collect::>(); + for (index, output_bytes, direct_temporary_bytes, graph_temporary_bytes, _) in lookup_jobs { + let job_started = std::time::Instant::now(); + let input = &inputs[index]; + let admits_graph = || { + graph_temporary_bytes.is_some() + && input.stage_1.0.has_resident_with_trace(input.stage_1.1) + && input + .preprocessed + .is_none_or(|(data, matrix)| data.resident(matrix).is_some()) + }; + let target_for = |graph_path: bool| { + let temporary_bytes = if graph_path { + graph_temporary_bytes.unwrap() + } else { + direct_temporary_bytes + }; + ( + temporary_bytes, + output_bytes + .saturating_add(temporary_bytes) + .saturating_add(total_device_bytes / 64), + ) + }; + let mut graph_path = admits_graph(); + let (mut temporary_bytes, mut target) = target_for(graph_path); + if target > total_device_bytes { + return None; + } + let mut free_bytes = + mmcs.ensure_device_headroom(input.stage_1.0, target, Some(input.stage_1.1), "lookup"); + if free_bytes < target { + free_bytes = mmcs.ensure_device_headroom(input.stage_1.0, target, None, "lookup"); + graph_path = admits_graph(); + (temporary_bytes, target) = target_for(graph_path); + if free_bytes < target { + free_bytes = mmcs.ensure_device_headroom(input.stage_1.0, target, None, "lookup"); + } + } + if free_bytes < target { + return None; + } + if !graph_path && !input.lookup_values.is_materialized() { + return None; + } + if crate::cuda::memory_diagnostics_enabled() { + eprintln!( + "[multi-stark/cuda] lookup job {index}: graph={graph_path} output={output_bytes} temporary={temporary_bytes} target={target} free={free_bytes}" + ); + } + let (_, num_lookups, _, _, arg_offsets) = input.lookup_values.cuda_parts(); + let cooperative = !graph_path + && output_bytes >= (8usize << 30) + && num_lookups >= 64 + && arg_offsets.last().copied().unwrap_or(0) >= 256; + results[index] = Some(evaluate(&inputs[index], graph_path, cooperative)?); + if crate::cuda::memory_diagnostics_enabled() { + eprintln!( + "[multi-stark/cuda] lookup job {index} complete: {:.3}s", + job_started.elapsed().as_secs_f64() + ); + } + } + let tree_headroom = max_lde_height + .saturating_mul(96) + .saturating_add(total_device_bytes / 64); + if let Some(input) = inputs.first() { + let free_bytes = + mmcs.ensure_device_headroom(input.stage_1.0, tree_headroom, None, "lookup_tree"); + if free_bytes < tree_headroom { + return None; + } + } + let mut ldes = Vec::with_capacity(results.len()); + let mut intermediates = Vec::with_capacity(inputs.len()); + for result in results { + let (lde, total) = result.expect("lookup job did not run"); + accumulator += EF::from_basis_coefficients_slice(&total)?; + intermediates.push(accumulator); + ldes.push(lde); + } + let (commitment, data) = mmcs.commit_cuda_spillable(ldes); + Some((commitment, data, intermediates)) +} + #[cfg(feature = "cuda")] fn cuda_worker_count(variable: &str, numerator: usize, denominator: usize) -> usize { let default_threads = std::thread::available_parallelism() @@ -458,7 +1087,7 @@ impl ProofConfig for GoldilocksBlake3Config { crate::witness::TraceSource, )>, ) -> (crate::config::Com, crate::config::PcsData) { - crate::cuda::witness::commit(&self.pcs, evaluations) + crate::cuda::witness::commit::(&self.pcs, evaluations) } #[cfg(not(feature = "cuda"))] @@ -762,62 +1391,16 @@ impl ProofConfig for GoldilocksBlake3Config { alpha: ExtVal, constraint_count: usize, ) -> Option> { - if !crate::cuda::quotient_graph_supported(&circuit.graph) { - return None; - } - let main = stage_1.0.resident(stage_1.1)?; - let s2 = stage_2.0.resident(stage_2.1)?; - let prep = match preprocessed { - Some((data, index)) => Some(data.resident(index)?), - None => None, - }; - let qsize = quotient_domain.size(); - let selectors = cuda_coset_selectors(trace_domain, quotient_domain); - let mut powers = Vec::with_capacity(constraint_count); - let mut power = ExtVal::ONE; - for _ in 0..constraint_count { - powers.push(power); - power *= alpha; - } - powers.reverse(); - let mut alpha_flat = Vec::with_capacity(2 * constraint_count); - for coordinate in 0..2 { - alpha_flat.extend(powers.iter().map(|x| { - >::as_basis_coefficients_slice(x)[coordinate] - })); - } - let n = Val::from_usize(trace_domain.size()); - let g = Val::two_adic_generator(trace_domain.size().ilog2() as usize); - let norm = (n * g).inverse(); - let delta = [ - (lookup_publics[6] - lookup_publics[4]) * norm, - (lookup_publics[7] - lookup_publics[5]) * norm, - ]; - let next_step = 1usize << (quotient_domain.size().ilog2() - trace_domain.size().ilog2()); - let flat = crate::cuda::quotient_values_resident( - &circuit.graph, - prep, - main, - s2, + cuda_accelerated_quotient_values( + circuit, lookup_publics, - selectors, - &alpha_flat, - &delta, - crate::system::extension_params::().w, - qsize, - next_step, - circuit.lookup_group_size, - ); - Some( - flat.values - .as_chunks::<2>() - .0 - .iter() - .map(|coords| { - ExtVal::from_basis_coefficients_slice(coords) - .expect("CUDA quotient has two coordinates") - }) - .collect(), + trace_domain, + quotient_domain, + preprocessed, + stage_1, + stage_2, + alpha, + constraint_count, ) } @@ -827,264 +1410,25 @@ impl ProofConfig for GoldilocksBlake3Config { inputs: &[crate::config::QuotientCommitInput<'_, Self>], alpha: ExtVal, ) -> Option<(crate::config::Com, crate::config::PcsData)> { - use crate::cuda::mmcs::CudaCommitMmcs; - - // The fused path commits every circuit's quotient from one device - // batch, so one circuit without a device evaluation sends the whole - // batch through the per-circuit path. - if inputs + let jobs: Vec> = inputs .iter() - .any(|input| !crate::cuda::quotient_graph_supported(&input.circuit.graph)) - { - return None; - } - let (_, total_device_bytes) = - crate::cuda::device_memory_info(self.pcs.mmcs.cuda_device_id()); - let matrix_width = |data: &crate::config::PcsData, index: usize| { - let dimensions = self.pcs.mmcs.matrix_dimensions(data); - dimensions - .get(index) - .expect("matrix index out of bounds") - .width - }; - let staging_bytes = |input: &crate::config::QuotientCommitInput<'_, Self>| { - let mut host_width = 0usize; - for (data, index) in [Some(input.stage_1), Some(input.stage_2), input.preprocessed] - .into_iter() - .flatten() - { - if !self.pcs.mmcs.is_matrix_cuda_resident(data, index) { - host_width = host_width.saturating_add(matrix_width(data, index)); - } - } - if host_width == 0 { - return 0; - } - let row_bytes = host_width - .saturating_mul(2) - .saturating_mul(size_of::()); - let per_buffer = input - .quotient_domain - .size() - .saturating_mul(row_bytes) - .min(512usize << 20); - 2usize.saturating_mul(per_buffer) - }; - let mut quotient_jobs = inputs - .iter() - .enumerate() - .map(|(index, input)| { - let quotient_size = input.quotient_domain.size(); - let quotient_degree = input.circuit.quotient_degree(); - let trace_height = quotient_size / quotient_degree; - let lde_height = trace_height - .checked_shl(u32::try_from(self.log_blowup).expect("LDE blowup exceeds u32")) - .unwrap_or(usize::MAX); - let (output_bytes, kernel_workspace) = crate::cuda::quotient_lde_memory_upper_bound( - &input.circuit.graph, - input.lookup_publics.len(), - input.constraint_count, - quotient_size, - quotient_degree, - self.log_blowup, - ); - let current_staging = staging_bytes(input); - let constant_bytes = quotient_degree.saturating_mul(size_of::()); - let quotient_plan = self.pcs.dft.forward_plan(quotient_size, 2); - let lde_plan = self.pcs.dft.forward_plan(lde_height, 2 * quotient_degree); - let kernel_workspace = kernel_workspace - .saturating_add(quotient_plan.scratch_bytes().max(lde_plan.scratch_bytes())); - ( - index, - output_bytes, - kernel_workspace, - constant_bytes, - current_staging - .saturating_add(kernel_workspace) - .saturating_add(output_bytes) - .saturating_add(constant_bytes), - lde_height, - ) + .map(|input| CudaQuotientJob { + circuit: input.circuit, + lookup_publics: &input.lookup_publics, + trace_domain: input.trace_domain, + quotient_domain: input.quotient_domain, + preprocessed: input.preprocessed, + stage_1: input.stage_1, + stage_2: input.stage_2, + constraint_count: input.constraint_count, }) - .collect::>(); - quotient_jobs.sort_unstable_by_key(|&(index, _, _, _, peak, _)| { - let input = &inputs[index]; - let ready = [Some(input.stage_1), Some(input.stage_2), input.preprocessed] - .into_iter() - .flatten() - .all(|(data, matrix)| self.pcs.mmcs.is_matrix_source_ready(data, matrix)); - (!ready, core::cmp::Reverse(peak)) - }); - let accumulated_output = quotient_jobs - .iter() - .map(|&(_, output, _, _, _, _)| output) - .sum::(); - let max_lde_height = quotient_jobs - .iter() - .map(|&(_, _, _, _, _, lde_height)| lde_height) - .max() - .unwrap_or(0); - if crate::cuda::memory_diagnostics_enabled() { - eprintln!( - "[multi-stark/cuda] quotient jobs={} output={}", - quotient_jobs.len(), - accumulated_output, - ); - } - - let mut ldes = (0..inputs.len()).map(|_| None).collect::>(); - for (index, output_bytes, kernel_workspace, constant_bytes, _, lde_height) in quotient_jobs - { - let job_started = std::time::Instant::now(); - let input = &inputs[index]; - let current_staging = || staging_bytes(input); - let required = || { - current_staging() - .saturating_add(kernel_workspace) - .saturating_add(output_bytes) - .saturating_add(constant_bytes) - .saturating_add(total_device_bytes / 64) - }; - let mut target = required(); - self.pcs.mmcs.ensure_device_headroom( - input.stage_1.0, - target, - Some(input.stage_1.1), - "quotient", - ); - target = required(); - self.pcs.mmcs.ensure_device_headroom( - input.stage_2.0, - target, - Some(input.stage_2.1), - "quotient", - ); - if let Some((data, matrix)) = input.preprocessed { - target = required(); - self.pcs - .mmcs - .ensure_device_headroom(data, target, Some(matrix), "quotient"); - } - target = required(); - let free_bytes = crate::cuda::device_memory_info(self.pcs.mmcs.cuda_device_id()).0; - if crate::cuda::memory_diagnostics_enabled() { - eprintln!( - "[multi-stark/cuda] quotient job {index}: lde_height={lde_height} output={output_bytes} workspace={kernel_workspace} staging={} target={} free={free_bytes}", - current_staging(), - target - ); - } - if free_bytes < target { - return None; - } - let lde = - { - let quotient_size = input.quotient_domain.size(); - let quotient_degree = input.circuit.quotient_degree(); - let selectors = cuda_coset_selectors(input.trace_domain, input.quotient_domain); - - let mut powers = Vec::with_capacity(input.constraint_count); - let mut power = ExtVal::ONE; - for _ in 0..input.constraint_count { - powers.push(power); - power *= alpha; - } - powers.reverse(); - let mut alpha_flat = Vec::with_capacity(2 * input.constraint_count); - for coordinate in 0..2 { - alpha_flat.extend(powers.iter().map(|value| { - >::as_basis_coefficients_slice(value) - [coordinate] - })); - } - let trace_size = input.trace_domain.size(); - let n = Val::from_usize(trace_size); - let generator = Val::two_adic_generator(trace_size.ilog2() as usize); - let normalization = (n * generator).inverse(); - let delta = [ - (input.lookup_publics[6] - input.lookup_publics[4]) * normalization, - (input.lookup_publics[7] - input.lookup_publics[5]) * normalization, - ]; - let next_step = quotient_size / trace_size; - let evaluate = |main: crate::cuda::mmcs::CudaMatrixSource<'_>, - stage2: crate::cuda::mmcs::CudaMatrixSource<'_>, - preprocessed: Option< - crate::cuda::mmcs::CudaMatrixSource<'_>, - >| { - crate::cuda::quotient_lde_mixed( - &self.pcs.dft, - &input.circuit.graph, - preprocessed, - main, - stage2, - &input.lookup_publics, - selectors, - &alpha_flat, - &delta, - crate::system::extension_params::().w, - quotient_size, - next_step, - input.circuit.lookup_group_size, - quotient_degree, - self.log_blowup, - ) - }; - self.pcs - .mmcs - .with_matrix_source(input.stage_1.0, input.stage_1.1, |main| { - self.pcs.mmcs.with_matrix_source( - input.stage_2.0, - input.stage_2.1, - |stage2| match input.preprocessed { - Some((data, index)) => self.pcs.mmcs.with_matrix_source( - data, - index, - |preprocessed| evaluate(main, stage2, Some(preprocessed)), - ), - None => evaluate(main, stage2, None), - }, - ) - }) - }; - ldes[index] = Some(lde); - if crate::cuda::memory_diagnostics_enabled() { - eprintln!( - "[multi-stark/cuda] quotient job {index} complete: {:.3}s", - job_started.elapsed().as_secs_f64() - ); - } - } - let tree_headroom = max_lde_height - .saturating_mul(96) - .saturating_add(total_device_bytes / 64); - if let Some(input) = inputs.first() { - self.pcs.mmcs.ensure_device_headroom( - input.stage_1.0, - tree_headroom, - None, - "quotient_tree", - ); - self.pcs.mmcs.ensure_device_headroom( - input.stage_2.0, - tree_headroom, - None, - "quotient_tree", - ); - } - if let Some((data, _)) = inputs.iter().find_map(|input| input.preprocessed) { - self.pcs - .mmcs - .ensure_device_headroom(data, tree_headroom, None, "quotient_tree"); - } - if crate::cuda::device_memory_info(self.pcs.mmcs.cuda_device_id()).0 < tree_headroom { - return None; - } - Some( - self.pcs.mmcs.commit_cuda_spillable( - ldes.into_iter() - .map(|lde| lde.expect("quotient job did not run")) - .collect(), - ), + .collect(); + cuda_accelerated_quotient_commit( + &self.pcs.dft, + &self.pcs.mmcs, + self.log_blowup, + &jobs, + alpha, ) } @@ -1094,320 +1438,30 @@ impl ProofConfig for GoldilocksBlake3Config { inputs: &[crate::config::LookupCommitInput<'_, Self>], lookup_challenge: ExtVal, fingerprint_challenge: ExtVal, - mut accumulator: ExtVal, + accumulator: ExtVal, ) -> Option<( crate::config::Com, crate::config::PcsData, Vec, )> { - use crate::cuda::mmcs::CudaCommitMmcs; - - let mut lookup_jobs = inputs + let jobs: Vec> = inputs .iter() - .enumerate() - .map(|(index, input)| { - let (height, num_lookups, _, _, arg_offsets) = input.lookup_values.cuda_parts(); - let group_size = input.circuit.lookup_group_size.max(1); - let groups = num_lookups.div_ceil(group_size).max(1); - let extended_height = height - .checked_shl(u32::try_from(self.log_blowup).expect("LDE blowup exceeds u32")) - .unwrap_or(usize::MAX); - let output_bytes = extended_height - .saturating_mul(2) - .saturating_mul(groups) - .saturating_mul(size_of::()); - let direct_temporary_bytes = if num_lookups == 0 { - 0 - } else { - let args_width = *arg_offsets.last().expect("lookup offsets are empty"); - let chunk_rows = height.min(1 << 16); - let messages = chunk_rows.saturating_mul(num_lookups); - messages - // Multiplicity, conjugate, norm, and inverse-norm arrays. - .saturating_mul(5 * size_of::()) - .saturating_add( - chunk_rows - .saturating_mul(args_width) - .saturating_mul(size_of::()), - ) - // Extension-field deltas before the exclusive scan. - .saturating_add( - height - .saturating_mul(groups) - .saturating_mul(2 * size_of::()), - ) - .saturating_add(arg_offsets.len().saturating_mul(size_of::())) - }; - let main_width = self - .pcs - .mmcs - .matrix_dimensions(input.stage_1.0) - .get(input.stage_1.1) - .expect("stage-1 matrix index out of bounds") - .width; - let graph_memory = (num_lookups != 0) - .then(|| { - crate::cuda::lookup_graph_lde_memory_upper_bound( - &input.circuit.graph, - height, - main_width, - group_size, - self.log_blowup, - ) - }) - .flatten(); - let transform_bytes = if num_lookups == 0 { - 0 - } else { - let plan = - self.pcs - .dft - .lde_plan(height, 2 * groups, self.log_blowup, Val::GENERATOR); - plan.scratch_bytes().saturating_add(plan.constant_bytes()) - }; - ( - index, - output_bytes, - direct_temporary_bytes.saturating_add(transform_bytes), - graph_memory.map(|(_, temporary)| temporary.saturating_add(transform_bytes)), - extended_height, - ) + .map(|input| CudaLookupJob { + circuit: input.circuit, + lookup_values: input.lookup_values, + preprocessed: input.preprocessed, + stage_1: input.stage_1, }) - .collect::>(); - // Permanent lookup LDEs accumulate until their MMCS commitment. Run - // the initially largest allocation first, while its trace is still - // resident, then allow that trace to become an eviction candidate for - // later jobs. - lookup_jobs.sort_unstable_by_key(|&(index, output, direct, graph, _)| { - let temporary = if inputs[index] - .stage_1 - .0 - .has_resident_with_trace(inputs[index].stage_1.1) - { - graph.unwrap_or(direct) - } else { - direct - }; - core::cmp::Reverse(output.saturating_add(temporary)) - }); - let accumulated_output = lookup_jobs - .iter() - .map(|&(_, output, _, _, _)| output) - .sum::(); - let max_lde_height = lookup_jobs - .iter() - .map(|&(_, _, _, _, extended_height)| extended_height) - .max() - .unwrap_or(0); - let (_, total_device_bytes) = - crate::cuda::device_memory_info(self.pcs.mmcs.cuda_device_id()); - if crate::cuda::memory_diagnostics_enabled() { - eprintln!( - "[multi-stark/cuda] lookup jobs={} output={}", - lookup_jobs.len(), - accumulated_output, - ); - } - - let pair = |value: ExtVal| { - let coordinates = value.as_basis_coefficients_slice(); - [coordinates[0], coordinates[1]] - }; - let beta = pair(lookup_challenge); - let gamma = pair(fingerprint_challenge); - let extension_generator = ExtVal::from_basis_coefficients_slice(&[Val::ZERO, Val::ONE])?; - let ext_w = pair(extension_generator * extension_generator)[0]; - let lookup_pool = - std::sync::Arc::new(cuda_host_pool("lookup-rows", cuda_lookup_worker_count())); - // `graph_path` is decided by admission below, which budgets the graph - // kernel from the same residency predicate; the kernel must not be - // re-chosen here or it can run under the other path's budget. - let evaluate = |input: &crate::config::LookupCommitInput<'_, Self>, - graph_path: bool, - cooperative: bool| { - let (height, num_lookups, multiplicities, args, arg_offsets) = - input.lookup_values.cuda_parts(); - let group_size = input.circuit.lookup_group_size.max(1); - let main = graph_path.then(|| { - input - .stage_1 - .0 - .resident_with_trace(input.stage_1.1) - .expect("lookup graph admission requires a trace-backed resident LDE") - }); - let result = if let Some(main) = main { - let preprocessed = input.preprocessed.map(|(data, index)| { - data.resident(index) - .expect("lookup graph admission requires a resident preprocessed LDE") - }); - crate::cuda::lookup_graph_lde_resident( - &self.pcs.dft, - &input.circuit.graph, - preprocessed, - main, - height, - group_size, - beta, - gamma, - ext_w, - self.log_blowup, - ) - } else if cooperative { - let pool = std::sync::Arc::clone(&lookup_pool); - Some(crate::cuda::lookup_lde_resident_partitioned( - &self.pcs.dft, - multiplicities, - args, - arg_offsets, - height, - num_lookups, - group_size, - beta, - gamma, - ext_w, - self.log_blowup, - move |rows| { - pool.install(|| { - input.lookup_values.cuda_stage_2_deltas::( - rows, - group_size, - lookup_challenge, - &fingerprint_challenge, - ) - }) - }, - )) - } else { - Some(crate::cuda::lookup_lde_resident( - &self.pcs.dft, - multiplicities, - args, - arg_offsets, - height, - num_lookups, - group_size, - beta, - gamma, - ext_w, - self.log_blowup, - )) - }; - // SAFETY: evaluation is synchronous and complete, while the - // retained matrix remains owned by the prover data. - if let Some(main) = main { - unsafe { main.release_trace() }; - main.release_generator_device(); - } - result - }; - let mut results = (0..inputs.len()).map(|_| None).collect::>(); - for (index, output_bytes, direct_temporary_bytes, graph_temporary_bytes, _) in lookup_jobs { - let job_started = std::time::Instant::now(); - let input = &inputs[index]; - // The graph kernel reads the trace through `resident_with_trace`, - // which also serves spilled LDEs that regenerate from a generator - // or a retained host trace. Admit it under the same predicate so - // the budget matches the kernel that runs. - let admits_graph = || { - graph_temporary_bytes.is_some() - && input.stage_1.0.has_resident_with_trace(input.stage_1.1) - && input - .preprocessed - .is_none_or(|(data, matrix)| data.resident(matrix).is_some()) - }; - let target_for = |graph_path: bool| { - let temporary_bytes = if graph_path { - graph_temporary_bytes.unwrap() - } else { - direct_temporary_bytes - }; - ( - temporary_bytes, - output_bytes - .saturating_add(temporary_bytes) - .saturating_add(total_device_bytes / 64), - ) - }; - let mut graph_path = admits_graph(); - let (mut temporary_bytes, mut target) = target_for(graph_path); - if target > total_device_bytes { - return None; - } - let mut free_bytes = self.pcs.mmcs.ensure_device_headroom( - input.stage_1.0, - target, - Some(input.stage_1.1), - "lookup", - ); - if free_bytes < target { - // This circuit alone does not fit beside its resident trace. - // Spill it as a last resort. If the spilled LDE can still - // regenerate its trace it stays on the graph path; otherwise - // re-budget for the direct lookup-values path, which remains - // protocol-identical. - free_bytes = - self.pcs - .mmcs - .ensure_device_headroom(input.stage_1.0, target, None, "lookup"); - graph_path = admits_graph(); - (temporary_bytes, target) = target_for(graph_path); - if free_bytes < target { - free_bytes = self.pcs.mmcs.ensure_device_headroom( - input.stage_1.0, - target, - None, - "lookup", - ); - } - } - if free_bytes < target { - return None; - } - if !graph_path && !input.lookup_values.is_materialized() { - return None; - } - if crate::cuda::memory_diagnostics_enabled() { - eprintln!( - "[multi-stark/cuda] lookup job {index}: graph={graph_path} output={output_bytes} temporary={temporary_bytes} target={target} free={free_bytes}" - ); - } - let (_, num_lookups, _, _, arg_offsets) = input.lookup_values.cuda_parts(); - let cooperative = !graph_path - && output_bytes >= (8usize << 30) - && num_lookups >= 64 - && arg_offsets.last().copied().unwrap_or(0) >= 256; - results[index] = Some(evaluate(&inputs[index], graph_path, cooperative)?); - if crate::cuda::memory_diagnostics_enabled() { - eprintln!( - "[multi-stark/cuda] lookup job {index} complete: {:.3}s", - job_started.elapsed().as_secs_f64() - ); - } - } - let tree_headroom = max_lde_height - .saturating_mul(96) - .saturating_add(total_device_bytes / 64); - if let Some(input) = inputs.first() { - let free_bytes = self.pcs.mmcs.ensure_device_headroom( - input.stage_1.0, - tree_headroom, - None, - "lookup_tree", - ); - if free_bytes < tree_headroom { - return None; - } - } - let mut ldes = Vec::with_capacity(results.len()); - let mut intermediates = Vec::with_capacity(inputs.len()); - for result in results { - let (lde, total) = result.expect("lookup job did not run"); - accumulator += ExtVal::from_basis_coefficients_slice(&total)?; - intermediates.push(accumulator); - ldes.push(lde); - } - let (commitment, data) = self.pcs.mmcs.commit_cuda_spillable(ldes); - Some((commitment, data, intermediates)) + .collect(); + cuda_accelerated_lookup_commit( + &self.pcs.dft, + &self.pcs.mmcs, + self.log_blowup, + &jobs, + lookup_challenge, + fingerprint_challenge, + accumulator, + ) } } @@ -1441,7 +1495,7 @@ pub struct FriParameters { pub query_proof_of_work_bits: usize, } -#[cfg(any(feature = "cuda", test))] +#[cfg(test)] pub(crate) type Blake3CompressionFunction = CompressionFunctionFromHasher; #[cfg(feature = "cuda")] @@ -1496,11 +1550,7 @@ fn new_mmcs(cap_height: usize, #[cfg(feature = "cuda")] device_id: i32) -> Mmcs } #[cfg(feature = "cuda")] { - let byte_hash = Blake3; - let field_hash = SerializingHasher::new(byte_hash); - let compress = Blake3CompressionFunction::new(byte_hash); - let cpu = CpuMmcs::new(field_hash, compress, cap_height); - crate::cuda::mmcs::CudaMmcs::with_device(cpu, device_id) + crate::cuda::mmcs::CudaMmcs::new_plain(cap_height, device_id) } } @@ -1739,7 +1789,8 @@ where #[cfg(feature = "cuda")] let pcs = { let dev = device_id.unwrap_or_else(crate::cuda::configured_device); - let val_mmcs = new_mmcs(commitment_parameters.cap_height, dev); + let val_mmcs = + crate::cuda::mmcs::CudaMmcs::new_v6(commitment_parameters.cap_height, dev); let ext_mmcs = ExtensionMmcs::new(val_mmcs.clone()); let inner_parameters = InnerFriParameters { log_blowup: commitment_parameters.log_blowup, @@ -1751,11 +1802,10 @@ where mmcs: ext_mmcs, }; let pcs_dft = CudaDft::new(dev); - DomainMappedPcs::new(crate::cuda::pcs::CudaTwoAdicFriPcs::new( - pcs_dft, - val_mmcs, - inner_parameters, - )) + DomainMappedPcs::new( + crate::cuda::pcs::CudaTwoAdicFriPcs::new(pcs_dft, val_mmcs, inner_parameters) + .with_batching(fri_batching), + ) }; let challenger_seed = @@ -1796,10 +1846,15 @@ where /// both the PCS and the protocol challenger seed. pub fn with_fri_batching(self, fri_batching: FriBatching) -> Self { let spill = self.spill_dir().map(std::path::Path::to_path_buf); - let cfg = Self::new_with_batching( + #[cfg(feature = "cuda")] + let device = Some(self.pcs.inner().dft.device_id()); + #[cfg(not(feature = "cuda"))] + let device = None; + let cfg = Self::with_device( self.commitment_parameters, self.fri_parameters, fri_batching, + device, ); match spill { Some(dir) => cfg.with_disk_spill(dir), @@ -2163,6 +2218,99 @@ where ) } + #[cfg(feature = "cuda")] + fn commit_main( + &self, + evaluations: Vec<( + crate::config::Domain, + crate::witness::TraceSource, + )>, + ) -> (crate::config::Com, crate::config::PcsData) { + let inner_evals = evaluations + .into_iter() + .map(|(domain, source)| (domain.into_inner(), source)) + .collect(); + crate::cuda::witness::commit::>(self.pcs.inner(), inner_evals) + } + + #[cfg(feature = "cuda")] + fn accelerated_quotient_values( + &self, + circuit: &crate::system::Circuit, + lookup_publics: &[Val], + trace_domain: crate::config::Domain, + quotient_domain: crate::config::Domain, + preprocessed: Option<(&crate::config::PcsData, usize)>, + stage_1: (&crate::config::PcsData, usize), + stage_2: (&crate::config::PcsData, usize), + alpha: EF, + constraint_count: usize, + ) -> Option> { + cuda_accelerated_quotient_values( + circuit, + lookup_publics, + trace_domain.into_inner(), + quotient_domain.into_inner(), + preprocessed, + stage_1, + stage_2, + alpha, + constraint_count, + ) + } + + #[cfg(feature = "cuda")] + fn accelerated_quotient_commit( + &self, + inputs: &[crate::config::QuotientCommitInput<'_, Self>], + alpha: EF, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let jobs: Vec> = inputs + .iter() + .map(|input| CudaQuotientJob { + circuit: input.circuit, + lookup_publics: &input.lookup_publics, + trace_domain: input.trace_domain.into_inner(), + quotient_domain: input.quotient_domain.into_inner(), + preprocessed: input.preprocessed, + stage_1: input.stage_1, + stage_2: input.stage_2, + constraint_count: input.constraint_count, + }) + .collect(); + let inner = self.pcs.inner(); + cuda_accelerated_quotient_commit(&inner.dft, &inner.mmcs, self.log_blowup, &jobs, alpha) + } + + #[cfg(feature = "cuda")] + fn accelerated_lookup_commit( + &self, + inputs: &[crate::config::LookupCommitInput<'_, Self>], + lookup_challenge: EF, + fingerprint_challenge: EF, + accumulator: EF, + ) -> Option> { + let jobs: Vec> = inputs + .iter() + .map(|input| CudaLookupJob { + circuit: input.circuit, + lookup_values: input.lookup_values, + preprocessed: input.preprocessed, + stage_1: input.stage_1, + }) + .collect(); + let inner = self.pcs.inner(); + cuda_accelerated_lookup_commit( + &inner.dft, + &inner.mmcs, + self.log_blowup, + &jobs, + lookup_challenge, + fingerprint_challenge, + accumulator, + ) + } + fn canonicalize_proof(proof: &mut crate::prover::Proof) { canonicalize_goldilocks_fri_proof::>(proof); } From 6171f18dc62e4018c62178a943f3d7247632a0a5 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sat, 21 Nov 2026 23:12:55 -0500 Subject: [PATCH 20/28] Add comprehensive Goldilocks F_p^3 and Protocol v6 integration tests, negative checks, and CPU benchmarks --- src/verifier/challenge_tests.rs | 30 + tests/fp3_v6.rs | 1173 +++++++++++++++++++++++++++++++ 2 files changed, 1203 insertions(+) create mode 100644 tests/fp3_v6.rs diff --git a/src/verifier/challenge_tests.rs b/src/verifier/challenge_tests.rs index d62b78c..16bd7ec 100644 --- a/src/verifier/challenge_tests.rs +++ b/src/verifier/challenge_tests.rs @@ -254,3 +254,33 @@ fn zero_batch_claim_and_message_denominators_are_rejected() { batch.preamble.messages.clear(); system.verify_batch(&batch).unwrap(); } + +#[test] +fn inactive_preprocessed_domain_zeta_is_rejected() { + let make_case = |zeta: Val| { + let (mut system, mut proof) = scripted_proof(Val::from_u8(7), zeta); + let (mut other, _) = scripted_proof(Val::from_u8(7), Val::TWO); + let mut inactive = other.circuits.pop().unwrap(); + inactive.preprocessed_width = 1; + inactive.preprocessed_height = 8; + system.circuits.push(inactive); + system.preprocessed_indices.push(Some(0)); + system.preprocessed_commit = Some(()); + proof.active.push(false); + proof.preprocessed_opened_values = + Some(vec![vec![vec![>::ZERO]]]); + (system, proof) + }; + + // `g_8` is outside the active 4-row domain, but lies inside the inactive + // 8-row preprocessed domain -> must be rejected with `InvalidChallenge`. + let (system_bad, proof_bad) = make_case(Val::two_adic_generator(3)); + assert!(matches!( + system_bad.verify_multiple_claims(&[], &proof_bad), + Err(VerificationError::InvalidChallenge) + )); + + // `zeta = 2` is outside both domains -> accepted. + let (system_ok, proof_ok) = make_case(Val::TWO); + system_ok.verify_multiple_claims(&[], &proof_ok).unwrap(); +} diff --git a/tests/fp3_v6.rs b/tests/fp3_v6.rs new file mode 100644 index 0000000..c83ac5f --- /dev/null +++ b/tests/fp3_v6.rs @@ -0,0 +1,1173 @@ +//! End-to-end integration tests and CPU benchmarks for Protocol `v6` and +//! Goldilocks cubic trinomial extension $\mathbb{F}_{p^3} = \mathbb{F}_p[X]/(X^3 - X - 1)$. + +#[cfg(not(feature = "cuda"))] +use std::fs; +#[cfg(not(feature = "cuda"))] +use std::path::PathBuf; +#[cfg(not(feature = "cuda"))] +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Instant; + +use multi_stark::batch::{BatchMessage, BatchProof, Retention, ShardInput}; +use multi_stark::expr::{Expr, ExtExpr, RowOffset}; +use multi_stark::lookup::Lookup; +use multi_stark::p3_adapter::fri_batching::FriBatching; +use multi_stark::plonkish::CircuitBuilder; +use multi_stark::plonkish::gadgets::{ByteGadgets, blake3}; +use multi_stark::prover::Proof; +use multi_stark::system::{CircuitInputs, System, SystemWitness}; +use multi_stark::types::{ + CommitmentParameters, ExtVal3, FriParameters, GoldilocksBlake3Config, GoldilocksBlake3V6Config, + GoldilocksBlake3V6Fp2Config, Val, +}; +use multi_stark::witness::{PreparedWitness, TraceSource}; +use p3_field::{BasedVectorSpace, PrimeCharacteristicRing, PrimeField64}; +use p3_matrix::dense::RowMajorMatrix; + +#[cfg(not(feature = "cuda"))] +static DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +#[cfg(not(feature = "cuda"))] +fn fresh_spill_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let seq = DIR_SEQ.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!( + "multi-stark-fp3-v6-{tag}-{}-{nanos}-{seq}", + std::process::id() + )) +} + +fn f(v: u32) -> Val { + Val::from_u32(v) +} + +/// Builds a 4-circuit system exercising: +/// - Circuit 0: Preprocessed 256-row byte ROM (`prep[0] = 0..255`, `main[0] = mult`) +/// - Circuit 1: Preprocessed 16-row aux ROM (can be left inactive for sparse tests) +/// - Circuit 2: Multi-lookup arithmetic + transition + degree-3 `ExtExpr` circuit +/// - Circuit 3: Zero-lookup quadratic circuit (`main[0]^2 == main[1]`) +fn multi_circuit_inputs( + lookup_group_size: usize, + work_rows: usize, + with_ext_constraint: bool, +) -> Vec> { + assert!(work_rows.is_power_of_two() && work_rows >= 4); + + let byte_prep = RowMajorMatrix::new((0..256u32).map(f).collect(), 1); + let byte_table = CircuitInputs { + main_width: 1, + preprocessed: Some(byte_prep), + constraints: vec![], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(10)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + let aux_prep = RowMajorMatrix::new((100..116u32).map(f).collect(), 1); + let aux_table = CircuitInputs { + main_width: 1, + preprocessed: Some(aux_prep), + constraints: vec![Expr::main(0) * (Expr::preprocessed(0) - Expr::preprocessed(0))], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(20)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + let work_prep = RowMajorMatrix::new( + (0..u32::try_from(work_rows).unwrap()) + .map(|r| f(r + 1)) + .collect(), + 1, + ); + let a = Expr::main(0); + let b = Expr::main(1); + let c = Expr::main(2); + let d = Expr::main(3); + let sum = Expr::main(4); + let mult = Expr::main(5); + let tag = Expr::preprocessed(0); + let tag_next = Expr::preprocessed_next(0); + let a_next = Expr::main_next(0); + + // Optional degree-3 ExtExpr exercising CubicTrinomial mul/add/sub in ConstraintGraph: + // On every row, `(s2_0 - s2_0) * (s2_0 + const_ext) == 0` AND a real algebraic identity: + // `a * (b + X*c + X^2*d) - (a*b + X*(a*c) + X^2*(a*d)) == 0`. + let ext_constraints = if with_ext_constraint { + let lhs = ExtExpr::from(a.clone()) * ExtExpr::Coords(vec![b.clone(), c.clone(), d.clone()]); + let rhs = ExtExpr::Coords(vec![ + a.clone() * b.clone(), + a.clone() * c.clone(), + a.clone() * d.clone(), + ]); + let s2 = ExtExpr::stage2(0, 3, RowOffset::Current); + let s2_id = s2.clone() * ExtExpr::from(a.clone()) - ExtExpr::from(a.clone()) * s2; + vec![lhs - rhs, s2_id] + } else { + vec![] + }; + + let work_constraints = vec![ + sum.clone() - (a.clone() + b.clone() + c.clone() + d.clone() + tag.clone()), + Expr::IsTransition * (a_next.clone() - (a.clone() + Expr::constant(Val::ONE))), + ]; + let work_lookups = vec![ + Lookup::pull( + mult, + vec![Expr::constant(f(30)), tag, tag_next, sum, a_next], + ), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), a]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), b]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), c]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), d]), + ]; + let work_circuit = CircuitInputs { + main_width: 6, + preprocessed: Some(work_prep), + constraints: work_constraints, + ext_constraints, + lookups: work_lookups, + lookup_group_size, + }; + + let sq = CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![Expr::main(0) * Expr::main(0) - Expr::main(1)], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + + vec![byte_table, aux_table, work_circuit, sq] +} + +fn build_multi_circuit_witness( + work_rows: usize, + aux_active: bool, + seed: u32, +) -> (Vec>, Vec>) { + let mut byte_mults = vec![0u32; 256]; + let mut work_values = Vec::with_capacity(work_rows * 6); + let mut claims = Vec::new(); + let base_a = seed % 120; + + for r in 0..work_rows { + let r32 = u32::try_from(r).unwrap(); + let a = (base_a + r32) & 0xFF; + let b = (r32 * 7 + seed * 3 + 5) & 0xFF; + let c = (r32 * 13 + seed * 11 + 17) & 0xFF; + let d = (r32 * 29 + seed * 19 + 41) & 0xFF; + let tag = r32 + 1; + let tag_next = u32::try_from((r + 1) % work_rows).unwrap() + 1; + let a_next = if r + 1 < work_rows { + (base_a + r32 + 1) & 0xFF + } else { + base_a & 0xFF + }; + let sum = a + b + c + d + tag; + let mult = u32::from(r % 2 == 0); + if mult == 1 { + claims.push(vec![f(30), f(tag), f(tag_next), f(sum), f(a_next)]); + } + byte_mults[usize::try_from(a).unwrap()] += 1; + byte_mults[usize::try_from(b).unwrap()] += 1; + byte_mults[usize::try_from(c).unwrap()] += 1; + byte_mults[usize::try_from(d).unwrap()] += 1; + work_values.extend([f(a), f(b), f(c), f(d), f(sum), f(mult)]); + } + + let byte_trace = RowMajorMatrix::new(byte_mults.into_iter().map(f).collect(), 1); + let aux_trace = if aux_active { + let mut aux_mults = vec![Val::ZERO; 16]; + aux_mults[3] = Val::ONE; + claims.push(vec![f(20), f(103)]); + RowMajorMatrix::new(aux_mults, 1) + } else { + RowMajorMatrix::new(Vec::new(), 1) + }; + let work_trace = RowMajorMatrix::new(work_values, 6); + let sq_trace = RowMajorMatrix::new( + (0..8u32) + .flat_map(|i| [f(i + 2 + seed), f((i + 2 + seed) * (i + 2 + seed))]) + .collect(), + 2, + ); + + (vec![byte_trace, aux_trace, work_trace, sq_trace], claims) +} + +/// Builds a U32Add + ByteTable circuit pair (`num_add_rows` power of two). +fn u32_add_system_inputs(lookup_group_size: usize) -> Vec> { + let byte_prep = RowMajorMatrix::new((0..256u32).map(f).collect(), 1); + let byte_table = CircuitInputs { + main_width: 1, + preprocessed: Some(byte_prep), + constraints: vec![], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(0)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + let carry = Expr::main(12); + let x = Expr::main(0) + + Expr::main(1) * Expr::constant(f(256)) + + Expr::main(2) * Expr::constant(f(256 * 256)) + + Expr::main(3) * Expr::constant(f(256 * 256 * 256)); + let y = Expr::main(4) + + Expr::main(5) * Expr::constant(f(256)) + + Expr::main(6) * Expr::constant(f(256 * 256)) + + Expr::main(7) * Expr::constant(f(256 * 256 * 256)); + let z = Expr::main(8) + + Expr::main(9) * Expr::constant(f(256)) + + Expr::main(10) * Expr::constant(f(256 * 256)) + + Expr::main(11) * Expr::constant(f(256 * 256 * 256)); + let two_32 = Expr::constant(Val::from_u64(1u64 << 32)); + let constraints = vec![ + carry.clone() * (carry.clone() - Expr::constant(Val::ONE)), + x.clone() + y.clone() - (z.clone() + carry * two_32), + ]; + let mut lookups = vec![Lookup::pull( + Expr::main(13), + vec![Expr::constant(f(1)), x, y, z], + )]; + lookups.extend((0..12).map(|i| { + Lookup::push( + Expr::constant(Val::ONE), + vec![Expr::constant(f(0)), Expr::main(i)], + ) + })); + let u32_add = CircuitInputs { + main_width: 14, + preprocessed: None, + constraints, + ext_constraints: vec![], + lookups, + lookup_group_size, + }; + + vec![byte_table, u32_add] +} + +fn u32_add_witness(num_rows: usize) -> (Vec>, Vec>) { + assert!(num_rows.is_power_of_two()); + let mut byte_mults = vec![0u32; 256]; + let mut add_values = Vec::with_capacity(num_rows * 14); + let mut claims = Vec::with_capacity(16); + + for r in 0..num_rows { + let r32 = u32::try_from(r).unwrap(); + let x = r32.wrapping_mul(2_654_435_761).wrapping_add(17); + let y = r32.wrapping_mul(1_597_334_677).wrapping_add(1_000_003); + let (z, overflow) = x.overflowing_add(y); + let xb = x.to_le_bytes(); + let yb = y.to_le_bytes(); + let zb = z.to_le_bytes(); + for &b in xb.iter().chain(&yb).chain(&zb) { + byte_mults[usize::from(b)] += 1; + } + let mult = u32::from(r < 16); + if mult == 1 { + claims.push(vec![f(1), f(x), f(y), f(z)]); + } + for &b in xb.iter().chain(&yb).chain(&zb) { + add_values.push(Val::from_u8(b)); + } + add_values.push(Val::from_u8(u8::from(overflow))); + add_values.push(f(mult)); + } + let byte_trace = RowMajorMatrix::new(byte_mults.into_iter().map(f).collect(), 1); + let add_trace = RowMajorMatrix::new(add_values, 14); + (vec![byte_trace, add_trace], claims) +} + +#[test] +fn fp3_v6_single_proof_matrix() { + let cases = [ + // (batching, group_size, log_blowup, cap_height, max_log_arity, pow_bits, aux_active) + (FriBatching::Tensor, 1, 2, 0, 1, 0, true), + (FriBatching::Tensor, 2, 2, 1, 2, 4, false), + (FriBatching::Tensor, 3, 2, 2, 2, 0, true), + (FriBatching::Tensor, 4, 3, 1, 2, 4, false), + (FriBatching::Horner, 2, 2, 0, 1, 4, false), + (FriBatching::Horner, 4, 2, 2, 2, 0, true), + ]; + + for (batching, group_size, log_blowup, cap_height, max_log_arity, pow_bits, aux_active) in cases + { + let comm = CommitmentParameters { + log_blowup, + cap_height: if cfg!(feature = "cuda") { + 0 + } else { + cap_height + }, + }; + let fri = FriParameters { + log_final_poly_len: 1, + max_log_arity: if cfg!(feature = "cuda") { + 1 + } else { + max_log_arity + }, + num_queries: 12, + commit_proof_of_work_bits: pow_bits, + query_proof_of_work_bits: pow_bits, + }; + let config = GoldilocksBlake3V6Config::new_with_batching(comm, fri, batching); + let inputs = multi_circuit_inputs(group_size, 32, true); + let (system, key) = System::new(config, inputs); + let (traces, claims) = build_multi_circuit_witness(32, aux_active, 7); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let witness = SystemWitness::from_stage_1(traces.clone(), &system); + let proof = system.prove_multiple_claims(&key, &claim_refs, witness); + system + .verify_multiple_claims(&claim_refs, &proof) + .unwrap_or_else(|e| { + panic!( + "failed for batching={batching:?}, k={group_size}, cap={cap_height}, arity={max_log_arity}, pow={pow_bits}, aux={aux_active}: {e:?}" + ) + }); + + // Serialization roundtrip + deterministic repeatability (including positive PoW). + let bytes = proof.to_bytes().unwrap(); + let decoded = Proof::::from_bytes(&bytes).unwrap(); + system + .verify_multiple_claims(&claim_refs, &decoded) + .unwrap(); + + let witness2 = SystemWitness::from_stage_1(traces, &system); + let proof2 = system.prove_multiple_claims(&key, &claim_refs, witness2); + assert_eq!( + proof2.to_bytes().unwrap(), + bytes, + "v6 F_p^3 proof must be deterministic (batching={batching:?}, pow={pow_bits})" + ); + } +} + +#[test] +fn fp3_v6_plonkish_proof_with_blake3_gadget() { + let mut builder = CircuitBuilder::::new(); + let bytes = ByteGadgets::new(&mut builder); + let x = builder.public_input("x"); + let inv_x = builder.inverse(x); + let prod = builder.mul(x, inv_x); + builder.expose_public(prod); + + let msg_wires: Vec<_> = (0..16) + .map(|i| bytes.input(&mut builder, &format!("m[{i}]"))) + .collect(); + let digest = blake3(&mut builder, &bytes, &msg_wires); + builder.expose_public(digest[0].value()); + + let lowered = builder + .finish() + .lower_to_multi_stark(Val::from_u32(7)) + .unwrap(); + + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: if cfg!(feature = "cuda") { 0 } else { 1 }, + }; + let fri = FriParameters { + log_final_poly_len: 1, + max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + num_queries: 12, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let config = GoldilocksBlake3V6Config::new(comm, fri); + let (system, key) = System::new(config, lowered.circuit_inputs()); + + let mut w = lowered.witness(); + w.set(x, Val::from_u32(42)).unwrap(); + let msg: Vec = (0..16u8) + .map(|i| i.wrapping_mul(19).wrapping_add(3)) + .collect(); + for (&wire, &byte) in msg_wires.iter().zip(&msg) { + w.set(wire.value(), Val::from_u8(byte)).unwrap(); + } + let assignment = w.generate().unwrap(); + let expected_first_byte = blake3::hash(&msg).as_bytes()[0]; + let public_vals = [ + Val::from_u32(42), + Val::ONE, + Val::from_u8(expected_first_byte), + ]; + let claims = lowered.claims(&public_vals).unwrap(); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let traces = lowered.traces(&assignment).unwrap(); + + let witness = SystemWitness::from_stage_1(traces.clone(), &system); + let proof = system.prove_multiple_claims(&key, &claim_refs, witness); + system.verify_multiple_claims(&claim_refs, &proof).unwrap(); + + // Lazy lookup + new_without_preprocessed must match byte-for-byte. + let lazy_witness = SystemWitness::from_stage_1_lazy(traces, &system); + let lazy_proof = system.prove_multiple_claims(&key, &claim_refs, lazy_witness); + assert_eq!(lazy_proof.to_bytes().unwrap(), proof.to_bytes().unwrap()); +} + +#[test] +fn fp3_v6_batch_proof_retain_regenerate_and_messages() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: if cfg!(feature = "cuda") { 0 } else { 1 }, + }; + let fri = FriParameters { + log_final_poly_len: 1, + max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + num_queries: 10, + commit_proof_of_work_bits: 2, + query_proof_of_work_bits: 2, + }; + + for batching in [FriBatching::Tensor, FriBatching::Horner] { + let config = GoldilocksBlake3V6Config::new_with_batching(comm, fri, batching); + // 3 circuits: + // 0: Preprocessed Byte ROM (active only in shard 0) + // 1: Arithmetic producer that pushes to byte ROM and sends a cross-shard message + // 2: Consumer that receives the cross-shard message and exposes a public claim + let byte_prep = RowMajorMatrix::new((0..256u32).map(f).collect(), 1); + let inputs = vec![ + CircuitInputs { + main_width: 1, + preprocessed: Some(byte_prep), + constraints: vec![], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(1)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }, + CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![Expr::main(0) + Expr::constant(f(5)) - Expr::main(1)], + ext_constraints: vec![], + lookups: vec![ + Lookup::push( + Expr::constant(Val::ONE), + vec![Expr::constant(f(1)), Expr::main(0)], + ), + Lookup::push( + Expr::constant(Val::ONE), + vec![Expr::constant(f(2)), Expr::main(1)], + ), + ], + lookup_group_size: 2, + }, + CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![Expr::main(0) - Expr::main(1)], + ext_constraints: vec![], + lookups: vec![ + Lookup::pull( + Expr::constant(Val::ONE), + vec![Expr::constant(f(2)), Expr::main(0)], + ), + Lookup::pull( + Expr::constant(Val::ONE), + vec![Expr::constant(f(3)), Expr::main(1)], + ), + ], + lookup_group_size: 2, + }, + ]; + + let (system, key) = System::new(config, inputs); + + // Shard 0: byte ROM + producer rows (a = 10..14 -> b = 15..19). + // Shard 1: consumer rows pulling channel 2 and exposing channel 3 claims. + // Plus batch messages pushing an extra byte lookup (pulled by shard 0's byte table) + // and a balanced push/pull pair on channel 99. + let mut byte_mults = vec![Val::ZERO; 256]; + let mut prod_vals = Vec::new(); + let mut consumer_vals = Vec::new(); + let mut shard1_claims = Vec::new(); + for a in 10..14u32 { + byte_mults[usize::try_from(a).unwrap()] = Val::ONE; + let b = a + 5; + prod_vals.extend([f(a), f(b)]); + consumer_vals.extend([f(b), f(b)]); + shard1_claims.push(vec![f(3), f(b)]); + } + byte_mults[77] = Val::ONE; + let batch_messages = vec![ + BatchMessage::push(vec![f(1), f(77)]), + BatchMessage::push(vec![f(99), f(1234)]), + BatchMessage::pull(vec![f(99), f(1234)]), + ]; + + let shard0_traces = vec![ + RowMajorMatrix::new(byte_mults, 1), + RowMajorMatrix::new(prod_vals, 2), + RowMajorMatrix::new(Vec::new(), 2), + ]; + let shard1_traces = vec![ + RowMajorMatrix::new(Vec::new(), 1), + RowMajorMatrix::new(Vec::new(), 2), + RowMajorMatrix::new(consumer_vals, 2), + ]; + let shard_traces = [shard0_traces, shard1_traces]; + let shard_claims = [Vec::new(), shard1_claims]; + + let retained_batch = system.prove_batch( + &key, + (0..2) + .map(|s| ShardInput { + witness: SystemWitness::from_stage_1(shard_traces[s].clone(), &system), + claims: shard_claims[s].clone(), + }) + .collect(), + batch_messages.clone(), + ); + let regenerated_batch = system.prove_batch_with( + &key, + &shard_claims, + batch_messages, + Retention::Regenerate, + |s| { + let sources = shard_traces[s] + .iter() + .cloned() + .map(TraceSource::Host) + .collect(); + PreparedWitness::from_stage_1_lazy(sources, &system) + }, + ); + + // Retain and Regenerate must produce byte-identical batch proofs. + let batch_bytes = retained_batch.to_bytes().unwrap(); + assert_eq!( + regenerated_batch.to_bytes().unwrap(), + batch_bytes, + "Retain and Regenerate batch proofs must be byte-identical ({batching:?})" + ); + + let decoded = BatchProof::::from_bytes(&batch_bytes).unwrap(); + system.verify_batch(&decoded).unwrap(); + let zero_ef = ::ZERO; + for shard_idx in 0..2 { + let residual = system + .verify_batch_shard(&decoded.preamble, shard_idx, &decoded.proofs[shard_idx]) + .unwrap(); + assert_ne!( + residual, zero_ef, + "cross-shard lookup traffic must yield non-zero per-shard residual" + ); + } + } +} + +#[cfg(not(feature = "cuda"))] +#[test] +fn fp3_v6_streaming_and_disk_spill_byte_identical() { + use multi_stark::p3_adapter::spill::active_spill_files; + + let spill_dir = fresh_spill_dir("single-and-batch"); + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: if cfg!(feature = "cuda") { 0 } else { 1 }, + }; + let fri = FriParameters { + log_final_poly_len: 1, + max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + num_queries: 10, + commit_proof_of_work_bits: 2, + query_proof_of_work_bits: 2, + }; + let inputs = multi_circuit_inputs(3, 64, true); + + let (mem_sys, mem_key) = System::new( + GoldilocksBlake3V6Config::new(comm, fri).without_disk_spill(), + inputs.clone(), + ); + let (spill_sys, spill_key) = System::new( + GoldilocksBlake3V6Config::new(comm, fri).with_disk_spill(&spill_dir), + inputs.clone(), + ); + let (noprep_sys, noprep_key) = System::new_without_preprocessed( + GoldilocksBlake3V6Config::new(comm, fri).with_disk_spill(&spill_dir), + inputs, + ); + assert_eq!(mem_sys.vk_digest, noprep_sys.vk_digest); + assert_eq!(mem_sys.vk_digest, spill_sys.vk_digest); + + let (traces, claims) = build_multi_circuit_witness(64, false, 11); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let mem_proof = mem_sys.prove_multiple_claims( + &mem_key, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &mem_sys), + ); + let mem_bytes = mem_proof.to_bytes().unwrap(); + + let spill_proof = spill_sys.prove_multiple_claims( + &spill_key, + &claim_refs, + SystemWitness::from_stage_1_lazy(traces.clone(), &spill_sys), + ); + assert_eq!(spill_proof.to_bytes().unwrap(), mem_bytes); + + let stage_1 = noprep_sys.prove_stage_1_streaming(traces.clone()); + let stream_proof = noprep_sys.prove_committed(&noprep_key, &claim_refs, stage_1); + assert_eq!(stream_proof.to_bytes().unwrap(), mem_bytes); + mem_sys + .verify_multiple_claims(&claim_refs, &stream_proof) + .unwrap(); + + // Multi-shard batch streaming + disk spill byte identity. + let (traces2, claims2) = build_multi_circuit_witness(64, true, 23); + let mem_batch = mem_sys.prove_batch( + &mem_key, + vec![ + ShardInput { + witness: SystemWitness::from_stage_1(traces.clone(), &mem_sys), + claims: claims.clone(), + }, + ShardInput { + witness: SystemWitness::from_stage_1(traces2.clone(), &mem_sys), + claims: claims2.clone(), + }, + ], + vec![], + ); + let shard_traces = [traces, traces2]; + let shard_claims = [claims, claims2]; + let spill_batch = noprep_sys.prove_batch_with( + &noprep_key, + &shard_claims, + vec![], + Retention::Regenerate, + |s| { + let sources = shard_traces[s] + .iter() + .cloned() + .map(TraceSource::Host) + .collect(); + PreparedWitness::from_stage_1_lazy(sources, &noprep_sys) + }, + ); + assert_eq!( + spill_batch.to_bytes().unwrap(), + mem_batch.to_bytes().unwrap(), + "spilled lazy F_p^3 batch proof must be byte-identical to in-memory" + ); + mem_sys.verify_batch(&spill_batch).unwrap(); + + drop(spill_key); + drop(noprep_key); + drop(spill_sys); + drop(noprep_sys); + assert_eq!(active_spill_files(), 0); + if spill_dir.exists() { + let leftover: Vec<_> = fs::read_dir(&spill_dir) + .unwrap() + .filter_map(Result::ok) + .collect(); + assert!(leftover.is_empty(), "leftover spill files: {leftover:?}"); + let _ = fs::remove_dir_all(&spill_dir); + } +} + +#[test] +fn v6_domain_separation_and_batching_cross_rejection() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 10, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + // Edge case: single width-1 circuit, no lookups -> minimal opening structure. + let single_col = vec![CircuitInputs { + main_width: 1, + preprocessed: None, + constraints: vec![Expr::main(0) * (Expr::main(0) - Expr::constant(Val::ONE))], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }]; + let trace = vec![RowMajorMatrix::new_col(vec![ + Val::ZERO, + Val::ONE, + Val::ONE, + Val::ZERO, + ])]; + + // 1. v6 F_p^3 Tensor vs Horner cross-rejection (and width=1 edge case). + let (sys_t, key_t) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri, FriBatching::Tensor), + single_col.clone(), + ); + let (sys_h, key_h) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri, FriBatching::Horner), + single_col.clone(), + ); + let proof_t = sys_t.prove_multiple_claims( + &key_t, + &[], + SystemWitness::from_stage_1(trace.clone(), &sys_t), + ); + let proof_h = sys_h.prove_multiple_claims( + &key_h, + &[], + SystemWitness::from_stage_1(trace.clone(), &sys_h), + ); + sys_t.verify_multiple_claims(&[], &proof_t).unwrap(); + sys_h.verify_multiple_claims(&[], &proof_h).unwrap(); + assert!( + sys_h.verify_multiple_claims(&[], &proof_t).is_err(), + "v6 Tensor proof must not verify under v6 Horner" + ); + assert!( + sys_t.verify_multiple_claims(&[], &proof_h).is_err(), + "v6 Horner proof must not verify under v6 Tensor" + ); + + // 2. v5 F_p^2 vs v6 F_p^2 (Horner and Tensor) cross-rejection via serialized wire bytes. + let (sys_v5, key_v5) = System::new(GoldilocksBlake3Config::new(comm, fri), single_col.clone()); + let (sys_v6_h, key_v6_h) = System::new( + GoldilocksBlake3V6Fp2Config::new_with_batching(comm, fri, FriBatching::Horner), + single_col.clone(), + ); + let (sys_v6_t, key_v6_t) = System::new( + GoldilocksBlake3V6Fp2Config::new_with_batching(comm, fri, FriBatching::Tensor), + single_col, + ); + let proof_v5 = sys_v5.prove_multiple_claims( + &key_v5, + &[], + SystemWitness::from_stage_1(trace.clone(), &sys_v5), + ); + let proof_v6_h = sys_v6_h.prove_multiple_claims( + &key_v6_h, + &[], + SystemWitness::from_stage_1(trace.clone(), &sys_v6_h), + ); + let proof_v6_t = sys_v6_t.prove_multiple_claims( + &key_v6_t, + &[], + SystemWitness::from_stage_1(trace.clone(), &sys_v6_t), + ); + sys_v5.verify_multiple_claims(&[], &proof_v5).unwrap(); + sys_v6_h.verify_multiple_claims(&[], &proof_v6_h).unwrap(); + sys_v6_t.verify_multiple_claims(&[], &proof_v6_t).unwrap(); + + // Wire bytes of v5 Proof deserialize into v6 F_p^2 Proof (same struct layout), + // but verification MUST fail due to v6 domain-separated BLAKE3 + transcript + VK digest. + let v5_as_v6 = + Proof::::from_bytes(&proof_v5.to_bytes().unwrap()).unwrap(); + assert!(sys_v6_h.verify_multiple_claims(&[], &v5_as_v6).is_err()); + assert!(sys_v6_t.verify_multiple_claims(&[], &v5_as_v6).is_err()); + + let v6_as_v5 = + Proof::::from_bytes(&proof_v6_h.to_bytes().unwrap()).unwrap(); + assert!(sys_v5.verify_multiple_claims(&[], &v6_as_v5).is_err()); + + // 3. Single-proof vs 1-shard batch-proof domain separation (`TranscriptSingle` != `TranscriptBatch`). + let batch1 = sys_t.prove_batch( + &key_t, + vec![ShardInput { + witness: SystemWitness::from_stage_1(trace, &sys_t), + claims: vec![], + }], + vec![], + ); + sys_t.verify_batch(&batch1).unwrap(); + assert!( + sys_t + .verify_multiple_claims(&[], &batch1.proofs[0]) + .is_err(), + "1-shard v6 batch proof must not verify as a single proof" + ); + let mut forged_batch = batch1; + forged_batch.proofs[0] = proof_t; + assert!( + sys_t.verify_batch(&forged_batch).is_err(), + "single v6 proof must not verify inside a 1-shard batch" + ); +} + +#[test] +fn v6_vk_digest_binds_full_constraint_graph_med5() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 10, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let prep = RowMajorMatrix::new((0..8u32).map(f).collect(), 1); + // Two circuits with IDENTICAL shape metadata (widths, preprocessed trace, + // constraint_count, max_constraint_degree, num_lookups, lookup_group_size), + // differing only in the constraint formula: + // Circuit A: main[0] * main[1] - main[2] == 0 + // Circuit B: main[0] * main[1] + main[2] == 0 + let inputs_a = vec![CircuitInputs { + main_width: 3, + preprocessed: Some(prep.clone()), + constraints: vec![Expr::main(0) * Expr::main(1) - Expr::main(2)], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }]; + let inputs_b = vec![CircuitInputs { + main_width: 3, + preprocessed: Some(prep), + constraints: vec![Expr::main(0) * Expr::main(1) + Expr::main(2)], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }]; + + let (sys_a, key_a) = System::new(GoldilocksBlake3V6Config::new(comm, fri), inputs_a.clone()); + let (sys_b, _key_b) = System::new(GoldilocksBlake3V6Config::new(comm, fri), inputs_b); + let (sys_a_noprep, _) = System::new_without_preprocessed( + GoldilocksBlake3V6Config::new(comm, fri), + inputs_a.clone(), + ); + let (sys_a_fp2, _) = System::new(GoldilocksBlake3V6Fp2Config::new(comm, fri), inputs_a); + + assert_ne!( + sys_a.vk_digest, sys_b.vk_digest, + "MED-5: circuits with identical shapes but distinct constraint graphs must have distinct vk_digest" + ); + assert_eq!( + sys_a.vk_digest, sys_a_noprep.vk_digest, + "new and new_without_preprocessed must compute identical vk_digest" + ); + assert_ne!( + sys_a.vk_digest, sys_a_fp2.vk_digest, + "F_p^3 and F_p^2 systems must have distinct vk_digest" + ); + + // Witness satisfying BOTH A and B (all zeros!) — yet cross-verification MUST fail + // because the transcript binds `vk_digest`! + let zero_trace = vec![RowMajorMatrix::new(vec![Val::ZERO; 8 * 3], 3)]; + let proof_a = + sys_a.prove_multiple_claims(&key_a, &[], SystemWitness::from_stage_1(zero_trace, &sys_a)); + sys_a.verify_multiple_claims(&[], &proof_a).unwrap(); + assert!( + sys_b.verify_multiple_claims(&[], &proof_a).is_err(), + "MED-5: even on a witness satisfying both circuits, proof for A must fail verification under B" + ); +} + +#[test] +fn v6_fp3_canonical_deserialization_and_tamper_rejection() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 1, + max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + num_queries: 10, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let config = GoldilocksBlake3V6Config::new(comm, fri); + let (system, key) = System::new(config, multi_circuit_inputs(2, 16, true)); + let (traces, claims) = build_multi_circuit_witness(16, true, 5); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let proof = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &system), + ); + system.verify_multiple_claims(&claim_refs, &proof).unwrap(); + let proof_bytes = proof.to_bytes().unwrap(); + + // 1. Trailing garbage bytes rejected for Proof. + let mut with_trailing = proof_bytes.clone(); + with_trailing.push(0x42); + assert!( + Proof::::from_bytes(&with_trailing).is_err(), + "Proof::from_bytes must reject trailing bytes" + ); + + // 2. Non-canonical Goldilocks field elements (>= P) rejected in Proof::from_bytes. + let p_bytes = Val::ORDER_U64.to_le_bytes(); + let max_bytes = u64::MAX.to_le_bytes(); + // Locate a known canonical u64 coordinate of `intermediate_accumulators[0]` in the wire bytes. + let target_u64 = >::as_basis_coefficients_slice( + &proof.intermediate_accumulators[0], + )[0] + .as_canonical_u64() + .to_le_bytes(); + let pos = proof_bytes + .windows(8) + .position(|w| w == target_u64) + .expect("serialized accumulator coordinate not found in proof bytes"); + for bad_word in [p_bytes, max_bytes] { + let mut non_canon = proof_bytes.clone(); + non_canon[pos..pos + 8].copy_from_slice(&bad_word); + assert!( + Proof::::from_bytes(&non_canon).is_err(), + "Proof::from_bytes must reject non-canonical Goldilocks word {bad_word:?}" + ); + } + + // 3. Semantic tamper checks: accumulator, opened values, FRI final_poly, Merkle sibling, claim. + let one_ef = ::ONE; + let mut bad = proof.clone(); + bad.intermediate_accumulators[0] += one_ef; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + + let mut bad = proof.clone(); + bad.stage_1_opened_values[0][0][0] += one_ef; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + + let mut bad = proof.clone(); + bad.stage_2_opened_values[0][0][0] += one_ef; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + + let mut bad = proof.clone(); + bad.quotient_opened_values[0][0][0] += one_ef; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + + let mut bad = proof.clone(); + bad.preprocessed_opened_values.as_mut().unwrap()[0][0][0] += one_ef; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + + let mut bad = proof.clone(); + bad.opening_proof.final_poly[0] += one_ef; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + + let mut bad = proof.clone(); + if let Some(first_sib) = bad.opening_proof.input_openings[0] + .opening_proof + .sibling_hashes + .first_mut() + { + first_sib[0] ^= 1; + assert!(system.verify_multiple_claims(&claim_refs, &bad).is_err()); + } + + let mut wrong_claims = claims.clone(); + wrong_claims[0][1] += Val::ONE; + let wrong_claim_refs: Vec<&[Val]> = wrong_claims.iter().map(Vec::as_slice).collect(); + assert!( + system + .verify_multiple_claims(&wrong_claim_refs, &proof) + .is_err() + ); + + // 4. BatchProof trailing bytes, non-canonical field element, and non-target shard header validation. + let batch = system.prove_batch( + &key, + vec![ + ShardInput { + witness: SystemWitness::from_stage_1(traces.clone(), &system), + claims: claims.clone(), + }, + ShardInput { + witness: SystemWitness::from_stage_1(traces, &system), + claims, + }, + ], + vec![], + ); + let batch_bytes = batch.to_bytes().unwrap(); + let mut batch_trailing = batch_bytes.clone(); + batch_trailing.push(0x99); + assert!( + BatchProof::::from_bytes(&batch_trailing).is_err(), + "BatchProof::from_bytes must reject trailing bytes" + ); + + let batch_target = >::as_basis_coefficients_slice( + &batch.proofs[0].intermediate_accumulators[0], + )[0] + .as_canonical_u64() + .to_le_bytes(); + let bpos = batch_bytes + .windows(8) + .position(|w| w == batch_target) + .expect("serialized accumulator coordinate not found in batch bytes"); + let mut batch_non_canon = batch_bytes; + batch_non_canon[bpos..bpos + 8].copy_from_slice(&p_bytes); + assert!( + BatchProof::::from_bytes(&batch_non_canon).is_err(), + "BatchProof::from_bytes must reject non-canonical Goldilocks word" + ); + + // Corrupting shard 1's preamble `log_degrees` length must be rejected even when + // verifying only shard 0 via `verify_batch_shard`. + let mut malformed_batch = batch; + malformed_batch.preamble.headers[1].log_degrees.pop(); + assert!( + system + .verify_batch_shard(&malformed_batch.preamble, 0, &malformed_batch.proofs[0]) + .is_err(), + "verify_batch_shard must reject malformed non-target shard headers" + ); +} + +fn min_and_median_ms(mut samples: Vec) -> (f64, f64) { + samples.sort_by(f64::total_cmp); + (samples[0], samples[samples.len() / 2]) +} + +#[test] +#[ignore = "CPU benchmark: run with `cargo test --release --features parallel --test fp3_v6 bench_fp2_vs_fp3_cpu -- --ignored --nocapture`"] +fn bench_fp2_vs_fp3_cpu() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 0, + max_log_arity: 2, + num_queries: 64, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + + for &rows in &[1usize << 12, 1usize << 14, 1usize << 16] { + let inputs = u32_add_system_inputs(4); + let (traces, claims) = u32_add_witness(rows); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let (sys_v5, key_v5) = System::new(GoldilocksBlake3Config::new(comm, fri), inputs.clone()); + let (sys_v6_fp2_t, key_v6_fp2_t) = System::new( + GoldilocksBlake3V6Fp2Config::new_with_batching(comm, fri, FriBatching::Tensor), + inputs.clone(), + ); + let (sys_v6_fp3_h, key_v6_fp3_h) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri, FriBatching::Horner), + inputs.clone(), + ); + let (sys_v6_fp3_t, key_v6_fp3_t) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri, FriBatching::Tensor), + inputs, + ); + + // Warmup all 4 configs. + let p_v5 = sys_v5.prove_multiple_claims( + &key_v5, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys_v5), + ); + let p_v6_fp2_t = sys_v6_fp2_t.prove_multiple_claims( + &key_v6_fp2_t, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys_v6_fp2_t), + ); + let p_v6_fp3_h = sys_v6_fp3_h.prove_multiple_claims( + &key_v6_fp3_h, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys_v6_fp3_h), + ); + let p_v6_fp3_t = sys_v6_fp3_t.prove_multiple_claims( + &key_v6_fp3_t, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys_v6_fp3_t), + ); + + // Interleaved timed rounds to cancel host load drift. + let mut prove = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + for _ in 0..5 { + let w = SystemWitness::from_stage_1(traces.clone(), &sys_v5); + let t0 = Instant::now(); + let _ = sys_v5.prove_multiple_claims(&key_v5, &claim_refs, w); + prove[0].push(t0.elapsed().as_secs_f64() * 1e3); + + let w = SystemWitness::from_stage_1(traces.clone(), &sys_v6_fp2_t); + let t0 = Instant::now(); + let _ = sys_v6_fp2_t.prove_multiple_claims(&key_v6_fp2_t, &claim_refs, w); + prove[1].push(t0.elapsed().as_secs_f64() * 1e3); + + let w = SystemWitness::from_stage_1(traces.clone(), &sys_v6_fp3_h); + let t0 = Instant::now(); + let _ = sys_v6_fp3_h.prove_multiple_claims(&key_v6_fp3_h, &claim_refs, w); + prove[2].push(t0.elapsed().as_secs_f64() * 1e3); + + let w = SystemWitness::from_stage_1(traces.clone(), &sys_v6_fp3_t); + let t0 = Instant::now(); + let _ = sys_v6_fp3_t.prove_multiple_claims(&key_v6_fp3_t, &claim_refs, w); + prove[3].push(t0.elapsed().as_secs_f64() * 1e3); + } + + let mut verify = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + for _ in 0..20 { + let t0 = Instant::now(); + sys_v5.verify_multiple_claims(&claim_refs, &p_v5).unwrap(); + verify[0].push(t0.elapsed().as_secs_f64() * 1e3); + + let t0 = Instant::now(); + sys_v6_fp2_t + .verify_multiple_claims(&claim_refs, &p_v6_fp2_t) + .unwrap(); + verify[1].push(t0.elapsed().as_secs_f64() * 1e3); + + let t0 = Instant::now(); + sys_v6_fp3_h + .verify_multiple_claims(&claim_refs, &p_v6_fp3_h) + .unwrap(); + verify[2].push(t0.elapsed().as_secs_f64() * 1e3); + + let t0 = Instant::now(); + sys_v6_fp3_t + .verify_multiple_claims(&claim_refs, &p_v6_fp3_t) + .unwrap(); + verify[3].push(t0.elapsed().as_secs_f64() * 1e3); + } + + let sizes = [ + p_v5.to_bytes().unwrap().len(), + p_v6_fp2_t.to_bytes().unwrap().len(), + p_v6_fp3_h.to_bytes().unwrap().len(), + p_v6_fp3_t.to_bytes().unwrap().len(), + ]; + let labels = [ + "`v5` `F_p^2` Horner", + "`v6` `F_p^2` Tensor", + "`v6` `F_p^3` Horner", + "`v6` `F_p^3` Tensor", + ]; + + println!( + "\n=== U32Add + ByteTable: {rows} rows (2^{}) | blowup=4, queries=64, arity=4 ===", + rows.ilog2() + ); + println!("| Config | Prove min / med (ms) | Verify min / med (ms) | Proof size (bytes) |"); + println!("|---|---:|---:|---:|"); + for i in 0..4 { + let (p_min, p_med) = min_and_median_ms(prove[i].clone()); + let (v_min, v_med) = min_and_median_ms(verify[i].clone()); + println!( + "| {} | {:.2} / {:.2} | {:.2} / {:.2} | {} |", + labels[i], p_min, p_med, v_min, v_med, sizes[i] + ); + } + } +} From 6625511141f93476528ad8694e08d11c0872ef39 Mon Sep 17 00:00:00 2001 From: samuelburnham <45365069+samuelburnham@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:39:14 +0000 Subject: [PATCH 21/28] Let concurrent device allocators reserve memory from admission Every proving phase sizes its device work from the free memory it measures when it starts and, without a standing reserve, allocates up to all of it. Memory another thread allocates on the device after that measurement (Ix uploads the next shard's population image on a prefetch thread while the current shard proves) is then missing when the phase allocates, and a resident coset LDE fails with cudaErrorMemoryAllocation instead of spilling. DeviceMemoryReservation holds bytes of a device back from every admission measurement until dropped. A concurrent allocator takes one before the phases it overlaps measure free memory and drops it once its allocation is live, so each measurement sees that memory as reserved or allocated, never free. A test fills the device so a stage-one commitment fits with little slack, then allocates beside it from a trace tile: unreserved, a resident LDE fails exactly as observed; reserved, admission builds the commitment within what remains and it matches the unconstrained commitment. The all-device path of the PCS commitment also charges the largest trace: an LDE uploads its trace beside its values, and a trace released after construction is still resident while its own LDE runs. The README's spill paragraph still described the removed quarter-device reserve; it now describes runtime admission and reservations. --- cuda/README.md | 11 ++- src/cuda/mod.rs | 111 +++++++++++++++++++++++++- src/cuda/pcs.rs | 14 ++++ src/cuda/tests/witness.rs | 158 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 290 insertions(+), 4 deletions(-) diff --git a/cuda/README.md b/cuda/README.md index 98ef665..f7a0506 100644 --- a/cuda/README.md +++ b/cuda/README.md @@ -28,9 +28,14 @@ prover pipeline device-resident: Large traces can be retained in pinned host memory and uploaded in bounded windows when keeping every source matrix resident would exceed device memory. -The spill policy reserves one quarter of reported device memory by default and -uses `cudaMemGetInfo` at runtime instead of assuming a particular GPU size. -This retains the exact CPU storage layout and proof bytes. +Each phase admits its allocations against the free memory it measures at +runtime (`cudaMemGetInfo` plus the allocation pool's unused pages, which the +driver returns to new requests when it runs short) instead of assuming a +particular GPU size. Memory allocated on the device by another thread while a +phase runs is invisible to that measurement, so such an allocator holds a +`multi_stark::cuda::DeviceMemoryReservation` of its size from before the +phases it overlaps until its allocation is live. This retains the exact CPU +storage layout and proof bytes. The ordinary `TwoAdicSubgroupDft` implementation remains available for direct host-matrix users and transfer-inclusive microbenchmarks. diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 771c00f..053d9f8 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2320,13 +2320,92 @@ pub(crate) fn bounded_parallel_map( } } +/// Device memory free for this backend's admission: what the driver and the +/// allocation pool report free, less every live [`DeviceMemoryReservation`] +/// on the device. pub(crate) fn device_memory_info(device_id: i32) -> (usize, usize) { let mut free_bytes = 0; let mut total_bytes = 0; let status = unsafe { multi_stark_cuda_memory_info(device_id, &mut free_bytes, &mut total_bytes) }; check_cuda(status, "CUDA device initialization"); - (free_bytes, total_bytes) + ( + free_bytes.saturating_sub(reserved_device_bytes(device_id)), + total_bytes, + ) +} + +fn device_reservations() -> &'static std::sync::Mutex> { + static RESERVATIONS: std::sync::OnceLock< + std::sync::Mutex>, + > = std::sync::OnceLock::new(); + RESERVATIONS.get_or_init(Default::default) +} + +/// Bytes the live reservations on `device_id` hold back from admission. +#[must_use] +pub fn reserved_device_bytes(device_id: i32) -> usize { + device_reservations() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&device_id) + .copied() + .unwrap_or(0) +} + +/// Device memory held back from this backend's admission for an allocation +/// made outside it, until dropped. +/// +/// Each proving phase sizes its device work from the free memory it measures +/// when it starts, and allocates up to all of it. Memory another thread +/// allocates on the device after that measurement, such as the next shard's +/// population input uploaded while the current shard proves, is then missing +/// when the phase allocates, and the phase fails with an out-of-memory error. +/// A concurrent allocator takes a reservation of its size before any phase +/// it can overlap measures free memory, allocates within it, and drops it +/// once the allocation is live (or abandoned), so every measurement sees the +/// memory as either reserved or allocated, never as free. +#[must_use = "the reservation ends when dropped"] +#[derive(Debug)] +pub struct DeviceMemoryReservation { + device_id: i32, + bytes: usize, +} + +impl DeviceMemoryReservation { + /// Holds `bytes` of `device_id` back from admission. + pub fn new(device_id: i32, bytes: usize) -> Self { + let mut reservations = device_reservations() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let held = reservations.entry(device_id).or_default(); + *held = held.saturating_add(bytes); + Self { device_id, bytes } + } + + #[must_use] + pub const fn device_id(&self) -> i32 { + self.device_id + } + + #[must_use] + pub const fn bytes(&self) -> usize { + self.bytes + } +} + +impl Drop for DeviceMemoryReservation { + fn drop(&mut self) { + let mut reservations = device_reservations() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(held) = reservations.get_mut(&self.device_id) { + *held = held.saturating_sub(self.bytes); + if *held == 0 { + reservations.remove(&self.device_id); + } + } + } } /// Returns the device memory this backend's allocation pool retains between @@ -4095,6 +4174,36 @@ mod tests { } } + #[test] + fn device_memory_reservations_nest_and_release() { + // No other test reserves memory on this device id. + let device = 63; + assert_eq!(reserved_device_bytes(device), 0); + let outer = DeviceMemoryReservation::new(device, 3 << 30); + let inner = DeviceMemoryReservation::new(device, 1 << 20); + assert_eq!(reserved_device_bytes(device), (3 << 30) + (1 << 20)); + assert_eq!(reserved_device_bytes(device - 1), 0); + drop(outer); + assert_eq!(reserved_device_bytes(device), 1 << 20); + drop(inner); + assert_eq!(reserved_device_bytes(device), 0); + } + + #[test] + #[ignore = "requires exclusive access to a CUDA device: hides its free memory"] + fn admission_excludes_reserved_device_memory() { + let device = configured_device(); + let bytes = 1usize << 40; + let reservation = DeviceMemoryReservation::new(device, bytes); + let (free, total) = device_memory_info(device); + assert!( + total < bytes && free == 0, + "free={free} beside a reservation larger than the device" + ); + drop(reservation); + assert!(device_memory_info(device).0 > 0); + } + #[test] #[ignore = "requires exclusive access to a CUDA device"] fn admission_release_restores_pool_capacity() { diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index f8ee762..96efc36 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -661,7 +661,21 @@ where .saturating_add(minimum_free) .saturating_add(max_transform_workspace) > initial_free; + // An LDE uploads its whole trace beside its values, and a trace + // released after construction is still resident while its own LDE + // runs, so the all-device path always needs the largest trace. + let max_trace_bytes = evaluations + .iter() + .map(|(_, matrix)| { + matrix + .height() + .saturating_mul(matrix.width()) + .saturating_mul(size_of::()) + }) + .max() + .unwrap_or(0); if lde_bytes + .saturating_add(max_trace_bytes) .saturating_add(minimum_free) .saturating_add(max_transform_workspace) > initial_free diff --git a/src/cuda/tests/witness.rs b/src/cuda/tests/witness.rs index 2d152d5..b6d3c37 100644 --- a/src/cuda/tests/witness.rs +++ b/src/cuda/tests/witness.rs @@ -348,3 +348,161 @@ fn generated_traces_prove_identically_under_lookup_pressure() { bincode::serde::encode_to_vec(&expected, bincode::config::standard()).unwrap() ); } + +/// A small generated source whose first tile allocates `bytes` of device +/// memory that commitment admission never charged, as a shard image +/// uploaded by another thread while the commitment runs does. With a +/// reservation, it drops it once that memory is allocated. +struct ConcurrentAllocation { + rows: HostRows, + bytes: usize, + held: std::sync::Mutex>, + reservation: std::sync::Mutex>, +} + +impl TraceGenerator for ConcurrentAllocation { + fn height(&self) -> usize { + self.rows.height() + } + + fn width(&self) -> usize { + self.rows.width() + } + + fn write_rows(&self, first: usize, output: &mut [Goldilocks]) { + self.rows.write_rows(first, output); + } + + fn device_workspace_bytes(&self) -> usize { + self.rows.device_workspace_bytes() + } + + fn write_device_rows(&self, view: DeviceTraceView<'_>) -> Result<(), String> { + let mut held = self.held.lock().unwrap(); + if held.is_empty() { + let mut remaining = self.bytes; + while remaining != 0 { + let chunk = (remaining / 2 + 1).next_power_of_two().min(1 << 30); + held.push(device_allocation(chunk)); + remaining -= chunk; + } + drop(self.reservation.lock().unwrap().take()); + } + drop(held); + self.rows.write_device_rows(view) + } +} + +/// Fills the device until the stage-one commitment of `hosts` beside a tiny +/// generated source fits resident with `slack` bytes to spare, then commits +/// while that source allocates `external` bytes admission did not see. +fn commit_beside_concurrent_allocation(reserve: bool) { + let config = GoldilocksBlake3Config::with_device( + CommitmentParameters { + log_blowup: 3, + cap_height: 0, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 8, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + Some(configured_device()), + ); + let pcs: &crate::types::InnerPcs = config.pcs(); + let device = configured_device(); + let blowup = 3; + let (height, width, hosts) = (1usize << 20, 8usize, 8usize); + let matrices: Vec<_> = (0..hosts) + .map(|seed| { + RowMajorMatrix::new( + (0..height * width) + .map(|index| Goldilocks::from_u64((index as u64 * 0x9e37_79b9) ^ seed as u64)) + .collect(), + width, + ) + }) + .collect(); + let generated = RowMajorMatrix::new((0..(1 << 10) * 2).map(Goldilocks::from_u64).collect(), 2); + let external = 3usize << 30; + let slack = 256usize << 20; + let reservation = std::sync::Mutex::new(None); + let source = Arc::new(ConcurrentAllocation { + rows: HostRows::new(generated.clone(), None), + bytes: external, + held: std::sync::Mutex::new(Vec::new()), + reservation, + }); + let domain = |height: usize| { + TwoAdicMultiplicativeCoset::new(Goldilocks::ONE, log2_strict_usize(height)).unwrap() + }; + let evaluations = |first: TraceSource| { + core::iter::once((domain(generated.height()), first)) + .chain( + matrices + .iter() + .map(|matrix| (domain(matrix.height()), TraceSource::Host(matrix.clone()))), + ) + .collect::>() + }; + // Also caches every transform constant before free memory is measured. + let (expected, _) = commit_with(pcs, evaluations(TraceSource::Host(generated.clone())), None); + + // The resident footprint `commit_with` admits for this batch. + let trace_bytes = height * width * size_of::(); + let plan = pcs + .dft + .lde_plan(height, width, blowup, Goldilocks::GENERATOR); + let footprint = (trace_bytes << blowup) + .saturating_add(trace_bytes) + .saturating_mul(hosts) + .saturating_add(plan.scratch_bytes() + plan.constant_bytes() + WRITER_WORKSPACE) + .saturating_add((height << blowup) * 96) + .saturating_add(minimum_free_bytes() + (128 << 20)); + let generated_bytes = generated.values.len() * size_of::() * ((1 << blowup) + 1); + let target = footprint + generated_bytes + slack; + assert!( + external > target - (trace_bytes << blowup).saturating_add(trace_bytes) * hosts, + "the external allocation must not fit in the admitted headroom" + ); + let mut ballast = Vec::new(); + loop { + let free = device_memory_info(device).0; + let remaining = free.saturating_sub(target); + if remaining < 4 << 20 { + break; + } + let chunk = (remaining / 2 + 1).next_power_of_two().min(1 << 30); + ballast.push(device_allocation(chunk)); + } + if reserve { + *source.reservation.lock().unwrap() = Some(DeviceMemoryReservation::new(device, external)); + } + let (commitment, _data) = commit_with( + pcs, + evaluations(TraceSource::Generated(source.clone())), + None, + ); + drop(ballast); + assert_eq!(commitment, expected); + assert_eq!(reserved_device_bytes(device), 0); +} + +/// Memory another thread allocates after commitment measured free memory +/// fails the resident LDEs that admission sized into it. +#[test] +#[ignore = "requires exclusive access to a CUDA device: fills its memory"] +#[should_panic(expected = "resident coset LDE failed (2): out of memory")] +fn unreserved_concurrent_allocation_exhausts_admitted_memory() { + commit_beside_concurrent_allocation(false); +} + +/// Reserved before the commitment measures free memory, the same allocation +/// makes admission choose a construction that fits beside it. +#[test] +#[ignore = "requires exclusive access to a CUDA device: fills its memory"] +fn reserved_concurrent_allocation_keeps_commitment_admissible() { + commit_beside_concurrent_allocation(true); +} From edb031d9a4e2a42fc19522a7c0d62d772619b7ef Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sun, 22 Nov 2026 07:40:52 -0500 Subject: [PATCH 22/28] fix(security): enforce exact MerkleCap root counts in MMCS and before transcript observation Enforce commit.num_roots() == 1 << cap_height.min(log2_ceil_usize(max_height)) across SpillableMmcs and CudaMmcs (verify_batch, verify_multi_batch) and validate exact expected cap root counts BEFORE Fiat-Shamir observation in: - System::verify_shape (preprocessed, stage_1_trace, stage_2_trace, quotient_chunks) - System::verify_preamble_headers (added for all shards including non-target shards in verify_batch_shard and verify_batch, enforcing active/log_degree, preprocessed_height, max_log_quotient_domain, and stage_1_trace cap count) - SpillableTwoAdicFriPcs::verify and CudaTwoAdicFriPcs::verify (all input and FRI commit_phase_commits validated before observing OOD evaluations or FRI commitments) Eliminates deterministic verify_batch_shard / verify_batch transcript-collision forgeries and O(1) commitment-preserving Fiat-Shamir grinding while keeping honest v5 proof bytes bit-identical (proof_bytes_pin and streaming_spill pass). Includes negative regression tests for all attack vectors. --- src/batch.rs | 451 ++++++++++++++++++++++++++ src/config.rs | 11 + src/cuda/mmcs.rs | 32 +- src/cuda/pcs.rs | 11 +- src/p3_adapter/cap.rs | 219 +++++++++++++ src/p3_adapter/mod.rs | 1 + src/p3_adapter/spill.rs | 108 +++++- src/test_circuits/baby_bear_config.rs | 11 + src/types.rs | 11 +- src/verifier.rs | 50 +++ 10 files changed, 897 insertions(+), 8 deletions(-) create mode 100644 src/p3_adapter/cap.rs diff --git a/src/batch.rs b/src/batch.rs index 806203f..6e41e6f 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -71,6 +71,7 @@ use crate::{ensure, ensure_eq}; use crate::traits::{Algebra, Field, Transcript, TwoAdicField}; use bincode::error::{DecodeError, EncodeError}; use bincode::serde::{decode_from_slice, encode_to_vec}; +use p3_util::log2_strict_usize; use serde::{Deserialize, Serialize}; /// What a shard publishes after round one: everything about it that the @@ -321,6 +322,129 @@ impl System { .expect("lookup challenge makes a batch message denominator zero") } + fn verify_preamble_headers( + &self, + preamble: &BatchPreamble, + ) -> Result<(), VerificationError>> { + ensure!( + !self.circuits.is_empty(), + VerificationError::InvalidSystem; + "system has no circuits" + ); + let num_preprocessed = self + .preprocessed_indices + .iter() + .map(|i| usize::from(i.is_some())) + .sum::(); + ensure_eq!( + self.preprocessed_commit.is_none(), + num_preprocessed == 0, + VerificationError::InvalidSystem; + commitment_present = self.preprocessed_commit.is_some(), + num_preprocessed, + "preprocessed commitment does not match configured circuits" + ); + if let Some(commit) = &self.preprocessed_commit { + let max_prep_height = self + .circuits + .iter() + .zip(&self.preprocessed_indices) + .filter_map(|(circuit, idx)| idx.map(|_| circuit.preprocessed_height)) + .max() + .unwrap_or(0); + ensure!( + max_prep_height > 0 + && max_prep_height.is_power_of_two() + && self.config.validate_commitment_cap( + commit, + log2_strict_usize(max_prep_height) + self.config.log_blowup(), + ), + VerificationError::InvalidSystem; + max_prep_height, + "preprocessed commitment cap root count mismatch" + ); + } + ensure!( + !preamble.headers.is_empty(), + VerificationError::BatchShapeMismatch; + "batch preamble has no shard headers" + ); + let max_log_degree = self.config.max_log_degree(); + let max_log_quotient_domain = self.config.max_log_quotient_domain(); + let log_blowup = self.config.log_blowup(); + for (idx, header) in preamble.headers.iter().enumerate() { + ensure!( + header.active.len() == self.circuits.len(), + VerificationError::BatchShapeMismatch; + shard = idx, + expected = self.circuits.len(), + got = header.active.len(), + "batch preamble header activation bitmap length mismatch" + ); + let active_indices: Vec = header + .active + .iter() + .enumerate() + .filter_map(|(ci, &is_active)| is_active.then_some(ci)) + .collect(); + ensure!( + !active_indices.is_empty() && header.log_degrees.len() == active_indices.len(), + VerificationError::BatchShapeMismatch; + shard = idx, + active_count = active_indices.len(), + log_degrees_len = header.log_degrees.len(), + "batch preamble header log_degrees count mismatch" + ); + for (&ci, &log_degree) in active_indices.iter().zip(&header.log_degrees) { + let circuit = &self.circuits[ci]; + if circuit.preprocessed_height != 0 { + ensure_eq!( + 1usize.checked_shl(u32::from(log_degree)), + Some(circuit.preprocessed_height), + VerificationError::BatchShapeMismatch; + shard = idx, + circuit = ci, + log_degree, + expected_height = circuit.preprocessed_height, + "batch preamble header trace height does not match preprocessed height" + ); + } + let quotient_degree = circuit.quotient_degree(); + ensure!( + usize::from(log_degree) <= max_log_degree + && usize::from(log_degree) < usize::BITS as usize + && usize::from(log_degree) + log2_strict_usize(quotient_degree) + <= max_log_quotient_domain, + VerificationError::BatchShapeMismatch; + shard = idx, + circuit = ci, + log_degree, + quotient_degree, + max_log_degree, + max_log_quotient_domain, + "batch preamble header trace or quotient domain exceeds supported size" + ); + } + let max_log_lde_height = header + .log_degrees + .iter() + .copied() + .map(usize::from) + .max() + .expect("active_indices is non-empty") + + log_blowup; + ensure!( + self.config + .validate_commitment_cap(&header.stage_1_trace, max_log_lde_height), + VerificationError::BatchShapeMismatch; + shard = idx, + max_log_lde_height, + "batch preamble header stage-1 commitment cap root count mismatch" + ); + } + Ok(()) + } + /// Verifies shard `shard` of a batch and returns its residual (final /// accumulator). The shard's header must describe `proof` exactly. pub fn verify_batch_shard( @@ -333,6 +457,7 @@ impl System { Val: TwoAdicField + Ord, Com: PartialEq, { + self.verify_preamble_headers(preamble)?; let (challenger, lookup_argument_challenge, fingerprint_challenge) = self.batch_challenger(preamble); self.verify_batch_shard_from( @@ -414,6 +539,7 @@ impl System { proof_count = proofs.len(), "invalid batch header/proof counts" ); + self.verify_preamble_headers(preamble)?; let (challenger, lookup_argument_challenge, fingerprint_challenge) = self.batch_challenger(preamble); let mut total = try_messages_accumulator( @@ -986,5 +1112,330 @@ mod tests { assert!(system.verify_batch(&batch).is_err()); } + fn pack_le_u64s(words: [u64; 4]) -> [u8; 32] { + let mut out = [0u8; 32]; + for (i, word) in words.into_iter().enumerate() { + out[i * 8..(i + 1) * 8].copy_from_slice(&word.to_le_bytes()); + } + out + } + + fn single_circuit_quad_system( + cap_height: usize, + ) -> ( + System, + ProverKey, + ) { + use crate::expr::Expr; + use crate::system::CircuitInputs; + + let cfg = GoldilocksBlake3Config::new( + CommitmentParameters { + log_blowup: 1, + cap_height, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 16, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + ); + let a = Expr::main(0); + let b = Expr::main(1); + System::new( + cfg, + [CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![a.clone() * a - b], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }], + ) + } + + fn quad_trace(log_degree: usize) -> RowMajorMatrix { + let rows = 1usize << log_degree; + let mut vals = Vec::with_capacity(rows * 2); + for i in 0..rows { + let x = Val::from_usize(i + 1); + vals.push(x); + vals.push(x * x); + } + RowMajorMatrix::new(vals, 2) + } + + /// Reproduces the `#240` #1A `verify_batch_shard` forgery: a 2-root + /// `MerkleCap` on non-target shard `H1.stage_1_trace` streams the exact + /// same bytes into the Fiat-Shamir transcript as a 1-root cap followed by + /// different `H1.log_degrees`, `H1.claims`, and `preamble.messages`. + #[test] + fn rejects_verify_batch_shard_merkle_cap_forgery() { + use p3_symmetric::MerkleCap; + + let (system, key) = single_circuit_quad_system(0); + let shards = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ]; + let messages_a = vec![ + BatchMessage { + args: vec![Val::from_u64(7)], + multiplicity: Val::from_u64(1), + }, + BatchMessage { + args: vec![Val::from_u64(999)], + multiplicity: Val::from_u64(0), + }, + ]; + let batch_a = system.prove_batch(&key, shards, messages_a); + assert!( + system + .verify_batch_shard(&batch_a.preamble, 0, &batch_a.proofs[0]) + .is_ok() + ); + + let r1 = batch_a.preamble.headers[1].stage_1_trace.roots()[0]; + let r_fake = pack_le_u64s([1, 5, 0, 2]); + let mut preamble_b = batch_a.preamble.clone(); + preamble_b.headers[1].stage_1_trace = MerkleCap::new(vec![r1, r_fake]); + preamble_b.headers[1].log_degrees = vec![7]; + preamble_b.headers[1].claims = vec![vec![Val::from_u64(999)]]; + preamble_b.messages = vec![]; + + // Confirm the forged preamble collides identically on the raw challenger stream. + let (_, beta_a, gamma_a) = system.batch_challenger(&batch_a.preamble); + let (_, beta_b, gamma_b) = system.batch_challenger(&preamble_b); + assert_eq!((beta_a, gamma_a), (beta_b, gamma_b)); + + // The verifier must reject the 2-root cap BEFORE transcript observation. + assert!(matches!( + system.verify_batch_shard(&preamble_b, 0, &batch_a.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + } + + /// Reproduces the `#240` #1B full `verify_batch` preamble/message forgery. + #[test] + fn rejects_verify_batch_merkle_cap_preamble_forgery() { + use p3_symmetric::MerkleCap; + + let (system, key) = single_circuit_quad_system(0); + let shards = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ]; + let messages_a = vec![ + BatchMessage { + args: vec![Val::from_u64(5)], + multiplicity: Val::from_u64(0), + }, + BatchMessage { + args: vec![Val::from_u64(0)], + multiplicity: Val::from_u64(0), + }, + ]; + let batch_a = system.prove_batch(&key, shards, messages_a); + system.verify_batch(&batch_a).unwrap(); + + let r1 = batch_a.preamble.headers[1].stage_1_trace.roots()[0]; + let forged_cap = MerkleCap::new(vec![r1, pack_le_u64s([1, 5, 0, 2])]); + let mut batch_b = batch_a.clone(); + batch_b.preamble.headers[1].stage_1_trace = forged_cap.clone(); + batch_b.proofs[1].commitments.stage_1_trace = forged_cap; + batch_b.preamble.messages = vec![BatchMessage { + args: vec![], + multiplicity: Val::from_u64(0), + }]; + + let (_, beta_a, gamma_a) = system.batch_challenger(&batch_a.preamble); + let (_, beta_b, gamma_b) = system.batch_challenger(&batch_b.preamble); + assert_eq!((beta_a, gamma_a), (beta_b, gamma_b)); + + assert!(matches!( + system.verify_batch(&batch_b), + Err(VerificationError::BatchShapeMismatch) + )); + assert!(matches!( + system.verify_shape(&batch_b.proofs[1]), + Err(VerificationError::InvalidProofShape) + )); + } + + /// Reproduces the `#240` #1C extra/truncated/non-power-of-two `MerkleCap` + /// Fiat-Shamir grinding attacks across stage-1, stage-2, quotient, and FRI + /// commit-phase commitments (for both `cap_height = 0` and `cap_height = 1`). + #[test] + fn rejects_merkle_cap_grinding_and_truncation() { + use p3_fri::verifier::FriError; + use p3_merkle_tree::MerkleTreeError; + use p3_symmetric::MerkleCap; + + let (system, key) = single_circuit_quad_system(0); + let proof = system.prove_multiple_claims( + &key, + &[], + SystemWitness::from_stage_1(vec![quad_trace(4)], &system), + ); + system.verify_multiple_claims(&[], &proof).unwrap(); + + let inflate = |cap: &MerkleCap| { + let mut roots = cap.roots().to_vec(); + roots.push([0xA5; 32]); + MerkleCap::new(roots) + }; + + // Stage-1 extra cap root + let mut bad_s1 = proof.clone(); + bad_s1.commitments.stage_1_trace = inflate(&proof.commitments.stage_1_trace); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_s1), + Err(VerificationError::InvalidProofShape) + )); + + // Stage-2 extra cap root + let mut bad_s2 = proof.clone(); + bad_s2.commitments.stage_2_trace = inflate(&proof.commitments.stage_2_trace); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_s2), + Err(VerificationError::InvalidProofShape) + )); + + // Quotient extra cap root + let mut bad_q = proof.clone(); + bad_q.commitments.quotient_chunks = inflate(&proof.commitments.quotient_chunks); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_q), + Err(VerificationError::InvalidProofShape) + )); + + // FRI commit-phase extra cap root + let mut bad_fri = proof.clone(); + bad_fri.opening_proof.commit_phase_commits[0] = + inflate(&proof.opening_proof.commit_phase_commits[0]); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_fri), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + + // Non-power-of-two (0-root and 3-root) caps constructed via serde deserialization + let zero_cap: MerkleCap = decode_from_slice( + &encode_to_vec(Vec::<[u8; 32]>::new(), bincode::config::standard()).unwrap(), + bincode::config::standard(), + ) + .unwrap() + .0; + let r0 = proof.commitments.stage_1_trace.roots()[0]; + let three_cap: MerkleCap = decode_from_slice( + &encode_to_vec(vec![r0, [1u8; 32], [2u8; 32]], bincode::config::standard()).unwrap(), + bincode::config::standard(), + ) + .unwrap() + .0; + for weird_cap in [zero_cap, three_cap] { + let mut p1 = proof.clone(); + p1.commitments.stage_1_trace = weird_cap.clone(); + assert!(matches!( + system.verify_multiple_claims(&[], &p1), + Err(VerificationError::InvalidProofShape) + )); + let mut pf = proof.clone(); + pf.opening_proof.commit_phase_commits[0] = weird_cap; + assert!(matches!( + system.verify_multiple_claims(&[], &pf), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + } + + // cap_height = 1: reject both truncated (1-root) and inflated (4-root) caps. + #[cfg(not(feature = "cuda"))] + { + let (sys1, key1) = single_circuit_quad_system(1); + let proof1 = sys1.prove_multiple_claims( + &key1, + &[], + SystemWitness::from_stage_1(vec![quad_trace(4)], &sys1), + ); + sys1.verify_multiple_claims(&[], &proof1).unwrap(); + assert_eq!(proof1.commitments.stage_1_trace.num_roots(), 2); + + let trunc_s1 = MerkleCap::new(vec![proof1.commitments.stage_1_trace.roots()[0]]); + let mut p_trunc = proof1.clone(); + p_trunc.commitments.stage_1_trace = trunc_s1; + assert!(matches!( + sys1.verify_multiple_claims(&[], &p_trunc), + Err(VerificationError::InvalidProofShape) + )); + + let fri_roots = proof1.opening_proof.commit_phase_commits[0] + .roots() + .to_vec(); + let mut p_fri_trunc = proof1.clone(); + p_fri_trunc.opening_proof.commit_phase_commits[0] = MerkleCap::new(vec![fri_roots[0]]); + assert!(matches!( + sys1.verify_multiple_claims(&[], &p_fri_trunc), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + + let mut p_fri_infl = proof1; + p_fri_infl.opening_proof.commit_phase_commits[0] = + MerkleCap::new(vec![fri_roots[0], fri_roots[1], [0x11; 32], [0x22; 32]]); + assert!(matches!( + sys1.verify_multiple_claims(&[], &p_fri_infl), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + } + } + + #[test] + fn rejects_invalid_non_target_shard_preamble_dimensions() { + let (system, key) = byte_system(config()); + let batch = system.prove_batch(&key, two_shards(&system), vec![]); + let _ = system + .verify_batch_shard(&batch.preamble, 0, &batch.proofs[0]) + .unwrap(); + + // Non-target shard 1 claims wrong preprocessed height for circuit 0 (256-row byte table). + let mut bad_prep = batch.preamble.clone(); + bad_prep.headers[1].active[0] = true; + bad_prep.headers[1].log_degrees.insert(0, 4); + assert!(matches!( + system.verify_batch_shard(&bad_prep, 0, &batch.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + + // Non-target shard 1 exceeds max_log_quotient_domain (or max_log_degree). + let mut bad_deg = batch.preamble; + bad_deg.headers[1].log_degrees[0] = + u8::try_from(system.config.max_log_degree() + 1).unwrap(); + assert!(matches!( + system.verify_batch_shard(&bad_deg, 0, &batch.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + } + type ExtVal = ::Challenge; } diff --git a/src/config.rs b/src/config.rs index 8e18245..4abd42f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -138,6 +138,17 @@ pub trait ProofConfig { /// evaluations. fn log_blowup(&self) -> usize; + /// Validate that `commit` has the exact expected structure (e.g. exact + /// Merkle cap root count) for a commitment whose tallest committed LDE has + /// height `2^max_log_lde_height`. + /// + /// Called by the verifier before observing any commitment into the + /// Fiat-Shamir transcript so variable-length caps cannot collide with + /// subsequent transcript fields or enable free challenge grinding. + fn validate_commitment_cap(&self, _commit: &Com, _max_log_lde_height: usize) -> bool { + true + } + /// Commit deterministic main-trace sources. fn commit_main( &self, diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index 41e7d7f..75bdd0c 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -10,6 +10,9 @@ use super::{ CudaLde, CudaMixedMerkleTree, mixed_lde_open_row, mixed_lde_open_row_at_height, mixed_lde_open_rows, mixed_lde_open_rows_at_height, }; +use crate::p3_adapter::cap::{ + CapValidatingMmcs, verify_merkle_cap_len, verify_merkle_cap_len_for_log_height, +}; use crate::types::Blake3CompressionFunction; use p3_blake3::Blake3; use p3_symmetric::SerializingHasher; @@ -488,6 +491,7 @@ fn hybrid_open_rows>( #[derive(Clone, Debug)] pub struct CudaMmcs { cpu: CpuMmcs, + cap_height: usize, device_id: i32, } @@ -496,9 +500,17 @@ impl CudaMmcs { /// it launches, allocation it makes and buffer it stages through belongs /// to that device, so several of these in one process can each own a /// device of their own. - pub(crate) fn with_device(cpu: CpuMmcs, device_id: i32) -> Self { + pub(crate) fn with_device(cpu: CpuMmcs, cap_height: usize, device_id: i32) -> Self { assert!(device_id >= 0, "CUDA device id must be non-negative"); - Self { cpu, device_id } + Self { + cpu, + cap_height, + device_id, + } + } + + pub const fn cap_height(&self) -> usize { + self.cap_height } } @@ -1413,6 +1425,7 @@ impl Mmcs for CudaMmcs { index: usize, batch_opening: BatchOpeningRef<'_, Goldilocks, Self>, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; self.cpu.verify_batch( commit, dimensions, @@ -1468,11 +1481,22 @@ impl Mmcs for CudaMmcs { opened_values: &[Vec], proof: &Self::MultiProof, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; self.cpu .verify_multi_batch(commit, dimensions, indices, opened_values, proof) } } +impl CapValidatingMmcs for CudaMmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) + } +} + #[cfg(test)] mod tests { use p3_commit::Mmcs; @@ -1543,7 +1567,7 @@ mod tests { .iter() .map(|&i| cpu.open_batch(i, &expected_data)) .collect(); - let mmcs = CudaMmcs::with_device(cpu, 0); + let mmcs = CudaMmcs::with_device(cpu, 0, 0); let ldes = matrices .iter() .map(|m| CudaLde::from_row_major_matrix(mmcs.device_id, m)) @@ -1567,7 +1591,7 @@ mod tests { let (expected_commitment, expected_data) = cpu.commit(matrices.clone()); let expected_opening = cpu.open_batch(5, &expected_data); - let mmcs = CudaMmcs::with_device(cpu, 0); + let mmcs = CudaMmcs::with_device(cpu, 0, 0); let resident = vec![ Some(CudaLde::from_row_major_matrix(mmcs.device_id, &matrices[0])), None, diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index a5ea164..632ce67 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -25,6 +25,7 @@ use std::borrow::Cow; use std::vec; use std::vec::Vec; +use crate::p3_adapter::cap::{CapValidatingMmcs, validate_fri_commitment_caps}; use itertools::{Itertools, izip}; use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; use p3_commit::{ExtensionMmcs, Mmcs, OpenedValues, Pcs, PeriodicLdeTable}; @@ -592,8 +593,8 @@ impl Pcs + CudaPcsDft + Sync, - InputMmcs: Mmcs + CudaCommitMmcs, - FriMmcs: Mmcs + CudaFriMmcs, + InputMmcs: CapValidatingMmcs + CudaCommitMmcs, + FriMmcs: CapValidatingMmcs + CudaFriMmcs, Challenge: ExtensionField, Challenger: FieldChallenger + CanObserve + GrindingChallenger, @@ -2242,6 +2243,12 @@ where proof: &Self::Proof, challenger: &mut Challenger, ) -> Result<(), Self::Error> { + validate_fri_commitment_caps( + &self.fri, + proof, + &commitments_with_opening_points, + &self.mmcs, + )?; // Write all evaluations to challenger. // Need to ensure to do this in the same order as the prover. for (_, round) in &commitments_with_opening_points { diff --git a/src/p3_adapter/cap.rs b/src/p3_adapter/cap.rs new file mode 100644 index 0000000..37a1066 --- /dev/null +++ b/src/p3_adapter/cap.rs @@ -0,0 +1,219 @@ +//! Exact `MerkleCap` root-count validation helpers shared by CPU and CUDA +//! MMCS/PCS verifiers. +//! +//! Plonky3's `MerkleCap` derives `Deserialize` directly on `Vec`, +//! `SerializingChallenger` observes `cap.roots()` raw without a length prefix, +//! and upstream `MerkleTreeMmcs::{verify_batch, verify_multi_batch}` only check +//! `cap_idx < commit.num_roots()`. Without enforcing the exact expected root +//! count (`1 << cap_height.min(log2_ceil_usize(max_height))`) both in MMCS +//! verification and before Fiat-Shamir observation, a prover can inject extra +//! cap roots to grind challenges for free or collide adjacent transcript fields. + +use p3_commit::{ExtensionMmcs, Mmcs}; +use p3_field::{ExtensionField, Field, TwoAdicField, coset::TwoAdicMultiplicativeCoset}; +use p3_fri::verifier::FriError; +use p3_fri::{CommitmentWithOpeningPoints, FriParameters, FriProof}; +use p3_matrix::Dimensions; +use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; +use p3_symmetric::MerkleCap; +use p3_util::{log2_ceil_usize, log2_strict_usize}; + +/// Exact Merkle cap root count for a binary Merkle tree whose tallest committed +/// matrix has `log2_ceil(max_height) == log_max_height`. +#[inline] +pub(crate) fn expected_merkle_cap_roots(cap_height: usize, log_max_height: usize) -> Option { + let effective_cap_height = cap_height.min(log_max_height); + let shift = u32::try_from(effective_cap_height).ok()?; + 1usize.checked_shl(shift) +} + +/// Validates that `commit` carries the exact expected root count for a binary +/// Merkle tree with `log2_ceil(max_height) == log_max_height`. +#[inline] +pub(crate) fn verify_merkle_cap_len_for_log_height( + cap_height: usize, + commit: &MerkleCap, + log_max_height: usize, +) -> Result<(), MerkleTreeError> { + let expected_roots = expected_merkle_cap_roots(cap_height, log_max_height) + .ok_or(MerkleTreeError::CapMismatch)?; + if commit.num_roots() != expected_roots { + return Err(MerkleTreeError::CapMismatch); + } + Ok(()) +} + +/// Validates that `commit` carries the exact expected root count for the +/// tallest matrix in `dimensions`. +#[inline] +pub(crate) fn verify_merkle_cap_len( + cap_height: usize, + commit: &MerkleCap, + dimensions: &[Dimensions], +) -> Result<(), MerkleTreeError> { + let max_height = dimensions + .iter() + .map(|dims| dims.height) + .max() + .ok_or(MerkleTreeError::EmptyBatch)?; + if max_height == 0 { + return Err(MerkleTreeError::EmptyBatch); + } + verify_merkle_cap_len_for_log_height(cap_height, commit, log2_ceil_usize(max_height)) +} + +/// MMCS that can validate a commitment's exact Merkle cap root count against a +/// verifier-known tree height before observing the commitment into a transcript. +pub trait CapValidatingMmcs: Mmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error>; +} + +impl CapValidatingMmcs for ExtensionMmcs +where + F: Field, + EF: ExtensionField, + InnerMmcs: + CapValidatingMmcs, Error = MerkleTreeError>, +{ + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + // Delegate through `verify_multi_batch` with an empty query set so + // `InnerMmcs` enforces its own configured `cap_height` without needing + // access to `ExtensionMmcs`'s private `inner` field. + let height = u32::try_from(log_max_height) + .ok() + .and_then(|shift| 1usize.checked_shl(shift)) + .ok_or(MerkleTreeError::CapMismatch)?; + let empty_rows: &[Vec<&[EF]>] = &[]; + let empty_proof = PrunedMerklePaths { + sibling_hashes: Vec::new(), + }; + self.verify_multi_batch( + commit, + &[Dimensions { width: 1, height }], + &[], + empty_rows, + &empty_proof, + ) + } +} + +/// Validates the exact Merkle cap root count of every input commitment and +/// every FRI commit-phase commitment before any commitment is observed into the +/// Fiat-Shamir transcript. +pub(crate) fn validate_fri_commitment_caps< + Val, + Challenge, + InputMmcs, + FriMmcs, + Witness, + InputProof, +>( + params: &FriParameters, + proof: &FriProof, + commitments_with_opening_points: &[CommitmentWithOpeningPoints< + Challenge, + InputMmcs::Commitment, + TwoAdicMultiplicativeCoset, + >], + input_mmcs: &InputMmcs, +) -> Result<(), FriError> +where + Val: TwoAdicField, + Challenge: ExtensionField, + InputMmcs: CapValidatingMmcs, + FriMmcs: CapValidatingMmcs, +{ + if params.num_queries == 0 { + return Err(FriError::ZeroQueries); + } + + for (comm, mats) in commitments_with_opening_points { + if let Some(max_log_height) = mats + .iter() + .map(|(domain, _)| log2_strict_usize(domain.size()) + params.log_blowup) + .max() + { + input_mmcs + .validate_commitment_cap_for_log_height(comm, max_log_height) + .map_err(FriError::InputError)?; + } + } + + let expected_rounds = proof.commit_phase_commits.len(); + if proof.commit_phase_openings.len() != expected_rounds { + return Err(FriError::CommitPhaseOpeningsCountMismatch { + expected: expected_rounds, + got: proof.commit_phase_openings.len(), + }); + } + + let mut total_log_reduction = 0usize; + let mut log_arities = Vec::with_capacity(expected_rounds); + for (round, opening) in proof.commit_phase_openings.iter().enumerate() { + let log_arity = usize::from(opening.log_arity); + if !(1..=params.max_log_arity).contains(&log_arity) { + return Err(FriError::InvalidLogArity { + round, + log_arity, + max: params.max_log_arity, + }); + } + total_log_reduction = total_log_reduction.checked_add(log_arity).ok_or( + FriError::GlobalMaxHeightTooLarge { + log_global_max_height: usize::MAX, + two_adicity: Val::TWO_ADICITY, + }, + )?; + log_arities.push(log_arity); + } + + let log_global_max_height = total_log_reduction + .checked_add(params.log_blowup) + .and_then(|v| v.checked_add(params.log_final_poly_len)) + .ok_or(FriError::GlobalMaxHeightTooLarge { + log_global_max_height: usize::MAX, + two_adicity: Val::TWO_ADICITY, + })?; + if log_global_max_height > Val::TWO_ADICITY { + return Err(FriError::GlobalMaxHeightTooLarge { + log_global_max_height, + two_adicity: Val::TWO_ADICITY, + }); + } + + let expected_log_global_max_height = commitments_with_opening_points + .iter() + .flat_map(|(_, mats)| { + mats.iter() + .map(|(domain, _)| log2_strict_usize(domain.size()) + params.log_blowup) + }) + .max(); + if let Some(expected) = expected_log_global_max_height + && log_global_max_height != expected + { + return Err(FriError::GlobalMaxHeightMismatch { + expected, + got: log_global_max_height, + }); + } + + let mut log_current_height = log_global_max_height; + for (comm, &log_arity) in proof.commit_phase_commits.iter().zip(&log_arities) { + let log_folded_height = log_current_height - log_arity; + params + .mmcs + .validate_commitment_cap_for_log_height(comm, log_folded_height) + .map_err(FriError::CommitPhaseMmcsError)?; + log_current_height = log_folded_height; + } + + Ok(()) +} diff --git a/src/p3_adapter/mod.rs b/src/p3_adapter/mod.rs index aed6546..34ef97e 100644 --- a/src/p3_adapter/mod.rs +++ b/src/p3_adapter/mod.rs @@ -4,6 +4,7 @@ mod air; #[cfg(not(feature = "cuda"))] pub(crate) mod blake3_simd; +pub mod cap; pub mod challenger; pub mod domain; pub mod field; diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs index 4620c79..a2ea0f5 100644 --- a/src/p3_adapter/spill.rs +++ b/src/p3_adapter/spill.rs @@ -50,6 +50,10 @@ use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_slice_index_bits}; use tracing::debug_span; use super::blake3_simd; +use super::cap::{ + CapValidatingMmcs, validate_fri_commitment_caps, verify_merkle_cap_len, + verify_merkle_cap_len_for_log_height, +}; use crate::types::{Blake3CompressionFunction, ExtVal, PackedVal, Val}; /// CPU reference MMCS used for verification and reference tests. @@ -1265,6 +1269,7 @@ impl Mmcs for SpillableMmcs { index: usize, batch_opening: BatchOpeningRef<'_, Val, Self>, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; let (opened_values, opening_proof) = batch_opening.unpack(); self.cpu.verify_batch( commit, @@ -1297,11 +1302,22 @@ impl Mmcs for SpillableMmcs { opened_values: &[Vec], proof: &Self::MultiProof, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; self.cpu .verify_multi_batch(commit, dimensions, indices, opened_values, proof) } } +impl CapValidatingMmcs for SpillableMmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) + } +} + /// CPU two-adic FRI PCS supporting optional disk-backed LDE spilling with /// streaming commitment, quotient-domain slicing, and FRI opening. /// @@ -1482,7 +1498,7 @@ impl SpillableTwoAdicFriPcs { impl Pcs for SpillableTwoAdicFriPcs where Dft: TwoAdicSubgroupDft, - FriMmcs: Mmcs, + FriMmcs: CapValidatingMmcs, Challenger: FieldChallenger + CanObserve + GrindingChallenger, { @@ -1864,6 +1880,12 @@ where proof: &Self::Proof, challenger: &mut Challenger, ) -> Result<(), Self::Error> { + validate_fri_commitment_caps( + &self.fri, + proof, + &commitments_with_opening_points, + &self.mmcs, + )?; for (_, round) in &commitments_with_opening_points { for (_, mat) in round { for (_, point) in mat { @@ -2458,4 +2480,88 @@ mod tests { } } } + + #[test] + fn verify_batch_and_multi_batch_reject_wrong_cap_root_count() { + use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; + + let mut rng = SmallRng::seed_from_u64(1337); + let mat = RowMajorMatrix::new( + (0..32 * 4).map(|_| Goldilocks::new(rng.random())).collect(), + 4, + ); + let dims = [Dimensions { + width: 4, + height: 32, + }]; + + for cap_height in [0usize, 1] { + let (_, mmcs) = make_mmcs(cap_height); + let (commit, data) = mmcs.commit(vec![mat.clone()]); + let single = mmcs.open_batch(7, &data); + let (multi_vals, multi_proof) = mmcs.open_multi_batch(&[3, 7, 19], &data); + + // Honest commitment verifies. + mmcs.verify_batch( + &commit, + &dims, + 7, + BatchOpeningRef::new(&single.opened_values, &single.opening_proof), + ) + .unwrap(); + mmcs.verify_multi_batch(&commit, &dims, &[3, 7, 19], &multi_vals, &multi_proof) + .unwrap(); + + // Inflated cap (double root count) is rejected by both single and multi-batch. + let mut inflated_roots = commit.roots().to_vec(); + inflated_roots.extend_from_slice(commit.roots()); + let inflated = MerkleCap::new(inflated_roots); + assert!(matches!( + mmcs.verify_batch( + &inflated, + &dims, + 7, + BatchOpeningRef::new(&single.opened_values, &single.opening_proof), + ), + Err(MerkleTreeError::CapMismatch) + )); + assert!(matches!( + mmcs.verify_multi_batch(&inflated, &dims, &[3, 7, 19], &multi_vals, &multi_proof), + Err(MerkleTreeError::CapMismatch) + )); + // Even with zero queries, wrong cap length is rejected. + let empty_rows: &[Vec<&[Val]>] = &[]; + let empty_proof = PrunedMerklePaths { + sibling_hashes: Vec::new(), + }; + assert!(matches!( + mmcs.verify_multi_batch(&inflated, &dims, &[], empty_rows, &empty_proof), + Err(MerkleTreeError::CapMismatch) + )); + + // Truncated cap (for cap_height = 1, 1 root instead of 2) is rejected. + if cap_height > 0 { + let truncated = MerkleCap::new(vec![commit.roots()[0]]); + assert!(matches!( + mmcs.verify_batch( + &truncated, + &dims, + 7, + BatchOpeningRef::new(&single.opened_values, &single.opening_proof), + ), + Err(MerkleTreeError::CapMismatch) + )); + assert!(matches!( + mmcs.verify_multi_batch( + &truncated, + &dims, + &[3, 7, 19], + &multi_vals, + &multi_proof, + ), + Err(MerkleTreeError::CapMismatch) + )); + } + } + } } diff --git a/src/test_circuits/baby_bear_config.rs b/src/test_circuits/baby_bear_config.rs index d5ce290..468c840 100644 --- a/src/test_circuits/baby_bear_config.rs +++ b/src/test_circuits/baby_bear_config.rs @@ -221,6 +221,17 @@ impl ProofConfig for BabyBearPoseidon2Config { fn log_blowup(&self) -> usize { self.log_blowup } + + fn validate_commitment_cap( + &self, + commit: &crate::config::Com, + max_log_lde_height: usize, + ) -> bool { + crate::p3_adapter::cap::expected_merkle_cap_roots( + self.pcs.commitment_parameters().cap_height, + max_log_lde_height, + ) == Some(commit.num_roots()) + } } /// A minimal AIR: enforces `a * b == c` per row, with a self-canceling diff --git a/src/types.rs b/src/types.rs index 4bbe999..ef28d2f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -438,6 +438,15 @@ impl ProofConfig for GoldilocksBlake3Config { self.log_blowup } + fn validate_commitment_cap( + &self, + commit: &crate::config::Com, + max_log_lde_height: usize, + ) -> bool { + crate::p3_adapter::cap::expected_merkle_cap_roots(self.cap_height, max_log_lde_height) + == Some(commit.num_roots()) + } + #[cfg(feature = "cuda")] fn commit_main( &self, @@ -1533,7 +1542,7 @@ fn new_mmcs(cap_height: usize, #[cfg(feature = "cuda")] device_id: i32) -> Mmcs #[cfg(feature = "cuda")] { let cpu = CpuMmcs::new(field_hash, compress, cap_height); - crate::cuda::mmcs::CudaMmcs::with_device(cpu, device_id) + crate::cuda::mmcs::CudaMmcs::with_device(cpu, cap_height, device_id) } } diff --git a/src/verifier.rs b/src/verifier.rs index 8e8c7b2..d6b5141 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -655,6 +655,26 @@ impl System { num_preprocessed, "preprocessed commitment does not match configured circuits" ); + if let Some(commit) = &self.preprocessed_commit { + let max_prep_height = self + .circuits + .iter() + .zip(&self.preprocessed_indices) + .filter_map(|(circuit, idx)| idx.map(|_| circuit.preprocessed_height)) + .max() + .unwrap_or(0); + crate::ensure!( + max_prep_height > 0 + && max_prep_height.is_power_of_two() + && self.config.validate_commitment_cap( + commit, + log2_strict_usize(max_prep_height) + self.config.log_blowup(), + ), + VerificationError::InvalidSystem; + max_prep_height, + "preprocessed commitment cap root count mismatch" + ); + } // Stage 0 round: the preprocessed commitment is built once over ALL // preprocessed traces at system construction, so its round carries one // entry per preprocessed matrix. Inactive matrices need one full-width @@ -844,6 +864,36 @@ impl System { ); quotient_degrees.push(quotient_degree); } + // Validate exact Merkle cap root counts before any commitment enters + // the Fiat-Shamir transcript. + let max_log_lde_height = log_degrees + .iter() + .copied() + .map(usize::from) + .max() + .expect("num_active > 0") + + self.config.log_blowup(); + crate::ensure!( + self.config + .validate_commitment_cap(&proof.commitments.stage_1_trace, max_log_lde_height), + VerificationError::InvalidProofShape; + max_log_lde_height, + "stage-1 commitment cap root count mismatch" + ); + crate::ensure!( + self.config + .validate_commitment_cap(&proof.commitments.stage_2_trace, max_log_lde_height), + VerificationError::InvalidProofShape; + max_log_lde_height, + "stage-2 commitment cap root count mismatch" + ); + crate::ensure!( + self.config + .validate_commitment_cap(&proof.commitments.quotient_chunks, max_log_lde_height), + VerificationError::InvalidProofShape; + max_log_lde_height, + "quotient commitment cap root count mismatch" + ); // One wide quotient matrix per active circuit, holding all its // coefficient slices, opened at the single point ζ. ensure_eq!( From ca241b4f1e9259dfeb0ad93c657078a46989241a Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sun, 22 Nov 2026 07:40:54 -0500 Subject: [PATCH 23/28] fix(security): enforce MerkleCap root counts (C2) and fix M24/L9 CUDA & verifier issues C2 (CRITICAL): - Enforce exact MerkleCap root count 1 << cap_height.min(log2_ceil(max_height)) in SpillableMmcs and CudaMmcs (verify_batch, verify_multi_batch). - Validate exact expected cap root counts before Fiat-Shamir observation in verify_shape, verify_preamble_headers, verify_fri_with_batching{,_inner}, SpillableTwoAdicFriPcs::verify, and CudaTwoAdicFriPcs::verify. - Add negative regression tests reproducing verify_batch_shard forgery, verify_batch preamble forgery, and extra/truncated/non-pow2 cap grinding for both v5 and v6 (F_p^3). M24 (MEDIUM): - Add host_hashed_heights (>4096-col) host-hashing fallback to CudaMmcs::commit_cuda_spillable matching commit_cuda_resident. - Reject preprocessed_opened_values = Some(vec![]) when num_preprocessed == 0 in System::verify_shape to eliminate proof malleability. - Enforce preprocessed_height and max_log_quotient_domain checks for all shards (including non-target shards) in System::verify_preamble_headers. L9 (LOW): - Mask mult == 0 norms to 1 in CUDA lookup_messages_t / lookup_messages_graph_t and mask mult == 0 messages to EF::ONE in LookupValues::cuda_stage_2_deltas. - Canonicalize operand before zero-check in CUDA Node::Neg at all 3 sites. - Skip empty opening point lists before allocating reduced_openings[log_height] in SpillableTwoAdicFriPcs::open. - Add >1024-row LDE (512 rows, blowup 4 => 2048 LDE) v6 F_p^3 test in tests/fp3_v6.rs to exercise CUDA resident FRI _ext3 kernels. --- cuda/kernels.cu | 28 +- src/batch.rs | 401 +++++++++++++++++++++++++- src/config.rs | 11 + src/cuda/mmcs.rs | 60 +++- src/cuda/pcs.rs | 11 +- src/lookup.rs | 18 +- src/p3_adapter/cap.rs | 219 ++++++++++++++ src/p3_adapter/fri_batching.rs | 14 +- src/p3_adapter/mod.rs | 1 + src/p3_adapter/spill.rs | 119 +++++++- src/test_circuits/baby_bear_config.rs | 11 + src/types.rs | 18 ++ src/verifier.rs | 65 ++++- tests/fp3_v6.rs | 354 +++++++++++++++++++++++ 14 files changed, 1282 insertions(+), 48 deletions(-) create mode 100644 src/p3_adapter/cap.rs diff --git a/cuda/kernels.cu b/cuda/kernels.cu index 6397ceb..b6a5801 100644 --- a/cuda/kernels.cu +++ b/cuda/kernels.cu @@ -1193,12 +1193,13 @@ __global__ void add_scaled_t(Ext* output,const Ext* input,size_t count,Ext scale } template -__global__ void lookup_messages_t(Ext* conjugates,uint64_t* norms,const uint64_t* args, - const size_t* arg_offsets,size_t height,size_t num_lookups,size_t args_width, +__global__ void lookup_messages_t(Ext* conjugates,uint64_t* norms,const uint64_t* multiplicities, + const uint64_t* args,const size_t* arg_offsets,size_t height,size_t num_lookups,size_t args_width, Ext beta,Ext gamma,uint64_t ext_w){ using Ops = ExtOps; const size_t count=height*num_lookups; for(size_t index=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;index(gridDim.x)*blockDim.x){ + if(canonicalize(multiplicities[index])==0){conjugates[index]=Ops::zero();norms[index]=1;continue;} const size_t row=index/num_lookups,lookup=index%num_lookups;Ext fingerprint=Ops::zero(); for(size_t j=arg_offsets[lookup+1];j>arg_offsets[lookup];--j) fingerprint=Ops::add_base(Ops::mul(fingerprint,gamma,ext_w),args[row*args_width+j-1]); @@ -1242,15 +1243,18 @@ __global__ void lookup_messages_graph_t( case 6:v=goldilocks_add(a,b);break; case 7:v=goldilocks_sub(a,b);break; case 8:v=goldilocks_mul(a,b);break; - case 9:v=a==0?0:GOLDILOCKS_P-canonicalize(a);break; + case 9:{const uint64_t ca=canonicalize(a);v=ca==0?0:GOLDILOCKS_P-ca;break;} }values[n.out*tile+lane]=v; while(next_lookup0;--k) fingerprint=Ops::add_base(Ops::mul(fingerprint,gamma,ext_w),values[lookup_args[l.arg_start+k-1]*tile+lane]); - const Ext message=Ops::add(beta,fingerprint);const size_t index=local_row*lookup_count+l.output; + const Ext message=Ops::add(beta,fingerprint); Ops::adjugate_and_norm(message,ext_w,conjugates[index],norms[index]); - multiplicities[index]=values[l.multiplicity*tile+lane]; } } } @@ -1519,7 +1523,7 @@ __global__ void evaluate_constraint_graph( case 6: result = goldilocks_add(left, right); break; case 7: result = goldilocks_sub(left, right); break; case 8: result = goldilocks_mul(left, right); break; - case 9: result = left == 0 ? 0 : GOLDILOCKS_P - canonicalize(left); break; + case 9: { const uint64_t cl = canonicalize(left); result = cl == 0 ? 0 : GOLDILOCKS_P - cl; break; } } values[node.out * tile + lane] = result; } @@ -1625,7 +1629,7 @@ __global__ void evaluate_quotient_t( case 6: v = goldilocks_add(a,b); break; case 7: v = goldilocks_sub(a,b); break; case 8: v = goldilocks_mul(a,b); break; - case 9: v = a == 0 ? 0 : GOLDILOCKS_P - canonicalize(a); break; + case 9: { const uint64_t ca = canonicalize(a); v = ca == 0 ? 0 : GOLDILOCKS_P - ca; break; } } values[n.out * tile + lane] = v; } @@ -3516,7 +3520,7 @@ int lookup_trace_impl(int device_id,uint64_t* output,uint64_t* total, if(status==cudaSuccess)status=cudaMemcpyAsync(dm,multiplicities,height*num_lookups*sizeof(uint64_t),cudaMemcpyHostToDevice,0); if(status==cudaSuccess&&args_width)status=cudaMemcpyAsync(da,args,height*args_width*sizeof(uint64_t),cudaMemcpyHostToDevice,0); if(status==cudaSuccess)status=cudaMemcpyAsync(offsets,arg_offsets,(num_lookups+1)*sizeof(size_t),cudaMemcpyHostToDevice,0); - if(status==cudaSuccess){lookup_messages_t<<>>(conjugates,norms,da,offsets,height,num_lookups,args_width,ExtOps::load(beta),ExtOps::load(gamma),ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){lookup_messages_t<<>>(conjugates,norms,dm,da,offsets,height,num_lookups,args_width,ExtOps::load(beta),ExtOps::load(gamma),ext_w);status=cudaGetLastError();} if(status==cudaSuccess)status=batch_inverse_norms(norm_inverses,norms,message_count); if(status==cudaSuccess){lookup_group_deltas_batched_t<<>>(deltas,dm,conjugates,norm_inverses,height,num_lookups,group_size);status=cudaGetLastError();} if(status==cudaSuccess)status=exclusive_scan_ext_t(scan,deltas,count); @@ -3654,7 +3658,7 @@ int lookup_lde_impl(int device_id,void** output_handle,uint64_t* total, const size_t messages=rows*num_lookups; status=cudaMemcpy(dm,multiplicities+row_start*num_lookups,messages*sizeof(uint64_t),cudaMemcpyHostToDevice); if(status==cudaSuccess&&args_width)status=cudaMemcpy(da,args+row_start*args_width,rows*args_width*sizeof(uint64_t),cudaMemcpyHostToDevice); - if(status==cudaSuccess){lookup_messages_t<<>>(conjugates,norms,da,offsets,rows,num_lookups,args_width,beta_ext,gamma_ext,ext_w);status=cudaGetLastError();} + if(status==cudaSuccess){lookup_messages_t<<>>(conjugates,norms,dm,da,offsets,rows,num_lookups,args_width,beta_ext,gamma_ext,ext_w);status=cudaGetLastError();} if(status==cudaSuccess)status=batch_inverse_norms(norm_inverses,norms,messages); if(status==cudaSuccess){lookup_group_deltas_batched_t<<>>(deltas+row_start*slots,dm,conjugates,norm_inverses,rows,num_lookups,group_size);status=cudaGetLastError();} } @@ -3784,8 +3788,8 @@ int lookup_lde_gpu_rows_partitioned_impl( if (status == cudaSuccess) { lookup_messages_t<<>>( reinterpret_cast(pending->conjugates), pending->norms, - pending->args, pending->arg_offsets, rows, pending->num_lookups, - pending->args_width, ExtOps::load(beta), + pending->multiplicities, pending->args, pending->arg_offsets, rows, + pending->num_lookups, pending->args_width, ExtOps::load(beta), ExtOps::load(gamma), ext_w); status = cudaGetLastError(); } diff --git a/src/batch.rs b/src/batch.rs index 8925b3d..f6e127c 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -71,6 +71,7 @@ use crate::{ensure, ensure_eq}; use crate::traits::{Algebra, Field, Transcript, TwoAdicField}; use bincode::error::{DecodeError, EncodeError}; use bincode::serde::{decode_from_slice, encode_to_vec}; +use p3_util::log2_strict_usize; use serde::{Deserialize, Serialize}; /// What a shard publishes after round one: everything about it that the @@ -330,12 +331,52 @@ impl System { &self, preamble: &BatchPreamble, ) -> Result<(), VerificationError>> { + ensure!( + !self.circuits.is_empty(), + VerificationError::InvalidSystem; + "system has no circuits" + ); + let num_preprocessed = self + .preprocessed_indices + .iter() + .map(|i| usize::from(i.is_some())) + .sum::(); + ensure_eq!( + self.preprocessed_commit.is_none(), + num_preprocessed == 0, + VerificationError::InvalidSystem; + commitment_present = self.preprocessed_commit.is_some(), + num_preprocessed, + "preprocessed commitment does not match configured circuits" + ); + if let Some(commit) = &self.preprocessed_commit { + let max_prep_height = self + .circuits + .iter() + .zip(&self.preprocessed_indices) + .filter_map(|(circuit, idx)| idx.map(|_| circuit.preprocessed_height)) + .max() + .unwrap_or(0); + ensure!( + max_prep_height > 0 + && max_prep_height.is_power_of_two() + && self.config.validate_commitment_cap( + commit, + log2_strict_usize(max_prep_height) + self.config.log_blowup(), + ), + VerificationError::InvalidSystem; + max_prep_height, + "preprocessed commitment cap root count mismatch" + ); + } ensure!( !preamble.headers.is_empty(), VerificationError::BatchShapeMismatch; "batch preamble has no shard headers" ); let max_log_degree = self.config.max_log_degree(); + let max_log_quotient_domain = self.config.max_log_quotient_domain(); + let log_blowup = self.config.log_blowup(); for (idx, header) in preamble.headers.iter().enumerate() { ensure!( header.active.len() == self.circuits.len(), @@ -345,25 +386,66 @@ impl System { got = header.active.len(), "batch preamble header activation bitmap length mismatch" ); - let active_count = header.active.iter().filter(|&&a| a).count(); + let active_indices: Vec = header + .active + .iter() + .enumerate() + .filter_map(|(ci, &is_active)| is_active.then_some(ci)) + .collect(); ensure!( - active_count > 0 && header.log_degrees.len() == active_count, + !active_indices.is_empty() && header.log_degrees.len() == active_indices.len(), VerificationError::BatchShapeMismatch; shard = idx, - active_count, + active_count = active_indices.len(), log_degrees_len = header.log_degrees.len(), "batch preamble header log_degrees count mismatch" ); - for &log_degree in &header.log_degrees { + for (&ci, &log_degree) in active_indices.iter().zip(&header.log_degrees) { + let circuit = &self.circuits[ci]; + if circuit.preprocessed_height != 0 { + ensure_eq!( + 1usize.checked_shl(u32::from(log_degree)), + Some(circuit.preprocessed_height), + VerificationError::BatchShapeMismatch; + shard = idx, + circuit = ci, + log_degree, + expected_height = circuit.preprocessed_height, + "batch preamble header trace height does not match preprocessed height" + ); + } + let quotient_degree = circuit.quotient_degree(); ensure!( - usize::from(log_degree) <= max_log_degree, + usize::from(log_degree) <= max_log_degree + && usize::from(log_degree) < usize::BITS as usize + && usize::from(log_degree) + log2_strict_usize(quotient_degree) + <= max_log_quotient_domain, VerificationError::BatchShapeMismatch; shard = idx, + circuit = ci, log_degree, + quotient_degree, max_log_degree, - "batch preamble header log_degree exceeds max_log_degree" + max_log_quotient_domain, + "batch preamble header trace or quotient domain exceeds supported size" ); } + let max_log_lde_height = header + .log_degrees + .iter() + .copied() + .map(usize::from) + .max() + .expect("active_indices is non-empty") + + log_blowup; + ensure!( + self.config + .validate_commitment_cap(&header.stage_1_trace, max_log_lde_height), + VerificationError::BatchShapeMismatch; + shard = idx, + max_log_lde_height, + "batch preamble header stage-1 commitment cap root count mismatch" + ); } Ok(()) } @@ -1035,5 +1117,312 @@ mod tests { assert!(system.verify_batch(&batch).is_err()); } + fn pack_le_u64s(words: [u64; 4]) -> [u8; 32] { + let mut out = [0u8; 32]; + for (i, word) in words.into_iter().enumerate() { + out[i * 8..(i + 1) * 8].copy_from_slice(&word.to_le_bytes()); + } + out + } + + fn single_circuit_quad_system( + cap_height: usize, + ) -> ( + System, + ProverKey, + ) { + use crate::expr::Expr; + use crate::system::CircuitInputs; + + let cfg = GoldilocksBlake3Config::new( + CommitmentParameters { + log_blowup: 1, + cap_height, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 16, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + ); + let a = Expr::main(0); + let b = Expr::main(1); + System::new( + cfg, + [CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![a.clone() * a - b], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }], + ) + } + + fn quad_trace(log_degree: usize) -> RowMajorMatrix { + let rows = 1usize << log_degree; + let mut vals = Vec::with_capacity(rows * 2); + for i in 0..rows { + let x = Val::from_usize(i + 1); + vals.push(x); + vals.push(x * x); + } + RowMajorMatrix::new(vals, 2) + } + + #[test] + fn rejects_verify_batch_shard_merkle_cap_forgery() { + use p3_symmetric::MerkleCap; + + let (system, key) = single_circuit_quad_system(0); + let shards = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ]; + let messages_a = vec![ + BatchMessage { + args: vec![Val::from_u64(7)], + multiplicity: Val::from_u64(1), + }, + BatchMessage { + args: vec![Val::from_u64(999)], + multiplicity: Val::from_u64(0), + }, + ]; + let batch_a = system.prove_batch(&key, shards, messages_a); + assert!( + system + .verify_batch_shard(&batch_a.preamble, 0, &batch_a.proofs[0]) + .is_ok() + ); + + let r1 = batch_a.preamble.headers[1].stage_1_trace.roots()[0]; + let r_fake = pack_le_u64s([1, 5, 0, 2]); + let mut preamble_b = batch_a.preamble.clone(); + preamble_b.headers[1].stage_1_trace = MerkleCap::new(vec![r1, r_fake]); + preamble_b.headers[1].log_degrees = vec![7]; + preamble_b.headers[1].claims = vec![vec![Val::from_u64(999)]]; + preamble_b.messages = vec![]; + + let (_, beta_a, gamma_a) = system.batch_challenger(&batch_a.preamble); + let (_, beta_b, gamma_b) = system.batch_challenger(&preamble_b); + assert_eq!((beta_a, gamma_a), (beta_b, gamma_b)); + + assert!(matches!( + system.verify_batch_shard(&preamble_b, 0, &batch_a.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + } + + #[test] + fn rejects_verify_batch_merkle_cap_preamble_forgery() { + use p3_symmetric::MerkleCap; + + let (system, key) = single_circuit_quad_system(0); + let shards = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace(5)], &system), + claims: vec![], + }, + ]; + let messages_a = vec![ + BatchMessage { + args: vec![Val::from_u64(5)], + multiplicity: Val::from_u64(0), + }, + BatchMessage { + args: vec![Val::from_u64(0)], + multiplicity: Val::from_u64(0), + }, + ]; + let batch_a = system.prove_batch(&key, shards, messages_a); + system.verify_batch(&batch_a).unwrap(); + + let r1 = batch_a.preamble.headers[1].stage_1_trace.roots()[0]; + let forged_cap = MerkleCap::new(vec![r1, pack_le_u64s([1, 5, 0, 2])]); + let mut batch_b = batch_a.clone(); + batch_b.preamble.headers[1].stage_1_trace = forged_cap.clone(); + batch_b.proofs[1].commitments.stage_1_trace = forged_cap; + batch_b.preamble.messages = vec![BatchMessage { + args: vec![], + multiplicity: Val::from_u64(0), + }]; + + let (_, beta_a, gamma_a) = system.batch_challenger(&batch_a.preamble); + let (_, beta_b, gamma_b) = system.batch_challenger(&batch_b.preamble); + assert_eq!((beta_a, gamma_a), (beta_b, gamma_b)); + + assert!(matches!( + system.verify_batch(&batch_b), + Err(VerificationError::BatchShapeMismatch) + )); + assert!(matches!( + system.verify_shape(&batch_b.proofs[1]), + Err(VerificationError::InvalidProofShape) + )); + } + + #[test] + fn rejects_merkle_cap_grinding_and_truncation() { + use p3_fri::verifier::FriError; + use p3_merkle_tree::MerkleTreeError; + use p3_symmetric::MerkleCap; + + let (system, key) = single_circuit_quad_system(0); + let proof = system.prove_multiple_claims( + &key, + &[], + SystemWitness::from_stage_1(vec![quad_trace(4)], &system), + ); + system.verify_multiple_claims(&[], &proof).unwrap(); + + let inflate = |cap: &MerkleCap| { + let mut roots = cap.roots().to_vec(); + roots.push([0xA5; 32]); + MerkleCap::new(roots) + }; + + let mut bad_s1 = proof.clone(); + bad_s1.commitments.stage_1_trace = inflate(&proof.commitments.stage_1_trace); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_s1), + Err(VerificationError::InvalidProofShape) + )); + + let mut bad_s2 = proof.clone(); + bad_s2.commitments.stage_2_trace = inflate(&proof.commitments.stage_2_trace); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_s2), + Err(VerificationError::InvalidProofShape) + )); + + let mut bad_q = proof.clone(); + bad_q.commitments.quotient_chunks = inflate(&proof.commitments.quotient_chunks); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_q), + Err(VerificationError::InvalidProofShape) + )); + + let mut bad_fri = proof.clone(); + bad_fri.opening_proof.commit_phase_commits[0] = + inflate(&proof.opening_proof.commit_phase_commits[0]); + assert!(matches!( + system.verify_multiple_claims(&[], &bad_fri), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + + let zero_cap: MerkleCap = decode_from_slice( + &encode_to_vec(Vec::<[u8; 32]>::new(), bincode::config::standard()).unwrap(), + bincode::config::standard(), + ) + .unwrap() + .0; + let r0 = proof.commitments.stage_1_trace.roots()[0]; + let three_cap: MerkleCap = decode_from_slice( + &encode_to_vec(vec![r0, [1u8; 32], [2u8; 32]], bincode::config::standard()).unwrap(), + bincode::config::standard(), + ) + .unwrap() + .0; + for weird_cap in [zero_cap, three_cap] { + let mut p1 = proof.clone(); + p1.commitments.stage_1_trace = weird_cap.clone(); + assert!(matches!( + system.verify_multiple_claims(&[], &p1), + Err(VerificationError::InvalidProofShape) + )); + let mut pf = proof.clone(); + pf.opening_proof.commit_phase_commits[0] = weird_cap; + assert!(matches!( + system.verify_multiple_claims(&[], &pf), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + } + + #[cfg(not(feature = "cuda"))] + { + let (sys1, key1) = single_circuit_quad_system(1); + let proof1 = sys1.prove_multiple_claims( + &key1, + &[], + SystemWitness::from_stage_1(vec![quad_trace(4)], &sys1), + ); + sys1.verify_multiple_claims(&[], &proof1).unwrap(); + assert_eq!(proof1.commitments.stage_1_trace.num_roots(), 2); + + let trunc_s1 = MerkleCap::new(vec![proof1.commitments.stage_1_trace.roots()[0]]); + let mut p_trunc = proof1.clone(); + p_trunc.commitments.stage_1_trace = trunc_s1; + assert!(matches!( + sys1.verify_multiple_claims(&[], &p_trunc), + Err(VerificationError::InvalidProofShape) + )); + + let fri_roots = proof1.opening_proof.commit_phase_commits[0] + .roots() + .to_vec(); + let mut p_fri_trunc = proof1.clone(); + p_fri_trunc.opening_proof.commit_phase_commits[0] = MerkleCap::new(vec![fri_roots[0]]); + assert!(matches!( + sys1.verify_multiple_claims(&[], &p_fri_trunc), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + + let mut p_fri_infl = proof1; + p_fri_infl.opening_proof.commit_phase_commits[0] = + MerkleCap::new(vec![fri_roots[0], fri_roots[1], [0x11; 32], [0x22; 32]]); + assert!(matches!( + sys1.verify_multiple_claims(&[], &p_fri_infl), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + } + } + + #[test] + fn rejects_invalid_non_target_shard_preamble_dimensions() { + let (system, key) = byte_system(config()); + let batch = system.prove_batch(&key, two_shards(&system), vec![]); + let _ = system + .verify_batch_shard(&batch.preamble, 0, &batch.proofs[0]) + .unwrap(); + + let mut bad_prep = batch.preamble.clone(); + bad_prep.headers[1].active[0] = true; + bad_prep.headers[1].log_degrees.insert(0, 4); + assert!(matches!( + system.verify_batch_shard(&bad_prep, 0, &batch.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + + let mut bad_deg = batch.preamble; + bad_deg.headers[1].log_degrees[0] = + u8::try_from(system.config.max_log_degree() + 1).unwrap(); + assert!(matches!( + system.verify_batch_shard(&bad_deg, 0, &batch.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + } + type ExtVal = ::Challenge; } diff --git a/src/config.rs b/src/config.rs index b07c6b5..84c3317 100644 --- a/src/config.rs +++ b/src/config.rs @@ -176,6 +176,17 @@ pub trait ProofConfig { /// evaluations. fn log_blowup(&self) -> usize; + /// Validate that `commit` has the exact expected structure (e.g. exact + /// Merkle cap root count) for a commitment whose tallest committed LDE has + /// height `2^max_log_lde_height`. + /// + /// Called by the verifier before observing any commitment into the + /// Fiat-Shamir transcript so variable-length caps cannot collide with + /// subsequent transcript fields or enable free challenge grinding. + fn validate_commitment_cap(&self, _commit: &Com, _max_log_lde_height: usize) -> bool { + true + } + /// Commit deterministic main-trace sources. fn commit_main( &self, diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index ee25bf8..506eb9d 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -10,6 +10,9 @@ use super::{ CudaLde, CudaMixedMerkleTree, mixed_lde_open_row, mixed_lde_open_row_at_height, mixed_lde_open_rows, mixed_lde_open_rows_at_height, }; +use crate::p3_adapter::cap::{ + CapValidatingMmcs, verify_merkle_cap_len, verify_merkle_cap_len_for_log_height, +}; use crate::p3_adapter::domain_blake3::{Blake3Domain, DomainBlake3}; use p3_symmetric::{CompressionFunctionFromHasher, SerializingHasher}; @@ -495,6 +498,7 @@ fn hybrid_open_rows>( #[derive(Clone, Debug)] pub struct CudaMmcs { cpu: CpuMmcs, + cap_height: usize, leaf_domain: Blake3Domain, device_id: i32, } @@ -506,7 +510,7 @@ impl CudaMmcs { let field_hash = SerializingHasher::new(DomainBlake3::new(Blake3Domain::Plain)); let compress = DomainCompressionFunction::new(DomainBlake3::new(Blake3Domain::Plain)); let cpu = CpuMmcs::new(field_hash, compress, cap_height); - Self::with_device_and_domain(cpu, Blake3Domain::Plain, device_id) + Self::with_device_and_domain(cpu, cap_height, Blake3Domain::Plain, device_id) } /// Creates a protocol `v6` domain-separated BLAKE3 CUDA MMCS separating @@ -517,7 +521,7 @@ impl CudaMmcs { let compress = DomainCompressionFunction::new(DomainBlake3::new(Blake3Domain::MerkleCompress)); let cpu = CpuMmcs::new(field_hash, compress, cap_height); - Self::with_device_and_domain(cpu, Blake3Domain::MerkleLeaf, device_id) + Self::with_device_and_domain(cpu, cap_height, Blake3Domain::MerkleLeaf, device_id) } /// A commitment scheme resident on the given CUDA device. Every kernel @@ -526,6 +530,7 @@ impl CudaMmcs { /// device of their own. pub(crate) fn with_device_and_domain( cpu: CpuMmcs, + cap_height: usize, leaf_domain: Blake3Domain, device_id: i32, ) -> Self { @@ -536,6 +541,7 @@ impl CudaMmcs { ); Self { cpu, + cap_height, leaf_domain, device_id, } @@ -543,7 +549,12 @@ impl CudaMmcs { #[cfg(test)] pub(crate) fn with_device(cpu: CpuMmcs, device_id: i32) -> Self { - Self::with_device_and_domain(cpu, Blake3Domain::Plain, device_id) + Self::with_device_and_domain(cpu, 0, Blake3Domain::Plain, device_id) + } + + #[inline] + pub const fn cap_height(&self) -> usize { + self.cap_height } #[inline] @@ -1197,6 +1208,37 @@ impl CudaCommitMmcs for CudaMmcs { Self::Commitment, Self::ProverData>, ) { + // Mirror `commit_cuda_resident`: height groups exceeding the 4096-column + // (32 KiB) device BLAKE3 leaf-hash limit must be hashed on the host. + let wide_heights = host_hashed_heights(ldes.iter().map(|lde| Dimensions { + width: lde.width(), + height: lde.height(), + })); + if !wide_heights.is_empty() { + let mut resident: Vec> = Vec::with_capacity(ldes.len()); + let mut host: Vec>> = Vec::with_capacity(ldes.len()); + for lde in ldes { + if wide_heights.contains(&lde.height()) { + host.push(Some(lde.to_row_major_matrix())); + resident.push(None); + } else { + host.push(None); + resident.push(Some(lde)); + } + } + let deferred: Vec>> = + (0..resident.len()).map(|_| None).collect(); + let deferred_dimensions = vec![None; resident.len()]; + let digests = hash_host_only_height_groups( + &host, + &resident.iter().map(Option::as_ref).collect::>(), + &deferred_dimensions, + &std::collections::BTreeSet::new(), + self.leaf_domain, + ); + let retained = (0..resident.len()).map(|_| None).collect(); + return self.commit_cuda_hybrid(resident, host, deferred, retained, digests); + } let matrix_count = ldes.len(); self.commit_cuda_hybrid( ldes.into_iter().map(Some).collect(), @@ -1490,6 +1532,7 @@ impl Mmcs for CudaMmcs { index: usize, batch_opening: BatchOpeningRef<'_, Goldilocks, Self>, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; self.cpu.verify_batch( commit, dimensions, @@ -1545,11 +1588,22 @@ impl Mmcs for CudaMmcs { opened_values: &[Vec], proof: &Self::MultiProof, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; self.cpu .verify_multi_batch(commit, dimensions, indices, opened_values, proof) } } +impl CapValidatingMmcs for CudaMmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) + } +} + #[cfg(test)] mod tests { use p3_commit::Mmcs; diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index 096e75b..7828514 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -48,6 +48,7 @@ use super::{ CudaFriWorkspace, CudaInterpolationTasks, CudaLde, CudaMixedMerkleTree, CudaReducedOpening, CudaReductionTasks, }; +use crate::p3_adapter::cap::{CapValidatingMmcs, validate_fri_commitment_caps}; use crate::p3_adapter::fri_batching::{ FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, }; @@ -686,8 +687,8 @@ impl Pcs + CudaPcsDft + Sync, - InputMmcs: Mmcs + CudaCommitMmcs, - FriMmcs: Mmcs + CudaFriMmcs, + InputMmcs: CapValidatingMmcs + CudaCommitMmcs, + FriMmcs: CapValidatingMmcs + CudaFriMmcs, Challenge: ExtensionField, Challenger: FieldChallenger + CanObserve + GrindingChallenger, @@ -2392,6 +2393,12 @@ where proof: &Self::Proof, challenger: &mut Challenger, ) -> Result<(), Self::Error> { + validate_fri_commitment_caps( + &self.fri, + proof, + &commitments_with_opening_points, + &self.mmcs, + )?; // Write all evaluations to challenger. // Need to ensure to do this in the same order as the prover. for (_, round) in &commitments_with_opening_points { diff --git a/src/lookup.rs b/src/lookup.rs index 8bbd488..fdbf202 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -1409,13 +1409,17 @@ impl LookupValues { let messages = (message_start..message_end) .into_par_iter() .map(|index| { - let row = index / self.num_lookups; - let lookup = index % self.num_lookups; - lookup_challenge - + fingerprint( - fingerprint_challenge, - self.args_at(row, lookup).iter().copied(), - ) + if self.multiplicities[index].is_zero() { + >::ONE + } else { + let row = index / self.num_lookups; + let lookup = index % self.num_lookups; + lookup_challenge + + fingerprint( + fingerprint_challenge, + self.args_at(row, lookup).iter().copied(), + ) + } }) .collect::>(); let inverses = crate::traits::batch_inverse(&messages); diff --git a/src/p3_adapter/cap.rs b/src/p3_adapter/cap.rs new file mode 100644 index 0000000..37a1066 --- /dev/null +++ b/src/p3_adapter/cap.rs @@ -0,0 +1,219 @@ +//! Exact `MerkleCap` root-count validation helpers shared by CPU and CUDA +//! MMCS/PCS verifiers. +//! +//! Plonky3's `MerkleCap` derives `Deserialize` directly on `Vec`, +//! `SerializingChallenger` observes `cap.roots()` raw without a length prefix, +//! and upstream `MerkleTreeMmcs::{verify_batch, verify_multi_batch}` only check +//! `cap_idx < commit.num_roots()`. Without enforcing the exact expected root +//! count (`1 << cap_height.min(log2_ceil_usize(max_height))`) both in MMCS +//! verification and before Fiat-Shamir observation, a prover can inject extra +//! cap roots to grind challenges for free or collide adjacent transcript fields. + +use p3_commit::{ExtensionMmcs, Mmcs}; +use p3_field::{ExtensionField, Field, TwoAdicField, coset::TwoAdicMultiplicativeCoset}; +use p3_fri::verifier::FriError; +use p3_fri::{CommitmentWithOpeningPoints, FriParameters, FriProof}; +use p3_matrix::Dimensions; +use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; +use p3_symmetric::MerkleCap; +use p3_util::{log2_ceil_usize, log2_strict_usize}; + +/// Exact Merkle cap root count for a binary Merkle tree whose tallest committed +/// matrix has `log2_ceil(max_height) == log_max_height`. +#[inline] +pub(crate) fn expected_merkle_cap_roots(cap_height: usize, log_max_height: usize) -> Option { + let effective_cap_height = cap_height.min(log_max_height); + let shift = u32::try_from(effective_cap_height).ok()?; + 1usize.checked_shl(shift) +} + +/// Validates that `commit` carries the exact expected root count for a binary +/// Merkle tree with `log2_ceil(max_height) == log_max_height`. +#[inline] +pub(crate) fn verify_merkle_cap_len_for_log_height( + cap_height: usize, + commit: &MerkleCap, + log_max_height: usize, +) -> Result<(), MerkleTreeError> { + let expected_roots = expected_merkle_cap_roots(cap_height, log_max_height) + .ok_or(MerkleTreeError::CapMismatch)?; + if commit.num_roots() != expected_roots { + return Err(MerkleTreeError::CapMismatch); + } + Ok(()) +} + +/// Validates that `commit` carries the exact expected root count for the +/// tallest matrix in `dimensions`. +#[inline] +pub(crate) fn verify_merkle_cap_len( + cap_height: usize, + commit: &MerkleCap, + dimensions: &[Dimensions], +) -> Result<(), MerkleTreeError> { + let max_height = dimensions + .iter() + .map(|dims| dims.height) + .max() + .ok_or(MerkleTreeError::EmptyBatch)?; + if max_height == 0 { + return Err(MerkleTreeError::EmptyBatch); + } + verify_merkle_cap_len_for_log_height(cap_height, commit, log2_ceil_usize(max_height)) +} + +/// MMCS that can validate a commitment's exact Merkle cap root count against a +/// verifier-known tree height before observing the commitment into a transcript. +pub trait CapValidatingMmcs: Mmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error>; +} + +impl CapValidatingMmcs for ExtensionMmcs +where + F: Field, + EF: ExtensionField, + InnerMmcs: + CapValidatingMmcs, Error = MerkleTreeError>, +{ + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + // Delegate through `verify_multi_batch` with an empty query set so + // `InnerMmcs` enforces its own configured `cap_height` without needing + // access to `ExtensionMmcs`'s private `inner` field. + let height = u32::try_from(log_max_height) + .ok() + .and_then(|shift| 1usize.checked_shl(shift)) + .ok_or(MerkleTreeError::CapMismatch)?; + let empty_rows: &[Vec<&[EF]>] = &[]; + let empty_proof = PrunedMerklePaths { + sibling_hashes: Vec::new(), + }; + self.verify_multi_batch( + commit, + &[Dimensions { width: 1, height }], + &[], + empty_rows, + &empty_proof, + ) + } +} + +/// Validates the exact Merkle cap root count of every input commitment and +/// every FRI commit-phase commitment before any commitment is observed into the +/// Fiat-Shamir transcript. +pub(crate) fn validate_fri_commitment_caps< + Val, + Challenge, + InputMmcs, + FriMmcs, + Witness, + InputProof, +>( + params: &FriParameters, + proof: &FriProof, + commitments_with_opening_points: &[CommitmentWithOpeningPoints< + Challenge, + InputMmcs::Commitment, + TwoAdicMultiplicativeCoset, + >], + input_mmcs: &InputMmcs, +) -> Result<(), FriError> +where + Val: TwoAdicField, + Challenge: ExtensionField, + InputMmcs: CapValidatingMmcs, + FriMmcs: CapValidatingMmcs, +{ + if params.num_queries == 0 { + return Err(FriError::ZeroQueries); + } + + for (comm, mats) in commitments_with_opening_points { + if let Some(max_log_height) = mats + .iter() + .map(|(domain, _)| log2_strict_usize(domain.size()) + params.log_blowup) + .max() + { + input_mmcs + .validate_commitment_cap_for_log_height(comm, max_log_height) + .map_err(FriError::InputError)?; + } + } + + let expected_rounds = proof.commit_phase_commits.len(); + if proof.commit_phase_openings.len() != expected_rounds { + return Err(FriError::CommitPhaseOpeningsCountMismatch { + expected: expected_rounds, + got: proof.commit_phase_openings.len(), + }); + } + + let mut total_log_reduction = 0usize; + let mut log_arities = Vec::with_capacity(expected_rounds); + for (round, opening) in proof.commit_phase_openings.iter().enumerate() { + let log_arity = usize::from(opening.log_arity); + if !(1..=params.max_log_arity).contains(&log_arity) { + return Err(FriError::InvalidLogArity { + round, + log_arity, + max: params.max_log_arity, + }); + } + total_log_reduction = total_log_reduction.checked_add(log_arity).ok_or( + FriError::GlobalMaxHeightTooLarge { + log_global_max_height: usize::MAX, + two_adicity: Val::TWO_ADICITY, + }, + )?; + log_arities.push(log_arity); + } + + let log_global_max_height = total_log_reduction + .checked_add(params.log_blowup) + .and_then(|v| v.checked_add(params.log_final_poly_len)) + .ok_or(FriError::GlobalMaxHeightTooLarge { + log_global_max_height: usize::MAX, + two_adicity: Val::TWO_ADICITY, + })?; + if log_global_max_height > Val::TWO_ADICITY { + return Err(FriError::GlobalMaxHeightTooLarge { + log_global_max_height, + two_adicity: Val::TWO_ADICITY, + }); + } + + let expected_log_global_max_height = commitments_with_opening_points + .iter() + .flat_map(|(_, mats)| { + mats.iter() + .map(|(domain, _)| log2_strict_usize(domain.size()) + params.log_blowup) + }) + .max(); + if let Some(expected) = expected_log_global_max_height + && log_global_max_height != expected + { + return Err(FriError::GlobalMaxHeightMismatch { + expected, + got: log_global_max_height, + }); + } + + let mut log_current_height = log_global_max_height; + for (comm, &log_arity) in proof.commit_phase_commits.iter().zip(&log_arities) { + let log_folded_height = log_current_height - log_arity; + params + .mmcs + .validate_commitment_cap_for_log_height(comm, log_folded_height) + .map_err(FriError::CommitPhaseMmcsError)?; + log_current_height = log_folded_height; + } + + Ok(()) +} diff --git a/src/p3_adapter/fri_batching.rs b/src/p3_adapter/fri_batching.rs index a179663..197bc83 100644 --- a/src/p3_adapter/fri_batching.rs +++ b/src/p3_adapter/fri_batching.rs @@ -28,6 +28,7 @@ use std::collections::BTreeMap; use std::iter; +use super::cap::{CapValidatingMmcs, validate_fri_commitment_caps}; use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; use p3_commit::Mmcs; use p3_field::coset::TwoAdicMultiplicativeCoset; @@ -203,8 +204,8 @@ pub fn verify_fri_with_batching, - InputMmcs: Mmcs, - FriMmcs: Mmcs, + InputMmcs: CapValidatingMmcs, + FriMmcs: CapValidatingMmcs, Challenger: FieldChallenger + GrindingChallenger + CanObserve, Folding: FriFoldingStrategy< Val, @@ -213,6 +214,7 @@ where InputProof = Vec>, >, { + validate_fri_commitment_caps(params, proof, commitments_with_opening_points, input_mmcs)?; match batching { FriBatching::Horner => verifier::verify_fri( folding, @@ -259,8 +261,8 @@ pub(crate) fn verify_fri_with_batching_inner< where Val: TwoAdicField, Challenge: ExtensionField, - InputMmcs: Mmcs, - FriMmcs: Mmcs, + InputMmcs: CapValidatingMmcs, + FriMmcs: CapValidatingMmcs, Challenger: FieldChallenger + GrindingChallenger + CanObserve, Folding: FriFoldingStrategy< Val, @@ -269,9 +271,7 @@ where InputProof = Vec>, >, { - if params.num_queries == 0 { - return Err(FriError::ZeroQueries); - } + validate_fri_commitment_caps(params, proof, commitments_with_opening_points, input_mmcs)?; // Derive max_width and max_openings_per_height from the authenticated // opening structure before sampling batching challenges. diff --git a/src/p3_adapter/mod.rs b/src/p3_adapter/mod.rs index c12a12a..3eeff1c 100644 --- a/src/p3_adapter/mod.rs +++ b/src/p3_adapter/mod.rs @@ -4,6 +4,7 @@ mod air; #[cfg(not(feature = "cuda"))] pub(crate) mod blake3_simd; +pub mod cap; pub mod challenger; pub mod domain; pub mod domain_blake3; diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs index b3cf06c..5cfc7fb 100644 --- a/src/p3_adapter/spill.rs +++ b/src/p3_adapter/spill.rs @@ -51,6 +51,10 @@ use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_slice_index_bits}; use tracing::debug_span; use super::blake3_simd; +use super::cap::{ + CapValidatingMmcs, validate_fri_commitment_caps, verify_merkle_cap_len, + verify_merkle_cap_len_for_log_height, +}; use super::domain_blake3::{Blake3Domain, DomainBlake3}; use super::fri_batching::{ FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, @@ -1352,6 +1356,7 @@ impl Mmcs for SpillableMmcs { index: usize, batch_opening: BatchOpeningRef<'_, Val, Self>, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; let (opened_values, opening_proof) = batch_opening.unpack(); self.cpu.verify_batch( commit, @@ -1384,11 +1389,22 @@ impl Mmcs for SpillableMmcs { opened_values: &[Vec], proof: &Self::MultiProof, ) -> Result<(), Self::Error> { + verify_merkle_cap_len(self.cap_height(), commit, dimensions)?; self.cpu .verify_multi_batch(commit, dimensions, indices, opened_values, proof) } } +impl CapValidatingMmcs for SpillableMmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) + } +} + /// CPU two-adic FRI PCS supporting optional disk-backed LDE spilling with /// streaming commitment, quotient-domain slicing, and FRI opening. /// @@ -1586,7 +1602,7 @@ impl Pcs for SpillableTwoAdicFriPc where EF: ExtensionField + ExtensionOf, Dft: TwoAdicSubgroupDft, - FriMmcs: Mmcs, + FriMmcs: CapValidatingMmcs, Challenger: FieldChallenger + CanObserve + GrindingChallenger, { @@ -1887,6 +1903,9 @@ where for (mat_idx, (points_for_mat, openings_for_mat)) in points.iter().zip(openings_for_round).enumerate() { + if points_for_mat.is_empty() || openings_for_mat.is_empty() { + continue; + } let dim = dims[mat_idx]; let log_height = log2_strict_usize(dim.height); let _guard = debug_span!("reduce matrix quotient", dims = %dim).entered(); @@ -1926,10 +1945,6 @@ where point_params.push((opening_weight, reduced_val, inv_denom)); } - if point_params.is_empty() { - continue; - } - match &data.0 { SpillableMmcsDataInner::InMemory { tree, .. } => { let mat = &tree.leaves[mat_idx]; @@ -2007,6 +2022,12 @@ where proof: &Self::Proof, challenger: &mut Challenger, ) -> Result<(), Self::Error> { + validate_fri_commitment_caps( + &self.fri, + proof, + &commitments_with_opening_points, + &self.mmcs, + )?; for (_, round) in &commitments_with_opening_points { for (_, mat) in round { for (_, point) in mat { @@ -2797,4 +2818,92 @@ mod tests { } } } + + #[test] + fn verify_batch_and_multi_batch_reject_wrong_cap_root_count() { + use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; + + let mut rng = SmallRng::seed_from_u64(1337); + let mat = RowMajorMatrix::new( + (0..32 * 4).map(|_| Goldilocks::new(rng.random())).collect(), + 4, + ); + let dims = [Dimensions { + width: 4, + height: 32, + }]; + + for v6 in [false, true] { + for cap_height in [0usize, 1] { + let (_, mmcs) = make_mmcs(cap_height, v6); + let (commit, data) = mmcs.commit(vec![mat.clone()]); + let single = mmcs.open_batch(7, &data); + let (multi_vals, multi_proof) = mmcs.open_multi_batch(&[3, 7, 19], &data); + + mmcs.verify_batch( + &commit, + &dims, + 7, + BatchOpeningRef::new(&single.opened_values, &single.opening_proof), + ) + .unwrap(); + mmcs.verify_multi_batch(&commit, &dims, &[3, 7, 19], &multi_vals, &multi_proof) + .unwrap(); + + let mut inflated_roots = commit.roots().to_vec(); + inflated_roots.extend_from_slice(commit.roots()); + let inflated = MerkleCap::new(inflated_roots); + assert!(matches!( + mmcs.verify_batch( + &inflated, + &dims, + 7, + BatchOpeningRef::new(&single.opened_values, &single.opening_proof), + ), + Err(MerkleTreeError::CapMismatch) + )); + assert!(matches!( + mmcs.verify_multi_batch( + &inflated, + &dims, + &[3, 7, 19], + &multi_vals, + &multi_proof, + ), + Err(MerkleTreeError::CapMismatch) + )); + let empty_rows: &[Vec<&[Val]>] = &[]; + let empty_proof = PrunedMerklePaths { + sibling_hashes: Vec::new(), + }; + assert!(matches!( + mmcs.verify_multi_batch(&inflated, &dims, &[], empty_rows, &empty_proof), + Err(MerkleTreeError::CapMismatch) + )); + + if cap_height > 0 { + let truncated = MerkleCap::new(vec![commit.roots()[0]]); + assert!(matches!( + mmcs.verify_batch( + &truncated, + &dims, + 7, + BatchOpeningRef::new(&single.opened_values, &single.opening_proof), + ), + Err(MerkleTreeError::CapMismatch) + )); + assert!(matches!( + mmcs.verify_multi_batch( + &truncated, + &dims, + &[3, 7, 19], + &multi_vals, + &multi_proof, + ), + Err(MerkleTreeError::CapMismatch) + )); + } + } + } + } } diff --git a/src/test_circuits/baby_bear_config.rs b/src/test_circuits/baby_bear_config.rs index d5ce290..468c840 100644 --- a/src/test_circuits/baby_bear_config.rs +++ b/src/test_circuits/baby_bear_config.rs @@ -221,6 +221,17 @@ impl ProofConfig for BabyBearPoseidon2Config { fn log_blowup(&self) -> usize { self.log_blowup } + + fn validate_commitment_cap( + &self, + commit: &crate::config::Com, + max_log_lde_height: usize, + ) -> bool { + crate::p3_adapter::cap::expected_merkle_cap_roots( + self.pcs.commitment_parameters().cap_height, + max_log_lde_height, + ) == Some(commit.num_roots()) + } } /// A minimal AIR: enforces `a * b == c` per row, with a self-canceling diff --git a/src/types.rs b/src/types.rs index 1c013f2..5210688 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1079,6 +1079,15 @@ impl ProofConfig for GoldilocksBlake3Config { self.log_blowup } + fn validate_commitment_cap( + &self, + commit: &crate::config::Com, + max_log_lde_height: usize, + ) -> bool { + crate::p3_adapter::cap::expected_merkle_cap_roots(self.cap_height, max_log_lde_height) + == Some(commit.num_roots()) + } + #[cfg(feature = "cuda")] fn commit_main( &self, @@ -1936,6 +1945,15 @@ where self.log_blowup } + fn validate_commitment_cap( + &self, + commit: &crate::config::Com, + max_log_lde_height: usize, + ) -> bool { + crate::p3_adapter::cap::expected_merkle_cap_roots(self.cap_height, max_log_lde_height) + == Some(commit.num_roots()) + } + #[cfg(not(feature = "cuda"))] fn commit_preprocessed( &self, diff --git a/src/verifier.rs b/src/verifier.rs index 029f420..4adbc35 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -668,17 +668,40 @@ impl System { num_preprocessed, "preprocessed commitment does not match configured circuits" ); + if let Some(commit) = &self.preprocessed_commit { + let max_prep_height = self + .circuits + .iter() + .zip(&self.preprocessed_indices) + .filter_map(|(circuit, idx)| idx.map(|_| circuit.preprocessed_height)) + .max() + .unwrap_or(0); + crate::ensure!( + max_prep_height > 0 + && max_prep_height.is_power_of_two() + && self.config.validate_commitment_cap( + commit, + log2_strict_usize(max_prep_height) + self.config.log_blowup(), + ), + VerificationError::InvalidSystem; + max_prep_height, + "preprocessed commitment cap root count mismatch" + ); + } // Stage 0 round: the preprocessed commitment is built once over ALL // preprocessed traces at system construction, so its round carries one // entry per preprocessed matrix. Inactive matrices need one full-width // opening unless the PCS authenticates their boundaries independently. - ensure_eq!( - preprocessed_opened_values - .as_ref() - .map_or(0, |values| values.len()), - num_preprocessed, + // Reject `Some(vec![])` when `num_preprocessed == 0` so there is a + // single canonical proof encoding. + crate::ensure!( + match preprocessed_opened_values { + None => num_preprocessed == 0, + Some(values) => num_preprocessed > 0 && values.len() == num_preprocessed, + }, VerificationError::InvalidProofShape; - actual = preprocessed_opened_values.as_ref().map_or(0, |values| values.len()), + present = preprocessed_opened_values.is_some(), + actual = preprocessed_opened_values.as_ref().map_or(0, Vec::len), expected = num_preprocessed, "unexpected number of preprocessed matrices" ); @@ -857,6 +880,36 @@ impl System { ); quotient_degrees.push(quotient_degree); } + // Validate exact Merkle cap root counts before any commitment enters + // the Fiat-Shamir transcript. + let max_log_lde_height = log_degrees + .iter() + .copied() + .map(usize::from) + .max() + .expect("num_active > 0") + + self.config.log_blowup(); + crate::ensure!( + self.config + .validate_commitment_cap(&proof.commitments.stage_1_trace, max_log_lde_height), + VerificationError::InvalidProofShape; + max_log_lde_height, + "stage-1 commitment cap root count mismatch" + ); + crate::ensure!( + self.config + .validate_commitment_cap(&proof.commitments.stage_2_trace, max_log_lde_height), + VerificationError::InvalidProofShape; + max_log_lde_height, + "stage-2 commitment cap root count mismatch" + ); + crate::ensure!( + self.config + .validate_commitment_cap(&proof.commitments.quotient_chunks, max_log_lde_height), + VerificationError::InvalidProofShape; + max_log_lde_height, + "quotient commitment cap root count mismatch" + ); // One wide quotient matrix per active circuit, holding all its // coefficient slices, opened at the single point ζ. ensure_eq!( diff --git a/tests/fp3_v6.rs b/tests/fp3_v6.rs index c83ac5f..ffd1a80 100644 --- a/tests/fp3_v6.rs +++ b/tests/fp3_v6.rs @@ -10,6 +10,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Instant; use multi_stark::batch::{BatchMessage, BatchProof, Retention, ShardInput}; +use multi_stark::config::ProofConfig; use multi_stark::expr::{Expr, ExtExpr, RowOffset}; use multi_stark::lookup::Lookup; use multi_stark::p3_adapter::fri_batching::FriBatching; @@ -23,6 +24,7 @@ use multi_stark::types::{ }; use multi_stark::witness::{PreparedWitness, TraceSource}; use p3_field::{BasedVectorSpace, PrimeCharacteristicRing, PrimeField64}; +use p3_matrix::Matrix; use p3_matrix::dense::RowMajorMatrix; #[cfg(not(feature = "cuda"))] @@ -1171,3 +1173,355 @@ fn bench_fp2_vs_fp3_cpu() { } } } + +fn pack_le_u64s(words: [u64; 4]) -> [u8; 32] { + let mut out = [0u8; 32]; + for (i, word) in words.into_iter().enumerate() { + out[i * 8..(i + 1) * 8].copy_from_slice(&word.to_le_bytes()); + } + out +} + +fn quad_v6_system( + cap_height: usize, +) -> ( + System, + multi_stark::system::ProverKey, +) { + let cfg = GoldilocksBlake3V6Config::new_with_batching( + CommitmentParameters { + log_blowup: 2, + cap_height, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 16, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + FriBatching::Tensor, + ); + let a = Expr::main(0); + let b = Expr::main(1); + System::new( + cfg, + [CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![a.clone() * a - b], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }], + ) +} + +fn quad_trace_v6(log_degree: usize) -> RowMajorMatrix { + let rows = 1usize << log_degree; + let mut vals = Vec::with_capacity(rows * 2); + for i in 0..rows { + let x = Val::from_usize(i + 1); + vals.push(x); + vals.push(x * x); + } + RowMajorMatrix::new(vals, 2) +} + +#[test] +fn v6_fp3_rejects_merkle_cap_forgery_and_grinding() { + use multi_stark::verifier::VerificationError; + use p3_fri::verifier::FriError; + use p3_merkle_tree::MerkleTreeError; + use p3_symmetric::MerkleCap; + + // #240 #1A: verify_batch_shard forgery via 2-root non-target MerkleCap. + let (system, key) = quad_v6_system(0); + let shards = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace_v6(5)], &system), + claims: vec![], + }, + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace_v6(5)], &system), + claims: vec![], + }, + ]; + let messages_a = vec![ + BatchMessage { + args: vec![Val::from_u64(7)], + multiplicity: Val::from_u64(1), + }, + BatchMessage { + args: vec![Val::from_u64(999)], + multiplicity: Val::from_u64(0), + }, + ]; + let batch_a = system.prove_batch(&key, shards, messages_a); + let _ = system + .verify_batch_shard(&batch_a.preamble, 0, &batch_a.proofs[0]) + .unwrap(); + + let r1 = batch_a.preamble.headers[1].stage_1_trace.roots()[0]; + let mut preamble_b = batch_a.preamble.clone(); + preamble_b.headers[1].stage_1_trace = MerkleCap::new(vec![r1, pack_le_u64s([1, 5, 0, 2])]); + preamble_b.headers[1].log_degrees = vec![7]; + preamble_b.headers[1].claims = vec![vec![Val::from_u64(999)]]; + preamble_b.messages = vec![]; + + let (_, beta_a, gamma_a) = system.batch_challenger(&batch_a.preamble); + let (_, beta_b, gamma_b) = system.batch_challenger(&preamble_b); + assert_eq!((beta_a, gamma_a), (beta_b, gamma_b)); + assert!(matches!( + system.verify_batch_shard(&preamble_b, 0, &batch_a.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + + // #240 #1B: full verify_batch preamble/message forgery. + let shards_b = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace_v6(5)], &system), + claims: vec![], + }, + ShardInput { + witness: SystemWitness::from_stage_1(vec![quad_trace_v6(5)], &system), + claims: vec![], + }, + ]; + let messages_b = vec![ + BatchMessage { + args: vec![Val::from_u64(5)], + multiplicity: Val::from_u64(0), + }, + BatchMessage { + args: vec![Val::from_u64(0)], + multiplicity: Val::from_u64(0), + }, + ]; + let batch_full_a = system.prove_batch(&key, shards_b, messages_b); + system.verify_batch(&batch_full_a).unwrap(); + + let r1_full = batch_full_a.preamble.headers[1].stage_1_trace.roots()[0]; + let forged_cap = MerkleCap::new(vec![r1_full, pack_le_u64s([1, 5, 0, 2])]); + let mut batch_full_b = batch_full_a.clone(); + batch_full_b.preamble.headers[1].stage_1_trace = forged_cap.clone(); + batch_full_b.proofs[1].commitments.stage_1_trace = forged_cap; + batch_full_b.preamble.messages = vec![BatchMessage { + args: vec![], + multiplicity: Val::from_u64(0), + }]; + let (_, ba, ga) = system.batch_challenger(&batch_full_a.preamble); + let (_, bb, gb) = system.batch_challenger(&batch_full_b.preamble); + assert_eq!((ba, ga), (bb, gb)); + assert!(matches!( + system.verify_batch(&batch_full_b), + Err(VerificationError::BatchShapeMismatch) + )); + + // #240 #1C: single-proof extra/truncated cap roots on stage-1, stage-2, quotient, and FRI. + let proof = system.prove_multiple_claims( + &key, + &[], + SystemWitness::from_stage_1(vec![quad_trace_v6(4)], &system), + ); + system.verify_multiple_claims(&[], &proof).unwrap(); + + let inflate = |cap: &MerkleCap| { + let mut roots = cap.roots().to_vec(); + roots.push([0x5A; 32]); + MerkleCap::new(roots) + }; + let mut p_s1 = proof.clone(); + p_s1.commitments.stage_1_trace = inflate(&proof.commitments.stage_1_trace); + assert!(matches!( + system.verify_multiple_claims(&[], &p_s1), + Err(VerificationError::InvalidProofShape) + )); + + let mut p_s2 = proof.clone(); + p_s2.commitments.stage_2_trace = inflate(&proof.commitments.stage_2_trace); + assert!(matches!( + system.verify_multiple_claims(&[], &p_s2), + Err(VerificationError::InvalidProofShape) + )); + + let mut p_q = proof.clone(); + p_q.commitments.quotient_chunks = inflate(&proof.commitments.quotient_chunks); + assert!(matches!( + system.verify_multiple_claims(&[], &p_q), + Err(VerificationError::InvalidProofShape) + )); + + let mut p_fri = proof; + p_fri.opening_proof.commit_phase_commits[0] = + inflate(&p_fri.opening_proof.commit_phase_commits[0]); + assert!(matches!( + system.verify_multiple_claims(&[], &p_fri), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + + #[cfg(not(feature = "cuda"))] + { + let (sys1, key1) = quad_v6_system(1); + let proof1 = sys1.prove_multiple_claims( + &key1, + &[], + SystemWitness::from_stage_1(vec![quad_trace_v6(4)], &sys1), + ); + sys1.verify_multiple_claims(&[], &proof1).unwrap(); + let fri_roots = proof1.opening_proof.commit_phase_commits[0] + .roots() + .to_vec(); + let mut trunc = proof1; + trunc.opening_proof.commit_phase_commits[0] = MerkleCap::new(vec![fri_roots[0]]); + assert!(matches!( + sys1.verify_multiple_claims(&[], &trunc), + Err(VerificationError::InvalidOpeningArgument( + FriError::CommitPhaseMmcsError(MerkleTreeError::CapMismatch) + )) + )); + } +} + +#[test] +fn v6_fp3_rejects_preprocessed_malleability_and_bad_preamble_dimensions() { + use multi_stark::verifier::VerificationError; + + // M24(b): num_preprocessed == 0 must reject `Some(vec![])` to prevent proof malleability. + let (system, key) = quad_v6_system(0); + let proof = system.prove_multiple_claims( + &key, + &[], + SystemWitness::from_stage_1(vec![quad_trace_v6(4)], &system), + ); + assert!(proof.preprocessed_opened_values.is_none()); + system.verify_multiple_claims(&[], &proof).unwrap(); + + let mut malleable = proof; + malleable.preprocessed_opened_values = Some(vec![]); + assert!(matches!( + system.verify_multiple_claims(&[], &malleable), + Err(VerificationError::InvalidProofShape) + )); + let encoded = malleable.to_bytes().unwrap(); + let decoded = Proof::::from_bytes(&encoded).unwrap(); + assert!(matches!( + system.verify_multiple_claims(&[], &decoded), + Err(VerificationError::InvalidProofShape) + )); + + // M24(c): verify_preamble_headers must enforce preprocessed_height and + // max_log_quotient_domain for non-target shards in verify_batch_shard. + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 16, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let inputs = u32_add_system_inputs(4); + let (sys_prep, key_prep) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri, FriBatching::Tensor), + inputs, + ); + let (traces, claims) = u32_add_witness(32); + let byte_table = traces[0].clone(); + let add_half = |start: usize, end: usize| { + RowMajorMatrix::new(traces[1].values[start * 14..end * 14].to_vec(), 14) + }; + let shards = vec![ + ShardInput { + witness: SystemWitness::from_stage_1(vec![byte_table, add_half(0, 16)], &sys_prep), + claims: claims.clone(), + }, + ShardInput { + witness: SystemWitness::from_stage_1( + vec![RowMajorMatrix::new(vec![], 1), add_half(16, 32)], + &sys_prep, + ), + claims: vec![], + }, + ]; + let batch = sys_prep.prove_batch(&key_prep, shards, vec![]); + let _ = sys_prep + .verify_batch_shard(&batch.preamble, 0, &batch.proofs[0]) + .unwrap(); + + // Non-target shard 1 claims wrong preprocessed height for circuit 0 (256-row byte table). + let mut bad_prep = batch.preamble.clone(); + bad_prep.headers[1].active[0] = true; + bad_prep.headers[1].log_degrees.insert(0, 4); + assert!(matches!( + sys_prep.verify_batch_shard(&bad_prep, 0, &batch.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); + + // Non-target shard 1 satisfies `log_degree <= max_log_degree` yet violates + // `log_degree + log2(quotient_degree) <= max_log_quotient_domain` (u32_add has + // lookup_group_size = 4 => quotient_degree >= 2). + assert!(sys_prep.circuits[1].quotient_degree() >= 2); + let mut bad_quot = batch.preamble; + bad_quot.headers[1].log_degrees[0] = + u8::try_from(sys_prep.config.max_log_quotient_domain()).unwrap(); + assert!(usize::from(bad_quot.headers[1].log_degrees[0]) <= sys_prep.config.max_log_degree()); + assert!(matches!( + sys_prep.verify_batch_shard(&bad_quot, 0, &batch.proofs[0]), + Err(VerificationError::BatchShapeMismatch) + )); +} + +/// L9(d): Exercise LDE heights strictly above 1024 (`512 << 2 = 2048 > 1024`) +/// so CUDA resident/streamed FRI `_ext3` kernels are covered on GPU as well as +/// CPU `v6` `F_p^3` (both `Tensor` and `Horner` batching). +#[test] +fn v6_fp3_large_lde_above_1024_rows_roundtrip() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 1, + max_log_arity: 2, + num_queries: 24, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let inputs = u32_add_system_inputs(4); + let (traces, claims) = u32_add_witness(512); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + assert_eq!(traces[1].height(), 512); + assert!(traces[1].height() << comm.log_blowup > 1024); + + for batching in [FriBatching::Tensor, FriBatching::Horner] { + let (system, key) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri, batching), + inputs.clone(), + ); + let proof = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &system), + ); + system.verify_multiple_claims(&claim_refs, &proof).unwrap(); + + let bytes = proof.to_bytes().unwrap(); + let decoded = Proof::::from_bytes(&bytes).unwrap(); + system + .verify_multiple_claims(&claim_refs, &decoded) + .unwrap(); + + let mut tampered = decoded; + tampered.stage_1_opened_values[1][0][0] += ExtVal3::ONE; + assert!( + system + .verify_multiple_claims(&claim_refs, &tampered) + .is_err() + ); + } +} From 98a0860384ac1d3e6532372ef9bd5073c064c9ea Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sun, 22 Nov 2026 17:57:52 -0500 Subject: [PATCH 24/28] feat(v6-zk): implement 128-bit hiding PCS, BLAKE3-CTR salting, and CUDA support Implement Protocol v6-zk (post-quantum transparent 128-bit statistical/ROM zero-knowledge over Goldilocks F_{p^3} = F_p[X]/(X^3 - X - 1)) cleanly alongside zero-overhead non-ZK v5/v6 using only stock pinned Plonky3 (3152b14a): - Domain separation: distinct BLAKE3 derive_key contexts for v6-zk (ZkMerkleLeaf, ZkMerkleCompress, ZkTranscriptSingle, ZkTranscriptBatch, ZkVerifyingKey) with pinned CUDA constant-memory key words. - 2x interleaved odd-coset hiding PCS (ePrint 2024/1037): odd-coset CSPRNG row blinding on witnesses, deterministic public preprocessed 2N*B LDE with public preprocessed salt seed, and exact modulo-folding re-evaluation. - Zero-storage BLAKE3-CTR leaf salting: single 256-bit OS CSPRNG salt_seed per commitment deriving 128-bit leaf salts on the fly on both CPU (SIMD multi-buffer & disk-spilled) and CUDA (zero persistent salt VRAM/RAM/disk). - Security Trap 1: fail-closed minimum trace height floor N >= next_pow2(2*Q + 2*D) (> next_pow2(Q + 2)) enforced at setup, prove, and verify. - Security Trap 2: W_R >= 4 base-field randomizer columns R(X) committed in the quotient MMCS for >= 128-bit hiding under FriBatching::Tensor / F_{p^3}. - Security Trap 3: zero-overhead C_active == 1 and committed boundary-mask U + row-0 delta-shift blinding of intermediate_accumulators for C_active > 1. - Security Trap 4: fail-closed quotient-degree vs log_blowup validation (q_zk = d.next_power_of_two() <= 2^log_blowup) with telescoping half-stride quotient blinding over 2*q_zk slices. - C2 MerkleCap exact root-count enforcement preserved before Fiat-Shamir observation across both non-ZK and hiding MMCS/PCS (CPU & CUDA). - CUDA v6-zk backend: salted BLAKE3-CTR leaf hashing kernels in cuda/kernels.cu, FFI bindings in src/cuda/mod.rs, HidingCudaMmcs + HidingCudaTwoAdicFriPcs (including resident GPU FRI folding, wide-row hybrid fallback, and unit tests). - Tests: 12 integration/security/indistinguishability/negative-control tests in tests/fp3_v6_zk.rs + 3 new lib unit tests; all 184 release tests pass. --- Cargo.lock | 1 + Cargo.toml | 1 + cuda/kernels.cu | 398 +++++-- src/batch.rs | 41 +- src/config.rs | 68 ++ src/cuda/hiding_mmcs.rs | 1174 +++++++++++++++++++++ src/cuda/hiding_pcs.rs | 975 ++++++++++++++++++ src/cuda/mmcs.rs | 6 + src/cuda/mod.rs | 328 ++++++ src/cuda/pcs.rs | 14 +- src/lookup.rs | 19 + src/p3_adapter/blake3_simd.rs | 390 +++++++ src/p3_adapter/cap.rs | 17 +- src/p3_adapter/domain_blake3.rs | 79 +- src/p3_adapter/mod.rs | 3 + src/p3_adapter/spill.rs | 113 +- src/p3_adapter/spill_zk.rs | 1718 +++++++++++++++++++++++++++++++ src/p3_adapter/zk.rs | 987 ++++++++++++++++++ src/prover.rs | 278 +++-- src/system.rs | 87 +- src/types.rs | 900 +++++++++++++++- src/verifier.rs | 173 +++- tests/fp3_v6_zk.rs | 1182 +++++++++++++++++++++ 23 files changed, 8730 insertions(+), 222 deletions(-) create mode 100644 src/cuda/hiding_mmcs.rs create mode 100644 src/cuda/hiding_pcs.rs create mode 100644 src/p3_adapter/spill_zk.rs create mode 100644 src/p3_adapter/zk.rs create mode 100644 tests/fp3_v6_zk.rs diff --git a/Cargo.lock b/Cargo.lock index a59a76d..acaa7ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -463,6 +463,7 @@ dependencies = [ "bincode", "blake3", "criterion", + "getrandom", "itertools 0.14.0", "p3-air", "p3-baby-bear", diff --git a/Cargo.toml b/Cargo.toml index b88c3de..5dfc277 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ links = "multi_stark_cuda" [dependencies] blake3 = "1" +getrandom = "0.4" tracing = "0.1" itertools = { version = "0.14", optional = true } rayon = { version = "1", optional = true } diff --git a/cuda/kernels.cu b/cuda/kernels.cu index b6a5801..f680584 100644 --- a/cuda/kernels.cu +++ b/cuda/kernels.cu @@ -19,6 +19,20 @@ #include #include "ntt.cuh" +namespace multi_stark_cuda { + +enum class Blake3DomainMode : uint32_t { + Plain = 0, + V6 = 1, + V6Zk = 2, +}; + +struct Blake3SaltSeed { + uint32_t words[8]; +}; + +} // namespace multi_stark_cuda + namespace { using namespace multi_stark_cuda; @@ -29,7 +43,20 @@ constexpr uint32_t BLAKE3_CHUNK_START = 1U << 0; constexpr uint32_t BLAKE3_CHUNK_END = 1U << 1; constexpr uint32_t BLAKE3_PARENT = 1U << 2; constexpr uint32_t BLAKE3_ROOT = 1U << 3; +constexpr uint32_t BLAKE3_KEYED_HASH = 1U << 4; constexpr uint32_t BLAKE3_DERIVE_KEY_MATERIAL = 1U << 6; + +inline Blake3SaltSeed load_salt_seed_host(const uint8_t* seed_bytes) { + Blake3SaltSeed seed{}; + for (unsigned int i = 0; i < 8; ++i) { + seed.words[i] = + static_cast(seed_bytes[4 * i]) | + (static_cast(seed_bytes[4 * i + 1]) << 8) | + (static_cast(seed_bytes[4 * i + 2]) << 16) | + (static_cast(seed_bytes[4 * i + 3]) << 24); + } + return seed; +} // All work currently uses CUDA's per-thread default stream. Stream-ordered // allocation preserves the same dependency order while avoiding cudaFree's // device-wide synchronization on thousands of short-lived PCS buffers. @@ -85,10 +112,50 @@ __device__ __constant__ uint32_t BLAKE3_V6_COMPRESS_CV[8] = { 0xCC4D7633U, 0xF8492FECU, 0x5704B1FDU, 0x2D69A6B5U, 0xA871EBB5U, 0x6439610DU, 0x89E86BE6U, 0x02E22A34U, }; +// Precomputed BLAKE3 derive_key context keys for Protocol v6-zk Merkle hashing +// (pinned against Rust's `Blake3Domain::ZkMerkleLeaf` and +// `Blake3Domain::ZkMerkleCompress`). +// Context "multi-stark/v6-zk/merkle/leaf": +__device__ __constant__ uint32_t BLAKE3_V6ZK_LEAF_CV[8] = { + 0x8A663924U, 0x051A410EU, 0xB5929C7AU, 0x52E6E08CU, + 0x51D3B0FAU, 0x1D1687C6U, 0x472E9E06U, 0x5A324ECAU, +}; +// Context "multi-stark/v6-zk/merkle/compress": +__device__ __constant__ uint32_t BLAKE3_V6ZK_COMPRESS_CV[8] = { + 0x6E9B081EU, 0xBAEEB5DAU, 0x18652A0DU, 0xA2D1B4E1U, + 0x9E40FB01U, 0xE905254DU, 0x451628D5U, 0x3D606842U, +}; __device__ __constant__ unsigned int BLAKE3_PERMUTATION[16] = { 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8, }; +__device__ __forceinline__ const uint32_t* blake3_leaf_cv( + Blake3DomainMode domain) { + if (domain == Blake3DomainMode::V6) { + return BLAKE3_V6_LEAF_CV; + } + if (domain == Blake3DomainMode::V6Zk) { + return BLAKE3_V6ZK_LEAF_CV; + } + return BLAKE3_IV; +} + +__device__ __forceinline__ const uint32_t* blake3_compress_cv( + Blake3DomainMode domain) { + if (domain == Blake3DomainMode::V6) { + return BLAKE3_V6_COMPRESS_CV; + } + if (domain == Blake3DomainMode::V6Zk) { + return BLAKE3_V6ZK_COMPRESS_CV; + } + return BLAKE3_IV; +} + +__device__ __forceinline__ uint32_t blake3_domain_flags( + Blake3DomainMode domain) { + return domain == Blake3DomainMode::Plain ? 0U : BLAKE3_DERIVE_KEY_MATERIAL; +} + __device__ __forceinline__ uint32_t rotate_right(uint32_t value, unsigned int count) { return __funnelshift_r(value, value, count); @@ -173,12 +240,13 @@ __device__ __forceinline__ uint32_t load_u32_le(const uint8_t* bytes, __device__ __forceinline__ void blake3_chunk( const uint8_t* bytes, size_t length, uint64_t chunk_counter, bool root, - uint32_t output[8], bool domain_v6 = false) { + uint32_t output[8], Blake3DomainMode domain = Blake3DomainMode::Plain) { uint32_t chaining_value[8]; - const uint32_t domain_flags = domain_v6 ? BLAKE3_DERIVE_KEY_MATERIAL : 0U; + const uint32_t domain_flags = blake3_domain_flags(domain); + const uint32_t* cv = blake3_leaf_cv(domain); #pragma unroll for (unsigned int i = 0; i < 8; ++i) { - chaining_value[i] = domain_v6 ? BLAKE3_V6_LEAF_CV[i] : BLAKE3_IV[i]; + chaining_value[i] = cv[i]; } const size_t blocks = length == 0 ? 1 : (length + 63) / 64; for (size_t block_index = 0; block_index < blocks; ++block_index) { @@ -218,10 +286,9 @@ __device__ __forceinline__ void blake3_chunk( } } -__device__ __forceinline__ void blake3_parent(const uint32_t left[8], - const uint32_t right[8], - bool root, uint32_t output[8], - bool domain_v6 = false) { +__device__ __forceinline__ void blake3_parent( + const uint32_t left[8], const uint32_t right[8], bool root, + uint32_t output[8], Blake3DomainMode domain = Blake3DomainMode::Plain) { uint32_t block[16]; #pragma unroll for (unsigned int i = 0; i < 8; ++i) { @@ -230,9 +297,8 @@ __device__ __forceinline__ void blake3_parent(const uint32_t left[8], } uint32_t compressed[16]; const uint32_t flags = BLAKE3_PARENT | (root ? BLAKE3_ROOT : 0U) | - (domain_v6 ? BLAKE3_DERIVE_KEY_MATERIAL : 0U); - blake3_compress(domain_v6 ? BLAKE3_V6_LEAF_CV : BLAKE3_IV, block, 0, 64, - flags, compressed); + blake3_domain_flags(domain); + blake3_compress(blake3_leaf_cv(domain), block, 0, 64, flags, compressed); #pragma unroll for (unsigned int i = 0; i < 8; ++i) { output[i] = compressed[i]; @@ -241,7 +307,7 @@ __device__ __forceinline__ void blake3_parent(const uint32_t left[8], __device__ __forceinline__ void blake3_hash_digest_pair( const uint8_t* left, const uint8_t* right, uint8_t* digest, - bool domain_v6 = false) { + Blake3DomainMode domain = Blake3DomainMode::Plain) { uint32_t block[16]; #pragma unroll for (unsigned int word = 0; word < 8; ++word) { @@ -251,9 +317,9 @@ __device__ __forceinline__ void blake3_hash_digest_pair( } uint32_t compressed[16]; const uint32_t flags = BLAKE3_CHUNK_START | BLAKE3_CHUNK_END | BLAKE3_ROOT | - (domain_v6 ? BLAKE3_DERIVE_KEY_MATERIAL : 0U); - blake3_compress(domain_v6 ? BLAKE3_V6_COMPRESS_CV : BLAKE3_IV, block, 0, 64, - flags, compressed); + blake3_domain_flags(domain); + blake3_compress(blake3_compress_cv(domain), block, 0, 64, flags, + compressed); #pragma unroll for (unsigned int word = 0; word < 8; ++word) { const uint32_t value = compressed[word]; @@ -264,6 +330,32 @@ __device__ __forceinline__ void blake3_hash_digest_pair( } } +// On-the-fly single-block keyed BLAKE3-CTR leaf salt derivation for Protocol +// v6-zk: `BLAKE3_keyed(salt_seed, height_u64_le || row_index_u64_le)[0..16]`. +// Matches `crate::p3_adapter::zk::derive_leaf_salt` byte-for-byte with zero +// persistent VRAM salt storage. +__device__ __forceinline__ void blake3_derive_leaf_salt( + const uint32_t seed_words[8], uint64_t height, uint64_t row_index, + uint64_t out_salt[2]) { + uint32_t block[16]; + block[0] = static_cast(height); + block[1] = static_cast(height >> 32); + block[2] = static_cast(row_index); + block[3] = static_cast(row_index >> 32); +#pragma unroll + for (unsigned int i = 4; i < 16; ++i) { + block[i] = 0U; + } + uint32_t compressed[16]; + const uint32_t flags = BLAKE3_KEYED_HASH | BLAKE3_CHUNK_START | + BLAKE3_CHUNK_END | BLAKE3_ROOT; + blake3_compress(seed_words, block, 0, 16, flags, compressed); + out_salt[0] = static_cast(compressed[0]) | + (static_cast(compressed[1]) << 32); + out_salt[1] = static_cast(compressed[2]) | + (static_cast(compressed[3]) << 32); +} + unsigned int blocks_for(size_t work_items) { if (work_items == 0) { return 0; @@ -1822,13 +1914,13 @@ __global__ void blake3_hash_short_rows_kernel(uint8_t* digests, const uint8_t* messages, size_t message_bytes, size_t message_count, - bool domain_v6) { + Blake3DomainMode domain) { const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; for (size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; index < message_count; index += grid_stride) { uint32_t output[8]; blake3_chunk(messages + index * message_bytes, message_bytes, 0, true, - output, domain_v6); + output, domain); uint8_t* digest = digests + index * 32; #pragma unroll for (unsigned int word = 0; word < 8; ++word) { @@ -1849,7 +1941,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, const uint8_t* messages, size_t message_bytes, size_t message_count, - bool domain_v6) { + Blake3DomainMode domain) { __shared__ uint32_t chunk_values[THREADS / 32][32][8]; const unsigned int lane = threadIdx.x & 31U; const unsigned int warp_in_block = threadIdx.x >> 5; @@ -1872,7 +1964,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, : 0; uint32_t chunk_output[8]; blake3_chunk(message + chunk_offset, chunk_length, lane, - chunks == 1, chunk_output, domain_v6); + chunks == 1, chunk_output, domain); #pragma unroll for (unsigned int word = 0; word < 8; ++word) { chunk_values[warp_in_block][lane][word] = chunk_output[word]; @@ -1889,7 +1981,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, uint32_t parent[8]; blake3_parent(chunk_values[warp_in_block][index], chunk_values[warp_in_block][index + 1], - root_level, parent, domain_v6); + root_level, parent, domain); #pragma unroll for (unsigned int word = 0; word < 8; ++word) { chunk_values[warp_in_block][next_count][word] = parent[word]; @@ -1923,7 +2015,7 @@ __global__ void blake3_hash_rows_kernel(uint8_t* digests, __global__ void blake3_hash_digest_pairs_kernel( uint8_t* digests, const uint8_t* left, const uint8_t* right, - size_t count, bool interleaved, bool domain_v6) { + size_t count, bool interleaved, Blake3DomainMode domain) { const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; for (size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; @@ -1933,17 +2025,18 @@ __global__ void blake3_hash_digest_pairs_kernel( const uint8_t* right_digest = right + (interleaved ? 2 * index + 1 : index) * 32; blake3_hash_digest_pair(left_digest, right_digest, - digests + index * 32, domain_v6); + digests + index * 32, domain); } } -cudaError_t launch_blake3_rows(uint8_t* digests, const uint8_t* messages, - size_t message_bytes, size_t message_count, - bool domain_v6 = false) { +cudaError_t launch_blake3_rows( + uint8_t* digests, const uint8_t* messages, size_t message_bytes, + size_t message_count, + Blake3DomainMode domain = Blake3DomainMode::Plain) { if (message_bytes <= BLAKE3_CHUNK_BYTES) { blake3_hash_short_rows_kernel<<>>( - digests, messages, message_bytes, message_count, domain_v6); + digests, messages, message_bytes, message_count, domain); return cudaGetLastError(); } constexpr unsigned int WARPS_PER_BLOCK = THREADS / 32; @@ -1952,18 +2045,16 @@ cudaError_t launch_blake3_rows(uint8_t* digests, const uint8_t* messages, const unsigned int blocks = static_cast( required < MAX_BLOCKS ? required : MAX_BLOCKS); blake3_hash_rows_kernel<<>>( - digests, messages, message_bytes, message_count, domain_v6); + digests, messages, message_bytes, message_count, domain); return cudaGetLastError(); } -cudaError_t launch_blake3_digest_pairs(uint8_t* digests, - const uint8_t* left, - const uint8_t* right, size_t count, - bool interleaved, - bool domain_v6 = false) { +cudaError_t launch_blake3_digest_pairs( + uint8_t* digests, const uint8_t* left, const uint8_t* right, size_t count, + bool interleaved, Blake3DomainMode domain = Blake3DomainMode::Plain) { blake3_hash_digest_pairs_kernel<<>>( - digests, left, right, count, interleaved, domain_v6); + digests, left, right, count, interleaved, domain); return cudaGetLastError(); } @@ -1980,10 +2071,45 @@ __global__ void gather_resident_lde_group( } } -cudaError_t hash_resident_lde_group(uint8_t* digests, - const void* const* handles, - size_t handle_count, size_t height, - bool domain_v6 = false) { +__global__ void gather_resident_lde_group_strided( + uint64_t* output, const uint64_t* const* columns, const size_t* strides, + size_t row_start, size_t rows, size_t width, size_t output_stride) { + const size_t count = rows * width; + const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; + for (size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + index < count; index += grid_stride) { + const size_t column = index % width; + const size_t local_row = index / width; + const size_t row = row_start + local_row; + output[local_row * output_stride + column] = + columns[column][row * strides[column]]; + } +} + +__global__ void fill_leaf_salts_kernel( + uint64_t* output, size_t output_stride, size_t salt_col_offset, + uint64_t height, size_t row_start, size_t rows, Blake3SaltSeed seed) { + const size_t grid_stride = static_cast(blockDim.x) * gridDim.x; + for (size_t local_row = + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + local_row < rows; local_row += grid_stride) { + uint64_t salt[2]; + blake3_derive_leaf_salt(seed.words, height, + static_cast(row_start + local_row), + salt); + uint64_t* dst = output + local_row * output_stride + salt_col_offset; + dst[0] = salt[0]; + dst[1] = salt[1]; + } +} + +cudaError_t hash_resident_lde_group( + uint8_t* digests, const void* const* handles, size_t handle_count, + size_t height, Blake3DomainMode domain = Blake3DomainMode::Plain, + const uint8_t* salt_seed = nullptr) { + const bool salted = salt_seed != nullptr; + const size_t salt_words = salted ? 2 : 0; + const size_t max_words = (32 * 1024) / sizeof(uint64_t) - salt_words; size_t total_width = 0; for (size_t index = 0; index < handle_count; ++index) { const ResidentLde* lde = static_cast(handles[index]); @@ -1994,15 +2120,20 @@ cudaError_t hash_resident_lde_group(uint8_t* digests, total_width += lde->width; } } - if (total_width == 0 || total_width > (32 * 1024) / sizeof(uint64_t) || - !product_fits(height, total_width)) { + if (total_width == 0 || total_width > max_words) { + return cudaErrorInvalidValue; + } + const size_t output_stride = total_width + salt_words; + if (!product_fits(height, output_stride)) { return cudaErrorInvalidValue; } constexpr size_t ROW_STAGING_BYTES = size_t(32) << 20; - const size_t row_bytes = total_width * sizeof(uint64_t); + const size_t row_bytes = output_stride * sizeof(uint64_t); const size_t rows_per_chunk = (ROW_STAGING_BYTES / row_bytes) > 0 ? (ROW_STAGING_BYTES / row_bytes) : 1; + const Blake3SaltSeed seed_words = + salted ? load_salt_seed_host(salt_seed) : Blake3SaltSeed{}; const uint64_t** host_columns = new (std::nothrow) const uint64_t*[total_width]; size_t* host_strides = new (std::nothrow) size_t[total_width]; @@ -2043,7 +2174,7 @@ cudaError_t hash_resident_lde_group(uint8_t* digests, DeviceBuffer combined_rows; if (status == cudaSuccess) { status = combined_rows.allocate( - (height < rows_per_chunk ? height : rows_per_chunk) * total_width); + (height < rows_per_chunk ? height : rows_per_chunk) * output_stride); } for (size_t row_start = 0; status == cudaSuccess && row_start < height; row_start += rows_per_chunk) { @@ -2051,18 +2182,35 @@ cudaError_t hash_resident_lde_group(uint8_t* digests, (height - row_start < rows_per_chunk) ? height - row_start : rows_per_chunk; const size_t count = rows * total_width; - gather_resident_lde_group<<>>( - combined_rows.get(), - reinterpret_cast(device_columns.get()), - reinterpret_cast(device_strides.get()), row_start, - rows, total_width); - status = cudaGetLastError(); + if (salted) { + gather_resident_lde_group_strided<<>>( + combined_rows.get(), + reinterpret_cast(device_columns.get()), + reinterpret_cast(device_strides.get()), row_start, + rows, total_width, output_stride); + status = cudaGetLastError(); + if (status == cudaSuccess) { + fill_leaf_salts_kernel<<>>( + combined_rows.get(), output_stride, total_width, + static_cast(height), row_start, rows, seed_words); + status = cudaGetLastError(); + } + } else { + gather_resident_lde_group<<>>( + combined_rows.get(), + reinterpret_cast(device_columns.get()), + reinterpret_cast(device_strides.get()), row_start, + rows, total_width); + status = cudaGetLastError(); + } if (status == cudaSuccess) { status = launch_blake3_rows( digests + row_start * 32, reinterpret_cast(combined_rows.get()), row_bytes, - rows, domain_v6); + rows, domain); } } return status; @@ -2072,7 +2220,8 @@ cudaError_t hash_partitioned_lde_group( uint8_t* digests, const void* const* handles, const uint64_t* const* host_values, const size_t* widths, const size_t* heights, size_t matrix_count, size_t height, - bool domain_v6 = false) { + Blake3DomainMode domain = Blake3DomainMode::Plain, + const uint8_t* salt_seed = nullptr) { bool has_host = false; bool has_resident = false; size_t total_width = 0; @@ -2089,11 +2238,16 @@ cudaError_t hash_partitioned_lde_group( } if (!has_host) { return hash_resident_lde_group(digests, handles, matrix_count, height, - domain_v6); + domain, salt_seed); + } + const bool salted = salt_seed != nullptr; + const size_t salt_words = salted ? 2 : 0; + const size_t max_words = (32 * 1024) / sizeof(uint64_t) - salt_words; + if (!has_resident || total_width == 0 || total_width > max_words) { + return cudaErrorInvalidValue; } - if (!has_resident || total_width == 0 || - total_width > (32 * 1024) / sizeof(uint64_t) || - !product_fits(height, total_width)) { + const size_t output_stride = total_width + salt_words; + if (!product_fits(height, output_stride)) { return cudaErrorInvalidValue; } @@ -2145,9 +2299,11 @@ cudaError_t hash_partitioned_lde_group( DeviceBuffer device_strides; DeviceBuffer combined_rows; constexpr size_t ROW_STAGING_BYTES = size_t(32) << 20; - const size_t row_bytes = total_width * sizeof(uint64_t); + const size_t row_bytes = output_stride * sizeof(uint64_t); const size_t rows_per_chunk = (ROW_STAGING_BYTES / row_bytes) > 0 ? (ROW_STAGING_BYTES / row_bytes) : 1; + const Blake3SaltSeed seed_words = + salted ? load_salt_seed_host(salt_seed) : Blake3SaltSeed{}; if (status == cudaSuccess) { status = device_columns.allocate(total_width); } @@ -2156,7 +2312,7 @@ cudaError_t hash_partitioned_lde_group( } if (status == cudaSuccess) { status = combined_rows.allocate( - (height < rows_per_chunk ? height : rows_per_chunk) * total_width); + (height < rows_per_chunk ? height : rows_per_chunk) * output_stride); } if (status == cudaSuccess) { status = cudaMemcpy(device_columns.get(), host_columns, @@ -2173,18 +2329,35 @@ cudaError_t hash_partitioned_lde_group( (height - row_start < rows_per_chunk) ? height - row_start : rows_per_chunk; const size_t count = rows * total_width; - gather_resident_lde_group<<>>( - combined_rows.get(), - reinterpret_cast(device_columns.get()), - reinterpret_cast(device_strides.get()), row_start, - rows, total_width); - status = cudaGetLastError(); + if (salted) { + gather_resident_lde_group_strided<<>>( + combined_rows.get(), + reinterpret_cast(device_columns.get()), + reinterpret_cast(device_strides.get()), row_start, + rows, total_width, output_stride); + status = cudaGetLastError(); + if (status == cudaSuccess) { + fill_leaf_salts_kernel<<>>( + combined_rows.get(), output_stride, total_width, + static_cast(height), row_start, rows, seed_words); + status = cudaGetLastError(); + } + } else { + gather_resident_lde_group<<>>( + combined_rows.get(), + reinterpret_cast(device_columns.get()), + reinterpret_cast(device_strides.get()), row_start, + rows, total_width); + status = cudaGetLastError(); + } if (status == cudaSuccess) { status = launch_blake3_rows( digests + row_start * 32, reinterpret_cast(combined_rows.get()), row_bytes, - rows, domain_v6); + rows, domain); } } if (status == cudaSuccess) { @@ -4208,7 +4381,7 @@ extern "C" int multi_stark_cuda_goldilocks_ops( namespace { int blake3_hash_rows_impl( int device_id, uint8_t* digests, const uint8_t* messages, - size_t message_bytes, size_t message_count, bool domain_v6) { + size_t message_bytes, size_t message_count, Blake3DomainMode domain) { if (digests == nullptr || messages == nullptr || message_count == 0 || message_bytes == 0 || message_bytes > 32 * 1024 || !product_fits(message_bytes, message_count) || @@ -4236,7 +4409,7 @@ int blake3_hash_rows_impl( status = launch_blake3_rows( reinterpret_cast(device_digests.get()), reinterpret_cast(device_messages.get()), - message_bytes, message_count, domain_v6); + message_bytes, message_count, domain); } if (status == cudaSuccess) { status = cudaMemcpy(digests, device_digests.get(), output_bytes, @@ -4250,14 +4423,14 @@ extern "C" int multi_stark_cuda_blake3_hash_rows( int device_id, uint8_t* digests, const uint8_t* messages, size_t message_bytes, size_t message_count) { return blake3_hash_rows_impl(device_id, digests, messages, message_bytes, - message_count, false); + message_count, Blake3DomainMode::Plain); } extern "C" int multi_stark_cuda_blake3_hash_rows_v6( int device_id, uint8_t* digests, const uint8_t* messages, size_t message_bytes, size_t message_count) { return blake3_hash_rows_impl(device_id, digests, messages, message_bytes, - message_count, true); + message_count, Blake3DomainMode::V6); } extern "C" int multi_stark_cuda_blake3_merkle_root( @@ -4601,12 +4774,13 @@ int mixed_merkle_create_hybrid_impl( const size_t* widths, const size_t* heights, size_t matrix_count, const uint8_t* const* host_digest_groups, const size_t* host_digest_heights, size_t host_digest_group_count, - bool domain_v6) { + Blake3DomainMode domain, const uint8_t* salt_seed = nullptr) { if (handle == nullptr || root == nullptr || matrix_count == 0 || lde_handles == nullptr || host_values == nullptr || widths == nullptr || heights == nullptr || (host_digest_group_count != 0 && - (host_digest_groups == nullptr || host_digest_heights == nullptr))) { + (host_digest_groups == nullptr || host_digest_heights == nullptr)) || + (domain == Blake3DomainMode::V6Zk && salt_seed == nullptr)) { return static_cast(cudaErrorInvalidValue); } size_t max_height = 0; @@ -4689,7 +4863,7 @@ int mixed_merkle_create_hybrid_impl( } return hash_partitioned_lde_group(output, lde_handles, host_values, widths, heights, matrix_count, height, - domain_v6); + domain, salt_seed); }; if (status == cudaSuccess) { status = hash_group(tree->digests, max_height); @@ -4703,7 +4877,7 @@ int mixed_merkle_create_hybrid_impl( count /= 2; uint8_t* next = tree->digests + offset; status = launch_blake3_digest_pairs(next, current, current, count, - true, domain_v6); + true, domain); bool inject = false; for (size_t index = 0; index < matrix_count; ++index) { @@ -4717,7 +4891,7 @@ int mixed_merkle_create_hybrid_impl( status = launch_blake3_digest_pairs( next, next, reinterpret_cast(injected_digests.get()), - count, false, domain_v6); + count, false, domain); } } if (status == cudaSuccess) { @@ -4736,10 +4910,11 @@ int hash_hybrid_height_group_impl( int device_id, uint8_t* host_digests, const void* const* lde_handles, const uint64_t* const* host_values, const size_t* widths, const size_t* heights, size_t matrix_count, size_t height, - bool domain_v6) { + Blake3DomainMode domain, const uint8_t* salt_seed = nullptr) { if (device_id < 0 || host_digests == nullptr || lde_handles == nullptr || host_values == nullptr || widths == nullptr || heights == nullptr || - matrix_count == 0 || !is_power_of_two(height) || height > SIZE_MAX / 4) { + matrix_count == 0 || !is_power_of_two(height) || height > SIZE_MAX / 4 || + (domain == Blake3DomainMode::V6Zk && salt_seed == nullptr)) { return static_cast(cudaErrorInvalidValue); } bool has_resident = false; @@ -4766,7 +4941,8 @@ int hash_hybrid_height_group_impl( if (status == cudaSuccess) { status = hash_partitioned_lde_group( reinterpret_cast(device_digests.get()), lde_handles, - host_values, widths, heights, matrix_count, height, domain_v6); + host_values, widths, heights, matrix_count, height, domain, + salt_seed); } if (status == cudaSuccess) { status = cudaMemcpy(host_digests, device_digests.get(), height * 32, @@ -4777,8 +4953,10 @@ int hash_hybrid_height_group_impl( int mixed_merkle_create_from_ldes_impl( int device_id, void** handle, uint8_t* root, - const void* const* lde_handles, size_t lde_count, bool domain_v6) { - if (lde_handles == nullptr || lde_count == 0) { + const void* const* lde_handles, size_t lde_count, Blake3DomainMode domain, + const uint8_t* salt_seed = nullptr) { + if (lde_handles == nullptr || lde_count == 0 || + (domain == Blake3DomainMode::V6Zk && salt_seed == nullptr)) { return static_cast(cudaErrorInvalidValue); } const uint64_t** host_values = @@ -4805,7 +4983,7 @@ int mixed_merkle_create_from_ldes_impl( } const int status = mixed_merkle_create_hybrid_impl( device_id, handle, root, lde_handles, host_values, widths, heights, - lde_count, nullptr, nullptr, 0, domain_v6); + lde_count, nullptr, nullptr, 0, domain, salt_seed); delete[] host_values; delete[] widths; delete[] heights; @@ -4814,8 +4992,10 @@ int mixed_merkle_create_from_ldes_impl( int fri_merkle_create_impl( int device_id, void** handle, uint8_t* root, const void* codeword_handle, - size_t arity, bool domain_v6) { - if (!codeword_handle || !is_power_of_two(arity)) { + size_t arity, Blake3DomainMode domain, + const uint8_t* salt_seed = nullptr) { + if (!codeword_handle || !is_power_of_two(arity) || + (domain == Blake3DomainMode::V6Zk && salt_seed == nullptr)) { return static_cast(cudaErrorInvalidValue); } const auto* codeword = static_cast(codeword_handle); @@ -4829,7 +5009,7 @@ int fri_merkle_create_impl( view.width = codeword->width * arity; const void* views[1] = {&view}; const int status = mixed_merkle_create_from_ldes_impl( - device_id, handle, root, views, 1, domain_v6); + device_id, handle, root, views, 1, domain, salt_seed); view.values = nullptr; return status; } @@ -4844,7 +5024,7 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid( return mixed_merkle_create_hybrid_impl( device_id, handle, root, lde_handles, host_values, widths, heights, matrix_count, host_digest_groups, host_digest_heights, - host_digest_group_count, false); + host_digest_group_count, Blake3DomainMode::Plain); } extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid_v6( @@ -4856,7 +5036,20 @@ extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid_v6( return mixed_merkle_create_hybrid_impl( device_id, handle, root, lde_handles, host_values, widths, heights, matrix_count, host_digest_groups, host_digest_heights, - host_digest_group_count, true); + host_digest_group_count, Blake3DomainMode::V6); +} + +extern "C" int multi_stark_cuda_mixed_merkle_create_hybrid_v6zk( + int device_id, void** handle, uint8_t* root, + const void* const* lde_handles, const uint64_t* const* host_values, + const size_t* widths, const size_t* heights, size_t matrix_count, + const uint8_t* const* host_digest_groups, + const size_t* host_digest_heights, size_t host_digest_group_count, + const uint8_t* salt_seed) { + return mixed_merkle_create_hybrid_impl( + device_id, handle, root, lde_handles, host_values, widths, heights, + matrix_count, host_digest_groups, host_digest_heights, + host_digest_group_count, Blake3DomainMode::V6Zk, salt_seed); } extern "C" int multi_stark_cuda_hash_hybrid_height_group( @@ -4865,7 +5058,7 @@ extern "C" int multi_stark_cuda_hash_hybrid_height_group( const size_t* heights, size_t matrix_count, size_t height) { return hash_hybrid_height_group_impl( device_id, host_digests, lde_handles, host_values, widths, heights, - matrix_count, height, false); + matrix_count, height, Blake3DomainMode::Plain); } extern "C" int multi_stark_cuda_hash_hybrid_height_group_v6( @@ -4874,35 +5067,62 @@ extern "C" int multi_stark_cuda_hash_hybrid_height_group_v6( const size_t* heights, size_t matrix_count, size_t height) { return hash_hybrid_height_group_impl( device_id, host_digests, lde_handles, host_values, widths, heights, - matrix_count, height, true); + matrix_count, height, Blake3DomainMode::V6); +} + +extern "C" int multi_stark_cuda_hash_hybrid_height_group_v6zk( + int device_id, uint8_t* host_digests, const void* const* lde_handles, + const uint64_t* const* host_values, const size_t* widths, + const size_t* heights, size_t matrix_count, size_t height, + const uint8_t* salt_seed) { + return hash_hybrid_height_group_impl( + device_id, host_digests, lde_handles, host_values, widths, heights, + matrix_count, height, Blake3DomainMode::V6Zk, salt_seed); } extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes( int device_id, void** handle, uint8_t* root, const void* const* lde_handles, size_t lde_count) { return mixed_merkle_create_from_ldes_impl( - device_id, handle, root, lde_handles, lde_count, false); + device_id, handle, root, lde_handles, lde_count, + Blake3DomainMode::Plain); } extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes_v6( int device_id, void** handle, uint8_t* root, const void* const* lde_handles, size_t lde_count) { return mixed_merkle_create_from_ldes_impl( - device_id, handle, root, lde_handles, lde_count, true); + device_id, handle, root, lde_handles, lde_count, Blake3DomainMode::V6); +} + +extern "C" int multi_stark_cuda_mixed_merkle_create_from_ldes_v6zk( + int device_id, void** handle, uint8_t* root, + const void* const* lde_handles, size_t lde_count, + const uint8_t* salt_seed) { + return mixed_merkle_create_from_ldes_impl( + device_id, handle, root, lde_handles, lde_count, + Blake3DomainMode::V6Zk, salt_seed); } extern "C" int multi_stark_cuda_fri_merkle_create( int device_id, void** handle, uint8_t* root, const void* codeword_handle, size_t arity) { return fri_merkle_create_impl(device_id, handle, root, codeword_handle, - arity, false); + arity, Blake3DomainMode::Plain); } extern "C" int multi_stark_cuda_fri_merkle_create_v6( int device_id, void** handle, uint8_t* root, const void* codeword_handle, size_t arity) { return fri_merkle_create_impl(device_id, handle, root, codeword_handle, - arity, true); + arity, Blake3DomainMode::V6); +} + +extern "C" int multi_stark_cuda_fri_merkle_create_v6zk( + int device_id, void** handle, uint8_t* root, const void* codeword_handle, + size_t arity, const uint8_t* salt_seed) { + return fri_merkle_create_impl(device_id, handle, root, codeword_handle, + arity, Blake3DomainMode::V6Zk, salt_seed); } extern "C" int multi_stark_cuda_mixed_merkle_create_from_host_matrices( diff --git a/src/batch.rs b/src/batch.rs index f6e127c..a4ba6e1 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -331,11 +331,23 @@ impl System { &self, preamble: &BatchPreamble, ) -> Result<(), VerificationError>> { + let is_zk = self.config.is_zk(); + let zk_shift = usize::from(is_zk); ensure!( !self.circuits.is_empty(), VerificationError::InvalidSystem; "system has no circuits" ); + if is_zk { + ensure!( + self.config.zk_randomizer_width() >= crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH + && self.config.log_blowup() >= 1, + VerificationError::InvalidSystem; + randomizer_width = self.config.zk_randomizer_width(), + log_blowup = self.config.log_blowup(), + "invalid v6-zk randomizer width or log_blowup" + ); + } let num_preprocessed = self .preprocessed_indices .iter() @@ -362,7 +374,7 @@ impl System { && max_prep_height.is_power_of_two() && self.config.validate_commitment_cap( commit, - log2_strict_usize(max_prep_height) + self.config.log_blowup(), + log2_strict_usize(max_prep_height) + zk_shift + self.config.log_blowup(), ), VerificationError::InvalidSystem; max_prep_height, @@ -374,8 +386,10 @@ impl System { VerificationError::BatchShapeMismatch; "batch preamble has no shard headers" ); + let min_log_degree = self.config.min_log_degree(); let max_log_degree = self.config.max_log_degree(); let max_log_quotient_domain = self.config.max_log_quotient_domain(); + let max_quotient_degree = self.config.max_quotient_degree(); let log_blowup = self.config.log_blowup(); for (idx, header) in preamble.headers.iter().enumerate() { ensure!( @@ -414,11 +428,31 @@ impl System { "batch preamble header trace height does not match preprocessed height" ); } - let quotient_degree = circuit.quotient_degree(); + let quotient_degree = circuit.quotient_degree_for(is_zk); + ensure!( + quotient_degree <= max_quotient_degree, + VerificationError::InvalidSystem; + shard = idx, + circuit = ci, + quotient_degree, + max_quotient_degree, + "batch circuit quotient degree exceeds PCS blowup budget" + ); + if is_zk { + ensure!( + usize::from(log_degree) >= min_log_degree, + VerificationError::BatchShapeMismatch; + shard = idx, + circuit = ci, + log_degree, + min_log_degree, + "batch preamble header trace height below v6-zk minimum floor" + ); + } ensure!( usize::from(log_degree) <= max_log_degree && usize::from(log_degree) < usize::BITS as usize - && usize::from(log_degree) + log2_strict_usize(quotient_degree) + && usize::from(log_degree) + zk_shift + log2_strict_usize(quotient_degree) <= max_log_quotient_domain, VerificationError::BatchShapeMismatch; shard = idx, @@ -437,6 +471,7 @@ impl System { .map(usize::from) .max() .expect("active_indices is non-empty") + + zk_shift + log_blowup; ensure!( self.config diff --git a/src/config.rs b/src/config.rs index 84c3317..61ffa5f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -31,6 +31,24 @@ pub type AcceleratedLookupTraces = ( pub type AcceleratedLookupCommitment = (Com, PcsData, Vec<::Challenge>); +/// Reference to the committed cross-circuit LogUp accumulator boundary mask +/// matrix `U` (matrix `#num_active` inside `stage_2_trace`) for multi-circuit +/// `v6-zk` proofs (`num_active > 1`). +pub struct ZkBoundaryMask<'a, SC: ProofConfig> { + pub data: &'a PcsData, + pub matrix_index: usize, + pub active_pos: usize, + pub num_active: usize, +} + +impl Clone for ZkBoundaryMask<'_, SC> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for ZkBoundaryMask<'_, SC> {} + /// One circuit's inputs to an optional fused quotient commitment backend. /// Keeping this protocol-level description free of CUDA types lets the /// generic CPU prover remain entirely independent of accelerator support. @@ -43,6 +61,7 @@ pub struct QuotientCommitInput<'a, SC: ProofConfig> { pub stage_1: (&'a PcsData, usize), pub stage_2: (&'a PcsData, usize), pub constraint_count: usize, + pub zk_boundary_mask: Option>, } /// One circuit's inputs to an optional fused lookup construction and @@ -75,6 +94,13 @@ pub enum ProtocolVersion { /// canonical VK & constraint-graph digest plus extension degree/modulus /// bound in the transcript, and configurable multilinear tensor FRI batching. V6, + /// Zero-knowledge `v6-zk` protocol: 2× interleaved odd-coset hiding PCS + /// with zero-storage BLAKE3-CTR leaf salting (`multi-stark/v6-zk/*`), + /// `W_R >= 4` base-field randomizer polynomial merged into quotient + /// commitment, telescoping half-stride quotient blinding, minimum trace + /// height floor, and boundary-mask blinding of `intermediate_accumulators` + /// when multiple circuits are active. + V6Zk, } /// Transcript mode separating standalone single-proof transcripts from @@ -110,6 +136,48 @@ pub trait ProofConfig { ProtocolVersion::V5 } + /// Returns `true` when zero-knowledge mode (`ProtocolVersion::V6Zk`) is + /// enabled. Non-ZK `v5` and `v6` configurations return `false` with zero + /// runtime overhead. + fn is_zk(&self) -> bool { + self.protocol_version() == ProtocolVersion::V6Zk + } + + /// Minimum admissible `log2(trace_height)` for active circuits (`0` in + /// non-ZK modes; enforces `N >= next_pow2(2Q + 2D)` in `v6-zk`). + fn min_log_degree(&self) -> usize { + 0 + } + + /// Base-field column width `W_R` of the randomizer polynomial `R(X)` + /// merged into `quotient_chunks` (`0` in non-ZK modes; `>= 4` in `v6-zk`). + fn zk_randomizer_width(&self) -> usize { + 0 + } + + /// Samples `count` uniformly random base-field elements from a CSPRNG for + /// `v6-zk` blinding (e.g. cross-circuit accumulator boundary masking). + fn sample_zk_base_randomness(&self, _count: usize) -> Vec> { + unimplemented!("ProofConfig does not support v6-zk CSPRNG sampling") + } + + /// Commits ZK blinded quotient polynomials (`2 * q_zk` telescoping slices + /// per active circuit) together with the `W_R`-column randomizer `R(X)` in + /// one hiding MMCS round. + fn commit_quotient_zk( + &self, + _quotients: Vec<( + Domain, + p3_matrix::dense::RowMajorMatrix>, + usize, + )>, + ) -> (Com, PcsData) + where + Self: Sized, + { + unimplemented!("ProofConfig does not support v6-zk quotient commitment") + } + /// Returns a fresh challenger. /// /// # Transcript contract diff --git a/src/cuda/hiding_mmcs.rs b/src/cuda/hiding_mmcs.rs new file mode 100644 index 0000000..82dfe22 --- /dev/null +++ b/src/cuda/hiding_mmcs.rs @@ -0,0 +1,1174 @@ +//! CUDA hiding MMCS (`v6-zk`) using on-the-fly BLAKE3-CTR leaf salting with +//! zero salt-matrix VRAM or RAM storage. +//! +//! Matches the wire format, leaf-salt derivation (`derive_leaf_salt`), +//! `ZkMerkleLeaf` / `ZkMerkleCompress` domain separation, and `C2` exact +//! `MerkleCap` root-count validation of the CPU hiding MMCS byte-for-byte. + +use core::cmp::Reverse; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, OnceLock}; + +use itertools::Itertools; +use p3_commit::{BatchOpening, BatchOpeningRef, ExtensionMmcs, Mmcs}; +use p3_field::{ExtensionField, PrimeField64}; +use p3_goldilocks::Goldilocks; +use p3_matrix::dense::RowMajorMatrix; +use p3_matrix::{Dimensions, Matrix}; +use p3_maybe_rayon::prelude::*; +use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; +use p3_symmetric::MerkleCap; +use p3_util::log2_ceil_usize; + +use super::{ + CudaLde, CudaMixedMerkleTree, mixed_lde_open_row, mixed_lde_open_row_at_height, + mixed_lde_open_rows, mixed_lde_open_rows_at_height, +}; +use crate::p3_adapter::cap::{CapValidatingMmcs, verify_merkle_cap_len_for_log_height}; +use crate::p3_adapter::domain_blake3::Blake3Domain; +use crate::p3_adapter::zk::{ + HidingBatchProof, HidingMultiProof, ZK_LEAF_SALT_BYTES, derive_leaf_salt, + open_hiding_batch_salts, open_hiding_multi_salts, random_seed, verify_hiding_batch, + verify_hiding_multi_batch, +}; + +/// Maximum concatenated leaf row payload (in bytes, excluding the 16-byte leaf +/// salt) that the device BLAKE3 leaf kernel hashes directly in a 32 KiB chunk +/// tree (`4094` Goldilocks columns + `2` `u64` salt words = `32 KiB`). +pub(crate) const MAX_DEVICE_LEAF_ROW_BYTES_ZK: usize = 32 * 1024 - ZK_LEAF_SALT_BYTES; + +/// Returns heights whose concatenated leaf payload exceeds +/// [`MAX_DEVICE_LEAF_ROW_BYTES_ZK`] and therefore must be salted and hashed on +/// the host before entering the CUDA Merkle tree as pre-hashed digest groups. +pub(crate) fn host_hashed_heights_zk( + dimensions: impl IntoIterator, +) -> BTreeSet { + let mut row_bytes = BTreeMap::::new(); + for dims in dimensions { + *row_bytes.entry(dims.height).or_default() += dims.width * size_of::(); + } + row_bytes + .into_iter() + .filter(|(_, bytes)| *bytes > MAX_DEVICE_LEAF_ROW_BYTES_ZK) + .map(|(height, _)| height) + .collect() +} + +#[inline] +fn padded_len_binary(len: usize) -> usize { + if len <= 1 { 1 } else { len.next_power_of_two() } +} + +#[inline] +fn compress_pair(compress_domain: Blake3Domain, left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] { + let mut block = [0u8; 64]; + block[..32].copy_from_slice(left); + block[32..].copy_from_slice(right); + compress_domain.hash_bytes(&block) +} + +fn hash_group_salted>( + matrices: &[&M], + height: usize, + salt_seed: &[u8; 32], + leaf_domain: Blake3Domain, +) -> Vec<[u8; 32]> { + (0..height) + .into_par_iter() + .map(|row| { + let mut hasher = leaf_domain.hasher(); + for matrix in matrices { + for elem in matrix.row(row).unwrap() { + hasher.update(&elem.as_canonical_u64().to_le_bytes()); + } + } + let salt = derive_leaf_salt(salt_seed, height, row); + hasher.update(&salt); + hasher.finalize().into() + }) + .collect() +} + +/// CPU salted binary BLAKE3 Merkle tree used for small commitments, wide height +/// groups, and CPU fallback FRI rounds. Stores only the 32-byte `salt_seed`. +struct CpuHidingTree { + leaves: Vec, + digest_layers: Vec>, + salt_seed: [u8; 32], +} + +impl> CpuHidingTree { + fn build( + leaves: Vec, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, + salt_seed: [u8; 32], + ) -> Self { + assert!(!leaves.is_empty(), "No matrices given?"); + let max_height = leaves + .iter() + .map(Matrix::height) + .max() + .expect("No matrices given?"); + assert!(max_height > 0, "matrix height must be positive"); + let log_max_height = log2_ceil_usize(max_height); + for matrix in &leaves { + let h = matrix.height(); + assert!(h > 0, "matrix height must be positive"); + let bits_reduced = log_max_height - log2_ceil_usize(h); + let expected = ((max_height - 1) >> bits_reduced) + 1; + assert_eq!( + h, expected, + "incompatible matrix height {h} for max_height {max_height}" + ); + } + + let mut order: Vec = (0..leaves.len()).collect(); + order.sort_by_key(|&idx| Reverse(leaves[idx].height())); + + let tallest_end = order + .iter() + .take_while(|&&idx| leaves[idx].height() == max_height) + .count(); + let tallest_refs: Vec<&M> = order[..tallest_end].iter().map(|&i| &leaves[i]).collect(); + let mut first_layer = hash_group_salted(&tallest_refs, max_height, &salt_seed, leaf_domain); + first_layer.resize(padded_len_binary(max_height), [0u8; 32]); + + let mut digest_layers = vec![first_layer]; + let mut cursor = tallest_end; + + loop { + let prev_layer = digest_layers.last().unwrap().as_slice(); + if prev_layer.len() <= 1 { + break; + } + let raw_next = prev_layer.len() / 2; + let next_layer_len = raw_next.next_power_of_two(); + + let inject_start = cursor; + while cursor < order.len() + && leaves[order[cursor]].height().next_power_of_two() == next_layer_len + { + cursor += 1; + } + let inject_group = &order[inject_start..cursor]; + + let mut next_digests: Vec<[u8; 32]> = if inject_group.is_empty() { + (0..raw_next) + .into_par_iter() + .map(|i| { + compress_pair(compress_domain, &prev_layer[2 * i], &prev_layer[2 * i + 1]) + }) + .collect() + } else { + let inject_refs: Vec<&M> = inject_group.iter().map(|&i| &leaves[i]).collect(); + let inject_height = inject_refs[0].height(); + let injected = + hash_group_salted(&inject_refs, inject_height, &salt_seed, leaf_domain); + let zero = [0u8; 32]; + (0..raw_next) + .into_par_iter() + .map(|i| { + let parent = compress_pair( + compress_domain, + &prev_layer[2 * i], + &prev_layer[2 * i + 1], + ); + let leaf = if i < inject_height { + &injected[i] + } else { + &zero + }; + compress_pair(compress_domain, &parent, leaf) + }) + .collect() + }; + next_digests.resize(padded_len_binary(raw_next), [0u8; 32]); + digest_layers.push(next_digests); + } + + Self { + leaves, + digest_layers, + salt_seed, + } + } + + fn cap(&self, cap_height: usize) -> MerkleCap { + let num_levels = self.digest_layers.len().saturating_sub(1); + let effective_cap = cap_height.min(num_levels); + let cap_layer = &self.digest_layers[num_levels - effective_cap]; + MerkleCap::new(cap_layer[..(1usize << effective_cap)].to_vec()) + } + + fn max_height(&self) -> usize { + self.leaves + .iter() + .map(Matrix::height) + .max() + .expect("No committed matrices?") + } + + fn matrix_heights(&self) -> Vec { + self.leaves.iter().map(Matrix::height).collect() + } + + fn dimensions(&self) -> Vec { + self.leaves.iter().map(Matrix::dimensions).collect() + } + + fn open_single_proof(&self, index: usize, cap_height: usize) -> Vec<[u8; 32]> { + let num_levels = self.digest_layers.len().saturating_sub(1); + let effective_cap = cap_height.min(num_levels); + let proof_levels = num_levels - effective_cap; + let mut siblings = Vec::with_capacity(proof_levels); + let mut pos = index; + for layer in &self.digest_layers[..proof_levels] { + siblings.push(layer[pos ^ 1]); + pos >>= 1; + } + siblings + } + + fn open_multi_proof(&self, indices: &[usize], cap_height: usize) -> PrunedMerklePaths { + if indices.is_empty() { + return PrunedMerklePaths { + sibling_hashes: Vec::new(), + }; + } + let num_levels = self.digest_layers.len().saturating_sub(1); + let effective_cap = cap_height.min(num_levels); + let proof_levels = num_levels - effective_cap; + let mut frontier: Vec = indices.to_vec(); + frontier.sort_unstable(); + frontier.dedup(); + let mut parents = Vec::with_capacity(frontier.len()); + let mut sibling_hashes = Vec::new(); + for layer in &self.digest_layers[..proof_levels] { + parents.clear(); + let mut at = 0; + while at < frontier.len() { + let first = frontier[at]; + let parent = first >> 1; + let group_start = at; + at += 1; + while at < frontier.len() && (frontier[at] >> 1) == parent { + at += 1; + } + if at - group_start == 1 { + sibling_hashes.push(layer[first ^ 1]); + } + parents.push(parent); + } + core::mem::swap(&mut frontier, &mut parents); + } + PrunedMerklePaths { sibling_hashes } + } + + fn open_batch( + &self, + index: usize, + cap_height: usize, + ) -> (Vec>, HidingBatchProof) { + let heights = self.matrix_heights(); + let max_height = self.max_height(); + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + let log_max_height = log2_ceil_usize(max_height); + let opened_values = self + .leaves + .iter() + .map(|matrix| { + let bits_reduced = log_max_height - log2_ceil_usize(matrix.height()); + matrix + .row(index >> bits_reduced) + .unwrap() + .into_iter() + .collect() + }) + .collect(); + let siblings = self.open_single_proof(index, cap_height); + let salts = open_hiding_batch_salts(&self.salt_seed, &heights, index, cap_height); + (opened_values, HidingBatchProof { salts, siblings }) + } + + fn open_multi_batch( + &self, + indices: &[usize], + cap_height: usize, + ) -> (Vec>>, HidingMultiProof) { + let heights = self.matrix_heights(); + let max_height = self.max_height(); + let log_max_height = log2_ceil_usize(max_height); + let opened_values = indices + .iter() + .map(|&index| { + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + self.leaves + .iter() + .map(|matrix| { + let bits_reduced = log_max_height - log2_ceil_usize(matrix.height()); + matrix + .row(index >> bits_reduced) + .unwrap() + .into_iter() + .collect() + }) + .collect() + }) + .collect(); + let pruned = self.open_multi_proof(indices, cap_height); + let salts = open_hiding_multi_salts(&self.salt_seed, &heights, indices, cap_height); + (opened_values, HidingMultiProof { salts, pruned }) + } +} + +/// Prover data for [`HidingCudaMmcs`], storing only a 32-byte `salt_seed` +/// alongside the committed matrices and Merkle tree (zero salt-matrix memory +/// or VRAM overhead). +pub struct HidingCudaMmcsData(HidingCudaMmcsDataInner); + +enum HidingCudaMmcsDataInner { + Cpu(CpuHidingTree), + Hybrid { + resident: Vec>, + materialize: Box M + Send + Sync>, + committed_matrices: Vec>, + dimensions: Vec, + tree: CudaMixedMerkleTree, + salt_seed: [u8; 32], + }, + Cuda { + resident: Arc>, + materialize: Option Vec + Send + Sync>>, + committed_matrices: OnceLock>, + tree: CudaMixedMerkleTree, + salt_seed: [u8; 32], + }, +} + +/// CUDA-accelerated salted BLAKE3 MMCS for Protocol `v6-zk`. +#[derive(Clone, Debug)] +pub struct HidingCudaMmcs { + cap_height: usize, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, + device_id: i32, +} + +impl HidingCudaMmcs { + /// Creates a Protocol `v6-zk` CUDA hiding MMCS separating salted Merkle + /// leaf hashing (`ZkMerkleLeaf`) from internal compressions + /// (`ZkMerkleCompress`). + pub(crate) fn new_v6_zk(cap_height: usize, device_id: i32) -> Self { + assert!(device_id >= 0, "CUDA device id must be non-negative"); + assert_eq!( + cap_height, 0, + "the CUDA backend currently supports only cap_height = 0" + ); + Self { + cap_height, + leaf_domain: Blake3Domain::ZkMerkleLeaf, + compress_domain: Blake3Domain::ZkMerkleCompress, + device_id, + } + } + + #[inline] + pub const fn cap_height(&self) -> usize { + self.cap_height + } + + #[inline] + pub(crate) const fn device_id(&self) -> i32 { + self.device_id + } + + #[inline] + pub(crate) fn is_cuda_resident(&self, data: &HidingCudaMmcsData) -> bool { + matches!(data.0, HidingCudaMmcsDataInner::Cuda { .. }) + } + + #[inline] + pub(crate) fn resident_arc( + &self, + data: &HidingCudaMmcsData, + ) -> Option>> { + match &data.0 { + HidingCudaMmcsDataInner::Cuda { resident, .. } => Some(Arc::clone(resident)), + HidingCudaMmcsDataInner::Cpu(_) | HidingCudaMmcsDataInner::Hybrid { .. } => None, + } + } + + /// Commits host matrices on CPU using an explicit `salt_seed`. + pub(crate) fn commit_cpu_with_seed>( + &self, + inputs: Vec, + salt_seed: [u8; 32], + ) -> ( + >::Commitment, + HidingCudaMmcsData, + ) { + let tree = CpuHidingTree::build(inputs, self.leaf_domain, self.compress_domain, salt_seed); + let commitment = tree.cap(self.cap_height); + ( + commitment, + HidingCudaMmcsData(HidingCudaMmcsDataInner::Cpu(tree)), + ) + } + + /// Commits device-resident CUDA LDEs with an explicit `salt_seed`, routing + /// any height group exceeding [`MAX_DEVICE_LEAF_ROW_BYTES_ZK`] through + /// host salted leaf hashing and hybrid CUDA Merkle tree construction. + pub(crate) fn commit_cuda_resident_with_seed( + &self, + ldes: Vec, + salt_seed: [u8; 32], + ) -> ( + >::Commitment, + HidingCudaMmcsData>, + ) { + let wide_heights = host_hashed_heights_zk(ldes.iter().map(|lde| Dimensions { + width: lde.width(), + height: lde.height(), + })); + if !wide_heights.is_empty() { + let mut resident: Vec> = Vec::with_capacity(ldes.len()); + let mut host: Vec>> = Vec::with_capacity(ldes.len()); + let mut dimensions = Vec::with_capacity(ldes.len()); + for lde in ldes { + let dims = Dimensions { + width: lde.width(), + height: lde.height(), + }; + dimensions.push(dims); + if wide_heights.contains(&dims.height) { + host.push(Some(lde.to_row_major_matrix())); + resident.push(None); + } else { + host.push(None); + resident.push(Some(lde)); + } + } + let host_digest_groups = + hash_wide_host_groups_salted(&host, &wide_heights, &salt_seed, self.leaf_domain); + let resident_refs: Vec> = + resident.iter().map(Option::as_ref).collect(); + let host_refs: Vec>> = + host.iter().map(Option::as_ref).collect(); + let deferred_dims = vec![None; resident.len()]; + let tree = CudaMixedMerkleTree::from_hybrid_v6zk( + self.device_id, + &resident_refs, + &host_refs, + &deferred_dims, + &host_digest_groups, + &salt_seed, + ); + let commitment = MerkleCap::new(vec![tree.root()]); + let committed_matrices = host + .into_iter() + .map(|mat| { + let cell = OnceLock::new(); + if let Some(mat) = mat { + cell.set(mat).expect("fresh hybrid matrix cell"); + } + cell + }) + .collect(); + return ( + commitment, + HidingCudaMmcsData(HidingCudaMmcsDataInner::Hybrid { + resident, + materialize: Box::new(CudaLde::to_row_major_matrix), + committed_matrices, + dimensions, + tree, + salt_seed, + }), + ); + } + + let ldes = Arc::new(ldes); + let tree = CudaMixedMerkleTree::from_ldes_v6zk(self.device_id, &ldes, &salt_seed); + let commitment = MerkleCap::new(vec![tree.root()]); + let materialize_ldes = Arc::clone(&ldes); + ( + commitment, + HidingCudaMmcsData(HidingCudaMmcsDataInner::Cuda { + resident: ldes, + materialize: Some(Box::new(move || { + materialize_ldes + .iter() + .map(CudaLde::to_row_major_matrix) + .collect() + })), + committed_matrices: OnceLock::new(), + tree, + salt_seed, + }), + ) + } + + /// Uploads host LDEs to CUDA when they fit device row limits and VRAM + /// headroom, committing them with an explicit `salt_seed` while retaining + /// the original host storage for fast re-reads. + pub(crate) fn commit_cuda_storage_with_seed( + &self, + ldes: Vec>, + salt_seed: [u8; 32], + ) -> ( + >::Commitment, + HidingCudaMmcsData>, + ) { + let total_bytes: usize = ldes + .iter() + .map(|m| { + m.height() + .saturating_mul(m.width()) + .saturating_mul(size_of::()) + }) + .sum(); + let (free_bytes, total_device_bytes) = super::device_memory_info(self.device_id); + let min_free = super::minimum_free_bytes(total_device_bytes); + if total_bytes.saturating_add(min_free) > free_bytes + || !host_hashed_heights_zk(ldes.iter().map(Matrix::dimensions)).is_empty() + { + return self.commit_cpu_with_seed(ldes, salt_seed); + } + let resident: Vec = ldes + .iter() + .map(|matrix| CudaLde::from_row_major_matrix(self.device_id, matrix)) + .collect(); + let (commitment, mut data) = self.commit_cuda_resident_with_seed(resident, salt_seed); + if let HidingCudaMmcsDataInner::Cuda { + committed_matrices, .. + } = &mut data.0 + { + let _ = committed_matrices.set(ldes); + } + (commitment, data) + } +} + +fn hash_wide_host_groups_salted( + host_matrices: &[Option>], + wide_heights: &BTreeSet, + salt_seed: &[u8; 32], + leaf_domain: Blake3Domain, +) -> Vec<(usize, Vec<[u8; 32]>)> { + let mut groups: BTreeMap>> = BTreeMap::new(); + for matrix in host_matrices.iter().flatten() { + if wide_heights.contains(&matrix.height()) { + groups.entry(matrix.height()).or_default().push(matrix); + } + } + groups + .into_iter() + .map(|(height, mats)| { + let digests = hash_group_salted(&mats, height, salt_seed, leaf_domain); + (height, digests) + }) + .collect() +} + +fn hybrid_open_row>( + resident: &[Option], + committed_matrices: &[OnceLock], + dimensions: &[Dimensions], + index: usize, +) -> Vec> { + let max_height = dimensions.iter().map(|d| d.height).max().unwrap(); + assert!(index < max_height, "MMCS opening index out of bounds"); + let active_ldes: Vec<&CudaLde> = resident.iter().filter_map(Option::as_ref).collect(); + let mut gpu_rows = if active_ldes.is_empty() { + Vec::new().into_iter() + } else { + mixed_lde_open_row_at_height(active_ldes, max_height, index).into_iter() + }; + resident + .iter() + .enumerate() + .map(|(matrix_index, lde)| { + if lde.is_some() { + gpu_rows.next().unwrap() + } else { + let matrix = committed_matrices[matrix_index] + .get() + .expect("hybrid host matrix missing"); + let row = index >> (max_height.trailing_zeros() - matrix.height().trailing_zeros()); + matrix.row(row).unwrap().into_iter().collect() + } + }) + .collect() +} + +fn hybrid_open_rows>( + resident: &[Option], + committed_matrices: &[OnceLock], + dimensions: &[Dimensions], + indices: &[usize], +) -> Vec>> { + if indices.is_empty() { + return Vec::new(); + } + let max_height = dimensions.iter().map(|d| d.height).max().unwrap(); + assert!(indices.iter().all(|&index| index < max_height)); + let active_ldes: Vec<&CudaLde> = resident.iter().filter_map(Option::as_ref).collect(); + let mut gpu_queries = if active_ldes.is_empty() { + (0..indices.len()) + .map(|_| Vec::new()) + .collect::>() + .into_iter() + } else { + mixed_lde_open_rows_at_height(active_ldes, max_height, indices).into_iter() + }; + indices + .iter() + .map(|&index| { + let mut gpu_rows = gpu_queries.next().unwrap().into_iter(); + resident + .iter() + .enumerate() + .map(|(matrix_index, lde)| { + if lde.is_some() { + gpu_rows.next().unwrap() + } else { + let matrix = committed_matrices[matrix_index] + .get() + .expect("hybrid host matrix missing"); + let row = index + >> (max_height.trailing_zeros() - matrix.height().trailing_zeros()); + matrix.row(row).unwrap().into_iter().collect() + } + }) + .collect() + }) + .collect() +} + +impl Mmcs for HidingCudaMmcs { + type ProverData = HidingCudaMmcsData; + type Commitment = MerkleCap; + type Proof = HidingBatchProof; + type MultiProof = HidingMultiProof; + type Error = MerkleTreeError; + + fn commit>( + &self, + inputs: Vec, + ) -> (Self::Commitment, Self::ProverData) { + let salt_seed = random_seed(); + let all_pow2 = inputs.iter().all(|m| m.height().is_power_of_two()); + let device_hashable = + all_pow2 && host_hashed_heights_zk(inputs.iter().map(Matrix::dimensions)).is_empty(); + let total_cells: usize = inputs + .iter() + .map(|matrix| matrix.height().saturating_mul(matrix.width())) + .sum(); + let total_bytes = total_cells.saturating_mul(size_of::()); + if device_hashable && total_cells > (1 << 18) { + let (free_bytes, total_device_bytes) = super::device_memory_info(self.device_id); + let min_free = super::minimum_free_bytes(total_device_bytes); + if total_bytes.saturating_add(min_free) <= free_bytes { + let resident: Vec = inputs + .iter() + .map(|matrix| { + let values = (0..matrix.height()) + .flat_map(|row| matrix.row(row).unwrap()) + .collect(); + CudaLde::from_row_major_matrix( + self.device_id, + &RowMajorMatrix::new(values, matrix.width()), + ) + }) + .collect(); + let resident = Arc::new(resident); + let tree = + CudaMixedMerkleTree::from_ldes_v6zk(self.device_id, &resident, &salt_seed); + let commitment = MerkleCap::new(vec![tree.root()]); + let committed_matrices = OnceLock::new(); + committed_matrices + .set(inputs) + .ok() + .expect("fresh CUDA matrix cell"); + return ( + commitment, + HidingCudaMmcsData(HidingCudaMmcsDataInner::Cuda { + resident, + materialize: None, + committed_matrices, + tree, + salt_seed, + }), + ); + } + } + self.commit_cpu_with_seed(inputs, salt_seed) + } + + fn open_batch>( + &self, + index: usize, + prover_data: &Self::ProverData, + ) -> BatchOpening { + match &prover_data.0 { + HidingCudaMmcsDataInner::Cpu(tree) => { + let (opened_values, proof) = tree.open_batch(index, self.cap_height); + BatchOpening::new(opened_values, proof) + } + HidingCudaMmcsDataInner::Hybrid { + resident, + committed_matrices, + dimensions, + tree, + salt_seed, + .. + } => { + let heights: Vec = dimensions.iter().map(|d| d.height).collect(); + let opened_values = + hybrid_open_row(resident, committed_matrices, dimensions, index); + let siblings = tree.open_siblings(index); + let salts = open_hiding_batch_salts(salt_seed, &heights, index, self.cap_height); + BatchOpening::new(opened_values, HidingBatchProof { salts, siblings }) + } + HidingCudaMmcsDataInner::Cuda { + resident, + tree, + salt_seed, + .. + } => { + let heights: Vec = resident.iter().map(CudaLde::height).collect(); + let opened_values = mixed_lde_open_row(resident, index); + let siblings = tree.open_siblings(index); + let salts = open_hiding_batch_salts(salt_seed, &heights, index, self.cap_height); + BatchOpening::new(opened_values, HidingBatchProof { salts, siblings }) + } + } + } + + fn get_matrices<'a, M: Matrix>( + &self, + prover_data: &'a Self::ProverData, + ) -> Vec<&'a M> { + match &prover_data.0 { + HidingCudaMmcsDataInner::Cpu(tree) => tree.leaves.iter().collect(), + HidingCudaMmcsDataInner::Hybrid { + resident, + materialize, + committed_matrices, + .. + } => resident + .iter() + .enumerate() + .map(|(index, lde)| { + if let Some(lde) = lde.as_ref() { + committed_matrices[index].get_or_init(|| materialize(lde)) + } else { + committed_matrices[index] + .get() + .expect("hybrid host matrix missing") + } + }) + .collect(), + HidingCudaMmcsDataInner::Cuda { + committed_matrices, + materialize, + .. + } => committed_matrices + .get_or_init(|| { + materialize + .as_ref() + .expect("CUDA matrices have no materializer")() + }) + .iter() + .collect(), + } + } + + fn get_matrix_heights>( + &self, + prover_data: &Self::ProverData, + ) -> Vec { + match &prover_data.0 { + HidingCudaMmcsDataInner::Cpu(tree) => tree.matrix_heights(), + HidingCudaMmcsDataInner::Hybrid { dimensions, .. } => { + dimensions.iter().map(|d| d.height).collect() + } + HidingCudaMmcsDataInner::Cuda { resident, .. } => { + resident.iter().map(CudaLde::height).collect() + } + } + } + + fn get_max_height>(&self, prover_data: &Self::ProverData) -> usize { + match &prover_data.0 { + HidingCudaMmcsDataInner::Cpu(tree) => tree.max_height(), + HidingCudaMmcsDataInner::Hybrid { dimensions, .. } => { + dimensions.iter().map(|d| d.height).max().unwrap() + } + HidingCudaMmcsDataInner::Cuda { resident, .. } => { + resident.iter().map(CudaLde::height).max().unwrap() + } + } + } + + fn verify_batch( + &self, + commit: &Self::Commitment, + dimensions: &[Dimensions], + index: usize, + batch_opening: BatchOpeningRef<'_, Goldilocks, Self>, + ) -> Result<(), Self::Error> { + verify_hiding_batch( + self.cap_height, + self.leaf_domain, + self.compress_domain, + commit, + dimensions, + index, + batch_opening.opened_values, + batch_opening.opening_proof, + ) + } + + fn open_multi_batch>( + &self, + indices: &[usize], + prover_data: &Self::ProverData, + ) -> (Vec>>, Self::MultiProof) { + match &prover_data.0 { + HidingCudaMmcsDataInner::Cpu(tree) => tree.open_multi_batch(indices, self.cap_height), + HidingCudaMmcsDataInner::Hybrid { + resident, + committed_matrices, + dimensions, + tree, + salt_seed, + .. + } => { + let heights: Vec = dimensions.iter().map(|d| d.height).collect(); + let opened_values = + hybrid_open_rows(resident, committed_matrices, dimensions, indices); + let pruned = tree.open_pruned_siblings(indices); + let salts = open_hiding_multi_salts(salt_seed, &heights, indices, self.cap_height); + (opened_values, HidingMultiProof { salts, pruned }) + } + HidingCudaMmcsDataInner::Cuda { + resident, + tree, + salt_seed, + .. + } => { + let heights: Vec = resident.iter().map(CudaLde::height).collect(); + let opened_values = if indices.is_empty() { + Vec::new() + } else { + mixed_lde_open_rows(resident, indices) + }; + let pruned = tree.open_pruned_siblings(indices); + let salts = open_hiding_multi_salts(salt_seed, &heights, indices, self.cap_height); + (opened_values, HidingMultiProof { salts, pruned }) + } + } + } + + fn verify_multi_batch + PartialEq>( + &self, + commit: &Self::Commitment, + dimensions: &[Dimensions], + indices: &[usize], + opened_values: &[Vec], + proof: &Self::MultiProof, + ) -> Result<(), Self::Error> { + verify_hiding_multi_batch( + self.cap_height, + self.leaf_domain, + self.compress_domain, + commit, + dimensions, + indices, + opened_values, + proof, + ) + } +} + +impl CapValidatingMmcs for HidingCudaMmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) + } + + fn empty_multi_proof() -> Self::MultiProof { + HidingMultiProof { + salts: Vec::new(), + pruned: PrunedMerklePaths { + sibling_hashes: Vec::new(), + }, + } + } +} + +/// Device-resident salted FRI commit-phase round holding the codeword, Merkle +/// tree, arity, and 32-byte `salt_seed` (zero salt-matrix VRAM overhead). +#[doc(hidden)] +pub struct HidingCudaFriRound { + pub(crate) codeword: CudaLde, + pub(crate) tree: CudaMixedMerkleTree, + pub(crate) arity: usize, + pub(crate) salt_seed: [u8; 32], +} + +/// Trait implemented by CUDA hiding FRI commit-phase MMCS types. +#[doc(hidden)] +pub trait HidingCudaFriMmcs: Mmcs { + fn commit_cuda_fri_hiding( + &self, + codeword: CudaLde, + log_arity: usize, + ) -> (Self::Commitment, HidingCudaFriRound); + + fn open_cuda_fri_hiding_batch( + &self, + round: &HidingCudaFriRound, + rows: &[usize], + ) -> (Vec>, Self::MultiProof); +} + +impl HidingCudaFriMmcs + for ExtensionMmcs +where + Challenge: ExtensionField, +{ + fn commit_cuda_fri_hiding( + &self, + codeword: CudaLde, + log_arity: usize, + ) -> (Self::Commitment, HidingCudaFriRound) { + let arity = 1usize << log_arity; + let salt_seed = random_seed(); + let tree = CudaMixedMerkleTree::from_fri_codeword_v6zk(&codeword, arity, &salt_seed); + let commitment = MerkleCap::new(vec![tree.root()]); + ( + commitment, + HidingCudaFriRound { + codeword, + tree, + arity, + salt_seed, + }, + ) + } + + fn open_cuda_fri_hiding_batch( + &self, + round: &HidingCudaFriRound, + rows: &[usize], + ) -> (Vec>, Self::MultiProof) { + let codeword_rows = rows + .iter() + .flat_map(|&row| (0..round.arity).map(move |column| row * round.arity + column)) + .collect_vec(); + let opened = round.codeword.rows(&codeword_rows); + let opened_rows = opened + .chunks_exact(round.arity) + .map(|query_rows| { + query_rows + .iter() + .map(|row| { + Challenge::from_basis_coefficients_slice(row).expect("extension row") + }) + .collect() + }) + .collect(); + let tree_height = round.codeword.height() / round.arity; + let pruned = round.tree.open_pruned_siblings(rows); + // CUDA backend enforces `cap_height == 0` on construction. + let salts = open_hiding_multi_salts(&round.salt_seed, &[tree_height], rows, 0); + (opened_rows, HidingMultiProof { salts, pruned }) + } +} + +#[cfg(test)] +mod tests { + use p3_field::PrimeCharacteristicRing; + + use super::*; + use crate::types::{ExtVal2, ExtVal3}; + + fn test_matrix(height: usize, width: usize, offset: usize) -> RowMajorMatrix { + RowMajorMatrix::new( + (0..height * width) + .map(|i| Goldilocks::from_usize(offset + i)) + .collect(), + width, + ) + } + + #[test] + fn wide_height_groups_zk_leave_room_for_leaf_salt() { + let d = |width, height| Dimensions { width, height }; + // 4094 Goldilocks columns + 16-byte leaf salt = exactly 32 KiB. + assert!(host_hashed_heights_zk([d(4094, 8)]).is_empty()); + assert_eq!( + host_hashed_heights_zk([d(4095, 8)]) + .into_iter() + .collect::>(), + vec![8] + ); + assert_eq!( + host_hashed_heights_zk([d(3000, 16), d(1095, 16), d(10, 4)]) + .into_iter() + .collect::>(), + vec![16] + ); + } + + #[test] + #[should_panic(expected = "cap_height = 0")] + fn cuda_v6zk_rejects_nonzero_merkle_caps() { + let _ = HidingCudaMmcs::new_v6_zk(1, 0); + } + + #[test] + fn cuda_v6zk_from_ldes_matches_cpu_salted_tree() { + let mmcs = HidingCudaMmcs::new_v6_zk(0, 0); + let salt_seed = [0x5Au8; 32]; + let matrices = vec![ + test_matrix(32, 5, 1), + test_matrix(16, 3, 100), + test_matrix(32, 2, 300), + test_matrix(8, 7, 500), + ]; + let dims: Vec = matrices.iter().map(Matrix::dimensions).collect(); + + let (cpu_commit, cpu_data) = mmcs.commit_cpu_with_seed(matrices.clone(), salt_seed); + let ldes: Vec = matrices + .iter() + .map(|m| CudaLde::from_row_major_matrix(mmcs.device_id(), m)) + .collect(); + let (gpu_commit, gpu_data) = mmcs.commit_cuda_resident_with_seed(ldes, salt_seed); + + assert_eq!( + gpu_commit, cpu_commit, + "GPU v6-zk Merkle root must match CPU salted tree bit-for-bit" + ); + + for idx in [0usize, 1, 7, 19, 31] { + let cpu_open = mmcs.open_batch(idx, &cpu_data); + let gpu_open = mmcs.open_batch(idx, &gpu_data); + assert_eq!(gpu_open.opened_values, cpu_open.opened_values); + assert_eq!(gpu_open.opening_proof, cpu_open.opening_proof); + mmcs.verify_batch( + &gpu_commit, + &dims, + idx, + BatchOpeningRef::new(&gpu_open.opened_values, &gpu_open.opening_proof), + ) + .expect("single-batch verification must pass"); + } + + let query_indices = [0usize, 3, 3, 15, 29]; + let (cpu_rows, cpu_proof) = mmcs.open_multi_batch(&query_indices, &cpu_data); + let (gpu_rows, gpu_proof) = mmcs.open_multi_batch(&query_indices, &gpu_data); + assert_eq!(gpu_rows, cpu_rows); + assert_eq!(gpu_proof, cpu_proof); + mmcs.verify_multi_batch(&gpu_commit, &dims, &query_indices, &gpu_rows, &gpu_proof) + .expect("multi-batch verification must pass"); + } + + #[test] + fn cuda_v6zk_wide_and_hybrid_group_match_cpu_salted_tree() { + let mmcs = HidingCudaMmcs::new_v6_zk(0, 0); + let salt_seed = [0xA3u8; 32]; + let matrices = vec![ + test_matrix(16, 12, 7), + test_matrix(8, 4100, 99), + test_matrix(16, 5, 200), + ]; + let dims: Vec = matrices.iter().map(Matrix::dimensions).collect(); + + // Exercise `hash_hybrid_height_group_v6zk` on a resident+host pair at height 16. + let lde0 = CudaLde::from_row_major_matrix(mmcs.device_id(), &matrices[0]); + let hybrid_digests = CudaMixedMerkleTree::hash_hybrid_height_group_v6zk( + mmcs.device_id(), + &[Some(&lde0), None], + &[None, Some(&matrices[2])], + &salt_seed, + ); + let expected_digests = hash_group_salted( + &[&matrices[0], &matrices[2]], + 16, + &salt_seed, + Blake3Domain::ZkMerkleLeaf, + ); + assert_eq!(hybrid_digests, expected_digests); + + // Exercise wide height-group (> 4094 cols) automatic hybrid commit. + let (cpu_commit, cpu_data) = mmcs.commit_cpu_with_seed(matrices.clone(), salt_seed); + let ldes: Vec = matrices + .iter() + .map(|m| CudaLde::from_row_major_matrix(mmcs.device_id(), m)) + .collect(); + let (gpu_commit, gpu_data) = mmcs.commit_cuda_resident_with_seed(ldes, salt_seed); + assert_eq!(gpu_commit, cpu_commit); + + let indices = [0usize, 5, 11, 15]; + let (cpu_rows, cpu_proof) = mmcs.open_multi_batch(&indices, &cpu_data); + let (gpu_rows, gpu_proof) = mmcs.open_multi_batch(&indices, &gpu_data); + assert_eq!(gpu_rows, cpu_rows); + assert_eq!(gpu_proof, cpu_proof); + mmcs.verify_multi_batch(&gpu_commit, &dims, &indices, &gpu_rows, &gpu_proof) + .expect("wide-group hybrid verification must pass"); + } + + #[test] + fn cuda_v6zk_fri_merkle_verifies_ext2_and_ext3() { + let base_mmcs = HidingCudaMmcs::new_v6_zk(0, 0); + + let ext3_mmcs: ExtensionMmcs = + ExtensionMmcs::new(base_mmcs.clone()); + let cw3 = test_matrix(64, 3, 17); + let cw3_gpu = CudaLde::from_row_major_matrix(base_mmcs.device_id(), &cw3); + let (commit3, round3) = ext3_mmcs.commit_cuda_fri_hiding(cw3_gpu, 1); + let rows = [0usize, 5, 13, 31]; + let (opened3, mut proof3) = ext3_mmcs.open_cuda_fri_hiding_batch(&round3, &rows); + let opened3_wrapped: Vec>> = + opened3.into_iter().map(|row| vec![row]).collect(); + let dims3 = [Dimensions { + width: 2, + height: 32, + }]; + ext3_mmcs + .verify_multi_batch(&commit3, &dims3, &rows, &opened3_wrapped, &proof3) + .expect("CUDA v6-zk ExtVal3 FRI Merkle opening must verify"); + proof3.salts[0][0][0] ^= 1; + assert!( + ext3_mmcs + .verify_multi_batch(&commit3, &dims3, &rows, &opened3_wrapped, &proof3) + .is_err(), + "tampered FRI leaf salt must fail verification" + ); + + let ext2_mmcs: ExtensionMmcs = + ExtensionMmcs::new(base_mmcs); + let cw2 = test_matrix(64, 2, 41); + let cw2_gpu = CudaLde::from_row_major_matrix(0, &cw2); + let (commit2, round2) = ext2_mmcs.commit_cuda_fri_hiding(cw2_gpu, 1); + let (opened2, proof2) = ext2_mmcs.open_cuda_fri_hiding_batch(&round2, &rows); + let opened2_wrapped: Vec>> = + opened2.into_iter().map(|row| vec![row]).collect(); + ext2_mmcs + .verify_multi_batch(&commit2, &dims3, &rows, &opened2_wrapped, &proof2) + .expect("CUDA v6-zk ExtVal2 FRI Merkle opening must verify"); + } +} diff --git a/src/cuda/hiding_pcs.rs b/src/cuda/hiding_pcs.rs new file mode 100644 index 0000000..440638a --- /dev/null +++ b/src/cuda/hiding_pcs.rs @@ -0,0 +1,975 @@ +//! CUDA hiding 2× interleaved odd-coset FRI PCS (`v6-zk`, ePrint 2024/1037). +//! +//! Mirrors the CPU [`crate::p3_adapter::spill_zk::HidingSpillableTwoAdicFriPcs`] +//! semantics and wire format byte-for-byte while executing coset LDEs, salted +//! Merkle tree construction, barycentric OOD interpolation, reduced-opening +//! accumulation, and FRI commit-phase folding on CUDA. + +use core::iter; +use core::marker::PhantomData; +use std::borrow::Cow; + +use itertools::{Itertools, izip}; +use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; +use p3_commit::{Mmcs, OpenedValues, Pcs, PeriodicLdeTable}; +use p3_dft::{Radix2DFTSmallBatch, Radix2DitParallel, TwoAdicSubgroupDft}; +use p3_field::coset::TwoAdicMultiplicativeCoset; +use p3_field::{ + ExtensionField, Field, PackedFieldExtension, PrimeCharacteristicRing, PrimeField64, + TwoAdicField, dot_product, +}; +use p3_fri::verifier::FriError; +use p3_fri::{ + BatchMultiOpening, CommitPhaseMultiStep, CommitmentWithOpeningPoints, FriParameters, FriProof, + ProverDataWithOpeningPoints, TwoAdicFriFolding, TwoAdicFriFoldingForMmcs, + build_periodic_lde_table_two_adic, compute_log_arity_for_round, prover, +}; +use p3_goldilocks::Goldilocks; +use p3_matrix::Matrix; +use p3_matrix::bitrev::{BitReversedMatrixView, BitReversibleMatrix}; +use p3_matrix::dense::{RowMajorMatrix, RowMajorMatrixCow}; +use p3_matrix::interpolation::{Interpolate, compute_adjusted_weights}; +use p3_maybe_rayon::prelude::*; +use p3_util::linear_map::LinearMap; +use p3_util::{log2_strict_usize, reverse_slice_index_bits}; +use tracing::debug_span; + +use super::hiding_mmcs::{HidingCudaFriMmcs, HidingCudaMmcs}; +use super::pcs::{ + CudaPcsDft, bit_reversed_coset, compute_inverse_denominators, cuda_ext_degree_and_w, + ext_from_goldilocks, ext_to_goldilocks, +}; +use super::{ + CudaFriWorkspace, CudaInterpolationTasks, CudaLde, CudaReducedOpening, CudaReductionTasks, +}; +use crate::p3_adapter::cap::{CapValidatingMmcs, validate_fri_commitment_caps}; +use crate::p3_adapter::fri_batching::{ + FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, +}; +use crate::p3_adapter::zk::{interleave_random_rows, preprocessed_salt_seed, random_seed}; + +/// CUDA hiding 2× interleaved odd-coset FRI PCS (`const ZK: bool = true`) for +/// Protocol `v6-zk`. +#[derive(Clone, Debug)] +pub struct HidingCudaTwoAdicFriPcs { + pub(crate) dft: Dft, + pub(crate) mmcs: InputMmcs, + pub(crate) fri: FriParameters, + pub(crate) batching: FriBatching, + _phantom: PhantomData, +} + +impl HidingCudaTwoAdicFriPcs { + pub const fn new(dft: Dft, mmcs: InputMmcs, fri: FriParameters) -> Self { + Self { + dft, + mmcs, + fri, + batching: FriBatching::Horner, + _phantom: PhantomData, + } + } + + /// Configures the FRI opening batching strategy (`Horner` or `Tensor`). + pub const fn with_batching(mut self, batching: FriBatching) -> Self { + self.batching = batching; + self + } +} + +#[allow(clippy::too_many_arguments)] +fn prove_fri_cuda_resident_hiding( + params: &FriParameters, + mut inputs: Vec, + challenger: &mut Challenger, + log_global_max_height: usize, + prover_data_with_opening_points: &[ProverDataWithOpeningPoints< + '_, + Challenge, + InputMmcs::ProverData>, + >], + input_mmcs: &InputMmcs, + ext_w: Goldilocks, + ext_degree: usize, +) -> FriProof>> +where + Challenge: ExtensionField, + InputMmcs: Mmcs, + FriMmcs: HidingCudaFriMmcs, + Challenger: FieldChallenger + GrindingChallenger + CanObserve, +{ + assert!(!inputs.is_empty()); + assert!(ext_degree == 2 || ext_degree == 3); + assert!( + params.num_queries > 0, + "num_queries must be at least 1 for FRI soundness" + ); + assert!( + params.max_log_arity > 0, + "max_log_arity must be at least 1 to guarantee folding progress" + ); + assert!( + inputs + .windows(2) + .all(|pair| pair[0].height() > pair[1].height()), + "inputs are not sorted in strictly descending order of height" + ); + assert_eq!( + log_global_max_height, + log2_strict_usize(inputs[0].height()), + "log_global_max_height must match the largest input height" + ); + let log_min_height = log2_strict_usize(inputs.last().unwrap().height()); + if params.log_final_poly_len > 0 { + assert!(log_min_height > params.log_final_poly_len + params.log_blowup); + } + + let mut codeword = inputs.remove(0).into_lde(); + let mut commits = Vec::new(); + let mut rounds = Vec::new(); + let mut log_arities = Vec::new(); + let mut commit_pow_witnesses = Vec::new(); + let final_height = params.blowup() * params.final_poly_len(); + + while codeword.height() > final_height { + let log_height = log2_strict_usize(codeword.height()); + let next_log_height = inputs + .first() + .map(|input| log2_strict_usize(input.height())); + let log_arity = compute_log_arity_for_round( + log_height, + next_log_height, + params.log_blowup + params.log_final_poly_len, + params.max_log_arity, + ); + let (commitment, round) = tracing::info_span!("stark/fri_round_commit") + .in_scope(|| params.mmcs.commit_cuda_fri_hiding(codeword, log_arity)); + challenger.observe(commitment.clone()); + commits.push(commitment); + commit_pow_witnesses.push( + tracing::info_span!("stark/fri_commit_grind") + .in_scope(|| challenger.grind(params.commit_proof_of_work_bits)), + ); + let beta: Challenge = challenger.sample_algebra_element(); + let mut beta_step = beta; + let mut betas_flat = Vec::with_capacity(log_arity * ext_degree); + for _ in 0..log_arity { + let (buf, d) = ext_to_goldilocks::(beta_step, ext_degree); + betas_flat.extend_from_slice(&buf[..d]); + beta_step = beta_step.square(); + } + let folded_height = round.codeword.height() >> log_arity; + let add_next = inputs + .first() + .is_some_and(|input| input.height() == folded_height); + let (beta_power_buf, _) = + ext_to_goldilocks::(beta.exp_power_of_2(log_arity), ext_degree); + let g_inv = Goldilocks::two_adic_generator(log_height).inverse(); + codeword = round.codeword.fri_fold( + add_next.then(|| &inputs[0]), + &betas_flat, + log_arity, + &beta_power_buf[..ext_degree], + g_inv, + ext_w, + ext_degree, + ); + if add_next { + inputs.remove(0); + } + rounds.push(round); + log_arities.push(log_arity); + } + assert!(inputs.is_empty()); + + let final_matrix = codeword.to_row_major_matrix(); + let mut final_values = final_matrix + .values + .chunks_exact(ext_degree) + .take(params.final_poly_len()) + .map(ext_from_goldilocks::) + .collect_vec(); + reverse_slice_index_bits(&mut final_values); + let final_poly = Radix2DFTSmallBatch::default().idft_algebra(final_values); + challenger.observe_algebra_slice(&final_poly); + + for &log_arity in &log_arities { + challenger.observe(Goldilocks::from_usize(log_arity)); + } + let _query_span = tracing::info_span!("stark/fri_queries").entered(); + let query_pow_witness = tracing::info_span!("stark/fri_query_grind") + .in_scope(|| challenger.grind(params.query_proof_of_work_bits)); + let query_indices = iter::repeat_with(|| challenger.sample_bits(log_global_max_height)) + .take(params.num_queries) + .collect_vec(); + let input_openings_span = tracing::info_span!("stark/fri_input_openings").entered(); + let input_openings = prover_data_with_opening_points + .iter() + .map(|(data, _)| { + let log_height = log2_strict_usize(input_mmcs.get_max_height(data)); + let indices = query_indices + .iter() + .map(|&index| index >> (log_global_max_height - log_height)) + .collect_vec(); + let (opened_values, opening_proof) = input_mmcs.open_multi_batch(&indices, data); + BatchMultiOpening { + opened_values, + opening_proof, + } + }) + .collect_vec(); + drop(input_openings_span); + + let mut current_indices = query_indices; + let commit_phase_openings = rounds + .iter() + .zip(&log_arities) + .map(|(round, &log_arity)| { + let arity = 1usize << log_arity; + let positions = current_indices + .iter() + .map(|&index| index % arity) + .collect_vec(); + let group_indices = current_indices + .iter() + .map(|&index| index >> log_arity) + .collect_vec(); + let (opened_rows, opening_proof) = + tracing::info_span!("stark/fri_commit_phase_opening").in_scope(|| { + params + .mmcs + .open_cuda_fri_hiding_batch(round, &group_indices) + }); + current_indices = group_indices; + let sibling_values = positions + .into_iter() + .zip(opened_rows) + .map(|(index_in_group, opened)| { + assert_eq!(opened.len(), arity, "FRI opening has the wrong arity"); + opened + .into_iter() + .enumerate() + .filter_map(|(column, value)| (column != index_in_group).then_some(value)) + .collect() + }) + .collect_vec(); + CommitPhaseMultiStep { + log_arity: u8::try_from(log_arity).expect("FRI arity exceeds u8"), + sibling_values, + opening_proof, + } + }) + .collect_vec(); + + FriProof { + commit_phase_commits: commits, + commit_pow_witnesses, + input_openings, + commit_phase_openings, + final_poly, + query_pow_witness, + } +} + +impl HidingCudaTwoAdicFriPcs +where + Dft: TwoAdicSubgroupDft + CudaPcsDft + Sync, +{ + /// Commits public preprocessed matrices onto the `2N · B` LDE coset WITHOUT + /// random rows and using the deterministic public [`preprocessed_salt_seed`] + /// so independent prover and verifier setups (including CPU and CUDA) produce + /// identical `preprocessed_commit` roots. + pub(crate) fn commit_preprocessed( + &self, + evaluations: impl IntoIterator< + Item = ( + TwoAdicMultiplicativeCoset, + RowMajorMatrix, + ), + >, + ) -> ( + >::Commitment, + >::ProverData>, + ) { + let evals: Vec<_> = evaluations.into_iter().collect(); + self.commit_inner(evals, false, preprocessed_salt_seed()) + } + + fn commit_inner( + &self, + evaluations: Vec<( + TwoAdicMultiplicativeCoset, + RowMajorMatrix, + )>, + blind_rows: bool, + salt_seed: [u8; 32], + ) -> ( + >::Commitment, + >::ProverData>, + ) { + assert!( + !evaluations.is_empty(), + "commit requires at least one matrix" + ); + let added_bits = if blind_rows { + self.fri.log_blowup + } else { + self.fri.log_blowup + 1 + }; + let prepared: Vec<( + TwoAdicMultiplicativeCoset, + RowMajorMatrix, + )> = evaluations + .into_iter() + .map(|(domain, evals)| { + assert_eq!(domain.size(), evals.height()); + let mat = if blind_rows { + interleave_random_rows(&evals) + } else { + evals + }; + (domain, mat) + }) + .collect(); + + let source_cells: usize = prepared + .iter() + .map(|(_, mat)| mat.height().saturating_mul(mat.width())) + .sum(); + let max_transform_workspace = prepared + .iter() + .map(|(domain, mat)| { + self.dft.coset_lde_workspace_bytes( + mat.height(), + mat.width(), + added_bits, + Goldilocks::GENERATOR / domain.shift(), + ) + }) + .max() + .unwrap_or(0); + let (initial_free, total_bytes) = super::device_memory_info(self.mmcs.device_id()); + let minimum_free = super::minimum_free_bytes(total_bytes); + let lde_bytes = source_cells + .saturating_mul(size_of::()) + .checked_shl(u32::try_from(added_bits).expect("LDE blowup exceeds u32")) + .unwrap_or(usize::MAX); + + if lde_bytes + .saturating_add(minimum_free) + .saturating_add(max_transform_workspace) + > initial_free + { + let ldes: Vec> = prepared + .into_par_iter() + .map(|(domain, evals)| { + let shift = Goldilocks::GENERATOR / domain.shift(); + if let Some(lde) = self.dft.try_coset_lde_batch_host(&evals, added_bits, shift) + { + return lde; + } + let cpu = Radix2DitParallel::::default(); + let mut lde = cpu + .coset_lde_batch(evals, added_bits, shift) + .bit_reverse_rows() + .to_row_major_matrix(); + lde.values.par_iter_mut().for_each(|v| { + *v = Goldilocks::from_u64(v.as_canonical_u64()); + }); + lde + }) + .collect(); + return self.mmcs.commit_cpu_with_seed(ldes, salt_seed); + } + + let mut ldes = Vec::with_capacity(prepared.len()); + for (domain, evals) in &prepared { + let shift = Goldilocks::GENERATOR / domain.shift(); + let lde = self.dft.coset_lde_batch_resident(evals, added_bits, shift); + // SAFETY: `coset_lde_batch_resident` completed synchronously; `v6-zk` + // does not retain separate 1× GPU trace buffers after LDE creation. + unsafe { lde.release_trace() }; + ldes.push(lde); + } + self.mmcs.commit_cuda_resident_with_seed(ldes, salt_seed) + } + + fn re_evaluate_from_lde<'a>( + &self, + lde_mat: RowMajorMatrix, + poly_height: usize, + domain: TwoAdicMultiplicativeCoset, + ) -> BitReversedMatrixView> { + let mut coeffs = self.dft.coset_idft_batch(lde_mat, Goldilocks::GENERATOR); + let width = coeffs.width(); + coeffs.values.truncate(poly_height * width); + let target_size = domain.size(); + if target_size >= poly_height { + coeffs.values.resize(target_size * width, Goldilocks::ZERO); + } else { + // Fold modulo `(X^m - shift^m)` so evaluating a degree `< 2N` blinded + // polynomial on a smaller coset `shift * H_m` (e.g. `H_N`) is exact. + debug_assert!(poly_height.is_multiple_of(target_size)); + let blocks = poly_height / target_size; + let shift_pow_m = domain + .shift() + .exp_u64(u64::try_from(target_size).expect("domain size exceeds u64")); + let mut factor = shift_pow_m; + for b in 1..blocks { + let src_off = b * target_size * width; + for i in 0..(target_size * width) { + let v = coeffs.values[src_off + i]; + coeffs.values[i] += factor * v; + } + factor *= shift_pow_m; + } + coeffs.values.truncate(target_size * width); + } + let result = self + .dft + .coset_dft_batch(coeffs, domain.shift()) + .bit_reverse_rows() + .to_row_major_matrix(); + let result_width = result.width(); + RowMajorMatrixCow::new(Cow::Owned(result.values), result_width).bit_reverse_rows() + } +} + +impl Pcs + for HidingCudaTwoAdicFriPcs +where + Dft: TwoAdicSubgroupDft + CudaPcsDft + Sync, + FriMmcs: CapValidatingMmcs + HidingCudaFriMmcs, + Challenge: ExtensionField, + Challenger: FieldChallenger + + CanObserve + + GrindingChallenger, +{ + type Domain = TwoAdicMultiplicativeCoset; + type Commitment = >::Commitment; + type ProverData = >::ProverData>; + type EvaluationsOnDomain<'a> = BitReversedMatrixView>; + type Proof = FriProof< + Challenge, + FriMmcs, + Goldilocks, + Vec>, + >; + type Error = FriError>::Error>; + const ZK: bool = true; + + fn natural_domain_for_degree(&self, degree: usize) -> Self::Domain { + TwoAdicMultiplicativeCoset::new(Goldilocks::ONE, log2_strict_usize(degree)).unwrap() + } + + fn log_max_lde_height(&self) -> usize { + Goldilocks::TWO_ADICITY + } + + fn commit( + &self, + evaluations: impl IntoIterator)>, + ) -> (Self::Commitment, Self::ProverData) { + let evals: Vec<_> = evaluations.into_iter().collect(); + self.commit_inner(evals, true, random_seed()) + } + + fn get_quotient_ldes( + &self, + evaluations: impl IntoIterator)>, + _num_chunks: usize, + ) -> Vec> { + evaluations + .into_iter() + .map(|(domain, evals)| { + assert_eq!(domain.size(), evals.height()); + let interleaved = interleave_random_rows(&evals); + let shift = Goldilocks::GENERATOR / domain.shift(); + self.dft + .coset_lde_batch(interleaved, self.fri.log_blowup, shift) + .bit_reverse_rows() + .to_row_major_matrix() + }) + .collect() + } + + fn commit_ldes( + &self, + ldes: Vec>, + ) -> (Self::Commitment, Self::ProverData) { + let min_height = 1usize << (self.fri.log_blowup + 1); + for lde in &ldes { + assert!( + lde.height() >= min_height, + "committed ZK LDE height {} is smaller than 2 * blowup ({min_height})", + lde.height() + ); + } + self.mmcs.commit_cuda_storage_with_seed(ldes, random_seed()) + } + + fn get_evaluations_on_domain<'a>( + &self, + prover_data: &'a Self::ProverData, + idx: usize, + domain: Self::Domain, + ) -> Self::EvaluationsOnDomain<'a> { + let lde = self.mmcs.get_matrices(prover_data)[idx]; + if domain.shift() == Goldilocks::GENERATOR && lde.height() >= domain.size() { + return lde.split_rows(domain.size()).0.as_cow().bit_reverse_rows(); + } + let poly_height = lde.height() >> self.fri.log_blowup; + let lde_mat = lde.as_view().bit_reverse_rows().to_row_major_matrix(); + self.re_evaluate_from_lde(lde_mat, poly_height, domain) + } + + fn open( + &self, + commitment_data_with_opening_points: Vec< + ProverDataWithOpeningPoints<'_, Challenge, Self::ProverData>, + >, + challenger: &mut Challenger, + ) -> (OpenedValues, Self::Proof) { + // Fast path: keep all GPU-resident commitments on device through + // barycentric OOD interpolation, reduced-opening accumulation, and + // salted FRI commit-phase folding. + if commitment_data_with_opening_points + .iter() + .all(|(data, _)| self.mmcs.is_cuda_resident(data)) + { + let resident_rounds = commitment_data_with_opening_points + .iter() + .map(|(data, points)| (self.mmcs.resident_arc(data).unwrap(), points)) + .collect_vec(); + let resident_max_height = resident_rounds + .iter() + .flat_map(|(ldes, _)| ldes.iter()) + .map(CudaLde::height) + .max() + .unwrap_or(0); + let final_fri_height = self.fri.blowup() * self.fri.final_poly_len(); + if resident_max_height > 1024 && resident_max_height > final_fri_height { + let _resident_guard = tracing::info_span!("stark/fri_resident_zk").entered(); + let device_id = self.mmcs.device_id(); + let (ext_degree, ext_w) = cuda_ext_degree_and_w::(); + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for (ldes, points) in &resident_rounds { + for (lde, ps) in ldes.iter().zip(points.iter()) { + if !ps.is_empty() { + opened_max_width = opened_max_width.max(lde.width()); + let lh = log2_strict_usize(lde.height()); + openings_per_height[lh] += ps.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); + let log_global_max_height = log2_strict_usize(resident_max_height); + let coset_gold = bit_reversed_coset::(log_global_max_height); + let mut max_log: LinearMap = LinearMap::new(); + for (ldes, points) in &resident_rounds { + for (lde, ps) in ldes.iter().zip(points.iter()) { + for &z in ps { + if let Some(h) = max_log.get_mut(&z) { + *h = (*h).max(log2_strict_usize(lde.height())); + } else { + max_log.insert(z, log2_strict_usize(lde.height())); + } + } + } + } + let mut inv_offsets = LinearMap::new(); + let mut inverse_points = Vec::new(); + let mut inverse_counts = Vec::new(); + let mut inverse_count = 0usize; + for (point, lh) in max_log { + inv_offsets.insert(point, inverse_count); + let (buf, d) = ext_to_goldilocks::(point, ext_degree); + inverse_points.extend_from_slice(&buf[..d]); + let count = 1usize << lh; + inverse_counts.push(count); + inverse_count += count; + } + let mut workspace = CudaFriWorkspace::new( + device_id, + &inverse_points, + &inverse_counts, + &coset_gold, + ext_w, + ext_degree, + ); + let mut interpolation_tasks = CudaInterpolationTasks::new(ext_degree); + let mut output_count = 0usize; + let layouts = resident_rounds + .iter() + .map(|(ldes, points)| { + ldes.iter() + .zip(points.iter()) + .map(|(lde, ps)| { + let h = lde.height() >> self.fri.log_blowup; + let lh = log2_strict_usize(h); + ps.iter() + .map(|&point| { + let offset = output_count; + output_count += lde.width(); + let shift_pow = Goldilocks::GENERATOR.exp_power_of_2(lh); + let scale = (point.exp_power_of_2(lh) - shift_pow) + * (Goldilocks::from_usize(h) * shift_pow).inverse(); + let (scale_buf, d) = + ext_to_goldilocks::( + scale, ext_degree, + ); + interpolation_tasks.push( + lde, + h, + *inv_offsets.get(&point).unwrap(), + offset, + &scale_buf[..d], + ); + (offset, lde.width()) + }) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec(); + let interpolated = tracing::info_span!("stark/fri_interpolate") + .in_scope(|| workspace.interpolate(&interpolation_tasks, output_count, ext_w)); + let all_opened_values = layouts + .into_iter() + .map(|round| { + round + .into_iter() + .map(|matrix| { + matrix + .into_iter() + .map(|(offset, width)| { + interpolated + [offset * ext_degree..(offset + width) * ext_degree] + .chunks_exact(ext_degree) + .map(ext_from_goldilocks::) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec(); + for round in &all_opened_values { + for matrix in round { + for values in matrix { + challenger.observe_algebra_slice(values); + } + } + } + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.powers().take(opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; + let mut col_weights_flat = Vec::with_capacity(col_weights.len() * ext_degree); + for &w in &col_weights { + let (buf, d) = ext_to_goldilocks::(w, ext_degree); + col_weights_flat.extend_from_slice(&buf[..d]); + } + let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; + let mut reduced: [Option; 33] = core::array::from_fn(|_| None); + let mut reduction_tasks = CudaReductionTasks::new(ext_degree); + for ((ldes, points), openings_round) in + resident_rounds.iter().zip(all_opened_values.iter()) + { + for ((lde, ps), openings) in + ldes.iter().zip(points.iter()).zip(openings_round.iter()) + { + if ps.is_empty() { + continue; + } + let lh = log2_strict_usize(lde.height()); + let target = reduced[lh].get_or_insert_with(|| { + CudaReducedOpening::new_with_degree(device_id, lde.height(), ext_degree) + }); + for (&point, ys) in ps.iter().zip(openings.iter()) { + let reduced_y: Challenge = + dot_product(col_weights.iter().copied(), ys.iter().copied()); + let offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => alpha.exp_u64( + u64::try_from(num_reduced[lh]) + .expect("reduced column count exceeds u64"), + ), + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[lh]] + } + }; + let (y_buf, d) = + ext_to_goldilocks::(reduced_y, ext_degree); + let (off_buf, _) = + ext_to_goldilocks::(offset, ext_degree); + reduction_tasks.push( + target, + lde, + *inv_offsets.get(&point).unwrap(), + &y_buf[..d], + &off_buf[..d], + ); + num_reduced[lh] += lde.width(); + opening_idx_by_height[lh] += 1; + } + } + } + if !reduction_tasks.is_empty() { + tracing::info_span!("stark/fri_reduce").in_scope(|| { + workspace.reduce(&reduction_tasks, &col_weights_flat, ext_w); + }); + } + let fri_input = reduced.into_iter().rev().flatten().collect_vec(); + let fri_proof = tracing::info_span!("stark/fri_prove").in_scope(|| { + prove_fri_cuda_resident_hiding( + &self.fri, + fri_input, + challenger, + log_global_max_height, + &commitment_data_with_opening_points, + &self.mmcs, + ext_w, + ext_degree, + ) + }); + return (all_opened_values, fri_proof); + } + } + + // Fallback path for small matrices (`height <= 1024`) or hybrid/CPU + // commitments (e.g., wide height groups exceeding 32 KiB per leaf). + let mats_and_points = commitment_data_with_opening_points + .iter() + .map(|(data, points)| { + let mats = self + .mmcs + .get_matrices(data) + .into_iter() + .map(|m| m.as_view()) + .collect_vec(); + debug_assert_eq!( + mats.len(), + points.len(), + "each matrix should have a corresponding set of evaluation points" + ); + (mats, points) + }) + .collect_vec(); + + let global_max_height = mats_and_points + .iter() + .flat_map(|(mats, _)| mats.iter().map(Matrix::height)) + .max() + .expect("No Matrices Supplied?"); + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for (mats, points) in &mats_and_points { + for (mat, pts) in mats.iter().zip(points.iter()) { + if !pts.is_empty() { + opened_max_width = opened_max_width.max(mat.width()); + let lh = log2_strict_usize(mat.height()); + openings_per_height[lh] += pts.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); + let log_global_max_height = log2_strict_usize(global_max_height); + + let coset = { + let coset = + TwoAdicMultiplicativeCoset::new(Goldilocks::GENERATOR, log_global_max_height) + .unwrap(); + let mut coset_points = coset.iter().collect(); + reverse_slice_index_bits(&mut coset_points); + coset_points + }; + let inv_denoms = compute_inverse_denominators(&mats_and_points, &coset); + let adjusted_weights: LinearMap> = inv_denoms + .iter() + .map(|(point, denoms)| (*point, compute_adjusted_weights(*point, denoms))) + .collect(); + + let all_opened_values = mats_and_points + .iter() + .map(|(mats, points)| { + izip!(mats.iter(), points.iter()) + .map(|(mat, points_for_mat)| { + let h = mat.height() >> self.fri.log_blowup; + let (low_coset, _) = mat.split_rows(h); + points_for_mat + .iter() + .map(|&point| { + let _guard = + debug_span!("evaluate matrix", dims = %mat.dimensions()) + .entered(); + let adjusted = &adjusted_weights.get(&point).unwrap()[..h]; + let ys = low_coset.interpolate_coset_with_precomputation( + Goldilocks::GENERATOR, + point, + adjusted, + ); + challenger.observe_algebra_slice(&ys); + ys + }) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec(); + + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let packed_col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + Challenge::ExtensionPacking::packed_ext_powers_capped(*alpha, opened_max_width) + .collect_vec() + } + FriBatchingSchedule::Tensor { col_weights, .. } => { + pack_ext_weights::(col_weights) + } + }; + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.powers().take(opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; + + let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; + let mut reduced_openings: [Option>; 33] = core::array::from_fn(|_| None); + + for ((mats, points), openings_for_round) in + mats_and_points.iter().zip(all_opened_values.iter()) + { + for (mat, points_for_mat, openings_for_mat) in + izip!(mats.iter(), points.iter(), openings_for_round.iter()) + { + if points_for_mat.is_empty() { + continue; + } + let log_height = log2_strict_usize(mat.height()); + let reduced_opening_for_log_height = reduced_openings[log_height] + .get_or_insert_with(|| vec![Challenge::ZERO; mat.height()]); + let mat_compressed = mat + .rowwise_packed_dot_product::(&packed_col_weights) + .collect::>(); + for (&point, openings) in points_for_mat.iter().zip(openings_for_mat) { + let alpha_pow_offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => alpha.exp_u64( + u64::try_from(num_reduced[log_height]) + .expect("reduced column count exceeds u64"), + ), + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[log_height]] + } + }; + let reduced_openings: Challenge = + dot_product(col_weights.iter().copied(), openings.iter().copied()); + mat_compressed + .par_iter() + .zip(reduced_opening_for_log_height.par_iter_mut()) + .zip(inv_denoms.get(&point).unwrap().par_iter()) + .for_each(|((&reduced_row, ro), &inv_denom)| { + *ro += alpha_pow_offset * (reduced_openings - reduced_row) * inv_denom; + }); + num_reduced[log_height] += mat.width(); + opening_idx_by_height[log_height] += 1; + } + } + } + + let fri_input = reduced_openings.into_iter().rev().flatten().collect_vec(); + let folding: TwoAdicFriFoldingForMmcs = + TwoAdicFriFolding(PhantomData); + let fri_proof = prover::prove_fri( + &folding, + &self.fri, + fri_input, + challenger, + log_global_max_height, + &commitment_data_with_opening_points, + &self.mmcs, + ); + + (all_opened_values, fri_proof) + } + + fn verify( + &self, + commitments_with_opening_points: Vec< + CommitmentWithOpeningPoints, + >, + proof: &Self::Proof, + challenger: &mut Challenger, + ) -> Result<(), Self::Error> { + // Every committed polynomial in `v6-zk` has degree `< 2 * domain.size()` + // and LDE height `2 * domain.size() * 2^log_blowup`. Double each domain + // before cap validation and FRI verification. + let mut doubled_commitments = Vec::with_capacity(commitments_with_opening_points.len()); + for (comm, mats) in commitments_with_opening_points { + let mut doubled_mats = Vec::with_capacity(mats.len()); + for (domain, pts) in mats { + let ext_log_size = domain.log_size() + 1; + let ext_domain = TwoAdicMultiplicativeCoset::new(domain.shift(), ext_log_size) + .ok_or(FriError::GlobalMaxHeightTooLarge { + log_global_max_height: ext_log_size + self.fri.log_blowup, + two_adicity: Goldilocks::TWO_ADICITY, + })?; + doubled_mats.push((ext_domain, pts)); + } + doubled_commitments.push((comm, doubled_mats)); + } + + validate_fri_commitment_caps(&self.fri, proof, &doubled_commitments, &self.mmcs)?; + for (_, round) in &doubled_commitments { + for (_, mat) in round { + for (_, point) in mat { + challenger.observe_algebra_slice(point); + } + } + } + + let folding: TwoAdicFriFoldingForMmcs = + TwoAdicFriFolding(PhantomData); + verify_fri_with_batching( + &folding, + &self.fri, + proof, + challenger, + &doubled_commitments, + &self.mmcs, + self.batching, + )?; + + Ok(()) + } + + fn build_periodic_lde_table( + &self, + periodic_cols: &[Vec], + trace_domain: Self::Domain, + quotient_domain: Self::Domain, + ) -> PeriodicLdeTable { + build_periodic_lde_table_two_adic::( + &self.dft, + periodic_cols, + &trace_domain, + "ient_domain, + ) + } +} diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index 506eb9d..e5f4e42 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -1602,6 +1602,12 @@ impl CapValidatingMmcs for CudaMmcs { ) -> Result<(), Self::Error> { verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) } + + fn empty_multi_proof() -> Self::MultiProof { + p3_merkle_tree::PrunedMerklePaths { + sibling_hashes: Vec::new(), + } + } } #[cfg(test)] diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index f96c94f..47c0314 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -5,6 +5,10 @@ //! lookup traces, quotient evaluations, and FRI codewords on the selected GPU. //! All public protocol types and serialized proofs remain unchanged. +#[doc(hidden)] +pub mod hiding_mmcs; +#[doc(hidden)] +pub mod hiding_pcs; pub(crate) mod mmcs; mod offload; #[doc(hidden)] @@ -3374,6 +3378,288 @@ impl CudaMixedMerkleTree { } } + /// Hashes a single hybrid height group under Protocol `v6-zk` (`ZkMerkleLeaf`) + /// with on-the-fly BLAKE3-CTR leaf salts derived from `salt_seed`. + #[cfg(test)] + #[must_use] + pub(crate) fn hash_hybrid_height_group_v6zk( + device_id: i32, + ldes: &[Option<&CudaLde>], + host_matrices: &[Option<&RowMajorMatrix>], + salt_seed: &[u8; 32], + ) -> Vec<[u8; 32]> { + assert!(device_id >= 0, "CUDA device id must be non-negative"); + assert_eq!(ldes.len(), host_matrices.len()); + assert!(!ldes.is_empty(), "hybrid height group is empty"); + assert!( + ldes.iter().flatten().all(|lde| lde.device_id == device_id), + "hybrid height group spans CUDA devices" + ); + assert!( + ldes.iter() + .zip(host_matrices) + .all(|(lde, matrix)| lde.is_some() ^ matrix.is_some()), + "every hybrid height-group matrix must have exactly one storage backend" + ); + let heights = ldes + .iter() + .zip(host_matrices) + .map(|(lde, matrix)| lde.map_or_else(|| matrix.unwrap().height(), CudaLde::height)) + .collect::>(); + let height = heights[0]; + assert!( + heights.iter().all(|&candidate| candidate == height), + "hybrid height group contains unequal heights" + ); + let handles = ldes + .iter() + .map(|lde| lde.map_or(core::ptr::null(), CudaLde::raw_handle)) + .collect::>(); + let host_values = host_matrices + .iter() + .map(|matrix| matrix.map_or(core::ptr::null(), |matrix| matrix.values.as_ptr().cast())) + .collect::>(); + let widths = ldes + .iter() + .zip(host_matrices) + .map(|(lde, matrix)| lde.map_or_else(|| matrix.unwrap().width(), CudaLde::width)) + .collect::>(); + let mut digests = vec![[0u8; 32]; height]; + // SAFETY: every pointer is backed by a matrix, CUDA handle, or stack + // salt seed borrowed for this synchronous call. + let status = unsafe { + multi_stark_cuda_hash_hybrid_height_group_v6zk( + device_id, + digests.as_mut_ptr().cast(), + handles.as_ptr(), + host_values.as_ptr(), + widths.as_ptr(), + heights.as_ptr(), + handles.len(), + height, + salt_seed.as_ptr(), + ) + }; + check_cuda(status, "hybrid CUDA v6-zk height-group hashing"); + digests + } + + /// Builds a salted `v6-zk` mixed-height tree directly from resident CUDA LDEs. + #[must_use] + pub(crate) fn from_ldes_v6zk(device_id: i32, ldes: &[CudaLde], salt_seed: &[u8; 32]) -> Self { + assert!(device_id >= 0, "CUDA device id must be non-negative"); + assert!(!ldes.is_empty(), "mixed Merkle tree has no resident LDEs"); + assert!( + ldes.iter().all(|lde| lde.device_id == device_id), + "resident LDEs belong to different CUDA devices" + ); + let handles: Vec<*const c_void> = ldes + .iter() + .map(|lde| lde.handle.as_ptr().cast_const()) + .collect(); + let mut handle = core::ptr::null_mut(); + let mut root = [0u8; 32]; + // SAFETY: all handles and `salt_seed` remain live for the synchronous call. + let status = unsafe { + multi_stark_cuda_mixed_merkle_create_from_ldes_v6zk( + device_id, + &mut handle, + root.as_mut_ptr(), + handles.as_ptr(), + handles.len(), + salt_seed.as_ptr(), + ) + }; + if status != 0 { + let dimensions: Vec<(usize, usize)> = + ldes.iter().map(|lde| (lde.height(), lde.width())).collect(); + check_cuda( + status, + &format!( + "resident LDE v6-zk Merkle tree creation over (height, width) {dimensions:?}" + ), + ); + } + Self { + device_id, + handle: NonNull::new(handle).expect("CUDA returned a null mixed Merkle handle"), + root, + row_count: ldes.iter().map(CudaLde::height).max().unwrap(), + } + } + + /// Builds a salted `v6-zk` mixed-height tree from resident CUDA LDEs, host + /// matrices, and pre-hashed salted height groups. + #[must_use] + pub(crate) fn from_hybrid_v6zk( + device_id: i32, + ldes: &[Option<&CudaLde>], + host_matrices: &[Option<&RowMajorMatrix>], + deferred_dimensions: &[Option], + host_digest_groups: &[(usize, Vec<[u8; 32]>)], + salt_seed: &[u8; 32], + ) -> Self { + assert!(device_id >= 0, "CUDA device id must be non-negative"); + assert_eq!(ldes.len(), host_matrices.len()); + assert_eq!(ldes.len(), deferred_dimensions.len()); + assert!(!ldes.is_empty(), "mixed Merkle tree has no LDE groups"); + assert!( + ldes.iter().flatten().all(|lde| lde.device_id == device_id), + "resident LDEs belong to different CUDA devices" + ); + for (height, digests) in host_digest_groups { + assert!( + height.is_power_of_two(), + "host digest height is not a power of two" + ); + assert_eq!( + *height, + digests.len(), + "host digest group has the wrong height" + ); + } + assert!( + ldes.iter().zip(host_matrices).zip(deferred_dimensions).all( + |((lde, matrix), deferred)| { + let sources = usize::from(lde.is_some()) + + usize::from(matrix.is_some()) + + usize::from(deferred.is_some()); + sources == 1 + && deferred.is_none_or(|dimensions| { + host_digest_groups + .iter() + .any(|(height, _)| *height == dimensions.height) + }) + } + ), + "every hybrid matrix needs one source, and deferred matrices need pre-hashed rows" + ); + let handles: Vec<*const c_void> = ldes + .iter() + .map(|lde| lde.map_or(core::ptr::null(), |lde| lde.handle.as_ptr().cast_const())) + .collect(); + let host_values = host_matrices + .iter() + .map(|matrix| { + matrix.map_or(core::ptr::null(), |matrix| { + matrix.values.as_ptr().cast::() + }) + }) + .collect::>(); + let widths = ldes + .iter() + .zip(host_matrices) + .zip(deferred_dimensions) + .map(|((lde, matrix), deferred)| { + lde.map_or_else( + || matrix.map_or_else(|| deferred.unwrap().width, Matrix::width), + CudaLde::width, + ) + }) + .collect::>(); + let heights: Vec = ldes + .iter() + .zip(host_matrices) + .zip(deferred_dimensions) + .map(|((lde, matrix), deferred)| { + lde.map_or_else( + || matrix.map_or_else(|| deferred.unwrap().height, Matrix::height), + CudaLde::height, + ) + }) + .collect(); + let host_digest_pointers: Vec<*const u8> = host_digest_groups + .iter() + .map(|(_, digests)| digests.as_ptr().cast()) + .collect(); + let host_digest_heights: Vec = host_digest_groups + .iter() + .map(|(height, _)| *height) + .collect(); + let mut handle = core::ptr::null_mut(); + let mut root = [0u8; 32]; + // SAFETY: all resident handles, host buffers, and `salt_seed` remain live + // for this synchronous call. + let status = unsafe { + multi_stark_cuda_mixed_merkle_create_hybrid_v6zk( + device_id, + &mut handle, + root.as_mut_ptr(), + handles.as_ptr(), + host_values.as_ptr(), + widths.as_ptr(), + heights.as_ptr(), + ldes.len(), + host_digest_pointers.as_ptr(), + host_digest_heights.as_ptr(), + host_digest_groups.len(), + salt_seed.as_ptr(), + ) + }; + if status != 0 { + let dims: Vec> = ldes + .iter() + .zip(host_matrices) + .zip(deferred_dimensions) + .map(|((lde, host), deferred)| { + lde.map(|l| (l.height(), l.width())) + .or_else(|| host.map(|m| (m.height(), m.width()))) + .or_else(|| deferred.map(|d| (d.height, d.width))) + }) + .collect(); + check_cuda( + status, + &format!( + "hybrid v6-zk Merkle tree creation over (height, width) {dims:?}, host digest groups at heights {:?}", + host_digest_groups + .iter() + .map(|(h, _)| *h) + .collect::>() + ), + ); + } + let row_count = heights.into_iter().max().unwrap(); + Self { + device_id, + handle: NonNull::new(handle).expect("CUDA returned a null mixed Merkle handle"), + root, + row_count, + } + } + + /// Builds a salted `v6-zk` FRI commit-phase Merkle tree from a resident + /// extension-field codeword. + #[must_use] + pub(crate) fn from_fri_codeword_v6zk( + codeword: &CudaLde, + arity: usize, + salt_seed: &[u8; 32], + ) -> Self { + assert!(codeword.width == 2 || codeword.width == 3); + assert!(arity.is_power_of_two()); + assert_eq!(codeword.height % arity, 0); + let mut handle = core::ptr::null_mut(); + let mut root = [0u8; 32]; + // SAFETY: `codeword` handle and `salt_seed` remain live for this synchronous call. + let status = unsafe { + multi_stark_cuda_fri_merkle_create_v6zk( + codeword.device_id, + &mut handle, + root.as_mut_ptr(), + codeword.raw_handle(), + arity, + salt_seed.as_ptr(), + ) + }; + check_cuda(status, "resident CUDA v6-zk FRI Merkle tree creation"); + Self { + device_id: codeword.device_id, + handle: NonNull::new(handle).expect("CUDA returned a null FRI Merkle handle"), + root, + row_count: codeword.height / arity, + } + } + /// Builds a mixed-height tree by uploading each host matrix directly, /// without constructing a concatenated host-side row buffer. #[cfg(test)] @@ -4066,6 +4352,48 @@ unsafe extern "C" { codeword: *const c_void, arity: usize, ) -> i32; + fn multi_stark_cuda_mixed_merkle_create_from_ldes_v6zk( + device_id: i32, + handle: *mut *mut c_void, + root: *mut u8, + lde_handles: *const *const c_void, + lde_count: usize, + salt_seed: *const u8, + ) -> i32; + fn multi_stark_cuda_mixed_merkle_create_hybrid_v6zk( + device_id: i32, + handle: *mut *mut c_void, + root: *mut u8, + lde_handles: *const *const c_void, + host_values: *const *const u64, + widths: *const usize, + heights: *const usize, + matrix_count: usize, + host_digest_groups: *const *const u8, + host_digest_heights: *const usize, + host_digest_group_count: usize, + salt_seed: *const u8, + ) -> i32; + #[cfg(test)] + fn multi_stark_cuda_hash_hybrid_height_group_v6zk( + device_id: i32, + host_digests: *mut u8, + lde_handles: *const *const c_void, + host_values: *const *const u64, + widths: *const usize, + heights: *const usize, + matrix_count: usize, + height: usize, + salt_seed: *const u8, + ) -> i32; + fn multi_stark_cuda_fri_merkle_create_v6zk( + device_id: i32, + handle: *mut *mut c_void, + root: *mut u8, + codeword: *const c_void, + arity: usize, + salt_seed: *const u8, + ) -> i32; fn multi_stark_cuda_quotient_values_ext3( device_id: i32, diff --git a/src/cuda/pcs.rs b/src/cuda/pcs.rs index 7828514..27f9173 100644 --- a/src/cuda/pcs.rs +++ b/src/cuda/pcs.rs @@ -112,8 +112,10 @@ fn goldilocks_cubic_trinomial_inverse_denominators( .collect() } -fn cuda_ext_degree_and_w>() --> (usize, Goldilocks) { +pub(super) fn cuda_ext_degree_and_w< + Val: TwoAdicField + PrimeField64, + Challenge: ExtensionField, +>() -> (usize, Goldilocks) { let d = >::DIMENSION; assert!( d == 2 || d == 3, @@ -144,7 +146,7 @@ fn cuda_ext_degree_and_w>( +pub(super) fn ext_to_goldilocks>( value: Challenge, d: usize, ) -> ([Goldilocks; 3], usize) { @@ -157,7 +159,7 @@ fn ext_to_goldilocks>( } #[inline] -fn ext_from_goldilocks>( +pub(super) fn ext_from_goldilocks>( slice: &[Goldilocks], ) -> Challenge { let mut coeffs = [Val::ZERO; 3]; @@ -395,7 +397,7 @@ pub struct CudaTwoAdicFriPcs { /// `i < 2^k`, so every smaller coset is a prefix of a larger one: one vector /// per process serves every height, and grows only when a larger height is /// opened. Every shard of a proof opens on the same coset. -fn bit_reversed_coset( +pub(super) fn bit_reversed_coset( log_height: usize, ) -> std::sync::Arc> { static CACHE: std::sync::Mutex>>> = @@ -2455,7 +2457,7 @@ where /// /// Return a LinearMap which allows us to recover the computed vectors for each `z`. #[instrument(skip_all)] -fn compute_inverse_denominators, M: Matrix>( +pub(super) fn compute_inverse_denominators, M: Matrix>( mats_and_points: &[(Vec, &Vec>)], coset: &[F], ) -> LinearMap> { diff --git a/src/lookup.rs b/src/lookup.rs index fdbf202..1134f97 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -127,6 +127,25 @@ pub fn logup_constraint_count(num_lookups: usize, group_size: usize, d: usize) - lookup_groups(num_lookups, group_size) * d } +/// Shifts row `0` of a stage-2 accumulator trace by `+delta` so that the +/// cyclic LogUp boundary injection moves cleanly from `is_last_row` +/// (`X = g_N^{-1}`) to `is_first_row` (`X = 1`), where every active circuit +/// subgroup shares the common point `X = 1` for multi-circuit `v6-zk` +/// accumulator boundary blinding. +#[inline] +pub(crate) fn apply_first_row_delta_shift( + stage_2_trace: &mut RowMajorMatrix, + delta: EF, +) { + let width = stage_2_trace.width(); + if width == 0 || stage_2_trace.height() == 0 { + return; + } + for elem in &mut stage_2_trace.values[..width] { + *elem += delta; + } +} + /// Coordinate product reduced modulo `modulus`, schoolbook. Generic-degree /// fallback; the hot D=2 binomial and D=3 cubic trinomial paths use [`mul2`] /// and [`mul3_trinomial`]. diff --git a/src/p3_adapter/blake3_simd.rs b/src/p3_adapter/blake3_simd.rs index afc6d54..5c40efd 100644 --- a/src/p3_adapter/blake3_simd.rs +++ b/src/p3_adapter/blake3_simd.rs @@ -20,6 +20,7 @@ use p3_maybe_rayon::prelude::*; use p3_symmetric::CryptographicHasher; use super::domain_blake3::{BLAKE3_IV as IV, Blake3Domain, DomainBlake3}; +use super::zk::{ZK_LEAF_SALT_BYTES, derive_leaf_salt}; use crate::types::Val; const BLOCK_LEN: usize = 64; @@ -786,6 +787,395 @@ pub(crate) fn hash_matrix_rows>( hash_matrix_rows_uninit(matrices, start_row, uninit, domain); } +/// Hashes `out.len()` contiguous fixed-length rows of `row_bytes` bytes each +/// with an on-the-fly BLAKE3-CTR leaf salt (`derive_leaf_salt(salt_seed, height, start_row + i)`) +/// appended to each leaf message. +pub(crate) fn hash_raw_rows_salted_uninit( + raw: &[u8], + row_bytes: usize, + height: usize, + start_row: usize, + salt_seed: &[u8; 32], + out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, +) { + assert_eq!(raw.len(), out.len() * row_bytes); + if out.is_empty() { + return; + } + let total_msg_bytes = row_bytes + ZK_LEAF_SALT_BYTES; + if total_msg_bytes > MAX_MULTIBUF_ROW_BYTES { + let hasher = DomainBlake3::new(domain); + out.par_iter_mut().enumerate().for_each(|(local_row, dst)| { + let salt = derive_leaf_salt(salt_seed, height, start_row + local_row); + let row = &raw[local_row * row_bytes..(local_row + 1) * row_bytes]; + dst.write(hasher.hash_iter_slices([row, &salt[..]])); + }); + return; + } + let backend = detect_backend(); + let batch = match backend { + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx512 => 16usize, + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx2 => 8usize, + SimdBackend::Scalar => 1usize, + }; + if batch == 1 { + let hasher = DomainBlake3::new(domain); + out.par_iter_mut().enumerate().for_each(|(local_row, dst)| { + let salt = derive_leaf_salt(salt_seed, height, start_row + local_row); + let row = &raw[local_row * row_bytes..(local_row + 1) * row_bytes]; + dst.write(hasher.hash_iter_slices([row, &salt[..]])); + }); + return; + } + let chunk_rows = (65_536 / total_msg_bytes.max(64)) + .clamp(batch, 256) + .next_multiple_of(batch); + let process_chunk = |scratch: &mut Vec, + chunk_offset: usize, + dst: &mut [MaybeUninit<[u8; 32]>]| { + let mut offset = 0; + while offset < dst.len() { + let take = (dst.len() - offset).min(batch); + for lane in 0..take { + let local_row = chunk_offset + offset + lane; + let base = lane * total_msg_bytes; + if row_bytes > 0 { + scratch[base..base + row_bytes] + .copy_from_slice(&raw[local_row * row_bytes..(local_row + 1) * row_bytes]); + } + let salt = derive_leaf_salt(salt_seed, height, start_row + local_row); + scratch[base + row_bytes..base + total_msg_bytes].copy_from_slice(&salt); + } + hash_raw_rows_slice( + &scratch[..take * total_msg_bytes], + total_msg_bytes, + &mut dst[offset..offset + take], + backend, + domain, + ); + offset += take; + } + }; + if out.len() <= chunk_rows { + let mut scratch = vec![0u8; batch * total_msg_bytes]; + process_chunk(&mut scratch, 0, out); + } else { + out.par_chunks_mut(chunk_rows).enumerate().for_each_init( + || vec![0u8; batch * total_msg_bytes], + |scratch, (chunk_idx, dst)| { + process_chunk(scratch, chunk_idx * chunk_rows, dst); + }, + ); + } +} + +/// Hashes `out.len()` rows formed by concatenating the corresponding row slices +/// across `blocks` plus the on-the-fly derived 16-byte leaf salt. +pub(crate) fn hash_raw_multi_rows_salted_uninit( + blocks: &[(Vec, usize)], + height: usize, + start_row: usize, + salt_seed: &[u8; 32], + out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, +) { + if out.is_empty() { + return; + } + if let [(buf, row_bytes)] = blocks { + hash_raw_rows_salted_uninit(buf, *row_bytes, height, start_row, salt_seed, out, domain); + return; + } + let total_row_bytes: usize = blocks.iter().map(|(_, rb)| *rb).sum(); + let total_msg_bytes = total_row_bytes + ZK_LEAF_SALT_BYTES; + if total_msg_bytes > MAX_MULTIBUF_ROW_BYTES { + let hasher = DomainBlake3::new(domain); + out.par_iter_mut() + .enumerate() + .for_each(|(local_row, digest)| { + let salt = derive_leaf_salt(salt_seed, height, start_row + local_row); + digest.write( + hasher.hash_iter_slices( + blocks + .iter() + .map(|(buf, rb)| &buf[local_row * *rb..(local_row + 1) * *rb]) + .chain(core::iter::once(&salt[..])), + ), + ); + }); + return; + } + let backend = detect_backend(); + let batch = match backend { + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx512 => 16usize, + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx2 => 8usize, + SimdBackend::Scalar => 1usize, + }; + if batch == 1 { + let hasher = DomainBlake3::new(domain); + out.par_iter_mut() + .enumerate() + .for_each(|(local_row, digest)| { + let salt = derive_leaf_salt(salt_seed, height, start_row + local_row); + digest.write( + hasher.hash_iter_slices( + blocks + .iter() + .map(|(buf, rb)| &buf[local_row * *rb..(local_row + 1) * *rb]) + .chain(core::iter::once(&salt[..])), + ), + ); + }); + return; + } + let chunk_rows = (65_536 / total_msg_bytes.max(64)) + .clamp(batch, 256) + .next_multiple_of(batch); + out.par_chunks_mut(chunk_rows).enumerate().for_each_init( + || vec![0u8; batch * total_msg_bytes], + |scratch, (chunk_idx, dst)| { + let chunk_start = chunk_idx * chunk_rows; + let mut offset = 0; + while offset < dst.len() { + let take = (dst.len() - offset).min(batch); + for lane in 0..take { + let local_row = chunk_start + offset + lane; + let mut pos = lane * total_msg_bytes; + for (buf, rb) in blocks { + if *rb > 0 { + scratch[pos..pos + *rb] + .copy_from_slice(&buf[local_row * *rb..(local_row + 1) * *rb]); + pos += *rb; + } + } + let salt = derive_leaf_salt(salt_seed, height, start_row + local_row); + scratch[pos..pos + ZK_LEAF_SALT_BYTES].copy_from_slice(&salt); + } + hash_raw_rows_slice( + &scratch[..take * total_msg_bytes], + total_msg_bytes, + &mut dst[offset..offset + take], + backend, + domain, + ); + offset += take; + } + }, + ); +} + +/// Safe wrapper over [`hash_raw_multi_rows_salted_uninit`] writing into an +/// initialized digest buffer. +pub(crate) fn hash_raw_multi_rows_salted( + blocks: &[(Vec, usize)], + height: usize, + start_row: usize, + salt_seed: &[u8; 32], + out: &mut [[u8; 32]], + domain: Blake3Domain, +) { + // SAFETY: `hash_raw_multi_rows_salted_uninit` only writes initialized digests. + let uninit = unsafe { as_uninit_slice(out) }; + hash_raw_multi_rows_salted_uninit(blocks, height, start_row, salt_seed, uninit, domain); +} + +/// Hashes `out.len()` rows starting at `start_row` across one or more in-memory +/// Goldilocks matrices (`Matrix`) with an on-the-fly derived 16-byte leaf +/// salt appended to each leaf message. +pub(crate) fn hash_matrix_rows_salted_uninit>( + matrices: &[&M], + height: usize, + start_row: usize, + salt_seed: &[u8; 32], + out: &mut [MaybeUninit<[u8; 32]>], + domain: Blake3Domain, +) { + if out.is_empty() { + return; + } + let total_width: usize = matrices.iter().map(|m| m.width()).sum(); + let total_row_bytes = total_width * size_of::(); + let total_msg_bytes = total_row_bytes + ZK_LEAF_SALT_BYTES; + let backend = detect_backend(); + let hasher = DomainBlake3::new(domain); + + if total_msg_bytes > MAX_MULTIBUF_ROW_BYTES { + out.par_iter_mut().enumerate().for_each_init( + || vec![0u8; total_msg_bytes], + |scratch, (local_row, digest)| { + let r = start_row + local_row; + let mut pos = 0; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + scratch[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + let salt = derive_leaf_salt(salt_seed, height, r); + scratch[pos..pos + ZK_LEAF_SALT_BYTES].copy_from_slice(&salt); + digest.write(hasher.hash_slice(scratch)); + }, + ); + return; + } + + let batch = match backend { + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx512 => 16usize, + #[cfg(target_arch = "x86_64")] + SimdBackend::Avx2 => 8usize, + SimdBackend::Scalar => 1usize, + }; + + #[cfg(target_arch = "x86_64")] + if total_msg_bytes <= BLOCK_LEN && batch > 1 { + let key = domain.key_words(); + let domain_flags = domain.domain_flags(); + let block_len_u32 = u32::try_from(total_msg_bytes).unwrap(); + let chunk_rows = 256usize; + let process_small = |chunk_start: usize, dst: &mut [MaybeUninit<[u8; 32]>]| { + let mut offset = 0; + while offset + batch <= dst.len() { + let mut blocks = [[0u8; BLOCK_LEN]; 16]; + for (lane, block) in blocks[..batch].iter_mut().enumerate() { + let r = chunk_start + offset + lane; + let mut pos = 0; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + block[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + let salt = derive_leaf_salt(salt_seed, height, r); + block[pos..pos + ZK_LEAF_SALT_BYTES].copy_from_slice(&salt); + } + if backend == SimdBackend::Avx512 { + // SAFETY: `avx512f` detected at runtime; `dst[offset..offset+16]` has 16 slots. + unsafe { + avx512::hash_16_single_block( + &blocks, + block_len_u32, + dst[offset..].as_mut_ptr().cast(), + key, + domain_flags, + ); + } + } else { + // SAFETY: `avx2` detected at runtime; `dst[offset..offset+8]` has 8 slots. + unsafe { + avx2::hash_8_single_block( + (&blocks[..8]).try_into().unwrap(), + block_len_u32, + dst[offset..].as_mut_ptr().cast(), + key, + domain_flags, + ); + } + } + offset += batch; + } + if offset < dst.len() { + let mut block = [0u8; BLOCK_LEN]; + while offset < dst.len() { + let r = chunk_start + offset; + let mut pos = 0; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + block[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + let salt = derive_leaf_salt(salt_seed, height, r); + block[pos..pos + ZK_LEAF_SALT_BYTES].copy_from_slice(&salt); + dst[offset].write(hasher.hash_slice(&block[..total_msg_bytes])); + offset += 1; + } + } + }; + if out.len() <= chunk_rows { + process_small(start_row, out); + } else { + out.par_chunks_mut(chunk_rows) + .enumerate() + .for_each(|(chunk_idx, dst)| { + process_small(start_row + chunk_idx * chunk_rows, dst); + }); + } + return; + } + + let chunk_rows = (65_536 / total_msg_bytes.max(64)) + .clamp(batch, 256) + .next_multiple_of(batch); + let process_chunk = + |scratch: &mut Vec, chunk_start: usize, dst: &mut [MaybeUninit<[u8; 32]>]| { + let mut offset = 0; + while offset < dst.len() { + let take = (dst.len() - offset).min(batch); + for lane in 0..take { + let r = chunk_start + offset + lane; + let mut pos = lane * total_msg_bytes; + for m in matrices { + // SAFETY: `r < m.height()`. + for elem in unsafe { m.row_unchecked(r) } { + scratch[pos..pos + 8] + .copy_from_slice(&elem.as_canonical_u64().to_le_bytes()); + pos += 8; + } + } + let salt = derive_leaf_salt(salt_seed, height, r); + scratch[pos..pos + ZK_LEAF_SALT_BYTES].copy_from_slice(&salt); + } + hash_raw_rows_slice( + &scratch[..take * total_msg_bytes], + total_msg_bytes, + &mut dst[offset..offset + take], + backend, + domain, + ); + offset += take; + } + }; + + if out.len() <= chunk_rows { + let mut scratch = vec![0u8; batch * total_msg_bytes]; + process_chunk(&mut scratch, start_row, out); + } else { + out.par_chunks_mut(chunk_rows).enumerate().for_each_init( + || vec![0u8; batch * total_msg_bytes], + |scratch, (chunk_idx, dst)| { + process_chunk(scratch, start_row + chunk_idx * chunk_rows, dst); + }, + ); + } +} + +/// Safe wrapper over [`hash_matrix_rows_salted_uninit`] writing into an +/// initialized digest buffer. +pub(crate) fn hash_matrix_rows_salted>( + matrices: &[&M], + height: usize, + start_row: usize, + salt_seed: &[u8; 32], + out: &mut [[u8; 32]], + domain: Blake3Domain, +) { + // SAFETY: `hash_matrix_rows_salted_uninit` only writes initialized digests. + let uninit = unsafe { as_uninit_slice(out) }; + hash_matrix_rows_salted_uninit(matrices, height, start_row, salt_seed, uninit, domain); +} + #[cfg(target_arch = "x86_64")] mod avx512 { use core::arch::x86_64::*; diff --git a/src/p3_adapter/cap.rs b/src/p3_adapter/cap.rs index 37a1066..0d848aa 100644 --- a/src/p3_adapter/cap.rs +++ b/src/p3_adapter/cap.rs @@ -14,7 +14,7 @@ use p3_field::{ExtensionField, Field, TwoAdicField, coset::TwoAdicMultiplicative use p3_fri::verifier::FriError; use p3_fri::{CommitmentWithOpeningPoints, FriParameters, FriProof}; use p3_matrix::Dimensions; -use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; +use p3_merkle_tree::MerkleTreeError; use p3_symmetric::MerkleCap; use p3_util::{log2_ceil_usize, log2_strict_usize}; @@ -70,14 +70,17 @@ pub trait CapValidatingMmcs: Mmcs { commit: &Self::Commitment, log_max_height: usize, ) -> Result<(), Self::Error>; + + /// Constructs an empty multi-batch proof used solely to delegate cap-length + /// validation through `ExtensionMmcs::verify_multi_batch`. + fn empty_multi_proof() -> Self::MultiProof; } impl CapValidatingMmcs for ExtensionMmcs where F: Field, EF: ExtensionField, - InnerMmcs: - CapValidatingMmcs, Error = MerkleTreeError>, + InnerMmcs: CapValidatingMmcs, { fn validate_commitment_cap_for_log_height( &self, @@ -92,9 +95,7 @@ where .and_then(|shift| 1usize.checked_shl(shift)) .ok_or(MerkleTreeError::CapMismatch)?; let empty_rows: &[Vec<&[EF]>] = &[]; - let empty_proof = PrunedMerklePaths { - sibling_hashes: Vec::new(), - }; + let empty_proof = InnerMmcs::empty_multi_proof(); self.verify_multi_batch( commit, &[Dimensions { width: 1, height }], @@ -103,6 +104,10 @@ where &empty_proof, ) } + + fn empty_multi_proof() -> Self::MultiProof { + InnerMmcs::empty_multi_proof() + } } /// Validates the exact Merkle cap root count of every input commitment and diff --git a/src/p3_adapter/domain_blake3.rs b/src/p3_adapter/domain_blake3.rs index ec28ff3..332e25b 100644 --- a/src/p3_adapter/domain_blake3.rs +++ b/src/p3_adapter/domain_blake3.rs @@ -53,6 +53,17 @@ pub const V6_TRANSCRIPT_BATCH_CONTEXT: &str = "multi-stark/v6/transcript/batch"; /// Domain-separation context string for v6 canonical VK / constraint-graph digests. pub const V6_VK_CONTEXT: &str = "multi-stark/v6/vk"; +/// Domain-separation context string for v6-zk salted Merkle leaf row hashes. +pub const V6ZK_MERKLE_LEAF_CONTEXT: &str = "multi-stark/v6-zk/merkle/leaf"; +/// Domain-separation context string for v6-zk Merkle 2-to-1 internal compressions. +pub const V6ZK_MERKLE_COMPRESS_CONTEXT: &str = "multi-stark/v6-zk/merkle/compress"; +/// Domain-separation context string for v6-zk single-proof Fiat-Shamir transcripts. +pub const V6ZK_TRANSCRIPT_SINGLE_CONTEXT: &str = "multi-stark/v6-zk/transcript/single"; +/// Domain-separation context string for v6-zk batch-proof Fiat-Shamir transcripts. +pub const V6ZK_TRANSCRIPT_BATCH_CONTEXT: &str = "multi-stark/v6-zk/transcript/batch"; +/// Domain-separation context string for v6-zk canonical VK / constraint-graph digests. +pub const V6ZK_VK_CONTEXT: &str = "multi-stark/v6-zk/vk"; + const fn g_const( mut state: [u32; 16], a: usize, @@ -149,6 +160,12 @@ const KEY_TRANSCRIPT_SINGLE: [u32; 8] = derive_context_key(V6_TRANSCRIPT_SINGLE_ const KEY_TRANSCRIPT_BATCH: [u32; 8] = derive_context_key(V6_TRANSCRIPT_BATCH_CONTEXT); const KEY_VK: [u32; 8] = derive_context_key(V6_VK_CONTEXT); +const KEY_ZK_MERKLE_LEAF: [u32; 8] = derive_context_key(V6ZK_MERKLE_LEAF_CONTEXT); +const KEY_ZK_MERKLE_COMPRESS: [u32; 8] = derive_context_key(V6ZK_MERKLE_COMPRESS_CONTEXT); +const KEY_ZK_TRANSCRIPT_SINGLE: [u32; 8] = derive_context_key(V6ZK_TRANSCRIPT_SINGLE_CONTEXT); +const KEY_ZK_TRANSCRIPT_BATCH: [u32; 8] = derive_context_key(V6ZK_TRANSCRIPT_BATCH_CONTEXT); +const KEY_ZK_VK: [u32; 8] = derive_context_key(V6ZK_VK_CONTEXT); + /// Cryptographic domain for BLAKE3 hashing. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum Blake3Domain { @@ -164,6 +181,16 @@ pub enum Blake3Domain { TranscriptBatch, /// Protocol `v6` canonical verifying-key / constraint-graph digest (`derive_key("multi-stark/v6/vk")`). VerifyingKey, + /// Protocol `v6-zk` salted Merkle leaf row hashing (`derive_key("multi-stark/v6-zk/merkle/leaf")`). + ZkMerkleLeaf, + /// Protocol `v6-zk` Merkle internal 2-to-1 compression (`derive_key("multi-stark/v6-zk/merkle/compress")`). + ZkMerkleCompress, + /// Protocol `v6-zk` single-proof Fiat-Shamir transcript (`derive_key("multi-stark/v6-zk/transcript/single")`). + ZkTranscriptSingle, + /// Protocol `v6-zk` batch-proof Fiat-Shamir transcript (`derive_key("multi-stark/v6-zk/transcript/batch")`). + ZkTranscriptBatch, + /// Protocol `v6-zk` canonical verifying-key / constraint-graph digest (`derive_key("multi-stark/v6-zk/vk")`). + ZkVerifyingKey, } impl Blake3Domain { @@ -177,6 +204,11 @@ impl Blake3Domain { Self::TranscriptSingle => Some(V6_TRANSCRIPT_SINGLE_CONTEXT), Self::TranscriptBatch => Some(V6_TRANSCRIPT_BATCH_CONTEXT), Self::VerifyingKey => Some(V6_VK_CONTEXT), + Self::ZkMerkleLeaf => Some(V6ZK_MERKLE_LEAF_CONTEXT), + Self::ZkMerkleCompress => Some(V6ZK_MERKLE_COMPRESS_CONTEXT), + Self::ZkTranscriptSingle => Some(V6ZK_TRANSCRIPT_SINGLE_CONTEXT), + Self::ZkTranscriptBatch => Some(V6ZK_TRANSCRIPT_BATCH_CONTEXT), + Self::ZkVerifyingKey => Some(V6ZK_VK_CONTEXT), } } @@ -191,6 +223,11 @@ impl Blake3Domain { Self::TranscriptSingle => KEY_TRANSCRIPT_SINGLE, Self::TranscriptBatch => KEY_TRANSCRIPT_BATCH, Self::VerifyingKey => KEY_VK, + Self::ZkMerkleLeaf => KEY_ZK_MERKLE_LEAF, + Self::ZkMerkleCompress => KEY_ZK_MERKLE_COMPRESS, + Self::ZkTranscriptSingle => KEY_ZK_TRANSCRIPT_SINGLE, + Self::ZkTranscriptBatch => KEY_ZK_TRANSCRIPT_BATCH, + Self::ZkVerifyingKey => KEY_ZK_VK, } } @@ -204,7 +241,12 @@ impl Blake3Domain { | Self::MerkleCompress | Self::TranscriptSingle | Self::TranscriptBatch - | Self::VerifyingKey => BLAKE3_DERIVE_KEY_MATERIAL, + | Self::VerifyingKey + | Self::ZkMerkleLeaf + | Self::ZkMerkleCompress + | Self::ZkTranscriptSingle + | Self::ZkTranscriptBatch + | Self::ZkVerifyingKey => BLAKE3_DERIVE_KEY_MATERIAL, } } @@ -282,6 +324,11 @@ mod tests { Blake3Domain::TranscriptSingle, Blake3Domain::TranscriptBatch, Blake3Domain::VerifyingKey, + Blake3Domain::ZkMerkleLeaf, + Blake3Domain::ZkMerkleCompress, + Blake3Domain::ZkTranscriptSingle, + Blake3Domain::ZkTranscriptBatch, + Blake3Domain::ZkVerifyingKey, ]; // Test empty, 64-byte single-block, and multi-chunk (>1024 B) inputs. let inputs: Vec> = vec![ @@ -350,7 +397,7 @@ mod tests { } seen.push((domain, got)); } - // All 6 domains must produce pairwise distinct digests on the same input. + // All 11 domains must produce pairwise distinct digests on the same input. for i in 0..seen.len() { for j in (i + 1)..seen.len() { assert_ne!( @@ -394,6 +441,34 @@ mod tests { 0x02E2_2A34, ] ); + // Pinned `v6-zk` constants shared with `cuda/kernels.cu` + // (`BLAKE3_V6ZK_LEAF_CV` and `BLAKE3_V6ZK_COMPRESS_CV`). + assert_eq!( + Blake3Domain::ZkMerkleLeaf.key_words(), + [ + 0x8A66_3924, + 0x051A_410E, + 0xB592_9C7A, + 0x52E6_E08C, + 0x51D3_B0FA, + 0x1D16_87C6, + 0x472E_9E06, + 0x5A32_4ECA, + ] + ); + assert_eq!( + Blake3Domain::ZkMerkleCompress.key_words(), + [ + 0x6E9B_081E, + 0xBAEE_B5DA, + 0x1865_2A0D, + 0xA2D1_B4E1, + 0x9E40_FB01, + 0xE905_254D, + 0x4516_28D5, + 0x3D60_6842, + ] + ); } #[test] diff --git a/src/p3_adapter/mod.rs b/src/p3_adapter/mod.rs index 3eeff1c..dd29dc1 100644 --- a/src/p3_adapter/mod.rs +++ b/src/p3_adapter/mod.rs @@ -13,5 +13,8 @@ pub mod fri_batching; pub mod pcs; #[cfg(not(feature = "cuda"))] pub mod spill; +#[cfg(not(feature = "cuda"))] +pub mod spill_zk; +pub mod zk; pub use air::*; diff --git a/src/p3_adapter/spill.rs b/src/p3_adapter/spill.rs index 5cfc7fb..ab2e894 100644 --- a/src/p3_adapter/spill.rs +++ b/src/p3_adapter/spill.rs @@ -79,7 +79,7 @@ type SpillCommitResult = ( /// Target memory budget per streamed row block during Merkle hashing and FRI /// opening passes (64 MiB). -const STREAM_BLOCK_BYTES: usize = 64 << 20; +pub(super) const STREAM_BLOCK_BYTES: usize = 64 << 20; /// Write buffer size for sequential spill-file packing (8 MiB = 1M field elements). const SPILL_WRITE_CHUNK_ELEMS: usize = 1 << 20; @@ -328,6 +328,68 @@ impl SpillPackWriter { ) } + /// Appends `mat` to the spill file AND computes each row's salted BLAKE3 + /// leaf digest on the fly from `salt_seed`, avoiding a second disk read + /// pass for single-matrix height groups in `v6-zk`. + pub(crate) fn append_matrix_and_hash_salted( + &mut self, + mat: &RowMajorMatrix, + leaf_domain: Blake3Domain, + salt_seed: &[u8; 32], + ) -> (SpilledMatrix, Vec<[u8; 32]>) { + let height = mat.height(); + let width = mat.width(); + let offset = self.next_offset; + let row_bytes = width * size_of::(); + let chunk_rows = ((SPILL_WRITE_CHUNK_ELEMS * size_of::()) / row_bytes.max(64)) + .clamp(1, height.max(1)); + // SAFETY: the loop partitions `0..height` into disjoint contiguous chunks + // and initializes each via `hash_raw_rows_salted_uninit`. + let digests = unsafe { + blake3_simd::alloc_and_fill_digests(height, height, |dst| { + for row_start in (0..height).step_by(chunk_rows) { + let n_rows = (height - row_start).min(chunk_rows); + let elem_start = row_start * width; + let elem_end = (row_start + n_rows) * width; + let byte_len = self.pack_chunk_bytes(&mat.values[elem_start..elem_end]); + blake3_simd::hash_raw_rows_salted_uninit( + &self.scratch[..byte_len], + row_bytes, + height, + row_start, + salt_seed, + &mut dst[row_start..row_start + n_rows], + leaf_domain, + ); + if byte_len > 0 { + self.writer + .write_all(&self.scratch[..byte_len]) + .expect("failed to write matrix chunk to spill file"); + } + } + }) + }; + let total_elems = mat.values.len(); + let bytes = u64::try_from(total_elems) + .expect("matrix element count exceeds u64") + .checked_mul(u64::try_from(size_of::()).unwrap()) + .expect("matrix byte length overflow"); + self.next_offset = self + .next_offset + .checked_add(bytes) + .expect("spill pack offset overflow"); + TOTAL_SPILLED_BYTES.fetch_add(bytes, Ordering::Relaxed); + ( + SpilledMatrix { + file: Arc::clone(&self.spill), + offset, + height, + width, + }, + digests, + ) + } + /// Flushes all buffered writes to the OS file before positional reads. pub(crate) fn flush(&mut self) { self.writer.flush().expect("failed to flush spill file"); @@ -364,7 +426,7 @@ impl SpilledMatrix { } #[inline] - const fn row_bytes(&self) -> usize { + pub(super) const fn row_bytes(&self) -> usize { self.width * size_of::() } @@ -460,7 +522,7 @@ fn bytes_to_goldilocks(raw: &[u8]) -> Vec { /// Binary Merkle-tree padded layer length (matching `p3_merkle_tree::padded_len(raw_len, 2)`). #[inline] -const fn padded_len_binary(raw_len: usize) -> usize { +pub(super) const fn padded_len_binary(raw_len: usize) -> usize { if raw_len <= 1 { raw_len } else { @@ -470,7 +532,9 @@ const fn padded_len_binary(raw_len: usize) -> usize { /// Validates that every matrix height sits on the `ceil(max_height / 2^k)` /// ladder anchored at the tallest matrix (matching `p3_merkle_tree`). -fn validate_reachable_heights_iter(heights: impl Iterator + Clone) -> usize { +pub(super) fn validate_reachable_heights_iter( + heights: impl Iterator + Clone, +) -> usize { let max_height = heights .clone() .max() @@ -494,13 +558,13 @@ fn validate_reachable_heights_iter(heights: impl Iterator + Clone) /// Shared Merkle digest layers and opening-proof traversal for both in-memory /// and disk-spilled binary BLAKE3 Merkle trees. -struct MerkleDigests { - digest_layers: Vec>, - arity_schedule: Vec, +pub(super) struct MerkleDigests { + pub(super) digest_layers: Vec>, + pub(super) arity_schedule: Vec, } impl MerkleDigests { - fn cap(&self, cap_height: usize) -> MerkleCap { + pub(super) fn cap(&self, cap_height: usize) -> MerkleCap { let num_layers = self.digest_layers.len(); let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); let layer_idx = num_layers - 1 - effective_cap_height; @@ -510,7 +574,7 @@ impl MerkleDigests { MerkleCap::new(layer[..cap_len].to_vec()) } - fn open_single_proof(&self, index: usize, cap_height: usize) -> Vec<[u8; 32]> { + pub(super) fn open_single_proof(&self, index: usize, cap_height: usize) -> Vec<[u8; 32]> { let num_layers = self.digest_layers.len(); let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); let proof_levels = num_layers @@ -533,7 +597,11 @@ impl MerkleDigests { proof } - fn open_multi_proof(&self, indices: &[usize], cap_height: usize) -> PrunedMerklePaths { + pub(super) fn open_multi_proof( + &self, + indices: &[usize], + cap_height: usize, + ) -> PrunedMerklePaths { let num_layers = self.digest_layers.len(); let effective_cap_height = cap_height.min(num_layers.saturating_sub(1)); let proof_levels = num_layers @@ -914,7 +982,11 @@ impl SpilledMerkleTree { } } -fn block_rows_for_group(matrices: &[SpilledMatrix], group: &[usize], height: usize) -> usize { +pub(super) fn block_rows_for_group( + matrices: &[SpilledMatrix], + group: &[usize], + height: usize, +) -> usize { let total_row_bytes: usize = group .iter() .map(|&idx| matrices[idx].row_bytes()) @@ -956,7 +1028,10 @@ fn hash_leaf_group_streaming( } } -fn compress_layer_binary(prev_layer: &[[u8; 32]], compress_domain: Blake3Domain) -> Vec<[u8; 32]> { +pub(super) fn compress_layer_binary( + prev_layer: &[[u8; 32]], + compress_domain: Blake3Domain, +) -> Vec<[u8; 32]> { let raw_next = prev_layer.len() / 2; let next_len_padded = padded_len_binary(raw_next); // SAFETY: `compress_pairs_uninit` initializes every element of `dst` (`0..raw_next`). @@ -967,7 +1042,7 @@ fn compress_layer_binary(prev_layer: &[[u8; 32]], compress_domain: Blake3Domain) } } -fn compress_and_inject_prehashed( +pub(super) fn compress_and_inject_prehashed( prev_layer: &[[u8; 32]], rows_digests: &[[u8; 32]], compress_domain: Blake3Domain, @@ -1403,6 +1478,12 @@ impl CapValidatingMmcs for SpillableMmcs { ) -> Result<(), Self::Error> { verify_merkle_cap_len_for_log_height(self.cap_height(), commit, log_max_height) } + + fn empty_multi_proof() -> Self::MultiProof { + PrunedMerklePaths { + sibling_hashes: Vec::new(), + } + } } /// CPU two-adic FRI PCS supporting optional disk-backed LDE spilling with @@ -2081,7 +2162,7 @@ impl, FriMmcs> SpillableTwoAdicFriPcs /// Builds the bit-reversed evaluation coset `GENERATOR * ` of size /// `1 << log_size` in parallel chunks. -fn build_bitrev_coset(log_size: usize) -> Vec { +pub(super) fn build_bitrev_coset(log_size: usize) -> Vec { let size = 1usize << log_size; let g = Val::two_adic_generator(log_size); let mut coset = Val::zero_vec(size); @@ -2376,7 +2457,7 @@ fn compute_inverse_denominators_for_point + ExtensionOf< } } -fn compute_inverse_denominators_from_dims + ExtensionOf>( +pub(super) fn compute_inverse_denominators_from_dims + ExtensionOf>( dims_and_points: &[(Vec, &Vec>)], coset: &[Val], ) -> LinearMap> { @@ -2408,7 +2489,7 @@ fn compute_inverse_denominators_from_dims + ExtensionOf< /// Streams rows `0..h` of `spilled` once in bounded chunks and computes the /// exact barycentric interpolation at every point in `points`, matching /// `Interpolate::interpolate_coset_with_precomputation`. -fn interpolate_spilled_coset>( +pub(super) fn interpolate_spilled_coset>( spilled: &SpilledMatrix, h: usize, points: &[EF], diff --git a/src/p3_adapter/spill_zk.rs b/src/p3_adapter/spill_zk.rs new file mode 100644 index 0000000..d37fb40 --- /dev/null +++ b/src/p3_adapter/spill_zk.rs @@ -0,0 +1,1718 @@ +//! CPU hiding spillable MMCS and 2× interleaved odd-coset FRI PCS for +//! Protocol `v6-zk`. +//! +//! - Leaf salting uses zero salt-matrix storage: each commitment draws a single +//! 256-bit OS CSPRNG `salt_seed` (or the deterministic public seed for +//! preprocessed setup commitments) and derives 128-bit leaf salts on the fly +//! via BLAKE3-CTR (`derive_leaf_salt(salt_seed, height, row_index)`) during +//! both leaf hashing and query opening. +//! - Witness commits interleave uniform CSPRNG rows on the odd coset (`2×` +//! domain extension), while preprocessed commits evaluate degree-`< N` public +//! polynomials onto the `2N · B` LDE coset without adding random rows. +//! - Supports both in-memory multi-buffer SIMD BLAKE3 hashing and disk-spilled +//! streaming commitments/openings with `FriBatching::{Tensor, Horner}` and +//! exact `C2` `MerkleCap` root-count enforcement. + +use std::borrow::Cow; +use std::cmp::Reverse; +use std::collections::HashMap; +use std::marker::PhantomData; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger}; +use p3_commit::{BatchOpening, BatchOpeningRef, Mmcs, OpenedValues, Pcs, PeriodicLdeTable}; +use p3_dft::TwoAdicSubgroupDft; +use p3_field::coset::TwoAdicMultiplicativeCoset; +use p3_field::{ + ExtensionField, Field, PackedFieldExtension, PrimeCharacteristicRing, TwoAdicField, dot_product, +}; +use p3_fri::verifier::FriError; +use p3_fri::{ + BatchMultiOpening, CommitmentWithOpeningPoints, FriParameters, FriProof, + ProverDataWithOpeningPoints, TwoAdicFriFolding, TwoAdicFriFoldingForMmcs, + build_periodic_lde_table_two_adic, prover, +}; +use p3_matrix::bitrev::{BitReversedMatrixView, BitReversibleMatrix}; +use p3_matrix::dense::{RowMajorMatrix, RowMajorMatrixCow}; +use p3_matrix::interpolation::{Interpolate, compute_adjusted_weights}; +use p3_matrix::{Dimensions, Matrix}; +use p3_maybe_rayon::prelude::*; +use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths}; +use p3_symmetric::MerkleCap; +use p3_util::linear_map::LinearMap; +use p3_util::{log2_ceil_usize, log2_strict_usize}; +use tracing::debug_span; + +use super::blake3_simd; +use super::cap::{ + CapValidatingMmcs, validate_fri_commitment_caps, verify_merkle_cap_len_for_log_height, +}; +use super::domain_blake3::Blake3Domain; +use super::fri_batching::{ + FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, +}; +use super::spill::{ + MerkleDigests, STREAM_BLOCK_BYTES, SpillPackWriter, SpilledMatrix, block_rows_for_group, + build_bitrev_coset, compress_and_inject_prehashed, compress_layer_binary, + compute_inverse_denominators_from_dims, interpolate_spilled_coset, padded_len_binary, + validate_reachable_heights_iter, +}; +use super::zk::{ + HidingBatchProof, HidingMultiProof, interleave_random_rows, open_hiding_batch_salts, + open_hiding_multi_salts, preprocessed_salt_seed, random_seed, verify_hiding_batch, + verify_hiding_multi_batch, +}; +use crate::traits::ExtensionOf; +use crate::types::Val; + +type HidingCommitResult = ( + >::Commitment, + HidingSpillableMmcsData>, +); + +/// In-memory salted binary BLAKE3 Merkle tree storing only a 32-byte +/// `salt_seed` (zero salt-matrix memory overhead). +struct FastInMemoryHidingMerkleTree { + leaves: Vec, + digests: MerkleDigests, + salt_seed: [u8; 32], +} + +impl> FastInMemoryHidingMerkleTree { + fn build( + leaves: Vec, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, + salt_seed: [u8; 32], + ) -> Self { + assert!(!leaves.is_empty(), "No matrices given?"); + let max_height = validate_reachable_heights_iter(leaves.iter().map(Matrix::height)); + + let mut order: Vec = (0..leaves.len()).collect(); + order.sort_by_key(|&idx| Reverse(leaves[idx].height())); + + let tallest_end = order + .iter() + .take_while(|&&idx| leaves[idx].height() == max_height) + .count(); + let tallest = &order[..tallest_end]; + let mut cursor = tallest_end; + + let tallest_refs: Vec<&M> = tallest.iter().map(|&idx| &leaves[idx]).collect(); + // SAFETY: `hash_matrix_rows_salted_uninit` initializes every element of `dst` (`0..max_height`). + let first_layer = unsafe { + blake3_simd::alloc_and_fill_digests(padded_len_binary(max_height), max_height, |dst| { + blake3_simd::hash_matrix_rows_salted_uninit( + &tallest_refs, + max_height, + 0, + &salt_seed, + dst, + leaf_domain, + ); + }) + }; + + let mut digest_layers = vec![first_layer]; + let mut arity_schedule = Vec::new(); + + loop { + let prev_layer = digest_layers.last().unwrap().as_slice(); + if prev_layer.len() <= 1 { + break; + } + let step = 2usize; + let raw_next = prev_layer.len() / step; + let next_layer_len = raw_next.next_power_of_two(); + + let inject_start = cursor; + while cursor < order.len() + && leaves[order[cursor]].height().next_power_of_two() == next_layer_len + { + cursor += 1; + } + let inject_group = &order[inject_start..cursor]; + + let next_digests = if inject_group.is_empty() { + compress_layer_binary(prev_layer, compress_domain) + } else { + let inject_refs: Vec<&M> = inject_group.iter().map(|&idx| &leaves[idx]).collect(); + compress_and_inject_in_memory_salted( + prev_layer, + &inject_refs, + &salt_seed, + leaf_domain, + compress_domain, + ) + }; + arity_schedule.push(step); + digest_layers.push(next_digests); + } + + Self { + leaves, + digests: MerkleDigests { + digest_layers, + arity_schedule, + }, + salt_seed, + } + } + + fn cap(&self, cap_height: usize) -> MerkleCap { + self.digests.cap(cap_height) + } + + fn max_height(&self) -> usize { + self.leaves + .iter() + .map(Matrix::height) + .max() + .expect("No committed matrices?") + } + + fn matrix_heights(&self) -> Vec { + self.leaves.iter().map(Matrix::height).collect() + } + + fn dimensions(&self) -> Vec { + self.leaves.iter().map(Matrix::dimensions).collect() + } + + fn open_batch(&self, index: usize, cap_height: usize) -> (Vec>, HidingBatchProof) { + let heights = self.matrix_heights(); + let max_height = self.max_height(); + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + let log_max_height = log2_ceil_usize(max_height); + let openings: Vec> = self + .leaves + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.row(reduced_index).unwrap().into_iter().collect() + }) + .collect(); + let siblings = self.digests.open_single_proof(index, cap_height); + let salts = open_hiding_batch_salts(&self.salt_seed, &heights, index, cap_height); + (openings, HidingBatchProof { salts, siblings }) + } + + fn open_multi_batch( + &self, + indices: &[usize], + cap_height: usize, + ) -> (Vec>>, HidingMultiProof) { + let heights = self.matrix_heights(); + let max_height = self.max_height(); + let log_max_height = log2_ceil_usize(max_height); + let opened_values: Vec>> = indices + .iter() + .map(|&index| { + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + self.leaves + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.row(reduced_index).unwrap().into_iter().collect() + }) + .collect() + }) + .collect(); + let pruned = self.digests.open_multi_proof(indices, cap_height); + let salts = open_hiding_multi_salts(&self.salt_seed, &heights, indices, cap_height); + (opened_values, HidingMultiProof { salts, pruned }) + } +} + +/// Disk-spilled salted binary BLAKE3 Merkle tree storing only a 32-byte +/// `salt_seed` (zero salt-matrix memory or disk overhead). +struct SpilledHidingMerkleTree { + matrices: Vec, + digests: MerkleDigests, + salt_seed: [u8; 32], + original_traces: Mutex>>, +} + +impl SpilledHidingMerkleTree { + fn build_with_prehashed( + matrices: Vec, + original_traces: Vec>, + mut prehashed: Vec>>, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, + salt_seed: [u8; 32], + ) -> Self { + assert!(!matrices.is_empty(), "No matrices given?"); + let max_height = + validate_reachable_heights_iter(matrices.iter().map(SpilledMatrix::height)); + + let mut order: Vec = (0..matrices.len()).collect(); + order.sort_by_key(|&idx| Reverse(matrices[idx].height())); + + let tallest_end = order + .iter() + .take_while(|&&idx| matrices[idx].height() == max_height) + .count(); + let tallest = &order[..tallest_end]; + let mut cursor = tallest_end; + + let first_layer = if let &[single_idx] = tallest + && let Some(mut digests) = prehashed.get_mut(single_idx).and_then(Option::take) + { + debug_assert_eq!(digests.len(), max_height); + digests.resize(padded_len_binary(max_height), [0u8; 32]); + digests + } else { + hash_leaf_group_streaming_salted( + &matrices, + tallest, + max_height, + &salt_seed, + leaf_domain, + ) + }; + let mut digest_layers = vec![first_layer]; + let mut arity_schedule = Vec::new(); + + loop { + let prev_layer = digest_layers.last().unwrap().as_slice(); + if prev_layer.len() <= 1 { + break; + } + let step = 2usize; + let raw_next = prev_layer.len() / step; + let next_layer_len = raw_next.next_power_of_two(); + + let inject_start = cursor; + while cursor < order.len() + && matrices[order[cursor]].height().next_power_of_two() == next_layer_len + { + cursor += 1; + } + let inject_group = &order[inject_start..cursor]; + + let next_digests = if inject_group.is_empty() { + compress_layer_binary(prev_layer, compress_domain) + } else if let &[single_idx] = inject_group + && let Some(rows_digests) = prehashed.get_mut(single_idx).and_then(Option::take) + { + compress_and_inject_prehashed(prev_layer, &rows_digests, compress_domain) + } else { + compress_and_inject_streaming_salted( + prev_layer, + &matrices, + inject_group, + &salt_seed, + leaf_domain, + compress_domain, + ) + }; + arity_schedule.push(step); + digest_layers.push(next_digests); + } + + Self { + matrices, + digests: MerkleDigests { + digest_layers, + arity_schedule, + }, + salt_seed, + original_traces: Mutex::new(original_traces), + } + } + + fn cap(&self, cap_height: usize) -> MerkleCap { + self.digests.cap(cap_height) + } + + fn max_height(&self) -> usize { + self.matrices + .iter() + .map(SpilledMatrix::height) + .max() + .expect("No committed matrices?") + } + + fn matrix_heights(&self) -> Vec { + self.matrices.iter().map(SpilledMatrix::height).collect() + } + + fn dimensions(&self) -> Vec { + self.matrices + .iter() + .map(SpilledMatrix::dimensions) + .collect() + } + + fn open_batch(&self, index: usize, cap_height: usize) -> (Vec>, HidingBatchProof) { + let heights = self.matrix_heights(); + let max_height = self.max_height(); + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + let log_max_height = log2_ceil_usize(max_height); + let openings: Vec> = self + .matrices + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.read_row(reduced_index) + }) + .collect(); + let siblings = self.digests.open_single_proof(index, cap_height); + let salts = open_hiding_batch_salts(&self.salt_seed, &heights, index, cap_height); + (openings, HidingBatchProof { salts, siblings }) + } + + fn open_multi_batch( + &self, + indices: &[usize], + cap_height: usize, + ) -> (Vec>>, HidingMultiProof) { + let heights = self.matrix_heights(); + let max_height = self.max_height(); + let log_max_height = log2_ceil_usize(max_height); + let opened_values: Vec>> = indices + .iter() + .map(|&index| { + assert!( + index < max_height, + "index {index} out of bounds for height {max_height}" + ); + self.matrices + .iter() + .map(|matrix| { + let log2_height = log2_ceil_usize(matrix.height()); + let bits_reduced = log_max_height - log2_height; + let reduced_index = index >> bits_reduced; + matrix.read_row(reduced_index) + }) + .collect() + }) + .collect(); + let pruned = self.digests.open_multi_proof(indices, cap_height); + let salts = open_hiding_multi_salts(&self.salt_seed, &heights, indices, cap_height); + (opened_values, HidingMultiProof { salts, pruned }) + } + + fn spilled_original_trace(&self, idx: usize) -> Option { + let guard = self + .original_traces + .lock() + .expect("original_traces lock poisoned"); + guard.get(idx).and_then(Clone::clone) + } + + fn release_original_traces(&self) { + let mut guard = self + .original_traces + .lock() + .expect("original_traces lock poisoned"); + guard.clear(); + } +} + +fn hash_leaf_group_streaming_salted( + matrices: &[SpilledMatrix], + group: &[usize], + max_height: usize, + salt_seed: &[u8; 32], + leaf_domain: Blake3Domain, +) -> Vec<[u8; 32]> { + let padded = padded_len_binary(max_height); + let block_rows = block_rows_for_group(matrices, group, max_height); + // SAFETY: the loop covers `0..max_height` in contiguous chunks and initializes + // each via `hash_raw_multi_rows_salted_uninit`. + unsafe { + blake3_simd::alloc_and_fill_digests(padded, max_height, |dst| { + for start in (0..max_height).step_by(block_rows) { + let n_rows = (max_height - start).min(block_rows); + let blocks: Vec<(Vec, usize)> = group + .iter() + .map(|&idx| { + let m = &matrices[idx]; + (m.read_raw_rows(start, n_rows), m.row_bytes()) + }) + .collect(); + blake3_simd::hash_raw_multi_rows_salted_uninit( + &blocks, + max_height, + start, + salt_seed, + &mut dst[start..start + n_rows], + leaf_domain, + ); + } + }) + } +} + +fn compress_and_inject_in_memory_salted>( + prev_layer: &[[u8; 32]], + inject_group: &[&M], + salt_seed: &[u8; 32], + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, +) -> Vec<[u8; 32]> { + let next_len = inject_group[0].height(); + let raw_next = prev_layer.len() / 2; + let next_len_padded = padded_len_binary(raw_next); + const BLOCK_ROWS: usize = 1 << 14; + let mut row_digests = vec![[0u8; 32]; next_len.min(BLOCK_ROWS)]; + + // SAFETY: initializes `dst[..next_len]` in contiguous chunks and (if + // `raw_next > next_len`) `dst[next_len..raw_next]`, covering all of `0..raw_next`. + unsafe { + blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { + for start in (0..next_len).step_by(BLOCK_ROWS) { + let n_rows = (next_len - start).min(BLOCK_ROWS); + blake3_simd::hash_matrix_rows_salted( + inject_group, + next_len, + start, + salt_seed, + &mut row_digests[..n_rows], + leaf_domain, + ); + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * start..], + &row_digests[..n_rows], + &mut dst[start..start + n_rows], + compress_domain, + ); + } + + if raw_next > next_len { + let zeros = vec![[0u8; 32]; raw_next - next_len]; + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * next_len..], + &zeros, + &mut dst[next_len..raw_next], + compress_domain, + ); + } + }) + } +} + +fn compress_and_inject_streaming_salted( + prev_layer: &[[u8; 32]], + matrices: &[SpilledMatrix], + inject_group: &[usize], + salt_seed: &[u8; 32], + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, +) -> Vec<[u8; 32]> { + let next_len = matrices[inject_group[0]].height(); + let raw_next = prev_layer.len() / 2; + let next_len_padded = padded_len_binary(raw_next); + let block_rows = block_rows_for_group(matrices, inject_group, next_len); + let mut row_digests = vec![[0u8; 32]; block_rows]; + + // SAFETY: initializes `dst[..next_len]` in contiguous chunks and (if + // `raw_next > next_len`) `dst[next_len..raw_next]`, covering all of `0..raw_next`. + unsafe { + blake3_simd::alloc_and_fill_digests(next_len_padded, raw_next, |dst| { + for start in (0..next_len).step_by(block_rows) { + let n_rows = (next_len - start).min(block_rows); + let blocks: Vec<(Vec, usize)> = inject_group + .iter() + .map(|&idx| { + let m = &matrices[idx]; + (m.read_raw_rows(start, n_rows), m.row_bytes()) + }) + .collect(); + blake3_simd::hash_raw_multi_rows_salted( + &blocks, + next_len, + start, + salt_seed, + &mut row_digests[..n_rows], + leaf_domain, + ); + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * start..], + &row_digests[..n_rows], + &mut dst[start..start + n_rows], + compress_domain, + ); + } + + if raw_next > next_len { + let zeros = vec![[0u8; 32]; raw_next - next_len]; + blake3_simd::compress_and_inject_from_digests_uninit( + &prev_layer[2 * next_len..], + &zeros, + &mut dst[next_len..raw_next], + compress_domain, + ); + } + }) + } +} + +/// Prover data for [`HidingSpillableMmcs`]. +pub struct HidingSpillableMmcsData(HidingSpillableMmcsDataInner); + +enum HidingSpillableMmcsDataInner { + InMemory { + tree: FastInMemoryHidingMerkleTree, + retained_traces: Mutex>>>, + }, + Spilled { + tree: SpilledHidingMerkleTree, + materialized: Vec>, + materialize: fn(&SpilledMatrix) -> M, + }, +} + +impl HidingSpillableMmcsData { + pub const fn is_spilled(&self) -> bool { + matches!(self.0, HidingSpillableMmcsDataInner::Spilled { .. }) + } + + pub(crate) fn spilled_original_trace(&self, idx: usize) -> Option { + match &self.0 { + HidingSpillableMmcsDataInner::InMemory { .. } => None, + HidingSpillableMmcsDataInner::Spilled { tree, .. } => tree.spilled_original_trace(idx), + } + } + + pub(crate) fn take_in_memory_original_trace(&self, idx: usize) -> Option> { + match &self.0 { + HidingSpillableMmcsDataInner::InMemory { + retained_traces, .. + } => { + let mut guard = retained_traces + .lock() + .expect("retained_traces lock poisoned"); + guard.get_mut(idx).and_then(Option::take) + } + HidingSpillableMmcsDataInner::Spilled { .. } => None, + } + } + + pub(crate) fn release_original_traces(&self) { + match &self.0 { + HidingSpillableMmcsDataInner::InMemory { + retained_traces, .. + } => { + let mut guard = retained_traces + .lock() + .expect("retained_traces lock poisoned"); + guard.clear(); + } + HidingSpillableMmcsDataInner::Spilled { tree, .. } => tree.release_original_traces(), + } + } +} + +/// CPU hiding MMCS for Protocol `v6-zk` using domain-separated BLAKE3 +/// (`ZkMerkleLeaf`, `ZkMerkleCompress`) and zero-storage on-the-fly BLAKE3-CTR +/// 128-bit leaf salts. +#[derive(Clone, Debug)] +pub struct HidingSpillableMmcs { + cap_height: usize, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, +} + +impl HidingSpillableMmcs { + /// Creates a Protocol `v6-zk` hiding MMCS. + pub const fn new_v6_zk(cap_height: usize) -> Self { + Self { + cap_height, + leaf_domain: Blake3Domain::ZkMerkleLeaf, + compress_domain: Blake3Domain::ZkMerkleCompress, + } + } + + pub const fn cap_height(&self) -> usize { + self.cap_height + } + + pub const fn leaf_domain(&self) -> Blake3Domain { + self.leaf_domain + } + + pub const fn compress_domain(&self) -> Blake3Domain { + self.compress_domain + } + + pub(crate) fn commit_with_seed>( + &self, + inputs: Vec, + salt_seed: [u8; 32], + ) -> (>::Commitment, HidingSpillableMmcsData) { + let tree = FastInMemoryHidingMerkleTree::build( + inputs, + self.leaf_domain, + self.compress_domain, + salt_seed, + ); + let commitment = tree.cap(self.cap_height); + ( + commitment, + HidingSpillableMmcsData(HidingSpillableMmcsDataInner::InMemory { + tree, + retained_traces: Mutex::new(Vec::new()), + }), + ) + } + + pub(crate) fn commit_in_memory_with_originals( + &self, + ldes: Vec>, + original_traces: Vec>>, + salt_seed: [u8; 32], + ) -> HidingCommitResult { + let tree = FastInMemoryHidingMerkleTree::build( + ldes, + self.leaf_domain, + self.compress_domain, + salt_seed, + ); + let commitment = tree.cap(self.cap_height); + ( + commitment, + HidingSpillableMmcsData(HidingSpillableMmcsDataInner::InMemory { + tree, + retained_traces: Mutex::new(original_traces), + }), + ) + } + + pub(crate) fn commit_spilled_prehashed( + &self, + matrices: Vec, + original_traces: Vec>, + prehashed: Vec>>, + salt_seed: [u8; 32], + ) -> HidingCommitResult { + let count = matrices.len(); + let tree = SpilledHidingMerkleTree::build_with_prehashed( + matrices, + original_traces, + prehashed, + self.leaf_domain, + self.compress_domain, + salt_seed, + ); + let cap = tree.cap(self.cap_height); + let materialized = (0..count).map(|_| OnceLock::new()).collect(); + ( + cap, + HidingSpillableMmcsData(HidingSpillableMmcsDataInner::Spilled { + tree, + materialized, + materialize: SpilledMatrix::read_all, + }), + ) + } + + pub(crate) fn matrix_dimensions>( + &self, + prover_data: &HidingSpillableMmcsData, + ) -> Vec { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => tree.dimensions(), + HidingSpillableMmcsDataInner::Spilled { tree, .. } => tree.dimensions(), + } + } +} + +impl Mmcs for HidingSpillableMmcs { + type ProverData = HidingSpillableMmcsData; + type Commitment = MerkleCap; + type Proof = HidingBatchProof; + type MultiProof = HidingMultiProof; + type Error = MerkleTreeError; + + fn commit>(&self, inputs: Vec) -> (Self::Commitment, Self::ProverData) { + self.commit_with_seed(inputs, random_seed()) + } + + fn open_batch>( + &self, + index: usize, + prover_data: &Self::ProverData, + ) -> BatchOpening { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => { + let (opened_values, opening_proof) = tree.open_batch(index, self.cap_height); + BatchOpening::new(opened_values, opening_proof) + } + HidingSpillableMmcsDataInner::Spilled { tree, .. } => { + let (opened_values, opening_proof) = tree.open_batch(index, self.cap_height); + BatchOpening::new(opened_values, opening_proof) + } + } + } + + fn get_matrices<'a, M: Matrix>(&self, prover_data: &'a Self::ProverData) -> Vec<&'a M> { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => tree.leaves.iter().collect(), + HidingSpillableMmcsDataInner::Spilled { + tree, + materialized, + materialize, + } => tree + .matrices + .iter() + .zip(materialized) + .map(|(spilled, slot)| slot.get_or_init(|| materialize(spilled))) + .collect(), + } + } + + fn get_matrix_heights>(&self, prover_data: &Self::ProverData) -> Vec { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => tree.matrix_heights(), + HidingSpillableMmcsDataInner::Spilled { tree, .. } => tree.matrix_heights(), + } + } + + fn get_max_height>(&self, prover_data: &Self::ProverData) -> usize { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => tree.max_height(), + HidingSpillableMmcsDataInner::Spilled { tree, .. } => tree.max_height(), + } + } + + fn verify_batch( + &self, + commit: &Self::Commitment, + dimensions: &[Dimensions], + index: usize, + batch_opening: BatchOpeningRef<'_, Val, Self>, + ) -> Result<(), Self::Error> { + let (opened_values, opening_proof) = batch_opening.unpack(); + verify_hiding_batch( + self.cap_height, + self.leaf_domain, + self.compress_domain, + commit, + dimensions, + index, + opened_values, + opening_proof, + ) + } + + fn open_multi_batch>( + &self, + indices: &[usize], + prover_data: &Self::ProverData, + ) -> (Vec>>, Self::MultiProof) { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => { + tree.open_multi_batch(indices, self.cap_height) + } + HidingSpillableMmcsDataInner::Spilled { tree, .. } => { + tree.open_multi_batch(indices, self.cap_height) + } + } + } + + fn verify_multi_batch + PartialEq>( + &self, + commit: &Self::Commitment, + dimensions: &[Dimensions], + indices: &[usize], + opened_values: &[Vec], + proof: &Self::MultiProof, + ) -> Result<(), Self::Error> { + verify_hiding_multi_batch( + self.cap_height, + self.leaf_domain, + self.compress_domain, + commit, + dimensions, + indices, + opened_values, + proof, + ) + } +} + +impl CapValidatingMmcs for HidingSpillableMmcs { + fn validate_commitment_cap_for_log_height( + &self, + commit: &Self::Commitment, + log_max_height: usize, + ) -> Result<(), Self::Error> { + verify_merkle_cap_len_for_log_height(self.cap_height, commit, log_max_height) + } + + fn empty_multi_proof() -> Self::MultiProof { + HidingMultiProof { + salts: Vec::new(), + pruned: PrunedMerklePaths { + sibling_hashes: Vec::new(), + }, + } + } +} + +/// CPU 2× interleaved odd-coset hiding two-adic FRI PCS for Protocol `v6-zk`, +/// supporting both in-memory and disk-spilled execution with `FriBatching`. +#[derive(Clone, Debug)] +pub struct HidingSpillableTwoAdicFriPcs { + dft: Dft, + mmcs: HidingSpillableMmcs, + fri: FriParameters, + spill_dir: Option, + batching: FriBatching, +} + +impl HidingSpillableTwoAdicFriPcs { + pub const fn new(dft: Dft, mmcs: HidingSpillableMmcs, fri: FriParameters) -> Self { + Self { + dft, + mmcs, + fri, + spill_dir: None, + batching: FriBatching::Tensor, + } + } + + pub const fn with_batching(mut self, batching: FriBatching) -> Self { + self.batching = batching; + self + } + + pub const fn batching(&self) -> FriBatching { + self.batching + } + + pub const fn leaf_domain(&self) -> Blake3Domain { + self.mmcs.leaf_domain() + } + + pub fn set_spill_dir(&mut self, spill_dir: Option) { + self.spill_dir = spill_dir; + } + + pub fn spill_dir(&self) -> Option<&Path> { + self.spill_dir.as_deref() + } + + /// Computes the blinded `2N · B` LDE of a height-`N` witness matrix by + /// interleaving odd-coset CSPRNG rows (height `2N`) and extending by + /// `log_blowup`. + pub(crate) fn compute_blinded_lde( + &self, + domain: TwoAdicMultiplicativeCoset, + evals: &RowMajorMatrix, + ) -> RowMajorMatrix + where + Dft: TwoAdicSubgroupDft, + { + assert_eq!(domain.size(), evals.height()); + let interleaved = interleave_random_rows(evals); + let shift = Val::GENERATOR / domain.shift(); + self.dft + .coset_lde_batch(interleaved, self.fri.log_blowup, shift) + .bit_reverse_rows() + .to_row_major_matrix() + } + + /// Computes the public `2N · B` LDE of a height-`N` preprocessed matrix + /// (degree `< N < 2N`, NO random rows) for uniform ZK verification. + pub(crate) fn compute_preprocessed_lde( + &self, + domain: TwoAdicMultiplicativeCoset, + evals: RowMajorMatrix, + ) -> RowMajorMatrix + where + Dft: TwoAdicSubgroupDft, + { + assert_eq!(domain.size(), evals.height()); + let shift = Val::GENERATOR / domain.shift(); + self.dft + .coset_lde_batch(evals, self.fri.log_blowup + 1, shift) + .bit_reverse_rows() + .to_row_major_matrix() + } + + pub(crate) fn commit_spilled_ldes_prehashed( + &self, + spilled_ldes: Vec, + original_traces: Option>>, + prehashed: Vec>>, + salt_seed: [u8; 32], + ) -> HidingCommitResult { + let min_height = 1usize << (self.fri.log_blowup + 1); + for lde in &spilled_ldes { + assert!( + lde.height() >= min_height, + "committed ZK LDE height {} is smaller than 2 * blowup ({min_height})", + lde.height() + ); + } + let originals = original_traces.unwrap_or_default(); + self.mmcs + .commit_spilled_prehashed(spilled_ldes, originals, prehashed, salt_seed) + } + + pub(crate) fn commit_in_memory_ldes( + &self, + ldes: Vec>, + ) -> HidingCommitResult { + let min_height = 1usize << (self.fri.log_blowup + 1); + for lde in &ldes { + assert!( + lde.height() >= min_height, + "committed ZK LDE height {} is smaller than 2 * blowup ({min_height})", + lde.height() + ); + } + self.mmcs.commit(ldes) + } + + /// Commits a streaming iterator of witness `(domain, matrix, retain_1x)` + /// items with odd-coset random row interleaving and fresh CSPRNG leaf + /// salting. + pub(crate) fn commit_streaming_with_originals( + &self, + evaluations: &mut dyn Iterator< + Item = (TwoAdicMultiplicativeCoset, RowMajorMatrix, bool), + >, + ) -> Option + where + Dft: TwoAdicSubgroupDft, + { + self.commit_streaming_inner(evaluations, true, random_seed()) + } + + /// Commits a streaming iterator of public preprocessed `(domain, matrix, retain_1x)` + /// items WITHOUT random rows and with the deterministic public preprocessed + /// salt seed so independent prover and verifier setups produce identical + /// `preprocessed_commit` roots. + pub(crate) fn commit_preprocessed_streaming( + &self, + evaluations: &mut dyn Iterator< + Item = (TwoAdicMultiplicativeCoset, RowMajorMatrix, bool), + >, + ) -> Option + where + Dft: TwoAdicSubgroupDft, + { + self.commit_streaming_inner(evaluations, false, preprocessed_salt_seed()) + } + + fn commit_streaming_inner( + &self, + evaluations: &mut dyn Iterator< + Item = (TwoAdicMultiplicativeCoset, RowMajorMatrix, bool), + >, + blind_rows: bool, + salt_seed: [u8; 32], + ) -> Option + where + Dft: TwoAdicSubgroupDft, + { + if let Some(dir) = &self.spill_dir { + let mut lde_pack: Option = None; + let mut orig_pack: Option = None; + let mut spilled_ldes = Vec::new(); + let mut spilled_originals = Vec::new(); + let mut prehashed: Vec>> = Vec::new(); + let mut first_idx_for_height: HashMap> = HashMap::new(); + + for (domain, evals, retain_1x) in evaluations { + if retain_1x { + let writer = orig_pack.get_or_insert_with(|| SpillPackWriter::create(dir)); + spilled_originals.push(Some(writer.append_matrix(&evals))); + } else { + spilled_originals.push(None); + } + let lde = if blind_rows { + self.compute_blinded_lde(domain, &evals) + } else { + self.compute_preprocessed_lde(domain, evals) + }; + let lde_height = lde.height(); + let idx = spilled_ldes.len(); + let writer = lde_pack.get_or_insert_with(|| SpillPackWriter::create(dir)); + match first_idx_for_height.get_mut(&lde_height) { + None => { + let (spilled, digests) = writer.append_matrix_and_hash_salted( + &lde, + self.mmcs.leaf_domain(), + &salt_seed, + ); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + first_idx_for_height.insert(lde_height, Some(idx)); + } + Some(prev) => { + if let Some(prev_idx) = prev.take() { + prehashed[prev_idx] = None; + } + spilled_ldes.push(writer.append_matrix(&lde)); + prehashed.push(None); + } + } + } + + if spilled_ldes.is_empty() { + return None; + } + if let Some(writer) = &mut lde_pack { + writer.flush(); + } + if let Some(writer) = &mut orig_pack { + writer.flush(); + } + let originals = if orig_pack.is_some() { + Some(spilled_originals) + } else { + None + }; + Some(self.commit_spilled_ldes_prehashed(spilled_ldes, originals, prehashed, salt_seed)) + } else { + let mut ldes = Vec::new(); + let mut originals = Vec::new(); + let mut any_retained = false; + for (domain, evals, retain_1x) in evaluations { + if retain_1x { + any_retained = true; + originals.push(Some(evals.clone())); + } else { + originals.push(None); + } + ldes.push(if blind_rows { + self.compute_blinded_lde(domain, &evals) + } else { + self.compute_preprocessed_lde(domain, evals) + }); + } + if ldes.is_empty() { + return None; + } + if any_retained { + Some( + self.mmcs + .commit_in_memory_with_originals(ldes, originals, salt_seed), + ) + } else { + Some(self.mmcs.commit_with_seed(ldes, salt_seed)) + } + } + } +} + +impl Pcs + for HidingSpillableTwoAdicFriPcs +where + EF: ExtensionField + ExtensionOf, + Dft: TwoAdicSubgroupDft, + FriMmcs: CapValidatingMmcs, + Challenger: + FieldChallenger + CanObserve + GrindingChallenger, +{ + type Domain = TwoAdicMultiplicativeCoset; + type Commitment = >::Commitment; + type ProverData = >::ProverData>; + type EvaluationsOnDomain<'a> = BitReversedMatrixView>; + type Proof = FriProof>>; + type Error = FriError>::Error>; + const ZK: bool = true; + + fn natural_domain_for_degree(&self, degree: usize) -> Self::Domain { + TwoAdicMultiplicativeCoset::new(Val::ONE, log2_strict_usize(degree)).unwrap() + } + + fn log_max_lde_height(&self) -> usize { + Val::TWO_ADICITY + } + + fn commit( + &self, + evaluations: impl IntoIterator)>, + ) -> (Self::Commitment, Self::ProverData) { + let mut iter = evaluations.into_iter().map(|(d, m)| (d, m, false)); + self.commit_streaming_with_originals(&mut iter) + .expect("commit requires at least one matrix") + } + + fn get_quotient_ldes( + &self, + evaluations: impl IntoIterator)>, + _num_chunks: usize, + ) -> Vec> { + evaluations + .into_iter() + .map(|(domain, evals)| self.compute_blinded_lde(domain, &evals)) + .collect() + } + + fn commit_ldes(&self, ldes: Vec>) -> (Self::Commitment, Self::ProverData) { + let min_height = 1usize << (self.fri.log_blowup + 1); + for lde in &ldes { + assert!( + lde.height() >= min_height, + "committed ZK LDE height {} is smaller than 2 * blowup ({min_height})", + lde.height() + ); + } + let salt_seed = random_seed(); + if let Some(dir) = &self.spill_dir { + let mut height_counts: HashMap = HashMap::new(); + for lde in &ldes { + *height_counts.entry(lde.height()).or_insert(0) += 1; + } + let mut pack = SpillPackWriter::create(dir); + let mut spilled = Vec::with_capacity(ldes.len()); + let mut prehashed = Vec::with_capacity(ldes.len()); + for lde in ldes { + if height_counts[&lde.height()] == 1 { + let (sp, digests) = pack.append_matrix_and_hash_salted( + &lde, + self.mmcs.leaf_domain(), + &salt_seed, + ); + spilled.push(sp); + prehashed.push(Some(digests)); + } else { + spilled.push(pack.append_matrix(&lde)); + prehashed.push(None); + } + } + pack.flush(); + self.mmcs + .commit_spilled_prehashed(spilled, Vec::new(), prehashed, salt_seed) + } else { + self.mmcs.commit_with_seed(ldes, salt_seed) + } + } + + fn get_evaluations_on_domain<'a>( + &self, + prover_data: &'a Self::ProverData, + idx: usize, + domain: Self::Domain, + ) -> Self::EvaluationsOnDomain<'a> { + match &prover_data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => { + let lde = &tree.leaves[idx]; + if domain.shift() == Val::GENERATOR && lde.height() >= domain.size() { + return lde.split_rows(domain.size()).0.as_cow().bit_reverse_rows(); + } + let poly_height = lde.height() >> self.fri.log_blowup; + let lde_mat = lde.as_view().bit_reverse_rows().to_row_major_matrix(); + self.re_evaluate_from_lde(lde_mat, poly_height, domain) + } + HidingSpillableMmcsDataInner::Spilled { tree, .. } => { + let spilled = &tree.matrices[idx]; + if domain.shift() == Val::GENERATOR && spilled.height() >= domain.size() { + let prefix = spilled.read_rows(0, domain.size()); + let width = prefix.width(); + return RowMajorMatrixCow::new(Cow::Owned(prefix.values), width) + .bit_reverse_rows(); + } + if domain.shift() == Val::ONE + && let Some(orig) = tree.spilled_original_trace(idx) + && orig.height() == domain.size() + { + let natural = orig.read_all(); + let bitrev = natural.as_view().bit_reverse_rows().to_row_major_matrix(); + let width = bitrev.width(); + return RowMajorMatrixCow::new(Cow::Owned(bitrev.values), width) + .bit_reverse_rows(); + } + let poly_height = spilled.height() >> self.fri.log_blowup; + let lde_mat = spilled + .read_all() + .as_view() + .bit_reverse_rows() + .to_row_major_matrix(); + self.re_evaluate_from_lde(lde_mat, poly_height, domain) + } + } + } + + fn open( + &self, + commitment_data_with_opening_points: Vec< + ProverDataWithOpeningPoints<'_, EF, Self::ProverData>, + >, + challenger: &mut Challenger, + ) -> (OpenedValues, Self::Proof) { + let dims_and_points: Vec<(Vec, &Vec>)> = + commitment_data_with_opening_points + .iter() + .map(|(data, points)| { + let dims = self.mmcs.matrix_dimensions(data); + debug_assert_eq!( + dims.len(), + points.len(), + "each matrix should have a corresponding set of evaluation points" + ); + (dims, points) + }) + .collect(); + + let global_max_height = dims_and_points + .iter() + .flat_map(|(dims, _)| dims.iter().map(|d| d.height)) + .max() + .expect("No Matrices Supplied?"); + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for (dims, points) in &dims_and_points { + for (dim, pts) in dims.iter().zip(*points) { + if !pts.is_empty() { + opened_max_width = opened_max_width.max(dim.width); + let lh = log2_strict_usize(dim.height); + openings_per_height[lh] += pts.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); + let log_global_max_height = log2_strict_usize(global_max_height); + + let coset = build_bitrev_coset(log_global_max_height); + let inv_denoms = compute_inverse_denominators_from_dims(&dims_and_points, &coset); + drop(coset); + + let adjusted_weights: LinearMap> = inv_denoms + .iter() + .map(|(point, denoms)| (*point, compute_adjusted_weights(*point, denoms))) + .collect(); + + // Pass 1: Barycentric interpolation over the low coset of size `h = 2N` + // (degree `< 2N` blinded polynomial). + let all_opened_values: OpenedValues = commitment_data_with_opening_points + .iter() + .zip(&dims_and_points) + .map(|((data, points), (dims, _))| { + points + .iter() + .enumerate() + .map(|(mat_idx, points_for_mat)| { + let dim = dims[mat_idx]; + let h = dim.height >> self.fri.log_blowup; + if points_for_mat.is_empty() { + return Vec::new(); + } + match &data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => { + let mat = &tree.leaves[mat_idx]; + let mat_view = mat.as_view(); + let (low_coset, _) = mat_view.split_rows(h); + points_for_mat + .iter() + .map(|&point| { + let _guard = debug_span!( + "evaluate matrix", + dims = %mat.dimensions() + ) + .entered(); + let adj = &adjusted_weights.get(&point).unwrap()[..h]; + let ys = low_coset.interpolate_coset_with_precomputation( + Val::GENERATOR, + point, + adj, + ); + challenger.observe_algebra_slice(&ys); + ys + }) + .collect() + } + HidingSpillableMmcsDataInner::Spilled { tree, .. } => { + let spilled = &tree.matrices[mat_idx]; + let _guard = debug_span!( + "evaluate spilled matrix", + dims = %dim + ) + .entered(); + let evals_per_point = interpolate_spilled_coset( + spilled, + h, + points_for_mat, + &adjusted_weights, + ); + for ys in &evals_per_point { + challenger.observe_algebra_slice(ys); + } + evals_per_point + } + } + }) + .collect() + }) + .collect(); + + drop(adjusted_weights); + + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let packed_col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + EF::ExtensionPacking::packed_ext_powers_capped(*alpha, opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => { + pack_ext_weights::(col_weights) + } + }; + + // Pass 2: Build reduced-opening codewords. + let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; + let mut reduced_openings: [Option>; 33] = core::array::from_fn(|_| None); + + for (((data, points), (dims, _)), openings_for_round) in commitment_data_with_opening_points + .iter() + .zip(&dims_and_points) + .zip(&all_opened_values) + { + for (mat_idx, (points_for_mat, openings_for_mat)) in + points.iter().zip(openings_for_round).enumerate() + { + if points_for_mat.is_empty() || openings_for_mat.is_empty() { + continue; + } + let dim = dims[mat_idx]; + let log_height = log2_strict_usize(dim.height); + let _guard = debug_span!("reduce matrix quotient", dims = %dim).entered(); + + let reduced_opening_for_log_height = reduced_openings[log_height] + .get_or_insert_with(|| ::zero_vec(dim.height)); + debug_assert_eq!(reduced_opening_for_log_height.len(), dim.height); + + let mut point_params = Vec::with_capacity(points_for_mat.len()); + for (&point, openings) in points_for_mat.iter().zip(openings_for_mat) { + let (opening_weight, reduced_val) = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + let w_open = PrimeCharacteristicRing::exp_u64( + alpha, + u64::try_from(num_reduced[log_height]) + .expect("reduced column count exceeds u64"), + ); + let rv: EF = dot_product( + PrimeCharacteristicRing::powers(alpha), + openings.iter().copied(), + ); + num_reduced[log_height] += dim.width; + (w_open, rv) + } + FriBatchingSchedule::Tensor { + col_weights, + open_weights, + } => { + let w_open = open_weights[opening_idx_by_height[log_height]]; + opening_idx_by_height[log_height] += 1; + let rv: EF = + dot_product(col_weights.iter().copied(), openings.iter().copied()); + (w_open, rv) + } + }; + let inv_denom = inv_denoms.get(&point).unwrap().as_slice(); + point_params.push((opening_weight, reduced_val, inv_denom)); + } + + match &data.0 { + HidingSpillableMmcsDataInner::InMemory { tree, .. } => { + let mat = &tree.leaves[mat_idx]; + let mat_compressed: Vec = mat + .as_view() + .rowwise_packed_dot_product::(&packed_col_weights) + .collect(); + for &(opening_weight, reduced_val, inv_denom) in &point_params { + mat_compressed + .par_iter() + .zip(reduced_opening_for_log_height.par_iter_mut()) + .zip(inv_denom.par_iter()) + .for_each(|((&reduced_row, ro), &inv_d)| { + *ro += opening_weight * (reduced_val - reduced_row) * inv_d; + }); + } + } + HidingSpillableMmcsDataInner::Spilled { tree, .. } => { + let spilled = &tree.matrices[mat_idx]; + let row_bytes = spilled.row_bytes().max(size_of::()); + let chunk_rows = (STREAM_BLOCK_BYTES / row_bytes) + .clamp(1, 1 << 14) + .min(dim.height); + for row_start in (0..dim.height).step_by(chunk_rows) { + let n_rows = (dim.height - row_start).min(chunk_rows); + let row_end = row_start + n_rows; + let chunk = spilled.read_rows(row_start, n_rows); + let mat_compressed: Vec = chunk + .as_view() + .rowwise_packed_dot_product::(&packed_col_weights) + .collect(); + drop(chunk); + for &(opening_weight, reduced_val, inv_denom) in &point_params { + mat_compressed + .par_iter() + .zip( + reduced_opening_for_log_height[row_start..row_end] + .par_iter_mut(), + ) + .zip(inv_denom[row_start..row_end].par_iter()) + .for_each(|((&reduced_row, ro), &inv_d)| { + *ro += opening_weight * (reduced_val - reduced_row) * inv_d; + }); + } + } + } + } + } + } + + drop(inv_denoms); + drop(packed_col_weights); + + let fri_input: Vec> = reduced_openings.into_iter().rev().flatten().collect(); + let folding: TwoAdicFriFoldingForMmcs = + TwoAdicFriFolding(PhantomData); + let fri_proof = prover::prove_fri( + &folding, + &self.fri, + fri_input, + challenger, + log_global_max_height, + &commitment_data_with_opening_points, + &self.mmcs, + ); + + (all_opened_values, fri_proof) + } + + fn verify( + &self, + commitments_with_opening_points: Vec< + CommitmentWithOpeningPoints, + >, + proof: &Self::Proof, + challenger: &mut Challenger, + ) -> Result<(), Self::Error> { + // Every committed polynomial in `v6-zk` has degree `< 2 * domain.size()` + // and LDE height `2 * domain.size() * 2^log_blowup`. Double each domain + // before cap validation and FRI verification. + let mut doubled_commitments = Vec::with_capacity(commitments_with_opening_points.len()); + for (comm, mats) in commitments_with_opening_points { + let mut doubled_mats = Vec::with_capacity(mats.len()); + for (domain, pts) in mats { + let ext_log_size = domain.log_size() + 1; + let ext_domain = TwoAdicMultiplicativeCoset::new(domain.shift(), ext_log_size) + .ok_or(FriError::GlobalMaxHeightTooLarge { + log_global_max_height: ext_log_size + self.fri.log_blowup, + two_adicity: Val::TWO_ADICITY, + })?; + doubled_mats.push((ext_domain, pts)); + } + doubled_commitments.push((comm, doubled_mats)); + } + + validate_fri_commitment_caps(&self.fri, proof, &doubled_commitments, &self.mmcs)?; + for (_, round) in &doubled_commitments { + for (_, mat) in round { + for (_, point) in mat { + challenger.observe_algebra_slice(point); + } + } + } + let folding: TwoAdicFriFoldingForMmcs = + TwoAdicFriFolding(PhantomData); + verify_fri_with_batching( + &folding, + &self.fri, + proof, + challenger, + &doubled_commitments, + &self.mmcs, + self.batching, + )?; + Ok(()) + } + + fn build_periodic_lde_table( + &self, + periodic_cols: &[Vec], + trace_domain: Self::Domain, + quotient_domain: Self::Domain, + ) -> PeriodicLdeTable { + build_periodic_lde_table_two_adic(&self.dft, periodic_cols, &trace_domain, "ient_domain) + } +} + +impl, FriMmcs> HidingSpillableTwoAdicFriPcs { + fn re_evaluate_from_lde<'a>( + &self, + lde_mat: RowMajorMatrix, + poly_height: usize, + domain: TwoAdicMultiplicativeCoset, + ) -> BitReversedMatrixView> { + let mut coeffs = self.dft.coset_idft_batch(lde_mat, Val::GENERATOR); + let width = coeffs.width(); + coeffs.values.truncate(poly_height * width); + let target_size = domain.size(); + if target_size >= poly_height { + coeffs.values.resize(target_size * width, Val::ZERO); + } else { + // Fold polynomial modulo `(X^m - shift^m)` so evaluating a degree + // `< poly_height` polynomial on a smaller coset `shift * H_m` (e.g. + // evaluating a degree-`< 2N` blinded trace on `H_N`) is exact. + debug_assert!(poly_height.is_multiple_of(target_size)); + let blocks = poly_height / target_size; + let shift_pow_m = domain + .shift() + .exp_u64(u64::try_from(target_size).expect("domain size exceeds u64")); + let mut factor = shift_pow_m; + for b in 1..blocks { + let src_off = b * target_size * width; + for i in 0..(target_size * width) { + let v = coeffs.values[src_off + i]; + coeffs.values[i] += factor * v; + } + factor *= shift_pow_m; + } + coeffs.values.truncate(target_size * width); + } + let result = self + .dft + .coset_dft_batch(coeffs, domain.shift()) + .bit_reverse_rows() + .to_row_major_matrix(); + let result_width = result.width(); + RowMajorMatrixCow::new(Cow::Owned(result.values), result_width).bit_reverse_rows() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::p3_adapter::zk::csprng_field_vec; + use std::fs; + + fn temp_spill_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!( + "multi-stark-zk-spill-test-{tag}-{}-{nanos}", + std::process::id() + )) + } + + #[test] + fn hiding_mmcs_in_memory_and_spilled_match_and_enforce_soundness() { + let mats = vec![ + RowMajorMatrix::new(csprng_field_vec(64 * 5), 5), + RowMajorMatrix::new(csprng_field_vec(16 * 3), 3), + RowMajorMatrix::new(csprng_field_vec(64 * 2), 2), + RowMajorMatrix::new(csprng_field_vec(4 * 7), 7), + ]; + let dims: Vec = mats.iter().map(Matrix::dimensions).collect(); + let queries = [63usize, 12, 0, 12, 41, 7, 13, 62]; + let fixed_seed = [0x5Au8; 32]; + + for cap_height in [0usize, 1, 2] { + let mmcs = HidingSpillableMmcs::new_v6_zk(cap_height); + let (mem_com, mem_data) = mmcs.commit_with_seed(mats.clone(), fixed_seed); + let (rand_com, _) = mmcs.commit(mats.clone()); + assert_ne!( + mem_com.roots(), + rand_com.roots(), + "distinct CSPRNG salt seeds must yield distinct Merkle caps" + ); + + // Spilled path with same seed must produce bit-identical cap and proofs. + let dir = temp_spill_dir(&format!("cap{cap_height}")); + let mut pack = SpillPackWriter::create(&dir); + let spilled_mats: Vec<_> = mats.iter().map(|m| pack.append_matrix(m)).collect(); + pack.flush(); + let (sp_com, sp_data) = + mmcs.commit_spilled_prehashed(spilled_mats, Vec::new(), Vec::new(), fixed_seed); + assert_eq!(mem_com.roots(), sp_com.roots()); + assert!(sp_data.is_spilled()); + + for &idx in &queries { + let b_mem = mmcs.open_batch(idx, &mem_data); + let b_sp = mmcs.open_batch(idx, &sp_data); + assert_eq!(b_mem.opened_values, b_sp.opened_values); + assert_eq!(b_mem.opening_proof, b_sp.opening_proof); + mmcs.verify_batch( + &mem_com, + &dims, + idx, + BatchOpeningRef::new(&b_mem.opened_values, &b_mem.opening_proof), + ) + .unwrap(); + + // Tampered salt must fail. + let mut bad_proof = b_mem.opening_proof.clone(); + bad_proof.salts[0][0] ^= 1; + assert!(matches!( + mmcs.verify_batch( + &mem_com, + &dims, + idx, + BatchOpeningRef::new(&b_mem.opened_values, &bad_proof), + ), + Err(MerkleTreeError::CapMismatch) + )); + } + + let (vals_mem, multi_mem) = mmcs.open_multi_batch(&queries, &mem_data); + let (vals_sp, multi_sp) = mmcs.open_multi_batch(&queries, &sp_data); + assert_eq!(vals_mem, vals_sp); + assert_eq!(multi_mem, multi_sp); + mmcs.verify_multi_batch(&mem_com, &dims, &queries, &vals_mem, &multi_mem) + .unwrap(); + + // Tampered multi-batch salt must fail. + let mut bad_multi = multi_mem.clone(); + bad_multi.salts[0][0][0] ^= 0x80; + assert!(matches!( + mmcs.verify_multi_batch(&mem_com, &dims, &queries, &vals_mem, &bad_multi), + Err(MerkleTreeError::CapMismatch) + )); + + // Tampered leaf value must fail. + let mut bad_vals = vals_mem.clone(); + bad_vals[0][0][0] += Val::ONE; + assert!( + mmcs.verify_multi_batch(&mem_com, &dims, &queries, &bad_vals, &multi_mem) + .is_err() + ); + + // C2: inflated MerkleCap root count must fail. + let mut inflated_roots = mem_com.roots().to_vec(); + inflated_roots.extend_from_slice(mem_com.roots()); + let inflated = MerkleCap::new(inflated_roots); + assert!(matches!( + mmcs.verify_multi_batch(&inflated, &dims, &queries, &vals_mem, &multi_mem), + Err(MerkleTreeError::CapMismatch) + )); + + drop(sp_data); + drop(pack); + let _ = fs::remove_dir_all(&dir); + } + } +} diff --git a/src/p3_adapter/zk.rs b/src/p3_adapter/zk.rs new file mode 100644 index 0000000..31723fc --- /dev/null +++ b/src/p3_adapter/zk.rs @@ -0,0 +1,987 @@ +//! Protocol `v6-zk` zero-knowledge cryptographic primitives, BLAKE3-CTR leaf +//! salting, odd-coset random row interleaving, telescoping quotient blinding, +//! and hiding Merkle verification shared across CPU and CUDA backends. + +use core::cmp::Reverse; + +use p3_dft::TwoAdicSubgroupDft; +use p3_field::{ExtensionField, PrimeCharacteristicRing, PrimeField64, TwoAdicField}; +use p3_matrix::bitrev::BitReversibleMatrix; +use p3_matrix::dense::RowMajorMatrix; +use p3_matrix::{Dimensions, Matrix}; +use p3_maybe_rayon::prelude::*; +use p3_merkle_tree::{MerkleTreeError, PrunedMerklePaths, PrunedProofError}; +use p3_symmetric::MerkleCap; +use p3_util::{log2_ceil_usize, log2_strict_usize, reverse_bits_len}; +use serde::{Deserialize, Serialize}; + +use super::cap::verify_merkle_cap_len; +use super::domain_blake3::Blake3Domain; +use crate::types::Val; + +/// Per-leaf salt length in bytes (128 bits = 16 bytes) for `v6-zk` hiding +/// Merkle commitments. +pub const ZK_LEAF_SALT_BYTES: usize = 16; + +/// Minimum and default number of base-field (`Goldilocks`) columns in the +/// randomizer polynomial `R(X)` committed inside the quotient MMCS. +/// +/// Under `FriBatching::Tensor` over the cubic extension $\mathbb{F}_{p^3}$, +/// 3 columns (`1, r_0, r_1`) fail to span $\mathbb{F}_{p^3}$ with probability +/// $1/p \approx 2^{-64}$. Using `W_R >= 4` columns (`1, r_0, r_1, r_0 r_1`) +/// reduces span-failure probability to $\le 2/p^2 \approx 2^{-127}$. +pub const ZK_RANDOMIZER_WIDTH: usize = 4; + +/// Context string used to derive the deterministic public salt seed for +/// preprocessed trace commitments in `v6-zk`. +/// +/// Preprocessed traces are public setup data; independent prover and verifier +/// setups MUST derive identical `preprocessed_commit` roots while sharing the +/// uniform hiding MMCS verification format. +const PREPROCESSED_SALT_CONTEXT: &str = "multi-stark/v6-zk/preprocessed-salt"; + +/// Draws a fresh 256-bit cryptographically secure random seed from the OS +/// CSPRNG (`getrandom`). +/// +/// Never stored in the proof or observed into the Fiat-Shamir transcript. +pub fn random_seed() -> [u8; 32] { + let mut seed = [0u8; 32]; + getrandom::fill(&mut seed).expect("OS CSPRNG unavailable for ZK randomness"); + seed +} + +/// Returns the deterministic 256-bit salt seed used solely for public +/// preprocessed commitments so independent prover and verifier `System::new` +/// calls produce identical `preprocessed_commit` digests. +pub fn preprocessed_salt_seed() -> [u8; 32] { + blake3::derive_key(PREPROCESSED_SALT_CONTEXT, b"preprocessed") +} + +/// Deterministically derives the 128-bit leaf salt for `(height, row_index)` +/// on the fly from `salt_seed` via single-block keyed BLAKE3: +/// +/// ```text +/// salt = BLAKE3_keyed(salt_seed, height_u64_le || row_index_u64_le)[0..16] +/// ``` +/// +/// Because this is a single 16-byte keyed BLAKE3 compression, both CPU and +/// CUDA compute leaf salts on the fly during hashing and opening with **zero** +/// salt storage in RAM, VRAM, or disk. +#[inline] +pub fn derive_leaf_salt( + salt_seed: &[u8; 32], + height: usize, + row_index: usize, +) -> [u8; ZK_LEAF_SALT_BYTES] { + let mut msg = [0u8; 16]; + msg[..8].copy_from_slice( + &u64::try_from(height) + .expect("height exceeds u64") + .to_le_bytes(), + ); + msg[8..16].copy_from_slice( + &u64::try_from(row_index) + .expect("row_index exceeds u64") + .to_le_bytes(), + ); + let mut hasher = blake3::Hasher::new_keyed(salt_seed); + hasher.update(&msg); + let digest = hasher.finalize(); + let mut salt = [0u8; ZK_LEAF_SALT_BYTES]; + salt.copy_from_slice(&digest.as_bytes()[..ZK_LEAF_SALT_BYTES]); + salt +} + +/// Samples `count` uniformly distributed canonical Goldilocks field elements +/// using a fresh 256-bit OS CSPRNG seed expanded via BLAKE3 XOF with exact +/// rejection sampling (`< Goldilocks::ORDER_U64`, zero modulo bias). +pub fn csprng_field_vec(count: usize) -> Vec { + if count == 0 { + return Vec::new(); + } + let seed = random_seed(); + csprng_field_vec_from_seed(&seed, count) +} + +/// Deterministic expansion helper behind [`csprng_field_vec`]. +pub(crate) fn csprng_field_vec_from_seed(seed: &[u8; 32], count: usize) -> Vec { + const CHUNK_ELEMS: usize = 4096; + let mut out = vec![Val::ZERO; count]; + let fill_chunk = |chunk_idx: usize, dst: &mut [Val]| { + let mut hasher = blake3::Hasher::new_keyed(seed); + hasher.update( + &u64::try_from(chunk_idx) + .expect("chunk index exceeds u64") + .to_le_bytes(), + ); + let mut xof = hasher.finalize_xof(); + let mut buf = [0u8; 512]; + let mut pos = buf.len(); + for slot in dst.iter_mut() { + loop { + if pos == buf.len() { + xof.fill(&mut buf); + pos = 0; + } + let word = u64::from_le_bytes(buf[pos..pos + 8].try_into().unwrap()); + pos += 8; + if word < Val::ORDER_U64 { + *slot = Val::from_u64(word); + break; + } + } + } + }; + if count <= CHUNK_ELEMS { + fill_chunk(0, &mut out); + } else { + out.par_chunks_mut(CHUNK_ELEMS) + .enumerate() + .for_each(|(chunk_idx, dst)| fill_chunk(chunk_idx, dst)); + } + out +} + +/// Samples `count` uniformly random extension field elements using the OS CSPRNG. +pub fn csprng_extension_vec>(count: usize) -> Vec { + let d = EF::DIMENSION; + let base = csprng_field_vec(count * d); + base.chunks_exact(d) + .map(|coords| { + EF::from_basis_coefficients_slice(coords).expect("extension basis coefficient length") + }) + .collect() +} + +/// Minimum admissible `log2(trace_height)` for Protocol `v6-zk` (Trap 1). +/// +/// In 2× odd-coset blinding (`T(X) = T_0(X) + Z_H(X) b(X)` with `deg(b) < N`), +/// `Q` FRI queries plus out-of-domain openings at `(zeta, zeta * g)` impose up +/// to `2 * Q + 2 * D` base-field linear constraints on `b` (each query can +/// expose `T(x_j)` directly and `T(g x_j)` indirectly via the quotient +/// relation, and each OOD opening over $\mathbb{F}_{p^D}$ imposes `D` base-field +/// equations). Enforcing `N >= (2 * Q + 2 * D).next_power_of_two()` strictly +/// exceeds both `next_pow2(Q + 2)` and the full transition + OOD degree budget. +#[inline] +pub const fn min_zk_log_degree(num_queries: usize, ext_degree: usize) -> usize { + let min_rows = (2 * num_queries + 2 * ext_degree).next_power_of_two(); + log2_strict_usize(min_rows) +} + +/// Doubles `mat` (height `N`, width `W`) to height `2N` by interleaving +/// witness rows on even indices (`2r`) and uniform CSPRNG blinding rows on odd +/// indices (`2r + 1`), matching the ePrint 2024/1037 / Plonky3 odd-coset +/// blinding polynomial `T(X) = T_0(X) + Z_H(X) b(X)`. +pub fn interleave_random_rows(mat: &RowMajorMatrix) -> RowMajorMatrix { + let height = mat.height(); + let width = mat.width(); + if width == 0 { + return RowMajorMatrix::new(Vec::new(), 0); + } + let rand_vals = csprng_field_vec(height * width); + let mut out = vec![Val::ZERO; 2 * height * width]; + out.par_chunks_mut(2 * width) + .enumerate() + .for_each(|(r, pair)| { + let src = &mat.values[r * width..(r + 1) * width]; + let rnd = &rand_vals[r * width..(r + 1) * width]; + pair[..width].copy_from_slice(src); + pair[width..].copy_from_slice(rnd); + }); + RowMajorMatrix::new(out, width) +} + +/// Telescoping half-stride ZK quotient slicing with the committed LDE's +/// `GENERATOR` shift folded in. +/// +/// Given evaluations of the quotient polynomial `Q(X)` (degree `< 2N * q_zk`) +/// on the disjoint quotient domain `GENERATOR * H_{2N * q_zk}` (flattened to +/// `ext_degree` base columns), decomposes +/// +/// ```text +/// Q(X) = sum_{k=0}^{2q - 1} X^{k N} c_k(X), deg(c_k) < N +/// ``` +/// +/// samples `2q - 1` uniform base-field blinding polynomials `rho_0..rho_{2q-2}` +/// of degree `< N` per extension coordinate, and forms `2q` blinded slices of +/// degree `< 2N`: +/// +/// ```text +/// c'_k(X) = c_k(X) - rho_{k-1}(X) + X^N rho_k(X) (rho_{-1} = rho_{2q-1} = 0) +/// ``` +/// +/// Telescoping guarantees `sum_{k=0}^{2q-1} X^{k N} c'_k(X) == Q(X)` identically +/// so verifier OOD recombination at `zeta` uses `zeta^N` with `2 * q_zk` slices. +/// +/// Returns a `(2N) × (2 * q_zk * ext_degree)` matrix of `GENERATOR`-shifted +/// slice coefficients ready for `lde_from_shifted_coefficients`. +pub(crate) fn shifted_quotient_slices_zk( + dft: &impl TwoAdicSubgroupDft, + quotient_evals: RowMajorMatrix, + domain_shift: F, + quotient_degree: usize, +) -> RowMajorMatrix +where + Val: Into, +{ + assert_eq!( + domain_shift, + F::GENERATOR, + "quotient domain shift must equal the LDE shift for the scalings to cancel" + ); + let ext_degree = quotient_evals.width(); + let big_height = quotient_evals.height(); + let log_big_height = log2_strict_usize(big_height); + let num_slices = 2 * quotient_degree; + assert!( + num_slices >= 2 && big_height.is_multiple_of(num_slices), + "ZK quotient domain height {big_height} must be a multiple of 2 * q_zk ({num_slices})" + ); + let n = big_height / num_slices; + let width = num_slices * ext_degree; + + let storage = dft + .dft_batch(quotient_evals) + .bit_reverse_rows() + .to_row_major_matrix(); + let n_inv = F::ONE.div_2exp_u64(u64::try_from(log_big_height).expect("log height exceeds u64")); + let gen_n = F::GENERATOR.exp_u64(u64::try_from(n).expect("trace height exceeds u64")); + let weight_step = gen_n.inverse(); + let weights: Vec = weight_step + .powers() + .take(num_slices) + .map(|w| w * n_inv) + .collect(); + + // Pre-scaled blinding coefficients `tilde_rho[k][r][c] = GENERATOR^r * rho_k[r][c]`. + // Because `GENERATOR != 0`, sampling `tilde_rho` uniformly is identically + // distributed to sampling `rho` uniformly and scaling row `r` by `GENERATOR^r`. + let num_blinders = num_slices - 1; + let rand_base = csprng_field_vec(num_blinders * n * ext_degree); + let tilde_rho: Vec = rand_base.into_iter().map(Into::into).collect(); + + let mut values = F::zero_vec(2 * n * width); + let (low_rows, high_rows) = values.split_at_mut(n * width); + + low_rows + .par_chunks_mut(width) + .enumerate() + .for_each(|(row, out)| { + for (slice_idx, weight) in weights.iter().enumerate() { + let j = slice_idx * n + row; + let src_idx = reverse_bits_len( + big_height.wrapping_sub(j) & (big_height - 1), + log_big_height, + ); + let src = &storage.values[src_idx * ext_degree..(src_idx + 1) * ext_degree]; + let dst = &mut out[slice_idx * ext_degree..(slice_idx + 1) * ext_degree]; + if slice_idx == 0 { + for (d, &s) in dst.iter_mut().zip(src) { + *d = s * *weight; + } + } else { + let prev_rho_off = ((slice_idx - 1) * n + row) * ext_degree; + let prev_rho = &tilde_rho[prev_rho_off..prev_rho_off + ext_degree]; + for ((d, &s), &r) in dst.iter_mut().zip(src).zip(prev_rho) { + *d = s * *weight - r; + } + } + } + }); + + high_rows + .par_chunks_mut(width) + .enumerate() + .for_each(|(row, out)| { + for slice_idx in 0..num_blinders { + let rho_off = (slice_idx * n + row) * ext_degree; + let rho = &tilde_rho[rho_off..rho_off + ext_degree]; + let dst = &mut out[slice_idx * ext_degree..(slice_idx + 1) * ext_degree]; + for (d, &r) in dst.iter_mut().zip(rho) { + *d = gen_n * r; + } + } + // Final slice `num_slices - 1` has degree < n (high rows stay zero). + }); + + RowMajorMatrix::new(values, width) +} + +/// Single-query hiding Merkle opening proof carrying one 128-bit leaf salt per +/// height group encountered along the authentication path plus the sibling +/// hashes up to the Merkle cap. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HidingBatchProof { + pub salts: Vec<[u8; ZK_LEAF_SALT_BYTES]>, + pub siblings: Vec<[u8; 32]>, +} + +/// Multi-query pruned hiding Merkle opening proof carrying deduplicated +/// height-group leaf salts (ordered tallest-first, ascending unique node index +/// within each height group) plus pruned binary Merkle sibling hashes. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct HidingMultiProof { + pub salts: Vec>, + pub pruned: PrunedMerklePaths, +} + +impl PartialEq for HidingMultiProof { + fn eq(&self, other: &Self) -> bool { + self.salts == other.salts && self.pruned.sibling_hashes == other.pruned.sibling_hashes + } +} + +impl Eq for HidingMultiProof {} + +/// One distinct height group within a mixed-height Merkle tree. +#[derive(Clone, Debug)] +pub(crate) struct HeightGroup { + pub(crate) height: usize, + pub(crate) level: usize, + pub(crate) matrices: Vec, +} + +/// Validates reachable matrix heights (`ceil(max_height / 2^k)`) and groups +/// matrix indices stably by strictly descending height. +pub(crate) fn height_groups_tallest_first( + heights: &[usize], +) -> Result<(usize, Vec), MerkleTreeError> { + let max_height = heights + .iter() + .copied() + .max() + .filter(|&h| h > 0) + .ok_or(MerkleTreeError::EmptyBatch)?; + let log_max_height = log2_ceil_usize(max_height); + for &h in heights { + if h == 0 { + return Err(MerkleTreeError::IncompatibleHeights { + height: 0, + max_height, + expected_height: 1, + bits_reduced: log_max_height, + }); + } + let bits_reduced = log_max_height - log2_ceil_usize(h); + let expected_height = ((max_height - 1) >> bits_reduced) + 1; + if h != expected_height { + return Err(MerkleTreeError::IncompatibleHeights { + height: h, + max_height, + expected_height, + bits_reduced, + }); + } + } + + let mut order: Vec = (0..heights.len()).collect(); + order.sort_by_key(|&idx| Reverse(heights[idx])); + + let mut groups: Vec = Vec::new(); + let mut cursor = 0usize; + while cursor < order.len() { + let h = heights[order[cursor]]; + let start = cursor; + while cursor < order.len() && heights[order[cursor]] == h { + cursor += 1; + } + let level = log_max_height - log2_ceil_usize(h); + groups.push(HeightGroup { + height: h, + level, + matrices: order[start..cursor].to_vec(), + }); + } + Ok((max_height, groups)) +} + +/// Computes the single-query leaf salts on the fly from `salt_seed` (zero +/// salt storage). +pub(crate) fn open_hiding_batch_salts( + salt_seed: &[u8; 32], + heights: &[usize], + index: usize, + cap_height: usize, +) -> Vec<[u8; ZK_LEAF_SALT_BYTES]> { + let (max_height, groups) = height_groups_tallest_first(heights).expect("valid tree heights"); + let log_max_height = log2_ceil_usize(max_height); + let effective_cap_height = cap_height.min(log_max_height); + let proof_levels = log_max_height - effective_cap_height; + groups + .iter() + .filter(|g| g.level <= proof_levels) + .map(|g| derive_leaf_salt(salt_seed, g.height, index >> g.level)) + .collect() +} + +/// Computes the pruned multi-batch leaf salts on the fly from `salt_seed` +/// (zero salt storage), in tallest-first height-group order and ascending +/// unique node index order within each height group. +pub(crate) fn open_hiding_multi_salts( + salt_seed: &[u8; 32], + heights: &[usize], + indices: &[usize], + cap_height: usize, +) -> Vec> { + if indices.is_empty() { + return Vec::new(); + } + let (max_height, groups) = height_groups_tallest_first(heights).expect("valid tree heights"); + let log_max_height = log2_ceil_usize(max_height); + let effective_cap_height = cap_height.min(log_max_height); + let proof_levels = log_max_height - effective_cap_height; + + groups + .iter() + .filter(|g| g.level <= proof_levels) + .map(|g| { + let mut nodes: Vec = indices.iter().map(|&idx| idx >> g.level).collect(); + nodes.sort_unstable(); + nodes.dedup(); + nodes + .into_iter() + .map(|node_idx| derive_leaf_salt(salt_seed, g.height, node_idx)) + .collect() + }) + .collect() +} + +#[inline] +fn hash_leaf_rows_with_salt>( + leaf_domain: Blake3Domain, + opened_rows: &[R], + matrix_indices: &[usize], + salt: &[u8; ZK_LEAF_SALT_BYTES], +) -> [u8; 32] { + let mut hasher = leaf_domain.hasher(); + for &mat_idx in matrix_indices { + for &elem in opened_rows[mat_idx].as_ref() { + hasher.update(&elem.as_canonical_u64().to_le_bytes()); + } + } + hasher.update(salt); + hasher.finalize().into() +} + +#[inline] +fn compress_pair_domain( + compress_domain: Blake3Domain, + left: &[u8; 32], + right: &[u8; 32], +) -> [u8; 32] { + let mut block = [0u8; 64]; + block[..32].copy_from_slice(left); + block[32..].copy_from_slice(right); + compress_domain.hash_bytes(&block) +} + +/// Verifies a single-query salted binary Merkle batch opening, enforcing exact +/// `C2` `MerkleCap` root count, exact row widths, exact salt count, and exact +/// sibling count. +#[allow(clippy::too_many_arguments)] +pub(crate) fn verify_hiding_batch( + cap_height: usize, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, + commit: &MerkleCap, + dimensions: &[Dimensions], + index: usize, + opened_values: &[Vec], + proof: &HidingBatchProof, +) -> Result<(), MerkleTreeError> { + verify_merkle_cap_len(cap_height, commit, dimensions)?; + if dimensions.len() != opened_values.len() { + return Err(MerkleTreeError::WrongBatchSize); + } + for (matrix, (dim, row)) in dimensions.iter().zip(opened_values).enumerate() { + if row.len() != dim.width { + return Err(MerkleTreeError::WrongWidth { + matrix, + expected: dim.width, + got: row.len(), + }); + } + } + let heights: Vec = dimensions.iter().map(|d| d.height).collect(); + let (max_height, groups) = height_groups_tallest_first(&heights)?; + if index >= max_height { + return Err(MerkleTreeError::IndexOutOfBounds { max_height, index }); + } + let log_max_height = log2_ceil_usize(max_height); + let effective_cap_height = cap_height.min(log_max_height); + let proof_levels = log_max_height - effective_cap_height; + + if proof.siblings.len() != proof_levels { + return Err(MerkleTreeError::WrongHeight { + expected_proof_len: proof_levels, + num_siblings: proof.siblings.len(), + }); + } + let expected_salt_groups = groups.iter().filter(|g| g.level <= proof_levels).count(); + if proof.salts.len() != expected_salt_groups { + return Err(MerkleTreeError::WrongBatchSize); + } + + let mut digest = hash_leaf_rows_with_salt( + leaf_domain, + opened_values, + &groups[0].matrices, + &proof.salts[0], + ); + let mut group_cursor = 1usize; + let mut salt_cursor = 1usize; + let mut idx = index; + + for (level, sibling) in proof.siblings.iter().enumerate() { + digest = if idx & 1 == 0 { + compress_pair_domain(compress_domain, &digest, sibling) + } else { + compress_pair_domain(compress_domain, sibling, &digest) + }; + idx >>= 1; + let next_level = level + 1; + if group_cursor < groups.len() && groups[group_cursor].level == next_level { + let injected = hash_leaf_rows_with_salt( + leaf_domain, + opened_values, + &groups[group_cursor].matrices, + &proof.salts[salt_cursor], + ); + digest = compress_pair_domain(compress_domain, &digest, &injected); + group_cursor += 1; + salt_cursor += 1; + } + } + + if idx < commit.num_roots() && commit[idx] == digest { + Ok(()) + } else { + Err(MerkleTreeError::CapMismatch) + } +} + +/// Verifies a pruned multi-query salted binary Merkle batch opening, enforcing +/// exact `C2` `MerkleCap` root count, exact row widths, duplicate/merged row +/// consistency, exact deduplicated salt counts, and exact pruned sibling count. +#[allow(clippy::too_many_arguments)] +pub(crate) fn verify_hiding_multi_batch + PartialEq>( + cap_height: usize, + leaf_domain: Blake3Domain, + compress_domain: Blake3Domain, + commit: &MerkleCap, + dimensions: &[Dimensions], + indices: &[usize], + opened_values: &[Vec], + proof: &HidingMultiProof, +) -> Result<(), MerkleTreeError> { + verify_merkle_cap_len(cap_height, commit, dimensions)?; + let heights: Vec = dimensions.iter().map(|d| d.height).collect(); + let (max_height, groups) = height_groups_tallest_first(&heights)?; + + if indices.len() != opened_values.len() { + return Err(MerkleTreeError::WrongBatchSize); + } + if indices.is_empty() { + if !proof.salts.is_empty() { + return Err(MerkleTreeError::WrongBatchSize); + } + if !proof.pruned.sibling_hashes.is_empty() { + return Err(MerkleTreeError::MalformedPrunedProof( + PrunedProofError::SiblingCountMismatch { + expected: 0, + got: proof.pruned.sibling_hashes.len(), + }, + )); + } + return Ok(()); + } + + for (q_idx, (&leaf_idx, query_rows)) in indices.iter().zip(opened_values).enumerate() { + let _ = q_idx; + if leaf_idx >= max_height { + return Err(MerkleTreeError::IndexOutOfBounds { + max_height, + index: leaf_idx, + }); + } + if query_rows.len() != dimensions.len() { + return Err(MerkleTreeError::WrongBatchSize); + } + for (matrix, (dim, row)) in dimensions.iter().zip(query_rows).enumerate() { + if row.as_ref().len() != dim.width { + return Err(MerkleTreeError::WrongWidth { + matrix, + expected: dim.width, + got: row.as_ref().len(), + }); + } + } + } + + let log_max_height = log2_ceil_usize(max_height); + let effective_cap_height = cap_height.min(log_max_height); + let proof_levels = log_max_height - effective_cap_height; + + let expected_salt_groups = groups.iter().filter(|g| g.level <= proof_levels).count(); + if proof.salts.len() != expected_salt_groups { + return Err(MerkleTreeError::WrongBatchSize); + } + + // Group queries by leaf index in ascending order, verifying that duplicate + // queries agree on all opened rows. + let mut query_order: Vec<(usize, usize)> = indices + .iter() + .enumerate() + .map(|(q, &idx)| (idx, q)) + .collect(); + query_order.sort_unstable_by_key(|&(idx, _)| idx); + + struct FrontierNode { + index: usize, + digest: [u8; 32], + queries: Vec, + } + + let mut unique_leaves: Vec<(usize, Vec)> = Vec::new(); + for (leaf_idx, q) in query_order { + if let Some((last_idx, qs)) = unique_leaves.last_mut() + && *last_idx == leaf_idx + { + let lead = qs[0]; + if opened_values[q] != opened_values[lead] { + let slot = unique_leaves.len() - 1; + return Err(MerkleTreeError::MalformedPrunedProof( + PrunedProofError::InconsistentDuplicateOpenings { slot }, + )); + } + qs.push(q); + } else { + unique_leaves.push((leaf_idx, vec![q])); + } + } + + if proof.salts[0].len() != unique_leaves.len() { + return Err(MerkleTreeError::WrongBatchSize); + } + let mut frontier: Vec = unique_leaves + .into_iter() + .zip(&proof.salts[0]) + .map(|((leaf_idx, qs), salt)| { + let digest = hash_leaf_rows_with_salt( + leaf_domain, + &opened_values[qs[0]], + &groups[0].matrices, + salt, + ); + FrontierNode { + index: leaf_idx, + digest, + queries: qs, + } + }) + .collect(); + + let siblings = &proof.pruned.sibling_hashes; + let mut sib_cursor = 0usize; + let mut group_cursor = 1usize; + let mut salt_cursor = 1usize; + + for level in 0..proof_levels { + let mut next_frontier: Vec = Vec::with_capacity(frontier.len()); + let mut i = 0usize; + while i < frontier.len() { + let parent_idx = frontier[i].index >> 1; + let is_left = (frontier[i].index & 1) == 0; + if is_left && i + 1 < frontier.len() && (frontier[i + 1].index >> 1) == parent_idx { + let left = &frontier[i]; + let right = &frontier[i + 1]; + let digest = compress_pair_domain(compress_domain, &left.digest, &right.digest); + let mut queries = Vec::with_capacity(left.queries.len() + right.queries.len()); + queries.extend_from_slice(&left.queries); + queries.extend_from_slice(&right.queries); + next_frontier.push(FrontierNode { + index: parent_idx, + digest, + queries, + }); + i += 2; + } else { + let Some(sibling) = siblings.get(sib_cursor) else { + // Sibling list ended early; report mismatch. + return Err(MerkleTreeError::MalformedPrunedProof( + PrunedProofError::SiblingCountMismatch { + expected: sib_cursor + 1, + got: siblings.len(), + }, + )); + }; + sib_cursor += 1; + let node = &frontier[i]; + let digest = if is_left { + compress_pair_domain(compress_domain, &node.digest, sibling) + } else { + compress_pair_domain(compress_domain, sibling, &node.digest) + }; + next_frontier.push(FrontierNode { + index: parent_idx, + digest, + queries: node.queries.clone(), + }); + i += 1; + } + } + + let next_level = level + 1; + if group_cursor < groups.len() && groups[group_cursor].level == next_level { + let group = &groups[group_cursor]; + let group_salts = &proof.salts[salt_cursor]; + if group_salts.len() != next_frontier.len() { + return Err(MerkleTreeError::WrongBatchSize); + } + for (slot, (node, salt)) in next_frontier.iter_mut().zip(group_salts).enumerate() { + let lead = node.queries[0]; + for &q in &node.queries[1..] { + for &mat_idx in &group.matrices { + if opened_values[q][mat_idx] != opened_values[lead][mat_idx] { + return Err(MerkleTreeError::MalformedPrunedProof( + PrunedProofError::InconsistentGroupOpening { + slot, + matrix: mat_idx, + }, + )); + } + } + } + let injected = hash_leaf_rows_with_salt( + leaf_domain, + &opened_values[lead], + &group.matrices, + salt, + ); + node.digest = compress_pair_domain(compress_domain, &node.digest, &injected); + } + group_cursor += 1; + salt_cursor += 1; + } + + frontier = next_frontier; + } + + if sib_cursor != siblings.len() { + return Err(MerkleTreeError::MalformedPrunedProof( + PrunedProofError::SiblingCountMismatch { + expected: sib_cursor, + got: siblings.len(), + }, + )); + } + + for node in &frontier { + if node.index >= commit.num_roots() || commit[node.index] != node.digest { + return Err(MerkleTreeError::CapMismatch); + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::p3_adapter::pcs::lde_from_shifted_coefficients; + use crate::types::ExtVal3; + use p3_dft::Radix2DitParallel; + use p3_field::{BasedVectorSpace, Field}; + + #[test] + fn derive_leaf_salt_matches_single_block_keyed_blake3_and_is_distinct() { + let seed: [u8; 32] = core::array::from_fn(|i| u8::try_from((i * 19 + 7) & 0xff).unwrap()); + let s0 = derive_leaf_salt(&seed, 1024, 0); + let s1 = derive_leaf_salt(&seed, 1024, 1); + let s2 = derive_leaf_salt(&seed, 512, 0); + assert_ne!(s0, s1); + assert_ne!(s0, s2); + assert_ne!(s1, s2); + assert_eq!(s0, derive_leaf_salt(&seed, 1024, 0)); + + // Cross-check directly against raw BLAKE3 single-block KEYED_HASH compression + // (matching `cuda/kernels.cu::blake3_derive_leaf_salt`). + const KEYED_HASH: u32 = 1 << 4; + const CHUNK_START: u32 = 1 << 0; + const CHUNK_END: u32 = 1 << 1; + const ROOT: u32 = 1 << 3; + const IV: [u32; 8] = [ + 0x6A09_E667, + 0xBB67_AE85, + 0x3C6E_F372, + 0xA54F_F53A, + 0x510E_527F, + 0x9B05_688C, + 0x1F83_D9AB, + 0x5BE0_CD19, + ]; + const MSG_SCHEDULE: [[usize; 16]; 7] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8], + [3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1], + [10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6], + [12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4], + [9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7], + [11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13], + ]; + let g = |mut st: [u32; 16], a: usize, b: usize, c: usize, d: usize, x: u32, y: u32| { + st[a] = st[a].wrapping_add(st[b]).wrapping_add(x); + st[d] = (st[d] ^ st[a]).rotate_right(16); + st[c] = st[c].wrapping_add(st[d]); + st[b] = (st[b] ^ st[c]).rotate_right(12); + st[a] = st[a].wrapping_add(st[b]).wrapping_add(y); + st[d] = (st[d] ^ st[a]).rotate_right(8); + st[c] = st[c].wrapping_add(st[d]); + st[b] = (st[b] ^ st[c]).rotate_right(7); + st + }; + let cv: [u32; 8] = core::array::from_fn(|i| { + u32::from_le_bytes(seed[4 * i..4 * i + 4].try_into().unwrap()) + }); + let height = 1024u64; + let row = 37u64; + let mut msg = [0u32; 16]; + msg[0] = u32::try_from(height & 0xffff_ffff).unwrap(); + msg[1] = u32::try_from(height >> 32).unwrap(); + msg[2] = u32::try_from(row & 0xffff_ffff).unwrap(); + msg[3] = u32::try_from(row >> 32).unwrap(); + let mut st = [ + cv[0], + cv[1], + cv[2], + cv[3], + cv[4], + cv[5], + cv[6], + cv[7], + IV[0], + IV[1], + IV[2], + IV[3], + 0, + 0, + 16, + KEYED_HASH | CHUNK_START | CHUNK_END | ROOT, + ]; + for sched in &MSG_SCHEDULE { + st = g(st, 0, 4, 8, 12, msg[sched[0]], msg[sched[1]]); + st = g(st, 1, 5, 9, 13, msg[sched[2]], msg[sched[3]]); + st = g(st, 2, 6, 10, 14, msg[sched[4]], msg[sched[5]]); + st = g(st, 3, 7, 11, 15, msg[sched[6]], msg[sched[7]]); + st = g(st, 0, 5, 10, 15, msg[sched[8]], msg[sched[9]]); + st = g(st, 1, 6, 11, 12, msg[sched[10]], msg[sched[11]]); + st = g(st, 2, 7, 8, 13, msg[sched[12]], msg[sched[13]]); + st = g(st, 3, 4, 9, 14, msg[sched[14]], msg[sched[15]]); + } + let mut expected = [0u8; 16]; + for i in 0..4 { + expected[4 * i..4 * i + 4].copy_from_slice(&(st[i] ^ st[i + 8]).to_le_bytes()); + } + assert_eq!( + derive_leaf_salt( + &seed, + usize::try_from(height).unwrap(), + usize::try_from(row).unwrap() + ), + expected + ); + } + + #[test] + fn shifted_quotient_slices_zk_recombines_identically_and_randomizes() { + let dft = Radix2DitParallel::::default(); + let zeta = ExtVal3::from_basis_coefficients_slice(&[ + Val::from_u64(12_345_678), + Val::from_u64(98_765_432), + Val::from_u64(55_555_555), + ]) + .unwrap(); + + for log_n in [2usize, 4, 6] { + let n = 1usize << log_n; + for q_zk in [1usize, 2, 4] { + let big_height = 2 * n * q_zk; + let ext_d = 3usize; + let coeffs = RowMajorMatrix::new(csprng_field_vec(big_height * ext_d), ext_d); + // Evaluate Q(zeta) directly from polynomial coefficients. + let mut q_at_zeta = ExtVal3::ZERO; + let mut zeta_pow = ExtVal3::ONE; + for r in 0..big_height { + let c = ExtVal3::from_basis_coefficients_slice( + &coeffs.values[r * ext_d..(r + 1) * ext_d], + ) + .unwrap(); + q_at_zeta += c * zeta_pow; + zeta_pow *= zeta; + } + + // Evaluate Q on the disjoint quotient domain `GENERATOR * H_{big_height}`. + let q_evals = dft + .coset_dft_batch(coeffs, Val::GENERATOR) + .to_row_major_matrix(); + + let slices_a = + shifted_quotient_slices_zk(&dft, q_evals.clone(), Val::GENERATOR, q_zk); + let slices_b = shifted_quotient_slices_zk(&dft, q_evals, Val::GENERATOR, q_zk); + assert_eq!(slices_a.height(), 2 * n); + assert_eq!(slices_a.width(), 2 * q_zk * ext_d); + assert_ne!( + slices_a.values, slices_b.values, + "telescoping quotient blinding must randomize slices across calls" + ); + + // Reconstruct LDE and verify recombination at zeta matches Q(zeta) exactly! + for slices in [slices_a, slices_b] { + let lde = lde_from_shifted_coefficients(&dft, slices, 2); + // Un-bit-reverse and take coset iDFT to read actual slice polynomials. + let natural_lde = lde.as_view().bit_reverse_rows().to_row_major_matrix(); + let recovered = dft.coset_idft_batch(natural_lde, Val::GENERATOR); + let width = recovered.width(); + // High coefficients (rows >= 2n) must be identically zero (degree < 2n). + for r in (2 * n)..recovered.height() { + for c in 0..width { + assert_eq!( + recovered.values[r * width + c], + Val::ZERO, + "slice degree exceeded 2n at row {r} col {c}" + ); + } + } + // Evaluate each slice polynomial at zeta and recombine with zeta^n. + let num_slices = 2 * q_zk; + let mut slice_evals = vec![ExtVal3::ZERO; width]; + let mut zp = ExtVal3::ONE; + for r in 0..(2 * n) { + for (c, eval) in slice_evals.iter_mut().enumerate().take(width) { + *eval += zp * recovered.values[r * width + c]; + } + zp *= zeta; + } + let zeta_pow_n = zeta.exp_power_of_2(log_n); + let mut recombined = ExtVal3::ZERO; + let mut zn_pow = ExtVal3::ONE; + for s in 0..num_slices { + let chunk = &slice_evals[s * ext_d..(s + 1) * ext_d]; + let basis_val = (0..ext_d).fold(ExtVal3::ZERO, |acc, idx| { + let basis = ExtVal3::from_basis_coefficients_fn(|j| { + if j == idx { Val::ONE } else { Val::ZERO } + }); + acc + chunk[idx] * basis + }); + recombined += zn_pow * basis_val; + zn_pow *= zeta_pow_n; + } + assert_eq!( + recombined, q_at_zeta, + "recombined blinded quotient mismatch at n={n}, q_zk={q_zk}" + ); + } + } + } + } +} diff --git a/src/prover.rs b/src/prover.rs index bfbd520..e5600be 100644 --- a/src/prover.rs +++ b/src/prover.rs @@ -499,6 +499,10 @@ where .filter_map(|(l, &is_active)| is_active.then_some(l)) .collect(); + let is_zk = self.config.is_zk(); + let min_log_degree = self.config.min_log_degree(); + let max_log_degree = self.config.max_log_degree(); + // Cost: "Stage 1 commit" — coset LDE (FFT) of each trace from n_i to // n_i·B rows (an iDFT plus B coset DFTs per column), then Merkle // tree. FFT work: Σ w_i · (B+1) · n_i · log₂(n_i). @@ -513,6 +517,17 @@ where .map(|((ci, trace), lookup)| { let degree = trace.height(); let log_degree = log2_strict_usize(degree); + if is_zk { + assert!( + log_degree >= min_log_degree, + "circuit {ci}: trace height {degree} (2^{log_degree}) is below v6-zk minimum height {} (2^{min_log_degree})", + 1usize << min_log_degree, + ); + assert!( + log_degree <= max_log_degree, + "circuit {ci}: trace log_degree {log_degree} exceeds v6-zk max_log_degree {max_log_degree}", + ); + } let trace_domain = pcs.natural_domain_for_degree(degree); log_degrees.push(log_degree); let retain_1x = !lookup.is_materialized() && self.circuits[ci].num_lookups > 0; @@ -552,6 +567,9 @@ where I::Item: Into>>, { let pcs = self.config.pcs(); + let is_zk = self.config.is_zk(); + let min_log_degree = self.config.min_log_degree(); + let max_log_degree = self.config.max_log_degree(); let mut active = Vec::with_capacity(self.circuits.len()); let mut active_indices = Vec::new(); let mut log_degrees = Vec::new(); @@ -570,6 +588,18 @@ where active.push(false); return None; } + let log_degree = log2_strict_usize(height); + if is_zk { + assert!( + log_degree >= min_log_degree, + "circuit {ci}: trace height {height} (2^{log_degree}) is below v6-zk minimum height {} (2^{min_log_degree})", + 1usize << min_log_degree, + ); + assert!( + log_degree <= max_log_degree, + "circuit {ci}: trace log_degree {log_degree} exceeds v6-zk max_log_degree {max_log_degree}", + ); + } if circuit.preprocessed_height != 0 { assert_eq!( height, circuit.preprocessed_height, @@ -578,7 +608,7 @@ where } active.push(true); active_indices.push(ci); - log_degrees.push(log2_strict_usize(height)); + log_degrees.push(log_degree); let slot_widths: Vec = circuit .graph .lookups @@ -626,6 +656,7 @@ where mut acc: SC::Challenge, ) -> Proof { let pcs = self.config.pcs(); + let is_zk = self.config.is_zk(); let Stage1 { active, active_indices, @@ -634,6 +665,8 @@ where stage_1_trace_data, lookups: active_lookups, } = stage_1; + let num_active = active_indices.len(); + let use_zk_acc_mask = is_zk && num_active > 1; // Canonical index -> active position (None = inactive). let mut active_pos: Vec> = vec![None; active.len()]; for (pos, &ci) in active_indices.iter().enumerate() { @@ -772,12 +805,63 @@ where // Cost: "Stage 2 commit" — LDE + Merkle for flattened extension traces. // FFT work: Σ w2_i · D · (B+1) · n_i · log₂(n_i). let _g = tracing::info_span!("stark/stage2_commit").entered(); - let evaluations = stage_2_traces.into_iter().map(|trace| { - let degree = trace.height(); - let trace_domain = pcs.natural_domain_for_degree(degree); - (trace_domain, flatten_to_base(trace)) - }); - let (commitment, data) = pcs.commit(evaluations.collect()); + let mut stage_2_traces = stage_2_traces; + let mut intermediate_accumulators = intermediate_accumulators; + let evaluations: Vec<_> = if use_zk_acc_mask { + let ext_d = >>::D; + // Move boundary injection to row 0 (X = 1) so every active + // circuit shares the common point X = 1 with the boundary + // mask matrix `U`. + let mut prev_true = acc; + for (trace, &true_acc) in + stage_2_traces.iter_mut().zip(&intermediate_accumulators) + { + let delta_true = true_acc - prev_true; + crate::lookup::apply_first_row_delta_shift(trace, delta_true); + prev_true = true_acc; + } + // Blind interior accumulators `0..num_active - 1` with fresh + // CSPRNG extension masks `mu_p`, leaving the final accumulator + // exact (`0` for single proofs, shard residual for batches). + let mask_cols = (num_active - 1) * ext_d; + let mu_base = self.config.sample_zk_base_randomness(mask_cols); + for p in 0..(num_active - 1) { + let mu = + SC::Challenge::from_basis_coefficients_fn(|c| mu_base[p * ext_d + c]); + intermediate_accumulators[p] += mu; + } + let mut evals: Vec<_> = stage_2_traces + .into_iter() + .map(|trace| { + let degree = trace.height(); + let trace_domain = pcs.natural_domain_for_degree(degree); + (trace_domain, flatten_to_base(trace)) + }) + .collect(); + let min_height = 1usize << log_degrees.iter().copied().min().unwrap(); + let mut mask_values = Vec::with_capacity(min_height * mask_cols); + mask_values.extend_from_slice(&mu_base); + if min_height > 1 { + mask_values.extend( + self.config + .sample_zk_base_randomness((min_height - 1) * mask_cols), + ); + } + let mask_mat = RowMajorMatrix::new(mask_values, mask_cols); + let min_domain = pcs.natural_domain_for_degree(min_height); + evals.push((min_domain, mask_mat)); + evals + } else { + stage_2_traces + .into_iter() + .map(|trace| { + let degree = trace.height(); + let trace_domain = pcs.natural_domain_for_degree(degree); + (trace_domain, flatten_to_base(trace)) + }) + .collect() + }; + let (commitment, data) = pcs.commit(evaluations); drop(_g); (commitment, data, intermediate_accumulators) }; @@ -801,6 +885,7 @@ where debug_assert_eq!(intermediate_accumulators.len(), active_indices.len()); debug_assert_eq!(log_degrees.len(), active_indices.len()); let mut quotient_inputs = Vec::with_capacity(active_indices.len()); + let zk_shift = usize::from(is_zk); for (pos, ((&ci, log_degree), next_acc)) in active_indices .iter() .zip(log_degrees.iter()) @@ -808,11 +893,11 @@ where .enumerate() { let circuit = &self.circuits[ci]; - let quotient_degree = circuit.quotient_degree(); + let quotient_degree = circuit.quotient_degree_for(is_zk); let log_quotient_degree = log2_strict_usize(quotient_degree); let trace_domain = pcs.natural_domain_for_degree(1 << log_degree); - let quotient_domain = - trace_domain.create_disjoint_domain(1 << (log_degree + log_quotient_degree)); + let quotient_domain = trace_domain + .create_disjoint_domain(1 << (log_degree + zk_shift + log_quotient_degree)); // The four lookup publics (β, γ, acc, next_acc) as flat base // coordinates, in the layout the synthesized constraints read. let mut lookup_publics: Vec> = Vec::new(); @@ -837,6 +922,12 @@ where stage_1: (&stage_1_trace_data, pos), stage_2: (&stage_2_trace_data, pos), constraint_count: circuit.constraint_count(), + zk_boundary_mask: use_zk_acc_mask.then_some(crate::config::ZkBoundaryMask { + data: &stage_2_trace_data, + matrix_index: num_active, + active_pos: pos, + num_active, + }), }); acc = *next_acc; } @@ -851,12 +942,11 @@ where .into_iter() .map(|input| { let circuit = input.circuit; - let quotient_degree = circuit.quotient_degree(); + let quotient_degree = circuit.quotient_degree_for(is_zk); // compute the quotient values which are elements of the extension field and flatten it to the base field - let quotient_values = self - .config - .accelerated_quotient_values( + let quotient_values = if input.zk_boundary_mask.is_none() { + self.config.accelerated_quotient_values( circuit, &input.lookup_publics, input.trace_domain, @@ -867,39 +957,61 @@ where constraint_challenge, input.constraint_count, ) - .unwrap_or_else(|| { - let preprocessed_trace_on_quotient_domain = - input.preprocessed.map(|(data, idx)| { - pcs.get_evaluations_on_domain(data, idx, input.quotient_domain) - }); - let stage_1_trace_on_quotient_domain = pcs.get_evaluations_on_domain( - input.stage_1.0, - input.stage_1.1, - input.quotient_domain, - ); - let stage_2_trace_on_quotient_domain = pcs.get_evaluations_on_domain( - input.stage_2.0, - input.stage_2.1, - input.quotient_domain, - ); - quotient_values::( - circuit, - &input.lookup_publics, - input.trace_domain, - input.quotient_domain, - &preprocessed_trace_on_quotient_domain, - &stage_1_trace_on_quotient_domain, - &stage_2_trace_on_quotient_domain, - constraint_challenge, - input.constraint_count, + } else { + None + } + .unwrap_or_else(|| { + let preprocessed_trace_on_quotient_domain = + input.preprocessed.map(|(data, idx)| { + pcs.get_evaluations_on_domain(data, idx, input.quotient_domain) + }); + let stage_1_trace_on_quotient_domain = pcs.get_evaluations_on_domain( + input.stage_1.0, + input.stage_1.1, + input.quotient_domain, + ); + let stage_2_trace_on_quotient_domain = pcs.get_evaluations_on_domain( + input.stage_2.0, + input.stage_2.1, + input.quotient_domain, + ); + let mask_evals_owned = input.zk_boundary_mask.map(|mask| { + ( + pcs.get_evaluations_on_domain( + mask.data, + mask.matrix_index, + input.quotient_domain, + ), + mask.active_pos, + mask.num_active, ) }); + let mask_ref = mask_evals_owned + .as_ref() + .map(|(evals, active_pos, n_active)| (evals, *active_pos, *n_active)); + quotient_values::( + circuit, + &input.lookup_publics, + input.trace_domain, + input.quotient_domain, + &preprocessed_trace_on_quotient_domain, + &stage_1_trace_on_quotient_domain, + &stage_2_trace_on_quotient_domain, + mask_ref, + constraint_challenge, + input.constraint_count, + ) + }); let quotient_flat = flatten_to_base::, _>(RowMajorMatrix::new_col(quotient_values)); (input.quotient_domain, quotient_flat, quotient_degree) }) .collect(); - pcs.commit_quotient(quotient_ldes) + if is_zk { + self.config.commit_quotient_zk(quotient_ldes) + } else { + pcs.commit_quotient(quotient_ldes) + } }; challenger.observe_commitment(quotient_commit.clone()); drop(_g); @@ -930,6 +1042,16 @@ where // One wide matrix per circuit holds all its quotient slices. round3_openings.push(vec![zeta]); } + // In multi-circuit `v6-zk`, open the committed accumulator boundary mask + // matrix `U` (matrix `#num_active` in `stage_2_trace`) at `zeta`. + if use_zk_acc_mask { + round2_openings.push(vec![zeta]); + } + // In `v6-zk`, open the `W_R`-column randomizer polynomial `R(X)` + // (matrix `#num_active` in `quotient_chunks`) at `zeta`. + if is_zk { + round3_openings.push(vec![zeta]); + } // The preprocessed commitment is built once over ALL preprocessed // traces at system construction, so its round must carry one entry // per preprocessed matrix regardless of activation. An inactive @@ -1014,6 +1136,7 @@ pub(crate) fn quotient_values( preprocessed_on_quotient_domain: &Option>, stage_1_on_quotient_domain: &EvaluationsOnDomain<'_, SC>, stage_2_on_quotient_domain: &EvaluationsOnDomain<'_, SC>, + mask_on_quotient_domain: Option<(&EvaluationsOnDomain<'_, SC>, usize, usize)>, alpha: SC::Challenge, constraint_count: usize, ) -> Vec @@ -1026,15 +1149,19 @@ where let stage_2_width = circuit.stage_2_width; let preprocessed_width = circuit.preprocessed_width; let mut sels = trace_domain.selectors_on_coset(quotient_domain); - // The logUp wrap constraint consumes the last-row selector ADDITIVELY, - // so its normalization matters — but the selector multiplies Δ, which - // is constant across the domain, so the normalization constant - // 1/(n·g) is absorbed into Δ once per circuit instead of rescaling - // the selector vectors (p3's unnormalized L_last has value n·g at the - // last row; see the selector-normalization pin test). + // The logUp wrap constraint consumes the boundary selector ADDITIVELY, so + // its normalization matters: + // - Non-ZK / 1-circuit ZK: `is_last_row` at `g^{-1}` has value `n·g`, so + // `inj_norm = 1/(n·g)`. + // - Multi-circuit ZK (`mask_on_quotient_domain.is_some()`): `is_first_row` + // at `1` has value `n`, so `inj_norm = 1/n`. let n_val = Val::::from_usize(trace_domain.size()); let g = Val::::two_adic_generator(log2_strict_usize(trace_domain.size())); - let inj_norm = (n_val * g).inverse(); + let inj_norm = if mask_on_quotient_domain.is_some() { + n_val.inverse() + } else { + (n_val * g).inverse() + }; let qdb = log2_strict_usize(quotient_domain.size()) - log2_strict_usize(trace_domain.size()); let next_step = 1 << qdb; @@ -1090,15 +1217,20 @@ where .map(|&c| PackedVal::::from(c)) .collect(); - // Δ/(n·g) per coordinate, broadcast: the logUp boundary injection with - // the last-row selector's normalization constant pre-absorbed. - let delta_scaled: Vec> = (0..ext_d) + // Unmasked constant `delta_scaled` (non-ZK / 1-circuit ZK) or unscaled + // `delta_tilde` (multi-circuit ZK with `U` mask subtracted per pack). + let delta_base: Vec> = (0..ext_d) .map(|k| { - PackedVal::::from( - (lookup_publics[3 * ext_d + k] - lookup_publics[2 * ext_d + k]) * inj_norm, - ) + let diff = lookup_publics[3 * ext_d + k] - lookup_publics[2 * ext_d + k]; + if mask_on_quotient_domain.is_some() { + PackedVal::::from(diff) + } else { + PackedVal::::from(diff * inj_norm) + } }) .collect(); + let inj_norm_packed = PackedVal::::from(inj_norm); + let mask_width = mask_on_quotient_domain.map_or(0, |(_, _, n_active)| (n_active - 1) * ext_d); let ext_params = crate::system::extension_params::(); @@ -1157,6 +1289,8 @@ where main_next: vec![PackedVal::::ZERO; main_next_len], s2_cur: vec![PackedVal::::ZERO; stage_2_width], s2_next: vec![PackedVal::::ZERO; s2_next_len], + mask_cur: vec![PackedVal::::ZERO; mask_width], + delta_eff: vec![PackedVal::::ZERO; if mask_width > 0 { ext_d } else { 0 }], buf: Vec::with_capacity(node_count), accs: vec![PackedVal::::ZERO; accs_len], }, @@ -1170,8 +1304,10 @@ where preprocessed_on_quotient_domain, stage_1_on_quotient_domain, stage_2_on_quotient_domain, + mask_on_quotient_domain, &publics_packed, - &delta_scaled, + &delta_base, + inj_norm_packed, &alpha_table, next_step, i_start, @@ -1200,6 +1336,8 @@ struct QuotientScratch

{ main_next: Vec

, s2_cur: Vec

, s2_next: Vec

, + mask_cur: Vec

, + delta_eff: Vec

, buf: Vec

, accs: Vec

, } @@ -1212,8 +1350,10 @@ fn eval_quotient_pack( preprocessed_on_quotient_domain: &Option>, stage_1_on_quotient_domain: &EvaluationsOnDomain<'_, SC>, stage_2_on_quotient_domain: &EvaluationsOnDomain<'_, SC>, + mask_on_quotient_domain: Option<(&EvaluationsOnDomain<'_, SC>, usize, usize)>, publics_packed: &[PackedVal], - delta_scaled: &[PackedVal], + delta_base: &[PackedVal], + inj_norm_packed: PackedVal, alpha_table: &AlphaTable>, next_step: usize, i_start: usize, @@ -1261,6 +1401,28 @@ fn eval_quotient_pack( &mut scratch.s2_next, ); + let (logup_selector, delta_scaled): (PackedVal, &[PackedVal]) = + if let Some((mask_evals, active_pos, num_active)) = mask_on_quotient_domain { + PackedVal::::fill_packed_row(mask_evals, i_start, &mut scratch.mask_cur); + for (k, (&d_tilde, dst)) in delta_base + .iter() + .zip(scratch.delta_eff.iter_mut()) + .enumerate() + { + let mut val = d_tilde; + if active_pos + 1 < num_active { + val -= scratch.mask_cur[active_pos * ext_degree + k]; + } + if active_pos > 0 { + val += scratch.mask_cur[(active_pos - 1) * ext_degree + k]; + } + *dst = val * inj_norm_packed; + } + (is_first_row, &scratch.delta_eff) + } else { + (is_last_row, delta_base) + }; + let view = VarValues { preprocessed: [&scratch.prep_cur, &scratch.prep_next], main: [&scratch.main_cur, &scratch.main_next], @@ -1285,7 +1447,7 @@ fn eval_quotient_pack( &scratch.s2_next, publics_packed, delta_scaled, - is_last_row, + logup_selector, ext_modulus, ext_degree, circuit.lookup_group_size, @@ -1313,7 +1475,7 @@ fn eval_quotient_pack( &scratch.s2_next, publics_packed, delta_scaled, - is_last_row, + logup_selector, ext_modulus, ext_degree, circuit.lookup_group_size, @@ -1347,7 +1509,7 @@ fn eval_quotient_pack( &scratch.s2_next, publics_packed, delta_scaled, - is_last_row, + logup_selector, ext_modulus, ext_degree, circuit.lookup_group_size, diff --git a/src/system.rs b/src/system.rs index fd1ff32..8fa826c 100644 --- a/src/system.rs +++ b/src/system.rs @@ -129,6 +129,21 @@ impl Circuit { (self.max_constraint_degree().max(2) - 1).next_power_of_two() } + /// Quotient degree multiple for non-ZK (`is_zk == false`) or `v6-zk` + /// (`is_zk == true`). + /// + /// In `v6-zk`, 2× odd-coset witness blinding yields trace polynomials of + /// degree `< 2N` so `deg(Q) <= (2d - 1)N - d + 1 < 2N · q_zk` where + /// `q_zk = max(d, 1).next_power_of_two()` (matching Plonky3's + /// `get_log_num_quotient_chunks(..., is_zk = 1)`). + pub fn quotient_degree_for(&self, is_zk: bool) -> usize { + if is_zk { + self.max_constraint_degree().max(1).next_power_of_two() + } else { + self.quotient_degree() + } + } + /// Returns `true` if any compiled node reads a column from `source` at `offset`. pub fn uses_row(&self, source: Source, offset: RowOffset) -> bool { self.graph.uses_row(source, offset) @@ -199,6 +214,25 @@ impl System { retain_preprocessed: bool, ) -> (Self, ProverKey) { let pcs = config.pcs(); + let is_zk = config.is_zk(); + if is_zk { + assert!( + config.zk_randomizer_width() >= crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH, + "v6-zk requires randomizer width W_R >= {} (got {})", + crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH, + config.zk_randomizer_width() + ); + assert!( + config.log_blowup() >= 1, + "v6-zk requires log_blowup >= 1 (got {})", + config.log_blowup() + ); + } + let min_zk_height = if is_zk { + 1usize << config.min_log_degree() + } else { + 0 + }; let max_quotient_degree = config.max_quotient_degree(); let params = extension_params::(); let d = params.degree; @@ -258,17 +292,26 @@ impl System { }; // The prover obtains trace evaluations on the quotient domain // from the PCS, which can only serve domains up to - // `max_quotient_degree` times the trace domain (the blowup - // factor for FRI). Beyond that, proving would silently produce - // invalid proofs, so reject the circuit upfront. + // `max_quotient_degree` times the committed trace domain (the + // blowup factor for FRI). Beyond that, proving would silently + // produce invalid proofs, so reject the circuit upfront. + let required_quotient_degree = circuit.quotient_degree_for(is_zk); assert!( - circuit.quotient_degree() <= max_quotient_degree, + required_quotient_degree <= max_quotient_degree, "circuit {i}: constraint degree {} needs quotient degree {}, but the PCS only \ supports {}; increase log_blowup or lower the constraint degree", circuit.max_constraint_degree(), - circuit.quotient_degree(), + required_quotient_degree, max_quotient_degree, ); + if is_zk && circuit.preprocessed_height > 0 { + assert!( + circuit.preprocessed_height >= min_zk_height, + "circuit {i}: preprocessed trace height {} is below v6-zk minimum height {}", + circuit.preprocessed_height, + min_zk_height, + ); + } let item = if let Some(preprocessed) = circuit.preprocessed.take() { preprocessed_indices.push(Some(next_preprocessed_index)); @@ -296,7 +339,12 @@ impl System { // Ensure all inputs are drained even if a custom backend stopped early. for _ in prep_iter {} - let vk_digest = compute_vk_digest::, SC::Challenge>(&circuits); + let vk_domain = match config.protocol_version() { + ProtocolVersion::V6Zk => Blake3Domain::ZkVerifyingKey, + ProtocolVersion::V5 | ProtocolVersion::V6 => Blake3Domain::VerifyingKey, + }; + let vk_digest = + compute_vk_digest_with_domain::, SC::Challenge>(&circuits, vk_domain); let system = Self { config, circuits, @@ -307,15 +355,18 @@ impl System { (system, ProverKey { preprocessed_data }) } - /// Binds the system shape (and, under protocol `v6`, the extension - /// degree/modulus and canonical VK / constraint-graph digest) into the - /// Fiat-Shamir transcript. The prover and the verifier must call this - /// identically, before observing any commitment, so that transcripts of - /// systems with different constraint graphs or circuit shapes never + /// Binds the system shape (and, under protocol `v6` / `v6-zk`, the + /// extension degree/modulus and canonical VK / constraint-graph digest) + /// into the Fiat-Shamir transcript. The prover and the verifier must call + /// this identically, before observing any commitment, so that transcripts + /// of systems with different constraint graphs or circuit shapes never /// collide. The protocol parameters are bound separately via the /// challenger seed (see [`ProofConfig::initialise_challenger_for_mode`]). pub fn observe_shape(&self, challenger: &mut SC::Challenger) { - if self.config.protocol_version() == ProtocolVersion::V6 { + if matches!( + self.config.protocol_version(), + ProtocolVersion::V6 | ProtocolVersion::V6Zk + ) { challenger.observe_field(Val::::from_usize( >>::D, )); @@ -352,7 +403,17 @@ impl System { /// `System::new_without_preprocessed` produce identical digests (the /// preprocessed traces themselves are bound via `preprocessed_commit`). pub fn compute_vk_digest>(circuits: &[Circuit]) -> [u8; 32] { - let mut hasher = Blake3Domain::VerifyingKey.hasher(); + compute_vk_digest_with_domain::(circuits, Blake3Domain::VerifyingKey) +} + +/// Computes the canonical verifying-key / constraint-graph digest under the +/// requested BLAKE3 `derive_key` domain (`VerifyingKey` for `v6`, +/// `ZkVerifyingKey` for `v6-zk`). +pub fn compute_vk_digest_with_domain>( + circuits: &[Circuit], + domain: Blake3Domain, +) -> [u8; 32] { + let mut hasher = domain.hasher(); let bincode_cfg = bincode::config::standard() .with_little_endian() .with_fixed_int_encoding(); diff --git a/src/types.rs b/src/types.rs index 5210688..2021d71 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1349,6 +1349,7 @@ impl ProofConfig for GoldilocksBlake3Config { &preprocessed_evals, &stage_1_evals, &stage_2_evals, + None, alpha, input.constraint_count, ); @@ -1384,7 +1385,7 @@ impl ProofConfig for GoldilocksBlake3Config { } fn canonicalize_proof(proof: &mut crate::prover::Proof) { - canonicalize_goldilocks_fri_proof::(proof); + canonicalize_goldilocks_fri_proof::(proof); } #[cfg(feature = "cuda")] @@ -1563,15 +1564,22 @@ fn new_mmcs(cap_height: usize, #[cfg(feature = "cuda")] device_id: i32) -> Mmcs } } -fn canonicalize_goldilocks_fri_proof(proof: &mut crate::prover::Proof) -where +fn canonicalize_goldilocks_fri_proof( + proof: &mut crate::prover::Proof, +) where EF: ExtensionField + crate::traits::ExtensionOf, + InputMmcs: p3_commit::Mmcs, FriMmcs: p3_commit::Mmcs, SC: ProofConfig, SC::Pcs: crate::traits::Pcs< F = Val, Challenge = EF, - Proof = p3_fri::FriProof>>, + Proof = p3_fri::FriProof< + EF, + FriMmcs, + Val, + Vec>, + >, >, { fn canonical_base(value: &mut Val) { @@ -1762,7 +1770,6 @@ where fri_parameters.max_log_arity <= 1, "the CUDA backend currently supports only binary FRI folds" ); - let _ = device_id; } #[cfg(not(feature = "cuda"))] let pcs = { @@ -2204,6 +2211,7 @@ where &preprocessed_evals, &stage_1_evals, &stage_2_evals, + None, alpha, input.constraint_count, ); @@ -2330,7 +2338,887 @@ where } fn canonicalize_proof(proof: &mut crate::prover::Proof) { - canonicalize_goldilocks_fri_proof::>(proof); + canonicalize_goldilocks_fri_proof::>(proof); + } +} + +/// Base hiding MMCS for Protocol `v6-zk` (CPU spillable or CUDA hiding MMCS). +#[cfg(not(feature = "cuda"))] +pub type ZkMmcs = crate::p3_adapter::spill_zk::HidingSpillableMmcs; +#[cfg(feature = "cuda")] +pub type ZkMmcs = crate::cuda::hiding_mmcs::HidingCudaMmcs; + +/// Extension hiding MMCS for Protocol `v6-zk` over any challenge extension `EF`. +pub type V6ZkExtMmcs = ExtensionMmcs; + +/// Inner hiding PCS for Protocol `v6-zk` over any challenge extension `EF` (CPU). +#[cfg(not(feature = "cuda"))] +pub type V6ZkInnerPcs = DomainMappedPcs< + crate::p3_adapter::spill_zk::HidingSpillableTwoAdicFriPcs>, +>; +/// Inner hiding PCS for Protocol `v6-zk` over any challenge extension `EF` (CUDA). +#[cfg(feature = "cuda")] +pub type V6ZkInnerPcs = DomainMappedPcs< + crate::cuda::hiding_pcs::HidingCudaTwoAdicFriPcs>, +>; + +/// Protocol `v6-zk` hiding FRI PCS parameterized over any Goldilocks challenge +/// extension `EF`. +pub type V6ZkPcs = crate::p3_adapter::pcs::FriPcs< + Val, + EF, + DomainChallenger, + Dft, + ZkMmcs, + V6ZkExtMmcs, + V6ZkInnerPcs, +>; + +/// Protocol `v6-zk` zero-knowledge Goldilocks/BLAKE3 configuration over the +/// degree-3 cubic trinomial extension $\mathbb{F}_{p^3} = \mathbb{F}_p[X]/(X^3 - X - 1)$ +/// (128-bit statistical/ROM post-quantum transparent ZK, `W_R = 4` base +/// randomizer columns, 2× odd-coset hiding PCS, zero-storage BLAKE3-CTR leaf +/// salts, multilinear tensor FRI batching). +pub type GoldilocksBlake3V6ZkConfig = GoldilocksV6ZkConfig; + +/// Protocol `v6-zk` zero-knowledge Goldilocks/BLAKE3 configuration over the +/// degree-2 binomial extension $\mathbb{F}_{p^2} = \mathbb{F}_p[X]/(X^2 - 7)$. +pub type GoldilocksBlake3V6ZkFp2Config = GoldilocksV6ZkConfig; + +/// Zero-knowledge Protocol `v6-zk` [`ProofConfig`] parameterized by Goldilocks +/// challenge extension `EF`. +pub struct GoldilocksV6ZkConfig +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + pcs: V6ZkPcs, + challenger_seed: Vec, + min_log_degree: usize, + max_log_degree: usize, + max_quotient_degree: usize, + log_blowup: usize, + cap_height: usize, + randomizer_width: usize, + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, +} + +fn build_v6_zk_challenger_seed>( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, + randomizer_width: usize, + min_log_degree: usize, +) -> Vec { + let modulus = EF::MODULUS; + let modulus_param = match modulus { + ExtensionModulus::Binomial { w } => w.as_canonical_u64(), + ExtensionModulus::Base | ExtensionModulus::CubicTrinomial => 0u64, + }; + let mut seed = b"multi-stark/v6-zk".to_vec(); + let params = [ + u64::try_from(EF::D).expect("extension degree exceeds u64"), + u64::from(modulus.tag()), + modulus_param, + fri_batching.tag(), + u64::try_from(crate::p3_adapter::zk::ZK_LEAF_SALT_BYTES).expect("parameter exceeds u64"), + u64::try_from(randomizer_width).expect("parameter exceeds u64"), + u64::try_from(min_log_degree).expect("parameter exceeds u64"), + u64::try_from(commitment_parameters.log_blowup).expect("parameter exceeds u64"), + u64::try_from(commitment_parameters.cap_height).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.log_final_poly_len).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.max_log_arity).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.num_queries).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.commit_proof_of_work_bits).expect("parameter exceeds u64"), + u64::try_from(fri_parameters.query_proof_of_work_bits).expect("parameter exceeds u64"), + ]; + for p in params { + seed.extend_from_slice(&p.to_le_bytes()); + } + seed +} + +impl GoldilocksV6ZkConfig +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + /// Creates a Protocol `v6-zk` configuration using multilinear tensor FRI + /// batching ([`FriBatching::Tensor`]) and `W_R = 4` base randomizer + /// columns by default. + pub fn new(commitment_parameters: CommitmentParameters, fri_parameters: FriParameters) -> Self { + Self::with_options( + commitment_parameters, + fri_parameters, + FriBatching::Tensor, + crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH, + None, + ) + } + + /// Creates a Protocol `v6-zk` configuration with an explicit [`FriBatching`] + /// strategy (`Tensor` or `Horner`). + pub fn new_with_batching( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, + ) -> Self { + Self::with_options( + commitment_parameters, + fri_parameters, + fri_batching, + crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH, + None, + ) + } + + /// Creates a Protocol `v6-zk` configuration targeting an optional CUDA device. + pub fn with_device( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, + device_id: Option, + ) -> Self { + Self::with_options( + commitment_parameters, + fri_parameters, + fri_batching, + crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH, + device_id, + ) + } + + /// Creates a Protocol `v6-zk` configuration with full explicit parameters, + /// validating all ZK security floors fail-closed. + pub fn with_options( + commitment_parameters: CommitmentParameters, + fri_parameters: FriParameters, + fri_batching: FriBatching, + randomizer_width: usize, + device_id: Option, + ) -> Self { + assert!( + commitment_parameters.log_blowup >= 1, + "v6-zk requires log_blowup >= 1 (got {})", + commitment_parameters.log_blowup + ); + assert!( + fri_parameters.num_queries >= 1, + "v6-zk requires num_queries >= 1" + ); + assert!( + randomizer_width >= crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH, + "v6-zk requires randomizer width W_R >= {} (got {randomizer_width})", + crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH + ); + let min_log_degree = + crate::p3_adapter::zk::min_zk_log_degree(fri_parameters.num_queries, EF::D); + let max_log_degree = Val::TWO_ADICITY + .checked_sub(1 + commitment_parameters.log_blowup) + .expect("log_blowup exceeds field two-adicity"); + assert!( + min_log_degree <= max_log_degree, + "v6-zk min_log_degree ({min_log_degree}) exceeds max_log_degree ({max_log_degree})" + ); + #[cfg(feature = "cuda")] + { + assert_eq!( + commitment_parameters.cap_height, 0, + "the CUDA backend currently supports only cap_height = 0" + ); + assert!( + fri_parameters.max_log_arity <= 1, + "the CUDA backend currently supports only binary FRI folds" + ); + } + #[cfg(not(feature = "cuda"))] + let pcs = { + assert!( + device_id.is_none_or(|device| device == 0), + "no CUDA backend to place a prover on device {device_id:?}" + ); + let val_mmcs = crate::p3_adapter::spill_zk::HidingSpillableMmcs::new_v6_zk( + commitment_parameters.cap_height, + ); + let ext_mmcs = ExtensionMmcs::new(val_mmcs.clone()); + let inner_parameters = InnerFriParameters { + log_blowup: commitment_parameters.log_blowup, + log_final_poly_len: fri_parameters.log_final_poly_len, + max_log_arity: fri_parameters.max_log_arity, + num_queries: fri_parameters.num_queries, + commit_proof_of_work_bits: fri_parameters.commit_proof_of_work_bits, + query_proof_of_work_bits: fri_parameters.query_proof_of_work_bits, + mmcs: ext_mmcs, + }; + let mut inner = crate::p3_adapter::spill_zk::HidingSpillableTwoAdicFriPcs::new( + PcsDft::default(), + val_mmcs, + inner_parameters, + ) + .with_batching(fri_batching); + if let Some(dir) = std::env::var_os("MULTI_STARK_SPILL_DIR") + && !dir.is_empty() + { + inner.set_spill_dir(Some(std::path::PathBuf::from(dir))); + } + DomainMappedPcs::new(inner) + }; + #[cfg(feature = "cuda")] + let pcs = { + let dev = device_id.unwrap_or_else(crate::cuda::configured_device); + let val_mmcs = crate::cuda::hiding_mmcs::HidingCudaMmcs::new_v6_zk( + commitment_parameters.cap_height, + dev, + ); + let ext_mmcs = ExtensionMmcs::new(val_mmcs.clone()); + let inner_parameters = InnerFriParameters { + log_blowup: commitment_parameters.log_blowup, + log_final_poly_len: fri_parameters.log_final_poly_len, + max_log_arity: fri_parameters.max_log_arity, + num_queries: fri_parameters.num_queries, + commit_proof_of_work_bits: fri_parameters.commit_proof_of_work_bits, + query_proof_of_work_bits: fri_parameters.query_proof_of_work_bits, + mmcs: ext_mmcs, + }; + let pcs_dft = CudaDft::new(dev); + DomainMappedPcs::new( + crate::cuda::hiding_pcs::HidingCudaTwoAdicFriPcs::new( + pcs_dft, + val_mmcs, + inner_parameters, + ) + .with_batching(fri_batching), + ) + }; + + let challenger_seed = build_v6_zk_challenger_seed::( + commitment_parameters, + fri_parameters, + fri_batching, + randomizer_width, + min_log_degree, + ); + let max_quotient_degree = 1usize << commitment_parameters.log_blowup; + Self { + pcs: V6ZkPcs::new(pcs, commitment_parameters, fri_parameters), + challenger_seed, + min_log_degree, + max_log_degree, + max_quotient_degree, + log_blowup: commitment_parameters.log_blowup, + cap_height: commitment_parameters.cap_height, + randomizer_width, + commitment_parameters, + fri_parameters, + fri_batching, + } + } + + /// Public protocol-domain seed used by the `v6-zk` challenger. + pub fn challenger_seed(&self) -> &[u8] { + &self.challenger_seed + } + + pub fn cap_height(&self) -> usize { + self.cap_height + } + + pub fn fri_parameters(&self) -> FriParameters { + self.fri_parameters + } + + pub fn fri_batching(&self) -> FriBatching { + self.fri_batching + } + + pub fn randomizer_width(&self) -> usize { + self.randomizer_width + } + + /// Switches the FRI opening batching mode (`Horner` or `Tensor`), updating + /// both the PCS and the protocol challenger seed. + pub fn with_fri_batching(self, fri_batching: FriBatching) -> Self { + let spill = self.spill_dir().map(std::path::Path::to_path_buf); + #[cfg(feature = "cuda")] + let device = Some(self.pcs.inner().dft.device_id()); + #[cfg(not(feature = "cuda"))] + let device = None; + let cfg = Self::with_options( + self.commitment_parameters, + self.fri_parameters, + fri_batching, + self.randomizer_width, + device, + ); + match spill { + Some(dir) => cfg.with_disk_spill(dir), + None => cfg.without_disk_spill(), + } + } + + /// Overrides the randomizer width `W_R` (must be `>= 4`). + pub fn with_randomizer_width(self, randomizer_width: usize) -> Self { + let spill = self.spill_dir().map(std::path::Path::to_path_buf); + #[cfg(feature = "cuda")] + let device = Some(self.pcs.inner().dft.device_id()); + #[cfg(not(feature = "cuda"))] + let device = None; + let cfg = Self::with_options( + self.commitment_parameters, + self.fri_parameters, + self.fri_batching, + randomizer_width, + device, + ); + match spill { + Some(dir) => cfg.with_disk_spill(dir), + None => cfg.without_disk_spill(), + } + } + + /// Enables disk-backed spilling of committed LDE matrices on the CPU prover. + #[cfg_attr(feature = "cuda", allow(unused_mut))] + pub fn with_disk_spill(mut self, dir: impl Into) -> Self { + #[cfg(not(feature = "cuda"))] + self.pcs + .inner_mut() + .inner_mut() + .set_spill_dir(Some(dir.into())); + #[cfg(feature = "cuda")] + let _ = dir.into(); + self + } + + /// Disables disk spilling (forces in-memory LDE storage on CPU). + #[cfg_attr(feature = "cuda", allow(unused_mut))] + pub fn without_disk_spill(mut self) -> Self { + #[cfg(not(feature = "cuda"))] + self.pcs.inner_mut().inner_mut().set_spill_dir(None); + self + } + + /// Returns the configured disk-spill directory, if enabled on the CPU backend. + pub fn spill_dir(&self) -> Option<&std::path::Path> { + #[cfg(not(feature = "cuda"))] + { + self.pcs.spill_dir() + } + #[cfg(feature = "cuda")] + { + None + } + } +} + +impl ProofConfig for GoldilocksV6ZkConfig +where + EF: TwoAdicField + ExtensionField + crate::traits::ExtensionOf, +{ + type Pcs = V6ZkPcs; + type Challenge = EF; + type Challenger = DomainChallenger; + + fn pcs(&self) -> &Self::Pcs { + &self.pcs + } + + fn protocol_version(&self) -> ProtocolVersion { + ProtocolVersion::V6Zk + } + + fn min_log_degree(&self) -> usize { + self.min_log_degree + } + + fn zk_randomizer_width(&self) -> usize { + self.randomizer_width + } + + fn sample_zk_base_randomness(&self, count: usize) -> Vec { + crate::p3_adapter::zk::csprng_field_vec(count) + } + + fn initialise_challenger(&self) -> Self::Challenger { + self.initialise_challenger_for_mode(TranscriptMode::Single) + } + + fn initialise_challenger_for_mode(&self, mode: TranscriptMode) -> Self::Challenger { + let domain = match mode { + TranscriptMode::Single => Blake3Domain::ZkTranscriptSingle, + TranscriptMode::Batch => Blake3Domain::ZkTranscriptBatch, + }; + DomainChallenger::from_domain(self.challenger_seed.clone(), domain) + } + + fn max_log_degree(&self) -> usize { + self.max_log_degree + } + + fn max_log_quotient_domain(&self) -> usize { + Val::TWO_ADICITY + } + + fn max_quotient_degree(&self) -> usize { + self.max_quotient_degree + } + + fn log_blowup(&self) -> usize { + self.log_blowup + } + + fn validate_commitment_cap( + &self, + commit: &crate::config::Com, + max_log_lde_height: usize, + ) -> bool { + crate::p3_adapter::cap::expected_merkle_cap_roots(self.cap_height, max_log_lde_height) + == Some(commit.num_roots()) + } + + #[cfg(not(feature = "cuda"))] + fn commit_preprocessed( + &self, + evaluations: &mut dyn Iterator< + Item = (crate::config::Domain, RowMajorMatrix, bool), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let mut inner_evals = + evaluations.map(|(domain, mat, retain_1x)| (domain.into_inner(), mat, retain_1x)); + self.pcs.commit_preprocessed_streaming(&mut inner_evals) + } + + #[cfg(feature = "cuda")] + fn commit_preprocessed( + &self, + evaluations: &mut dyn Iterator< + Item = (crate::config::Domain, RowMajorMatrix, bool), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let evals: Vec<_> = evaluations + .map(|(domain, mat, _)| (domain.into_inner(), mat)) + .collect(); + if evals.is_empty() { + None + } else { + Some(self.pcs.inner().commit_preprocessed(evals)) + } + } + + #[cfg(not(feature = "cuda"))] + fn commit_main_streaming( + &self, + evaluations: &mut dyn Iterator< + Item = ( + crate::config::Domain, + crate::witness::TraceSource, + bool, + ), + >, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + let mut inner_evals = evaluations.map(|(domain, trace, retain_1x)| { + (domain.into_inner(), trace.materialize(), retain_1x) + }); + self.pcs.commit_streaming_with_originals(&mut inner_evals) + } + + fn commit_quotient_zk( + &self, + quotients: Vec<(crate::config::Domain, RowMajorMatrix, usize)>, + ) -> (crate::config::Com, crate::config::PcsData) { + use crate::p3_adapter::pcs::lde_from_shifted_coefficients; + use crate::p3_adapter::zk::{csprng_field_vec, shifted_quotient_slices_zk}; + use crate::traits::EvaluationDomain; + use p3_matrix::Matrix as _; + + let dft = Dft::default(); + let mut ldes: Vec> = Vec::with_capacity(quotients.len() + 1); + let mut max_ext_height = 0usize; + for (quotient_domain, evaluations, quotient_degree) in quotients { + let sliced = shifted_quotient_slices_zk( + &dft, + evaluations, + EvaluationDomain::first_point("ient_domain), + quotient_degree, + ); + max_ext_height = max_ext_height.max(sliced.height()); + ldes.push(lde_from_shifted_coefficients(&dft, sliced, self.log_blowup)); + } + assert!( + max_ext_height > 0, + "commit_quotient_zk requires at least one quotient matrix" + ); + // Sample `W_R` uniform base-field shifted coefficient polynomials of + // degree `< 2 * N_max_active` and extend in one forward DFT. + let r_shifted = RowMajorMatrix::new( + csprng_field_vec(max_ext_height * self.randomizer_width), + self.randomizer_width, + ); + ldes.push(lde_from_shifted_coefficients( + &dft, + r_shifted, + self.log_blowup, + )); + as PcsTrait>>::commit_ldes(&self.pcs, ldes) + } + + #[cfg(not(feature = "cuda"))] + fn accelerated_lookup_commit( + &self, + inputs: &[crate::config::LookupCommitInput<'_, Self>], + lookup_challenge: EF, + fingerprint_challenge: EF, + mut accumulator: EF, + ) -> Option> { + use crate::lookup::{ + InMemoryChunk, OwnedWindowChunk, TraceRowChunk, apply_first_row_delta_shift, + stage_2_trace_chunked, + }; + use crate::p3_adapter::spill::{SpillPackWriter, SpilledMatrix}; + use crate::p3_adapter::zk::{csprng_field_vec, random_seed}; + use crate::traits::{Pcs as _, flatten_to_base}; + + enum CpuRowChunk<'a> { + InMemory(InMemoryChunk<'a, Val>), + Spilled(OwnedWindowChunk), + } + + impl TraceRowChunk for CpuRowChunk<'_> { + #[inline] + fn row_pair(&self, local_row: usize) -> (&[Val], &[Val]) { + match self { + Self::InMemory(chunk) => chunk.row_pair(local_row), + Self::Spilled(chunk) => chunk.row_pair(local_row), + } + } + } + + enum TraceBacking<'a> { + Borrowed(&'a RowMajorMatrix), + Owned(RowMajorMatrix), + Spilled(SpilledMatrix), + } + + impl TraceBacking<'_> { + fn load_chunk(&self, start: usize, len: usize) -> CpuRowChunk<'_> { + match self { + Self::Borrowed(mat) => CpuRowChunk::InMemory(InMemoryChunk::new(mat, start)), + Self::Owned(mat) => CpuRowChunk::InMemory(InMemoryChunk::new(mat, start)), + Self::Spilled(spilled) => CpuRowChunk::Spilled(OwnedWindowChunk::new( + spilled.read_window_with_wrap(start, len), + )), + } + } + } + + let spill_dir = self.spill_dir(); + let any_unmaterialized = inputs + .iter() + .any(|input| !input.lookup_values.is_materialized()); + if spill_dir.is_none() && !any_unmaterialized { + return None; + } + + let num_active = inputs.len(); + let use_acc_mask = num_active > 1; + let ext_d = EF::D; + let mu_base = if use_acc_mask { + csprng_field_vec((num_active - 1) * ext_d) + } else { + Vec::new() + }; + let min_height = inputs + .iter() + .map(|input| input.lookup_values.height()) + .min() + .unwrap_or(0); + + let salt_seed = random_seed(); + let mut spill_pack = spill_dir.map(SpillPackWriter::create); + let total_mats = num_active + usize::from(use_acc_mask); + let mut spilled_ldes = Vec::with_capacity(if spill_dir.is_some() { total_mats } else { 0 }); + let mut prehashed = Vec::with_capacity(if spill_dir.is_some() { total_mats } else { 0 }); + let height_counts: std::collections::HashMap = if spill_dir.is_some() { + let mut counts = std::collections::HashMap::new(); + for input in inputs { + let lde_height = input.lookup_values.height() << (self.log_blowup + 1); + *counts.entry(lde_height).or_insert(0) += 1; + } + if use_acc_mask { + let mask_lde_height = min_height << (self.log_blowup + 1); + *counts.entry(mask_lde_height).or_insert(0) += 1; + } + counts + } else { + std::collections::HashMap::new() + }; + let mut in_memory_ldes = + Vec::with_capacity(if spill_dir.is_none() { total_mats } else { 0 }); + let mut intermediates = Vec::with_capacity(num_active); + let leaf_domain = self.pcs.leaf_domain(); + + for (pos, input) in inputs.iter().enumerate() { + let circuit = input.circuit; + let height = input.lookup_values.height(); + let (mut stage_2_ext, delta) = if input.lookup_values.is_materialized() { + input.lookup_values.stage_2_trace( + circuit.lookup_group_size, + lookup_challenge, + &fingerprint_challenge, + ) + } else if circuit.graph.lookups.is_empty() { + ( + RowMajorMatrix::new(vec![::ZERO; height], 1), + ::ZERO, + ) + } else { + let (s1_data, s1_idx) = input.stage_1; + let main_backing = if let Some(spilled) = s1_data.spilled_original_trace(s1_idx) { + TraceBacking::Spilled(spilled) + } else if let Some(owned) = s1_data.take_in_memory_original_trace(s1_idx) { + TraceBacking::Owned(owned) + } else { + let trace_domain = self.pcs.natural_domain_for_degree(height); + TraceBacking::Owned( + self.pcs + .get_evaluations_on_domain(s1_data, s1_idx, trace_domain) + .to_row_major_matrix(), + ) + }; + + let prep_backing = if circuit.graph.lookup_prefix_uses_preprocessed() { + if let Some(pp) = circuit.preprocessed.as_ref() { + Some(TraceBacking::Borrowed(pp)) + } else if let Some((prep_data, prep_idx)) = input.preprocessed { + if let Some(spilled) = prep_data.spilled_original_trace(prep_idx) { + Some(TraceBacking::Spilled(spilled)) + } else { + let trace_domain = self.pcs.natural_domain_for_degree(height); + Some(TraceBacking::Owned( + self.pcs + .get_evaluations_on_domain(prep_data, prep_idx, trace_domain) + .to_row_major_matrix(), + )) + } + } else { + panic!( + "circuit lookup expressions read preprocessed columns, but no preprocessed trace is available" + ); + } + } else { + None + }; + + stage_2_trace_chunked( + circuit, + height, + lookup_challenge, + &fingerprint_challenge, + |start, len| main_backing.load_chunk(start, len), + prep_backing + .as_ref() + .map(|prep| move |start, len| prep.load_chunk(start, len)), + ) + }; + + accumulator += delta; + if use_acc_mask { + apply_first_row_delta_shift(&mut stage_2_ext, delta); + if pos + 1 < num_active { + let mu = + EF::from_basis_coefficients_slice(&mu_base[pos * ext_d..(pos + 1) * ext_d]) + .expect("mask basis slice"); + intermediates.push(accumulator + mu); + } else { + intermediates.push(accumulator); + } + } else { + intermediates.push(accumulator); + } + + let stage_2_base = flatten_to_base::(stage_2_ext); + let domain = self.pcs.natural_domain_for_degree(stage_2_base.height()); + let lde = self + .pcs + .compute_blinded_lde(domain.into_inner(), &stage_2_base); + if let Some(pack) = &mut spill_pack { + if height_counts.get(&lde.height()).copied() == Some(1) { + let (spilled, digests) = + pack.append_matrix_and_hash_salted(&lde, leaf_domain, &salt_seed); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } + } else { + in_memory_ldes.push(lde); + } + } + + if use_acc_mask { + let mask_cols = (num_active - 1) * ext_d; + let mut mask_values = Vec::with_capacity(min_height * mask_cols); + mask_values.extend_from_slice(&mu_base); + if min_height > 1 { + mask_values.extend(csprng_field_vec((min_height - 1) * mask_cols)); + } + let mask_mat = RowMajorMatrix::new(mask_values, mask_cols); + let min_domain = self.pcs.natural_domain_for_degree(min_height); + let mask_lde = self + .pcs + .compute_blinded_lde(min_domain.into_inner(), &mask_mat); + if let Some(pack) = &mut spill_pack { + if height_counts.get(&mask_lde.height()).copied() == Some(1) { + let (spilled, digests) = + pack.append_matrix_and_hash_salted(&mask_lde, leaf_domain, &salt_seed); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&mask_lde)); + prehashed.push(None); + } + } else { + in_memory_ldes.push(mask_lde); + } + } + + if let Some(first) = inputs.first() { + first.stage_1.0.release_original_traces(); + } + + let (commitment, data) = if let Some(mut pack) = spill_pack { + pack.flush(); + self.pcs + .commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed, salt_seed) + } else { + self.pcs.commit_in_memory_ldes(in_memory_ldes) + }; + Some((commitment, data, intermediates)) + } + + #[cfg(not(feature = "cuda"))] + fn accelerated_quotient_commit( + &self, + inputs: &[crate::config::QuotientCommitInput<'_, Self>], + alpha: EF, + ) -> Option<(crate::config::Com, crate::config::PcsData)> { + use crate::p3_adapter::pcs::lde_from_shifted_coefficients; + use crate::p3_adapter::spill::SpillPackWriter; + use crate::p3_adapter::zk::{csprng_field_vec, random_seed, shifted_quotient_slices_zk}; + use crate::traits::{EvaluationDomain, Pcs as _, flatten_to_base}; + + let spill_dir = self.spill_dir()?; + let salt_seed = random_seed(); + let mut pack = SpillPackWriter::create(spill_dir); + let mut spilled_ldes = Vec::with_capacity(inputs.len() + 1); + let mut prehashed = Vec::with_capacity(inputs.len() + 1); + let dft = self.pcs.quotient_dft(); + let log_blowup = self.log_blowup; + let leaf_domain = self.pcs.leaf_domain(); + let mut height_counts = std::collections::HashMap::new(); + let mut max_ext_height = 0usize; + for input in inputs { + let q_zk = input.circuit.quotient_degree_for(true); + let ext_height = input.quotient_domain.size() / q_zk; + max_ext_height = max_ext_height.max(ext_height); + let lde_height = ext_height << log_blowup; + *height_counts.entry(lde_height).or_insert(0) += 1; + } + // Account for the randomizer matrix `R(X)` at height `max_ext_height << log_blowup`. + let r_lde_height = max_ext_height << log_blowup; + *height_counts.entry(r_lde_height).or_insert(0) += 1; + + for input in inputs { + let circuit = input.circuit; + let q_zk = circuit.quotient_degree_for(true); + let preprocessed_evals = input.preprocessed.map(|(data, idx)| { + self.pcs + .get_evaluations_on_domain(data, idx, input.quotient_domain) + }); + let stage_1_evals = self.pcs.get_evaluations_on_domain( + input.stage_1.0, + input.stage_1.1, + input.quotient_domain, + ); + let stage_2_evals = self.pcs.get_evaluations_on_domain( + input.stage_2.0, + input.stage_2.1, + input.quotient_domain, + ); + let mask_evals_owned = input.zk_boundary_mask.map(|mask| { + ( + self.pcs.get_evaluations_on_domain( + mask.data, + mask.matrix_index, + input.quotient_domain, + ), + mask.active_pos, + mask.num_active, + ) + }); + let mask_ref = mask_evals_owned + .as_ref() + .map(|(evals, active_pos, num_active)| (evals, *active_pos, *num_active)); + let q_vals = crate::prover::quotient_values::( + circuit, + &input.lookup_publics, + input.trace_domain, + input.quotient_domain, + &preprocessed_evals, + &stage_1_evals, + &stage_2_evals, + mask_ref, + alpha, + input.constraint_count, + ); + drop(mask_evals_owned); + drop(preprocessed_evals); + drop(stage_1_evals); + drop(stage_2_evals); + + let quotient_flat = flatten_to_base::(RowMajorMatrix::new_col(q_vals)); + let sliced = shifted_quotient_slices_zk( + dft, + quotient_flat, + EvaluationDomain::first_point(&input.quotient_domain), + q_zk, + ); + let lde = lde_from_shifted_coefficients(dft, sliced, log_blowup); + if height_counts.get(&lde.height()).copied() == Some(1) { + let (spilled, digests) = + pack.append_matrix_and_hash_salted(&lde, leaf_domain, &salt_seed); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&lde)); + prehashed.push(None); + } + } + + let r_shifted = RowMajorMatrix::new( + csprng_field_vec(max_ext_height * self.randomizer_width), + self.randomizer_width, + ); + let r_lde = lde_from_shifted_coefficients(dft, r_shifted, log_blowup); + if height_counts.get(&r_lde.height()).copied() == Some(1) { + let (spilled, digests) = + pack.append_matrix_and_hash_salted(&r_lde, leaf_domain, &salt_seed); + spilled_ldes.push(spilled); + prehashed.push(Some(digests)); + } else { + spilled_ldes.push(pack.append_matrix(&r_lde)); + prehashed.push(None); + } + + pack.flush(); + Some( + self.pcs + .commit_spilled_ldes_prehashed(spilled_ldes, None, prehashed, salt_seed), + ) + } + + fn canonicalize_proof(proof: &mut crate::prover::Proof) { + canonicalize_goldilocks_fri_proof::>(proof); } } diff --git a/src/verifier.rs b/src/verifier.rs index 4adbc35..0ab1a7b 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -328,6 +328,7 @@ impl System { stage_2_opened_values, } = proof; let pcs = self.config.pcs(); + let is_zk = self.config.is_zk(); // Canonical index of each active circuit; every per-circuit sequence // in the proof is indexed by position in this list. let active_indices: Vec = active @@ -335,6 +336,8 @@ impl System { .enumerate() .filter_map(|(i, &a)| a.then_some(i)) .collect(); + let num_active = active_indices.len(); + let use_zk_acc_mask = is_zk && num_active > 1; // observe stage_2 commitment challenger.observe_commitment(commitments.stage_2_trace.clone()); @@ -396,6 +399,22 @@ impl System { vec![(zeta, quotient_opened_values[pos][0].clone())], )); } + if use_zk_acc_mask { + let min_log_degree = log_degrees.iter().copied().min().expect("num_active > 0"); + let min_domain = pcs.natural_domain_for_degree(1 << min_log_degree); + stage_2_trace_evaluations.push(( + min_domain, + vec![(zeta, stage_2_opened_values[num_active][0].clone())], + )); + } + if is_zk { + let max_log_degree = log_degrees.iter().copied().max().expect("num_active > 0"); + let max_domain = pcs.natural_domain_for_degree(1 << max_log_degree); + quotient_chunks_evaluations.push(( + max_domain, + vec![(zeta, quotient_opened_values[num_active][0].clone())], + )); + } // The preprocessed commitment covers ALL preprocessed matrices, in // canonical slot order. Inactive openings follow the PCS boundary policy. let mut preprocessed_trace_evaluations = vec![]; @@ -485,12 +504,18 @@ impl System { let next_acc = intermediate_accumulators[pos]; let trace_domain = pcs.natural_domain_for_degree(degree); let sels = trace_domain.selectors_at_point(zeta); - // The logUp boundary injection absorbs the last-row selector's - // normalization constant into Δ (mirroring the prover): p3's - // unnormalized L_last has value n·g at the last row. + // The logUp boundary injection absorbs the selector's normalization + // constant into Δ (mirroring the prover): + // - Non-ZK / 1-circuit ZK: `is_last_row` has value `n·g` at `g^{-1}`. + // - Multi-circuit ZK (`use_zk_acc_mask`): `is_first_row` has value + // `n` at `1`, and subtracts `U_p(ζ) - U_{p-1}(ζ)`. let n_val = Val::::from_usize(degree); let g = Val::::two_adic_generator(usize::from(log_degrees[pos])); - let inj_norm = SC::Challenge::from((n_val * g).inverse()); + let inj_norm = if use_zk_acc_mask { + SC::Challenge::from(n_val.inverse()) + } else { + SC::Challenge::from((n_val * g).inverse()) + }; // The four lookup publics (β, γ, acc, next_acc) as base // coordinates embedded into the challenge field. @@ -540,9 +565,31 @@ impl System { let mut buf = Vec::new(); circuit.graph.sweep(&view, &mut buf); let mut constraint_values = circuit.graph.constraint_values(&buf); - let delta_scaled: Vec = (0..extension_d) - .map(|k| (publics[3 * extension_d + k] - publics[2 * extension_d + k]) * inj_norm) - .collect(); + let (logup_selector, delta_scaled): (SC::Challenge, Vec) = + if use_zk_acc_mask { + let mask_row = &stage_2_opened_values[num_active][0]; + let scaled = (0..extension_d) + .map(|k| { + let mut val = + publics[3 * extension_d + k] - publics[2 * extension_d + k]; + if pos + 1 < num_active { + val -= mask_row[pos * extension_d + k]; + } + if pos > 0 { + val += mask_row[(pos - 1) * extension_d + k]; + } + val * inj_norm + }) + .collect(); + (view.is_first_row, scaled) + } else { + let scaled = (0..extension_d) + .map(|k| { + (publics[3 * extension_d + k] - publics[2 * extension_d + k]) * inj_norm + }) + .collect(); + (view.is_last_row, scaled) + }; crate::lookup::logup_constraint_values( &circuit.graph.lookups, &buf, @@ -550,9 +597,7 @@ impl System { view.stage2[1], &publics, &delta_scaled, - // p3's (unnormalized) last-row selector; the normalization - // constant is pre-absorbed into `delta_scaled`. - view.is_last_row, + logup_selector, crate::system::extension_params::().modulus, extension_d, circuit.lookup_group_size, @@ -570,7 +615,12 @@ impl System { // `Q(ζ) = Σᵢ ζ^{i·n}·cᵢ(ζ)`, with each slice's value read from // the wide quotient matrix opened at ζ. let quotient_row = "ient_opened_values[pos][0]; - debug_assert_eq!(quotient_row.len(), quotient_degree * extension_d); + let expected_slices = if is_zk { + 2 * quotient_degree + } else { + quotient_degree + }; + debug_assert_eq!(quotient_row.len(), expected_slices * extension_d); let zeta_pow_n = zeta.exp_power_of_2(log2_strict_usize(degree)); let quotient = quotient_row .chunks_exact(extension_d) @@ -619,6 +669,9 @@ impl System { stage_2_opened_values, .. } = proof; + let is_zk = self.config.is_zk(); + let zk_shift = usize::from(is_zk); + let extension_d = >>::D; let num_circuits = self.circuits.len(); crate::ensure!( num_circuits > 0, @@ -626,6 +679,16 @@ impl System { num_circuits, "system has no circuits" ); + if is_zk { + crate::ensure!( + self.config.zk_randomizer_width() >= crate::p3_adapter::zk::ZK_RANDOMIZER_WIDTH + && self.config.log_blowup() >= 1, + VerificationError::InvalidSystem; + randomizer_width = self.config.zk_randomizer_width(), + log_blowup = self.config.log_blowup(), + "invalid v6-zk randomizer width or log_blowup" + ); + } ensure_eq!( active.len(), num_circuits, @@ -681,7 +744,7 @@ impl System { && max_prep_height.is_power_of_two() && self.config.validate_commitment_cap( commit, - log2_strict_usize(max_prep_height) + self.config.log_blowup(), + log2_strict_usize(max_prep_height) + zk_shift + self.config.log_blowup(), ), VerificationError::InvalidSystem; max_prep_height, @@ -738,6 +801,8 @@ impl System { } } } + let use_zk_acc_mask = is_zk && num_active > 1; + let expected_stage_2_mats = num_active + usize::from(use_zk_acc_mask); ensure_eq!( stage_1_opened_values.len(), num_active, @@ -748,12 +813,30 @@ impl System { ); ensure_eq!( stage_2_opened_values.len(), - num_active, + expected_stage_2_mats, VerificationError::InvalidProofShape; actual = stage_2_opened_values.len(), - expected = num_active, + expected = expected_stage_2_mats, "unexpected number of stage-2 matrices" ); + if use_zk_acc_mask { + ensure_eq!( + stage_2_opened_values[num_active].len(), + 1, + VerificationError::InvalidProofShape; + actual = stage_2_opened_values[num_active].len(), + expected = 1, + "unexpected number of ZK boundary mask openings" + ); + ensure_eq!( + stage_2_opened_values[num_active][0].len(), + (num_active - 1) * extension_d, + VerificationError::InvalidProofShape; + actual = stage_2_opened_values[num_active][0].len(), + expected = (num_active - 1) * extension_d, + "unexpected ZK boundary mask opening width" + ); + } for (pos, &ci) in active_indices.iter().enumerate() { let circuit = &self.circuits[ci]; let preprocessed_i = self.preprocessed_indices[ci]; @@ -859,7 +942,26 @@ impl System { "trace height does not match preprocessed height" ); } - let quotient_degree = circuit.quotient_degree(); + let quotient_degree = circuit.quotient_degree_for(is_zk); + crate::ensure!( + quotient_degree <= self.config.max_quotient_degree(), + VerificationError::InvalidSystem; + circuit = ci, + quotient_degree, + max_quotient_degree = self.config.max_quotient_degree(), + "circuit quotient degree exceeds PCS blowup budget" + ); + if is_zk { + crate::ensure!( + usize::from(*log_degree) >= self.config.min_log_degree(), + VerificationError::InvalidProofShape; + circuit = ci, + active_position = pos, + log_degree = *log_degree, + min_log_degree = self.config.min_log_degree(), + "trace height is below v6-zk minimum height floor" + ); + } // The claimed log degree must be small enough that the quotient // domain can still be committed and opened by the PCS. This also // guards the `1 << log_degree` shifts used during verification @@ -867,7 +969,7 @@ impl System { crate::ensure!( usize::from(*log_degree) <= self.config.max_log_degree() && usize::from(*log_degree) < usize::BITS as usize - && usize::from(*log_degree) + log2_strict_usize(quotient_degree) + && usize::from(*log_degree) + zk_shift + log2_strict_usize(quotient_degree) <= self.config.max_log_quotient_domain(), VerificationError::InvalidProofShape; circuit = ci, @@ -888,6 +990,7 @@ impl System { .map(usize::from) .max() .expect("num_active > 0") + + zk_shift + self.config.log_blowup(); crate::ensure!( self.config @@ -910,18 +1013,24 @@ impl System { max_log_lde_height, "quotient commitment cap root count mismatch" ); - // One wide quotient matrix per active circuit, holding all its - // coefficient slices, opened at the single point ζ. + // One wide quotient matrix per active circuit (holding `q` slices in + // non-ZK or `2 * q_zk` blinded slices in `v6-zk`), plus one `W_R`-column + // randomizer polynomial `R(X)` in `v6-zk`, all opened at ζ. + let expected_quotient_mats = num_active + usize::from(is_zk); ensure_eq!( quotient_opened_values.len(), - num_active, + expected_quotient_mats, VerificationError::InvalidProofShape; actual = quotient_opened_values.len(), - expected = num_active, + expected = expected_quotient_mats, "unexpected number of quotient matrices" ); - let extension_d = >>::D; for (pos, quotient_degree) in quotient_degrees.iter().enumerate() { + let expected_slices = if is_zk { + 2 * quotient_degree + } else { + *quotient_degree + }; ensure_eq!( quotient_opened_values[pos].len(), 1, @@ -936,17 +1045,35 @@ impl System { ); ensure_eq!( quotient_opened_values[pos][0].len(), - quotient_degree * extension_d, + expected_slices * extension_d, VerificationError::InvalidProofShape; circuit = active_indices[pos], active_position = pos, actual = quotient_opened_values[pos][0].len(), - expected = quotient_degree * extension_d, + expected = expected_slices * extension_d, quotient_degree = *quotient_degree, extension_degree = extension_d, "unexpected quotient opening width" ); } + if is_zk { + ensure_eq!( + quotient_opened_values[num_active].len(), + 1, + VerificationError::InvalidProofShape; + actual = quotient_opened_values[num_active].len(), + expected = 1, + "unexpected number of ZK randomizer openings" + ); + ensure_eq!( + quotient_opened_values[num_active][0].len(), + self.config.zk_randomizer_width(), + VerificationError::InvalidProofShape; + actual = quotient_opened_values[num_active][0].len(), + expected = self.config.zk_randomizer_width(), + "unexpected ZK randomizer opening width" + ); + } ensure_eq!( intermediate_accumulators.len(), num_active, diff --git a/tests/fp3_v6_zk.rs b/tests/fp3_v6_zk.rs new file mode 100644 index 0000000..0bcfedc --- /dev/null +++ b/tests/fp3_v6_zk.rs @@ -0,0 +1,1182 @@ +//! End-to-end integration, zero-knowledge randomization, fail-closed security, +//! and proof-size tests for Protocol `v6-zk` over Goldilocks +//! $\mathbb{F}_{p^3} = \mathbb{F}_p[X]/(X^3 - X - 1)$. + +#[cfg(not(feature = "cuda"))] +use std::fs; +#[cfg(not(feature = "cuda"))] +use std::path::PathBuf; +#[cfg(not(feature = "cuda"))] +use std::sync::atomic::{AtomicU64, Ordering}; + +use multi_stark::batch::{BatchMessage, BatchProof, Retention, ShardInput}; +use multi_stark::config::ProofConfig; +use multi_stark::expr::{Expr, ExtExpr, RowOffset}; +use multi_stark::lookup::Lookup; +use multi_stark::p3_adapter::fri_batching::FriBatching; +use multi_stark::p3_adapter::zk::{ZK_LEAF_SALT_BYTES, ZK_RANDOMIZER_WIDTH, min_zk_log_degree}; +use multi_stark::prover::Proof; +use multi_stark::system::{CircuitInputs, System, SystemWitness}; +use multi_stark::types::{ + CommitmentParameters, ExtVal3, FriParameters, GoldilocksBlake3V6Config, + GoldilocksBlake3V6ZkConfig, GoldilocksBlake3V6ZkFp2Config, Val, +}; +use multi_stark::verifier::VerificationError; +use p3_field::PrimeCharacteristicRing; +use p3_matrix::dense::RowMajorMatrix; +use p3_symmetric::MerkleCap; + +#[cfg(not(feature = "cuda"))] +static DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +#[cfg(not(feature = "cuda"))] +fn fresh_spill_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let seq = DIR_SEQ.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!( + "multi-stark-fp3-v6-zk-{tag}-{}-{nanos}-{seq}", + std::process::id() + )) +} + +fn f(v: u32) -> Val { + Val::from_u32(v) +} + +fn zk_fri_params(num_queries: usize, pow_bits: usize) -> FriParameters { + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries, + commit_proof_of_work_bits: pow_bits, + query_proof_of_work_bits: pow_bits, + } +} + +/// Single-circuit shrinker-style AIR with a private witness `(a, b)` proving +/// `a + b == target` and `a^3 == a3` (degree-3 constraint + transition + claim +/// lookup on `target`, so `a, b` remain completely private to the witness). +fn single_circuit_private_sum_inputs(rows: usize) -> Vec> { + assert!(rows.is_power_of_two() && rows >= 8); + let a = Expr::main(0); + let b = Expr::main(1); + let target = Expr::main(2); + let a3 = Expr::main(3); + let mult = Expr::main(4); + let target_next = Expr::main_next(2); + + let constraints = vec![ + a.clone() + b - target.clone(), + a.clone() * a.clone() * a - a3, + // Keep `target` constant across all rows via transition constraint. + Expr::IsTransition * (target_next - target.clone()), + ]; + let lookups = vec![Lookup::pull(mult, vec![Expr::constant(f(77)), target])]; + + vec![CircuitInputs { + main_width: 5, + preprocessed: None, + constraints, + ext_constraints: vec![], + lookups, + lookup_group_size: 1, + }] +} + +fn build_single_circuit_witness( + rows: usize, + target: u32, + witness_seed: u32, +) -> (Vec>, Vec>) { + let mut values = Vec::with_capacity(rows * 5); + for r in 0..rows { + let a_u = (witness_seed.wrapping_add(u32::try_from(r).unwrap().wrapping_mul(17))) % target; + let b_u = target - a_u; + let a = f(a_u); + let b = f(b_u); + let t = f(target); + let a3 = a * a * a; + let mult = if r == 0 { Val::ONE } else { Val::ZERO }; + values.extend([a, b, t, a3, mult]); + } + let trace = RowMajorMatrix::new(values, 5); + let claims = vec![vec![f(77), f(target)]]; + (vec![trace], claims) +} + +/// Multi-circuit system (`C = 4`, mixed heights, preprocessed ROM, grouped +/// lookups, degree-3 `ExtExpr`, and sparse activation) sized to satisfy the +/// `v6-zk` minimum height floor (`>= 256` rows). +fn multi_circuit_zk_inputs( + lookup_group_size: usize, + work_rows: usize, + aux_rows: usize, + with_ext_constraint: bool, +) -> Vec> { + assert!(work_rows.is_power_of_two() && work_rows >= 64); + assert!(aux_rows.is_power_of_two() && aux_rows >= 64); + + // Circuit 0: 256-row preprocessed byte ROM (`prep[0] = 0..255`). + let byte_prep = RowMajorMatrix::new((0..256u32).map(f).collect(), 1); + let byte_table = CircuitInputs { + main_width: 1, + preprocessed: Some(byte_prep), + constraints: vec![], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(10)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + // Circuit 1: `aux_rows`-row preprocessed aux ROM (can be deactivated). + let aux_prep = RowMajorMatrix::new( + (0..u32::try_from(aux_rows).unwrap()) + .map(|r| f(1000 + r)) + .collect(), + 1, + ); + let aux_table = CircuitInputs { + main_width: 1, + preprocessed: Some(aux_prep), + constraints: vec![Expr::main(0) * (Expr::preprocessed(0) - Expr::preprocessed(0))], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(f(20)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + // Circuit 2: `work_rows`-row arithmetic + lookup + transition + optional cubic ExtExpr. + let work_prep = RowMajorMatrix::new( + (0..u32::try_from(work_rows).unwrap()) + .map(|r| f(r + 1)) + .collect(), + 1, + ); + let a = Expr::main(0); + let b = Expr::main(1); + let c = Expr::main(2); + let d = Expr::main(3); + let sum = Expr::main(4); + let mult = Expr::main(5); + let tag = Expr::preprocessed(0); + let tag_next = Expr::preprocessed_next(0); + let a_next = Expr::main_next(0); + + let ext_constraints = if with_ext_constraint { + let lhs = ExtExpr::from(a.clone()) * ExtExpr::Coords(vec![b.clone(), c.clone(), d.clone()]); + let rhs = ExtExpr::Coords(vec![ + a.clone() * b.clone(), + a.clone() * c.clone(), + a.clone() * d.clone(), + ]); + let s2 = ExtExpr::stage2(0, 3, RowOffset::Current); + let s2_id = s2.clone() * ExtExpr::from(a.clone()) - ExtExpr::from(a.clone()) * s2; + vec![lhs - rhs, s2_id] + } else { + vec![] + }; + + let work_constraints = vec![ + sum.clone() - (a.clone() + b.clone() + c.clone() + d.clone() + tag.clone()), + Expr::IsTransition * (a_next.clone() - (a.clone() + Expr::constant(Val::ONE))), + ]; + let work_lookups = vec![ + Lookup::pull( + mult, + vec![Expr::constant(f(30)), tag, tag_next, sum, a_next], + ), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), a]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), b]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), c]), + Lookup::push(Expr::constant(Val::ONE), vec![Expr::constant(f(10)), d]), + ]; + let work_circuit = CircuitInputs { + main_width: 6, + preprocessed: Some(work_prep), + constraints: work_constraints, + ext_constraints, + lookups: work_lookups, + lookup_group_size, + }; + + // Circuit 3: zero-lookup quadratic circuit (`main[0]^2 == main[1]`). + let sq = CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![Expr::main(0) * Expr::main(0) - Expr::main(1)], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + + vec![byte_table, aux_table, work_circuit, sq] +} + +fn build_multi_circuit_zk_witness( + work_rows: usize, + aux_rows: usize, + sq_rows: usize, + aux_active: bool, + seed: u32, +) -> (Vec>, Vec>) { + let mut byte_mults = vec![0u32; 256]; + let mut work_values = Vec::with_capacity(work_rows * 6); + let mut claims = Vec::new(); + let max_base = 256usize.saturating_sub(work_rows); + let base_a = if max_base == 0 { + 0 + } else { + seed % u32::try_from(max_base).unwrap() + }; + + for r in 0..work_rows { + let r32 = u32::try_from(r).unwrap(); + let a = (base_a + r32) & 0xFF; + let b = (r32 * 7 + seed * 3 + 5) & 0xFF; + let c = (r32 * 13 + seed * 11 + 17) & 0xFF; + let d = (r32 * 29 + seed * 19 + 41) & 0xFF; + let tag = r32 + 1; + let tag_next = u32::try_from((r + 1) % work_rows).unwrap() + 1; + let a_next = if r + 1 < work_rows { + (base_a + r32 + 1) & 0xFF + } else { + base_a & 0xFF + }; + let sum = a + b + c + d + tag; + let mult = u32::from(r % 16 == 0); + if mult == 1 { + claims.push(vec![f(30), f(tag), f(tag_next), f(sum), f(a_next)]); + } + byte_mults[usize::try_from(a).unwrap()] += 1; + byte_mults[usize::try_from(b).unwrap()] += 1; + byte_mults[usize::try_from(c).unwrap()] += 1; + byte_mults[usize::try_from(d).unwrap()] += 1; + work_values.extend([f(a), f(b), f(c), f(d), f(sum), f(mult)]); + } + + let byte_trace = RowMajorMatrix::new(byte_mults.into_iter().map(f).collect(), 1); + let aux_trace = if aux_active { + let mut aux_mults = vec![Val::ZERO; aux_rows]; + aux_mults[3] = Val::ONE; + claims.push(vec![f(20), f(1003)]); + RowMajorMatrix::new(aux_mults, 1) + } else { + RowMajorMatrix::new(Vec::new(), 1) + }; + let work_trace = RowMajorMatrix::new(work_values, 6); + let sq_trace = RowMajorMatrix::new( + (0..u32::try_from(sq_rows).unwrap()) + .flat_map(|i| [f(i + 2 + seed), f((i + 2 + seed) * (i + 2 + seed))]) + .collect(), + 2, + ); + + (vec![byte_trace, aux_trace, work_trace, sq_trace], claims) +} + +/// 1-circuit shrinker-style `v6-zk` roundtrips across `log_blowup = 2, 3, 4`, +/// `Tensor` & `Horner` batching, `cap_height = 0, 1`, PoW, serialization, and +/// both `ExtVal3` and `ExtVal2`. +#[test] +fn v6_zk_single_circuit_roundtrip_matrix() { + let rows = 128usize; // >= next_pow2(2*24 + 6) = 64 + let fri = zk_fri_params(24, 0); + + for log_blowup in [2usize, 3, 4] { + for batching in [FriBatching::Tensor, FriBatching::Horner] { + for cap_height in [0usize, 1] { + #[cfg(feature = "cuda")] + if cap_height != 0 { + continue; + } + let config = GoldilocksBlake3V6ZkConfig::new_with_batching( + CommitmentParameters { + log_blowup, + cap_height, + }, + fri, + batching, + ); + let (system, key) = System::new(config, single_circuit_private_sum_inputs(rows)); + let (traces, claims) = build_single_circuit_witness(rows, 500, 11); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let witness = SystemWitness::from_stage_1(traces, &system); + let proof = system.prove_multiple_claims(&key, &claim_refs, witness); + + // 1-circuit ZK has no boundary mask matrix `U` in stage_2, + // and exactly 1 randomizer matrix `R` of width `W_R = 4` in quotient. + assert_eq!(proof.stage_2_opened_values.len(), 1); + assert_eq!(proof.quotient_opened_values.len(), 2); + assert_eq!( + proof.quotient_opened_values[1][0].len(), + ZK_RANDOMIZER_WIDTH + ); + assert_eq!(proof.intermediate_accumulators, vec![ExtVal3::ZERO]); + + system + .verify_multiple_claims(&claim_refs, &proof) + .unwrap_or_else(|e| { + panic!("1-circuit ZK verify failed (lb={log_blowup}, {batching:?}, cap={cap_height}): {e:?}") + }); + + let bytes = proof.to_bytes().expect("serialize ZK proof"); + let decoded = Proof::::from_bytes(&bytes) + .expect("deserialize ZK proof"); + system + .verify_multiple_claims(&claim_refs, &decoded) + .expect("deserialized 1-circuit ZK proof must verify"); + } + } + } + + // Also test positive PoW bits + quadratic `ExtVal2` config. + let fp2_cfg = GoldilocksBlake3V6ZkFp2Config::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + zk_fri_params(20, 4), + ); + let (sys_fp2, key_fp2) = System::new(fp2_cfg, single_circuit_private_sum_inputs(64)); + let (traces, claims) = build_single_circuit_witness(64, 300, 5); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let witness = SystemWitness::from_stage_1(traces, &sys_fp2); + let proof = sys_fp2.prove_multiple_claims(&key_fp2, &claim_refs, witness); + sys_fp2 + .verify_multiple_claims(&claim_refs, &proof) + .expect("Fp2 v6-zk proof with PoW must verify"); +} + +/// Multi-circuit (`C_active > 1`) `v6-zk` roundtrips with preprocessed traces, +/// mixed heights (`N_min < N_max`), grouped lookups, sparse activation, +/// `intermediate_accumulators` blinding, streaming prover, disk spill, and +/// multi-shard batch proofs across `log_blowup = 2, 3, 4`. +#[test] +fn v6_zk_multi_circuit_roundtrip_and_batch_and_spill() { + let fri = zk_fri_params(20, 0); // min height = next_pow2(46) = 64 + + for log_blowup in [2usize, 3, 4] { + for (group_size, aux_active) in [(1usize, true), (2usize, false)] { + let work_rows = 128usize; + let aux_rows = 64usize; + let sq_rows = 64usize; + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup, + cap_height: 0, + }, + fri, + ); + let inputs = multi_circuit_zk_inputs(group_size, work_rows, aux_rows, true); + let (system, key) = System::new(config, inputs); + let (traces, claims) = + build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, aux_active, 7); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let witness = SystemWitness::from_stage_1(traces.clone(), &system); + let proof = system.prove_multiple_claims(&key, &claim_refs, witness); + + let num_active = if aux_active { 4 } else { 3 }; + // Multi-circuit ZK commits boundary mask `U` as matrix `#num_active` + // in `stage_2_trace` and randomizer `R` as matrix `#num_active` in `quotient`. + assert_eq!(proof.stage_2_opened_values.len(), num_active + 1); + assert_eq!( + proof.stage_2_opened_values[num_active][0].len(), + (num_active - 1) * 3 + ); + assert_eq!(proof.quotient_opened_values.len(), num_active + 1); + assert_eq!( + proof.quotient_opened_values[num_active][0].len(), + ZK_RANDOMIZER_WIDTH + ); + assert_eq!(proof.intermediate_accumulators.len(), num_active); + assert_eq!(proof.intermediate_accumulators.last(), Some(&ExtVal3::ZERO)); + + system + .verify_multiple_claims(&claim_refs, &proof) + .unwrap_or_else(|e| { + panic!( + "multi-circuit ZK failed (lb={log_blowup}, gs={group_size}, aux={aux_active}): {e:?}" + ) + }); + } + } + + // Verify streaming + disk spill + `new_without_preprocessed` on CPU. + #[cfg(not(feature = "cuda"))] + { + let dir = fresh_spill_dir("multi-circuit"); + let work_rows = 128usize; + let aux_rows = 64usize; + let sq_rows = 64usize; + let inputs = multi_circuit_zk_inputs(2, work_rows, aux_rows, true); + + let cfg_mem = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 1, + }, + fri, + ) + .without_disk_spill(); + let cfg_spill = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 1, + }, + fri, + ) + .with_disk_spill(&dir); + + let (sys_mem, _) = System::new(cfg_mem, inputs.clone()); + let (sys_spill, key_spill) = System::new_without_preprocessed(cfg_spill, inputs); + + // Deterministic public preprocessed salt guarantees identical setup commitments! + assert_eq!( + sys_mem.preprocessed_commit.as_ref().unwrap().roots(), + sys_spill.preprocessed_commit.as_ref().unwrap().roots(), + "independent v6-zk setups must produce identical preprocessed_commit" + ); + assert_eq!(sys_mem.vk_digest, sys_spill.vk_digest); + + let (traces, claims) = + build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, true, 13); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let streaming_proof = + sys_spill.prove_multiple_claims_streaming(&key_spill, &claim_refs, traces); + // Cross-verify spilled streaming proof against independent in-memory verifier! + sys_mem + .verify_multiple_claims(&claim_refs, &streaming_proof) + .expect("in-memory verifier must accept disk-spilled streaming v6-zk proof"); + let _ = fs::remove_dir_all(&dir); + } + + // Multi-shard batch proof in `v6-zk` (`Retention::Retain`). + { + let work_rows = 64usize; + let aux_rows = 64usize; + let sq_rows = 64usize; + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + fri, + ); + let inputs = multi_circuit_zk_inputs(1, work_rows, aux_rows, false); + let (system, key) = System::new(config, inputs); + let (t0, mut c0) = build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, false, 3); + let (t1, c1) = build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, true, 9); + // Move one claim from shard 0 to a batch-level message so shards have non-zero residuals. + let moved = c0.pop().unwrap(); + let messages = vec![BatchMessage::push(moved)]; + let shards = vec![ + ShardInput { + claims: c0, + witness: SystemWitness::from_stage_1(t0, &system), + }, + ShardInput { + claims: c1, + witness: SystemWitness::from_stage_1(t1, &system), + }, + ]; + let batch_proof = system.prove_batch(&key, shards, messages); + assert_ne!( + batch_proof.proofs[0].intermediate_accumulators.last(), + Some(&ExtVal3::ZERO), + "shard 0 should have a non-zero residual before batch balancing" + ); + system + .verify_batch(&batch_proof) + .expect("multi-shard v6-zk batch proof must verify"); + let bytes = batch_proof.to_bytes().expect("serialize batch proof"); + let decoded = BatchProof::::from_bytes(&bytes) + .expect("deserialize batch proof"); + system + .verify_batch(&decoded) + .expect("deserialized v6-zk batch proof must verify"); + // Ensure `Retention::Retain` path works via `prove_batch_with` too. + let (t_a, c_a) = build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, false, 1); + let batch2 = system.prove_batch_with(&key, &[c_a], vec![], Retention::Retain, |_| { + SystemWitness::from_stage_1(t_a.clone(), &system) + }); + system.verify_batch(&batch2).unwrap(); + } +} + +/// ZK randomization & indistinguishability tests: +/// 1. Same statement + same witness proved twice -> distinct Merkle roots, +/// distinct opened trace values, distinct leaf salts, distinct blinded +/// `intermediate_accumulators[0..C-1]`, BOTH verify. +/// 2. Same public statement + two DIFFERENT private witnesses -> identically +/// structured transcripts, BOTH verify. +#[test] +fn v6_zk_randomization_and_witness_indistinguishability() { + let fri = zk_fri_params(24, 0); + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + fri, + ); + + // Part A: Multi-circuit same statement + same witness proved twice. + { + let work_rows = 128usize; + let aux_rows = 64usize; + let sq_rows = 64usize; + let inputs = multi_circuit_zk_inputs(1, work_rows, aux_rows, true); + let (system, key) = System::new(config, inputs); + let (traces, claims) = + build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, true, 19); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let p1 = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &system), + ); + let p2 = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces, &system), + ); + + system.verify_multiple_claims(&claim_refs, &p1).unwrap(); + system.verify_multiple_claims(&claim_refs, &p2).unwrap(); + + // Distinct commitments for every prover round. + assert_ne!( + p1.commitments.stage_1_trace.roots(), + p2.commitments.stage_1_trace.roots(), + "stage_1 Merkle root must be freshly randomized" + ); + assert_ne!( + p1.commitments.stage_2_trace.roots(), + p2.commitments.stage_2_trace.roots(), + "stage_2 Merkle root must be freshly randomized" + ); + assert_ne!( + p1.commitments.quotient_chunks.roots(), + p2.commitments.quotient_chunks.roots(), + "quotient Merkle root must be freshly randomized" + ); + + // Distinct OOD openings (witness, stage_2, boundary mask U, quotient, randomizer R). + assert_ne!(p1.stage_1_opened_values, p2.stage_1_opened_values); + assert_ne!(p1.stage_2_opened_values, p2.stage_2_opened_values); + assert_ne!(p1.quotient_opened_values, p2.quotient_opened_values); + + // Distinct leaf salts and opened leaf rows across all prover rounds. + for round in 0..3 { + assert_ne!( + p1.opening_proof.input_openings[round].opening_proof.salts, + p2.opening_proof.input_openings[round].opening_proof.salts, + "leaf salts in round {round} must differ across proofs" + ); + assert_ne!( + p1.opening_proof.input_openings[round].opened_values, + p2.opening_proof.input_openings[round].opened_values, + "opened blinded leaves in round {round} must differ across proofs" + ); + // Every leaf salt is exactly 16 bytes (128 bits). + for group_salts in &p1.opening_proof.input_openings[round].opening_proof.salts { + assert!(!group_salts.is_empty()); + for salt in group_salts { + assert_eq!(salt.len(), ZK_LEAF_SALT_BYTES); + } + } + } + + // Distinct blinded interior `intermediate_accumulators[0..C-1]`, while final == 0. + let num_active = p1.intermediate_accumulators.len(); + assert_eq!(num_active, 4); + for i in 0..(num_active - 1) { + assert_ne!( + p1.intermediate_accumulators[i], p2.intermediate_accumulators[i], + "blinded intermediate_accumulator[{i}] must be freshly masked" + ); + } + assert_eq!(p1.intermediate_accumulators[num_active - 1], ExtVal3::ZERO); + assert_eq!(p2.intermediate_accumulators[num_active - 1], ExtVal3::ZERO); + } + + // Part B: Same public statement + TWO DIFFERENT witnesses -> identically + // structured transcripts, both verify. + { + let rows = 128usize; + let cfg = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + fri, + ); + let (system, key) = System::new(cfg, single_circuit_private_sum_inputs(rows)); + + let (t1, claims1) = build_single_circuit_witness(rows, 10_000, 1); + let (t2, claims2) = build_single_circuit_witness(rows, 10_000, 4_321); + assert_eq!( + claims1, claims2, + "both witnesses satisfy the SAME public statement" + ); + assert_ne!( + t1[0].values, t2[0].values, + "the two private witnesses must differ" + ); + + let claim_refs: Vec<&[Val]> = claims1.iter().map(Vec::as_slice).collect(); + let p1 = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(t1, &system), + ); + let p2 = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(t2, &system), + ); + + system.verify_multiple_claims(&claim_refs, &p1).unwrap(); + system.verify_multiple_claims(&claim_refs, &p2).unwrap(); + + // Identical structural shapes. + assert_eq!(p1.active, p2.active); + assert_eq!(p1.log_degrees, p2.log_degrees); + assert_eq!(p1.intermediate_accumulators, p2.intermediate_accumulators); + assert_eq!( + p1.stage_1_opened_values.len(), + p2.stage_1_opened_values.len() + ); + assert_eq!( + p1.stage_2_opened_values.len(), + p2.stage_2_opened_values.len() + ); + assert_eq!( + p1.quotient_opened_values.len(), + p2.quotient_opened_values.len() + ); + assert_eq!( + p1.opening_proof.commit_phase_commits.len(), + p2.opening_proof.commit_phase_commits.len() + ); + assert_eq!( + p1.opening_proof.input_openings.len(), + p2.opening_proof.input_openings.len() + ); + } +} + +/// Comprehensive fail-closed soundness and security negative controls: +/// - Tampered opened leaf salt (input commitment + FRI commit phase) +/// - Tampered blinded leaf value +/// - Tampered `R(X)` randomizer OOD evaluation +/// - Tampered `U(X)` boundary mask OOD evaluation +/// - Tampered `intermediate_accumulators` (interior & final) +/// - Tampered `MerkleCap` root count (`C2`) on every commitment + FRI commit phase +/// - Cross-mode replay (`v6` <-> `v6-zk`, `Tensor` <-> `Horner`, single <-> batch) +/// - Under-sized trace rejected fail-closed at verifier +/// - Truncated `R(X)` width `< 4` rejected fail-closed at verifier +#[test] +fn v6_zk_fail_closed_security_negative_controls() { + let fri = zk_fri_params(20, 0); // min_log_degree = 6 (64 rows) + let work_rows = 128usize; + let aux_rows = 64usize; + let sq_rows = 64usize; + + let make_system = |batching: FriBatching| { + let cfg = GoldilocksBlake3V6ZkConfig::new_with_batching( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + fri, + batching, + ); + System::new(cfg, multi_circuit_zk_inputs(1, work_rows, aux_rows, true)) + }; + + let (system, key) = make_system(FriBatching::Tensor); + let (traces, claims) = build_multi_circuit_zk_witness(work_rows, aux_rows, sq_rows, true, 5); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let valid_proof = system.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &system), + ); + system + .verify_multiple_claims(&claim_refs, &valid_proof) + .unwrap(); + + // 1. Tampered opened leaf salt in input commitments (stage_1, stage_2, quotient, preprocessed). + for round in 0..valid_proof.opening_proof.input_openings.len() { + let mut tampered = valid_proof.clone(); + tampered.opening_proof.input_openings[round] + .opening_proof + .salts[0][0][0] ^= 0x01; + assert!( + matches!( + system.verify_multiple_claims(&claim_refs, &tampered), + Err(VerificationError::InvalidOpeningArgument(_)) + ), + "tampered input leaf salt in round {round} must be rejected" + ); + } + + // 2. Tampered leaf salt inside FRI commit-phase Merkle opening. + { + let mut tampered = valid_proof.clone(); + tampered.opening_proof.commit_phase_openings[0] + .opening_proof + .salts[0][0][0] ^= 0x80; + assert!( + matches!( + system.verify_multiple_claims(&claim_refs, &tampered), + Err(VerificationError::InvalidOpeningArgument(_)) + ), + "tampered FRI commit-phase leaf salt must be rejected" + ); + } + + // 3. Tampered blinded leaf value. + { + let mut tampered = valid_proof.clone(); + tampered.opening_proof.input_openings[0].opened_values[0][0][0] += Val::ONE; + assert!( + matches!( + system.verify_multiple_claims(&claim_refs, &tampered), + Err(VerificationError::InvalidOpeningArgument(_)) + ), + "tampered opened blinded leaf value must be rejected" + ); + } + + // 4. Tampered `R(X)` OOD evaluation. + { + let mut tampered = valid_proof.clone(); + let r_idx = tampered.quotient_opened_values.len() - 1; + tampered.quotient_opened_values[r_idx][0][0] += ExtVal3::ONE; + assert!( + system + .verify_multiple_claims(&claim_refs, &tampered) + .is_err(), + "tampered R(X) OOD evaluation must be rejected" + ); + } + + // 5. Truncated `R(X)` opening width (`W_R < 4`). + { + let mut tampered = valid_proof.clone(); + let r_idx = tampered.quotient_opened_values.len() - 1; + tampered.quotient_opened_values[r_idx][0].pop(); + assert!( + matches!( + system.verify_multiple_claims(&claim_refs, &tampered), + Err(VerificationError::InvalidProofShape) + ), + "truncated R(X) width < 4 must be rejected as InvalidProofShape" + ); + } + + // 6. Tampered `U(X)` boundary mask OOD evaluation. + { + let mut tampered = valid_proof.clone(); + let u_idx = tampered.stage_2_opened_values.len() - 1; + tampered.stage_2_opened_values[u_idx][0][0] += ExtVal3::ONE; + assert!( + system + .verify_multiple_claims(&claim_refs, &tampered) + .is_err(), + "tampered boundary mask U(X) OOD evaluation must be rejected" + ); + } + + // 7. Tampered `intermediate_accumulators` (interior blinded slot AND final slot). + { + let mut tampered_interior = valid_proof.clone(); + tampered_interior.intermediate_accumulators[0] += ExtVal3::ONE; + assert!( + system + .verify_multiple_claims(&claim_refs, &tampered_interior) + .is_err(), + "tampered interior blinded accumulator must be rejected" + ); + + let mut tampered_final = valid_proof.clone(); + let last = tampered_final.intermediate_accumulators.len() - 1; + tampered_final.intermediate_accumulators[last] += ExtVal3::ONE; + assert!( + matches!( + system.verify_multiple_claims(&claim_refs, &tampered_final), + Err(VerificationError::UnbalancedChannel) + ), + "tampered final accumulator must be rejected as UnbalancedChannel" + ); + } + + // 8. C2: Inflated `MerkleCap` root count on stage_1, stage_2, quotient, + // FRI commit-phase commitment, and preprocessed commitment. + { + let inflate = |cap: &MerkleCap| { + let mut roots = cap.roots().to_vec(); + roots.push([0xAAu8; 32]); + MerkleCap::new(roots) + }; + + let mut t1 = valid_proof.clone(); + t1.commitments.stage_1_trace = inflate(&t1.commitments.stage_1_trace); + assert!(matches!( + system.verify_multiple_claims(&claim_refs, &t1), + Err(VerificationError::InvalidProofShape) + )); + + let mut t2 = valid_proof.clone(); + t2.commitments.stage_2_trace = inflate(&t2.commitments.stage_2_trace); + assert!(matches!( + system.verify_multiple_claims(&claim_refs, &t2), + Err(VerificationError::InvalidProofShape) + )); + + let mut t3 = valid_proof.clone(); + t3.commitments.quotient_chunks = inflate(&t3.commitments.quotient_chunks); + assert!(matches!( + system.verify_multiple_claims(&claim_refs, &t3), + Err(VerificationError::InvalidProofShape) + )); + + let mut t_fri = valid_proof.clone(); + t_fri.opening_proof.commit_phase_commits[0] = + inflate(&t_fri.opening_proof.commit_phase_commits[0]); + assert!(matches!( + system.verify_multiple_claims(&claim_refs, &t_fri), + Err(VerificationError::InvalidOpeningArgument(_)) + )); + + // C2 on preprocessed commitment cap root count. + let (mut bad_prep_sys, _) = make_system(FriBatching::Tensor); + bad_prep_sys.preprocessed_commit = + Some(inflate(bad_prep_sys.preprocessed_commit.as_ref().unwrap())); + assert!(matches!( + bad_prep_sys.verify_multiple_claims(&claim_refs, &valid_proof), + Err(VerificationError::InvalidSystem) + )); + } + + // 9. Trap 1: Adversarial proof claiming `log_degrees` below `min_log_degree`. + { + let mut undersized = valid_proof.clone(); + // Circuit 3 has no preprocessed height so `log_degrees[3]` is untrusted. + let min_ld = system.config.min_log_degree(); + undersized.log_degrees[3] = u8::try_from(min_ld - 1).unwrap(); + assert!( + matches!( + system.verify_multiple_claims(&claim_refs, &undersized), + Err(VerificationError::InvalidProofShape) + ), + "proof with trace height below ZK floor must be rejected fail-closed" + ); + } + + // 10. Cross-mode replay: + // (a) `Tensor` proof rejected by `Horner` `v6-zk` verifier. + // (b) `v6-zk` proof bytes rejected by non-ZK `v6` deserialization/verifier + // AND `v6` proof bytes rejected by `v6-zk` deserialization/verifier. + { + let (horner_sys, _) = make_system(FriBatching::Horner); + assert!( + horner_sys + .verify_multiple_claims(&claim_refs, &valid_proof) + .is_err(), + "Tensor v6-zk proof must not verify under Horner v6-zk verifier" + ); + + let v6_cfg = GoldilocksBlake3V6Config::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + fri, + ); + let (v6_sys, v6_key) = System::new( + v6_cfg, + multi_circuit_zk_inputs(1, work_rows, aux_rows, true), + ); + // Distinct VK digests and challenger seeds between `v6` and `v6-zk`. + assert_ne!(v6_sys.vk_digest, system.vk_digest); + assert_ne!( + v6_sys.config.challenger_seed(), + system.config.challenger_seed() + ); + let v6_proof = v6_sys.prove_multiple_claims( + &v6_key, + &claim_refs, + SystemWitness::from_stage_1(traces, &v6_sys), + ); + v6_sys + .verify_multiple_claims(&claim_refs, &v6_proof) + .unwrap(); + + let v6_bytes = v6_proof.to_bytes().unwrap(); + let zk_bytes = valid_proof.to_bytes().unwrap(); + // Cross-deserialization or verification MUST fail in BOTH directions. + if let Ok(decoded_as_zk) = Proof::::from_bytes(&v6_bytes) { + assert!( + system + .verify_multiple_claims(&claim_refs, &decoded_as_zk) + .is_err(), + "non-ZK v6 proof must never verify under v6-zk verifier" + ); + } + if let Ok(decoded_as_v6) = Proof::::from_bytes(&zk_bytes) { + assert!( + v6_sys + .verify_multiple_claims(&claim_refs, &decoded_as_v6) + .is_err(), + "v6-zk proof must never verify under non-ZK v6 verifier" + ); + } + } +} + +/// Trap 1 prover enforcement: proving an under-sized trace (`N < min_zk_height`) +/// MUST panic fail-closed. +#[test] +#[should_panic(expected = "below v6-zk minimum height")] +fn v6_zk_rejects_undersized_trace_at_prove() { + let fri = zk_fri_params(20, 0); // min_log_degree = 6 -> 64 rows + assert_eq!(min_zk_log_degree(20, 3), 6); + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + fri, + ); + let (system, key) = System::new(config, single_circuit_private_sum_inputs(32)); + let (traces, claims) = build_single_circuit_witness(32, 100, 1); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let witness = SystemWitness::from_stage_1(traces, &system); + let _ = system.prove_multiple_claims(&key, &claim_refs, witness); +} + +/// Trap 1 setup enforcement: preprocessed trace height below `min_zk_height` +/// MUST be rejected fail-closed at `System::new`. +#[test] +#[should_panic(expected = "below v6-zk minimum height")] +fn v6_zk_rejects_undersized_preprocessed_trace_at_setup() { + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + zk_fri_params(20, 0), // min height = 64 + ); + let tiny_prep = CircuitInputs { + main_width: 1, + preprocessed: Some(RowMajorMatrix::new(vec![Val::ZERO; 16], 1)), + constraints: vec![Expr::main(0) - Expr::preprocessed(0)], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + let _ = System::new(config, [tiny_prep]); +} + +/// Trap 2 config enforcement: `W_R < 4` MUST be rejected fail-closed. +#[test] +#[should_panic(expected = "randomizer width W_R >= 4")] +fn v6_zk_rejects_randomizer_width_below_4() { + let _ = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + zk_fri_params(20, 0), + ) + .with_randomizer_width(3); +} + +/// Trap 4 enforcement (a): `log_blowup = 0` in ZK config MUST be rejected. +#[test] +#[should_panic(expected = "log_blowup >= 1")] +fn v6_zk_rejects_zero_log_blowup() { + let _ = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 0, + cap_height: 0, + }, + zk_fri_params(20, 0), + ); +} + +/// Trap 4 enforcement (b): degree-3 constraint at `log_blowup = 1` (`q_zk = 4 > 2`) +/// MUST be rejected fail-closed at `System::new`. +#[test] +#[should_panic(expected = "needs quotient degree 4, but the PCS only supports 2")] +fn v6_zk_rejects_degree_3_at_log_blowup_1() { + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 1, + cap_height: 0, + }, + zk_fri_params(20, 0), + ); + let _ = System::new(config, single_circuit_private_sum_inputs(64)); +} + +/// Trap 4 enforcement (c): degree-5 constraint at `log_blowup = 2` (`q_zk = 8 > 4`) +/// MUST be rejected fail-closed at `System::new`, and succeeds at `log_blowup = 3`. +#[test] +#[should_panic(expected = "needs quotient degree 8, but the PCS only supports 4")] +fn v6_zk_rejects_degree_5_at_log_blowup_2() { + let x = Expr::main(0); + let y = Expr::main(1); + let x5 = x.clone() * x.clone() * x.clone() * x.clone() * x; + let deg5_circuit = CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![x5 - y], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + zk_fri_params(20, 0), + ); + let _ = System::new(config, [deg5_circuit]); +} + +/// Companion positive check for Trap 4: degree-5 constraint succeeds cleanly at +/// `log_blowup = 3` (`q_zk = 8 <= 8`). +#[test] +fn v6_zk_accepts_degree_5_at_log_blowup_3() { + let x = Expr::main(0); + let y = Expr::main(1); + let x5 = x.clone() * x.clone() * x.clone() * x.clone() * x; + let deg5_circuit = CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![x5 - y], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + let config = GoldilocksBlake3V6ZkConfig::new( + CommitmentParameters { + log_blowup: 3, + cap_height: 0, + }, + zk_fri_params(20, 0), + ); + let (system, key) = System::new(config, [deg5_circuit]); + let rows = 64usize; + let mut vals = Vec::with_capacity(rows * 2); + for r in 0..rows { + let v = f(u32::try_from(r % 11).unwrap()); + let v5 = v * v * v * v * v; + vals.extend([v, v5]); + } + let trace = RowMajorMatrix::new(vals, 2); + let witness = SystemWitness::from_stage_1(vec![trace], &system); + let no_claims: &[&[Val]] = &[]; + let proof = system.prove_multiple_claims(&key, no_claims, witness); + system.verify_multiple_claims(no_claims, &proof).unwrap(); +} + +/// Measures and reports serialized proof sizes for non-ZK `v6` vs `v6-zk` on +/// both 1-circuit shrinker-style and 4-circuit multi-circuit systems at +/// 128-bit security parameters (`log_blowup = 2`, `num_queries = 64`, `Q` queries). +#[test] +fn v6_vs_v6_zk_proof_size_comparison() { + let fri = zk_fri_params(64, 0); // min_zk_height = 256 (2*64 + 6 = 134 -> 256) + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + + // 1-circuit (N = 256, degree 3). + { + let rows = 256usize; + let (traces, claims) = build_single_circuit_witness(rows, 999, 7); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let (sys_v6, key_v6) = System::new( + GoldilocksBlake3V6Config::new(comm, fri), + single_circuit_private_sum_inputs(rows), + ); + let p_v6 = sys_v6.prove_multiple_claims( + &key_v6, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys_v6), + ); + sys_v6.verify_multiple_claims(&claim_refs, &p_v6).unwrap(); + let v6_bytes = p_v6.to_bytes().unwrap().len(); + + let (sys_zk, key_zk) = System::new( + GoldilocksBlake3V6ZkConfig::new(comm, fri), + single_circuit_private_sum_inputs(rows), + ); + let p_zk = sys_zk.prove_multiple_claims( + &key_zk, + &claim_refs, + SystemWitness::from_stage_1(traces, &sys_zk), + ); + sys_zk.verify_multiple_claims(&claim_refs, &p_zk).unwrap(); + let zk_bytes = p_zk.to_bytes().unwrap().len(); + + eprintln!( + "[proof-size] 1-circuit (N=256, lb=2, Q=64): v6={v6_bytes} B, v6-zk={zk_bytes} B (+{} B)", + zk_bytes.saturating_sub(v6_bytes) + ); + assert!(zk_bytes > v6_bytes); + } + + // 4-circuit multi-circuit (N = 256, lookups + preprocessed + ExtExpr). + { + let rows = 256usize; + let (traces, claims) = build_multi_circuit_zk_witness(rows, rows, rows, true, 11); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + let (sys_v6, key_v6) = System::new( + GoldilocksBlake3V6Config::new(comm, fri), + multi_circuit_zk_inputs(1, rows, rows, true), + ); + let p_v6 = sys_v6.prove_multiple_claims( + &key_v6, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys_v6), + ); + sys_v6.verify_multiple_claims(&claim_refs, &p_v6).unwrap(); + let v6_bytes = p_v6.to_bytes().unwrap().len(); + + let (sys_zk, key_zk) = System::new( + GoldilocksBlake3V6ZkConfig::new(comm, fri), + multi_circuit_zk_inputs(1, rows, rows, true), + ); + let p_zk = sys_zk.prove_multiple_claims( + &key_zk, + &claim_refs, + SystemWitness::from_stage_1(traces, &sys_zk), + ); + sys_zk.verify_multiple_claims(&claim_refs, &p_zk).unwrap(); + let zk_bytes = p_zk.to_bytes().unwrap().len(); + + eprintln!( + "[proof-size] 4-circuit (N=256, lb=2, Q=64): v6={v6_bytes} B, v6-zk={zk_bytes} B (+{} B)", + zk_bytes.saturating_sub(v6_bytes) + ); + assert!(zk_bytes > v6_bytes); + } +} From 04b10be013a0ffd39b8d2c408063ca4730385ea0 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sun, 22 Nov 2026 22:21:13 -0500 Subject: [PATCH 25/28] fix(cuda): resolve Blackwell --features parallel,cuda clippy and test build issues Fold in the 5-file GPU Wave 1.5 fixes so multi-stark-fp3-zk builds and passes with zero warnings under CARGO_BUILD_WARNINGS=deny and --features parallel,cuda: - src/cuda/hiding_pcs.rs: borrow &self.dft before rayon parallel closure. - src/cuda/mmcs.rs: update test calls to 2-arg CudaMmcs::with_device. - src/cuda/tests/quotient.rs: pass None for mask_on_quotient_domain. - src/cuda/hiding_mmcs.rs: allow dead_code on CpuHidingTree::dimensions. - tests/fp3_v6.rs: use binary FRI fold (max_log_arity = 1) when cuda feature is enabled. --- src/cuda/hiding_mmcs.rs | 1 + src/cuda/hiding_pcs.rs | 4 ++-- src/cuda/mmcs.rs | 4 ++-- src/cuda/tests/quotient.rs | 1 + tests/fp3_v6.rs | 4 ++-- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/cuda/hiding_mmcs.rs b/src/cuda/hiding_mmcs.rs index 82dfe22..c64e4dd 100644 --- a/src/cuda/hiding_mmcs.rs +++ b/src/cuda/hiding_mmcs.rs @@ -213,6 +213,7 @@ impl> CpuHidingTree { self.leaves.iter().map(Matrix::height).collect() } + #[allow(dead_code)] fn dimensions(&self) -> Vec { self.leaves.iter().map(Matrix::dimensions).collect() } diff --git a/src/cuda/hiding_pcs.rs b/src/cuda/hiding_pcs.rs index 440638a..4c1e173 100644 --- a/src/cuda/hiding_pcs.rs +++ b/src/cuda/hiding_pcs.rs @@ -360,12 +360,12 @@ where .saturating_add(max_transform_workspace) > initial_free { + let dft = &self.dft; let ldes: Vec> = prepared .into_par_iter() .map(|(domain, evals)| { let shift = Goldilocks::GENERATOR / domain.shift(); - if let Some(lde) = self.dft.try_coset_lde_batch_host(&evals, added_bits, shift) - { + if let Some(lde) = dft.try_coset_lde_batch_host(&evals, added_bits, shift) { return lde; } let cpu = Radix2DitParallel::::default(); diff --git a/src/cuda/mmcs.rs b/src/cuda/mmcs.rs index a6fc51a..19a4ae5 100644 --- a/src/cuda/mmcs.rs +++ b/src/cuda/mmcs.rs @@ -1804,7 +1804,7 @@ mod tests { .iter() .map(|&i| cpu.open_batch(i, &expected_data)) .collect(); - let mmcs = CudaMmcs::with_device(cpu, 0, 0); + let mmcs = CudaMmcs::with_device(cpu, 0); let ldes = matrices .iter() .map(|m| CudaLde::from_row_major_matrix(mmcs.device_id, m)) @@ -1828,7 +1828,7 @@ mod tests { let (expected_commitment, expected_data) = cpu.commit(matrices.clone()); let expected_opening = cpu.open_batch(5, &expected_data); - let mmcs = CudaMmcs::with_device(cpu, 0, 0); + let mmcs = CudaMmcs::with_device(cpu, 0); let resident = vec![ Some(CudaLde::from_row_major_matrix(mmcs.device_id, &matrices[0])), None, diff --git a/src/cuda/tests/quotient.rs b/src/cuda/tests/quotient.rs index ffb2ce2..233f830 100644 --- a/src/cuda/tests/quotient.rs +++ b/src/cuda/tests/quotient.rs @@ -271,6 +271,7 @@ fn check_quotient( &(circuit.preprocessed_width != 0).then(|| evaluations(0)), &evaluations(1), &evaluations(2), + None, alpha, constraint_count, ); diff --git a/tests/fp3_v6.rs b/tests/fp3_v6.rs index ffd1a80..793af16 100644 --- a/tests/fp3_v6.rs +++ b/tests/fp3_v6.rs @@ -1048,7 +1048,7 @@ fn bench_fp2_vs_fp3_cpu() { }; let fri = FriParameters { log_final_poly_len: 0, - max_log_arity: 2, + max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, num_queries: 64, commit_proof_of_work_bits: 0, query_proof_of_work_bits: 0, @@ -1487,7 +1487,7 @@ fn v6_fp3_large_lde_above_1024_rows_roundtrip() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: 2, + max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, num_queries: 24, commit_proof_of_work_bits: 0, query_proof_of_work_bits: 0, From 310c5a3f1889940702c293edc864be4477860243 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Sun, 22 Nov 2026 22:24:50 -0500 Subject: [PATCH 26/28] feat(plonkish): support Blake3Domain derive_key mode in compact and generic BLAKE3 gadgets Add backwards-compatible domain-separated BLAKE3 support to Plonkish hashing for Protocol v6 recursion and proof compression with zero extra gates or tables: - src/plonkish/hash.rs: record Blake3Domain on HashCall, initialize Compact chaining values from domain.key_words(), OR domain.domain_flags() into compression flags, and verify via domain.hash_bytes() in check_values. - src/plonkish/builder.rs: add CircuitBuilder::constrain_blake3_domain and Circuit::blake3_domain_calls (keeping existing plain APIs unchanged). - src/plonkish/gadgets/{blake3.rs, mod.rs}: expose blake3_domain and re-export Blake3Domain across both compact and generic lowering modes. - src/plonkish/tests/compact_hash.rs: verify Plain, MerkleLeaf, MerkleCompress, TranscriptSingle, and TranscriptBatch across block/tree boundaries, full v6 STARK prove/verify roundtrip, and cross-domain forgery rejection. --- src/plonkish/builder.rs | 37 ++++++- src/plonkish/gadgets/blake3.rs | 42 +++++--- src/plonkish/gadgets/mod.rs | 3 +- src/plonkish/hash.rs | 32 +++--- src/plonkish/tests/compact_hash.rs | 150 ++++++++++++++++++++++++++++- 5 files changed, 238 insertions(+), 26 deletions(-) diff --git a/src/plonkish/builder.rs b/src/plonkish/builder.rs index d69c23a..0486945 100644 --- a/src/plonkish/builder.rs +++ b/src/plonkish/builder.rs @@ -3,6 +3,7 @@ use std::{collections::HashMap, fmt}; use p3_maybe_rayon::prelude::*; +use crate::p3_adapter::domain_blake3::Blake3Domain; use crate::traits::Field; use super::{Witness, WitnessError}; @@ -260,6 +261,17 @@ impl Circuit { .map(|c| (c.input.as_slice(), &c.output)) } + /// Compact BLAKE3 calls with their [`Blake3Domain`] that a backend must + /// constrain, including byte bindings. + pub fn blake3_domain_calls( + &self, + ) -> impl Iterator { + self.hashes + .iter() + .flat_map(|h| &h.calls) + .map(|c| (c.domain, c.input.as_slice(), &c.output)) + } + /// Public bindings in the order they were exposed. pub fn public_values(&self) -> &[Value] { &self.publics @@ -414,11 +426,33 @@ impl CircuitBuilder { /// Both input and output bytes are range constrained by the lowering. /// This adds a relation, not a witness recipe for the output wires. pub fn constrain_blake3(&mut self, input: Vec, output: &[Value; 32]) { + self.constrain_blake3_domain(Blake3Domain::Plain, input, output); + } + + /// Constrain existing byte wires to a domain-separated BLAKE3 digest using + /// compact traces. Both input and output bytes are range constrained by + /// the lowering. This adds a relation, not a witness recipe for the output wires. + pub fn constrain_blake3_domain( + &mut self, + domain: Blake3Domain, + input: Vec, + output: &[Value; 32], + ) { self.enable_compact_blake3(); - self.record_hash(input, output); + self.record_hash_domain(domain, input, output); } + #[cfg_attr(not(test), allow(dead_code))] pub(super) fn record_hash(&mut self, input: Vec, output: &[Value; 32]) { + self.record_hash_domain(Blake3Domain::Plain, input, output); + } + + pub(super) fn record_hash_domain( + &mut self, + domain: Blake3Domain, + input: Vec, + output: &[Value; 32], + ) { for &v in input.iter().chain(output) { self.check(v); } @@ -434,6 +468,7 @@ impl CircuitBuilder { .as_mut() .expect("compact hash enabled") .add_call(super::hash::HashCall { + domain, input, output: *output, }); diff --git a/src/plonkish/gadgets/blake3.rs b/src/plonkish/gadgets/blake3.rs index 49e3db7..b55db76 100644 --- a/src/plonkish/gadgets/blake3.rs +++ b/src/plonkish/gadgets/blake3.rs @@ -1,3 +1,4 @@ +use crate::p3_adapter::domain_blake3::Blake3Domain; use crate::traits::PrimeField; use super::bytes::Word; @@ -105,33 +106,36 @@ impl Output { fn subtree( b: &mut CircuitBuilder, bytes: &ByteGadgets, + domain: Blake3Domain, input: &[ByteValue], counter: u64, ) -> Output { - let iv = IV.map(|x| bytes.word_constant(b, x)); + let cv_init = domain.key_words().map(|x| bytes.word_constant(b, x)); + let domain_flags = domain.domain_flags(); if input.len() > 1024 { let chunks = input.len().div_ceil(1024); let left_chunks = 1usize << (usize::BITS - 1 - (chunks - 1).leading_zeros()); let split = left_chunks * 1024; - let left = subtree(b, bytes, &input[..split], counter).compress(b, bytes, false); + let left = subtree(b, bytes, domain, &input[..split], counter).compress(b, bytes, false); let right = subtree( b, bytes, + domain, &input[split..], counter + u64::try_from(left_chunks).unwrap(), ) .compress(b, bytes, false); return Output { - cv: iv, + cv: cv_init, block: std::array::from_fn(|i| if i < 8 { left[i] } else { right[i - 8] }), counter: 0, len: 64, - flags: PARENT, + flags: PARENT | domain_flags, }; } let zero = bytes.constant(b, 0); let blocks = input.len().div_ceil(64).max(1); - let mut cv = iv; + let mut cv = cv_init; for i in 0..blocks { let start = i * 64; let len = input.len().saturating_sub(start).min(64); @@ -154,7 +158,9 @@ fn subtree( block, counter, len: u32::try_from(len).unwrap(), - flags: if i == 0 { CHUNK_START } else { 0 } | if last { CHUNK_END } else { 0 }, + flags: (if i == 0 { CHUNK_START } else { 0 }) + | (if last { CHUNK_END } else { 0 }) + | domain_flags, }; if last { return output; @@ -171,11 +177,23 @@ pub fn blake3( b: &mut CircuitBuilder, bytes: &ByteGadgets, input: &[ByteValue], +) -> [ByteValue; 32] { + blake3_domain(b, bytes, Blake3Domain::Plain, input) +} + +/// Domain-separated BLAKE3 (`Plain` unkeyed or BLAKE3 `derive_key` mode), +/// 32-byte output, with a construction-time fixed input length. Uses the +/// builder's compact BLAKE3 custom gates when enabled, or generic Plonkish +/// gates otherwise. +pub fn blake3_domain( + b: &mut CircuitBuilder, + bytes: &ByteGadgets, + domain: Blake3Domain, + input: &[ByteValue], ) -> [ByteValue; 32] { if b.compact_blake3_enabled() { - use p3_symmetric::CryptographicHasher; let input: Vec<_> = input.iter().map(|v| v.value()).collect(); - let output = b.hint_many("BLAKE3 advice", &input, |values| { + let output = b.hint_many("BLAKE3 advice", &input, move |values| { let bytes: Result, String> = values .iter() .map(|&v| { @@ -183,13 +201,13 @@ pub fn blake3( .map_err(|_error| "non-byte hash input".into()) }) .collect(); - let digest: [u8; 32] = p3_blake3::Blake3.hash_iter(bytes?); + let digest = domain.hash_bytes(&bytes?); Ok(digest.map(F::from_u8)) }); - b.record_hash(input, &output); + b.record_hash_domain(domain, input, &output); return output.map(|v| bytes.constrain_byte(b, v)); } - let output = subtree(b, bytes, input, 0).compress(b, bytes, true); + let output = subtree(b, bytes, domain, input, 0).compress(b, bytes, true); let words = output.map(|w| bytes.word_bytes(b, w)); std::array::from_fn(|i| words[i / 4][i % 4]) } @@ -205,7 +223,7 @@ pub fn blake3_xof( if length == 0 { return vec![]; } - let root = subtree(b, bytes, input, 0); + let root = subtree(b, bytes, Blake3Domain::Plain, input, 0); let mut result = Vec::with_capacity(length); for counter in 0..length.div_ceil(64) { let state = root.state(b, bytes, true, counter as u64); diff --git a/src/plonkish/gadgets/mod.rs b/src/plonkish/gadgets/mod.rs index 4c3d84f..a6e7523 100644 --- a/src/plonkish/gadgets/mod.rs +++ b/src/plonkish/gadgets/mod.rs @@ -7,5 +7,6 @@ mod blake3; mod bytes; -pub use blake3::{blake3, blake3_xof}; +pub use crate::p3_adapter::domain_blake3::Blake3Domain; +pub use blake3::{blake3, blake3_domain, blake3_xof}; pub use bytes::{ByteGadgets, ByteValue}; diff --git a/src/plonkish/hash.rs b/src/plonkish/hash.rs index 4c7eda7..6dd4166 100644 --- a/src/plonkish/hash.rs +++ b/src/plonkish/hash.rs @@ -18,12 +18,11 @@ //! pull from generic wires; digest bindings push back. Channel 4 contains //! this entire vocabulary, disjoint from generic copy/public/table channels. use super::{Value, WitnessError}; +use crate::p3_adapter::domain_blake3::Blake3Domain; use crate::traits::Field; use crate::{expr::Expr, lookup::Lookup, system::CircuitInputs}; -use p3_blake3::Blake3; use p3_matrix::{Matrix, dense::RowMajorMatrix}; use p3_maybe_rayon::prelude::*; -use p3_symmetric::CryptographicHasher; use std::collections::HashMap; const IV: [u32; 8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, @@ -98,6 +97,7 @@ struct Output { flags: u32, } pub(super) struct HashCall { + pub domain: Blake3Domain, pub input: Vec, pub output: [Value; 32], } @@ -176,31 +176,39 @@ impl Compact { w }) } - fn subtree(&mut self, input: &[usize], len: usize, counter: u64) -> Output { - let iv = IV.map(|x| self.constant(x)); + fn subtree( + &mut self, + input: &[usize], + len: usize, + counter: u64, + domain: Blake3Domain, + ) -> Output { + let cv_init = domain.key_words().map(|x| self.constant(x)); + let domain_flags = domain.domain_flags(); if len > 1024 { let chunks = len.div_ceil(1024); let left = 1usize << (usize::BITS - 1 - (chunks - 1).leading_zeros()); let split = left * 1024; - let lo = self.subtree(&input[..split / 4], split, counter); + let lo = self.subtree(&input[..split / 4], split, counter, domain); let lo = self.compress(lo, false); let hi = self.subtree( &input[split / 4..], len - split, counter + u64::try_from(left).unwrap(), + domain, ); let hi = self.compress(hi, false); return Output { - cv: iv, + cv: cv_init, block: std::array::from_fn(|i| if i < 8 { lo[i] } else { hi[i - 8] }), counter: 0, len: 64, - flags: 4, + flags: 4 | domain_flags, }; } let zero = self.constant(0); let blocks = len.div_ceil(64).max(1); - let mut cv = iv; + let mut cv = cv_init; for i in 0..blocks { let block = std::array::from_fn(|j| input.get(i * 16 + j).copied().unwrap_or(zero)); let out = Output { @@ -208,7 +216,9 @@ impl Compact { block, counter, len: u32::try_from(len.saturating_sub(i * 64).min(64)).unwrap(), - flags: if i == 0 { 1 } else { 0 } | if i + 1 == blocks { 2 } else { 0 }, + flags: (if i == 0 { 1 } else { 0 }) + | (if i + 1 == blocks { 2 } else { 0 }) + | domain_flags, }; if i + 1 == blocks { return out; @@ -233,7 +243,7 @@ impl Compact { output: false, }); } - let out = self.subtree(&input, len, 0); + let out = self.subtree(&input, len, 0, call.domain); let digest = self.compress(out, true); for (i, w) in digest.into_iter().enumerate() { self.rows[5].push(vec![w]); @@ -275,7 +285,7 @@ impl Compact { } pub(super) fn check_values(&self, values: &[F]) -> Result<(), WitnessError> { for (call, msg) in self.calls.iter().zip(self.messages(values)?) { - let digest: [u8; 32] = Blake3.hash_iter(msg); + let digest: [u8; 32] = call.domain.hash_bytes(&msg); if call .output .iter() diff --git a/src/plonkish/tests/compact_hash.rs b/src/plonkish/tests/compact_hash.rs index a2274c1..ead2a69 100644 --- a/src/plonkish/tests/compact_hash.rs +++ b/src/plonkish/tests/compact_hash.rs @@ -1,5 +1,6 @@ use super::*; -use crate::plonkish::gadgets::{ByteGadgets, blake3}; +use crate::plonkish::gadgets::{Blake3Domain, ByteGadgets, blake3, blake3_domain}; +use crate::types::GoldilocksBlake3V6Config; use p3_blake3::Blake3; use p3_symmetric::CryptographicHasher; @@ -158,3 +159,150 @@ fn compact_hash_bridge_rejects_valid_hash_traces_for_a_different_witness() { assert!(!relations_hold(&defs, &bad, claims)); } } + +#[test] +fn domain_separated_blake3_compact_and_generic_match_native_across_boundaries() { + let domains = [ + Blake3Domain::Plain, + Blake3Domain::MerkleLeaf, + Blake3Domain::MerkleCompress, + Blake3Domain::TranscriptSingle, + Blake3Domain::TranscriptBatch, + ]; + let lengths = [0usize, 1, 63, 64, 65, 1023, 1024, 1025, 2049]; + for compact in [false, true] { + let mut b = CircuitBuilder::::new(); + if compact { + b.enable_compact_blake3(); + } + let bytes = ByteGadgets::new(&mut b); + let mut calls = vec![]; + for (idx, &len) in lengths.iter().enumerate() { + let domain = domains[idx % domains.len()]; + let input: Vec<_> = (0..len) + .map(|i| bytes.input(&mut b, &format!("d{idx}/{i}"))) + .collect(); + let digest = blake3_domain(&mut b, &bytes, domain, &input); + for byte in digest { + b.expose_public(byte.value()); + } + calls.push((domain, input)); + } + let circuit = b.finish(); + if compact { + assert_eq!(circuit.stats().hash_calls, lengths.len()); + let recorded: Vec<_> = circuit.blake3_domain_calls().map(|(d, _, _)| d).collect(); + let expected_domains: Vec<_> = calls.iter().map(|(d, _)| *d).collect(); + assert_eq!(recorded, expected_domains); + } else { + assert_eq!(circuit.stats().hash_calls, 0); + } + let compiled = circuit.lower_to_multi_stark(Val::from_u8(95)).unwrap(); + let defs = compiled.circuit_inputs(); + let mut w = compiled.witness(); + let mut expected = vec![]; + for (domain, input) in &calls { + let message: Vec = (0..input.len()) + .map(|i| u8::try_from((i * 19 + 7) % 256).unwrap()) + .collect(); + for (wire, &byte) in input.iter().zip(&message) { + w.set(wire.value(), Val::from_u8(byte)).unwrap(); + } + let digest = domain.hash_bytes(&message); + expected.extend(digest.map(Val::from_u8)); + } + let a = w.generate().unwrap(); + assert_eq!(a.public_values(), expected); + let traces = compiled.traces(&a).unwrap(); + let claims = compiled.claims(&expected).unwrap(); + assert!(relations_hold(&defs, &traces, &claims)); + } +} + +#[test] +fn compact_domain_separated_blake3_roundtrips_and_rejects_cross_domain_forgery() { + let domains = [ + Blake3Domain::Plain, + Blake3Domain::MerkleLeaf, + Blake3Domain::MerkleCompress, + Blake3Domain::TranscriptSingle, + Blake3Domain::TranscriptBatch, + ]; + let mut b = CircuitBuilder::::new(); + b.enable_compact_blake3(); + let bytes = ByteGadgets::new(&mut b); + let input: Vec<_> = (0..64) + .map(|i| bytes.input(&mut b, &format!("msg{i}"))) + .collect(); + for &domain in &domains { + let digest = blake3_domain(&mut b, &bytes, domain, &input); + for byte in digest { + b.expose_public(byte.value()); + } + } + let circuit = b.finish(); + let compiled = circuit.lower_to_multi_stark(Val::from_u8(96)).unwrap(); + let defs = compiled.circuit_inputs(); + let v6_cfg = GoldilocksBlake3V6Config::new( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + FriParameters { + log_final_poly_len: 0, + max_log_arity: 1, + num_queries: 32, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + ); + let (system, key) = System::new(v6_cfg, defs.clone()); + + let message: Vec = (0..64).map(|i| u8::try_from(i * 3 + 5).unwrap()).collect(); + let mut w = compiled.witness(); + for (wire, &byte) in input.iter().zip(&message) { + w.set(wire.value(), Val::from_u8(byte)).unwrap(); + } + let a = w.generate().unwrap(); + let mut expected = vec![]; + for &domain in &domains { + expected.extend(domain.hash_bytes(&message).map(Val::from_u8)); + } + assert_eq!(a.public_values(), expected); + + let traces = compiled.traces(&a).unwrap(); + let claims = compiled.claims(&expected).unwrap(); + assert!(relations_hold(&defs, &traces, &claims)); + let refs: Vec<_> = claims.iter().map(Vec::as_slice).collect(); + let proof = system.prove_multiple_claims( + &key, + &refs, + SystemWitness::from_stage_1(traces.clone(), &system), + ); + system.verify_multiple_claims(&refs, &proof).unwrap(); + + // Swapping Plain's digest into MerkleLeaf's public slots must fail both + // relations and STARK verification. + let mut swapped_publics = expected.clone(); + swapped_publics[32..64].copy_from_slice(&expected[0..32]); + let swapped_claims = compiled.claims(&swapped_publics).unwrap(); + assert!(!relations_hold(&defs, &traces, &swapped_claims)); + let swapped_refs: Vec<_> = swapped_claims.iter().map(Vec::as_slice).collect(); + assert!( + system + .verify_multiple_claims(&swapped_refs, &proof) + .is_err() + ); + + // Direct check_values must reject a witness with Plain's digest in a keyed call. + let mut bad_values = a.values(compiled.circuit().id()).unwrap().to_vec(); + let (_, _, leaf_output) = compiled.circuit().blake3_domain_calls().nth(1).unwrap(); + let plain_digest = Blake3Domain::Plain.hash_bytes(&message); + for (wire, byte) in leaf_output.iter().zip(plain_digest) { + bad_values[wire.index()] = Val::from_u8(byte); + } + assert_eq!( + compiled.circuit().check_values(&bad_values), + Err(WitnessError::HashMismatch) + ); +} From 23861659c802b860ac6421d4c70b3198a98c54e3 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Mon, 23 Nov 2026 09:38:11 -0500 Subject: [PATCH 27/28] feat(cuda): support multi-ary FRI folding (max_log_arity > 1) for v5, v6, and v6-zk --- cuda/kernels.cu | 84 ++- src/cuda/mod.rs | 10 + src/cuda/tests/fri_arity.rs | 1248 +++++++++++++++++++++++++++++++++++ src/types.rs | 49 +- tests/fp3_v6.rs | 195 +++++- tests/fp3_v6_zk.rs | 89 +++ tests/streaming_spill.rs | 2 +- 7 files changed, 1641 insertions(+), 36 deletions(-) create mode 100644 src/cuda/tests/fri_arity.rs diff --git a/cuda/kernels.cu b/cuda/kernels.cu index 13bfe62..bdd94a2 100644 --- a/cuda/kernels.cu +++ b/cuda/kernels.cu @@ -1277,6 +1277,13 @@ __global__ void init_fri_powers(uint64_t* powers,size_t height,uint64_t g_inv){ powers[row]=goldilocks_mul(0x7fffffff80000001ULL,goldilocks_pow(g_inv,exponent)); } } +__global__ void halve_fri_powers(uint64_t* output,const uint64_t* input,size_t height){ + for(size_t row=static_cast(blockIdx.x)*blockDim.x+threadIdx.x;row(gridDim.x)*blockDim.x){ + const uint64_t v=input[row<<1]; + const uint64_t sq=goldilocks_mul(v,v); + output[row]=goldilocks_add(sq,sq); + } +} template __global__ void add_scaled_t(Ext* output,const Ext* input,size_t count,Ext scale,uint64_t ext_w){ using Ops = ExtOps; @@ -3560,20 +3567,67 @@ int fri_fold_resident_impl(int device_id,void** output,const void* input, const void* next_reduced,const uint64_t* beta,size_t log_arity, Ext beta_power,uint64_t g_inv,uint64_t ext_w){ constexpr size_t D = ExtOps::D; - if(!output||!input||!beta||log_arity!=1)return static_cast(cudaErrorInvalidValue);*output=nullptr; - auto* in=static_cast(input);if(in->width!=D||in->height%2)return static_cast(cudaErrorInvalidValue); - const size_t final_height=in->height>>log_arity;auto* next=static_cast(next_reduced); - if(next&&(next->height!=final_height||next->ext_degree!=D))return static_cast(cudaErrorInvalidValue); - cudaError_t status=cudaSetDevice(device_id);Ext *a=reinterpret_cast(in->values),*first=nullptr;uint64_t* powers=nullptr; - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&first),(in->height/2)*sizeof(Ext)); - if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&powers),(in->height/2)*sizeof(uint64_t)); - if(status==cudaSuccess){init_fri_powers<<height/2),THREADS>>>(powers,in->height/2,g_inv);status=cudaGetLastError();} - if(status==cudaSuccess){fold_fri_t<<>>(first,a,powers,final_height,ExtOps::load(beta),ext_w);status=cudaGetLastError();} - a=first; - if(status==cudaSuccess&&next){add_scaled_t<<>>(a,reinterpret_cast(next->values),final_height,beta_power,ext_w);status=cudaGetLastError();} - ResidentLde* result=nullptr;if(status==cudaSuccess)status=create_resident_lde(&result); - if(status==cudaSuccess){result->values=reinterpret_cast(a);result->height=final_height;result->width=D;first=nullptr;*output=result;}else destroy_resident_lde(result); - cudaFree(powers);cudaFree(first);return static_cast(status); + if(!output||!input||!beta||log_arity==0||log_arity>=sizeof(size_t)*8) + return static_cast(cudaErrorInvalidValue); + *output=nullptr; + auto* in=static_cast(input); + const size_t arity=size_t(1)<width!=D||!is_power_of_two(in->height)||in->height(cudaErrorInvalidValue); + const size_t final_height=in->height>>log_arity; + auto* next=static_cast(next_reduced); + if(next&&(next->height!=final_height||next->ext_degree!=D)) + return static_cast(cudaErrorInvalidValue); + cudaError_t status=cudaSetDevice(device_id); + Ext *out_buf=nullptr,*scratch_a=nullptr,*scratch_b=nullptr; + uint64_t *powers_a=nullptr,*powers_b=nullptr; + const size_t first_half=in->height>>1; + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&out_buf),final_height*sizeof(Ext)); + if(status==cudaSuccess)status=cudaMalloc(reinterpret_cast(&powers_a),first_half*sizeof(uint64_t)); + if(status==cudaSuccess&&log_arity>=2)status=cudaMalloc(reinterpret_cast(&scratch_a),first_half*sizeof(Ext)); + if(status==cudaSuccess&&log_arity>=2)status=cudaMalloc(reinterpret_cast(&powers_b),(first_half>>1)*sizeof(uint64_t)); + if(status==cudaSuccess&&log_arity>=3)status=cudaMalloc(reinterpret_cast(&scratch_b),(first_half>>1)*sizeof(Ext)); + const Ext* src=reinterpret_cast(in->values); + const uint64_t* cur_powers=powers_a; + size_t half_height=first_half; + for(size_t step=0;status==cudaSuccess&&step>>(powers_a,half_height,g_inv); + status=cudaGetLastError(); + cur_powers=powers_a; + }else{ + uint64_t* next_powers=(step&1U)?powers_b:powers_a; + halve_fri_powers<<>>(next_powers,cur_powers,half_height); + status=cudaGetLastError(); + cur_powers=next_powers; + } + Ext* dst=(step+1==log_arity)?out_buf:((step&1U)==0?scratch_a:scratch_b); + if(status==cudaSuccess){ + fold_fri_t<<>>( + dst,src,cur_powers,half_height,ExtOps::load(beta+step*D),ext_w); + status=cudaGetLastError(); + } + src=dst; + half_height>>=1; + } + if(status==cudaSuccess&&next){ + add_scaled_t<<>>( + out_buf,reinterpret_cast(next->values),final_height,beta_power,ext_w); + status=cudaGetLastError(); + } + ResidentLde* result=nullptr; + if(status==cudaSuccess)status=create_resident_lde(&result); + if(status==cudaSuccess){ + result->values=reinterpret_cast(out_buf); + result->height=final_height; + result->width=D; + out_buf=nullptr; + *output=result; + }else{ + destroy_resident_lde(result); + } + cudaFree(powers_b);cudaFree(powers_a);cudaFree(scratch_b);cudaFree(scratch_a);cudaFree(out_buf); + return static_cast(status); } template @@ -5030,7 +5084,7 @@ int fri_merkle_create_impl( } const auto* codeword = static_cast(codeword_handle); if ((codeword->width != 2 && codeword->width != 3) || - codeword->height % arity != 0) { + !is_power_of_two(codeword->height) || codeword->height < arity) { return static_cast(cudaErrorInvalidValue); } ResidentLde view; diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 5e59d5c..c094b81 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -477,6 +477,15 @@ impl CudaLde { ) -> Self { let _span = tracing::info_span!("cuda/fri_fold").entered(); assert!(ext_degree == 2 || ext_degree == 3); + assert!( + log_arity > 0 && log_arity < usize::BITS as usize, + "invalid FRI log_arity {log_arity}" + ); + assert!( + self.height.is_power_of_two() && self.height >= (1usize << log_arity), + "codeword height {} incompatible with log_arity {log_arity}", + self.height + ); assert_eq!(self.width, ext_degree); assert_eq!(betas.len(), log_arity * ext_degree); assert_eq!(beta_power.len(), ext_degree); @@ -4753,6 +4762,7 @@ mod tests { use p3_symmetric::CryptographicHasher; use rand::{RngExt, SeedableRng, rngs::SmallRng}; + mod fri_arity; mod lookup_graph; mod quotient; mod witness; diff --git a/src/cuda/tests/fri_arity.rs b/src/cuda/tests/fri_arity.rs new file mode 100644 index 0000000..dc54bc0 --- /dev/null +++ b/src/cuda/tests/fri_arity.rs @@ -0,0 +1,1248 @@ +use core::marker::PhantomData; +use std::time::Instant; + +use p3_commit::{ExtensionMmcs, Mmcs, Pcs}; +use p3_field::coset::TwoAdicMultiplicativeCoset; +use p3_field::{ExtensionField, PackedFieldExtension, batch_multiplicative_inverse, dot_product}; +use p3_fri::{ + FriFoldingStrategy, FriParameters as InnerFriParameters, TwoAdicFriFolding, + TwoAdicFriFoldingForMmcs, prover, +}; +use p3_matrix::interpolation::{Interpolate, compute_adjusted_weights}; +use p3_maybe_rayon::prelude::*; +use p3_merkle_tree::MerkleTreeMmcs; +use p3_symmetric::{CompressionFunctionFromHasher, SerializingHasher}; +use p3_util::linear_map::LinearMap; +use p3_util::reverse_slice_index_bits; + +use super::*; +use crate::cuda::hiding_mmcs::{HidingCudaFriMmcs, HidingCudaFriRound, HidingCudaMmcs}; +use crate::cuda::mmcs::CudaMmcs; +use crate::cuda::pcs::CudaTwoAdicFriPcs; +use crate::expr::Expr; +use crate::lookup::Lookup; +use crate::p3_adapter::domain_blake3::{Blake3Domain, DomainBlake3}; +use crate::p3_adapter::fri_batching::{ + FriBatching, FriBatchingSchedule, pack_ext_weights, verify_fri_with_batching, +}; +use crate::prover::Proof; +use crate::system::{CircuitInputs, System, SystemWitness}; +use crate::types::{ + Challenger, CommitmentParameters, DomainChallenger, ExtVal2, ExtVal3, FriParameters, + GoldilocksBlake3Config, GoldilocksBlake3V6Config, GoldilocksBlake3V6ZkConfig, Val, +}; + +fn random_ext>(rng: &mut SmallRng, d: usize) -> Challenge { + let mut coeffs = [Goldilocks::ZERO; 3]; + for coeff in &mut coeffs[..d] { + *coeff = rng.random::(); + } + Challenge::from_basis_coefficients_slice(&coeffs[..d]).expect("extension element") +} + +fn flatten_ext>( + values: &[Challenge], + d: usize, +) -> Vec { + let mut flat = Vec::with_capacity(values.len() * d); + for value in values { + flat.extend_from_slice(&value.as_basis_coefficients_slice()[..d]); + } + flat +} + +fn unflatten_ext>( + matrix: &RowMajorMatrix, + d: usize, +) -> Vec { + assert_eq!(matrix.width(), d); + matrix + .values + .chunks_exact(d) + .map(|chunk| Challenge::from_basis_coefficients_slice(chunk).expect("extension row")) + .collect() +} + +fn check_fri_fold_parity>( + device: i32, + ext_degree: usize, + ext_w: Goldilocks, + seed: u64, +) { + let mut rng = SmallRng::seed_from_u64(seed); + let folding: TwoAdicFriFolding<(), ()> = TwoAdicFriFolding(PhantomData); + + for log_arity in 1usize..=5 { + let arity = 1usize << log_arity; + let heights = [arity, arity << 4, 1usize << 13]; + for height in heights { + if height < arity { + continue; + } + let log_height = log2_strict_usize(height); + let final_height = height >> log_arity; + + let input_ext: Vec = (0..height) + .map(|_| random_ext(&mut rng, ext_degree)) + .collect(); + let input_flat = flatten_ext(&input_ext, ext_degree); + let input_mat = RowMajorMatrix::new(input_flat, ext_degree); + let input_gpu = CudaLde::from_row_major_matrix(device, &input_mat); + + let beta: Challenge = random_ext(&mut rng, ext_degree); + let mut beta_step = beta; + let mut betas_flat = Vec::with_capacity(log_arity * ext_degree); + for _ in 0..log_arity { + betas_flat + .extend_from_slice(&beta_step.as_basis_coefficients_slice()[..ext_degree]); + beta_step = beta_step.square(); + } + let beta_power = beta.exp_power_of_2(log_arity); + let beta_power_slice = &beta_power.as_basis_coefficients_slice()[..ext_degree]; + let g_inv = Goldilocks::two_adic_generator(log_height).inverse(); + + let cpu_folded = folding.fold_matrix( + beta, + log_arity, + RowMajorMatrix::new(input_ext.clone(), arity).as_view(), + ); + assert_eq!(cpu_folded.len(), final_height); + + // Case 1: without next_reduced. + let gpu_folded = input_gpu.fri_fold( + None, + &betas_flat, + log_arity, + beta_power_slice, + g_inv, + ext_w, + ext_degree, + ); + assert_eq!(gpu_folded.height(), final_height); + assert_eq!(gpu_folded.width(), ext_degree); + let gpu_mat = gpu_folded.to_row_major_matrix(); + assert!( + gpu_mat.values.iter().all(|&v| { + // SAFETY: Goldilocks is repr(transparent) over u64. + let raw = unsafe { core::mem::transmute::(v) }; + raw < Goldilocks::ORDER_U64 + }), + "folded codeword must be canonical (d={ext_degree}, log_arity={log_arity}, h={height})" + ); + let gpu_ext: Vec = unflatten_ext(&gpu_mat, ext_degree); + assert_eq!( + gpu_ext, cpu_folded, + "GPU fri_fold mismatch without next_reduced (d={ext_degree}, log_arity={log_arity}, h={height})" + ); + + // Case 2: with next_reduced folded in via beta^(2^log_arity). + let next_ext: Vec = (0..final_height) + .map(|_| random_ext(&mut rng, ext_degree)) + .collect(); + let next_flat = flatten_ext(&next_ext, ext_degree); + let mut next_gpu = + CudaReducedOpening::new_with_degree(device, final_height, ext_degree); + next_gpu.add_host_flat(&next_flat); + + let cpu_with_next: Vec = cpu_folded + .iter() + .zip(&next_ext) + .map(|(&f, &n)| f + beta_power * n) + .collect(); + let gpu_with_next = input_gpu.fri_fold( + Some(&next_gpu), + &betas_flat, + log_arity, + beta_power_slice, + g_inv, + ext_w, + ext_degree, + ); + let gpu_with_next_ext: Vec = + unflatten_ext(&gpu_with_next.to_row_major_matrix(), ext_degree); + assert_eq!( + gpu_with_next_ext, cpu_with_next, + "GPU fri_fold mismatch with next_reduced (d={ext_degree}, log_arity={log_arity}, h={height})" + ); + } + } +} + +#[test] +fn cuda_fri_fold_matches_cpu_all_arities_ext2_and_ext3() { + let device = configured_device(); + check_fri_fold_parity::(device, 2, Goldilocks::from_u64(7), 0xF102_0002); + check_fri_fold_parity::(device, 3, Goldilocks::ZERO, 0xF103_0003); +} + +fn check_fri_merkle_parity>( + device: i32, + ext_degree: usize, + seed: u64, +) { + type CpuDomMmcs = MerkleTreeMmcs< + Goldilocks, + u8, + SerializingHasher, + CompressionFunctionFromHasher, + 2, + 32, + >; + + let mut rng = SmallRng::seed_from_u64(seed); + let hiding_mmcs = HidingCudaMmcs::new_v6_zk(0, device); + let hiding_ext_mmcs: ExtensionMmcs = + ExtensionMmcs::new(hiding_mmcs.clone()); + + for log_arity in 1usize..=4 { + let arity = 1usize << log_arity; + for height in [64usize, 4096usize] { + let tree_height = height / arity; + let codeword_ext: Vec = (0..height) + .map(|_| random_ext(&mut rng, ext_degree)) + .collect(); + let codeword_flat = flatten_ext(&codeword_ext, ext_degree); + let codeword_mat = RowMajorMatrix::new(codeword_flat.clone(), ext_degree); + let codeword_gpu = CudaLde::from_row_major_matrix(device, &codeword_mat); + + let query_rows = [0usize, 1, tree_height / 2, 1, tree_height - 1, 0]; + let dims = [Dimensions { + width: arity, + height: tree_height, + }]; + + // Plain (v5) and domain-separated (v6) FRI Merkle trees. + for domain_v6 in [false, true] { + let (leaf_dom, comp_dom) = if domain_v6 { + (Blake3Domain::MerkleLeaf, Blake3Domain::MerkleCompress) + } else { + (Blake3Domain::Plain, Blake3Domain::Plain) + }; + let cpu_base = CpuDomMmcs::new( + SerializingHasher::new(DomainBlake3::new(leaf_dom)), + CompressionFunctionFromHasher::new(DomainBlake3::new(comp_dom)), + 0, + ); + let cpu_ext: ExtensionMmcs = + ExtensionMmcs::new(cpu_base); + let (cpu_commit, cpu_data) = + cpu_ext.commit_matrix(RowMajorMatrix::new(codeword_ext.clone(), arity)); + + let gpu_tree = CudaMixedMerkleTree::from_fri_codeword_with_domain( + &codeword_gpu, + arity, + domain_v6, + ); + assert_eq!( + gpu_tree.root(), + cpu_commit.roots()[0], + "FRI Merkle root mismatch (d={ext_degree}, arity={arity}, h={height}, v6={domain_v6})" + ); + + let (cpu_opened, cpu_proof) = cpu_ext.open_multi_batch(&query_rows, &cpu_data); + let gpu_pruned = gpu_tree.open_pruned_siblings(&query_rows); + assert_eq!( + gpu_pruned.sibling_hashes, cpu_proof.sibling_hashes, + "FRI Merkle pruned proof mismatch (d={ext_degree}, arity={arity}, h={height}, v6={domain_v6})" + ); + + // Gather rows from resident GPU codeword and verify with CPU verifier. + let codeword_rows: Vec = query_rows + .iter() + .flat_map(|&row| (0..arity).map(move |col| row * arity + col)) + .collect(); + let opened_flat = codeword_gpu.rows(&codeword_rows); + let gpu_opened: Vec>> = opened_flat + .chunks_exact(arity) + .map(|rows| { + vec![ + rows.iter() + .map(|r| { + Challenge::from_basis_coefficients_slice(r) + .expect("extension row") + }) + .collect(), + ] + }) + .collect(); + assert_eq!(gpu_opened, cpu_opened); + cpu_ext + .verify_multi_batch(&cpu_commit, &dims, &query_rows, &gpu_opened, &gpu_pruned) + .expect("GPU FRI Merkle multi-batch opening must verify on CPU"); + } + + // Salted v6-zk FRI Merkle tree. + let salt_seed: [u8; 32] = core::array::from_fn(|i| { + u8::try_from((i * 37 + arity + ext_degree) & 0xFF).unwrap() + }); + let flattened_leaves = RowMajorMatrix::new(codeword_flat, arity * ext_degree); + let (cpu_zk_commit, cpu_zk_data) = + hiding_mmcs.commit_cpu_with_seed(vec![flattened_leaves], salt_seed); + let gpu_zk_tree = + CudaMixedMerkleTree::from_fri_codeword_v6zk(&codeword_gpu, arity, &salt_seed); + assert_eq!( + gpu_zk_tree.root(), + cpu_zk_commit.roots()[0], + "v6-zk FRI Merkle root mismatch (d={ext_degree}, arity={arity}, h={height})" + ); + + let round = HidingCudaFriRound { + codeword: CudaLde::from_row_major_matrix(device, &codeword_mat), + tree: gpu_zk_tree, + arity, + salt_seed, + }; + let (gpu_zk_rows, mut gpu_zk_proof) = + hiding_ext_mmcs.open_cuda_fri_hiding_batch(&round, &query_rows); + let (_, cpu_zk_proof) = hiding_mmcs.open_multi_batch(&query_rows, &cpu_zk_data); + assert_eq!( + gpu_zk_proof, cpu_zk_proof, + "v6-zk FRI Merkle multi-proof mismatch (d={ext_degree}, arity={arity}, h={height})" + ); + let wrapped_rows: Vec>> = + gpu_zk_rows.into_iter().map(|r| vec![r]).collect(); + hiding_ext_mmcs + .verify_multi_batch( + &cpu_zk_commit, + &dims, + &query_rows, + &wrapped_rows, + &gpu_zk_proof, + ) + .expect("GPU v6-zk FRI Merkle opening must verify"); + + // Tampered salt must fail verification. + gpu_zk_proof.salts[0][0][0] ^= 1; + assert!( + hiding_ext_mmcs + .verify_multi_batch( + &cpu_zk_commit, + &dims, + &query_rows, + &wrapped_rows, + &gpu_zk_proof, + ) + .is_err(), + "tampered v6-zk FRI leaf salt must fail verification" + ); + } + } +} + +#[test] +fn cuda_fri_merkle_matches_cpu_all_arities_plain_v6_and_v6zk() { + let device = configured_device(); + check_fri_merkle_parity::(device, 2, 0xA117_0002); + check_fri_merkle_parity::(device, 3, 0xA117_0003); +} + +#[allow(clippy::type_complexity, clippy::too_many_arguments)] +fn cpu_reference_open( + mmcs: &CudaMmcs, + fri: &InnerFriParameters>, + batching: FriBatching, + commitments_with_points: &[( + &>::ProverData>, + Vec>, + )], + challenger: &mut ChallengerType, +) -> ( + p3_commit::OpenedValues, + p3_fri::FriProof< + Challenge, + ExtensionMmcs, + Goldilocks, + Vec>, + >, +) +where + Challenge: ExtensionField, + ChallengerType: p3_challenger::FieldChallenger + + p3_challenger::GrindingChallenger + + p3_challenger::CanObserve>, +{ + let mats_and_points: Vec<_> = commitments_with_points + .iter() + .map(|(data, points)| { + let mats = mmcs + .get_matrices(data) + .into_iter() + .map(|m| m.as_view()) + .collect::>(); + (mats, points) + }) + .collect(); + let global_max_height = mats_and_points + .iter() + .flat_map(|(mats, _)| mats.iter().map(Matrix::height)) + .max() + .unwrap(); + let log_global_max_height = log2_strict_usize(global_max_height); + + let mut opened_max_width = 0usize; + let mut openings_per_height = [0usize; 33]; + for (mats, points) in &mats_and_points { + for (mat, pts) in mats.iter().zip(points.iter()) { + if !pts.is_empty() { + opened_max_width = opened_max_width.max(mat.width()); + openings_per_height[log2_strict_usize(mat.height())] += pts.len(); + } + } + } + let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); + + let mut coset: Vec = + TwoAdicMultiplicativeCoset::new(Goldilocks::GENERATOR, log_global_max_height) + .unwrap() + .iter() + .collect(); + reverse_slice_index_bits(&mut coset); + + let mut max_log: LinearMap = LinearMap::new(); + for (mats, points) in &mats_and_points { + for (mat, pts) in mats.iter().zip(points.iter()) { + let lh = log2_strict_usize(mat.height()); + for &z in pts { + if let Some(cur) = max_log.get_mut(&z) { + *cur = (*cur).max(lh); + } else { + max_log.insert(z, lh); + } + } + } + } + let inv_denoms: LinearMap> = max_log + .into_iter() + .map(|(z, lh)| { + let diffs: Vec = coset[..(1usize << lh)].iter().map(|&x| z - x).collect(); + (z, batch_multiplicative_inverse(&diffs)) + }) + .collect(); + let adjusted_weights: LinearMap> = inv_denoms + .iter() + .map(|(point, denoms)| (*point, compute_adjusted_weights(*point, denoms))) + .collect(); + + let all_opened_values: p3_commit::OpenedValues = mats_and_points + .iter() + .map(|(mats, points)| { + mats.iter() + .zip(points.iter()) + .map(|(mat, pts)| { + let h = mat.height() >> fri.log_blowup; + let (low_coset, _) = mat.split_rows(h); + pts.iter() + .map(|&point| { + let adjusted = &adjusted_weights.get(&point).unwrap()[..h]; + let ys = low_coset.interpolate_coset_with_precomputation( + Goldilocks::GENERATOR, + point, + adjusted, + ); + challenger.observe_algebra_slice(&ys); + ys + }) + .collect() + }) + .collect() + }) + .collect(); + + let schedule = FriBatchingSchedule::::sample( + batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let packed_col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + Challenge::ExtensionPacking::packed_ext_powers_capped(*alpha, opened_max_width) + .collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => { + pack_ext_weights::(col_weights) + } + }; + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => alpha.powers().take(opened_max_width).collect(), + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; + + let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; + let mut reduced_openings: [Option>; 33] = core::array::from_fn(|_| None); + for ((mats, points), openings_round) in mats_and_points.iter().zip(&all_opened_values) { + for ((mat, pts), openings_mat) in mats.iter().zip(points.iter()).zip(openings_round.iter()) + { + if pts.is_empty() { + continue; + } + let lh = log2_strict_usize(mat.height()); + let target = + reduced_openings[lh].get_or_insert_with(|| vec![Challenge::ZERO; mat.height()]); + let compressed: Vec = mat + .rowwise_packed_dot_product::(&packed_col_weights) + .collect(); + for (&point, ys) in pts.iter().zip(openings_mat.iter()) { + let offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => alpha.exp_u64( + u64::try_from(num_reduced[lh]).expect("reduced width exceeds u64"), + ), + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[lh]] + } + }; + let reduced_y: Challenge = + dot_product(col_weights.iter().copied(), ys.iter().copied()); + let denoms = inv_denoms.get(&point).unwrap(); + for ((&row_val, out), &inv_d) in + compressed.iter().zip(target.iter_mut()).zip(denoms) + { + *out += offset * (reduced_y - row_val) * inv_d; + } + num_reduced[lh] += mat.width(); + opening_idx_by_height[lh] += 1; + } + } + } + + let fri_input: Vec> = reduced_openings.into_iter().rev().flatten().collect(); + let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); + let fri_proof = prover::prove_fri( + &folding, + fri, + fri_input, + challenger, + log_global_max_height, + commitments_with_points, + mmcs, + ); + (all_opened_values, fri_proof) +} + +#[allow(clippy::too_many_arguments)] +fn check_pcs_open_cpu_gpu_parity( + device: i32, + domain_v6: bool, + batching: FriBatching, + log_blowup: usize, + log_final_poly_len: usize, + max_log_arity: usize, + trace_shapes: &[(usize, usize)], + make_challenger: impl Fn() -> ChallengerType, + ext_degree: usize, + seed: u64, +) where + Challenge: ExtensionField, + ChallengerType: p3_challenger::FieldChallenger + + p3_challenger::GrindingChallenger + + p3_challenger::CanObserve> + + Clone, +{ + let dft = CudaDft::new(device); + let mmcs = if domain_v6 { + CudaMmcs::new_v6(0, device) + } else { + CudaMmcs::new_plain(0, device) + }; + let fri_mmcs: ExtensionMmcs = ExtensionMmcs::new(mmcs.clone()); + let fri_params = InnerFriParameters { + log_blowup, + log_final_poly_len, + max_log_arity, + num_queries: 16, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + mmcs: fri_mmcs, + }; + let pcs = CudaTwoAdicFriPcs::::new(dft, mmcs.clone(), fri_params.clone()) + .with_batching(batching); + + let mut rng = SmallRng::seed_from_u64(seed); + let max_lde_height = trace_shapes + .iter() + .map(|&(h, _)| h << log_blowup) + .max() + .unwrap(); + let final_fri_height = (1usize << log_blowup) * (1usize << log_final_poly_len); + assert!( + max_lde_height > 1024 && max_lde_height > final_fri_height, + "test must trigger resident CUDA FRI path (max_lde_height={max_lde_height}, final={final_fri_height})" + ); + + let domains_and_mats: Vec<( + TwoAdicMultiplicativeCoset, + RowMajorMatrix, + )> = trace_shapes + .iter() + .map(|&(height, width)| { + let domain = + TwoAdicMultiplicativeCoset::new(Goldilocks::ONE, log2_strict_usize(height)) + .unwrap(); + let mat = RowMajorMatrix::new( + (0..height * width) + .map(|_| rng.random::()) + .collect(), + width, + ); + (domain, mat) + }) + .collect(); + + let (commitment, prover_data) = + Pcs::::commit(&pcs, domains_and_mats); + + let zeta: Challenge = random_ext(&mut rng, ext_degree); + let points_per_mat: Vec> = trace_shapes + .iter() + .map(|&(height, _)| { + let g = Goldilocks::two_adic_generator(log2_strict_usize(height)); + vec![zeta, zeta * g] + }) + .collect(); + + let mut gpu_challenger = make_challenger(); + let mut cpu_challenger = gpu_challenger.clone(); + let mut ver_challenger = gpu_challenger.clone(); + + let (gpu_opened, gpu_proof) = pcs.open( + vec![(&prover_data, points_per_mat.clone())], + &mut gpu_challenger, + ); + let (cpu_opened, cpu_proof) = cpu_reference_open( + &mmcs, + &fri_params, + batching, + &[(&prover_data, points_per_mat.clone())], + &mut cpu_challenger, + ); + + // Exact parity on opened values, commits, final poly, arities, siblings, and Merkle proofs. + assert_eq!(gpu_opened, cpu_opened, "opened values mismatch"); + assert_eq!( + gpu_proof.commit_phase_commits, cpu_proof.commit_phase_commits, + "FRI commit_phase_commits mismatch" + ); + assert_eq!( + gpu_proof.final_poly, cpu_proof.final_poly, + "FRI final_poly mismatch" + ); + assert_eq!( + gpu_proof.commit_pow_witnesses, cpu_proof.commit_pow_witnesses, + "FRI commit PoW mismatch" + ); + assert_eq!( + gpu_proof.query_pow_witness, cpu_proof.query_pow_witness, + "FRI query PoW mismatch" + ); + assert_eq!( + gpu_proof.commit_phase_openings.len(), + cpu_proof.commit_phase_openings.len(), + "FRI round count mismatch" + ); + for (round_idx, (gpu_step, cpu_step)) in gpu_proof + .commit_phase_openings + .iter() + .zip(&cpu_proof.commit_phase_openings) + .enumerate() + { + assert_eq!( + gpu_step.log_arity, cpu_step.log_arity, + "round {round_idx} log_arity mismatch" + ); + assert_eq!( + gpu_step.sibling_values, cpu_step.sibling_values, + "round {round_idx} sibling_values mismatch" + ); + assert_eq!( + gpu_step.opening_proof.sibling_hashes, cpu_step.opening_proof.sibling_hashes, + "round {round_idx} Merkle sibling_hashes mismatch" + ); + } + assert_eq!( + gpu_proof.input_openings.len(), + cpu_proof.input_openings.len() + ); + for (gpu_in, cpu_in) in gpu_proof + .input_openings + .iter() + .zip(&cpu_proof.input_openings) + { + assert_eq!(gpu_in.opened_values, cpu_in.opened_values); + assert_eq!( + gpu_in.opening_proof.sibling_hashes, + cpu_in.opening_proof.sibling_hashes + ); + } + + // Confirm CPU verifier accepts the GPU proof. + type OpenedMatrix = (TwoAdicMultiplicativeCoset, Vec<(C, Vec)>); + let verify_mats: Vec> = trace_shapes + .iter() + .zip(&points_per_mat) + .zip(&gpu_opened[0]) + .map(|((&(height, _), pts), vals)| { + let domain = + TwoAdicMultiplicativeCoset::new(Goldilocks::ONE, log2_strict_usize(height)) + .unwrap(); + let pairs = pts.iter().copied().zip(vals.iter().cloned()).collect(); + (domain, pairs) + }) + .collect(); + for (_, vals) in &verify_mats { + for (_, evals) in vals { + p3_challenger::FieldChallenger::observe_algebra_slice( + &mut ver_challenger, + evals.as_slice(), + ); + } + } + let folding: TwoAdicFriFoldingForMmcs = TwoAdicFriFolding(PhantomData); + verify_fri_with_batching( + &folding, + &fri_params, + &gpu_proof, + &mut ver_challenger, + &[(commitment, verify_mats)], + &mmcs, + batching, + ) + .expect("CPU verifier must accept GPU multi-arity FRI proof"); +} + +#[test] +fn cuda_pcs_open_multi_arity_matches_cpu_prove_fri_v5_and_v6() { + let device = configured_device(); + let v6_challenger = || { + DomainChallenger::::from_domain( + b"fri-arity-v6-test".to_vec(), + Blake3Domain::TranscriptSingle, + ) + }; + let v5_challenger = + || Challenger::from_hasher(b"fri-arity-v5-test".to_vec(), p3_blake3::Blake3); + + // v6 (Ext3): uniform and mixed heights across max_log_arity in 1..=4, log_final_poly_len in {0, 6, 8}. + for max_log_arity in [1usize, 2, 3, 4] { + for log_final_poly_len in [0usize, 6, 8] { + for batching in [FriBatching::Tensor, FriBatching::Horner] { + // Uniform height: 2^12 trace -> 2^14 LDE (> 1024 and >= 2^14 so arity=4 hits full fold even with log_final=8). + check_pcs_open_cpu_gpu_parity::( + device, + true, + batching, + 2, + log_final_poly_len, + max_log_arity, + &[(4096, 5)], + v6_challenger, + 3, + 0x6000 + u64::try_from(max_log_arity * 100 + log_final_poly_len * 10).unwrap(), + ); + // Mixed heights: 2^12, 2^10, 2^9 traces -> 2^14, 2^12, 2^11 LDEs (forces mixed log_arity steps!). + check_pcs_open_cpu_gpu_parity::( + device, + true, + batching, + 2, + log_final_poly_len, + max_log_arity, + &[(4096, 3), (1024, 4), (512, 2)], + v6_challenger, + 3, + 0x7000 + u64::try_from(max_log_arity * 100 + log_final_poly_len * 10).unwrap(), + ); + } + } + } + + // v5 (Ext2): uniform and mixed heights at max_log_arity = 2, 3. + for max_log_arity in [2usize, 3] { + for log_final_poly_len in [0usize, 6] { + check_pcs_open_cpu_gpu_parity::( + device, + false, + FriBatching::Horner, + 2, + log_final_poly_len, + max_log_arity, + &[(1024, 5)], + v5_challenger, + 2, + 0x5000 + u64::try_from(max_log_arity * 100 + log_final_poly_len * 10).unwrap(), + ); + check_pcs_open_cpu_gpu_parity::( + device, + false, + FriBatching::Horner, + 2, + log_final_poly_len, + max_log_arity, + &[(4096, 3), (1024, 4), (512, 2)], + v5_challenger, + 2, + 0x5500 + u64::try_from(max_log_arity * 100 + log_final_poly_len * 10).unwrap(), + ); + } + } +} + +fn single_circuit_cubic_inputs() -> Vec> { + let a = Expr::main(0); + let b = Expr::main(1); + let target = Expr::main(2); + let a3 = Expr::main(3); + let mult = Expr::main(4); + let target_next = Expr::main_next(2); + vec![CircuitInputs { + main_width: 5, + preprocessed: None, + constraints: vec![ + a.clone() + b - target.clone(), + a.clone() * a.clone() * a - a3, + Expr::IsTransition * (target_next - target.clone()), + ], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + mult, + vec![Expr::constant(Val::from_u32(77)), target], + )], + lookup_group_size: 1, + }] +} + +fn single_circuit_cubic_witness( + rows: usize, + target: u32, + seed: u32, +) -> (Vec>, Vec>) { + let mut values = Vec::with_capacity(rows * 5); + for r in 0..rows { + let a_u = seed.wrapping_add(u32::try_from(r).unwrap().wrapping_mul(17)) % target; + let b_u = target - a_u; + let a = Val::from_u32(a_u); + let b = Val::from_u32(b_u); + let t = Val::from_u32(target); + let a3 = a * a * a; + let mult = if r == 0 { Val::ONE } else { Val::ZERO }; + values.extend([a, b, t, a3, mult]); + } + ( + vec![RowMajorMatrix::new(values, 5)], + vec![vec![Val::from_u32(77), Val::from_u32(target)]], + ) +} + +fn mismatched_height_system_inputs(rom_rows: usize) -> Vec> { + let rom_prep = RowMajorMatrix::new( + (0..u32::try_from(rom_rows).unwrap()) + .map(Val::from_u32) + .collect(), + 1, + ); + let rom_circuit = CircuitInputs { + main_width: 1, + preprocessed: Some(rom_prep), + constraints: vec![], + ext_constraints: vec![], + lookups: vec![Lookup::pull( + Expr::main(0), + vec![Expr::constant(Val::from_u32(10)), Expr::preprocessed(0)], + )], + lookup_group_size: 1, + }; + + let a = Expr::main(0); + let b = Expr::main(1); + let sum = Expr::main(2); + let mult = Expr::main(3); + let work_circuit = CircuitInputs { + main_width: 4, + preprocessed: None, + constraints: vec![sum.clone() - (a.clone() + b.clone())], + ext_constraints: vec![], + lookups: vec![ + Lookup::push( + Expr::constant(Val::ONE), + vec![Expr::constant(Val::from_u32(10)), a], + ), + Lookup::push( + Expr::constant(Val::ONE), + vec![Expr::constant(Val::from_u32(10)), b], + ), + Lookup::pull(mult, vec![Expr::constant(Val::from_u32(20)), sum]), + ], + lookup_group_size: 2, + }; + + let sq_circuit = CircuitInputs { + main_width: 2, + preprocessed: None, + constraints: vec![Expr::main(0) * Expr::main(0) - Expr::main(1)], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }; + + vec![rom_circuit, work_circuit, sq_circuit] +} + +fn mismatched_height_system_witness( + rom_rows: usize, + work_rows: usize, + sq_rows: usize, +) -> (Vec>, Vec>) { + let mask = u32::try_from(rom_rows - 1).unwrap(); + let mut rom_mults = vec![0u32; rom_rows]; + let mut work_vals = Vec::with_capacity(work_rows * 4); + let mut claims = Vec::new(); + for r in 0..work_rows { + let r32 = u32::try_from(r).unwrap(); + let a = (r32.wrapping_mul(13) + 7) & mask; + let b = (r32.wrapping_mul(29) + 19) & mask; + let sum = a + b; + let mult = u32::from(r == 0); + if mult == 1 { + claims.push(vec![Val::from_u32(20), Val::from_u32(sum)]); + } + rom_mults[usize::try_from(a).unwrap()] += 1; + rom_mults[usize::try_from(b).unwrap()] += 1; + work_vals.extend([ + Val::from_u32(a), + Val::from_u32(b), + Val::from_u32(sum), + Val::from_u32(mult), + ]); + } + let rom_trace = RowMajorMatrix::new(rom_mults.into_iter().map(Val::from_u32).collect(), 1); + let work_trace = RowMajorMatrix::new(work_vals, 4); + let sq_trace = RowMajorMatrix::new( + (0..u32::try_from(sq_rows).unwrap()) + .flat_map(|i| { + let x = Val::from_u32(i + 3); + [x, x * x] + }) + .collect(), + 2, + ); + (vec![rom_trace, work_trace, sq_trace], claims) +} + +#[test] +fn cuda_full_system_multi_arity_v6_and_v5() { + let device = configured_device(); + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + + // v6 (Ext3): single-circuit uniform & multi-circuit mismatched heights across + // max_log_arity in 1..=4 and log_final_poly_len in {0, 6, 8}. + for max_log_arity in [1usize, 2, 3, 4] { + for log_final_poly_len in [0usize, 6, 8] { + let fri = FriParameters { + log_final_poly_len, + max_log_arity, + num_queries: 20, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + + // 1. Single-circuit uniform height (2^12 trace -> 2^14 LDE > 1024 and >= 2^14 so arity=4 hits full fold even with log_final=8). + let (sys, key) = System::new( + GoldilocksBlake3V6Config::with_device(comm, fri, FriBatching::Tensor, Some(device)), + single_circuit_cubic_inputs(), + ); + let (traces, claims) = single_circuit_cubic_witness(4096, 500, 11); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let proof = sys.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces.clone(), &sys), + ); + sys.verify_multiple_claims(&claim_refs, &proof) + .unwrap_or_else(|e| { + panic!("v6 single-circuit verify failed (arity={max_log_arity}, final={log_final_poly_len}): {e:?}") + }); + let arities: Vec = proof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + assert!( + arities.contains(&max_log_arity), + "expected log_arity={max_log_arity} in {arities:?}" + ); + let bytes = proof.to_bytes().unwrap(); + let decoded = Proof::::from_bytes(&bytes).unwrap(); + sys.verify_multiple_claims(&claim_refs, &decoded).unwrap(); + + // 2. Multi-circuit mismatched heights: rom=512 (LDE 2048), work=4096 (LDE 16384), sq=1024 (LDE 4096). + let (msys, mkey) = System::new( + GoldilocksBlake3V6Config::with_device(comm, fri, FriBatching::Tensor, Some(device)), + mismatched_height_system_inputs(512), + ); + let (mtraces, mclaims) = mismatched_height_system_witness(512, 4096, 1024); + let mclaim_refs: Vec<&[Val]> = mclaims.iter().map(Vec::as_slice).collect(); + let mproof = msys.prove_multiple_claims( + &mkey, + &mclaim_refs, + SystemWitness::from_stage_1(mtraces, &msys), + ); + msys.verify_multiple_claims(&mclaim_refs, &mproof) + .unwrap_or_else(|e| { + panic!("v6 multi-circuit verify failed (arity={max_log_arity}, final={log_final_poly_len}): {e:?}") + }); + let marities: Vec = mproof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + if max_log_arity >= 3 { + // Heights are 2^14, 2^12, 2^11 => steps between injections are 2 and 1, + // then folding down from 2^11 uses max_log_arity when final_height permits! + assert!( + marities.contains(&1) && marities.contains(&2), + "expected mixed arities for mismatched heights, got {marities:?}" + ); + } + } + } + + // v5 (Ext2): single-circuit and multi-circuit at max_log_arity = 2, 3. + for max_log_arity in [2usize, 3] { + for log_final_poly_len in [0usize, 6] { + let fri = FriParameters { + log_final_poly_len, + max_log_arity, + num_queries: 20, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let (sys, key) = System::new( + GoldilocksBlake3Config::with_device(comm, fri, Some(device)), + single_circuit_cubic_inputs(), + ); + let (traces, claims) = single_circuit_cubic_witness(1024, 500, 17); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let proof = sys.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces, &sys), + ); + sys.verify_multiple_claims(&claim_refs, &proof) + .unwrap_or_else(|e| { + panic!("v5 single-circuit verify failed (arity={max_log_arity}, final={log_final_poly_len}): {e:?}") + }); + + let (msys, mkey) = System::new( + GoldilocksBlake3Config::with_device(comm, fri, Some(device)), + mismatched_height_system_inputs(512), + ); + let (mtraces, mclaims) = mismatched_height_system_witness(512, 2048, 1024); + let mclaim_refs: Vec<&[Val]> = mclaims.iter().map(Vec::as_slice).collect(); + let mproof = msys.prove_multiple_claims( + &mkey, + &mclaim_refs, + SystemWitness::from_stage_1(mtraces, &msys), + ); + msys.verify_multiple_claims(&mclaim_refs, &mproof) + .unwrap_or_else(|e| { + panic!("v5 multi-circuit verify failed (arity={max_log_arity}, final={log_final_poly_len}): {e:?}") + }); + } + } +} + +#[test] +fn cuda_full_system_multi_arity_v6_zk() { + let device = configured_device(); + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + + for max_log_arity in [1usize, 2, 3, 4] { + for log_final_poly_len in [0usize, 6, 8] { + let fri = FriParameters { + log_final_poly_len, + max_log_arity, + num_queries: 24, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + + // 1. Single-circuit uniform height: rows = 2048 -> ZK LDE height = 2 * 2048 * 4 = 16384 (2^14 > 1024). + let (sys, key) = System::new( + GoldilocksBlake3V6ZkConfig::with_device( + comm, + fri, + FriBatching::Tensor, + Some(device), + ), + single_circuit_cubic_inputs(), + ); + let (traces, claims) = single_circuit_cubic_witness(2048, 500, 19); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + let proof = sys.prove_multiple_claims( + &key, + &claim_refs, + SystemWitness::from_stage_1(traces, &sys), + ); + sys.verify_multiple_claims(&claim_refs, &proof) + .unwrap_or_else(|e| { + panic!("v6-zk single-circuit verify failed (arity={max_log_arity}, final={log_final_poly_len}): {e:?}") + }); + let arities: Vec = proof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + assert!( + arities.contains(&max_log_arity), + "v6-zk expected log_arity={max_log_arity} in {arities:?}" + ); + + // Serialization roundtrip + tamper checks. + let bytes = proof.to_bytes().unwrap(); + let decoded = Proof::::from_bytes(&bytes).unwrap(); + sys.verify_multiple_claims(&claim_refs, &decoded).unwrap(); + + if max_log_arity == 3 && log_final_poly_len == 8 { + let mut bad_sibling = decoded.clone(); + bad_sibling.opening_proof.commit_phase_openings[0].sibling_values[0][0] += + ExtVal3::ONE; + assert!( + sys.verify_multiple_claims(&claim_refs, &bad_sibling) + .is_err(), + "tampered v6-zk FRI sibling must fail verification" + ); + let mut bad_salt = decoded; + bad_salt.opening_proof.commit_phase_openings[0] + .opening_proof + .salts[0][0][0] ^= 1; + assert!( + sys.verify_multiple_claims(&claim_refs, &bad_salt).is_err(), + "tampered v6-zk FRI leaf salt must fail verification" + ); + } + + // 2. Multi-circuit mismatched heights: rom=256 (LDE 2048), work=2048 (LDE 16384), sq=512 (LDE 4096). + // All ZK LDE heights > 2^(8+2) = 1024! + let (msys, mkey) = System::new( + GoldilocksBlake3V6ZkConfig::with_device( + comm, + fri, + FriBatching::Tensor, + Some(device), + ), + mismatched_height_system_inputs(256), + ); + let (mtraces, mclaims) = mismatched_height_system_witness(256, 2048, 512); + let mclaim_refs: Vec<&[Val]> = mclaims.iter().map(Vec::as_slice).collect(); + let mproof = msys.prove_multiple_claims( + &mkey, + &mclaim_refs, + SystemWitness::from_stage_1(mtraces, &msys), + ); + msys.verify_multiple_claims(&mclaim_refs, &mproof) + .unwrap_or_else(|e| { + panic!("v6-zk multi-circuit verify failed (arity={max_log_arity}, final={log_final_poly_len}): {e:?}") + }); + let marities: Vec = mproof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + if max_log_arity >= 3 { + assert!( + marities.contains(&1) && marities.contains(&2), + "v6-zk expected mixed arities for mismatched heights, got {marities:?}" + ); + } + } + } +} + +#[test] +#[ignore = "live GPU timing smoke test for 2^20 and 2^22 single-circuit v6 & v6-zk max_log_arity=3"] +fn cuda_smoke_timing_v6_and_v6zk_arity3() { + let device = configured_device(); + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + let fri = FriParameters { + log_final_poly_len: 8, + max_log_arity: 3, + num_queries: 64, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + + for &log_rows in &[20usize, 22usize] { + let rows = 1usize << log_rows; + let (traces, claims) = single_circuit_cubic_witness(rows, 500, 11); + let claim_refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); + + // v6 (Ext3) + let (sys_v6, key_v6) = System::new( + GoldilocksBlake3V6Config::with_device(comm, fri, FriBatching::Tensor, Some(device)), + single_circuit_cubic_inputs(), + ); + let w_v6 = SystemWitness::from_stage_1(traces.clone(), &sys_v6); + let t0 = Instant::now(); + let proof_v6 = sys_v6.prove_multiple_claims(&key_v6, &claim_refs, w_v6); + let prove_v6 = t0.elapsed(); + let t1 = Instant::now(); + sys_v6 + .verify_multiple_claims(&claim_refs, &proof_v6) + .expect("v6 smoke proof must verify"); + let verify_v6 = t1.elapsed(); + let bytes_v6 = proof_v6.to_bytes().unwrap().len(); + let arities_v6: Vec = proof_v6 + .opening_proof + .commit_phase_openings + .iter() + .map(|s| s.log_arity) + .collect(); + eprintln!( + "[RTX PRO 6000] v6 2^{log_rows} (max_log_arity=3, log_final=8, q=64): prove={:.3}s verify={:.3}ms bytes={} arities={arities_v6:?}", + prove_v6.as_secs_f64(), + verify_v6.as_secs_f64() * 1e3, + bytes_v6, + ); + + // v6-zk (Ext3 hiding) + let (sys_zk, key_zk) = System::new( + GoldilocksBlake3V6ZkConfig::with_device(comm, fri, FriBatching::Tensor, Some(device)), + single_circuit_cubic_inputs(), + ); + let w_zk = SystemWitness::from_stage_1(traces, &sys_zk); + let t2 = Instant::now(); + let proof_zk = sys_zk.prove_multiple_claims(&key_zk, &claim_refs, w_zk); + let prove_zk = t2.elapsed(); + let t3 = Instant::now(); + sys_zk + .verify_multiple_claims(&claim_refs, &proof_zk) + .expect("v6-zk smoke proof must verify"); + let verify_zk = t3.elapsed(); + let bytes_zk = proof_zk.to_bytes().unwrap().len(); + let arities_zk: Vec = proof_zk + .opening_proof + .commit_phase_openings + .iter() + .map(|s| s.log_arity) + .collect(); + eprintln!( + "[RTX PRO 6000] v6-zk 2^{log_rows} (max_log_arity=3, log_final=8, q=64): prove={:.3}s verify={:.3}ms bytes={} arities={arities_zk:?}", + prove_zk.as_secs_f64(), + verify_zk.as_secs_f64() * 1e3, + bytes_zk, + ); + } +} diff --git a/src/types.rs b/src/types.rs index 12db085..b1d4798 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1041,8 +1041,9 @@ impl GoldilocksBlake3Config { "the CUDA backend currently supports only cap_height = 0" ); assert!( - fri_parameters.max_log_arity <= 1, - "the CUDA backend currently supports only binary FRI folds" + (1..=10).contains(&fri_parameters.max_log_arity), + "the CUDA backend requires 1 <= max_log_arity <= 10 (got {})", + fri_parameters.max_log_arity ); } #[cfg(feature = "cuda")] @@ -1860,8 +1861,9 @@ where "the CUDA backend currently supports only cap_height = 0" ); assert!( - fri_parameters.max_log_arity <= 1, - "the CUDA backend currently supports only binary FRI folds" + (1..=10).contains(&fri_parameters.max_log_arity), + "the CUDA backend requires 1 <= max_log_arity <= 10 (got {})", + fri_parameters.max_log_arity ); } #[cfg(not(feature = "cuda"))] @@ -2668,8 +2670,9 @@ where "the CUDA backend currently supports only cap_height = 0" ); assert!( - fri_parameters.max_log_arity <= 1, - "the CUDA backend currently supports only binary FRI folds" + (1..=10).contains(&fri_parameters.max_log_arity), + "the CUDA backend requires 1 <= max_log_arity <= 10 (got {})", + fri_parameters.max_log_arity ); } #[cfg(not(feature = "cuda"))] @@ -3471,17 +3474,45 @@ mod pcs_ref_gen { #[cfg(feature = "cuda")] #[test] - #[should_panic(expected = "binary FRI folds")] - fn cuda_rejects_multi_bit_fri_folds() { + #[should_panic(expected = "1 <= max_log_arity <= 10")] + fn cuda_rejects_zero_fri_arity() { let _ = GoldilocksBlake3Config::new( CommitmentParameters { log_blowup: 1, cap_height: 0, }, - test_fri_parameters(2), + test_fri_parameters(0), ); } + #[cfg(feature = "cuda")] + #[test] + #[should_panic(expected = "1 <= max_log_arity <= 10")] + fn cuda_rejects_excessive_fri_arity() { + let _ = GoldilocksBlake3V6Config::new( + CommitmentParameters { + log_blowup: 1, + cap_height: 0, + }, + test_fri_parameters(11), + ); + } + + #[cfg(feature = "cuda")] + #[test] + fn cuda_accepts_multi_bit_fri_folds() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + for max_log_arity in 1..=4 { + let fri = test_fri_parameters(max_log_arity); + let _ = GoldilocksBlake3Config::new(comm, fri); + let _ = GoldilocksBlake3V6Config::new(comm, fri); + let _ = GoldilocksBlake3V6ZkConfig::new(comm, fri); + } + } + fn limbs(d: [u8; 32]) -> [u64; 4] { core::array::from_fn(|i| u64::from_le_bytes(d[i * 8..i * 8 + 8].try_into().unwrap())) } diff --git a/tests/fp3_v6.rs b/tests/fp3_v6.rs index 793af16..2753ea4 100644 --- a/tests/fp3_v6.rs +++ b/tests/fp3_v6.rs @@ -319,11 +319,7 @@ fn fp3_v6_single_proof_matrix() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: if cfg!(feature = "cuda") { - 1 - } else { - max_log_arity - }, + max_log_arity, num_queries: 12, commit_proof_of_work_bits: pow_bits, query_proof_of_work_bits: pow_bits, @@ -387,7 +383,7 @@ fn fp3_v6_plonkish_proof_with_blake3_gadget() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + max_log_arity: 2, num_queries: 12, commit_proof_of_work_bits: 0, query_proof_of_work_bits: 0, @@ -432,7 +428,7 @@ fn fp3_v6_batch_proof_retain_regenerate_and_messages() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + max_log_arity: 2, num_queries: 10, commit_proof_of_work_bits: 2, query_proof_of_work_bits: 2, @@ -590,7 +586,7 @@ fn fp3_v6_streaming_and_disk_spill_byte_identical() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + max_log_arity: 2, num_queries: 10, commit_proof_of_work_bits: 2, query_proof_of_work_bits: 2, @@ -890,7 +886,7 @@ fn v6_fp3_canonical_deserialization_and_tamper_rejection() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + max_log_arity: 2, num_queries: 10, commit_proof_of_work_bits: 0, query_proof_of_work_bits: 0, @@ -1048,7 +1044,7 @@ fn bench_fp2_vs_fp3_cpu() { }; let fri = FriParameters { log_final_poly_len: 0, - max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + max_log_arity: 2, num_queries: 64, commit_proof_of_work_bits: 0, query_proof_of_work_bits: 0, @@ -1487,7 +1483,7 @@ fn v6_fp3_large_lde_above_1024_rows_roundtrip() { }; let fri = FriParameters { log_final_poly_len: 1, - max_log_arity: if cfg!(feature = "cuda") { 1 } else { 2 }, + max_log_arity: 2, num_queries: 24, commit_proof_of_work_bits: 0, query_proof_of_work_bits: 0, @@ -1525,3 +1521,180 @@ fn v6_fp3_large_lde_above_1024_rows_roundtrip() { ); } } + +/// Multi-arity FRI (`max_log_arity = 2, 3, 4`) + `log_final_poly_len = 8` on +/// both single-circuit uniform and multi-circuit mismatched heights above 1024 +/// LDE rows (exercises CUDA resident multi-ary folding on GPU builds and CPU +/// folding on CPU builds). +#[test] +fn v6_fp3_multi_arity_and_final_poly_roundtrip() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + + // Single-circuit 4096-row cubic AIR (LDE height = 16384 = 2^14 > 1024). + let single_inputs = vec![CircuitInputs { + main_width: 3, + preprocessed: None, + constraints: vec![ + Expr::main(0) * Expr::main(0) * Expr::main(0) - Expr::main(1), + Expr::main(0) + Expr::main(1) - Expr::main(2), + ], + ext_constraints: vec![], + lookups: vec![], + lookup_group_size: 1, + }]; + let single_trace = RowMajorMatrix::new( + (0..4096u32) + .flat_map(|i| { + let x = f(i + 5); + let x3 = x * x * x; + [x, x3, x + x3] + }) + .collect(), + 3, + ); + + // Multi-circuit mismatched heights: 256-row byte ROM (LDE 1024) + 2048-row u32_add (LDE 8192). + // For `log_final_poly_len = 6` (`final = 256 < 1024`) this hits mixed arities. + let multi_inputs = u32_add_system_inputs(4); + let (multi_traces, multi_claims) = u32_add_witness(2048); + let multi_claim_refs: Vec<&[Val]> = multi_claims.iter().map(Vec::as_slice).collect(); + + let v6_pins = [ + ( + 2usize, + "086737873d2f8ae34d0a32422cbf40142eeb263ac8501c001b564ca50b6a27a5", + "d237e09c7e37281163e3d3c0b241f14c90827bf93dbc0ede1b4d1749696fbced", + ), + ( + 3, + "3c2ee68b168628fcfd32151e4cf34558c77f37c994ef8c89b8f2b9ba42ea03fe", + "30f612a81fdae48acaa04a722b2f68e0b8ff65da5f796c04544237f2b639022f", + ), + ( + 4, + "58b29e8066350a58a04a22fc68bf9dcd8ceb705cc7ba1afa7258b0a900c2ac9b", + "b6a1446af46cdbb95741da5ef0be85c9a3aef7d4cbb9063c1e7edcca31ebc047", + ), + ]; + + for (max_log_arity, expected_uniform_pin, expected_mixed_pin) in v6_pins { + // Uniform single circuit with `log_final_poly_len = 8` (final height = 1024 < 16384). + let fri_uniform = FriParameters { + log_final_poly_len: 8, + max_log_arity, + num_queries: 20, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let (sys, key) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri_uniform, FriBatching::Tensor), + single_inputs.clone(), + ); + let proof = sys.prove_multiple_claims( + &key, + &[], + SystemWitness::from_stage_1(vec![single_trace.clone()], &sys), + ); + sys.verify_multiple_claims(&[], &proof).unwrap(); + let arities: Vec = proof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + assert!( + arities.contains(&max_log_arity), + "uniform v6 expected log_arity={max_log_arity} in {arities:?}" + ); + assert_eq!( + blake3::hash(&proof.to_bytes().unwrap()).to_hex().as_str(), + expected_uniform_pin, + "v6 uniform proof bytes drifted from CPU/GPU pin (max_log_arity={max_log_arity})" + ); + + // Multi-circuit mismatched heights with `log_final_poly_len = 6` (final height = 256 < 1024). + let fri_mixed = FriParameters { + log_final_poly_len: 6, + max_log_arity, + num_queries: 20, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let (msys, mkey) = System::new( + GoldilocksBlake3V6Config::new_with_batching(comm, fri_mixed, FriBatching::Tensor), + multi_inputs.clone(), + ); + let mproof = msys.prove_multiple_claims( + &mkey, + &multi_claim_refs, + SystemWitness::from_stage_1(multi_traces.clone(), &msys), + ); + msys.verify_multiple_claims(&multi_claim_refs, &mproof) + .unwrap(); + assert_eq!( + blake3::hash(&mproof.to_bytes().unwrap()).to_hex().as_str(), + expected_mixed_pin, + "v6 mixed proof bytes drifted from CPU/GPU pin (max_log_arity={max_log_arity})" + ); + } + + // v5 (Ext2): uniform (LDE 16384) and multi-circuit mismatched heights (LDE 1024 & 8192) + // at max_log_arity = 2, 3 (cross-backend byte-identical pins). + let v5_pins = [ + ( + 2usize, + "aade459d9f7323e51fbc8754b9efa59d76b33639375e4a86832369a4f699ac23", + "92eef3aa6c33dea9fb81728cb06bf8bcfd89c2e69c5c5ef1d4c13dabefc54ff1", + ), + ( + 3, + "6011dced08818b9a22c306bb1cd936d566ff9d73fc135f78479644a913fe096b", + "a2613d86c4f72788df9b47a3bfcdcac20f5e0941b509004e512457747c2477af", + ), + ]; + for (max_log_arity, expected_uniform_pin, expected_mixed_pin) in v5_pins { + let fri_u = FriParameters { + log_final_poly_len: 6, + max_log_arity, + num_queries: 20, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + let (sys5, key5) = System::new( + GoldilocksBlake3Config::new(comm, fri_u), + single_inputs.clone(), + ); + let p5 = sys5.prove_multiple_claims( + &key5, + &[], + SystemWitness::from_stage_1(vec![single_trace.clone()], &sys5), + ); + sys5.verify_multiple_claims(&[], &p5).unwrap(); + assert_eq!( + blake3::hash(&p5.to_bytes().unwrap()).to_hex().as_str(), + expected_uniform_pin, + "v5 uniform proof bytes drifted from CPU/GPU pin (max_log_arity={max_log_arity})" + ); + + let (msys5, mkey5) = System::new( + GoldilocksBlake3Config::new(comm, fri_u), + multi_inputs.clone(), + ); + let mp5 = msys5.prove_multiple_claims( + &mkey5, + &multi_claim_refs, + SystemWitness::from_stage_1(multi_traces.clone(), &msys5), + ); + msys5 + .verify_multiple_claims(&multi_claim_refs, &mp5) + .unwrap(); + assert_eq!( + blake3::hash(&mp5.to_bytes().unwrap()).to_hex().as_str(), + expected_mixed_pin, + "v5 mixed proof bytes drifted from CPU/GPU pin (max_log_arity={max_log_arity})" + ); + } +} diff --git a/tests/fp3_v6_zk.rs b/tests/fp3_v6_zk.rs index 0bcfedc..81618e4 100644 --- a/tests/fp3_v6_zk.rs +++ b/tests/fp3_v6_zk.rs @@ -1180,3 +1180,92 @@ fn v6_vs_v6_zk_proof_size_comparison() { assert!(zk_bytes > v6_bytes); } } + +/// Multi-arity FRI (`max_log_arity = 2, 3, 4`) + `log_final_poly_len = 8` for +/// Protocol `v6-zk` (`Ext3` hiding) across both single-circuit uniform height +/// and multi-circuit mismatched heights strictly above 1024 LDE rows (runs on +/// both CPU and CUDA builds). +#[test] +fn v6_zk_multi_arity_and_final_poly_roundtrip() { + let comm = CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }; + + // Single-circuit 2048-row trace -> ZK LDE height = 2 * 2048 * 4 = 16384 = 2^14 > 1024. + let single_rows = 2048usize; + let (single_traces, single_claims) = build_single_circuit_witness(single_rows, 999, 13); + let single_claim_refs: Vec<&[Val]> = single_claims.iter().map(Vec::as_slice).collect(); + + // Multi-circuit mismatched heights: byte ROM / aux / work = 256 (ZK LDE 2048 = 2^11), + // sq = 4096 (ZK LDE 32768 = 2^15) — all > 2^(8+2) = 1024, exercising mixed log_arity + // including full max_log_arity = 2, 3, 4! + let (multi_traces, multi_claims) = build_multi_circuit_zk_witness(256, 256, 4096, true, 17); + let multi_claim_refs: Vec<&[Val]> = multi_claims.iter().map(Vec::as_slice).collect(); + + for max_log_arity in [2usize, 3, 4] { + let fri = FriParameters { + log_final_poly_len: 8, + max_log_arity, + num_queries: 24, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }; + + let (sys, key) = System::new( + GoldilocksBlake3V6ZkConfig::new(comm, fri), + single_circuit_private_sum_inputs(single_rows), + ); + let proof = sys.prove_multiple_claims( + &key, + &single_claim_refs, + SystemWitness::from_stage_1(single_traces.clone(), &sys), + ); + sys.verify_multiple_claims(&single_claim_refs, &proof) + .unwrap_or_else(|e| { + panic!( + "v6-zk single-circuit multi-arity verify failed (arity={max_log_arity}): {e:?}" + ) + }); + let single_arities: Vec = proof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + assert!( + single_arities.contains(&max_log_arity), + "v6-zk single-circuit expected log_arity={max_log_arity} in {single_arities:?}" + ); + let bytes = proof.to_bytes().unwrap(); + let decoded = Proof::::from_bytes(&bytes).unwrap(); + sys.verify_multiple_claims(&single_claim_refs, &decoded) + .unwrap(); + + let (msys, mkey) = System::new( + GoldilocksBlake3V6ZkConfig::new(comm, fri), + multi_circuit_zk_inputs(2, 256, 256, true), + ); + let mproof = msys.prove_multiple_claims( + &mkey, + &multi_claim_refs, + SystemWitness::from_stage_1(multi_traces.clone(), &msys), + ); + msys.verify_multiple_claims(&multi_claim_refs, &mproof) + .unwrap_or_else(|e| { + panic!( + "v6-zk multi-circuit multi-arity verify failed (arity={max_log_arity}): {e:?}" + ) + }); + let marities: Vec = mproof + .opening_proof + .commit_phase_openings + .iter() + .map(|s| usize::from(s.log_arity)) + .collect(); + assert!( + marities.contains(&max_log_arity) && marities.contains(&1), + "v6-zk multi-circuit expected mixed arities containing {max_log_arity} and 1, got {marities:?}" + ); + } +} diff --git a/tests/streaming_spill.rs b/tests/streaming_spill.rs index 74333c5..9300366 100644 --- a/tests/streaming_spill.rs +++ b/tests/streaming_spill.rs @@ -323,7 +323,7 @@ fn streaming_and_spilled_proofs_are_byte_identical_across_configs() { ) in cases.iter().enumerate() { #[cfg(feature = "cuda")] - if cap_height != 0 || max_log_arity > 1 { + if cap_height != 0 { continue; } let inputs = multi_circuit_inputs(k, work_rows); From 48e6e06a33173ef880039257354080b2b1f2b6d6 Mon Sep 17 00:00:00 2001 From: "John C. Burnham" Date: Mon, 23 Nov 2026 11:25:20 -0500 Subject: [PATCH 28/28] fix(cuda): align v6-zk hiding PCS/MMCS and witness tests with DeviceMemoryReservation admission --- src/cuda/hiding_mmcs.rs | 23 +- src/cuda/hiding_pcs.rs | 563 ++++++++++++++++++++++++++------------ src/cuda/tests/witness.rs | 8 +- 3 files changed, 414 insertions(+), 180 deletions(-) diff --git a/src/cuda/hiding_mmcs.rs b/src/cuda/hiding_mmcs.rs index c64e4dd..dd7877f 100644 --- a/src/cuda/hiding_mmcs.rs +++ b/src/cuda/hiding_mmcs.rs @@ -535,9 +535,14 @@ impl HidingCudaMmcs { .saturating_mul(size_of::()) }) .sum(); - let (free_bytes, total_device_bytes) = super::device_memory_info(self.device_id); - let min_free = super::minimum_free_bytes(total_device_bytes); - if total_bytes.saturating_add(min_free) > free_bytes + let max_height = ldes.iter().map(Matrix::height).max().unwrap_or(0); + let tree_workspace_bytes = max_height.saturating_mul(96); + let (free_bytes, _) = super::device_memory_info(self.device_id); + let min_free = super::minimum_free_bytes(); + if total_bytes + .saturating_add(tree_workspace_bytes) + .saturating_add(min_free) + > free_bytes || !host_hashed_heights_zk(ldes.iter().map(Matrix::dimensions)).is_empty() { return self.commit_cpu_with_seed(ldes, salt_seed); @@ -674,9 +679,15 @@ impl Mmcs for HidingCudaMmcs { .sum(); let total_bytes = total_cells.saturating_mul(size_of::()); if device_hashable && total_cells > (1 << 18) { - let (free_bytes, total_device_bytes) = super::device_memory_info(self.device_id); - let min_free = super::minimum_free_bytes(total_device_bytes); - if total_bytes.saturating_add(min_free) <= free_bytes { + let max_height = inputs.iter().map(Matrix::height).max().unwrap_or(0); + let tree_workspace_bytes = max_height.saturating_mul(96); + let (free_bytes, _) = super::device_memory_info(self.device_id); + let min_free = super::minimum_free_bytes(); + if total_bytes + .saturating_add(tree_workspace_bytes) + .saturating_add(min_free) + <= free_bytes + { let resident: Vec = inputs .iter() .map(|matrix| { diff --git a/src/cuda/hiding_pcs.rs b/src/cuda/hiding_pcs.rs index 4c1e173..d962f8d 100644 --- a/src/cuda/hiding_pcs.rs +++ b/src/cuda/hiding_pcs.rs @@ -348,16 +348,43 @@ where }) .max() .unwrap_or(0); - let (initial_free, total_bytes) = super::device_memory_info(self.mmcs.device_id()); - let minimum_free = super::minimum_free_bytes(total_bytes); + let (initial_free, _) = super::device_memory_info(self.mmcs.device_id()); + let minimum_free = super::minimum_free_bytes(); let lde_bytes = source_cells .saturating_mul(size_of::()) .checked_shl(u32::try_from(added_bits).expect("LDE blowup exceeds u32")) .unwrap_or(usize::MAX); + // An LDE uploads its whole trace beside its values, and a trace + // released after construction is still resident while its own LDE + // runs, so the all-device path always needs the largest trace. + let max_trace_bytes = prepared + .iter() + .map(|(_, mat)| { + mat.height() + .saturating_mul(mat.width()) + .saturating_mul(size_of::()) + }) + .max() + .unwrap_or(0); + let max_lde_height = prepared + .iter() + .map(|(_, mat)| { + mat.height() + .checked_shl(u32::try_from(added_bits).expect("LDE blowup exceeds u32")) + .unwrap_or(usize::MAX) + }) + .max() + .unwrap_or(0); + // The salted Merkle tree built immediately after the LDE loop holds + // all binary digest layers plus one injected frontier (~96 bytes/row). + let tree_workspace_bytes = max_lde_height.saturating_mul(96); + let peak_workspace = max_trace_bytes + .saturating_add(max_transform_workspace) + .max(tree_workspace_bytes); if lde_bytes + .saturating_add(peak_workspace) .saturating_add(minimum_free) - .saturating_add(max_transform_workspace) > initial_free { let dft = &self.dft; @@ -549,200 +576,237 @@ where .unwrap_or(0); let final_fri_height = self.fri.blowup() * self.fri.final_poly_len(); if resident_max_height > 1024 && resident_max_height > final_fri_height { - let _resident_guard = tracing::info_span!("stark/fri_resident_zk").entered(); let device_id = self.mmcs.device_id(); let (ext_degree, ext_w) = cuda_ext_degree_and_w::(); let mut opened_max_width = 0usize; let mut openings_per_height = [0usize; 33]; + let mut max_log: LinearMap = LinearMap::new(); for (ldes, points) in &resident_rounds { for (lde, ps) in ldes.iter().zip(points.iter()) { if !ps.is_empty() { opened_max_width = opened_max_width.max(lde.width()); let lh = log2_strict_usize(lde.height()); openings_per_height[lh] += ps.len(); - } - } - } - let max_openings_per_height = openings_per_height.into_iter().max().unwrap_or(0); - let log_global_max_height = log2_strict_usize(resident_max_height); - let coset_gold = bit_reversed_coset::(log_global_max_height); - let mut max_log: LinearMap = LinearMap::new(); - for (ldes, points) in &resident_rounds { - for (lde, ps) in ldes.iter().zip(points.iter()) { - for &z in ps { - if let Some(h) = max_log.get_mut(&z) { - *h = (*h).max(log2_strict_usize(lde.height())); - } else { - max_log.insert(z, log2_strict_usize(lde.height())); + for &z in ps { + if let Some(h) = max_log.get_mut(&z) { + *h = (*h).max(lh); + } else { + max_log.insert(z, lh); + } } } } } - let mut inv_offsets = LinearMap::new(); - let mut inverse_points = Vec::new(); - let mut inverse_counts = Vec::new(); - let mut inverse_count = 0usize; - for (point, lh) in max_log { - inv_offsets.insert(point, inverse_count); - let (buf, d) = ext_to_goldilocks::(point, ext_degree); - inverse_points.extend_from_slice(&buf[..d]); - let count = 1usize << lh; - inverse_counts.push(count); - inverse_count += count; - } - let mut workspace = CudaFriWorkspace::new( - device_id, - &inverse_points, - &inverse_counts, - &coset_gold, - ext_w, - ext_degree, - ); - let mut interpolation_tasks = CudaInterpolationTasks::new(ext_degree); - let mut output_count = 0usize; - let layouts = resident_rounds + let point_logs = max_log.into_iter().collect_vec(); + let inverse_elements: usize = point_logs.iter().map(|&(_, lh)| 1usize << lh).sum(); + let max_inverse_elements: usize = point_logs + .iter() + .map(|&(_, lh)| 1usize << lh) + .max() + .unwrap_or(0); + let reduced_elements: usize = openings_per_height .iter() - .map(|(ldes, points)| { - ldes.iter() - .zip(points.iter()) - .map(|(lde, ps)| { - let h = lde.height() >> self.fri.log_blowup; - let lh = log2_strict_usize(h); - ps.iter() - .map(|&point| { - let offset = output_count; - output_count += lde.width(); - let shift_pow = Goldilocks::GENERATOR.exp_power_of_2(lh); - let scale = (point.exp_power_of_2(lh) - shift_pow) - * (Goldilocks::from_usize(h) * shift_pow).inverse(); - let (scale_buf, d) = - ext_to_goldilocks::( - scale, ext_degree, + .enumerate() + .filter_map(|(lh, &count)| (count > 0).then_some(1usize << lh)) + .sum(); + let (free_bytes, total_device_bytes) = super::device_memory_info(device_id); + let minimum_free = super::minimum_free_bytes(); + let fri_workspace_bytes = inverse_elements + .saturating_mul(ext_degree * size_of::()) + .saturating_add(resident_max_height.saturating_mul(size_of::())) + .saturating_add( + max_inverse_elements.saturating_mul(ext_degree * size_of::()), + ) + .saturating_add( + reduced_elements.saturating_mul(ext_degree * size_of::()), + ) + .saturating_add( + resident_max_height + .saturating_mul(ext_degree * size_of::() + 96), + ) + .saturating_add(total_device_bytes / 64); + if fri_workspace_bytes.saturating_add(minimum_free) <= free_bytes { + let _resident_guard = tracing::info_span!("stark/fri_resident_zk").entered(); + let max_openings_per_height = + openings_per_height.into_iter().max().unwrap_or(0); + let log_global_max_height = log2_strict_usize(resident_max_height); + let coset_gold = bit_reversed_coset::(log_global_max_height); + let mut inv_offsets = LinearMap::new(); + let mut inverse_points = Vec::new(); + let mut inverse_counts = Vec::new(); + let mut inverse_count = 0usize; + for (point, lh) in point_logs { + inv_offsets.insert(point, inverse_count); + let (buf, d) = + ext_to_goldilocks::(point, ext_degree); + inverse_points.extend_from_slice(&buf[..d]); + let count = 1usize << lh; + inverse_counts.push(count); + inverse_count += count; + } + let mut workspace = CudaFriWorkspace::new( + device_id, + &inverse_points, + &inverse_counts, + &coset_gold, + ext_w, + ext_degree, + ); + let mut interpolation_tasks = CudaInterpolationTasks::new(ext_degree); + let mut output_count = 0usize; + let layouts = resident_rounds + .iter() + .map(|(ldes, points)| { + ldes.iter() + .zip(points.iter()) + .map(|(lde, ps)| { + let h = lde.height() >> self.fri.log_blowup; + let lh = log2_strict_usize(h); + ps.iter() + .map(|&point| { + let offset = output_count; + output_count += lde.width(); + let shift_pow = + Goldilocks::GENERATOR.exp_power_of_2(lh); + let scale = (point.exp_power_of_2(lh) - shift_pow) + * (Goldilocks::from_usize(h) * shift_pow).inverse(); + let (scale_buf, d) = + ext_to_goldilocks::( + scale, ext_degree, + ); + interpolation_tasks.push( + lde, + h, + *inv_offsets.get(&point).unwrap(), + offset, + &scale_buf[..d], ); - interpolation_tasks.push( - lde, - h, - *inv_offsets.get(&point).unwrap(), - offset, - &scale_buf[..d], - ); - (offset, lde.width()) - }) - .collect_vec() - }) - .collect_vec() - }) - .collect_vec(); - let interpolated = tracing::info_span!("stark/fri_interpolate") - .in_scope(|| workspace.interpolate(&interpolation_tasks, output_count, ext_w)); - let all_opened_values = layouts - .into_iter() - .map(|round| { - round - .into_iter() - .map(|matrix| { - matrix - .into_iter() - .map(|(offset, width)| { - interpolated - [offset * ext_degree..(offset + width) * ext_degree] - .chunks_exact(ext_degree) - .map(ext_from_goldilocks::) - .collect_vec() - }) - .collect_vec() - }) - .collect_vec() - }) - .collect_vec(); - for round in &all_opened_values { - for matrix in round { - for values in matrix { - challenger.observe_algebra_slice(values); + (offset, lde.width()) + }) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec(); + let interpolated = + tracing::info_span!("stark/fri_interpolate").in_scope(|| { + workspace.interpolate(&interpolation_tasks, output_count, ext_w) + }); + let all_opened_values = layouts + .into_iter() + .map(|round| { + round + .into_iter() + .map(|matrix| { + matrix + .into_iter() + .map(|(offset, width)| { + interpolated + [offset * ext_degree..(offset + width) * ext_degree] + .chunks_exact(ext_degree) + .map(ext_from_goldilocks::) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec() + }) + .collect_vec(); + for round in &all_opened_values { + for matrix in round { + for values in matrix { + challenger.observe_algebra_slice(values); + } } } - } - let schedule = FriBatchingSchedule::::sample( - self.batching, - opened_max_width, - max_openings_per_height, - challenger, - ); - let col_weights: Vec = match &schedule { - FriBatchingSchedule::Horner { alpha } => { - alpha.powers().take(opened_max_width).collect() + let schedule = FriBatchingSchedule::::sample( + self.batching, + opened_max_width, + max_openings_per_height, + challenger, + ); + let col_weights: Vec = match &schedule { + FriBatchingSchedule::Horner { alpha } => { + alpha.powers().take(opened_max_width).collect() + } + FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), + }; + let mut col_weights_flat = Vec::with_capacity(col_weights.len() * ext_degree); + for &w in &col_weights { + let (buf, d) = ext_to_goldilocks::(w, ext_degree); + col_weights_flat.extend_from_slice(&buf[..d]); } - FriBatchingSchedule::Tensor { col_weights, .. } => col_weights.clone(), - }; - let mut col_weights_flat = Vec::with_capacity(col_weights.len() * ext_degree); - for &w in &col_weights { - let (buf, d) = ext_to_goldilocks::(w, ext_degree); - col_weights_flat.extend_from_slice(&buf[..d]); - } - let mut num_reduced = [0usize; 33]; - let mut opening_idx_by_height = [0usize; 33]; - let mut reduced: [Option; 33] = core::array::from_fn(|_| None); - let mut reduction_tasks = CudaReductionTasks::new(ext_degree); - for ((ldes, points), openings_round) in - resident_rounds.iter().zip(all_opened_values.iter()) - { - for ((lde, ps), openings) in - ldes.iter().zip(points.iter()).zip(openings_round.iter()) + let mut num_reduced = [0usize; 33]; + let mut opening_idx_by_height = [0usize; 33]; + let mut reduced: [Option; 33] = + core::array::from_fn(|_| None); + let mut reduction_tasks = CudaReductionTasks::new(ext_degree); + for ((ldes, points), openings_round) in + resident_rounds.iter().zip(all_opened_values.iter()) { - if ps.is_empty() { - continue; + for ((lde, ps), openings) in + ldes.iter().zip(points.iter()).zip(openings_round.iter()) + { + if ps.is_empty() { + continue; + } + let lh = log2_strict_usize(lde.height()); + let target = reduced[lh].get_or_insert_with(|| { + CudaReducedOpening::new_with_degree( + device_id, + lde.height(), + ext_degree, + ) + }); + for (&point, ys) in ps.iter().zip(openings.iter()) { + let reduced_y: Challenge = + dot_product(col_weights.iter().copied(), ys.iter().copied()); + let offset = match &schedule { + FriBatchingSchedule::Horner { alpha } => alpha.exp_u64( + u64::try_from(num_reduced[lh]) + .expect("reduced column count exceeds u64"), + ), + FriBatchingSchedule::Tensor { open_weights, .. } => { + open_weights[opening_idx_by_height[lh]] + } + }; + let (y_buf, d) = ext_to_goldilocks::( + reduced_y, ext_degree, + ); + let (off_buf, _) = + ext_to_goldilocks::(offset, ext_degree); + reduction_tasks.push( + target, + lde, + *inv_offsets.get(&point).unwrap(), + &y_buf[..d], + &off_buf[..d], + ); + num_reduced[lh] += lde.width(); + opening_idx_by_height[lh] += 1; + } } - let lh = log2_strict_usize(lde.height()); - let target = reduced[lh].get_or_insert_with(|| { - CudaReducedOpening::new_with_degree(device_id, lde.height(), ext_degree) + } + if !reduction_tasks.is_empty() { + tracing::info_span!("stark/fri_reduce").in_scope(|| { + workspace.reduce(&reduction_tasks, &col_weights_flat, ext_w); }); - for (&point, ys) in ps.iter().zip(openings.iter()) { - let reduced_y: Challenge = - dot_product(col_weights.iter().copied(), ys.iter().copied()); - let offset = match &schedule { - FriBatchingSchedule::Horner { alpha } => alpha.exp_u64( - u64::try_from(num_reduced[lh]) - .expect("reduced column count exceeds u64"), - ), - FriBatchingSchedule::Tensor { open_weights, .. } => { - open_weights[opening_idx_by_height[lh]] - } - }; - let (y_buf, d) = - ext_to_goldilocks::(reduced_y, ext_degree); - let (off_buf, _) = - ext_to_goldilocks::(offset, ext_degree); - reduction_tasks.push( - target, - lde, - *inv_offsets.get(&point).unwrap(), - &y_buf[..d], - &off_buf[..d], - ); - num_reduced[lh] += lde.width(); - opening_idx_by_height[lh] += 1; - } } - } - if !reduction_tasks.is_empty() { - tracing::info_span!("stark/fri_reduce").in_scope(|| { - workspace.reduce(&reduction_tasks, &col_weights_flat, ext_w); + let fri_input = reduced.into_iter().rev().flatten().collect_vec(); + let fri_proof = tracing::info_span!("stark/fri_prove").in_scope(|| { + prove_fri_cuda_resident_hiding( + &self.fri, + fri_input, + challenger, + log_global_max_height, + &commitment_data_with_opening_points, + &self.mmcs, + ext_w, + ext_degree, + ) }); + return (all_opened_values, fri_proof); } - let fri_input = reduced.into_iter().rev().flatten().collect_vec(); - let fri_proof = tracing::info_span!("stark/fri_prove").in_scope(|| { - prove_fri_cuda_resident_hiding( - &self.fri, - fri_input, - challenger, - log_global_max_height, - &commitment_data_with_opening_points, - &self.mmcs, - ext_w, - ext_degree, - ) - }); - return (all_opened_values, fri_proof); } } @@ -973,3 +1037,158 @@ where ) } } + +#[cfg(test)] +mod tests { + use p3_commit::{ExtensionMmcs, Mmcs, Pcs}; + use p3_field::coset::TwoAdicMultiplicativeCoset; + use p3_field::{BasedVectorSpace, PrimeCharacteristicRing}; + use p3_fri::FriParameters; + use p3_goldilocks::Goldilocks; + use p3_matrix::dense::RowMajorMatrix; + use p3_util::log2_strict_usize; + + use super::HidingCudaTwoAdicFriPcs; + use crate::config::ProofConfig; + use crate::cuda::hiding_mmcs::HidingCudaMmcs; + use crate::cuda::{CudaDft, DeviceMemoryReservation, configured_device}; + use crate::p3_adapter::fri_batching::FriBatching; + use crate::types::{ + CommitmentParameters, ExtVal3, FriParameters as ConfigFriParameters, + GoldilocksBlake3V6ZkConfig, + }; + + #[test] + #[ignore = "requires exclusive access to a CUDA device: hides its free memory"] + fn hiding_pcs_and_mmcs_honor_device_memory_reservation() { + let device = configured_device(); + let mmcs = HidingCudaMmcs::new_v6_zk(0, device); + let ext_mmcs: ExtensionMmcs = + ExtensionMmcs::new(mmcs.clone()); + let fri = FriParameters { + log_blowup: 2, + log_final_poly_len: 1, + max_log_arity: 2, + num_queries: 8, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + mmcs: ext_mmcs, + }; + let pcs = HidingCudaTwoAdicFriPcs::new(CudaDft::new(device), mmcs.clone(), fri) + .with_batching(FriBatching::Tensor); + let config = GoldilocksBlake3V6ZkConfig::with_device( + CommitmentParameters { + log_blowup: 2, + cap_height: 0, + }, + ConfigFriParameters { + log_final_poly_len: 1, + max_log_arity: 2, + num_queries: 8, + commit_proof_of_work_bits: 0, + query_proof_of_work_bits: 0, + }, + FriBatching::Tensor, + Some(device), + ); + + // Height 512 -> LDE height 512 * 2 * 4 = 4096 (> 1024 GPU FRI threshold). + let height = 512usize; + let width = 8usize; + let domain = + TwoAdicMultiplicativeCoset::new(Goldilocks::ONE, log2_strict_usize(height)).unwrap(); + let matrix = RowMajorMatrix::new( + (0..height * width) + .map(|i| Goldilocks::from_u64((i as u64).wrapping_mul(0x9e37_79b9) ^ 0x5a5a)) + .collect(), + width, + ); + + // 1. Unreserved: commit_preprocessed and commit stay CUDA-resident. + let (gpu_prep_commit, gpu_prep_data) = pcs.commit_preprocessed([(domain, matrix.clone())]); + assert!( + mmcs.is_cuda_resident(&gpu_prep_data), + "unreserved v6-zk preprocessed commit should be CUDA-resident" + ); + type ZkChallenger = ::Challenger; + let (gpu_commit, gpu_data) = as Pcs< + ExtVal3, + ZkChallenger, + >>::commit(&pcs, [(domain, matrix.clone())]); + assert!( + mmcs.is_cuda_resident(&gpu_data), + "unreserved v6-zk commit should be CUDA-resident" + ); + + // 2. Under a reservation larger than VRAM, admission must spill to CPU + // and still produce identical commitments and verifying openings. + let reservation = DeviceMemoryReservation::new(device, 1usize << 40); + + let (cpu_prep_commit, cpu_prep_data) = pcs.commit_preprocessed([(domain, matrix)]); + assert!( + !mmcs.is_cuda_resident(&cpu_prep_data), + "reserved v6-zk preprocessed commit must fall back to CPU" + ); + assert_eq!( + cpu_prep_commit, gpu_prep_commit, + "CPU fallback and GPU v6-zk preprocessed commitments must match" + ); + + // HidingCudaMmcs::commit_cuda_storage_with_seed & Mmcs::commit (> 1<<18 cells). + let big_lde = RowMajorMatrix::new( + (0..(1 << 16) * 5) + .map(|i| Goldilocks::from_usize(i + 1)) + .collect(), + 5, + ); + let salt_seed = [0x33u8; 32]; + let (reserved_storage_commit, reserved_storage_data) = + mmcs.commit_cuda_storage_with_seed(vec![big_lde.clone()], salt_seed); + assert!( + !mmcs.is_cuda_resident(&reserved_storage_data), + "reserved commit_cuda_storage_with_seed must fall back to CPU" + ); + let (_, reserved_mmcs_data) = mmcs.commit(vec![big_lde.clone()]); + assert!( + !mmcs.is_cuda_resident(&reserved_mmcs_data), + "reserved Mmcs::commit must fall back to CPU" + ); + + // Opening already-resident GPU data while VRAM is reserved falls back + // cleanly to the CPU opening path and verifies. + let z = ExtVal3::from_basis_coefficients_slice(&[ + Goldilocks::from_u64(11), + Goldilocks::from_u64(19), + Goldilocks::from_u64(29), + ]) + .unwrap(); + let mut prover_challenger = config.initialise_challenger(); + let (opened, proof) = as Pcs>::open( + &pcs, + vec![(&gpu_data, vec![vec![z]])], + &mut prover_challenger, + ); + let mut verifier_challenger = config.initialise_challenger(); + as Pcs>::verify( + &pcs, + vec![( + gpu_commit, + vec![(domain, vec![(z, opened[0][0][0].clone())])], + )], + &proof, + &mut verifier_challenger, + ) + .expect("v6-zk proof opened under DeviceMemoryReservation must verify"); + + drop(reservation); + + // After dropping the reservation, storage commit returns to GPU and matches. + let (gpu_storage_commit, gpu_storage_data) = + mmcs.commit_cuda_storage_with_seed(vec![big_lde], salt_seed); + assert!( + mmcs.is_cuda_resident(&gpu_storage_data), + "unreserved commit_cuda_storage_with_seed should return to GPU" + ); + assert_eq!(reserved_storage_commit, gpu_storage_commit); + } +} diff --git a/src/cuda/tests/witness.rs b/src/cuda/tests/witness.rs index f6dd1a9..a882839 100644 --- a/src/cuda/tests/witness.rs +++ b/src/cuda/tests/witness.rs @@ -456,7 +456,11 @@ fn commit_beside_concurrent_allocation(reserve: bool) { .collect::>() }; // Also caches every transform constant before free memory is measured. - let (expected, _) = commit_with(pcs, evaluations(TraceSource::Host(generated.clone())), None); + let (expected, _) = commit_with::( + pcs, + evaluations(TraceSource::Host(generated.clone())), + None, + ); // The resident footprint `commit_with` admits for this batch. let trace_bytes = height * width * size_of::(); @@ -488,7 +492,7 @@ fn commit_beside_concurrent_allocation(reserve: bool) { if reserve { *source.reservation.lock().unwrap() = Some(DeviceMemoryReservation::new(device, external)); } - let (commitment, _data) = commit_with( + let (commitment, _data) = commit_with::( pcs, evaluations(TraceSource::Generated(source.clone())), None,