From be4cb02d415ae350209b418739fe6e1b0c1d6532 Mon Sep 17 00:00:00 2001 From: IlyasRidhuan Date: Thu, 5 Nov 2026 15:27:39 +0000 Subject: [PATCH 001/116] perf: enable advisory scalar deduplication for AVM wires Only enable the existing MSM scheduling hint for witness wire commitments. Equal scalars multiply aggregated base points, preserving commitment group elements, transcript ordering and randomness consumption. Leave inverse commitments unchanged. (cherry picked from commit 85ee5510f567517560327e451b056f517696b1c3) --- barretenberg/cpp/src/barretenberg/vm2/constraining/prover.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/barretenberg/cpp/src/barretenberg/vm2/constraining/prover.cpp b/barretenberg/cpp/src/barretenberg/vm2/constraining/prover.cpp index 84a874f..af305ad 100644 --- a/barretenberg/cpp/src/barretenberg/vm2/constraining/prover.cpp +++ b/barretenberg/cpp/src/barretenberg/vm2/constraining/prover.cpp @@ -101,7 +101,7 @@ void AvmProver::execute_wire_commitments_round() // logderivative phase) auto batch = commitment_key.start_batch(); for (const auto& [poly, label] : zip_view(prover_polynomials.get_wires(), prover_polynomials.get_wires_labels())) { - batch.add_to_batch(poly, label); + batch.add_to_batch(poly, label, /*has_duplicates_hint=*/true); } batch.commit_and_send_to_verifier(transcript); } From e0b646c17ac572cabd82a249c71074526901ab45 Mon Sep 17 00:00:00 2001 From: opt Date: Sun, 11 Oct 2026 00:19:18 +0000 Subject: [PATCH 002/116] uint256: accelerate single-limb division and remainder Long division by one limb computes the same exact quotient and remainder with a bounded carry chain; it changes no field/protocol inputs. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0003-perf-single-limb-fast-path-in-uint256-divmod-chunked.patch Source SHA256: fe35739a2d7a45b62b51fe9413c180371196f4cac5e44071ebfeb0dd890df9ae Original author: opt Series feature ID: 001 (0003.division) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. (cherry picked from commit 2d2c6cfd780e76cdeb0ad72bcd90700689e08e95) --- .../numeric/uint256/uint256_impl.hpp | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/barretenberg/cpp/src/barretenberg/numeric/uint256/uint256_impl.hpp b/barretenberg/cpp/src/barretenberg/numeric/uint256/uint256_impl.hpp index 6e0cecd..18d7567 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/uint256/uint256_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/numeric/uint256/uint256_impl.hpp @@ -149,6 +149,11 @@ constexpr std::pair uint256_t::divmod(const uint256_t& b) if (b > *this) { return { 0, *this }; } + // Single-limb divisor: limb-wise long division is far cheaper than the bitwise shift-subtract loop below. + if ((b.data[1] | b.data[2] | b.data[3]) == 0) { + const auto [q, r] = divmod(b.data[0]); + return { q, uint256_t(r) }; + } uint256_t quotient = 0; uint256_t remainder = *this; @@ -212,9 +217,45 @@ constexpr std::pair uint256_t::divmod(uint64_t b) const } return { quotient, remainder }; #else - // Fallback to the general divmod since wasm doesn't have native support for 128-bit instructions. - auto [q, r] = divmod(uint256_t(b)); - return { q, static_cast(r.data[0]) }; + if (b <= 0xffffffffULL) { + // Schoolbook long division in base 2^32: each step divides a 64-bit intermediate (remainder << 32 | half-limb) + // by b, which only needs native 64-bit arithmetic. + uint256_t quotient; + uint64_t remainder = 0; + for (int i = 3; i >= 0; --i) { + const uint64_t hi = (remainder << 32) | (data[i] >> 32); + const uint64_t q_hi = hi / b; + remainder = hi % b; + const uint64_t lo = (remainder << 32) | (data[i] & 0xffffffffULL); + const uint64_t q_lo = lo / b; + remainder = lo % b; + quotient.data[i] = (q_hi << 32) | q_lo; + } + return { quotient, remainder }; + } + // Fallback to the bitwise division since wasm doesn't have native support for 128-bit instructions. + uint256_t quotient = 0; + uint256_t remainder = *this; + const uint256_t divisor_256(b); + if (divisor_256 > remainder) { + return { 0, data[0] }; + } + uint64_t bit_difference = get_msb() - divisor_256.get_msb(); + uint256_t divisor = divisor_256 << bit_difference; + uint256_t accumulator = uint256_t(1) << bit_difference; + if (divisor > remainder) { + divisor >>= 1; + accumulator >>= 1; + } + while (remainder >= divisor_256) { + if (remainder >= divisor) { + remainder -= divisor; + quotient |= accumulator; + } + divisor >>= 1; + accumulator >>= 1; + } + return { quotient, static_cast(remainder.data[0]) }; #endif } From 97231dd1a7bd3ccb12fee679b0162dd0010d5696 Mon Sep 17 00:00:00 2001 From: opt Date: Sun, 11 Oct 2026 00:19:18 +0000 Subject: [PATCH 003/116] keccak: normalize sparse chunks using single-limb division The same sparse base-11 digits are extracted in bounded chunks; quotient/remainder arithmetic preserves the original witnesses. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): 001. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0003-perf-single-limb-fast-path-in-uint256-divmod-chunked.patch Source SHA256: fe35739a2d7a45b62b51fe9413c180371196f4cac5e44071ebfeb0dd890df9ae Original author: opt Series feature ID: 002 (0003.keccak) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. (cherry picked from commit 49031c96500d0a751abb6788f2daa88aa4ba740d) --- .../stdlib/hash/keccak/keccak.hpp | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.hpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.hpp index 86f54ca..e185270 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.hpp @@ -5,6 +5,7 @@ // ===================== #pragma once +#include "barretenberg/numeric/bitop/pow.hpp" #include "barretenberg/stdlib/primitives/byte_array/byte_array.hpp" #include @@ -92,19 +93,31 @@ template class keccak { */ static constexpr uint256_t normalize_sparse(uint256_t input) { - std::array out_bits; - size_t count = 0; + // Peel off the base-11 digits in chunks of NORMALIZE_CHUNK_DIGITS so that only one wide division is needed + // per chunk and the per-digit work is native 64-bit arithmetic. The chunk base fits in a single limb (and in + // 32 bits on wasm, where only 64-bit native division is available). +#if defined(__wasm__) + constexpr size_t NORMALIZE_CHUNK_DIGITS = 9; +#else + constexpr size_t NORMALIZE_CHUNK_DIGITS = 18; +#endif + constexpr uint64_t chunk_base = numeric::pow64(11, NORMALIZE_CHUNK_DIGITS); + uint256_t out = 0; + uint256_t chunk_place = 1; while (input > 0) { - const auto [quotient, slice] = input.divmod(BASE); - uint64_t bit = static_cast(slice) & 1; - out_bits[count++] = bit; + const auto [quotient, chunk] = input.divmod(chunk_base); + uint64_t remaining = chunk; + uint64_t normalized_chunk = 0; + uint64_t digit_place = 1; + for (size_t i = 0; i < NORMALIZE_CHUNK_DIGITS && remaining > 0; ++i) { + normalized_chunk += ((remaining % 11) & 1) * digit_place; + remaining /= 11; + digit_place *= 11; + } + out += chunk_place * uint256_t(normalized_chunk); + chunk_place *= uint256_t(chunk_base); input = quotient; } - uint256_t out; - for (size_t i = 0; i < count; ++i) { - out *= BASE; - out += out_bits[count - 1 - i]; - } return out; } From 4e03a2acc54f87865eb70d97be505fbd54e83efd Mon Sep 17 00:00:00 2001 From: opt Date: Sun, 11 Oct 2026 00:31:03 +0000 Subject: [PATCH 004/116] perf(msm): fused scalar batch-affine drain for native Stage 6a The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0004-perf-msm-fused-scalar-batch-affine-drain-for-native-.patch Source SHA256: d9dfa0c5539864cbde9c5a2ff3e9052d8becb45f0e765e3960f6d6f9f549de7f Original author: opt Series feature ID: 003 (0004) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. (cherry picked from commit 6fc7a8c53fb0a406bc5734064bdfa046e2021541) --- .../scalar_multiplication_fast.cpp | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) 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 97ee46f..df1f595 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 @@ -294,8 +294,126 @@ template inline void drain_batch(ThreadScratch& s, size_ * On return, `s.result_len` holds the deduplicated count and the surviving * (point, bucket) pairs occupy curr_pts/curr_buckets[0..result_len). */ +/** + * @brief Scalar (non-SIMD) drain: curr_pts[pair_dest[k]] = lhs[k] + rhs[k] for k < pair_count, where the operands + * live as plain field elements in the packed-drain backing (see `scalar_drain_slot`). + * + * @details Montgomery's trick fused with the affine-add finish: a forward pass forms dx = x2 - x1 and the running + * prefix products, one field inversion inverts the full product, and a backward pass peels off each + * 1 / dx_k, completes the slope and writes the sum straight to its destination slot. Six multiplications + * per pair, with every intermediate held in registers rather than in packed VectorField temporaries. + */ +template +inline void drain_batch_scalar(ThreadScratch& s, size_t pair_count) noexcept +{ + using BaseField = typename Curve::BaseField; + if (pair_count == 0) { + return; + } + auto& lx = s.lhs.x.vector_fields; + auto& ly = s.lhs.y.vector_fields; + auto& rx = s.rhs.x.vector_fields; + auto& ry = s.rhs.y.vector_fields; + auto& dxs = s.add_scratch.dx.vector_fields; + auto& prefix = s.add_scratch.inv.vector_fields; + constexpr size_t W = bb::VectorField::SIZE; + + BaseField acc = BaseField::one(); + for (size_t k = 0; k < pair_count; ++k) { + const size_t g = k / W; + const size_t l = k % W; + const BaseField dx = rx[g].elts[l] - lx[g].elts[l]; + dxs[g].elts[l] = dx; + prefix[g].elts[l] = acc; + acc *= dx; + } + if (acc.is_zero()) { + throw_or_abort("batch_invert: attempted to invert zero"); + } + acc = acc.invert(); + for (size_t k = pair_count; k-- > 0;) { + const size_t g = k / W; + const size_t l = k % W; + const BaseField inv = acc * prefix[g].elts[l]; + acc *= dxs[g].elts[l]; + const BaseField& x1 = lx[g].elts[l]; + const BaseField& y1 = ly[g].elts[l]; + const BaseField slope = (ry[g].elts[l] - y1) * inv; + const BaseField x3 = slope.sqr() - (x1 + rx[g].elts[l]); + auto& dst = s.curr_pts[s.pair_dest[k]]; + dst.y = slope * (x1 - x3) - y1; + dst.x = x3; + } +} + +/** + * @brief Scalar (non-SIMD) twin of tree_reduce_in_place's level walk: identical pairing and compaction, with the + * queued operands written as plain field elements into the packed-drain backing and drained by + * drain_batch_scalar. + */ +template void tree_reduce_in_place_scalar(ThreadScratch& s, size_t initial_len) noexcept +{ + using BaseField = typename Curve::BaseField; + constexpr size_t W = bb::VectorField::SIZE; + auto& lx = s.lhs.x.vector_fields; + auto& ly = s.lhs.y.vector_fields; + auto& rx = s.rhs.x.vector_fields; + auto& ry = s.rhs.y.vector_fields; + size_t curr_len = initial_len; + + while (true) { + size_t i = 0; + size_t next_len = 0; + size_t pair_count = 0; + bool made_pair = false; + + while (i < curr_len) { + if (i + 1 < curr_len && s.curr_buckets[i] == s.curr_buckets[i + 1]) { + const size_t g = pair_count / W; + const size_t l = pair_count % W; + lx[g].elts[l] = s.curr_pts[i].x; + ly[g].elts[l] = s.curr_pts[i].y; + rx[g].elts[l] = s.curr_pts[i + 1].x; + ry[g].elts[l] = s.curr_pts[i + 1].y; + s.curr_buckets[next_len] = s.curr_buckets[i]; + s.pair_dest[pair_count] = static_cast(next_len); + ++next_len; + ++pair_count; + i += 2; + made_pair = true; + + if (pair_count >= BATCH_CAPACITY) { + drain_batch_scalar(s, pair_count); + pair_count = 0; + } + } else { + s.curr_pts[next_len] = s.curr_pts[i]; + s.curr_buckets[next_len] = s.curr_buckets[i]; + ++next_len; + ++i; + } + } + + drain_batch_scalar(s, pair_count); + + if (!made_pair) { + break; + } + + curr_len = next_len; + } + + s.result_len = curr_len; +} + template void tree_reduce_in_place(ThreadScratch& s, size_t initial_len) noexcept { + // Without SIMD a VectorField is just W scalar field elements, so the packed drain only adds data movement; + // run the fused scalar drain instead. + if constexpr (!bb::simd_available_v) { + tree_reduce_in_place_scalar(s, initial_len); + return; + } size_t curr_len = initial_len; // The drain spans (lhs/rhs) are scratch shared with the Stage-6b reduction, which leaves a non-zero From 3a431c78e3f386fbbe8d0d71aa037fd46ee5b3ac Mon Sep 17 00:00:00 2001 From: opt Date: Sun, 11 Oct 2026 00:43:40 +0000 Subject: [PATCH 005/116] perf(translator): fetch only grand-product columns per row The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0005-perf-translator-fetch-only-grand-product-columns-per.patch Source SHA256: d0a729df4241c815814791e8fd7c72e22ef35dd2430421dbdfe5ed92c6ee29cf Original author: opt Series feature ID: 004 (0005) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. (cherry picked from commit 49ff278a8163b9b371876b6f01cb0d45258c8381) --- .../honk/library/grand_product_library.hpp | 2 ++ .../translator_vm/translator_flavor.hpp | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+) 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 f8dde2b..3080185 100644 --- a/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp @@ -124,6 +124,8 @@ void compute_grand_product(typename Flavor::ProverPolynomials& full_polynomials, // TODO: consider avoiding get_row if possible. if constexpr (IsUltraOrMegaHonk) { row = full_polynomials.get_row_for_permutation_arg(poly_idx); + } else if constexpr (requires { full_polynomials.get_row_for_grand_product(poly_idx); }) { + row = full_polynomials.get_row_for_grand_product(poly_idx); } else { row = full_polynomials.get_row(poly_idx); } diff --git a/barretenberg/cpp/src/barretenberg/translator_vm/translator_flavor.hpp b/barretenberg/cpp/src/barretenberg/translator_vm/translator_flavor.hpp index 5fd10c1..4869abb 100644 --- a/barretenberg/cpp/src/barretenberg/translator_vm/translator_flavor.hpp +++ b/barretenberg/cpp/src/barretenberg/translator_vm/translator_flavor.hpp @@ -1146,6 +1146,33 @@ class TranslatorFlavor { } return result; } + /** + * @brief Returns, at one point of the boolean hypercube, only the evaluations read by the numerator and + * denominator of TranslatorPermutationRelation (the grand product computation). All other entries of the + * returned AllValues are left uninitialized. + */ + [[nodiscard]] AllValues get_row_for_grand_product(size_t row_idx) const + { + const auto value_at = [row_idx](const Polynomial& polynomial) { + return (row_idx >= polynomial.start_index() && row_idx < polynomial.end_index()) ? polynomial[row_idx] + : FF(0); + }; + AllValues result; + result.concatenated_range_constraints_0 = value_at(this->concatenated_range_constraints_0); + result.concatenated_range_constraints_1 = value_at(this->concatenated_range_constraints_1); + result.concatenated_range_constraints_2 = value_at(this->concatenated_range_constraints_2); + result.concatenated_range_constraints_3 = value_at(this->concatenated_range_constraints_3); + result.ordered_extra_range_constraints_numerator = + value_at(this->ordered_extra_range_constraints_numerator); + result.ordered_range_constraints_0 = value_at(this->ordered_range_constraints_0); + result.ordered_range_constraints_1 = value_at(this->ordered_range_constraints_1); + result.ordered_range_constraints_2 = value_at(this->ordered_range_constraints_2); + result.ordered_range_constraints_3 = value_at(this->ordered_range_constraints_3); + result.ordered_range_constraints_4 = value_at(this->ordered_range_constraints_4); + result.lagrange_masking = value_at(this->lagrange_masking); + result.lagrange_ordered_masking = value_at(this->lagrange_ordered_masking); + return result; + } // Set all shifted polynomials based on their to-be-shifted counterpart. // Uses get_all_to_be_shifted() (86 entries for Sumcheck), not get_to_be_shifted() (9 entries for PCS). void set_shifted() From d6eb175d776981f7d8532d6dcd2792447404ccbe Mon Sep 17 00:00:00 2001 From: opt Date: Sun, 11 Oct 2026 00:51:39 +0000 Subject: [PATCH 006/116] perf(sumcheck): skip fold multiply for bit-identical neighbour pairs The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0006-perf-sumcheck-skip-fold-multiply-for-bit-identical-n.patch Source SHA256: a020292acd79a53372a3fffef7a4e5a23af11507ce46e514527d9018c08804d8 Original author: opt Series feature ID: 005 (0006) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. (cherry picked from commit a2a5b786027d10b1d8a1940a0eba9c362c1fa7c4) --- .../cpp/src/barretenberg/polynomials/fold_stride2.hpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp index 4709491..0b56f20 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp @@ -56,7 +56,15 @@ void fold_stride2( #endif for (; k < end; ++k) { const Fr even = src[2 * k]; - dst[ScalarIndex{ k }] = even + challenge * (src[2 * k + 1] - even); + const Fr odd = src[2 * k + 1]; + // Equal neighbours (constant selector runs, zero padding inside the active extent) fold to themselves, so + // skip the multiplication. Only bit-identical representations are short-cut. + if (even.data[0] == odd.data[0] && even.data[1] == odd.data[1] && even.data[2] == odd.data[2] && + even.data[3] == odd.data[3]) { + dst[ScalarIndex{ k }] = even; + } else { + dst[ScalarIndex{ k }] = even + challenge * (odd - even); + } } } From b45aedeb3e1377c48be1db0ca6c0631a3b35ddde Mon Sep 17 00:00:00 2001 From: bench Date: Sun, 11 Oct 2026 01:44:08 +0000 Subject: [PATCH 007/116] perf(ecc): batched variable-time divsteps in Bernstein-Yang inverse The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Original author rationale (historical, not a new measurement): Evaluate each BATCH of safegcd divsteps several at a time (the variable-time formulation of libsecp256k1's modinv64): count-trailing-zeros consumes a run of g-even steps at once, and consecutive g <- (g + f)/2 steps collapse into a single g <- g + w*f cancelling up to 4 (6 after a swap) low bits. Same divstep sequence, matrix and delta as the one-step-per-iteration loop, without one unpredictable branch per divstep. Shared by the Native5x64 and Wasm9x29 kernels. Fq inversion 2.97 us -> 1.60 us on the 4-vCPU bench VM. Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0007-perf-ecc-batched-variable-time-divsteps-in-Bernstein.patch Source SHA256: deb7fdb309ee98d4a5186c645f3f82bb40a44ab8eaff3bf341ba11922fd8ec85 Original author: bench Series feature ID: 006 (0007) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. (cherry picked from commit 6b9ad56fef95d5645560931346bea98c8ce2f067) --- .../ecc/fields/bernstein_yang_inverse.hpp | 122 ++++++++++++------ .../fields/bernstein_yang_inverse_wasm.hpp | 30 +---- 2 files changed, 83 insertions(+), 69 deletions(-) diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse.hpp index 4e4190d..3f534b9 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse.hpp @@ -23,6 +23,7 @@ #pragma once #include "barretenberg/numeric/uint256/uint256.hpp" +#include #include namespace bb::bernstein_yang { @@ -40,6 +41,86 @@ struct DivstepMatrix { i64 u, v, q, r; }; +// Each divstep shrinks |g| by ~1 bit using a binary-GCD-style move. +// Three cases, depending on g's parity and the "δ" tracker (which decides +// whether |f| or |g| is currently smaller): +// g even : g ← g/2. +// g odd, δ ≤ 0 : g ← (g + f)/2 (adding f to make g+f even before /2). +// g odd, δ > 0 : swap roles — (f, g) ← (g, (g - f)/2). +// The matrix (u, v, q, r) tracks the same linear transform applied +// symbolically; doubling u, v (or q, r) corresponds to the implicit /2 each +// divstep performs. After BATCH divsteps the low BATCH bits of the +// transformed state are guaranteed zero, so apply_divstep_matrix's implicit +// "/ 2^BATCH" is an exact integer division. +// +// The BATCH divsteps are evaluated several at a time (the variable-time +// formulation of libsecp256k1's modinv64, safegcd_implementation.md §5), +// producing the same matrix and δ as stepping one divstep at a time: +// - a run of z trailing zero bits of g is z "g even" steps at once +// (count-trailing-zeros, shift g, double u and v); +// - with g odd, the δ > 0 swap is applied as (f, g) ← (g, -f) followed by +// "g odd, δ ≤ 0"-style steps, and consecutive "g ← (g + f)/2" steps +// taken while δ stays ≤ 0 collapse into one g ← g + w·f, where w ≡ -g/f +// cancels up to min(δ' + 1, steps left, 6 or 4) low bits of g; the +// zero bits this creates are consumed by the next count-trailing-zeros. +// The work is ~one iteration per few divsteps instead of one unpredictable +// branch per divstep. Shared by Native5x64 (BATCH = 62) and Wasm9x29 +// (BATCH = 58); only the low BATCH bits of f_lo and g_lo are read. +template inline DivstepMatrix compute_divsteps_vartime(i64& delta, u64 f_lo, u64 g_lo) noexcept +{ + static_assert(BATCH > 0 && BATCH <= 62); + // Unsigned two's-complement arithmetic throughout; every entry stays within + // ±2^BATCH, so the final reinterpretation as i64 is exact. eta = -δ. + u64 u = 1, v = 0, q = 0, r = 1; + u64 f = f_lo, g = g_lo; + i64 eta = -delta; + int i = BATCH; + while (true) { + // Sentinel bit at position i caps the zero count at the divsteps left. + const int zeros = __builtin_ctzll(g | (~u64{ 0 } << i)); + g >>= zeros; + u <<= zeros; + v <<= zeros; + eta -= zeros; + i -= zeros; + if (i == 0) { + break; + } + // f and g are both odd here. + u64 m; + u64 w; + if (eta < 0) { + // δ > 0 swap: (f, g) ← (g, -f), and (u, v, q, r) ← (q, r, -u, -v). + eta = -eta; + u64 tmp = f; + f = g; + g = 0 - tmp; + tmp = u; + u = q; + q = 0 - tmp; + tmp = v; + v = r; + r = 0 - tmp; + // Cancel up to min(eta + 1, i, 6) low bits of g: w = -g · f⁻¹ mod 2^6, with + // f⁻¹ ≡ f · (2 - f²) mod 2^6 (one Newton step from f⁻¹ ≡ f mod 2^3). + const int limit = static_cast(std::min(eta + 1, i)); + m = (~u64{ 0 } >> (64 - limit)) & 63U; + w = (f * g * (f * f - 2)) & m; + } else { + // Cancel up to min(eta + 1, i, 4) low bits of g: w = -g · f⁻¹ mod 2^4. + const int limit = static_cast(std::min(eta + 1, i)); + m = (~u64{ 0 } >> (64 - limit)) & 15U; + w = f + (((f + 1) & 4) << 1); + w = (0 - w * g) & m; + } + g += f * w; + q += u * w; + r += v * w; + } + delta = -eta; + return { static_cast(u), static_cast(v), static_cast(q), static_cast(r) }; +} + // 5 × 64-bit limbs, top limb two's-complement signed. Products via __int128. class Native5x64 { public: @@ -211,48 +292,9 @@ struct NativeMatrix { } }; -// Each inner step shrinks |g| by ~1 bit using a binary-GCD-style move. -// Three cases, depending on g's parity and the "δ" tracker (which decides -// whether |f| or |g| is currently smaller): -// g even : g ← g/2. -// g odd, δ ≤ 0 : g ← (g + f)/2 (adding f to make g+f even before /2). -// g odd, δ > 0 : swap roles — (f, g) ← (g, (g - f)/2). -// The matrix (u, v, q, r) tracks the same linear transform applied -// symbolically; doubling u, v (or q, r) corresponds to the implicit /2 each -// inner step performs. After BATCH steps the low BATCH bits of the -// transformed state are guaranteed zero, so apply_divstep_matrix's implicit -// "/ 2^BATCH" is an exact integer division. inline DivstepMatrix Native5x64::compute_divstep_matrix(i64& delta, u64 f_lo, u64 g_lo) noexcept { - i64 u = 1, v = 0, q = 0, r = 1; - for (int i = 0; i < BATCH; ++i) { - if (g_lo & 1) { - if (delta > 0) { - u64 nf = g_lo, ng = (g_lo - f_lo) >> 1; - i64 nu = q << 1, nv = r << 1, nq = q - u, nr = r - v; - f_lo = nf; - g_lo = ng; - u = nu; - v = nv; - q = nq; - r = nr; - delta = 1 - delta; - } else { - g_lo = (g_lo + f_lo) >> 1; - q = q + u; - r = r + v; - u <<= 1; - v <<= 1; - delta = delta + 1; - } - } else { - g_lo >>= 1; - u <<= 1; - v <<= 1; - delta = delta + 1; - } - } - return { u, v, q, r }; + return compute_divsteps_vartime(delta, f_lo, g_lo); } inline void Native5x64::apply_divstep_matrix(const DivstepMatrix& m, diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse_wasm.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse_wasm.hpp index 4d728e3..f0ea003 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse_wasm.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/bernstein_yang_inverse_wasm.hpp @@ -164,35 +164,7 @@ inline void Wasm9x29::reduce_to_canonical(const Wasm9x29& p) noexcept inline DivstepMatrix Wasm9x29::compute_divstep_matrix(i64& delta, u64 f_lo, u64 g_lo) noexcept { - i64 u = 1, v = 0, q = 0, r = 1; - for (int i = 0; i < BATCH; ++i) { - if (g_lo & 1) { - if (delta > 0) { - u64 nf = g_lo, ng = (g_lo - f_lo) >> 1; - i64 nu = q << 1, nv = r << 1, nq = q - u, nr = r - v; - f_lo = nf; - g_lo = ng; - u = nu; - v = nv; - q = nq; - r = nr; - delta = 1 - delta; - } else { - g_lo = (g_lo + f_lo) >> 1; - q = q + u; - r = r + v; - u <<= 1; - v <<= 1; - delta = delta + 1; - } - } else { - g_lo >>= 1; - u <<= 1; - v <<= 1; - delta = delta + 1; - } - } - return { u, v, q, r }; + return compute_divsteps_vartime(delta, f_lo, g_lo); } // Streamed schoolbook: for each limb position i compute From 299066833e24480e843b17eccf24de8641cd0c0e Mon Sep 17 00:00:00 2001 From: bench Date: Sun, 11 Oct 2026 01:50:58 +0000 Subject: [PATCH 008/116] perf(sumcheck): fold subrelation separators into Poseidon2 quad relations on the prover The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test. Applicability: Native cumulative prover source; effect varies by flow and available ISA. Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites. Optional performance companions (not semantic requirements): none. Patch-context predecessors: accepted base. The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests. Original author rationale (historical, not a new measurement): Poseidon2QuadInternal, Poseidon2QuadInternalTerminal and Poseidon2TransitionEntry apply different constant linear maps to the same S-box outputs in each subrelation and scale every subrelation by the same selector factor. SumcheckProverRound now hands relations that opt in (SubrelationBatchingConstants) their subrelation separators relative to the first one; such a relation accumulates the separator-weighted sum of its subrelations into the first accumulator. Each S-box constant is folded into the degree-1 factor of x^5 = x^4 * x, so the per-row cost of the quad internal relation drops from ~320 to ~155 field multiplications. scale_univariates then multiplies by the first separator, so the round univariate is unchanged. Verifier paths are untouched. Mandatory integrated corrections: complete CPU/OS ISA detection and pinned-compiler target compatibility where applicable; MessagePack EXT copying or flavor tuple preservation at the feature that first needs it. They are not deferred broken intermediate states. Correction source: research/sol-tuple-family-fix/0078-preserve-flavor-tuple-family-in-subrelation-batching.patch sha256=23b2316d8a66cc99e7661324d037dd0f7fe395de870dd4681285798d7bab2a6e Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required. Source mail: client-research/chonk-golf/sources/final2/patches/0008-perf-sumcheck-fold-subrelation-separators-into-Posei.patch Source SHA256: 1b6488c6f52c21c1c49cbb06656bbc513a97f820d146c8edc433a70ce741854b Original author: bench Series feature ID: 007 (0008) Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout. Co-authored-by: Golf Research (cherry picked from commit eae7408a4d8682db8a25ce54152aa5eaf1294129) --- .../poseidon2_quad_internal_relation.hpp | 94 +++++++++++ ...eidon2_quad_internal_terminal_relation.hpp | 79 +++++++++ .../poseidon2_transition_entry_relation.hpp | 70 ++++++++ .../barretenberg/sumcheck/sumcheck_round.hpp | 150 +++++++++++++++--- .../sumcheck/sumcheck_round.test.cpp | 82 ++++++++++ 5 files changed, 453 insertions(+), 22 deletions(-) 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 89030ed..8f35f9d 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_quad_internal_relation.hpp @@ -188,6 +188,100 @@ template class Poseidon2QuadInternalRelationImpl { u_1_next * D1_MINUS_3 + u_2_next * D1 + Accumulator(wp3_full); std::get<3>(evals) += q_times_scaling * a3_body; } + + /** + * @brief Prover-only constants of the separator-weighted sum of the four subrelation bodies (see + * HasProverSubrelationBatching): \f$ \sum_k w_k A_k = \sum_i m_i u_i + \sum_j n_j \cdot \text{wire}_j \f$. + */ + struct SubrelationBatchingConstants { + std::array sbox; // m_i for u_0, u_1, u_2, u_3, u_0', u_1', u_2' + std::array wires; // n_j for w_r, w_o, w_4, w_l_shift, w_r_shift, w_o_shift, w_4_shift + }; + + static SubrelationBatchingConstants compute_subrelation_batching_constants(const std::array& weights) + { + const auto& cf0 = QuadParams::tables.closed_form[0]; + const auto& l0 = QuadParams::tables.forward_vandermonde_lhs[0]; + const auto& l1 = QuadParams::tables.forward_vandermonde_lhs[1]; + const auto& l2 = QuadParams::tables.forward_vandermonde_lhs[2]; + SubrelationBatchingConstants constants; + for (size_t i = 0; i < 4; ++i) { + constants.sbox[i] = + weights[0] * cf0[3 + i] + weights[1] * l0[3 + i] + weights[2] * l1[3 + i] + weights[3] * l2[3 + i]; + } + for (size_t j = 0; j < 3; ++j) { + constants.wires[j] = weights[0] * cf0[j] + weights[1] * l0[j] + weights[2] * l1[j] + weights[3] * l2[j]; + } + // u_0' enters A_1 with D_1, A_2 with 3 - 2 D_1 and A_3 with -B3_U0_COEF; u_1' enters A_2 with D_1 and A_3 with + // -(D_1 - 3); u_2' enters A_3 with D_1. + constants.sbox[4] = weights[1] * D1 + weights[2] * (fr(3) - D1 - D1) - weights[3] * B3_U0_COEF; + constants.sbox[5] = weights[2] * D1 - weights[3] * D1_MINUS_3; + constants.sbox[6] = weights[3] * D1; + constants.wires[3] = -weights[0]; + constants.wires[4] = weights[2] + weights[2] + weights[3] * SIGMA_PLUS_2 - weights[1]; + constants.wires[5] = weights[3] - weights[2]; + constants.wires[6] = -weights[3]; + return constants; + } + + /** + * @brief Prover-only: add \f$ q \cdot \text{scaling} \cdot \sum_k w_k A_k \f$ into the first subrelation + * accumulator. Each S-box output is scaled by its constant before the last multiplication of x^5 = x^4 \cdot x, in + * the degree-1 coefficient basis, so the weighted sum costs no full-length multiplications beyond the S-boxes. + */ + template + static void accumulate_with_subrelation_batching(ContainerOverSubrelations& evals, + const AllEntities& in, + const Parameters& /*params*/, + const FF& scaling_factor, + const SubrelationBatchingConstants& constants) + { + using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; + using CoeffAcc = typename Accumulator::CoefficientAccumulator; + + const auto w_l = CoeffAcc(in[AllEntities::EntityId::w_l]); + const auto w_r = CoeffAcc(in[AllEntities::EntityId::w_r]); + const auto w_o = CoeffAcc(in[AllEntities::EntityId::w_o]); + const auto w_4 = CoeffAcc(in[AllEntities::EntityId::w_4]); + const auto w_l_shift = CoeffAcc(in[AllEntities::EntityId::w_l_shift]); + const auto w_r_shift = CoeffAcc(in[AllEntities::EntityId::w_r_shift]); + const auto w_o_shift = CoeffAcc(in[AllEntities::EntityId::w_o_shift]); + const auto w_4_shift = CoeffAcc(in[AllEntities::EntityId::w_4_shift]); + + const auto q_l = CoeffAcc(in[AllEntities::EntityId::q_l]); + const auto q_r = CoeffAcc(in[AllEntities::EntityId::q_r]); + const auto q_o = CoeffAcc(in[AllEntities::EntityId::q_o]); + const auto q_4 = CoeffAcc(in[AllEntities::EntityId::q_4]); + const auto q_m = CoeffAcc(in[AllEntities::EntityId::q_m]); + const auto q_c = CoeffAcc(in[AllEntities::EntityId::q_c]); + const auto q_5 = CoeffAcc(in[AllEntities::EntityId::q_5]); + const auto q_sel = CoeffAcc(in[AllEntities::EntityId::q_poseidon2_quad_internal]); + + // m * x^5 = (x^2)^2 * (m * x) + auto scaled_pow5 = [](const auto& x_m, const FF& m) -> Accumulator { + const Accumulator sq(x_m.sqr()); + return sq.sqr() * Accumulator(x_m * m); + }; + + auto body = scaled_pow5(w_l + q_l, constants.sbox[0]); + body += scaled_pow5(w_r + q_r, constants.sbox[1]); + body += scaled_pow5(w_o + q_o, constants.sbox[2]); + body += scaled_pow5(w_4 + q_4, constants.sbox[3]); + body += scaled_pow5(w_l_shift + q_m, constants.sbox[4]); + body += scaled_pow5(w_r_shift + q_c, constants.sbox[5]); + body += scaled_pow5(w_o_shift + q_5, constants.sbox[6]); + + auto wires = w_r * constants.wires[0]; + wires += w_o * constants.wires[1]; + wires += w_4 * constants.wires[2]; + wires += w_l_shift * constants.wires[3]; + wires += w_r_shift * constants.wires[4]; + wires += w_o_shift * constants.wires[5]; + wires += w_4_shift * constants.wires[6]; + body += Accumulator(wires); + + std::get<0>(evals) += Accumulator(q_sel * scaling_factor) * body; + } }; template using Poseidon2QuadInternalRelation = Relation>; 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 654e02d..85b90bf 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 @@ -93,6 +93,85 @@ template class Poseidon2QuadInternalTerminalRelationImpl { std::get<2>(evals) += q_by_scaling * a2_body; std::get<3>(evals) += q_by_scaling * a3_body; } + + /** + * @brief Prover-only constants of the separator-weighted sum of the four subrelation bodies (see + * HasProverSubrelationBatching): \f$ \sum_k w_k A_k = \sum_i m_i u_i + \sum_j n_j \cdot \text{wire}_j \f$. + */ + struct SubrelationBatchingConstants { + std::array sbox; // m_i for u_0, u_1, u_2, u_3 + std::array wires; // n_j for w_r, w_o, w_4, w_l_shift, w_r_shift, w_o_shift, w_4_shift + }; + + static SubrelationBatchingConstants compute_subrelation_batching_constants(const std::array& weights) + { + const auto& C = QuadParams::tables.closed_form; + SubrelationBatchingConstants constants; + for (size_t i = 0; i < 3; ++i) { + constants.sbox[i] = weights[0] * C[0][3 + i] + weights[1] * C[1][3 + i] + weights[2] * C[2][3 + i] + + weights[3] * C[3][3 + i]; + constants.wires[i] = + weights[0] * C[0][i] + weights[1] * C[1][i] + weights[2] * C[2][i] + weights[3] * C[3][i]; + } + // u_3 enters A_1, A_2, A_3 with coefficient 1. + constants.sbox[3] = weights[0] * C[0][6] + weights[1] + weights[2] + weights[3]; + for (size_t k = 0; k < 4; ++k) { + constants.wires[3 + k] = -weights[k]; + } + return constants; + } + + /** + * @brief Prover-only: add \f$ q \cdot \text{scaling} \cdot \sum_k w_k A_k \f$ into the first subrelation + * accumulator, folding each S-box constant into the degree-1 factor of x^5 = x^4 \cdot x. + */ + template + static void accumulate_with_subrelation_batching(ContainerOverSubrelations& evals, + const AllEntities& in, + const Parameters& /*params*/, + const FF& scaling_factor, + const SubrelationBatchingConstants& constants) + { + using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; + using CoeffAcc = typename Accumulator::CoefficientAccumulator; + + const auto w_l = CoeffAcc(in[AllEntities::EntityId::w_l]); + const auto w_r = CoeffAcc(in[AllEntities::EntityId::w_r]); + const auto w_o = CoeffAcc(in[AllEntities::EntityId::w_o]); + const auto w_4 = CoeffAcc(in[AllEntities::EntityId::w_4]); + const auto w_l_shift = CoeffAcc(in[AllEntities::EntityId::w_l_shift]); + const auto w_r_shift = CoeffAcc(in[AllEntities::EntityId::w_r_shift]); + const auto w_o_shift = CoeffAcc(in[AllEntities::EntityId::w_o_shift]); + const auto w_4_shift = CoeffAcc(in[AllEntities::EntityId::w_4_shift]); + + const auto q_l = CoeffAcc(in[AllEntities::EntityId::q_l]); + const auto q_r = CoeffAcc(in[AllEntities::EntityId::q_r]); + const auto q_o = CoeffAcc(in[AllEntities::EntityId::q_o]); + const auto q_4 = CoeffAcc(in[AllEntities::EntityId::q_4]); + const auto q_sel = CoeffAcc(in[AllEntities::EntityId::q_poseidon2_quad_internal_terminal]); + + // m * x^5 = (x^2)^2 * (m * x) + auto scaled_pow5 = [](const auto& x_m, const FF& m) -> Accumulator { + const Accumulator sq(x_m.sqr()); + return sq.sqr() * Accumulator(x_m * m); + }; + + auto body = scaled_pow5(w_l + q_l, constants.sbox[0]); + body += scaled_pow5(w_r + q_r, constants.sbox[1]); + body += scaled_pow5(w_o + q_o, constants.sbox[2]); + body += scaled_pow5(w_4 + q_4, constants.sbox[3]); + + auto wires = w_r * constants.wires[0]; + wires += w_o * constants.wires[1]; + wires += w_4 * constants.wires[2]; + wires += w_l_shift * constants.wires[3]; + wires += w_r_shift * constants.wires[4]; + wires += w_o_shift * constants.wires[5]; + wires += w_4_shift * constants.wires[6]; + body += Accumulator(wires); + + std::get<0>(evals) += Accumulator(q_sel * scaling_factor) * body; + } }; template 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 4399325..92ab0de 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_transition_entry_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_transition_entry_relation.hpp @@ -129,6 +129,76 @@ template class Poseidon2TransitionEntryRelationImpl { auto a2_body = u_2 * D1 + u_1 * fr(3) + u_0 * sum_A_one + Accumulator(wp_2); std::get<2>(evals) += q_by_scaling * a2_body; } + + /** + * @brief Prover-only constants of the separator-weighted sum of the three subrelation bodies (see + * HasProverSubrelationBatching): \f$ \sum_k w_k A_k = \sum_i m_i u_i + \sum_j n_j \cdot \text{wire}_j \f$. + */ + struct SubrelationBatchingConstants { + std::array sbox; // m_i for u_0, u_1, u_2 + std::array wires; // n_j for w_r, w_o, w_4, w_r_shift, w_o_shift, w_4_shift + }; + + static SubrelationBatchingConstants compute_subrelation_batching_constants(const std::array& weights) + { + SubrelationBatchingConstants constants; + constants.sbox[0] = weights[0] * D1 + weights[1] * fr(3) + weights[2] * sum_A_one; + constants.sbox[1] = weights[1] * D1 + weights[2] * fr(3); + constants.sbox[2] = weights[2] * D1; + for (size_t j = 0; j < 3; ++j) { + constants.wires[j] = weights[0] + weights[1] * A_one[j] + weights[2] * A2_one[j]; + constants.wires[3 + j] = -weights[j]; + } + return constants; + } + + /** + * @brief Prover-only: add \f$ q \cdot \text{scaling} \cdot \sum_k w_k A_k \f$ into the first subrelation + * accumulator, folding each S-box constant into the degree-1 factor of x^5 = x^4 \cdot x. + */ + template + static void accumulate_with_subrelation_batching(ContainerOverSubrelations& evals, + const AllEntities& in, + const Parameters& /*params*/, + const FF& scaling_factor, + const SubrelationBatchingConstants& constants) + { + using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; + using CoeffAcc = typename Accumulator::CoefficientAccumulator; + + const auto w_l = CoeffAcc(in[AllEntities::EntityId::w_l]); + const auto w_r = CoeffAcc(in[AllEntities::EntityId::w_r]); + const auto w_o = CoeffAcc(in[AllEntities::EntityId::w_o]); + const auto w_4 = CoeffAcc(in[AllEntities::EntityId::w_4]); + const auto w_r_shift = CoeffAcc(in[AllEntities::EntityId::w_r_shift]); + const auto w_o_shift = CoeffAcc(in[AllEntities::EntityId::w_o_shift]); + const auto w_4_shift = CoeffAcc(in[AllEntities::EntityId::w_4_shift]); + + const auto q_l = CoeffAcc(in[AllEntities::EntityId::q_l]); + const auto q_r = CoeffAcc(in[AllEntities::EntityId::q_r]); + const auto q_o = CoeffAcc(in[AllEntities::EntityId::q_o]); + const auto q_sel = CoeffAcc(in[AllEntities::EntityId::q_poseidon2_transition_entry]); + + // m * x^5 = (x^2)^2 * (m * x) + auto scaled_pow5 = [](const auto& x_m, const FF& m) -> Accumulator { + const Accumulator sq(x_m.sqr()); + return sq.sqr() * Accumulator(x_m * m); + }; + + auto body = scaled_pow5(w_l + q_l, constants.sbox[0]); + body += scaled_pow5(w_r_shift + q_r, constants.sbox[1]); + body += scaled_pow5(w_o_shift + q_o, constants.sbox[2]); + + auto wires = w_r * constants.wires[0]; + wires += w_o * constants.wires[1]; + wires += w_4 * constants.wires[2]; + wires += w_r_shift * constants.wires[3]; + wires += w_o_shift * constants.wires[4]; + wires += w_4_shift * constants.wires[5]; + body += Accumulator(wires); + + std::get<0>(evals) += Accumulator(q_sel * scaling_factor) * body; + } }; template using Poseidon2TransitionEntryRelation = Relation>; diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp index 372d089..71fc2d2 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp @@ -22,6 +22,7 @@ #include #include #include +#include namespace bb { @@ -46,6 +47,37 @@ concept IsVectorField = requires { T::SIZE; }; template inline constexpr size_t lane_count = 1; template inline constexpr size_t lane_count = T::SIZE; +/** + * @brief Prover-only subrelation batching hook. + * @details A relation whose subrelations share most of their per-row work (e.g. a common selector factor and a + * constant linear map applied to shared S-box outputs) may expose + * - `SubrelationBatchingConstants`, + * - `compute_subrelation_batching_constants(weights)`, where `weights[k] = separator_k / separator_0` are its + * subrelation separators relative to that of its first subrelation, and + * - `accumulate_with_subrelation_batching(accumulators, in, params, scaling_factor, constants)`, which adds + * \f$ \sum_k w_k T_k \f$ (with \f$ w_k \f$ the weights) into the first subrelation accumulator and leaves the others + * untouched. + * After `scale_univariates` multiplies the first accumulator by separator_0, the batched round univariate equals the + * per-subrelation one, so this is only valid for relations whose subrelations are all linearly independent and of + * equal length (they are then extended and batched identically). Verifiers never take this path. + */ +template +concept HasProverSubrelationBatching = requires { typename Relation::SubrelationBatchingConstants; }; + +template struct SubrelationBatchingSlot { + using type = std::monostate; +}; +template struct SubrelationBatchingSlot { + // Empty when the relation's first separator is zero, in which case its subrelations are accumulated separately. + using type = std::optional; +}; +template struct SubrelationBatchingTuple; +// Preserve the flavor's tuple family: AVM uses flat_tuple to avoid recursive std::tuple storage. +template