From e4f9c2360b5d571e7b684296965d8dde4b007fe1 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Thu, 26 Nov 2026 21:11:38 -0300 Subject: [PATCH] Season 2 leaders (3/3): the client-WASM leader's stack The client-WASM leader's whole stack merged into the other two, without the harness patches; the merge question on the shared concurrent MSM gate resolved (the rollup stack's gate, not slower for AVM); and a client test made to compile on x86 (-Wconversion). Squashed from the PR's 98 commits (each original patch with its author; they stay on the PR's page). Co-authored-by: bench Co-authored-by: iAmMichaelConnor Co-authored-by: opt Co-authored-by: Golf Research Co-authored-by: Astra Ideator 1 Co-authored-by: Golf Research Co-authored-by: alejoamiras --- barretenberg/cpp/src/CMakeLists.txt | 9 +- .../cpp/src/barretenberg/common/assert.hpp | 117 ++++--- .../common/parallel_for_mutex_pool.cpp | 18 +- .../barretenberg/ecc/fields/vector_field.hpp | 25 +- .../fields/vector_field_mont_sqr_body.inl.hpp | 81 +++++ .../ecc/fields/vector_field_sqr.test.cpp | 63 ++++ .../ecc/fields/vector_field_wasm.cpp | 258 ++++++++++++++- .../ecc/groups/affine_add_packed.hpp | 25 ++ .../pippenger_batched.hpp | 83 +++-- .../pippenger_batched_full_width.test.cpp | 166 ++++++++++ .../pippenger_constantine.hpp | 8 + .../pippenger_constantine.test.cpp | 6 + .../pippenger_window_skip.test.hpp | 179 ++++++++++ .../scalar_multiplication_fast.cpp | 186 ++++++++++- .../flavor/multilinear_batching_flavor.hpp | 6 + .../honk/composer/composer_lib.hpp | 3 + .../honk/composer/permutation_lib.hpp | 7 + .../honk/library/grand_product_library.hpp | 100 +++++- .../multilinear_batching_prover.cpp | 40 ++- .../multilinear_batching_sumcheck.hpp | 311 ++++++++++++++++++ .../multilinear_batching_sumcheck.test.cpp | 271 +++++++++++++++ .../barretenberg/polynomials/fold_stride2.hpp | 86 ++++- .../delta_range_constraint_relation.hpp | 2 +- .../relations/poseidon2_external_relation.hpp | 4 + .../poseidon2_initial_external_relation.hpp | 4 + .../poseidon2_quad_internal_relation.hpp | 6 +- ...eidon2_quad_internal_terminal_relation.hpp | 6 +- .../poseidon2_transition_entry_relation.hpp | 6 +- .../plookup_tables/secp256r1_fixed_base.cpp | 39 +-- .../secp256r1_fixed_base.test.cpp | 42 +++ .../ultra_circuit_builder.cpp | 2 + .../barretenberg/sumcheck/sumcheck_round.hpp | 200 ++++++++--- .../sumcheck/sumcheck_sparse_lanes.test.cpp | 125 +++++++ .../translator_ordered_range_sort.test.cpp | 232 +++++++++++++ .../translator_vm/translator_proving_key.cpp | 145 ++++++-- .../ultra_honk/range_list_sort.test.cpp | 66 ++++ 36 files changed, 2734 insertions(+), 193 deletions(-) create mode 100644 barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_mont_sqr_body.inl.hpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_sqr.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched_full_width.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_window_skip.test.hpp create mode 100644 barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.hpp create mode 100644 barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_sparse_lanes.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/translator_vm/translator_ordered_range_sort.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/ultra_honk/range_list_sort.test.cpp diff --git a/barretenberg/cpp/src/CMakeLists.txt b/barretenberg/cpp/src/CMakeLists.txt index 0ba2333..60f19a2 100644 --- a/barretenberg/cpp/src/CMakeLists.txt +++ b/barretenberg/cpp/src/CMakeLists.txt @@ -43,14 +43,13 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "GNU") endif() # We enable -O1 level optimsations, even when compiling debug wasm, otherwise we get "local count too large" at runtime. -# Release wasm is built with -O3 and the loop vectorizer off: the vectorizer turns field-arithmetic loops into i64x2 -# multiplies that V8 lowers to slow sequences (scalar Fr mul 50 ns -> 72 ns), while the rest of -O3 (inlining, -# unrolling) proves ~8% faster than -Oz end to end. The cost is a larger artifact (gzipped ~3.9 MB -> ~5.6 MB); -# configure with -DWASM_RELEASE_OPT=-Oz to prioritise size instead. +# Release wasm is built with -O2 and the loop vectorizer off: the vectorizer turns field-arithmetic loops into i64x2 +# multiplies that V8 lowers to slow sequences, while -O2 proves faster than -Oz and keeps V8's code memory within the +# proving RAM budget (-O3 did not). Configure WASM_RELEASE_OPT explicitly to experiment with other release flags. if(WASM) set(CMAKE_CXX_FLAGS_DEBUG "-O1 -g") set(CMAKE_C_FLAGS_DEBUG "-O1 -g") - set(WASM_RELEASE_OPT "-O3 -fno-vectorize" CACHE STRING "Optimisation flags for release WASM builds") + set(WASM_RELEASE_OPT "-O2 -fno-vectorize" CACHE STRING "Optimisation flags for release WASM builds") set(CMAKE_CXX_FLAGS_RELEASE "${WASM_RELEASE_OPT} -DNDEBUG") set(CMAKE_C_FLAGS_RELEASE "${WASM_RELEASE_OPT} -DNDEBUG") add_link_options(-Wl,--export-memory,--import-memory,--stack-first,-z,stack-size=1048576,--max-memory=4294967296) diff --git a/barretenberg/cpp/src/barretenberg/common/assert.hpp b/barretenberg/cpp/src/barretenberg/common/assert.hpp index a3f8e79..68db984 100644 --- a/barretenberg/cpp/src/barretenberg/common/assert.hpp +++ b/barretenberg/cpp/src/barretenberg/common/assert.hpp @@ -17,6 +17,17 @@ enum class AssertMode : std::uint8_t { ABORT, WARN }; AssertMode& get_assert_mode(); void assert_failure(std::string const& err); +namespace detail { +// Builds and reports a failed assertion's message out of line, so an assertion site costs its comparison and a call. +// Formatting the message inline puts a std::ostringstream in every function that asserts, which inflates hot code +// and the inliner's cost estimate for it. The message arguments are evaluated inside a lambda that captures by +// reference: `__func__` there names the lambda, and a structured binding to a bit-field cannot appear in a message. +template [[gnu::cold, gnu::noinline]] void assert_failed(MakeMessage make_message) +{ + assert_failure(make_message()); +} +} // namespace detail + // NOTE do not use in threaded contexts! struct AssertGuard { AssertGuard(AssertMode mode) @@ -60,10 +71,12 @@ struct AssertGuard { do { \ BB_BENCH_ASSERT("BB_ASSERT" #expression); \ if (!(BB_LIKELY(expression))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #expression ")"; \ - __VA_OPT__(oss << "\nReason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #expression ")"; \ + __VA_OPT__(oss << "\nReason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) #else @@ -71,11 +84,13 @@ struct AssertGuard { do { \ BB_BENCH_ASSERT("BB_ASSERT" #expression); \ if (!(BB_LIKELY(expression))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #expression ")"; \ - __VA_OPT__(oss << "\nReason : " << __VA_ARGS__;) \ - info(oss.str()); \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #expression ")"; \ + __VA_OPT__(oss << "\nReason : " << __VA_ARGS__;) \ + info(oss.str()); \ + return oss.str(); \ + }); \ } \ } while (0) #endif @@ -86,12 +101,14 @@ struct AssertGuard { const auto& _actual = (actual); \ const auto& _expected = (expected); \ if (!(BB_LIKELY(_actual == _expected))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #actual " == " #expected ")\n"; \ - oss << " Actual : " << _actual << "\n"; \ - oss << " Expected: " << _expected; \ - __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #actual " == " #expected ")\n"; \ + oss << " Actual : " << _actual << "\n"; \ + oss << " Expected: " << _expected; \ + __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) @@ -101,12 +118,14 @@ struct AssertGuard { const auto& _actual = (actual); \ const auto& _expected = (expected); \ if (!(BB_LIKELY(_actual != _expected))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #actual " != " #expected ")\n"; \ - oss << " Actual : " << _actual << "\n"; \ - oss << " Not expected: " << _expected; \ - __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #actual " != " #expected ")\n"; \ + oss << " Actual : " << _actual << "\n"; \ + oss << " Not expected: " << _expected; \ + __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) @@ -116,12 +135,14 @@ struct AssertGuard { const auto& _left = (left); \ const auto& _right = (right); \ if (!(BB_LIKELY(_left > _right))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #left " > " #right ")\n"; \ - oss << " Left : " << _left << "\n"; \ - oss << " Right : " << _right; \ - __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #left " > " #right ")\n"; \ + oss << " Left : " << _left << "\n"; \ + oss << " Right : " << _right; \ + __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) @@ -131,12 +152,14 @@ struct AssertGuard { const auto& _left = (left); \ const auto& _right = (right); \ if (!(BB_LIKELY(_left >= _right))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #left " >= " #right ")\n"; \ - oss << " Left : " << _left << "\n"; \ - oss << " Right : " << _right; \ - __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #left " >= " #right ")\n"; \ + oss << " Left : " << _left << "\n"; \ + oss << " Right : " << _right; \ + __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) @@ -146,12 +169,14 @@ struct AssertGuard { const auto& _left = (left); \ const auto& _right = (right); \ if (!(BB_LIKELY(_left < _right))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #left " < " #right ")\n"; \ - oss << " Left : " << _left << "\n"; \ - oss << " Right : " << _right; \ - __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #left " < " #right ")\n"; \ + oss << " Left : " << _left << "\n"; \ + oss << " Right : " << _right; \ + __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) @@ -161,12 +186,14 @@ struct AssertGuard { const auto& _left = (left); \ const auto& _right = (right); \ if (!(BB_LIKELY(_left <= _right))) { \ - std::ostringstream oss; \ - oss << "Assertion failed: (" #left " <= " #right ")\n"; \ - oss << " Left : " << _left << "\n"; \ - oss << " Right : " << _right; \ - __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ - bb::assert_failure(oss.str()); \ + bb::detail::assert_failed([&]() { \ + std::ostringstream oss; \ + oss << "Assertion failed: (" #left " <= " #right ")\n"; \ + oss << " Left : " << _left << "\n"; \ + oss << " Right : " << _right; \ + __VA_OPT__(oss << "\n Reason : " << __VA_ARGS__;) \ + return oss.str(); \ + }); \ } \ } while (0) diff --git a/barretenberg/cpp/src/barretenberg/common/parallel_for_mutex_pool.cpp b/barretenberg/cpp/src/barretenberg/common/parallel_for_mutex_pool.cpp index 0f91763..3b17751 100644 --- a/barretenberg/cpp/src/barretenberg/common/parallel_for_mutex_pool.cpp +++ b/barretenberg/cpp/src/barretenberg/common/parallel_for_mutex_pool.cpp @@ -37,9 +37,15 @@ constexpr size_t CACHE_LINE_SIZE = 64; // How long an idle thread busy-waits for the next job (workers) or for the job to finish (caller) before blocking on a // condition variable. Provers issue thousands of short parallel_for calls back to back (sumcheck rounds, MSM stages, // per-polynomial loops); waking a blocked thread costs tens of microseconds, which is comparable to the work itself. +#ifdef __wasm__ +// On WASM the spin is bounded by a poll count, not the clock: steady_clock::now() is a call out to the host's WASI +// clock_time_get, which bb.js answers in whole milliseconds, so a 100 us deadline would last until the next tick. +constexpr size_t SPIN_POLLS = size_t{ 1 } << 19; +#else constexpr auto SPIN_DURATION = std::chrono::microseconds(100); // The clock is only read once every SPIN_CLOCK_INTERVAL spins. constexpr size_t SPIN_CLOCK_INTERVAL = 64; +#endif inline void cpu_relax() { @@ -51,11 +57,20 @@ inline void cpu_relax() } /** - * @brief Busy-waits until `done()` holds or SPIN_DURATION elapses. + * @brief Busy-waits until `done()` holds or the spin bound (SPIN_POLLS, or SPIN_DURATION off WASM) is reached. * @return true if `done()` holds. */ template bool spin_until(const Done& done) { +#ifdef __wasm__ + for (size_t polls = 0; polls < SPIN_POLLS; ++polls) { + if (done()) { + return true; + } + cpu_relax(); + } + return done(); +#else auto deadline = std::chrono::steady_clock::now() + SPIN_DURATION; for (size_t spins = 1;; ++spins) { if (done()) { @@ -66,6 +81,7 @@ template bool spin_until(const Done& done) } cpu_relax(); } +#endif } /** diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field.hpp index 4015e4c..884f472 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field.hpp @@ -16,6 +16,8 @@ // in the product phase, NOT 81. Combined with 9 Yuval reductions × 9 // madConst = 81, total is 66+81 = 147. Schoolbook would have been 81+81 = // 162. The gist: "it's ~25% of the total runtime." +// sqr() keeps the split but squares each part, doubling the off-diagonal +// terms: 39 muls in the product phase (see vector_field_wasm.cpp). // // 2. Op-by-op interleaving. // Scalar statement, then equivalent quad statement, then next scalar, etc. @@ -103,12 +105,12 @@ template inline constexpr std::array compute_tnm_was return tnm; } -// Marker trait: specialized to true for each Params whose VectorField has a -// SIMD operator* body (an explicit specialization defined in +// Marker trait: specialized to true for each Params whose VectorField has +// SIMD operator* and sqr bodies (explicit specializations defined in // vector_field_wasm.cpp). vectorized_for / vectorized_for_if read this to // decide whether to take the bulk path. Add a new specialization (below) -// when adding the corresponding operator* body so the gate and the body -// stay in lockstep. +// when adding the corresponding operator* and sqr bodies so the gate and the +// bodies stay in lockstep. template struct has_simd_mont_mul : std::false_type {}; template inline constexpr bool has_simd_mont_mul_v = has_simd_mont_mul::value; @@ -192,8 +194,17 @@ template struct alignas(32) VectorField { static VectorField zero() noexcept { return broadcast(Field::zero()); } static VectorField one() noexcept { return broadcast(Field::one()); } +#if BB_VECTOR_FIELD_SIMD + // Under WASM SIMD, sqr has explicit specializations for Bn254FrParams and Bn254FqParams next to operator* + // (see vector_field_wasm.cpp), with the same link-time contract. Their output limbs equal (*this) * (*this). + VectorField sqr() const noexcept; + // Square entry point for the packed affine addition. + VectorField sqr_for_affine() const noexcept { return sqr(); } + void self_sqr() noexcept { *this = sqr(); } +#else VectorField sqr() const noexcept { return (*this) * (*this); } void self_sqr() noexcept { *this = (*this) * (*this); } +#endif VectorField operator-() const noexcept { return zero() - *this; } // Per-lane scalar invert. Slow path -- for static-init constants and rare relation use. For batched // inversions of independent values use the K=5 batch-inversion pattern in ecc/groups/element_impl.hpp. @@ -291,18 +302,20 @@ template struct alignas(32) VectorField { base[idx[2] - offset], base[idx[3] - offset], base[idx[4] - offset] }; - return VectorField(tmp); + return VectorField(tmp.data()); } // Counterpart to `gather` for sources that aren't a flat `Field*` -- e.g. a polynomial's `operator[]`, // which handles virtual-zero and start-index translation. lane L is set to value_at(L). + // The lanes are staged contiguously, so they pack through the transpose constructor rather than the per-lane + // scalar pack of the std::array constructor (the limbs are identical). template static VectorField from_lanes(const Fn& value_at) noexcept { std::array lanes; for (size_t lane = 0; lane < SIZE; ++lane) { lanes[lane] = value_at(lane); } - return VectorField(lanes); + return VectorField(lanes.data()); } // SLOW PATH — see gather. Writes base[idx[L] - offset] = this->get(L) for L in 0..4. diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_mont_sqr_body.inl.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_mont_sqr_body.inl.hpp new file mode 100644 index 0000000..30b7e46 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_mont_sqr_body.inl.hpp @@ -0,0 +1,81 @@ +// Body of VectorField::sqr under WASM SIMD: the squaring counterpart of +// vector_field_mont_mul_body.inl.hpp, included inside per-Params explicit +// specializations in vector_field_wasm.cpp in the same way. +// +// BB_VF_KARATSUBA_SQR_STAGES_1_4 yields the same pl*, ph*, pc* columns as the +// multiply kernel does for identical operands, except that pc8 (= pl8) is not +// formed and pc7 is only available as pm7 = pc7 - pl7. Stage 5 below is the +// multiply's combine with those two substitutions, so temp_0..temp_16 and the +// stage 6..10 output match (*this) * (*this) limb for limb. +// +// Including this file inside `{ ... }` of a `VectorField::sqr` +// specialization is the supported use; do not include it at namespace scope. +VectorField result; + +BB_VF_LOAD_SQR_LIMBS(*this); +BB_VF_KARATSUBA_SQR_STAGES_1_4(); + +// ============================================================ +// Stage 5: Combine into temp_0..temp_16 (see the multiply body), with +// temp[12] = pm7 + ph[2] (pm7 = pc[7] - pl[7]) +// temp[13] = ph[3] (pc[8] - pl[8] = 0) +// ============================================================ +uint64_t temp_0 = pl0; +v128_t tlo_0 = pl0_lo; +v128_t thi_0 = pl0_hi; +uint64_t temp_1 = pl1; +v128_t tlo_1 = pl1_lo; +v128_t thi_1 = pl1_hi; +uint64_t temp_2 = pl2; +v128_t tlo_2 = pl2_lo; +v128_t thi_2 = pl2_hi; +uint64_t temp_3 = pl3; +v128_t tlo_3 = pl3_lo; +v128_t thi_3 = pl3_hi; +uint64_t temp_4 = pl4; +v128_t tlo_4 = pl4_lo; +v128_t thi_4 = pl4_hi; + +uint64_t temp_5 = pl5 + (pc0 - pl0 - ph0); +v128_t tlo_5 = wasm_i64x2_add(pl5_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc0_lo, pl0_lo), ph0_lo)); +v128_t thi_5 = wasm_i64x2_add(pl5_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc0_hi, pl0_hi), ph0_hi)); +uint64_t temp_6 = pl6 + (pc1 - pl1 - ph1); +v128_t tlo_6 = wasm_i64x2_add(pl6_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc1_lo, pl1_lo), ph1_lo)); +v128_t thi_6 = wasm_i64x2_add(pl6_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc1_hi, pl1_hi), ph1_hi)); +uint64_t temp_7 = pl7 + (pc2 - pl2 - ph2); +v128_t tlo_7 = wasm_i64x2_add(pl7_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc2_lo, pl2_lo), ph2_lo)); +v128_t thi_7 = wasm_i64x2_add(pl7_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc2_hi, pl2_hi), ph2_hi)); +uint64_t temp_8 = pl8 + (pc3 - pl3 - ph3); +v128_t tlo_8 = wasm_i64x2_add(pl8_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc3_lo, pl3_lo), ph3_lo)); +v128_t thi_8 = wasm_i64x2_add(pl8_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc3_hi, pl3_hi), ph3_hi)); + +uint64_t temp_9 = pc4 - pl4 - ph4; +v128_t tlo_9 = wasm_i64x2_sub(wasm_i64x2_sub(pc4_lo, pl4_lo), ph4_lo); +v128_t thi_9 = wasm_i64x2_sub(wasm_i64x2_sub(pc4_hi, pl4_hi), ph4_hi); + +uint64_t temp_10 = (pc5 - pl5 - ph5) + ph0; +v128_t tlo_10 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc5_lo, pl5_lo), ph5_lo), ph0_lo); +v128_t thi_10 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc5_hi, pl5_hi), ph5_hi), ph0_hi); +uint64_t temp_11 = (pc6 - pl6 - ph6) + ph1; +v128_t tlo_11 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc6_lo, pl6_lo), ph6_lo), ph1_lo); +v128_t thi_11 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc6_hi, pl6_hi), ph6_hi), ph1_hi); +uint64_t temp_12 = pm7 + ph2; +v128_t tlo_12 = wasm_i64x2_add(pm7_lo, ph2_lo); +v128_t thi_12 = wasm_i64x2_add(pm7_hi, ph2_hi); +uint64_t temp_13 = ph3; +v128_t tlo_13 = ph3_lo; +v128_t thi_13 = ph3_hi; + +uint64_t temp_14 = ph4; +v128_t tlo_14 = ph4_lo; +v128_t thi_14 = ph4_hi; +uint64_t temp_15 = ph5; +v128_t tlo_15 = ph5_lo; +v128_t thi_15 = ph5_hi; +uint64_t temp_16 = ph6; +v128_t tlo_16 = ph6_lo; +v128_t thi_16 = ph6_hi; + +// Stages 6..10: unchanged from the multiply. +BB_VF_RUN_STAGES_6_THROUGH_10(); +return result; diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_sqr.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_sqr.test.cpp new file mode 100644 index 0000000..36ff77f --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_sqr.test.cpp @@ -0,0 +1,63 @@ +#include "barretenberg/ecc/fields/vector_field.hpp" + +#include "barretenberg/ecc/curves/bn254/fq.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" + +#include +#include +#include +#include + +namespace { + +// sqr / self_sqr / sqr_for_affine run a dedicated squaring kernel under WASM SIMD; it must return the exact +// limbs of v * v, not just the same residue, on coarse [0, 2p) lanes and boundary values alike. +template void expect_sqr_limbs_match_self_mul() +{ + using F = typename VecT::Field; + const F neg_one = -F::one(); + const auto two_p_minus_one = F::modulus + F::modulus - bb::numeric::uint256_t(1); + const F raw_p(F::modulus.data[0], F::modulus.data[1], F::modulus.data[2], F::modulus.data[3]); + const F raw_two_p_minus_one( + two_p_minus_one.data[0], two_p_minus_one.data[1], two_p_minus_one.data[2], two_p_minus_one.data[3]); + + std::vector inputs{ VecT(std::array{ F::zero(), F::one(), neg_one, raw_p, raw_two_p_minus_one }), + VecT(std::array{ raw_two_p_minus_one, raw_p, neg_one, F::one(), F::zero() }) }; + for (int trial = 0; trial < 256; ++trial) { + std::array a; + std::array b; + for (size_t i = 0; i < 5; ++i) { + a[i] = F::random_element(); + b[i] = F::random_element(); + } + inputs.push_back(VecT(a) + VecT(b)); + } + + const auto expect_same_limbs = [](const std::array& expected, const std::array& got) { + for (size_t i = 0; i < 5; ++i) { + EXPECT_EQ(std::memcmp(expected[i].data, got[i].data, sizeof(expected[i].data)), 0) << "lane " << i; + } + }; + for (const VecT& v : inputs) { + const auto expected = (v * v).to_array(); + expect_same_limbs(expected, v.sqr().to_array()); + VecT self = v; + self.self_sqr(); + expect_same_limbs(expected, self.to_array()); + if constexpr (bb::vector_field_simd_enabled) { + expect_same_limbs(expected, v.sqr_for_affine().to_array()); + } + } +} + +} // namespace + +TEST(VectorFieldTest, SqrLimbsMatchSelfMul) +{ + expect_sqr_limbs_match_self_mul>(); +} + +TEST(VectorFieldFqTest, SqrLimbsMatchSelfMul) +{ + expect_sqr_limbs_match_self_mul>(); +} diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_wasm.cpp b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_wasm.cpp index b7522ce..befc74b 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_wasm.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_wasm.cpp @@ -1,10 +1,10 @@ -// Out-of-line explicit specializations of `VectorField::operator*` for -// WASM. Compiled as a separate TU so LLVM emits each per-Params specialization -// as a standalone function (not inlined into callers), giving it the same -// register-allocation scope the gist's hand-written WAT function gets — -// inlining across ~2400 lines of carefully ordered ops lets LLVM's instruction -// scheduler re-coalesce locals and recreate the stream-reorder problem the -// asm barriers solve. +// Out-of-line explicit specializations of `VectorField::operator*` and +// `VectorField::sqr` for WASM. Compiled as a separate TU so LLVM emits +// each per-Params specialization as a standalone function (not inlined into +// callers), giving it the same register-allocation scope the gist's +// hand-written WAT function gets — inlining across ~2400 lines of carefully +// ordered ops lets LLVM's instruction scheduler re-coalesce locals and recreate +// the stream-reorder problem the asm barriers solve. // // The kernel body is hand-maintained (no generator script) in // vector_field_mont_mul_body.inl.hpp and #included once per specialization @@ -12,7 +12,8 @@ // BB_VF_KARATSUBA_STAGES_1_4, BB_VF_RUN_STAGES_6_THROUGH_10) reference // unqualified R_INV_WASM, P_WASM, R_INV_MOD_2_29 — these resolve in the // enclosing class scope to whichever Params constants the specialization -// was bound to. +// was bound to. The squaring body, vector_field_mont_sqr_body.inl.hpp, swaps +// the first two for BB_VF_LOAD_SQR_LIMBS and BB_VF_KARATSUBA_SQR_STAGES_1_4. #include "barretenberg/ecc/curves/bn254/fq.hpp" #include "barretenberg/ecc/curves/bn254/fr.hpp" @@ -331,6 +332,233 @@ namespace bb { const v128_t qri0 = (RIGHT).quad_data[0], qri1 = (RIGHT).quad_data[1], qri2 = (RIGHT).quad_data[2], \ qri3 = (RIGHT).quad_data[3], qri4 = (RIGHT).quad_data[4], qri5 = (RIGHT).quad_data[5], \ qri6 = (RIGHT).quad_data[6], qri7 = (RIGHT).quad_data[7], qri8 = (RIGHT).quad_data[8] + +// Load the 9-scalar-limb + 9-quad-limb single operand used by +// BB_VF_KARATSUBA_SQR_STAGES_1_4. +#define BB_VF_LOAD_SQR_LIMBS(SRC) \ + const uint64_t sl0 = (SRC).scalar_data[0], sl1 = (SRC).scalar_data[1], sl2 = (SRC).scalar_data[2], \ + sl3 = (SRC).scalar_data[3], sl4 = (SRC).scalar_data[4], sl5 = (SRC).scalar_data[5], \ + sl6 = (SRC).scalar_data[6], sl7 = (SRC).scalar_data[7], sl8 = (SRC).scalar_data[8]; \ + const v128_t ql0 = (SRC).quad_data[0], ql1 = (SRC).quad_data[1], ql2 = (SRC).quad_data[2], \ + ql3 = (SRC).quad_data[3], ql4 = (SRC).quad_data[4], ql5 = (SRC).quad_data[5], \ + ql6 = (SRC).quad_data[6], ql7 = (SRC).quad_data[7], ql8 = (SRC).quad_data[8] + +// ===================================================================== +// Squaring counterpart of BB_VF_KARATSUBA_STAGES_1_4 over the single operand +// `sl0..sl8` / `ql0..ql8`, producing the same pl*, ph*, pc* columns that the +// multiply produces for identical operands, in 39 muls per lane instead of 66. +// +// With the same 5 + 4 split, all three partial products are squares +// (P_lo = a_lo^2, P_hi = a_hi^2, P_cross = s^2 with s = a_lo + a_hi), so each +// off-diagonal pair is one product against a doubled limb: 15 + 10 + 15 muls. +// Two P_cross columns are not needed as such: pc8 = s4^2 = a4^2 = pl8 cancels +// in stage 5, and pc7 enters only as pc7 - pl7 = 2 a4 (s3 - a3) = a8 * 2 a4, +// emitted directly as pm7. That leaves 39. +// +// Bit-identity with operator*: in Z/2^64, sum_{i+j=k} x_i x_j equals +// sum_{i VectorField::operator*(const VectorFie #include "barretenberg/ecc/fields/vector_field_mont_mul_body.inl.hpp" } +// sqr specializations: same per-Params stamping as operator*, over the +// squaring kernel in vector_field_mont_sqr_body.inl.hpp. +template <> VectorField VectorField::sqr() const noexcept +{ +#include "barretenberg/ecc/fields/vector_field_mont_sqr_body.inl.hpp" +} + +template <> VectorField VectorField::sqr() const noexcept +{ +#include "barretenberg/ecc/fields/vector_field_mont_sqr_body.inl.hpp" +} + #undef BB_VF_RUN_STAGES_6_THROUGH_10 +#undef BB_VF_KARATSUBA_SQR_STAGES_1_4 #undef BB_VF_KARATSUBA_STAGES_1_4 +#undef BB_VF_LOAD_SQR_LIMBS #undef BB_VF_LOAD_LIMBS } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ecc/groups/affine_add_packed.hpp b/barretenberg/cpp/src/barretenberg/ecc/groups/affine_add_packed.hpp index 1286261..6ee9c36 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/groups/affine_add_packed.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/groups/affine_add_packed.hpp @@ -11,6 +11,27 @@ namespace bb::group_elements { +#if BB_VECTOR_FIELD_SIMD +namespace detail { +// Keep scalar tails and Fr packed arithmetic on the original multiply. +template +[[gnu::always_inline]] inline Value affine_add_square(const Value& value) noexcept +{ + return value * value; +} + +template +[[gnu::always_inline]] inline VectorField affine_add_square(const VectorField& value) noexcept +{ + if constexpr (std::is_same_v) { + return value.sqr_for_affine(); + } else { + return value * value; + } +} +} // namespace detail +#endif + // Scratch buffers for batch_affine_add, one VectorFieldPushSpan each: the per-element denominators // dx = x2 - x1, numerators dy = y2 - y1, coordinate sums xsum = x1 + x2, and inverted denominators // inv. All four must be distinct from one another and from the point spans, and inv must not alias dx @@ -62,7 +83,11 @@ inline void batch_affine_add(const VectorAffineElementPushSpan& lhs, out.y, [](const auto& x1, const auto& y1, const auto& dy, const auto& inv, const auto& xsum, auto& ox, auto& oy) { auto slope = dy * inv; +#if BB_VECTOR_FIELD_SIMD + auto x3 = detail::affine_add_square(slope) - xsum; +#else auto x3 = slope * slope - xsum; +#endif auto y3 = slope * (x1 - x3) - y1; ox = x3; oy = y3; diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp index 90d14a0..6b820fc 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp @@ -279,6 +279,9 @@ void pippenger_round_parallel_batched(std::span CONCURRENT_MIN_MEMBERS && max_large_n <= total_large_n / pool_width; + // The rollup stack's evolution of the shared concurrent-chunk path (few_wide_members, chunks to whole pool + // rounds, one arena block per worker), kept in the merge over the AVM leader's earlier gate (many balanced + // members only). Measured on the merged build: AVM's proving was not slower with it. const bool few_wide_members = (3 * pool_width) >= (8 * large_members.size()) && min_chunks >= pool_width; const bool large_members_concurrent = pool_width >= CONCURRENT_MIN_POOL_WIDTH && !large_members.empty() && (many_balanced_members || few_wide_members) && scalar_spans_disjoint(); @@ -488,37 +491,69 @@ void pippenger_round_parallel_batched(std::span(1, aggregate_arena_budget / small_arena_bytes) : std::numeric_limits::max(); const size_t num_workers = std::min({ pool_width, small_members.size(), workers_by_budget }); - std::unique_ptr small_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) - if (small_arena_bytes > 0) { - small_arena_owner = std::make_unique_for_overwrite( - num_workers * small_arena_bytes); // NOLINT(cppcoreguidelines-avoid-c-arrays) +#ifdef __wasm__ + // When the budget, not the member count, leaves at most half the pool busy, run the members one at a + // time across the whole pool instead. Only if every member's full-width arena fits in the block the + // pool would allocate, so the one arena allocated in its place is never larger. + bool run_full_width = + workers_by_budget < std::min(pool_width, small_members.size()) && 2 * workers_by_budget <= pool_width; + size_t full_width_arena_bytes = 0; + for (size_t s = 0; run_full_width && s < small_members.size(); ++s) { + const size_t m = small_members[s]; + const bool ext_glv = !external_glv_for(m, n_input[m]).empty(); + const size_t bytes = compute_arena_bytes_for_msm(n_input[m], ext_glv, info_for(m)); + run_full_width = bytes <= num_workers * small_arena_bytes; + full_width_arena_bytes = std::max(full_width_arena_bytes, bytes); } - // A block this large is normally mapped on its own, so its free unmaps every resident page on this thread. The - // workers discard their slices' interior pages first, which leaves that free little to unmap. glibc still - // serves the block from the heap when free heap space holds it; the next allocation there then faults the - // discarded pages back in. The floor is release_pages_in_parallel's. - const bool release_slices = num_workers * small_arena_bytes >= (size_t{ 64 } << 20); - std::atomic next_member{ 0 }; - bb::parallel_for(num_workers, [&](size_t tid) { - std::span worker_arena; - if (small_arena_bytes > 0) { - worker_arena = { small_arena_owner.get() + (tid * small_arena_bytes), small_arena_bytes }; + if (run_full_width) { + std::unique_ptr full_width_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) + std::span full_width_arena; + if (full_width_arena_bytes > 0) { + full_width_arena_owner = std::make_unique_for_overwrite( + full_width_arena_bytes); // NOLINT(cppcoreguidelines-avoid-c-arrays) + full_width_arena = std::span(full_width_arena_owner.get(), full_width_arena_bytes); } - while (true) { - const size_t s = next_member.fetch_add(1, std::memory_order_relaxed); - if (s >= small_members.size()) { - break; - } - const size_t m = small_members[s]; + for (size_t m : small_members) { const size_t n = n_input[m]; PolynomialSpan sp(0, std::span(scalar_arrays[m].data(), n)); out_results[m] = pippenger_round_parallel( - sp, point_arrays[m], info_for(m), external_glv_for(m, n), worker_arena, /*max_threads=*/1); + sp, point_arrays[m], info_for(m), external_glv_for(m, n), full_width_arena); } - if (release_slices) { - round_parallel_detail::release_arena_slice(worker_arena); + } else +#endif + { + std::unique_ptr small_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) + if (small_arena_bytes > 0) { + small_arena_owner = std::make_unique_for_overwrite( + num_workers * small_arena_bytes); // NOLINT(cppcoreguidelines-avoid-c-arrays) } - }); + // A block this large is normally mapped on its own, so its free unmaps every resident page on this + // thread. The workers discard their slices' interior pages first, which leaves that free little to unmap. + // glibc still serves the block from the heap when free heap space holds it; the next allocation there + // then faults the discarded pages back in. The floor is release_pages_in_parallel's. + const bool release_slices = num_workers * small_arena_bytes >= (size_t{ 64 } << 20); + std::atomic next_member{ 0 }; + bb::parallel_for(num_workers, [&](size_t tid) { + std::span worker_arena; + if (small_arena_bytes > 0) { + worker_arena = { small_arena_owner.get() + (tid * small_arena_bytes), small_arena_bytes }; + } + while (true) { + const size_t s = next_member.fetch_add(1, std::memory_order_relaxed); + if (s >= small_members.size()) { + break; + } + const size_t m = small_members[s]; + const size_t n = n_input[m]; + PolynomialSpan sp(0, std::span(scalar_arrays[m].data(), n)); + out_results[m] = pippenger_round_parallel( + sp, point_arrays[m], info_for(m), external_glv_for(m, n), worker_arena, /*max_threads=*/1); + } + if (release_slices) { + round_parallel_detail::release_arena_slice(worker_arena); + } + }); + } } if (large_members_concurrent) { diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched_full_width.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched_full_width.test.cpp new file mode 100644 index 0000000..f9ca6ff --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched_full_width.test.cpp @@ -0,0 +1,166 @@ +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/bn254/bn254.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include "barretenberg/ecc/scalar_multiplication/pippenger_arena_layout.hpp" +#include "barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include +#include + +using namespace bb; + +namespace { +auto& engine = numeric::get_randomness(); + +class ConcurrencyScope { + size_t prev_; + + public: + explicit ConcurrencyScope(size_t n) + : prev_(bb::get_num_cpus()) + { + bb::set_parallel_for_concurrency(n); + } + ~ConcurrencyScope() { bb::set_parallel_for_concurrency(prev_); } + ConcurrencyScope(const ConcurrencyScope&) = delete; + ConcurrencyScope& operator=(const ConcurrencyScope&) = delete; + ConcurrencyScope(ConcurrencyScope&&) = delete; + ConcurrencyScope& operator=(ConcurrencyScope&&) = delete; +}; +} // namespace + +/** + * @brief Batches whose small members have single-thread arenas large enough that the memory budget, not the + * member count, caps the concurrent pool. On wasm, at a pool width where that cap leaves at most half the + * pool busy, the driver runs those members one at a time at full width; at narrower widths it keeps the + * pool. Every width must return the same commitments. + */ +template class PippengerBatchedFullWidthTest : public ::testing::Test { + public: + using Element = typename Curve::Element; + using AffineElement = typename Curve::AffineElement; + using ScalarField = typename Curve::ScalarField; + + static constexpr size_t kSmallN = scalar_multiplication::SMALL_MSM_BATCH_THRESHOLD; + // One member above the small-member bound keeps the sequential large-member path in the same batch. + static constexpr size_t kNumPoints = kSmallN + 1024; + static constexpr size_t kWidePool = 8; + + // points[i] = G * dlogs[i], so each expected MSM is one scalar multiplication of G. + static inline std::vector dlogs{}; + static inline std::vector points{}; + + static void SetUpTestSuite() + { + dlogs.resize(kNumPoints); + for (auto& d : dlogs) { + d = ScalarField::random_element(&engine); + } + points.resize(kNumPoints); + parallel_for_range(kNumPoints, [&](size_t start, size_t end) { + for (size_t i = start; i < end; ++i) { + points[i] = AffineElement(Curve::Group::one * dlogs[i]); + } + }); + } + + struct Batch { + std::vector> scalars; + std::vector dedup_infos; + std::vector expected; + }; + + // Dense members near the bound, a dedup-hinted member of repeated scalars, a member sparse enough to fall to + // the compacting fallback at full width, an all-zero member, and one member above the bound. + static Batch make_batch() + { + Batch b; + auto add = [&](size_t n, uint32_t dedup_info, auto&& scalar_at) { + std::vector s(n); + ScalarField acc = ScalarField::zero(); + for (size_t i = 0; i < n; ++i) { + s[i] = scalar_at(i); + acc += s[i] * dlogs[i]; + } + b.scalars.push_back(std::move(s)); + b.dedup_infos.push_back(dedup_info); + b.expected.push_back(AffineElement(Curve::Group::one * acc)); + }; + auto random = [](size_t) { return ScalarField::random_element(&engine); }; + for (size_t k = 0; k < 8; ++k) { + add(kSmallN - (61 * k), 0, random); + } + const uint256_t high_bit(0, 0, 0, uint64_t{ 1 } << (200 - 192)); + add(kSmallN - 500, 1, [&](size_t i) { return ScalarField(high_bit + uint256_t((i / 8) + 1)); }); + add(kSmallN, 0, [&](size_t i) { return (i % 137 == 0) ? random(i) : ScalarField::zero(); }); + add(kSmallN / 2, 0, [](size_t) { return ScalarField::zero(); }); + add(kNumPoints, 0, random); + return b; + } + + static std::vector run(Batch& b) + { + std::vector> spans; + for (auto& s : b.scalars) { + spans.emplace_back(0, std::span(s)); + } + return scalar_multiplication::MSM_fast::batch_multi_scalar_mul( + points, spans, /*handle_edge_cases=*/false, b.dedup_infos); + } + + // Mirrors the driver's arena sizing for this batch's small members (one shared-SRS group, so GLV follows the + // group's largest member), so a sizer change that stops the batch from reaching the full-width path fails here + // instead of silently testing only the pool. The sizer is instantiated for BN254 only; Grumpkin's field and + // point sizes are the same. + static void expect_wide_pool_runs_full_width(const Batch& b) + { + ConcurrencyScope scope(kWidePool); + const bool ext_glv = kNumPoints <= scalar_multiplication::round_parallel_detail::GLV_SMALL_N_THRESHOLD; + size_t small_count = 0; + size_t pool_arena = 0; + size_t full_width_arena = 0; + for (size_t m = 0; m < b.scalars.size(); ++m) { + const size_t n = b.scalars[m].size(); + if (n > kSmallN) { + continue; + } + ++small_count; + const bool dd = b.dedup_infos[m] != 0; + pool_arena = + std::max(pool_arena, scalar_multiplication::compute_arena_bytes_for_msm(n, ext_glv, dd, 1)); + full_width_arena = + std::max(full_width_arena, scalar_multiplication::compute_arena_bytes_for_msm(n, ext_glv, dd)); + } + ASSERT_GT(pool_arena, size_t{ 0 }); + const size_t workers_by_budget = + std::max(1, scalar_multiplication::round_parallel_detail::BATCH_MEM_BUDGET / pool_arena); + EXPECT_LT(workers_by_budget, std::min(kWidePool, small_count)); + EXPECT_LE(2 * workers_by_budget, kWidePool); + EXPECT_LE(full_width_arena, workers_by_budget * pool_arena); + } +}; + +using CurveTypes = ::testing::Types; +TYPED_TEST_SUITE(PippengerBatchedFullWidthTest, CurveTypes); + +TYPED_TEST(PippengerBatchedFullWidthTest, SameCommitmentsAtEveryPoolWidth) +{ + auto batch = TestFixture::make_batch(); +#ifdef __wasm__ + if constexpr (std::is_same_v) { + TestFixture::expect_wide_pool_runs_full_width(batch); + } +#endif + // On wasm, width 1 has no concurrent pool; at 8 (asserted above) and at any other width where the rule holds the + // members run at full width, and elsewhere the pool runs. + for (const size_t width : { size_t{ 1 }, size_t{ 2 }, size_t{ 4 }, size_t{ 8 }, size_t{ 16 } }) { + ConcurrencyScope scope(width); + const auto result = TestFixture::run(batch); + ASSERT_EQ(result.size(), batch.expected.size()); + for (size_t m = 0; m < result.size(); ++m) { + EXPECT_EQ(result[m], batch.expected[m]) + << "pool width " << width << ", member " << m << " (n=" << batch.scalars[m].size() << ")"; + } + } +} diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.hpp index 9df6ed4..81ba4f5 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.hpp @@ -36,6 +36,14 @@ namespace bb::scalar_multiplication::round_parallel_detail { +// A Booth window starts reading at bit_base - 1. Equality must remain live: +// a scalar whose highest bit is that lookback bit can produce a carry digit. +// maximum_bit_length excludes inactive/zero scalars and is at most 254 (128 for GLV). +[[nodiscard]] constexpr bool window_above_scalar_bits(uint16_t maximum_bit_length, size_t bit_base) noexcept +{ + return maximum_bit_length < bit_base; +} + // Bring the shared signed-Booth slice primitive (from ecc/groups/booth_recode.hpp) into // this namespace so the MSM-specific readers below can call it unqualified. The same // primitive is also used by the GLV-endo straus path in element_impl.hpp; only the diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.test.cpp index 88a2ad4..71aa30a 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_constantine.test.cpp @@ -446,3 +446,9 @@ TEST(PippengerConstantine, ParamClassifierU64U32Consistency) } } } + +#include "pippenger_window_skip.test.hpp" +TEST(PippengerConstantine, WindowBlockSkipPreservesNonzeroDigits) +{ + EXPECT_EQ((bb::test::check_msm_window_skip()), 0U); +} diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_window_skip.test.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_window_skip.test.hpp new file mode 100644 index 0000000..83f5f27 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_window_skip.test.hpp @@ -0,0 +1,179 @@ +#pragma once +#include +#include +#include +#include + +namespace bb::test { +namespace window_skip_test { +namespace rec = bb::scalar_multiplication::round_parallel_detail; +using Scalar = std::array; +inline std::array counters{}; +inline uint16_t bit_length(const Scalar& s) +{ + for (size_t b = 254; b != 0; --b) { + if (((s[(b - 1) / 64] >> ((b - 1) % 64)) & 1) != 0) { return static_cast(b); } + } + return 0; +} +inline uint32_t reference(const Scalar& s, size_t base, size_t width) +{ + uint32_t raw = 0; + for (size_t k = 0; k <= width; ++k) { + const int64_t bit = static_cast(base + k) - 1; + if (bit >= 0 && bit < 256) { + raw |= static_cast((s[static_cast(bit) / 64] >> (bit % 64)) & 1) << k; + } + } + const uint32_t sign = (raw >> width) & 1; + const uint32_t mask = (uint32_t(1) << width) - 1; + return (sign << 31) | (((((raw + 1) >> 1) - sign) ^ (0U - sign)) & mask); +} +inline uint32_t scalar_digit(const Scalar& s, size_t base, size_t width) +{ + const auto p = rec::compute_constantine_slice_params(base, width, 4); + return rec::get_constantine_packed_digit(s.data(), p.lo_limb, p.hi_limb, p.lo_off, p.lo_bits, + p.lo_mask, p.hi_mask, p.slice_localised_to_one_u64, width); +} +inline void quad_digits(const Scalar* s, size_t base, size_t width, uint32_t* out) +{ + const auto p = rec::compute_constantine_slice_params_u32(base, width, 8); + const auto w = static_cast(width); + const rec::SimdU32x4 lo{ p.lo_mask, p.lo_mask, p.lo_mask, p.lo_mask }; + const rec::SimdU32x4 hi{ p.hi_mask, p.hi_mask, p.hi_mask, p.hi_mask }; + const rec::SimdU32x4 one{ 1, 1, 1, 1 }; + const uint32_t m = (uint32_t(1) << width) - 1; + const rec::SimdU32x4 mask{ m, m, m, m }; + const auto* a = reinterpret_cast(s[0].data()); + const auto* b = reinterpret_cast(s[1].data()); + const auto* c = reinterpret_cast(s[2].data()); + const auto* d = reinterpret_cast(s[3].data()); + switch (rec::classify_slice_path_u32(p)) { + case rec::ConstantineSlicePath::Localised: + rec::store_constantine_packed_digits_x4_localised(out,a,b,c,d,p.lo_limb,p.lo_off,lo,one,mask,w); break; + case rec::ConstantineSlicePath::Bottom: + rec::store_constantine_packed_digits_x4_bottom(out,a,b,c,d,p.hi_limb,p.lo_bits,hi,one,mask,w); break; + case rec::ConstantineSlicePath::Boundary: + rec::store_constantine_packed_digits_x4_boundary(out,a,b,c,d,p.lo_limb,p.hi_limb,p.lo_off,p.lo_bits,lo,hi,one,mask,w); break; + } +} +inline bool skip(uint16_t bits, size_t base) +{ +#ifdef MSM_SKIP_TEST_BASELINE + (void)bits; (void)base; + return false; +#else + return rec::window_above_scalar_bits(bits, base); +#endif +} +} // namespace window_skip_test + +template uint32_t check_msm_window_skip() +{ + using namespace window_skip_test; + counters.fill(0); + // Exact Booth lookback equality: highest bit base-1 must NOT be skipped. + for (size_t bits = 1; bits <= 254; ++bits) { + Scalar s{}; s[(bits - 1) / 64] = uint64_t(1) << ((bits - 1) % 64); + for (size_t width = 1; width <= 19; ++width) { + for (const size_t base : { bits - 1, bits, std::min(255, bits + 1) }) { + const uint32_t want = reference(s, base, width); + const uint32_t got = scalar_digit(s, base, width); + if (got != want) { return 1; } + if constexpr (EnableSkip) { + if (skip(static_cast(bits), base) && (want & 0x7fffffffU) != 0) { return 2; } +#ifndef MSM_SKIP_TEST_BASELINE + if (base == bits && skip(static_cast(bits), base)) { return 3; } +#endif + } + ++counters[0]; + } + } + } + std::array scalars{}; + std::array msbs{}; + std::array active{}; + std::array out_base{}; + uint32_t hash = 2166136261U; + for (const size_t origin : { size_t(0), size_t(17) }) { + for (const size_t length : {size_t(0),size_t(1),size_t(63),size_t(64),size_t(65),size_t(127),size_t(129),size_t(2047),size_t(2048),size_t(2049)}) { + const size_t n = origin + length; + for (unsigned pattern = 0; pattern < 7; ++pattern) { + for (unsigned membership = 0; membership < 3; ++membership) { + for (size_t i = origin; i < n; ++i) { + Scalar s{}; + if (pattern != 0) { s[0] = 1 + i * 17; } + if (pattern == 2 || (pattern == 1 && i - origin < 4)) { + s[1] = 0x9e3779b97f4a7c15ULL ^ i; s[2] = 0x123456789abcdefULL; s[3] = uint64_t(1) << 61; + } + if (pattern == 3) { s = {}; s[(i % 254) / 64] = uint64_t(1) << (i % 254); } + if (pattern == 4) { s[1] = (uint64_t(1) << 63) | i; } // GLV-width components. + if (pattern == 5 && i % 2 == 0) { s = {}; } + if (pattern == 6 && i % 64 == 0) { s[3] = uint64_t(1) << 61; } + scalars[i] = s; + const uint16_t bits = bit_length(s); + msbs[i] = bits == 0 ? uint8_t(255) : static_cast(bits - 1); + const bool excluded = membership == 1 ? i % 2 == 0 : membership == 2 && i % 64 == 0; + active[i] = bits != 0 && !excluded; + out_base[i] = membership == 2 && i % 7 == 0 ? (0x40000000U | static_cast(i)) : static_cast(i); + } + for (const size_t stride : {size_t(1),size_t(5),size_t(13),size_t(19)}) { + for (size_t base = 0; base < 254; base += stride) { + const size_t width = std::min(stride, size_t(254) - base); + for (size_t tile = origin; tile < n; tile += 2048) { + const size_t end = std::min(n, tile + 2048); + std::array masks{}; + std::array bits{}; + for (size_t i = tile; i < end; ++i) { + masks[(i-tile)/64] |= uint64_t(active[i]) << ((i-tile)%64); + if (active[i]) { bits[(i-tile)/64] = std::max(bits[(i-tile)/64], uint16_t(msbs[i]+1)); } + } + size_t i = tile; + while (i + 64 <= end) { + const size_t block = (i-tile)/64; + uint64_t fresh = 0; + for (size_t k = 0; k < 64; ++k) { fresh |= uint64_t(active[i+k]) << k; } + if (fresh != masks[block]) { return 4; } + const bool omitted = masks[block] == 0 || (EnableSkip && skip(bits[block], base)); + std::array packed{}; + if (!omitted) { + for (size_t k = 0; k < 64; k += 4) { quad_digits(&scalars[i+k], base, width, packed.data()+k); } + ++counters[2]; + } else { ++counters[3]; } + for (size_t k = 0; k < 64; ++k) { + if (!active[i+k]) { continue; } + const uint32_t want = reference(scalars[i+k], base, width); + if (omitted ? (want & 0x7fffffffU) != 0 : packed[k] != want) { return 5; } + if ((want & 0x7fffffffU) != 0) { + hash = (hash ^ want) * 16777619U; + hash = (hash ^ out_base[i+k]) * 16777619U; + ++counters[4]; + } + } + i += 64; + } + for (; i < end; ++i) { + if (!active[i]) { continue; } + const uint32_t want = reference(scalars[i], base, width); + const bool omitted = EnableSkip && skip(uint16_t(msbs[i]+1), base); + if (omitted ? (want & 0x7fffffffU) != 0 : scalar_digit(scalars[i], base, width) != want) { return 6; } + if ((want & 0x7fffffffU) != 0) { + hash = (hash ^ want) * 16777619U; + hash = (hash ^ out_base[i]) * 16777619U; + ++counters[4]; + } + ++counters[5]; + } + } + ++counters[1]; + } + } + } + } + } + } + counters[6] = hash; + counters[7] = 1; + return 0; +} +} // namespace bb::test diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.cpp index b13df72..de43fea 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.cpp @@ -646,6 +646,104 @@ void merge_overflow(ThreadScratch& s, typename Curve::AffineElement* dst_ s.overflow_len = 0; } +#ifdef __wasm_simd128__ +/** + * @brief Gather the first reduction level directly into the existing packed affine-add queue. + * + * This is the WASM counterpart of the native IFMA first-level gather fusion: original and dedup + * points remain outside curr_pts, so a queue drain cannot overwrite a pending source. Pair order, + * queue boundaries and singleton positions match compacting all inputs before the first level. + */ +template +void reduce_chunk_packed_first_level(ThreadScratch& s, + const uint32_t* schedule, + const size_t* bucket_start, + size_t chunk_lo, + size_t chunk_hi, + size_t& bucket_cursor, + size_t chunk_bucket_hi, + std::span points, + std::span dedup_extra_points) noexcept +{ + using AffineElement = typename Curve::AffineElement; + // Stage 6b reuses these spans and can leave nonzero cursors. Rewind before the first push, + // including chunks that eventually contain only singletons or skipped entries. + s.lhs.reset(); + s.rhs.reset(); + size_t next_len = 0; + size_t pair_count = 0; + bool made_pair = false; + size_t bucket = bucket_cursor; + size_t pos = chunk_lo; + while (bucket <= chunk_bucket_hi && pos < chunk_hi) { + const size_t run_lo = std::max(pos, bucket_start[bucket]); + const size_t run_hi = std::min(chunk_hi, bucket_start[bucket + 1]); + if (run_lo >= run_hi) { + ++bucket; + continue; + } + + const uint32_t bucket_u32 = static_cast(bucket); + const AffineElement* pending = nullptr; + bool pending_neg = false; + for (size_t i = run_lo; i < run_hi; ++i) { + if (i + GATHER_PREFETCH_DIST < chunk_hi) { + const size_t pf_idx = + std::min(schedule[i + GATHER_PREFETCH_DIST] & SCHEDULE_INDEX_MASK, points.size() - 1); + __builtin_prefetch(points.data() + pf_idx, 0, 3); + } + const uint32_t e = schedule[i]; + if ((e & DEDUP_SKIP_BIT) != 0) { + continue; + } + const uint32_t raw_idx = e & SCHEDULE_INDEX_MASK; + const bool neg = (e & SCHEDULE_SIGN_BIT) != 0; + const auto& point = (e & DEDUP_REDIRECT_BIT) != 0 ? dedup_extra_points[raw_idx] : points[raw_idx]; + if (pending == nullptr) { + pending = &point; + pending_neg = neg; + continue; + } + + // push_point copies its arguments immediately, including a negated temporary. + // Keep the old lhs/rhs order and the same field negation before SIMD packing. + s.lhs.push_point(pending->x, pending_neg ? -pending->y : pending->y); + s.rhs.push_point(point.x, neg ? -point.y : point.y); + s.curr_buckets[next_len] = bucket_u32; + s.pair_dest[pair_count] = static_cast(next_len); + ++next_len; + ++pair_count; + made_pair = true; + pending = nullptr; + if (pair_count >= BATCH_CAPACITY) { + drain_batch(s, pair_count); + pair_count = 0; + } + } + if (pending != nullptr) { + auto& dst = s.curr_pts[next_len]; + copy_affine64(dst, *pending); + if (pending_neg) { + dst.y = -dst.y; + } + s.curr_buckets[next_len] = bucket_u32; + ++next_len; + } + pos = run_hi; + if (pos < chunk_hi) { + ++bucket; + } + } + bucket_cursor = bucket; + drain_batch(s, pair_count); + if (made_pair) { + tree_reduce_in_place(s, next_len); + } else { + s.result_len = next_len; + } +} +#endif + /** * @brief Tree-reduce one thread's bucket-aligned slice of the bucket-partitioned schedule into the * deduplicated (point, digit) list in `curr_pts / curr_buckets`, which the caller scatters into @@ -671,6 +769,14 @@ void reduce_chunk(ThreadScratch& s, BB_ASSERT_LTE(chunk_len, s.curr_pts.size()); static_assert(BATCH_CAPACITY <= 4096, "BATCH_CAPACITY must fit in pair_dest scratch"); +#ifdef __wasm_simd128__ + if constexpr (bb::simd_available_v) { + reduce_chunk_packed_first_level( + s, schedule, bucket_start, chunk_lo, chunk_hi, bucket_cursor, chunk_bucket_hi, points, dedup_extra_points); + return; + } +#endif + // Compact entries while loading: dedup non-rep entries (DEDUP_SKIP_BIT set in the // schedule entry) carry no contribution — their points are already accumulated // into the cluster's combined `extra_points[cid]` emitted at the rep's slot. Skip @@ -1757,10 +1863,15 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan k1{ 0, 0 }; + std::array k2{ 0, 0 }; + if (!input_scalars[i].is_zero()) { + const ScalarField canonical = input_scalars[i].from_montgomery_form_reduced(); + const auto split = ScalarField::split_into_endomorphism_scalars(canonical); + k1 = split.first; + k2 = split.second; + } glv_scalars_storage[2 * i].data[0] = k1[0]; glv_scalars_storage[2 * i].data[1] = k1[1]; glv_scalars_storage[2 * i].data[2] = 0; @@ -1788,7 +1899,13 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan uint64_t { + auto compute_include_mask = [&](size_t block_start, + [[maybe_unused]] uint16_t& block_bits) noexcept -> uint64_t { uint64_t include_mask = 0; for (size_t k = 0; k < SIMD_BATCH; ++k) { const size_t scalar_idx = block_start + k; @@ -2487,19 +2605,32 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan(include) << k; +#ifdef __wasm__ + if (include) { + block_bits = std::max(block_bits, static_cast(m + 1)); + } +#endif } return include_mask; }; size_t i = start; while (i + SIMD_BATCH <= end) { - const uint64_t include_mask = compute_include_mask(i); + [[maybe_unused]] uint16_t block_bits = 0; + const uint64_t include_mask = compute_include_mask(i, block_bits); if (include_mask == 0) { i += SIMD_BATCH; continue; } const bool all_included = include_mask == ~uint64_t{ 0 }; for (size_t w = 0; w < windows_in_batch; ++w) { +#ifdef __wasm__ + // Booth's lookback bit is bit_base - 1. Keep the equality case: + // a scalar with that bit set can still produce a nonzero carry digit. + if (round_parallel_detail::window_above_scalar_bits(block_bits, sched.bit_base[batch_start + w])) { + continue; + } +#endif fill_packed_digit_buffer(w, i, packed_buf.data()); uint32_t* my_counts = digit_cursors.data() + (((w * num_threads) + tid) * bucket_stride); if (all_included) { @@ -2534,6 +2665,11 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan(m + 1), sched.bit_base[batch_start + w])) { + continue; + } +#endif uint32_t* my_counts = digit_cursors.data() + (((w * num_threads) + tid) * bucket_stride); const round_parallel_detail::ConstantineSliceParams sp = slice_params[w]; const uint32_t window_bits_w = static_cast(per_window_bits[w]); @@ -2656,11 +2792,22 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan packed_buf{}; constexpr size_t STAGE4_SCALAR_TILE = 2048; std::array active_tile{}; +#ifdef __wasm__ + // Reuse each block's inclusion mask across all windows in this scalar tile. + // Active membership is independent of the window being decoded. + static_assert(STAGE4_SCALAR_TILE % SIMD_BATCH == 0); + std::array include_masks{}; + std::array block_bits{}; +#endif [[maybe_unused]] std::array out_base_tile{}; for (size_t tile_start = start; tile_start < end; tile_start += STAGE4_SCALAR_TILE) { const size_t tile_end = std::min(end, tile_start + STAGE4_SCALAR_TILE); const size_t tile_len = tile_end - tile_start; +#ifdef __wasm__ + include_masks.fill(0); + block_bits.fill(0); +#endif for (size_t j = 0; j < tile_len; ++j) { const size_t scalar_idx = tile_start + j; const uint8_t m = msb_per_scalar[scalar_idx]; @@ -2677,6 +2824,13 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan(include); +#ifdef __wasm__ + include_masks[j / SIMD_BATCH] |= static_cast(include) << (j % SIMD_BATCH); + if (include) { + block_bits[j / SIMD_BATCH] = + std::max(block_bits[j / SIMD_BATCH], static_cast(m + 1)); + } +#endif } for (size_t w = 0; w < windows_in_batch; ++w) { @@ -2686,10 +2840,18 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan(active_tile[rel + k]) << k; } +#endif if (include_mask == 0) { i += SIMD_BATCH; continue; @@ -2721,6 +2883,11 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan(msb_per_scalar[i] + 1), sched.bit_base[batch_start + w])) { + continue; + } +#endif const round_parallel_detail::ConstantineSliceParams sp = slice_params[w]; const uint32_t packed = round_parallel_detail::get_constantine_packed_digit( scalars[i].data, @@ -3283,7 +3450,10 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan class MultilinearBatchingFlavor_ { std::array non_shifted_evaluations; std::array shifted_evaluations; size_t circuit_size = 0; + // Set when log2(circuit_size) >= 2 and every claim challenge r satisfies |r| >= log2(circuit_size) with no + // r_j = 1. The sumcheck then runs MultilinearBatchingSumcheckProver on eq_suffix_tables, which hold + // eq(y, (r_1, .., r_{L-1})) · ∏_{j >= L} (1 - r_j) over the circuit_size / 2 points y, and polynomials.eq + // stays empty. Otherwise polynomials.eq holds the full eq tables for the generic sumcheck. + bool eq_factored = false; + std::array eq_suffix_tables; ProvingKey() = default; explicit ProvingKey(std::vector&& claims); diff --git a/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp b/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp index 9a4fb46..1171a9f 100644 --- a/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp @@ -44,6 +44,9 @@ void construct_lookup_table_polynomials(const RefArray void construct_lookup_read_counts(typename Flavor::Polynomial& read_counts, diff --git a/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp b/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp index 8988f40..b9a5676 100644 --- a/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp @@ -148,7 +148,14 @@ void compute_permutation_argument_polynomials(const typename Flavor::CircuitBuil for (size_t node_idx = 0; node_idx + 1 < cycle_size; ++node_idx) { const cycle_node& current = cycle[node_idx]; const cycle_node& next = cycle[node_idx + 1]; +#ifdef __wasm__ + // Phase 1 already constructed this exact identity. Only first nodes receive + // id tags below; next is a non-first node in this disjoint cycle, so no worker + // can modify its identity during this phase. + sigmas[current.wire_idx].at(current.gate_idx) = ids[next.wire_idx].at(next.gate_idx); +#else sigmas[current.wire_idx].at(current.gate_idx) = FF(next.gate_idx + (SEPARATOR * next.wire_idx)); +#endif } const uint32_t var_tag = real_variable_tags[cycle_idx]; diff --git a/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp b/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp index ed75285..fefe507 100644 --- a/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp @@ -11,6 +11,10 @@ #include "barretenberg/common/thread.hpp" #include "barretenberg/common/zip_view.hpp" #include "barretenberg/constants.hpp" +#if defined(__wasm_simd128__) +#include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/ecc/fields/vector_field.hpp" +#endif #include "barretenberg/flavor/flavor.hpp" #include "barretenberg/relations/permutation_relation.hpp" @@ -19,6 +23,54 @@ namespace bb { +#if defined(__wasm_simd128__) +namespace detail { +// Only the permutation term inputs are stored, rather than a whole SIMD flavor row. +template struct PackedGrandProductRow { + using EntityId = EntityId_; + std::array wires; + std::array ids; + std::array sigmas; + + auto& get_wires() { return wires; } + auto& get_ids() { return ids; } + auto& get_sigmas() { return sigmas; } + + const Vec& operator[](EntityId id) const + { + switch (id) { + case EntityId::w_l: + return wires[0]; + case EntityId::w_r: + return wires[1]; + case EntityId::w_o: + return wires[2]; + case EntityId::w_4: + return wires[3]; + case EntityId::id_1: + return ids[0]; + case EntityId::id_2: + return ids[1]; + case EntityId::id_3: + return ids[2]; + case EntityId::id_4: + return ids[3]; + case EntityId::sigma_1: + return sigmas[0]; + case EntityId::sigma_2: + return sigmas[1]; + case EntityId::sigma_3: + return sigmas[2]; + case EntityId::sigma_4: + return sigmas[3]; + default: + throw_or_abort("Unexpected grand-product packed-row input"); + } + } +}; +} // namespace detail +#endif + /** * @brief Compute a grand product polynomial, `grand_product_polynomial`, which for historical reasons is sometimes also * called Z_perm(X). This polynomial will bear witness to some subset of: {copy constraints, multiset-equality, public @@ -119,7 +171,53 @@ void compute_grand_product(typename Flavor::ProverPolynomials& full_polynomials, const size_t end = thread_data.end[thread_idx]; typename Flavor::AllValues row; uint32_t local_duplicates = 0; - for (size_t i = start; i < end; ++i) { + size_t i = start; +#if defined(__wasm_simd128__) + if constexpr (std::is_same_v && + std::is_same_v>) { + using Vec = VectorField; + // Reuse one row per worker, filling only the twelve entries read by the relation. + detail::PackedGrandProductRow packed_row; + struct PackedParameters { + using DataType = Vec; + Vec beta; + Vec gamma; + }; + const PackedParameters packed_parameters{ Vec(relation_parameters.beta), Vec(relation_parameters.gamma) }; + for (; end - i >= Vec::SIZE; i += Vec::SIZE) { + const size_t poly_idx = i + gp_start; + const auto load = [&](const auto& polynomial) { + const size_t first = polynomial.start_index(); + const size_t last = polynomial.end_index(); + if (poly_idx >= first && poly_idx <= last && Vec::SIZE <= last - poly_idx) { + return Vec(polynomial.data() + (poly_idx - first)); + } + return Vec::from_lanes([&](size_t lane) { return polynomial[poly_idx + lane]; }); + }; + for (auto [value, polynomial] : zip_view(packed_row.get_wires(), full_polynomials.get_wires())) { + value = load(polynomial); + } + for (auto [value, polynomial] : zip_view(packed_row.get_ids(), full_polynomials.get_ids())) { + value = load(polynomial); + } + for (auto [value, polynomial] : zip_view(packed_row.get_sigmas(), full_polynomials.get_sigmas())) { + value = load(polynomial); + } + const Vec num = + GrandProdRelation::template compute_grand_product_numerator(packed_row, packed_parameters); + const Vec den = + GrandProdRelation::template compute_grand_product_denominator(packed_row, packed_parameters); + num.store_to(&numerator.at(i)); + den.store_to(&denominator.at(i)); + if (count_duplicates) { + for (size_t lane = 0; lane < Vec::SIZE; ++lane) { + local_duplicates += static_cast(numerator[i + lane] == denominator[i + lane]); + } + } + } + } +#endif + for (; i < end; ++i) { const size_t poly_idx = i + gp_start; // TODO: consider avoiding get_row if possible. if constexpr (std::is_same_v>) { diff --git a/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_prover.cpp b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_prover.cpp index adf4cf9..bce081f 100644 --- a/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_prover.cpp @@ -8,8 +8,12 @@ #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/constexpr_utils.hpp" #include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/multilinear_batching/multilinear_batching_sumcheck.hpp" #include "barretenberg/sumcheck/sumcheck.hpp" +#include +#include + namespace bb { template @@ -24,6 +28,13 @@ MultilinearBatchingFlavor_::ProvingKey::ProvingKey(std::vector::VIRTUAL_LOG_N; const size_t log_circuit_size = bb::numeric::get_msb(circuit_size); + // The factored sumcheck divides by every 1 - r_j and needs at least two real rounds. Any other input builds the + // full eq tables as the generic sumcheck expects, including its handling of r_j = 1. + eq_factored = log_circuit_size >= 2 && std::ranges::all_of(claims, [&](const ProverClaim& claim) { + return claim.challenge.size() >= log_circuit_size && + std::ranges::none_of(claim.challenge, [](const FF& r) { return r == FF(1); }); + }); + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { auto& claim = claims[idx]; @@ -31,7 +42,12 @@ MultilinearBatchingFlavor_::ProvingKey::ProvingKey(std::vector::construct(claim.challenge, log_circuit_size); + if (eq_factored) { + eq_suffix_tables[idx] = ProverEqPolynomial::construct(std::span(claim.challenge).subspan(1), + log_circuit_size - 1); + } else { + polynomials.eq(idx) = ProverEqPolynomial::construct(claim.challenge, log_circuit_size); + } polynomials.claim_challenges[idx] = std::move(claim.challenge); non_shifted_evaluations[idx] = claim.non_shifted_evaluation; @@ -58,14 +74,20 @@ template void MultilinearBatchingProverInternal::execu const FF alpha = transcript->template get_challenge("Sumcheck:alpha"); RelationParameters relation_parameters; relation_parameters.compute_multilinear_batching_challenges(claim_batching_challenge, Flavor::NUM_CLAIMS); - Sumcheck sumcheck(key.circuit_size, - key.polynomials, - transcript, - alpha, - /*gate_challenges=*/{}, // No need for gate challenges, all the relations are linearly dependent - relation_parameters, - Flavor::VIRTUAL_LOG_N); - sumcheck_output = sumcheck.prove(); + if (key.eq_factored) { + MultilinearBatchingSumcheckProver sumcheck(key, transcript, alpha, relation_parameters); + sumcheck_output = sumcheck.prove(); + } else { + Sumcheck sumcheck( + key.circuit_size, + key.polynomials, + transcript, + alpha, + /*gate_challenges=*/{}, // No need for gate challenges, all the relations are linearly dependent + relation_parameters, + Flavor::VIRTUAL_LOG_N); + sumcheck_output = sumcheck.prove(); + } // Draw the merge challenge after the sumcheck's claimed evaluations are bound to the transcript, so that // the single opening of the combined accumulator commitment binds each P_i(r) individually. diff --git a/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.hpp b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.hpp new file mode 100644 index 0000000..5d4fb9b --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.hpp @@ -0,0 +1,311 @@ +// === AUDIT STATUS === +// internal: { status: not started, auditors: [], commit: } +// external_1: { status: not started, auditors: [], commit: } +// external_2: { status: not started, auditors: [], commit: } +// ===================== +#pragma once + +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/numeric/bitop/get_msb.hpp" +#include "barretenberg/polynomials/eq_polynomial.hpp" +#include "barretenberg/polynomials/fold_stride2.hpp" +#include "barretenberg/polynomials/univariate.hpp" +#include "barretenberg/relations/relation_parameters.hpp" +#include "barretenberg/sumcheck/sumcheck_output.hpp" + +#include +#include +#include +#include +#include + +namespace bb { + +/** + * @brief Sumcheck prover for the MultilinearBatching relation with each claim's eq polynomial kept in factored form. + * + * @details Write eq1(r, x) = (1 - r)(1 - x) + r·x and L = log2(n). After the challenges u_0, .., u_{k-1}, the eq table + * of claim i folded as SumcheckProver folds it is c_{i,k} · eq1(r_{i,k}, X) · E_{i,k}(y), where + * c_{i,k} = ∏_{j=L} (1 - r_{i,j}). + * The round univariate is therefore + * s_k(X) = Σ_i γ^i · c_{i,k} · eq1(r_{i,k}, X) · Σ_y E_{i,k}(y) · (P_i(X, y) + α · Q_i(X, y)), + * and P_i, Q_i are linear in X, so a round needs two sums per polynomial over its own backed rows instead of extending + * and multiplying eq, P and Q on every edge. Only E_{i,0} (n/2 entries, built by the proving key) is stored, since + * E_{i,k}(y) = E_{i,0}(y << k) · ∏_{1<=j<=k} (1 - r_{i,j})^{-1}. + * + * Every value is an exact field identity, so the sent univariates, the challenges and the claimed evaluations equal + * those of SumcheckProver on the same claims, at any thread count. The proving key selects this prover only + * when every 1 - r_{i,j} is invertible and L >= 2 (see ProvingKey::eq_factored). + */ +template class MultilinearBatchingSumcheckProver { + public: + using FF = typename Flavor::FF; + using Polynomial = typename Flavor::Polynomial; + using ProvingKey = typename Flavor::ProvingKey; + using Transcript = typename Flavor::Transcript; + using ClaimedEvaluations = typename Flavor::AllValues; + using RoundUnivariate = Univariate; + + static constexpr size_t NUM_CLAIMS = Flavor::NUM_CLAIMS; + static constexpr size_t NUM_TABLES = 2 * NUM_CLAIMS; + static constexpr size_t VIRTUAL_LOG_N = Flavor::VIRTUAL_LOG_N; + // The edge granularity of the generic FF sumcheck round (64 rows per chunk). + static constexpr size_t EDGES_PER_CHUNK = 32; + static_assert(Flavor::BATCHED_RELATION_PARTIAL_LENGTH == 3, "the round univariate is sent at X = 0, 1, 2"); + + // Per table t (P_i at t = 2i, Q_i at t = 2i + 1): the sums over y of E·f(2y) and of E·f(2y + 1). + using RoundSums = std::array; + + MultilinearBatchingSumcheckProver(ProvingKey& key, + std::shared_ptr transcript, + const FF& alpha, + const RelationParameters& relation_parameters) + : key(key) + , transcript(std::move(transcript)) + , alpha(alpha) + { + BB_ASSERT_EQ(relation_parameters.num_multilinear_batching_challenges, + NUM_CLAIMS, + "Incorrect number of computed multilinear batching challenges."); + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + gamma_powers[idx] = relation_parameters.multilinear_batching_challenges[idx]; + } + } + + SumcheckOutput prove() + { + vinfo("starting sumcheck rounds..."); + const size_t circuit_size = key.circuit_size; + BB_ASSERT(circuit_size != 0 && (circuit_size & (circuit_size - 1)) == 0, + "MultilinearBatchingSumcheckProver: circuit size must be a power of two"); + const size_t log_n = numeric::get_msb(circuit_size); + BB_ASSERT(key.eq_factored && log_n >= 2, + "MultilinearBatchingSumcheckProver: the key holds no eq-suffix tables"); + + const auto& claim_challenges = key.polynomials.claim_challenges; + std::vector challenge; + challenge.reserve(VIRTUAL_LOG_N); + + // inverses[idx * (log_n - 1) + j - 1] = (1 - r_{idx,j})^{-1} for 1 <= j < log_n. + std::vector inverses(NUM_CLAIMS * (log_n - 1)); + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + for (size_t j = 1; j < log_n; ++j) { + inverses[(idx * (log_n - 1)) + j - 1] = FF(1) - claim_challenges[idx][j]; + } + } + FF::batch_invert(inverses); + + // eq_prefix[idx] = c_{idx,k}; suffix_scale[idx] = ∏_{1<=j<=k} (1 - r_{idx,j})^{-1}. + std::array eq_prefix; + std::array suffix_scale; + eq_prefix.fill(FF(1)); + suffix_scale.fill(FF(1)); + + std::array tables; + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + tables[2 * idx] = &key.polynomials.non_shifted(idx); + tables[(2 * idx) + 1] = &key.polynomials.shifted(idx); + } + // Book-keeping tables of P and Q after the first fold, allocated as PartiallyEvaluatedMultivariatesBase does. + std::array folded; + + for (size_t round = 0; round < log_n; ++round) { + if (round > 0) { + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + suffix_scale[idx] *= inverses[(idx * (log_n - 1)) + round - 1]; + } + } + const RoundSums sums = compute_round_sums(tables, round); + + std::array evaluations{ FF(0), FF(0), FF(0) }; + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + const FF scale = gamma_powers[idx] * eq_prefix[idx] * suffix_scale[idx]; + const FF& r = claim_challenges[idx][round]; + const FF at_0 = sums[4 * idx] + (alpha * sums[(4 * idx) + 2]); + const FF at_1 = sums[(4 * idx) + 1] + (alpha * sums[(4 * idx) + 3]); + const FF at_2 = at_1 + at_1 - at_0; + evaluations[0] += scale * (FF(1) - r) * at_0; + evaluations[1] += scale * r * at_1; + evaluations[2] += scale * (r + r + r - FF(1)) * at_2; + } + const RoundUnivariate round_univariate(evaluations); + transcript->send_to_verifier("Sumcheck:univariate_" + std::to_string(round), round_univariate); + const FF round_challenge = transcript->template get_challenge("Sumcheck:u_" + std::to_string(round)); + challenge.emplace_back(round_challenge); + + if (round == 0) { + for (size_t t = 0; t < NUM_TABLES; ++t) { + const auto [start, end] = folded_backed_range(*tables[t]); + folded[t] = Polynomial(end - start, circuit_size / 2, start, Polynomial::DontZeroMemory::FLAG); + } + parallel_for(NUM_TABLES, + [&](size_t t) { fold_stride2_backed(*tables[t], folded[t], round_challenge); }); + for (size_t t = 0; t < NUM_TABLES; ++t) { + tables[t] = &folded[t]; + } + } else { + parallel_for(NUM_TABLES, [&](size_t t) { fold_stride2_backed(folded[t], folded[t], round_challenge); }); + } + + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + const FF& r = claim_challenges[idx][round]; + eq_prefix[idx] *= ((FF(1) - r) * (FF(1) - round_challenge)) + (r * round_challenge); + } + } + vinfo("completed ", log_n, " rounds of sumcheck"); + + // After the real rounds each table has at most one backed entry, at index 0, and eq_i equals c_{i,L} times the + // trailing factor ∏_{j>=L} (1 - r_{i,j}), which is the generic eq table folded L times. + std::array non_shifted_value; + std::array shifted_value; + std::array eq_value; + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + key.eq_suffix_tables[idx] = Polynomial(); + non_shifted_value[idx] = value_at_zero(folded[2 * idx]); + shifted_value[idx] = value_at_zero(folded[(2 * idx) + 1]); + FF trailing(1); + for (size_t j = log_n; j < claim_challenges[idx].size(); ++j) { + trailing *= FF(1) - claim_challenges[idx][j]; + } + eq_value[idx] = eq_prefix[idx] * trailing; + } + + // Virtual rounds: P and Q are padded by zero, so their edge is (p, 0); eq's edge is (e_0, e_1) with e_1 the + // claim's eq at (u_0, .., u_{k-1}, 1, 0, .., 0), as in Flavor::extend_eq_polynomials_for_virtual_round. + for (size_t round = log_n; round < VIRTUAL_LOG_N; ++round) { + std::vector round_point(VIRTUAL_LOG_N); + for (size_t j = 0; j < round; ++j) { + round_point[j] = challenge[j]; + } + round_point[round] = FF(1); + + std::array eq_at_one; + std::array evaluations{ FF(0), FF(0), FF(0) }; + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + eq_at_one[idx] = VerifierEqPolynomial::eval(claim_challenges[idx], round_point); + const FF eq_slope = eq_at_one[idx] - eq_value[idx]; + const FF batched = non_shifted_value[idx] + (alpha * shifted_value[idx]); + // At X = 0, 1, 2: eq = e_0, e_1, e_1 + slope; the padded P + α·Q = batched, 0, -batched. + evaluations[0] += gamma_powers[idx] * eq_value[idx] * batched; + evaluations[2] -= gamma_powers[idx] * (eq_at_one[idx] + eq_slope) * batched; + } + const RoundUnivariate round_univariate(evaluations); + transcript->send_to_verifier("Sumcheck:univariate_" + std::to_string(round), round_univariate); + const FF round_challenge = transcript->template get_challenge("Sumcheck:u_" + std::to_string(round)); + challenge.emplace_back(round_challenge); + + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + non_shifted_value[idx] *= FF(1) - round_challenge; + shifted_value[idx] *= FF(1) - round_challenge; + eq_value[idx] = (eq_value[idx] * (FF(1) - round_challenge)) + (eq_at_one[idx] * round_challenge); + } + } + + ClaimedEvaluations claimed_evaluations; + for (size_t idx = 0; idx < NUM_CLAIMS; ++idx) { + claimed_evaluations.non_shifted(idx) = non_shifted_value[idx]; + claimed_evaluations.shifted(idx) = shifted_value[idx]; + claimed_evaluations.eq(idx) = eq_value[idx]; + } + transcript->send_to_verifier("Sumcheck:evaluations", claimed_evaluations.get_all()); + + vinfo("finished sumcheck"); + return SumcheckOutput{ .challenge = challenge, .claimed_evaluations = claimed_evaluations }; + } + + private: + ProvingKey& key; + std::shared_ptr transcript; + FF alpha; + std::array gamma_powers; + + static FF value_at_zero(const Polynomial& table) { return table.is_empty() ? FF(0) : table[0]; } + + /** + * @brief Adds Σ_{y in [first, last)} E(y << shift) · f(2y) to even_sum and the same with f(2y + 1) to odd_sum. + * @details f is zero outside its backed range, which is read directly; only the edges at an odd start or end have a + * single backed row. + */ + static void add_edge_sums(const Polynomial& f, + const Polynomial& eq_suffix, + const size_t shift, + const size_t first, + const size_t last, + FF& even_sum, + FF& odd_sum) + { + const size_t start = f.start_index(); + const size_t end = f.end_index(); + const FF* values = f.data(); + const FF* suffix = eq_suffix.data(); + + const size_t full_begin = std::max(first, (start + 1) / 2); + const size_t full_end = std::min(last, end / 2); + for (size_t y = full_begin; y < full_end; ++y) { + const FF& weight = suffix[y << shift]; + even_sum += weight * values[(2 * y) - start]; + odd_sum += weight * values[(2 * y) + 1 - start]; + } + if ((start & 1) != 0 && first <= start / 2 && start / 2 < last) { + odd_sum += suffix[(start / 2) << shift] * values[0]; + } + if ((end & 1) != 0 && first <= end / 2 && end / 2 < last) { + even_sum += suffix[(end / 2) << shift] * values[end - 1 - start]; + } + } + + /** + * @brief The round's per-table sums, split into equal shares of work across up to get_num_cpus() slots. + * @details One unit of work is one edge of one table's backed range; empty tables are never read. Field addition is + * exact, so the result does not depend on the split. + */ + RoundSums compute_round_sums(const std::array& tables, const size_t round) const + { + std::array offsets{}; + for (size_t t = 0; t < NUM_TABLES; ++t) { + const Polynomial& f = *tables[t]; + const size_t num_edges = f.is_empty() ? 0 : ((f.end_index() + 1) / 2) - (f.start_index() / 2); + offsets[t + 1] = offsets[t] + num_edges; + } + const size_t total = offsets[NUM_TABLES]; + const size_t num_chunks = (total + EDGES_PER_CHUNK - 1) / EDGES_PER_CHUNK; + const size_t num_slots = std::min(get_num_cpus(), std::max(num_chunks, 1)); + + RoundSums zero; + zero.fill(FF(0)); + std::vector slot_sums(num_slots, zero); + parallel_for(num_slots, [&](size_t slot) { + const size_t begin = (total * slot) / num_slots; + const size_t end = (total * (slot + 1)) / num_slots; + RoundSums& acc = slot_sums[slot]; + for (size_t t = 0; t < NUM_TABLES; ++t) { + const size_t lo = std::max(begin, offsets[t]); + const size_t hi = std::min(end, offsets[t + 1]); + if (lo >= hi) { + continue; + } + const Polynomial& f = *tables[t]; + const size_t first_edge = f.start_index() / 2; + add_edge_sums(f, + key.eq_suffix_tables[t / 2], + round, + first_edge + (lo - offsets[t]), + first_edge + (hi - offsets[t]), + acc[2 * t], + acc[(2 * t) + 1]); + } + }); + + RoundSums sums = zero; + for (const RoundSums& acc : slot_sums) { + for (size_t j = 0; j < sums.size(); ++j) { + sums[j] += acc[j]; + } + } + return sums; + } +}; + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.test.cpp b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.test.cpp new file mode 100644 index 0000000..3c266e9 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_sumcheck.test.cpp @@ -0,0 +1,271 @@ +#include "barretenberg/multilinear_batching/multilinear_batching_sumcheck.hpp" +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/serialize.hpp" +#include "barretenberg/common/test.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/multilinear_batching/multilinear_batching_prover.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/sumcheck/sumcheck.hpp" +#include "barretenberg/transcript/transcript.hpp" + +#include +#include +#include +#include +#include +#include +#include + +using namespace bb; + +namespace { + +using FF = MultilinearBatchingProverClaim::FF; +using Polynomial = bb::Polynomial; + +// One claim's polynomial shapes: dyadic size 2^log_size, the non-shifted backed range [start, end) (empty when +// start == end and default_empty) and the pre-shift backed range [shift_start, shift_end), shift_start >= 1. +struct ClaimShape { + size_t log_size; + size_t start; + size_t end; + size_t shift_start; + size_t shift_end; + bool default_empty = false; +}; + +// A coordinate of a claim challenge forced to a fixed value. +struct ForcedChallenge { + size_t claim; + size_t coordinate; + FF value; +}; + +template using BatchingFlavor = MultilinearBatchingFlavor_; + +Polynomial random_backed(size_t start, size_t end, size_t dyadic_size, numeric::RNG& engine) +{ + Polynomial result(end - start, dyadic_size, start); + for (size_t i = start; i < end; ++i) { + result.at(i) = FF::random_element(&engine); + } + return result; +} + +std::vector make_claims(const std::vector& shapes, + const std::vector& forced, + uint64_t seed) +{ + auto& engine = numeric::get_debug_randomness(/*reset=*/true, seed); + std::vector claims; + for (const ClaimShape& shape : shapes) { + const size_t dyadic_size = size_t{ 1 } << shape.log_size; + MultilinearBatchingProverClaim claim; + claim.challenge.resize(CONST_FOLDING_LOG_N); + for (FF& r : claim.challenge) { + r = FF::random_element(&engine); + } + claim.non_shifted_polynomial = + shape.default_empty ? Polynomial() : random_backed(shape.start, shape.end, dyadic_size, engine); + claim.shifted_polynomial = random_backed(shape.shift_start, shape.shift_end, dyadic_size, engine); + claim.non_shifted_evaluation = FF(0); + claim.shifted_evaluation = FF(0); + claim.non_shifted_commitment = MultilinearBatchingProverClaim::Commitment::one(); + claim.shifted_commitment = MultilinearBatchingProverClaim::Commitment::one(); + claim.dyadic_size = dyadic_size; + claims.push_back(std::move(claim)); + } + for (const ForcedChallenge& f : forced) { + claims[f.claim].challenge[f.coordinate] = f.value; + } + return claims; +} + +// Sets the slot count get_num_cpus() reports, which decides how the factored prover splits a round. The pool's worker +// count is fixed at its first use, so this varies the partition, not the number of running threads. +void set_slots(size_t num_slots) +{ +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(num_slots); +#else + static_cast(num_slots); +#endif +} + +struct SumcheckRun { + std::vector proof_bytes; + std::vector output_bytes; +}; + +// Builds the proving key as the production constructor does, in the factored form (one suffix table per claim) or with +// the full eq tables the generic sumcheck takes. The constructor itself is defined and instantiated only inside the +// prover's translation unit, so the test reaches it through MultilinearBatchingProver alone. +template +typename BatchingFlavor::ProvingKey build_key(std::vector&& claims, bool factored) +{ + using F = BatchingFlavor; + typename F::ProvingKey key; + for (const auto& claim : claims) { + key.circuit_size = std::max(key.circuit_size, claim.dyadic_size); + } + const size_t log_n = numeric::get_msb(key.circuit_size); + key.eq_factored = factored; + for (size_t idx = 0; idx < K; ++idx) { + auto& claim = claims[idx]; + key.polynomials.non_shifted(idx) = std::move(claim.non_shifted_polynomial); + key.preshifted_polynomials[idx] = std::move(claim.shifted_polynomial); + key.polynomials.shifted(idx) = key.preshifted_polynomials[idx].shifted(); + if (factored) { + key.eq_suffix_tables[idx] = + ProverEqPolynomial::construct(std::span(claim.challenge).subspan(1), log_n - 1); + } else { + key.polynomials.eq(idx) = ProverEqPolynomial::construct(claim.challenge, log_n); + } + key.polynomials.claim_challenges[idx] = std::move(claim.challenge); + } + key.polynomials.increase_polynomials_virtual_size(size_t{ 1 } << F::VIRTUAL_LOG_N); + return key; +} + +std::shared_ptr seeded_transcript() +{ + auto transcript = std::make_shared(); + transcript->send_to_verifier("seed", FF(7)); + return transcript; +} + +// Runs the batching sumcheck on claims regenerated from the seed, with the given slot count, on the factored prover or +// on the generic SumcheckProver, drawing the challenges MultilinearBatchingProver draws before it. +template +SumcheckRun run_sumcheck(const std::vector& shapes, + const std::vector& forced, + uint64_t seed, + bool factored, + size_t num_slots) +{ + using F = BatchingFlavor; + set_slots(num_slots); + typename F::ProvingKey key = build_key(make_claims(shapes, forced, seed), factored); + + auto transcript = seeded_transcript(); + const FF gamma = transcript->template get_challenge("claim_batching_challenge"); + const FF alpha = transcript->template get_challenge("Sumcheck:alpha"); + RelationParameters relation_parameters; + relation_parameters.compute_multilinear_batching_challenges(gamma, K); + + std::optional> output; + if (factored) { + MultilinearBatchingSumcheckProver sumcheck(key, transcript, alpha, relation_parameters); + output = sumcheck.prove(); + } else { + SumcheckProver sumcheck( + key.circuit_size, key.polynomials, transcript, alpha, {}, relation_parameters, F::VIRTUAL_LOG_N); + output = sumcheck.prove(); + } + + SumcheckRun run; + run.proof_bytes = to_buffer(transcript->export_proof()); + std::vector output_fields = output->challenge; + for (const FF& eval : output->claimed_evaluations.get_all()) { + output_fields.push_back(eval); + } + run.output_bytes = to_buffer(output_fields); + return run; +} + +// The production prover end to end: its key constructor (and guard), whichever sumcheck the guard selects, then the +// claim merge, which needs the largest claim's backed range to contain every other claim's. +std::vector prover_proof(const std::vector& shapes, + const std::vector& forced, + uint64_t seed, + size_t num_slots) +{ + set_slots(num_slots); + MultilinearBatchingProver prover(make_claims(shapes, forced, seed), seeded_transcript()); + return to_buffer(prover.construct_proof()); +} + +// The factored prover's proof and output must equal the generic prover's byte for byte at every slot count, and so must +// the production prover's proof when the shapes satisfy its merge. +template +void expect_identical(const std::vector& shapes, + const std::vector& forced = {}, + bool check_prover = true) +{ + ASSERT_EQ(shapes.size(), K); + const size_t default_slots = get_num_cpus(); + const uint64_t seed = 0xb1a5ed + K; + const SumcheckRun reference = run_sumcheck(shapes, forced, seed, /*factored=*/false, default_slots); + for (const size_t num_slots : { size_t{ 1 }, size_t{ 3 }, size_t{ 4 }, size_t{ 8 } }) { + const SumcheckRun generic = run_sumcheck(shapes, forced, seed, /*factored=*/false, num_slots); + const SumcheckRun factored = run_sumcheck(shapes, forced, seed, /*factored=*/true, num_slots); + EXPECT_EQ(generic.proof_bytes, reference.proof_bytes) << "generic, slots " << num_slots; + EXPECT_EQ(factored.proof_bytes, reference.proof_bytes) << "factored, slots " << num_slots; + EXPECT_EQ(factored.output_bytes, reference.output_bytes) << "factored, slots " << num_slots; + if (check_prover) { + EXPECT_EQ(prover_proof(shapes, forced, seed, num_slots), reference.proof_bytes) + << "prover, slots " << num_slots; + } + } + set_slots(default_slots); +} + +} // namespace + +// Mixed dyadic sizes; odd starts and ends; support up to n - 1; a pre-shift range ending at n. +TEST(MultilinearBatchingSumcheck, MixedShapesMatchGeneric) +{ + expect_identical<3>({ { .log_size = 9, .start = 0, .end = 511, .shift_start = 1, .shift_end = 512 }, + { .log_size = 5, .start = 3, .end = 29, .shift_start = 5, .shift_end = 31 }, + { .log_size = 7, .start = 1, .end = 100, .shift_start = 2, .shift_end = 101 } }); +} + +// The smallest factored size, L = 2. +TEST(MultilinearBatchingSumcheck, TwoRealRoundsMatchGeneric) +{ + expect_identical<2>({ { .log_size = 2, .start = 0, .end = 4, .shift_start = 1, .shift_end = 4 }, + { .log_size = 2, .start = 1, .end = 3, .shift_start = 1, .shift_end = 2 } }); +} + +// Seven claims, one with a default-empty non-shifted polynomial (virtual size 0, never read) and one whose pre-shift +// polynomial is backed on nothing but has a positive virtual size. No claim's range contains all the others, so the +// production prover's merge rejects these shapes and only the sumcheck provers are compared. +TEST(MultilinearBatchingSumcheck, EmptyPolynomialsMatchGeneric) +{ + expect_identical<7>( + { { .log_size = 8, .start = 0, .end = 200, .shift_start = 1, .shift_end = 201 }, + { .log_size = 6, .start = 0, .end = 0, .shift_start = 1, .shift_end = 40, .default_empty = true }, + { .log_size = 8, .start = 7, .end = 256, .shift_start = 1, .shift_end = 1 }, + { .log_size = 3, .start = 0, .end = 8, .shift_start = 1, .shift_end = 8 }, + { .log_size = 8, .start = 0, .end = 1, .shift_start = 255, .shift_end = 256 }, + { .log_size = 5, .start = 31, .end = 32, .shift_start = 1, .shift_end = 2 }, + { .log_size = 7, .start = 64, .end = 65, .shift_start = 63, .shift_end = 66 } }, + {}, + /*check_prover=*/false); +} + +// r_j = 0 in a real coordinate (j < L) and in a trailing one (j >= L) keeps the factored path exact. +TEST(MultilinearBatchingSumcheck, ZeroChallengeCoordinatesMatchGeneric) +{ + expect_identical<2>({ { .log_size = 6, .start = 0, .end = 64, .shift_start = 1, .shift_end = 64 }, + { .log_size = 6, .start = 2, .end = 61, .shift_start = 3, .shift_end = 63 } }, + { { .claim = 0, .coordinate = 0, .value = FF(0) }, + { .claim = 0, .coordinate = 3, .value = FF(0) }, + { .claim = 1, .coordinate = 10, .value = FF(0) } }); +} + +// For r_j = 1 the key's guard selects the generic eq tables, whose construction rejects a challenge longer than L (as +// it does without the factored prover). The guard's L < 2 branch is not run: at n = 2 the generic sumcheck itself +// rejects the input in its first virtual round. +TEST(MultilinearBatchingSumcheck, GuardSelectsGenericPath) +{ + // Coordinate 0 is not a factor of the suffix table, so only the key's guard routes it to the generic tables. + for (const size_t coordinate : { size_t{ 0 }, size_t{ 2 }, size_t{ 12 } }) { + auto claims = make_claims({ { .log_size = 5, .start = 0, .end = 32, .shift_start = 1, .shift_end = 32 }, + { .log_size = 5, .start = 0, .end = 20, .shift_start = 1, .shift_end = 20 } }, + { { .claim = 1, .coordinate = coordinate, .value = FF(1) } }, + /*seed=*/2); + EXPECT_THROW_OR_ABORT(MultilinearBatchingProver(std::move(claims), seeded_transcript()).construct_proof(), + ".*"); + } +} diff --git a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp index 1db7120..4706afc 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp @@ -159,7 +159,59 @@ void fold_stride4_backed_range(const Polynomial& src, const Fr& first_challenge, const Fr& second_challenge) { - for (size_t k = k_begin; k < k_end; ++k) { + size_t k = k_begin; +#if defined(__wasm_simd128__) + if constexpr (simd_supported_v) { + using Vec = VectorField; + constexpr size_t WIDTH = Vec::SIZE; + const Vec first = Vec::broadcast(first_challenge); + const Vec second = Vec::broadcast(second_challenge); + const auto same = [](const Fr& a, const Fr& b) { + return a.data[0] == b.data[0] && a.data[1] == b.data[1] && a.data[2] == b.data[2] && a.data[3] == b.data[3]; + }; + // The first output can straddle a virtual-zero prefix. Preserve its scalar path. + for (; k < k_end && 4 * k < src.start_index(); ++k) { + const Fr even = fold_pair(src[4 * k], src[(4 * k) + 1], first_challenge); + const Fr odd = fold_pair(src[(4 * k) + 2], src[(4 * k) + 3], first_challenge); + dst[ScalarIndex{ k }] = fold_pair(even, odd, second_challenge); + } + for (; k + WIDTH <= k_end && 4 * (k + WIDTH) <= src.end_index(); k += WIDTH) { + const Fr* values = src.data() + (4 * k - src.start_index()); + bool constant_block = true; + bool dense_block = true; + for (size_t lane = 0; lane < WIDTH; ++lane) { + const bool left_equal = same(values[4 * lane], values[4 * lane + 1]); + const bool right_equal = same(values[4 * lane + 2], values[4 * lane + 3]); + constant_block = constant_block && left_equal && right_equal && + same(values[4 * lane], values[4 * lane + 2]); + dense_block = dense_block && !left_equal && !right_equal; + } + if (constant_block) { + // Preserve bit-identical constant/zero runs without packing or multiplying. + for (size_t lane = 0; lane < WIDTH; ++lane) { + dst[ScalarIndex{ k + lane }] = values[4 * lane]; + } + } else if (dense_block) { + const auto fold_lanes = [&](size_t offset) { + const Vec even = Vec::from_lanes([&](size_t lane) { return values[4 * lane + offset]; }); + const Vec odd = Vec::from_lanes([&](size_t lane) { return values[4 * lane + offset + 1]; }); + return even + first * (odd - even); + }; + const Vec even = fold_lanes(0); + const Vec odd = fold_lanes(2); + dst[ContiguousVectorIndex{ k }] = even + second * (odd - even); + } else { + // Mixed sparse groups retain each scalar equality shortcut. + for (size_t lane = 0; lane < WIDTH; ++lane) { + const Fr even = fold_pair(values[4 * lane], values[4 * lane + 1], first_challenge); + const Fr odd = fold_pair(values[4 * lane + 2], values[4 * lane + 3], first_challenge); + dst[ScalarIndex{ k + lane }] = fold_pair(even, odd, second_challenge); + } + } + } + } +#endif + for (; k < k_end; ++k) { const Fr even = fold_pair(src[4 * k], src[(4 * k) + 1], first_challenge); const Fr odd = fold_pair(src[(4 * k) + 2], src[(4 * k) + 3], first_challenge); dst[ScalarIndex{ k }] = fold_pair(even, odd, second_challenge); @@ -242,6 +294,38 @@ template class FoldedPolynomialView { {} Fr operator[](const size_t k) const { return fold_pair((*source)[2 * k], (*source)[(2 * k) + 1], challenge); } +#if defined(__wasm_simd128__) + // Load strided folded values for a SIMD edge. Constant/mixed groups keep the scalar shortcuts; + // only a group with no bit-identical source pair replaces all scalar multiplies by one packed multiply. + template Element gather_folded(const size_t begin, const size_t stride) const + { + constexpr size_t WIDTH = Element::SIZE; + static_assert(WIDTH <= 32); + std::array evens; + std::array odds; + uint32_t equal_mask = 0; + for (size_t lane = 0; lane < WIDTH; ++lane) { + const size_t k = begin + stride * lane; + evens[lane] = &(*source)[2 * k]; + odds[lane] = &(*source)[2 * k + 1]; + const auto& a = *evens[lane]; + const auto& b = *odds[lane]; + if (a.data[0] == b.data[0] && a.data[1] == b.data[1] && a.data[2] == b.data[2] && a.data[3] == b.data[3]) { + equal_mask |= uint32_t{ 1 } << lane; + } + } + if (equal_mask != 0) { + return Element::from_lanes([&](size_t lane) { + return (equal_mask & (uint32_t{ 1 } << lane)) != 0 + ? *evens[lane] + : *evens[lane] + challenge * (*odds[lane] - *evens[lane]); + }); + } + const Element even = Element::from_lanes([&](size_t lane) { return *evens[lane]; }); + const Element odd = Element::from_lanes([&](size_t lane) { return *odds[lane]; }); + return even + Element::broadcast(challenge) * (odd - even); + } +#endif size_t start_index() const { return range.first; } size_t end_index() const { return range.second; } size_t size() const { return range.second - range.first; } diff --git a/barretenberg/cpp/src/barretenberg/relations/delta_range_constraint_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/delta_range_constraint_relation.hpp index 6e93673..9236fee 100644 --- a/barretenberg/cpp/src/barretenberg/relations/delta_range_constraint_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/delta_range_constraint_relation.hpp @@ -128,7 +128,7 @@ template class DeltaRangeConstraintRelationImpl { const AllEntities& in, const Parameters& /*params*/, const FF& scaling_factor, - const SubrelationBatchingConstants& constants) + const auto& constants) { using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; using CoefficientAccumulator = typename Accumulator::CoefficientAccumulator; diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp index 4a541bd..766fe67 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp @@ -65,6 +65,10 @@ template class Poseidon2ExternalRelationImpl { 7, // external poseidon2 round sub-relation for fourth value }; + // A permutation's rows of each Poseidon2 gate kind are interleaved in one trace block, so this selector is live + // on few edges of a SIMD sumcheck group (see HasSparseSelector). + static constexpr bool SPARSE_SELECTOR = true; + /** * @brief Returns true if the contribution from all subrelations for the provided inputs is identically zero * diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_initial_external_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_initial_external_relation.hpp index 85566ee..57d4ed2 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_initial_external_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_initial_external_relation.hpp @@ -30,6 +30,10 @@ template class Poseidon2InitialExternalRelationImpl { 3, // A_3 }; + // A permutation's rows of each Poseidon2 gate kind are interleaved in one trace block, so this selector is live + // on few edges of a SIMD sumcheck group (see HasSparseSelector). + static constexpr bool SPARSE_SELECTOR = true; + template inline static bool skip(const AllEntities& in) { return in[AllEntities::EntityId::q_poseidon2_external_initial].is_zero(); diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_relation.hpp index 8f35f9d..2568d16 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_relation.hpp @@ -76,6 +76,10 @@ template class Poseidon2QuadInternalRelationImpl { static constexpr fr B3_U0_COEF = SIGMA_PLUS_2 * D1 - QuadParams::SIGMA - fr(3); // (Σ+2) D_1 - Σ - 3 static constexpr fr D1_MINUS_3 = D1 - fr(3); // D_1 - 3 + // A permutation's rows of each Poseidon2 gate kind are interleaved in one trace block, so this selector is live + // on few edges of a SIMD sumcheck group (see HasSparseSelector). + static constexpr bool SPARSE_SELECTOR = true; + /** * @brief Skip when the selector is identically zero on this row. */ @@ -234,7 +238,7 @@ template class Poseidon2QuadInternalRelationImpl { const AllEntities& in, const Parameters& /*params*/, const FF& scaling_factor, - const SubrelationBatchingConstants& constants) + const auto& constants) { using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; using CoeffAcc = typename Accumulator::CoefficientAccumulator; diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_terminal_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_terminal_relation.hpp index 85b90bf..88c05e3 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_terminal_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_terminal_relation.hpp @@ -27,6 +27,10 @@ template class Poseidon2QuadInternalTerminalRelationImpl { static constexpr std::array SUBRELATION_PARTIAL_LENGTHS{ 7, 7, 7, 7 }; + // A permutation's rows of each Poseidon2 gate kind are interleaved in one trace block, so this selector is live + // on few edges of a SIMD sumcheck group (see HasSparseSelector). + static constexpr bool SPARSE_SELECTOR = true; + template inline static bool skip(const AllEntities& in) { return in[AllEntities::EntityId::q_poseidon2_quad_internal_terminal].is_zero(); @@ -130,7 +134,7 @@ template class Poseidon2QuadInternalTerminalRelationImpl { const AllEntities& in, const Parameters& /*params*/, const FF& scaling_factor, - const SubrelationBatchingConstants& constants) + const auto& constants) { using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; using CoeffAcc = typename Accumulator::CoefficientAccumulator; diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_transition_entry_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_transition_entry_relation.hpp index 92ab0de..94422f1 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_transition_entry_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_transition_entry_relation.hpp @@ -66,6 +66,10 @@ template class Poseidon2TransitionEntryRelationImpl { static constexpr auto& A2_one = QuadParams::A2_one; static constexpr fr sum_A_one = QuadParams::sum_A_one; + // A permutation's rows of each Poseidon2 gate kind are interleaved in one trace block, so this selector is live + // on few edges of a SIMD sumcheck group (see HasSparseSelector). + static constexpr bool SPARSE_SELECTOR = true; + template inline static bool skip(const AllEntities& in) { return in[AllEntities::EntityId::q_poseidon2_transition_entry].is_zero(); @@ -161,7 +165,7 @@ template class Poseidon2TransitionEntryRelationImpl { const AllEntities& in, const Parameters& /*params*/, const FF& scaling_factor, - const SubrelationBatchingConstants& constants) + const auto& constants) { using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; using CoeffAcc = typename Accumulator::CoefficientAccumulator; diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.cpp index 97a412d..cb3960b 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.cpp @@ -2,6 +2,7 @@ #include "./types.hpp" #include "barretenberg/common/assert.hpp" +#include "barretenberg/common/thread.hpp" #include "barretenberg/ecc/curves/secp256r1/secp256r1.hpp" #include "barretenberg/ecc/groups/precomputed_generators.hpp" #include "barretenberg/ecc/groups/precomputed_generators_secp256r1_impl.hpp" @@ -20,39 +21,39 @@ void table::init_tables() constexpr AffineElement H = bb::get_precomputed_generators()[0]; - // Step per window: 2^(8w) · G. + // Per window w: step 2^(sum of the earlier windows' bits) · G and offset 2^w · H, both by doubling. The + // per-window size and step follow table_size(w) and window_bits(w) (7-bit "big" windows plus a 3-bit lo-tail + // and a 1-bit hi-tail). + std::array window_steps; + std::array window_offsets; Element window_step = Element(G1::affine_one); - + Element window_offset = Element(H); // Total offset accumulator: sums all 2^w · H contributions. Element offset_total = Element::infinity(); - for (size_t w = 0; w < NUM_WINDOWS; ++w) { - // Per-window offset: 2^w · H. We compute it by doubling H w times rather than scalar-mul to keep this - // straightforward; this code runs once per process so the cost is irrelevant. - const G1::Fr offset_scalar(uint256_t(1) << w); - const Element window_offset = Element(H) * offset_scalar; + window_steps[w] = window_step; + window_offsets[w] = window_offset; offset_total += window_offset; + for (size_t i = 0; i < window_bits(w); ++i) { + window_step = window_step.dbl(); + } + window_offset = window_offset.dbl(); + } - // Build the entries for this window: T[k] = k · window_step + window_offset. The per-window - // size and step are determined by table_size(w) and window_bits(w) (7-bit "big" windows - // plus a 3-bit lo-tail and a 1-bit hi-tail). + // Entries T_w[k] = k · step_w + offset_w. Windows are independent, and normalization fixes each entry's + // affine coordinates whatever thread computed it. + parallel_for(NUM_WINDOWS, [&](size_t w) { const size_t ts = table_size(w); - const size_t wb = window_bits(w); std::array projective; - projective[0] = window_offset; + projective[0] = window_offsets[w]; for (size_t k = 1; k < ts; ++k) { - projective[k] = projective[k - 1] + window_step; + projective[k] = projective[k - 1] + window_steps[w]; } Element::batch_normalize(projective.data(), ts); for (size_t k = 0; k < ts; ++k) { native_table[w][k] = AffineElement(projective[k].x, projective[k].y); } - - // Advance the step for the next window: window_step *= 2^window_bits(w). - for (size_t i = 0; i < wb; ++i) { - window_step = window_step.dbl(); - } - } + }); cached_total_offset = AffineElement(offset_total); }); diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.test.cpp new file mode 100644 index 0000000..9844c53 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/secp256r1_fixed_base.test.cpp @@ -0,0 +1,42 @@ +#include "./secp256r1_fixed_base.hpp" + +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/groups/precomputed_generators.hpp" +#include "barretenberg/ecc/groups/precomputed_generators_secp256r1_impl.hpp" + +#include + +using namespace bb::plookup::secp256r1_fixed_base; + +namespace { +using G1 = table::G1; +using Element = table::Element; +using AffineElement = table::AffineElement; +using Fr = G1::Fr; +} // namespace + +// Every entry is k · 2^(bit_offset(w)) · G + 2^w · H, computed here by scalar multiplication, and the total offset is +// (2^NUM_WINDOWS - 1) · H. Reads run from several threads at once, as the builders' lookups do. +TEST(Secp256r1FixedBaseTable, EntriesAreTheWindowMultiples) +{ + constexpr AffineElement H = bb::get_precomputed_generators()[0]; + std::array bit_offset{}; + for (size_t w = 1; w < table::NUM_WINDOWS; ++w) { + bit_offset[w] = bit_offset[w - 1] + table::window_bits(w - 1); + } + std::array window_ok{}; + bb::parallel_for(table::NUM_WINDOWS, [&](size_t w) { + const Element offset = Element(H) * Fr(uint256_t(1) << w); + bool ok = true; + for (size_t k = 0; k < table::table_size(w); ++k) { + const Element expected = Element(G1::affine_one) * Fr(uint256_t(k) << bit_offset[w]) + offset; + ok = ok && table::get_entry(w, k) == AffineElement(expected); + } + window_ok[w] = ok; + }); + for (size_t w = 0; w < table::NUM_WINDOWS; ++w) { + EXPECT_TRUE(window_ok[w]) << "window " << w; + } + const Fr total = Fr((uint256_t(1) << table::NUM_WINDOWS) - 1); + EXPECT_EQ(table::total_offset(), AffineElement(Element(H) * total)); +} diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp index fba518d..cb37905 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp @@ -32,6 +32,8 @@ #include #include +#include "barretenberg/common/thread.hpp" + namespace bb { namespace { diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp index a1c6ef5..275314e 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp @@ -66,6 +66,15 @@ template inline constexpr size_t lane_count = T::SIZE; template concept HasProverSubrelationBatching = requires { typename Relation::SubrelationBatchingConstants; }; +/** + * @brief Relations whose gate rows are interleaved with other gate kinds in their trace block, so their selector is + * live on few edges of a SIMD group (`SPARSE_SELECTOR = true`). + * @details The SIMD sumcheck evaluates such a relation lane by lane when it does not skip a group: a group in which a + * single edge is live is accumulated on the scalar path, one edge instead of `lane_count` lanes. + */ +template +concept HasSparseSelector = requires { requires Relation::SPARSE_SELECTOR; }; + template struct SubrelationBatchingSlot { using type = std::monostate; }; @@ -317,9 +326,20 @@ template class SumcheckProverRound { // Gather each lane's edge pair: `Element::from_lanes` reads `(current_edge + 2j, +1)` for lane // j -- `lane_count` strided pairs for `VectorField`, just `(current_edge, current_edge + 1)` // for scalar `FF`. - cache[index] = bb::Univariate( - { Element::from_lanes([&](size_t lane) { return multivariate[current_edge + (2 * lane)]; }), - Element::from_lanes([&](size_t lane) { return multivariate[current_edge + (2 * lane) + 1]; }) }); +#if defined(__wasm_simd128__) + if constexpr (IsVectorField && requires { + multivariate.template gather_folded(current_edge, size_t{ 2 }); + }) { + cache[index] = bb::Univariate( + { multivariate.template gather_folded(current_edge, 2), + multivariate.template gather_folded(current_edge + 1, 2) }); + } else +#endif + { + cache[index] = bb::Univariate( + { Element::from_lanes([&](size_t lane) { return multivariate[current_edge + (2 * lane)]; }), + Element::from_lanes([&](size_t lane) { return multivariate[current_edge + (2 * lane) + 1]; }) }); + } materialized.set(index); } return cache[index]; @@ -635,26 +655,47 @@ template class SumcheckProverRound { } } + // No scalar evaluation of single live lanes (scalar element, or callers outside the SIMD main loop). + struct NoLaneFallback {}; + + // The scalar tail's state, through which a SIMD group's `HasSparseSelector` relations are evaluated edge by edge: + // its edge container, its `FF` accumulators (into which the wide accumulator is reduced at slot end), the scalar + // parameters, and the group's first edge. + template struct LaneFallback { + ScalarEdges& edges; + SumcheckTupleOfTuplesOfUnivariates& accumulators; + const Multivariates& polynomials; + const bb::RelationParameters& parameters; + const bb::GateSeparatorPolynomial& gate_separators; + size_t group_begin; + }; + // Fold one edge's relation contributions into `accumulator`: position `edge_container` at `edge_idx`, // then run the relation set (in the element type `Element`, deduced from `params`) scaled by the // gate-separator factor. Both `accumulate_edge_chunks` passes share this body -- the full-group pass // calls it with the wide `VectorField` element (`edges` / `wide_accumulator`), the leftover-pair pass // with the scalar `FF` element (`tail_edges` / `result`); they differ only in which element they pass. - template + template void accumulate_edge(Accumulators& accumulator, Edges& edge_container, const Multivariates& polynomials, const bb::RelationParameters& params, const bb::GateSeparatorPolynomial& gate_separators, const size_t edge_idx, - const SubrelationBatching* subrelation_batching) + const SubrelationBatching* subrelation_batching, + const Fallback& lane_fallback = {}) { SumcheckProverRound::load_edge(edge_container, polynomials, edge_idx); accumulate_relation_univariates>(accumulator, edge_container, params, element_scaling(gate_separators, edge_idx), - subrelation_batching); + subrelation_batching, + lane_fallback); } // Accumulate the round univariate over `chunks` in element type `Element`. Each work-stealing slot owns a @@ -688,13 +729,26 @@ template class SumcheckProverRound { chunk->end, EDGE_STRIDE, [&](const size_t edge_idx) { - accumulate_edge(wide_accumulator, - edges, - polynomials, - element_parameters, - gate_separators, - edge_idx, - subrelation_batching); + if constexpr (IsVectorField) { + accumulate_edge( + wide_accumulator, + edges, + polynomials, + element_parameters, + gate_separators, + edge_idx, + subrelation_batching, + LaneFallback>{ + tail_edges, result, polynomials, relation_parameters, gate_separators, edge_idx }); + } else { + accumulate_edge(wide_accumulator, + edges, + polynomials, + element_parameters, + gate_separators, + edge_idx, + subrelation_batching); + } }, [&](const size_t edge_idx) { accumulate_edge(result, @@ -1266,52 +1320,114 @@ template class SumcheckProverRound { * @result #univariate_accumulators are updated with the contribution from the current group of edges. For each * relation, a univariate of some degree is computed by accumulating the contributions of each group of edges. */ - template + template void accumulate_relation_univariates(Accumulators& univariate_accumulators, const Edges& extended_edges, const bb::RelationParameters& relation_parameters, const Element& scaling_factor, - const SubrelationBatching* subrelation_batching = nullptr) + const SubrelationBatching* subrelation_batching = nullptr, + const Fallback& lane_fallback = {}) { // `RelationTuple` is `Relations` or `Flavor::Relations_` -- the same relation set over // different fields, so its size is always NUM_RELATIONS. static_assert(std::tuple_size_v == NUM_RELATIONS); constexpr_for<0, NUM_RELATIONS, 1>([&]() { using Relation = std::tuple_element_t; - auto accumulate_relation = [&]() { - // Subrelation batching is wired for the scalar element only; `RelationTuple` is then `Relations`. - if constexpr (HasProverSubrelationBatching && std::same_as) { - if (subrelation_batching != nullptr) { - const auto& constants = std::get(*subrelation_batching); - if (constants.has_value()) { - Relation::accumulate_with_subrelation_batching( - std::get(univariate_accumulators), - extended_edges, - relation_parameters, - scaling_factor, - *constants); - return; - } - } - } - Relation::accumulate(std::get(univariate_accumulators), - extended_edges, - relation_parameters, - scaling_factor); - }; // Check if the relation is skippable to speed up accumulation - if constexpr (!isSkippable) { - // If not, accumulate normally - accumulate_relation(); - } else { + if constexpr (isSkippable) { // If so, only compute the contribution if the relation is active - if (!Relation::skip(extended_edges)) { - accumulate_relation(); + if (Relation::skip(extended_edges)) { + return; + } + if constexpr (!std::same_as && HasSparseSelector) { + if (accumulate_sparse_lanes>(lane_fallback, + subrelation_batching)) { + return; + } } } + accumulate_relation(std::get(univariate_accumulators), + extended_edges, + relation_parameters, + scaling_factor, + subrelation_batching); }); } + // Accumulate one relation's contribution for the current edge (or SIMD group), through the prover-only + // subrelation batching when the relation has it and its constants are set. + template + static void accumulate_relation(RelationAccumulator& relation_accumulator, + const Edges& extended_edges, + const bb::RelationParameters& relation_parameters, + const Element& scaling_factor, + const SubrelationBatching* subrelation_batching) + { + // Packed WASM lanes share the scalar separators. The batching hooks broadcast their scalar + // constants while retaining the same separator-weighted formulas as the scalar prover. +#if defined(__wasm__) && defined(__wasm_simd128__) + constexpr bool can_batch = + HasProverSubrelationBatching && (std::same_as || IsVectorField); +#else + constexpr bool can_batch = HasProverSubrelationBatching && std::same_as; +#endif + if constexpr (can_batch) { + if (subrelation_batching != nullptr) { + const auto& constants = std::get(*subrelation_batching); + if (constants.has_value()) { + Relation::accumulate_with_subrelation_batching( + relation_accumulator, extended_edges, relation_parameters, scaling_factor, *constants); + return; + } + } + } + Relation::accumulate(relation_accumulator, extended_edges, relation_parameters, scaling_factor); + } + + /** + * @brief Evaluate a `HasSparseSelector` relation that does not skip the SIMD group starting at + * `fallback.group_begin` lane by lane, if at most one of the group's `LANES` edges is live. + * @details Edge `group_begin + 2j` is lane j of the group. Each is tested with the relation's scalar `skip()`, the + * test the scalar path applies to every edge. With no live edge the group contributes nothing; with one, that + * edge is accumulated into the scalar accumulators exactly as the scalar tail would accumulate it. Both are + * exact field sums of the same per-edge contributions, so the round univariate is unchanged. + * @return false if two or more edges are live, in which case the caller evaluates the whole group. + */ + template + static bool accumulate_sparse_lanes(const Fallback& fallback, const SubrelationBatching* subrelation_batching) + { + using ScalarRelation = std::tuple_element_t>; + size_t live_edge = 0; + size_t num_live = 0; + size_t loaded_edge = 0; + for (size_t lane = 0; lane < LANES; ++lane) { + loaded_edge = fallback.group_begin + (2 * lane); + load_edge(fallback.edges, fallback.polynomials, loaded_edge); + if (!ScalarRelation::skip(fallback.edges)) { + if (++num_live > 1) { + return false; + } + live_edge = loaded_edge; + } + } + if (num_live == 0) { + return true; + } + if (loaded_edge != live_edge) { + load_edge(fallback.edges, fallback.polynomials, live_edge); + } + accumulate_relation(std::get(fallback.accumulators), + fallback.edges, + fallback.parameters, + element_scaling(fallback.gate_separators, live_edge), + subrelation_batching); + return true; + } + /** * @brief In regular round i = 0,...,multivariate_d-1, equals 2^{multivariate_d - i}; halved once per regular * round via advance_round(). diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_sparse_lanes.test.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_sparse_lanes.test.cpp new file mode 100644 index 0000000..032881f --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_sparse_lanes.test.cpp @@ -0,0 +1,125 @@ +#include "barretenberg/flavor/mega_flavor.hpp" +#include "barretenberg/sumcheck/sumcheck_round.hpp" + +#include + +#include + +using namespace bb; + +namespace { + +using Flavor = MegaFlavor; +using FF = Flavor::FF; +using EntityId = Flavor::EntityId; +using SelectorRows = std::map>; + +static_assert(HasSparseSelector>); +static_assert(HasSparseSelector>); +static_assert(HasSparseSelector>); +static_assert(HasSparseSelector>); +static_assert(HasSparseSelector>); + +// Selector rows of one Poseidon2 permutation in Mega's `poseidon2` block, starting at `base`: initial linear layer, +// four external rounds, transition entry, thirteen quad-internal rows, terminal, four external rounds, output row. +void add_permutation_rows(SelectorRows& rows, const size_t base) +{ + rows[EntityId::q_poseidon2_external_initial].push_back(base); + for (size_t i = 0; i < 4; ++i) { + rows[EntityId::q_poseidon2_external].push_back(base + 1 + i); + rows[EntityId::q_poseidon2_external].push_back(base + 20 + i); + } + rows[EntityId::q_poseidon2_transition_entry].push_back(base + 5); + for (size_t i = 0; i < 13; ++i) { + rows[EntityId::q_poseidon2_quad_internal].push_back(base + 6 + i); + } + rows[EntityId::q_poseidon2_quad_internal_terminal].push_back(base + 19); +} + +/** + * @brief The SIMD-element round univariate must equal the scalar one when the Poseidon2 selectors are sparse. + * @details Every entity is random except the Poseidon2 selectors, which are random on `selector_rows` and zero + * elsewhere, so the 10-row groups of the `VectorField` path see one live edge (scalar evaluation of that lane), several + * (packed evaluation) or none (skip). On native `VectorField` is an emulation, so this checks the lane orchestration, + * not the SIMD kernels. + */ +void check_sparse_selectors_match_scalar(const SelectorRows& selector_rows, const size_t log_n) +{ + const size_t round_size = size_t{ 1 } << log_n; + typename Flavor::ProverPolynomials prover_polynomials; + for (size_t entity = 0; entity < Flavor::NUM_ALL_ENTITIES; ++entity) { + Polynomial poly(round_size); + const auto sparse = selector_rows.find(static_cast(entity)); + if (sparse != selector_rows.end()) { + for (const size_t row : sparse->second) { + poly.at(row) = FF::random_element(); + } + } else { + for (size_t row = 0; row < round_size; ++row) { + poly.at(row) = FF::random_element(); + } + } + prover_polynomials.get_all()[entity] = poly.share(); + } + + const auto relation_parameters = RelationParameters::get_random(); + std::vector betas(log_n); + for (auto& beta : betas) { + beta = FF::random_element(); + } + GateSeparatorPolynomial gate_separators(betas, log_n); + std::array alphas; + for (auto& alpha : alphas) { + alpha = FF::random_element(); + } + + SumcheckProverRound round_scalar(round_size); + const auto result_scalar = + round_scalar.template compute_univariate(prover_polynomials, relation_parameters, gate_separators, alphas); + SumcheckProverRound round_vec(round_size); + const auto result_vec = round_vec.template compute_univariate>( + prover_polynomials, relation_parameters, gate_separators, alphas); + + EXPECT_EQ(result_scalar, result_vec); +} + +} // namespace + +// Hand-placed rows in a 32-row round (10-row groups at rows 0, 10, 20; scalar tail at rows 30-31): every Poseidon2 +// relation is live on a single edge of some group, External and QuadInternal also on several edges of others, and +// External and ExtInitial in the tail. +TEST(SumcheckSparseLanes, SingleAndMultiLaneGroupsMatchScalarMega) +{ + const SelectorRows rows{ + { EntityId::q_poseidon2_quad_internal_terminal, { 3 } }, + { EntityId::q_poseidon2_transition_entry, { 12, 13, 25 } }, + { EntityId::q_poseidon2_external_initial, { 17, 31 } }, + { EntityId::q_poseidon2_external, { 1, 2, 30 } }, + { EntityId::q_poseidon2_quad_internal, { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 28 } }, + }; + check_sparse_selectors_match_scalar(rows, 5); +} + +// Back-to-back permutations in Mega's row layout across a 128-row round (several work-stealing chunks). +TEST(SumcheckSparseLanes, PermutationLayoutMatchesScalarMega) +{ + SelectorRows rows; + for (size_t base = 3; base + 25 <= 128; base += 25) { + add_permutation_rows(rows, base); + } + check_sparse_selectors_match_scalar(rows, 7); +} + +// No Poseidon2 row at all: every group skips the five relations. +TEST(SumcheckSparseLanes, NoPoseidon2RowsMatchesScalarMega) +{ + SelectorRows rows; + for (const auto id : { EntityId::q_poseidon2_external, + EntityId::q_poseidon2_external_initial, + EntityId::q_poseidon2_quad_internal, + EntityId::q_poseidon2_quad_internal_terminal, + EntityId::q_poseidon2_transition_entry }) { + rows[id] = {}; + } + check_sparse_selectors_match_scalar(rows, 5); +} diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/translator_ordered_range_sort.test.cpp b/barretenberg/cpp/src/barretenberg/translator_vm/translator_ordered_range_sort.test.cpp new file mode 100644 index 0000000..33506c2 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/translator_vm/translator_ordered_range_sort.test.cpp @@ -0,0 +1,232 @@ +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/translator_vm/translator_proving_key.hpp" + +#include + +#include +#include +#include +#include +#include + +using namespace bb; + +namespace { +using Key = TranslatorProvingKey; +using Flavor = Key::Flavor; +using FF = Key::FF; + +constexpr size_t NUM_RANGE_CONSTRAINT_GROUPS = Flavor::NUM_CONCATENATED_POLYS - 1; +constexpr size_t VALUES_PER_LANE = Flavor::MINI_CIRCUIT_SIZE - 1 - Flavor::NUM_MASKED_ROWS_END; +constexpr size_t CIRCUIT_SIZE = Flavor::MINI_CIRCUIT_SIZE * Flavor::CONCATENATION_GROUP_SIZE; +constexpr uint64_t MAX_MICRO_LIMB = (uint64_t{ 1 } << Flavor::MICRO_LIMB_BITS) - 1; +// Row of lane 15 whose slot is the last one before the runway of steps. +constexpr size_t LAST_ROW_BEFORE_RUNWAY = Key::dyadic_circuit_size_without_masking - Flavor::SORTED_STEPS_COUNT - + ((Flavor::CONCATENATION_GROUP_SIZE - 1) * VALUES_PER_LANE); + +// Value of row k of lane j in range-constraint group i (rows exclude the masking rows). +using Pattern = std::function; + +struct Case { + std::string name; + Pattern pattern; + // Wire polynomials to reshape before filling: {group, lane, number of rows}. + std::vector> reshaped_lanes = {}; +}; + +void fill_range_constraint_groups(Key& key, const Case& c) +{ + auto& engine = numeric::get_debug_randomness(); + auto groups = key.proving_key->polynomials.get_groups_to_be_concatenated(); + for (size_t i = 0; i < NUM_RANGE_CONSTRAINT_GROUPS; i++) { + for (size_t j = 0; j < Flavor::CONCATENATION_GROUP_SIZE; j++) { + size_t num_rows = Flavor::MINI_CIRCUIT_SIZE - 1; + for (const auto& [group, lane, rows] : c.reshaped_lanes) { + if (group == i && lane == j) { + num_rows = rows; + } + } + groups[i][j] = Key::Polynomial(num_rows, CIRCUIT_SIZE, /*start_index=*/1); + auto& wire = groups[i][j]; + const size_t masking_start = wire.end_index() - Flavor::NUM_MASKED_ROWS_END; + for (size_t k = wire.start_index(); k < masking_start; k++) { + wire.at(k) = c.pattern(i, j, k); + } + for (size_t k = masking_start; k < wire.end_index(); k++) { + wire.at(k) = FF::random_element(&engine); + } + } + } +} + +// Gives the masking rows of the concatenated range-constraint polynomials distinct values, and fills the ordered +// polynomials with a sentinel, so that the comparison covers every coefficient. +void fill_masking_rows_and_sentinels(Key& key, const FF& sentinel) +{ + auto concatenated = key.proving_key->polynomials.get_concatenated(); + for (size_t i = 0; i < NUM_RANGE_CONSTRAINT_GROUPS; i++) { + for (size_t j = 0; j < Flavor::CONCATENATION_GROUP_SIZE; j++) { + for (size_t k = 0; k < Flavor::NUM_MASKED_ROWS_END; k++) { + const size_t row = + (j * Flavor::MINI_CIRCUIT_SIZE) + Flavor::MINI_CIRCUIT_SIZE - Flavor::NUM_MASKED_ROWS_END + k; + concatenated[i].at(row) = + FF(uint64_t{ 1000000 } + (((i * Flavor::CONCATENATION_GROUP_SIZE) + j) * 8) + k); + } + } + } + for (auto& ordered : key.proving_key->polynomials.get_ordered_range_constraints()) { + for (size_t pos = ordered.start_index(); pos < ordered.end_index(); pos++) { + ordered.at(pos) = sentinel; + } + } +} + +/** + * @brief Every coefficient of the ordered range-constraint polynomials, by the comparison sort. Each receives the + * sorted sequence of its multiset without the first element at [1, circuit_size - MAX_RANDOM_VALUES_PER_ORDERED), and + * its share of the concatenated polynomials' masking values at the end; the coefficients between keep the sentinel. + * Lanes are written in order, so an overlong lane is overwritten by the next one as in the sorting vector. + */ +std::array, Flavor::NUM_CONCATENATED_POLYS> reference_ordered_values(Key& key, const FF& sentinel) +{ + auto groups = key.proving_key->polynomials.get_groups_to_be_concatenated(); + const auto steps = Key::get_sorted_steps(); + const size_t vector_size = Key::dyadic_circuit_size_without_masking; + const size_t free_space = vector_size - steps.size(); + const size_t end = key.proving_key->polynomials.get_polynomial_size() - Flavor::MAX_RANDOM_VALUES_PER_ORDERED; + + std::array, Flavor::NUM_CONCATENATED_POLYS> sorted; + std::vector extra(vector_size, 0); + for (size_t i = 0; i < NUM_RANGE_CONSTRAINT_GROUPS; i++) { + std::vector values(vector_size, 0); + size_t extra_offset = i * steps.size(); + for (size_t j = 0; j < Flavor::CONCATENATION_GROUP_SIZE; j++) { + const auto& wire = groups[i][j]; + for (size_t k = wire.start_index(); k < wire.end_index() - Flavor::NUM_MASKED_ROWS_END; k++) { + const size_t idx = (j * VALUES_PER_LANE) + (k - wire.start_index()); + const uint64_t value = static_cast(uint256_t(wire[k]).data[0]); + if (idx < free_space) { + values[idx] = value; + } else { + extra[extra_offset++] = value; + } + } + } + std::copy(steps.begin(), steps.end(), values.begin() + static_cast(free_space)); + std::sort(values.begin(), values.end()); + sorted[i] = std::move(values); + } + std::copy(steps.begin(), + steps.end(), + extra.begin() + static_cast(NUM_RANGE_CONSTRAINT_GROUPS * steps.size())); + std::sort(extra.begin(), extra.end()); + sorted[NUM_RANGE_CONSTRAINT_GROUPS] = std::move(extra); + + std::vector masking_values; + auto concatenated = key.proving_key->polynomials.get_concatenated(); + for (size_t i = 0; i < NUM_RANGE_CONSTRAINT_GROUPS; i++) { + for (size_t j = 0; j < Flavor::CONCATENATION_GROUP_SIZE; j++) { + for (size_t k = 0; k < Flavor::NUM_MASKED_ROWS_END; k++) { + masking_values.push_back(concatenated[i][(j * Flavor::MINI_CIRCUIT_SIZE) + Flavor::MINI_CIRCUIT_SIZE - + Flavor::NUM_MASKED_ROWS_END + k]); + } + } + } + const size_t per_ordered = masking_values.size() / Flavor::NUM_CONCATENATED_POLYS; + const size_t remainder = masking_values.size() % Flavor::NUM_CONCATENATED_POLYS; + + std::array, Flavor::NUM_CONCATENATED_POLYS> result; + for (size_t i = 0; i < Flavor::NUM_CONCATENATED_POLYS; i++) { + result[i].assign(CIRCUIT_SIZE, sentinel); + result[i][0] = FF(0); + for (size_t pos = 1; pos < end; pos++) { + result[i][pos] = FF(sorted[i][pos]); + } + // Dealt round-robin, as split_concatenated_random_coefficients_to_ordered does (bb v6.1.0): masking value + // (m * NUM_CONCATENATED_POLYS) + i is ordered polynomial i's m-th. + const size_t num_masking = per_ordered + (i < remainder ? 1 : 0); + for (size_t m = 0; m < num_masking; m++) { + result[i][CIRCUIT_SIZE - num_masking + m] = masking_values[(m * Flavor::NUM_CONCATENATED_POLYS) + i]; + } + } + return result; +} + +std::vector adversarial_cases() +{ + auto& engine = numeric::get_debug_randomness(); + const auto random_micro_limb = [&engine](size_t, size_t, size_t) { + return FF(engine.get_random_uint16() & MAX_MICRO_LIMB); + }; + // Position of row k of lane j in its group's sorting vector, increasing across the group. + const auto flat_index = [](size_t j, size_t k) { return (j * VALUES_PER_LANE) + k; }; + return { + { "all equal at the maximum", [](size_t, size_t, size_t) { return FF(MAX_MICRO_LIMB); } }, + { "all zero", [](size_t, size_t, size_t) { return FF(0); } }, + { "empty tail", + [&engine](size_t, size_t, size_t k) { + return k < 64 ? FF(engine.get_random_uint16() & MAX_MICRO_LIMB) : FF(0); + } }, + { "already sorted", [flat_index](size_t, size_t j, size_t k) { return FF(flat_index(j, k) / 8); } }, + { "reversed", + [flat_index](size_t, size_t j, size_t k) { return FF(MAX_MICRO_LIMB - (flat_index(j, k) / 8)); } }, + { "maximum range", random_micro_limb }, + // Each value names its group and lane, so a value counted in the wrong polynomial, or an overflow entry + // written to the wrong offset, changes a multiset. + { "group and lane signatures", + [](size_t i, size_t j, size_t k) { return FF((i << 12) | (j << 8) | (k & 0xff)); } }, + // 2^32 + 5 truncates to 5, as the sorting vectors store it. + { "value truncating into the range", + [&engine](size_t i, size_t j, size_t k) { + return (i == 3 && j == 0 && k == 1) ? FF((uint64_t{ 1 } << 32) + 5) + : FF(engine.get_random_uint16() & MAX_MICRO_LIMB); + } }, + // Out-of-range values below the runway of group 1, at the last slot before the runway of group 3, and in the + // overflow of group 2, which feeds the fifth polynomial. + { "out of range", + [&engine](size_t i, size_t j, size_t k) { + constexpr size_t LAST_LANE = Flavor::CONCATENATION_GROUP_SIZE - 1; + if (i == 1 && j == 0 && k <= 3) { + const std::array out_of_range{ FF(MAX_MICRO_LIMB + 1), FF(uint64_t{ 0xffffffff }), FF(-1) }; + return out_of_range[k - 1]; + } + if ((i == 2 && j == LAST_LANE && k == VALUES_PER_LANE) || + (i == 3 && j == LAST_LANE && k == LAST_ROW_BEFORE_RUNWAY)) { + return FF(MAX_MICRO_LIMB + 1); + } + return FF(engine.get_random_uint16() & MAX_MICRO_LIMB); + } }, + // A short lane leaves zero slots below the runway; an overlong one overwrites the next lane's first slots. + { "short and overlong lanes", + random_micro_limb, + { { 0, 3, Flavor::MINI_CIRCUIT_SIZE - 1 - 2000 }, { 2, 6, Flavor::MINI_CIRCUIT_SIZE - 1 + 50 } } }, + }; +} +} // namespace + +// Every coefficient of the ordered range-constraint polynomials equals the comparison sort of their multisets, +// including ties, padding zeros, the overflow into the fifth polynomial, layouts or values outside the counting path, +// and the masking tail. +TEST(TranslatorOrderedRangeSort, MatchesComparisonSort) +{ + Key key; + key.proving_key = std::make_shared(); + const FF sentinel = FF(uint64_t{ 0x5e7715e1 }); + for (const auto& c : adversarial_cases()) { + fill_range_constraint_groups(key, c); + fill_masking_rows_and_sentinels(key, sentinel); + const auto expected = reference_ordered_values(key, sentinel); + key.compute_translator_range_constraint_ordered_polynomials(); + + auto ordered = key.proving_key->polynomials.get_ordered_range_constraints(); + for (size_t i = 0; i < Flavor::NUM_CONCATENATED_POLYS; i++) { + EXPECT_EQ(ordered[i].start_index(), 1U) << c.name; + EXPECT_EQ(ordered[i].end_index(), CIRCUIT_SIZE) << c.name; + size_t mismatches = 0; + for (size_t pos = 0; pos < expected[i].size(); pos++) { + mismatches += static_cast(ordered[i][pos] != expected[i][pos]); + } + EXPECT_EQ(mismatches, 0U) << c.name << ": ordered_range_constraints_" << i; + } + } +} diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/translator_proving_key.cpp b/barretenberg/cpp/src/barretenberg/translator_vm/translator_proving_key.cpp index 45e0b1e..ba94b91 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/translator_proving_key.cpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/translator_proving_key.cpp @@ -10,6 +10,47 @@ #include namespace bb { +namespace { +// Range of the micro limbs held by the range-constraint wires, and of the sorted steps appended to them. +constexpr size_t MICRO_LIMB_RANGE = size_t{ 1 } << TranslatorProvingKey::Flavor::MICRO_LIMB_BITS; + +/** + * @brief Writes a multiset given by its histogram into `polynomial` at positions [1, end): position `pos` receives + * element `pos` of the multiset's non-descending sequence, so its smallest element is dropped. + * + * @details Each distinct value is converted to a field element once, through `ValueType` as the sorting vectors store + * it. The histogram's counts must sum to at least `end`; it is consumed. + */ +template +void write_sorted_values_from_histogram(std::vector& histogram, + TranslatorProvingKey::Polynomial& polynomial, + size_t end) +{ + using FF = TranslatorProvingKey::FF; + size_t value = 0; + const auto advance_to_next_present_value = [&]() { + while (histogram[value] == 0) { + value++; + BB_ASSERT_LT( + value, histogram.size(), "Translator: histogram holds fewer values than the ordered polynomial"); + } + }; + advance_to_next_present_value(); + histogram[value]--; + size_t converted_value = value; + FF value_as_field = FF(static_cast(value)); + for (size_t pos = 1; pos < end; pos++) { + advance_to_next_present_value(); + if (value != converted_value) { + converted_value = value; + value_as_field = FF(static_cast(value)); + } + polynomial.at(pos) = value_as_field; + histogram[value]--; + } +} +} // namespace + /** * @brief Construct a set of polynomials that are the result of concatenating a group of polynomials into one. * Used in translator to reduce the number of commitments while preserving PCS compatibility. @@ -83,25 +124,73 @@ void TranslatorProvingKey::compute_translator_range_constraint_ordered_polynomia const auto sorted_elements = get_sorted_steps(); auto to_be_concatenated_groups = proving_key->polynomials.get_groups_to_be_concatenated(); const size_t circuit_size = proving_key->polynomials.get_polynomial_size(); + const size_t sorted_values_end = circuit_size - Flavor::MAX_RANDOM_VALUES_PER_ORDERED; + + // Calculate how much space there is for values from the group polynomials given we also need to append the + // additional steps + const size_t free_space_before_runway = dyadic_circuit_size_without_masking - sorted_elements.size(); + + // Number of real values per lane: MINI_CIRCUIT_SIZE positions minus the virtual zero at index 0 + // minus NUM_MASKED_ROWS_END masking rows at the end of each block + static constexpr size_t values_per_lane = Flavor::MINI_CIRCUIT_SIZE - 1 - Flavor::NUM_MASKED_ROWS_END; + + // Sorts group_i by counting: its sorting vector would hold, below the runway, one value per slot, then the steps, + // so a histogram of those values determines the sorted sequence. Applies when the lanes fill every slot below the + // runway exactly once with values below MICRO_LIMB_RANGE; otherwise returns false having written only the + // overflow entries, which the comparison sort rewrites with the same values. + auto order_group_by_counting = [&](size_t i) -> bool { + const auto& group = to_be_concatenated_groups[i]; + std::vector histogram(MICRO_LIMB_RANGE, 0); + size_t num_counted = 0; + size_t extra_denominator_offset = i * sorted_elements.size(); + + for (size_t j = 0; j < Flavor::CONCATENATION_GROUP_SIZE; j++) { + const size_t start = group[j].start_index(); + const size_t end = group[j].end_index() - Flavor::NUM_MASKED_ROWS_END; + // A lane longer than values_per_lane would overwrite the next lane's first slots. + if (end > start && end - start > values_per_lane) { + return false; + } + const size_t current_offset = j * values_per_lane; + for (size_t k = start; k < end; k++) { + const size_t vec_idx = current_offset + (k - start); + const auto value = static_cast(uint256_t(group[j][k]).data[0]); + if (vec_idx < free_space_before_runway) { + if (value >= MICRO_LIMB_RANGE) { + return false; + } + histogram[value]++; + num_counted++; + } else { + extra_denominator_uint[extra_denominator_offset] = value; + extra_denominator_offset++; + } + } + } + + BB_ASSERT(extra_denominator_offset <= (i + 1) * Flavor::SORTED_STEPS_COUNT, + "Translator: overflow entries exceed reserved space in ordered polynomial"); + if (num_counted != free_space_before_runway) { + return false; + } + for (const size_t step : sorted_elements) { + BB_ASSERT_LT(step, MICRO_LIMB_RANGE); + histogram[step]++; + } + write_sorted_values_from_histogram(histogram, ordered_constraint_polynomials[i], sorted_values_end); + return true; + }; // Given the polynomials in group_i, transfer their elements, sorted in non-descending order, into the corresponding // ordered_range_constraint_i up to the given capacity and the remaining elements to the last range constraint. // Sorting is done by converting the elements to uint for efficiency. - auto ordering_function = [&](size_t i) { + auto order_group_by_comparison = [&](size_t i) { const auto& group = to_be_concatenated_groups[i]; std::vector ordered_vectors_uint(dyadic_circuit_size_without_masking); - // Calculate how much space there is for values from the group polynomials given we also need to append the - // additional steps - auto free_space_before_runway = dyadic_circuit_size_without_masking - sorted_elements.size(); - // Calculate the starting index of this group's overflowing elements in the extra denominator polynomial size_t extra_denominator_offset = i * sorted_elements.size(); - // Number of real values per lane: MINI_CIRCUIT_SIZE positions minus the virtual zero at index 0 - // minus NUM_MASKED_ROWS_END masking rows at the end of each block - static constexpr size_t values_per_lane = Flavor::MINI_CIRCUIT_SIZE - 1 - Flavor::NUM_MASKED_ROWS_END; - // Go through each polynomial in the concatenated group for (size_t j = 0; j < Flavor::CONCATENATION_GROUP_SIZE; j++) { @@ -148,15 +237,20 @@ void TranslatorProvingKey::compute_translator_range_constraint_ordered_polynomia // Place sorted values contiguously from position 1 to circuit_size - MAX_RANDOM_VALUES_PER_ORDERED // Position 0 remains 0 (virtual zero). Last MAX_RANDOM_VALUES_PER_ORDERED positions reserved for random values. size_t sorted_idx = 1; // Skip vec[0] (virtual zero at position 0) - for (size_t pos = 1; pos < circuit_size - Flavor::MAX_RANDOM_VALUES_PER_ORDERED; pos++) { + for (size_t pos = 1; pos < sorted_values_end; pos++) { ordered_constraint_polynomials[i].at(pos) = FF(ordered_vectors_uint[sorted_idx]); sorted_idx++; } }; - // Construct the first NUM_CONCATENATED_POLYS - 1 polynomials (range constraint groups only) + // Construct the first NUM_CONCATENATED_POLYS - 1 polynomials (range constraint groups only). The counting attempt + // releases its histogram before the comparison sort allocates its vector. constexpr size_t NUM_RANGE_CONSTRAINT_GROUPS = Flavor::NUM_CONCATENATED_POLYS - 1; - parallel_for(NUM_RANGE_CONSTRAINT_GROUPS, ordering_function); + parallel_for(NUM_RANGE_CONSTRAINT_GROUPS, [&](size_t i) { + if (!order_group_by_counting(i)) { + order_group_by_comparison(i); + } + }); // Advance the iterator into the extra range constraint past the last written element auto extra_denominator_it = extra_denominator_uint.begin(); @@ -164,18 +258,29 @@ void TranslatorProvingKey::compute_translator_range_constraint_ordered_polynomia // Add steps to the extra denominator polynomial to fill it std::copy(sorted_elements.cbegin(), sorted_elements.cend(), extra_denominator_it); - // Sort it + + // Place sorted values for the 5th polynomial, by counting when every value is below MICRO_LIMB_RANGE + // All polynomials reserve the same amount of space at the end + auto order_extra_by_counting = [&]() -> bool { + std::vector histogram(MICRO_LIMB_RANGE, 0); + for (const size_t value : extra_denominator_uint) { + if (value >= MICRO_LIMB_RANGE) { + return false; + } + histogram[value]++; + } + write_sorted_values_from_histogram( + histogram, proving_key->polynomials.ordered_range_constraints_4, sorted_values_end); + return true; + }; + if (!order_extra_by_counting()) { #ifdef NO_PAR_ALGOS - std::sort(extra_denominator_uint.begin(), extra_denominator_uint.end()); + std::sort(extra_denominator_uint.begin(), extra_denominator_uint.end()); #else - std::sort(std::execution::par_unseq, extra_denominator_uint.begin(), extra_denominator_uint.end()); + std::sort(std::execution::par_unseq, extra_denominator_uint.begin(), extra_denominator_uint.end()); #endif - - // Place sorted values for the 5th polynomial - // All polynomials reserve the same amount of space at the end - { size_t sorted_idx = 1; // Skip vec[0] (virtual zero at position 0) - for (size_t pos = 1; pos < circuit_size - Flavor::MAX_RANDOM_VALUES_PER_ORDERED; pos++) { + for (size_t pos = 1; pos < sorted_values_end; pos++) { proving_key->polynomials.ordered_range_constraints_4.at(pos) = FF(extra_denominator_uint[sorted_idx]); sorted_idx++; } diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/range_list_sort.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/range_list_sort.test.cpp new file mode 100644 index 0000000..0467826 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/range_list_sort.test.cpp @@ -0,0 +1,66 @@ +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include + +#include +#include + +using namespace bb; + +namespace { +/** + * @brief Processes a range list holding one fresh variable per value and + * returns the values of the sorted-list variables the builder adds, which + * process_range_list appends in sorted order. + */ +std::vector sorted_by_builder(uint64_t target_range, const std::vector& values) +{ + UltraCircuitBuilder builder; + UltraCircuitBuilder::RangeList list{ .target_range = target_range, + .range_tag = builder.get_new_tag(), + .tau_tag = builder.get_new_tag(), + .variable_indices = {} }; + for (const uint32_t value : values) { + list.variable_indices.push_back(builder.add_variable(fr(value))); + } + const size_t first_sorted = builder.get_num_variables(); + builder.process_range_list(list); + std::vector sorted; + for (size_t i = 0; i < values.size(); ++i) { + sorted.push_back(uint256_t(builder.get_variable(static_cast(first_sorted + i))).data[0]); + } + return sorted; +} + +std::vector reference_sort(const std::vector& values) +{ + std::vector sorted(values.begin(), values.end()); + std::sort(sorted.begin(), sorted.end()); + return sorted; +} +} // namespace + +// Each case is a list with duplicates; the sorted variables must equal an +// independent sort of the values whichever way the builder sorts them. +TEST(RangeListSort, SortedVariablesMatchAReferenceSort) +{ + std::vector many; + for (uint32_t i = 0; i < 500; ++i) { + many.push_back((i * 37) % 101); + } + const struct { + const char* name; + uint64_t target_range; + std::vector values; + } cases[] = { + { "small range", 50, { 7, 0, 50, 7, 13, 13, 49, 0 } }, + { "small range, many duplicates", 100, many }, + { "single element", 10, { 4 } }, + { "value above the range", 20, { 3, 25, 3, 0, 20, 25 } }, + { "range of 2^16", uint64_t(1) << 16, { 65536, 1, 40000, 1, 0, 40000 } }, + { "range above 2^16", (uint64_t(1) << 16) + 5, { 65540, 2, 65536, 2, 9 } }, + }; + for (const auto& c : cases) { + EXPECT_EQ(sorted_by_builder(c.target_range, c.values), reference_sort(c.values)) << c.name; + } +}