From 7c671f27ddf16fd684901a12d6197ce003596763 Mon Sep 17 00:00:00 2001 From: IlyasRidhuan Date: Thu, 5 Nov 2026 15:27:39 +0000 Subject: [PATCH 001/100] 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 652ffb8fa346174592c34d582ece3207388879af Mon Sep 17 00:00:00 2001 From: Golf Research Date: Fri, 6 Nov 2026 04:29:57 +0000 Subject: [PATCH 002/100] Import the complete cumulative AVM stack over the accepted leader Mechanical delta from accepted Ilyas AVM hint submission enable-duplicate-scalar-msm-hints-for-av-738e5e to the exact t165 screened source tree fdae2c47cdd57887b7d4f21abae9af5cfd218481. Retain full78: Oleh's original final2 collection, all 73 production mails, reviewed integration/parser/compiler/tuple/CPU corrections, and bounded reciprocal division. Add reviewed Sol PCS scratch elimination, equal-extent reuse and bounded inverse row scheduling. The accepted advisory hint is already present in the ancestor. No further algorithms are added here. Original authored mails, hashes and source review records remain preserved under client-research/chonk-golf/sources/final2, research/astra-cumulative, and research/sol-avm-inverse-scheduling. Upstream original collection: https://github.com/olehmisar/chonk-golf/tree/da701932463498f56fe784f9a105da52cf0cf742/sources/final2 Screen evidence is diagnostic. Full proof identity, original tests, all timing guards and memory qualification remain required. Co-authored-by: opt Co-authored-by: bench Co-authored-by: Sol research Co-authored-by: IlyasRidhuan (cherry picked from commit 66d2b3ce8729b5950b00be7817ee57383d0ffee6) --- barretenberg/cpp/src/CMakeLists.txt | 10 +- .../cpp/src/barretenberg/api/api_msgpack.cpp | 9 +- .../batched_honk_translator_prover.cpp | 133 ++-- .../cpp/src/barretenberg/chonk/chonk.cpp | 7 +- .../batched_linear_quotient.hpp | 179 ++++++ .../commitment_schemes/gemini/gemini.hpp | 61 +- .../commitment_schemes/gemini/gemini_impl.hpp | 7 +- .../commitment_schemes/kzg/kzg.hpp | 16 +- .../commitment_schemes/shplonk/shplonk.hpp | 101 ++-- .../src/barretenberg/common/cpu_supports.hpp | 39 ++ .../common/parallel_for_mutex_pool.cpp | 192 ++++-- .../src/barretenberg/common/thread.test.cpp | 40 ++ .../poseidon2/poseidon2_permutation.hpp | 103 +++- .../src/barretenberg/crypto/sha256/sha256.cpp | 160 ++++- .../src/barretenberg/crypto/sha256/sha256.hpp | 5 + .../crypto/sha256/sha256.test.cpp | 54 ++ .../acir_format/acir_compact_decoder.test.cpp | 217 +++++++ .../acir_format/arithmetic_constraints.cpp | 18 +- .../dsl/acir_format/serde/acir.hpp | 413 ++++++------- .../dsl/acir_format/serde/serde.hpp | 1 + .../dsl/acir_format/serde/witness_stack.hpp | 13 +- .../barretenberg/ecc/fields/asm_macros.hpp | 553 +++++------------ .../ecc/fields/bernstein_yang_inverse.hpp | 122 ++-- .../fields/bernstein_yang_inverse_wasm.hpp | 30 +- .../ecc/fields/field_declarations.hpp | 14 +- .../barretenberg/ecc/fields/ifma_field.hpp | 566 ++++++++++++++++++ .../ecc/fields/ifma_field.test.cpp | 217 +++++++ .../ecc/groups/affine_element.test.cpp | 11 +- .../barretenberg/ecc/groups/element_impl.hpp | 233 +++++++ .../ecc/groups/two_round_fold_ifma.hpp | 449 ++++++++++++++ .../batch_affine_ifma.hpp | 457 ++++++++++++++ .../scalar_multiplication.test.cpp | 138 +++++ .../scalar_multiplication_fast.cpp | 232 +++++++ .../cpp/src/barretenberg/eccvm/eccvm.test.cpp | 86 +++ .../src/barretenberg/eccvm/eccvm_flavor.hpp | 151 +++++ .../src/barretenberg/eccvm/eccvm_prover.cpp | 45 +- .../src/barretenberg/eccvm/eccvm_prover.hpp | 3 + .../src/barretenberg/eccvm/msm_builder.hpp | 23 +- .../barretenberg/eccvm/transcript_builder.hpp | 26 +- .../partially_evaluated_multivariates.hpp | 43 +- .../execution_trace/execution_trace_block.hpp | 3 + .../honk/library/grand_product_library.hpp | 101 ++-- .../proof_system/logderivative_library.hpp | 9 +- .../logderivative_library.test.cpp | 111 ++++ .../src/barretenberg/ipc/socket_server.cpp | 27 +- .../src/barretenberg/ipc/socket_server.hpp | 17 +- .../multilinear_batching_prover.cpp | 34 +- .../numeric/uint256/uint256_impl.hpp | 47 +- .../barretenberg/numeric/uintx/uintx.test.cpp | 30 + .../barretenberg/numeric/uintx/uintx_impl.hpp | 54 +- .../barretenberg/polynomials/fold_stride2.hpp | 162 ++++- .../polynomials/fold_stride2.test.cpp | 92 +++ .../barretenberg/polynomials/polynomial.cpp | 120 +++- .../barretenberg/polynomials/polynomial.hpp | 7 + .../polynomials/polynomial_arithmetic.cpp | 57 +- .../polynomial_arithmetic.test.cpp | 18 + .../barretenberg/polynomials/univariate.hpp | 48 ++ .../relations/databus_lookup_relation.hpp | 125 +++- .../delta_range_constraint_relation.hpp | 53 ++ .../relations/logderiv_lookup_relation.hpp | 98 ++- .../relations/memory_relation.hpp | 109 ++++ .../poseidon2_quad_internal_relation.hpp | 94 +++ ...eidon2_quad_internal_terminal_relation.hpp | 79 +++ .../poseidon2_transition_entry_relation.hpp | 70 +++ .../relations/ultra_arithmetic_relation.hpp | 25 + .../barretenberg/serialize/msgpack_impl.hpp | 18 +- .../stdlib/hash/keccak/keccak.cpp | 121 ++-- .../stdlib/hash/keccak/keccak.hpp | 58 +- .../stdlib/primitives/bigfield/bigfield.hpp | 103 +++- .../primitives/bigfield/bigfield_impl.hpp | 103 ++-- .../stdlib/primitives/field/field.cpp | 52 +- .../stdlib/primitives/field/field.hpp | 23 +- .../src/barretenberg/sumcheck/sumcheck.hpp | 71 ++- .../barretenberg/sumcheck/sumcheck_round.hpp | 150 ++++- .../sumcheck/sumcheck_round.test.cpp | 215 +++++++ .../copied_circuit_data.hpp | 12 + .../trace_to_polynomials.cpp | 196 +++--- .../trace_to_polynomials.hpp | 10 +- .../barretenberg/transcript/origin_tag.hpp | 19 +- .../translator_vm/translator_flavor.hpp | 27 + .../ultra_honk/prover_instance.cpp | 18 +- .../ultra_honk/prover_instance.hpp | 8 +- .../barretenberg/vm2/constraining/prover.cpp | 118 ++-- 83 files changed, 6651 insertions(+), 1438 deletions(-) create mode 100644 barretenberg/cpp/src/barretenberg/commitment_schemes/batched_linear_quotient.hpp create mode 100644 barretenberg/cpp/src/barretenberg/common/cpu_supports.hpp create mode 100644 barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.hpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/groups/two_round_fold_ifma.hpp create mode 100644 barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_affine_ifma.hpp create mode 100644 barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.test.cpp create mode 100644 barretenberg/cpp/src/barretenberg/trace_to_polynomials/copied_circuit_data.hpp diff --git a/barretenberg/cpp/src/CMakeLists.txt b/barretenberg/cpp/src/CMakeLists.txt index 2ca7c57..0ba2333 100644 --- a/barretenberg/cpp/src/CMakeLists.txt +++ b/barretenberg/cpp/src/CMakeLists.txt @@ -43,12 +43,16 @@ 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. -# We prioritize reducing size of final artifacts in release with -Oz. +# 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. if(WASM) set(CMAKE_CXX_FLAGS_DEBUG "-O1 -g") set(CMAKE_C_FLAGS_DEBUG "-O1 -g") - set(CMAKE_CXX_FLAGS_RELEASE "-Oz -DNDEBUG") - set(CMAKE_C_FLAGS_RELEASE "-Oz -DNDEBUG") + set(WASM_RELEASE_OPT "-O3 -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) endif() diff --git a/barretenberg/cpp/src/barretenberg/api/api_msgpack.cpp b/barretenberg/cpp/src/barretenberg/api/api_msgpack.cpp index 0abba6e..ba3c19d 100644 --- a/barretenberg/cpp/src/barretenberg/api/api_msgpack.cpp +++ b/barretenberg/cpp/src/barretenberg/api/api_msgpack.cpp @@ -2,6 +2,7 @@ #include "barretenberg/bbapi/c_bind.hpp" #include "barretenberg/common/log.hpp" #include "barretenberg/serialize/msgpack.hpp" +#include "barretenberg/serialize/msgpack_impl.hpp" #include #include #include @@ -60,7 +61,9 @@ int process_msgpack_commands(std::istream& input_stream) // Deserialize the msgpack buffer // The buffer should contain a tuple of arguments (array) matching the bbapi function signature. // Since bbapi(Command) takes one argument, we expect a 1-element array containing the Command. - auto unpacked = msgpack::unpack(reinterpret_cast(buffer.data()), buffer.size()); + // The buffer outlives the command's execution, so blobs (bytecode, witnesses, VKs) are referenced in place. + auto unpacked = + msgpack::unpack(reinterpret_cast(buffer.data()), buffer.size(), msgpack_reference_input); auto obj = unpacked.get(); // First, expect an array (the tuple of arguments) @@ -213,7 +216,9 @@ int execute_msgpack_ipc_server(std::unique_ptr server) // Deserialize msgpack command // The buffer should contain a tuple of arguments (array) matching the bbapi function signature. // Since bbapi(Command) takes one argument, we expect a 1-element array containing the Command. - auto unpacked = msgpack::unpack(reinterpret_cast(request.data()), request.size()); + // The buffer outlives the command's execution, so blobs (bytecode, witnesses, VKs) are referenced in place. + auto unpacked = + msgpack::unpack(reinterpret_cast(request.data()), request.size(), msgpack_reference_input); auto obj = unpacked.get(); // First, expect an array (the tuple of arguments) diff --git a/barretenberg/cpp/src/barretenberg/chonk/batched_honk_translator/batched_honk_translator_prover.cpp b/barretenberg/cpp/src/barretenberg/chonk/batched_honk_translator/batched_honk_translator_prover.cpp index c96dc71..4b97eb3 100644 --- a/barretenberg/cpp/src/barretenberg/chonk/batched_honk_translator/batched_honk_translator_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/chonk/batched_honk_translator/batched_honk_translator_prover.cpp @@ -4,10 +4,15 @@ #include "barretenberg/commitment_schemes/shplonk/shplemini.hpp" #include "barretenberg/commitment_schemes/small_subgroup_ipa/small_subgroup_ipa.hpp" #include "barretenberg/common/bb_bench.hpp" +#include "barretenberg/polynomials/fold_stride2.hpp" #include "barretenberg/polynomials/gate_separator.hpp" #include "barretenberg/polynomials/row_disabling_polynomial.hpp" #include "barretenberg/translator_vm/translator_prover.hpp" +#include +#include +#include + // Short-monomial translator relation definitions: the joint sumcheck round (TransProverRound) is templated on // TranslatorShortMonomialFlavor, so this TU instantiates the short relations' prover-side accumulate. The short // relations are otherwise header-only (no explicit instantiation into librelations), so include the _impl here. @@ -20,6 +25,67 @@ namespace bb { +namespace { + +/** + * @brief Partially evaluate the MegaZK and translator tables in one parallel region: at one round challenge, or (with + * `second_challenge`) at the first two round challenges straight from the full polynomials. + * @details Equivalent to SumcheckProver::partially_evaluate (respectively partially_evaluate_first_two_rounds) on each + * circuit's tables, but the polynomials of both circuits form a single work list scheduled largest-first, so the + * smaller circuit's folds fill the tail of the larger one's instead of each circuit paying its own load-imbalance tail + * and parallel_for dispatch. Source and destination may alias for a single fold (in-place rounds). + */ +template +void joint_partially_evaluate(MegaZKSource& mega_zk_source, + MegaZKDest& mega_zk_dest, + TranslatorSource& translator_source, + TranslatorDest& translator_dest, + const FF& round_challenge, + const std::optional& second_challenge = std::nullopt) +{ + struct FoldJob { + const Polynomial* source; + Polynomial* dest; + size_t num_outputs; + }; + std::vector jobs; + auto add_jobs = [&](auto& source, auto& dest) { + for (auto [source_poly, dest_poly] : zip_view(source.get_all(), dest.get_all())) { + const auto [begin, end] = second_challenge.has_value() ? twice_folded_backed_range(source_poly) + : folded_backed_range(source_poly); + jobs.push_back({ &source_poly, &dest_poly, end - begin }); + } + }; + add_jobs(mega_zk_source, mega_zk_dest); + add_jobs(translator_source, translator_dest); + std::stable_sort( + jobs.begin(), jobs.end(), [](const FoldJob& a, const FoldJob& b) { return a.num_outputs > b.num_outputs; }); + + parallel_for(jobs.size(), [&](size_t j) { + const FoldJob& job = jobs[j]; + if (second_challenge.has_value()) { + fold_stride4_backed(*job.source, *job.dest, round_challenge, *second_challenge); + } else { + fold_stride2_backed(*job.source, *job.dest, round_challenge); + } + }); + + // Halve the active-row prefix to track the folded trace (only tables that carry it). + auto halve_active_prefix = [](auto& source, auto& dest) { + if constexpr (requires { + source.row_skip_active_prefix_end; + dest.row_skip_active_prefix_end; + }) { + dest.row_skip_active_prefix_end = + (source.row_skip_active_prefix_end / 2) + (source.row_skip_active_prefix_end % 2); + } + }; + halve_active_prefix(mega_zk_source, mega_zk_dest); + halve_active_prefix(translator_source, translator_dest); +} + +} // namespace + BatchedHonkTranslatorProver::BatchedHonkTranslatorProver(std::shared_ptr mega_zk_instance, std::shared_ptr mega_zk_vk, std::shared_ptr transcript) @@ -122,9 +188,11 @@ void BatchedHonkTranslatorProver::execute_joint_sumcheck_rounds() auto& mega_zk_params = mega_zk_inst->relation_parameters; auto& translator_polys = translator_key->proving_key->polynomials; - // Allocate partially evaluated polynomial tables (populated by the first partially_evaluate call). - MegaZKPartialEvals mega_zk_partial(mega_zk_polys, static_cast(1) << mega_zk_log_n); - TransPartialEvals translator_partial(translator_polys, static_cast(1) << JOINT_LOG_N); + // Allocate partially evaluated polynomial tables, sized for the state after two rounds: round 1 reads the full + // polynomials folded on access, and the tables are populated after it. + BB_ASSERT(mega_zk_log_n >= 2); + MegaZKPartialEvals mega_zk_partial(mega_zk_polys, static_cast(1) << mega_zk_log_n, /*num_folds=*/2); + TransPartialEvals translator_partial(translator_polys, static_cast(1) << JOINT_LOG_N, /*num_folds=*/2); // Type aliases for static partial-evaluation helpers from SumcheckProver. using MegaZKSumcheck = SumcheckProver; @@ -196,46 +264,41 @@ void BatchedHonkTranslatorProver::execute_joint_sumcheck_rounds() return send_round(round_idx); }; - // ==================== Round 0: bootstraps mega_zk_partial and translator_partial ==================== - // PartiallyEvaluatedMultivariates only allocates output buffers; values are populated here. + // ============ Rounds 0 and 1: bootstrap mega_zk_partial and translator_partial ============ + // Round 0 reads the full polynomials and round 1 reads them folded at u_0 on access; the tables are populated + // after round 1 from the full polynomials (PartiallyEvaluatedMultivariates only allocates output buffers). { - const FF u = do_round(mega_zk_polys, translator_polys, 0); - { - BB_BENCH_NAME("joint_sumcheck/hiding_kernel"); - { - BB_BENCH_NAME("joint_sumcheck/hiding_kernel/partially_evaluate"); - MegaZKSumcheck::partially_evaluate(mega_zk_polys, mega_zk_partial, u); - } - } + const FF u_0 = do_round(mega_zk_polys, translator_polys, 0); + rdp.update_evaluations(u_0, 0); + mega_zk_round.advance_round(); + mega_zk_round.excluded_head_size = 2; // After round 0, disabled zone collapses to 1 edge pair + update_round_state(0, u_0); + + using MegaZKFolded = FoldedMultivariatesBase>, + MegaZKFlavor::ProverPolynomials, + FF>; + using TransFolded = FoldedMultivariatesBase>, + TranslatorFlavor::ProverPolynomials, + FF>; + const MegaZKFolded mega_zk_folded(mega_zk_polys, u_0); + const TransFolded translator_folded(translator_polys, u_0); + const FF u_1 = do_round(mega_zk_folded, translator_folded, 1); { - BB_BENCH_NAME("joint_sumcheck/translator"); - { - BB_BENCH_NAME("joint_sumcheck/translator/partially_evaluate"); - TransSumcheck::partially_evaluate(translator_polys, translator_partial, u); - } + BB_BENCH_NAME("joint_sumcheck/partially_evaluate"); + joint_partially_evaluate( + mega_zk_polys, mega_zk_partial, translator_polys, translator_partial, u_0, std::optional(u_1)); } - rdp.update_evaluations(u, 0); + rdp.update_evaluations(u_1, 1); mega_zk_round.advance_round(); - mega_zk_round.excluded_head_size = 2; // After round 0, disabled zone collapses to 1 edge pair - update_round_state(0, u); + update_round_state(1, u_1); } - // ==================== Real rounds 1..mega_zk_log_n-1 ==================== - for (size_t round_idx = 1; round_idx < mega_zk_log_n; round_idx++) { + // ==================== Real rounds 2..mega_zk_log_n-1 ==================== + for (size_t round_idx = 2; round_idx < mega_zk_log_n; round_idx++) { const FF u = do_round(mega_zk_partial, translator_partial, round_idx); { - BB_BENCH_NAME("joint_sumcheck/hiding_kernel"); - { - BB_BENCH_NAME("joint_sumcheck/hiding_kernel/partially_evaluate_in_place"); - MegaZKSumcheck::partially_evaluate_in_place(mega_zk_partial, u); - } - } - { - BB_BENCH_NAME("joint_sumcheck/translator"); - { - BB_BENCH_NAME("joint_sumcheck/translator/partially_evaluate_in_place"); - TransSumcheck::partially_evaluate_in_place(translator_partial, u); - } + BB_BENCH_NAME("joint_sumcheck/partially_evaluate_in_place"); + joint_partially_evaluate(mega_zk_partial, mega_zk_partial, translator_partial, translator_partial, u); } rdp.update_evaluations(u, round_idx); mega_zk_round.advance_round(); diff --git a/barretenberg/cpp/src/barretenberg/chonk/chonk.cpp b/barretenberg/cpp/src/barretenberg/chonk/chonk.cpp index 28ee3c1..8561988 100644 --- a/barretenberg/cpp/src/barretenberg/chonk/chonk.cpp +++ b/barretenberg/cpp/src/barretenberg/chonk/chonk.cpp @@ -167,7 +167,7 @@ void Chonk::accumulate_hiding_kernel(HidingKernelCircuit& circuit, } vinfo("Constructing hiding kernel instance (proving deferred to prove())"); - hiding_prover_inst = std::make_shared(circuit); + hiding_prover_inst = std::make_shared(circuit, CopiedCircuitData::RELEASE); // The circuit has been copied into the prover polynomials; free its construction data. circuit.free_construction_data(); @@ -195,9 +195,12 @@ HonkProof Chonk::instance_to_accumulator(typename InstanceFlavor::CircuitBuilder using PI = ProverInstance_; BB_ASSERT(vk != nullptr, "Chonk::accumulate_and_fold - VK expected for the provided circuit"); - auto prover_instance = std::make_shared(circuit); #ifndef NDEBUG + // The debug checks below read the circuit after the instance is built. + auto prover_instance = std::make_shared(circuit, CopiedCircuitData::KEEP); debug_incoming_circuit(circuit, prover_instance, vk); +#else + auto prover_instance = std::make_shared(circuit, CopiedCircuitData::RELEASE); #endif // The circuit has been copied into the prover polynomials; free its construction data. circuit.free_construction_data(); diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/batched_linear_quotient.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/batched_linear_quotient.hpp new file mode 100644 index 0000000..15df425 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/batched_linear_quotient.hpp @@ -0,0 +1,179 @@ +#pragma once +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/thread.hpp" + +#include +#include +#include +#include + +namespace bb { + +/** + * @brief One term ν⋅(p(X) − v)/(X − x) of a batched linear quotient, where v = p(x). + */ +template struct LinearQuotientTerm { + std::span coefficients; // p(X) = ∑ᵢ pᵢ⋅Xⁱ, starting from X⁰ + Fr root; // x + Fr evaluation; // v + Fr scalar; // ν +}; + +/** + * @brief Adds ∑ⱼ νⱼ⋅(pⱼ(X) − vⱼ)/(X − xⱼ) to `quotient`, asserting that every division is exact (pⱼ(xⱼ) = vⱼ). + * + * @details For p of size s, the quotient q(X) = ∑ᵢ qᵢ⋅Xⁱ of (p(X) − v) by (X − x) has q_{s−1} = 0 and + * qᵢ = pᵢ₊₁ + x⋅qᵢ₊₁, i.e. qᵢ = ∑_{k>i} pₖ⋅x^{k−i−1}; v only enters the remainder p₀ − v + x⋅q₀, which must vanish. + * The quotient index range is split into chunks that are processed in parallel: + * 1. every chunk except the lowest Horner-evaluates its own coefficients, Hᶜ = ∑_{lo +void add_batched_linear_quotients(std::span quotient, std::span> terms) +{ + // Coefficient count of the quotient of each term + auto quotient_size = [](const LinearQuotientTerm& term) { + return term.coefficients.empty() ? size_t{ 0 } : term.coefficients.size() - 1; + }; + + size_t length = 0; + for (const auto& term : terms) { + length = std::max(length, quotient_size(term)); + } + BB_ASSERT_LTE(length, quotient.size()); + + // Work below index i, counted in quotient coefficients over all terms + auto work_below = [&](size_t i) { + size_t work = 0; + for (const auto& term : terms) { + work += std::min(i, quotient_size(term)); + } + return work; + }; + const size_t total_work = work_below(length); + + // Chunks with less work than this are not worth the extra Horner pass of the parallel split + constexpr size_t MIN_CHUNK_WORK = size_t{ 1 } << 13; + const size_t num_chunks = std::clamp(total_work / MIN_CHUNK_WORK, 1, get_num_cpus()); + // Chunk boundaries split the total work evenly; terms are of different sizes, so the low indices carry more. + std::vector chunk_starts(num_chunks + 1, length); + chunk_starts[0] = 0; + for (size_t chunk = 1; chunk < num_chunks; ++chunk) { + const size_t target = (total_work / num_chunks) * chunk; + size_t lo = chunk_starts[chunk - 1]; + size_t hi = length; + while (lo < hi) { + const size_t mid = lo + ((hi - lo) / 2); + if (work_below(mid) < target) { + lo = mid + 1; + } else { + hi = mid; + } + } + chunk_starts[chunk] = lo; + } + auto chunk_start = [&](size_t chunk) { return chunk_starts[chunk]; }; + + const size_t num_terms = terms.size(); + // boundary_values[chunk * num_terms + j] = q⁽ʲ⁾ at the upper boundary of the chunk + std::vector boundary_values(num_chunks * num_terms, Fr::zero()); + if (num_chunks > 1) { + std::vector chunk_horner(num_chunks * num_terms, Fr::zero()); + parallel_for(num_chunks - 1, [&](size_t idx) { + const size_t chunk = idx + 1; + const size_t lo = chunk_start(chunk); + const size_t hi = chunk_start(chunk + 1); + for (size_t j = 0; j < num_terms; ++j) { + const auto& term = terms[j]; + const size_t end = std::max(std::min(hi, quotient_size(term)), lo); + // Horner's rule on the two halves of the chunk, interleaved so that the two multiplication chains + // overlap + const size_t low_size = (end - lo) / 2; + const size_t high_size = (end - lo) - low_size; + const Fr* low = term.coefficients.data() + lo; + const Fr* high = low + low_size; + Fr low_acc = Fr::zero(); + Fr high_acc = (high_size > low_size) ? high[high_size] : Fr::zero(); + for (size_t k = low_size; k > 0; --k) { + low_acc = (low_acc * term.root) + low[k]; + high_acc = (high_acc * term.root) + high[k]; + } + chunk_horner[(chunk * num_terms) + j] = low_acc + (term.root.pow(low_size) * high_acc); + } + }); + for (size_t j = 0; j < num_terms; ++j) { + const Fr& root = terms[j].root; + for (size_t chunk = num_chunks - 1; chunk > 0; --chunk) { + const size_t lo = chunk_start(chunk); + const size_t hi = chunk_start(chunk + 1); + boundary_values[((chunk - 1) * num_terms) + j] = + chunk_horner[(chunk * num_terms) + j] + + (root.pow(hi - lo) * boundary_values[(chunk * num_terms) + j]); + } + } + } + + // q⁽ʲ⁾₀ for the remainder check + std::vector lowest_coefficients(num_terms, Fr::zero()); + parallel_for(num_chunks, [&](size_t chunk) { + const size_t lo = chunk_start(chunk); + const size_t hi = chunk_start(chunk + 1); + // Runs the recurrence of one term for i = from, …, to + 1 + auto run_single = [&](const LinearQuotientTerm& term, Fr& q, size_t from, size_t to) { + if (term.scalar == Fr::one()) { + for (size_t i = from; i > to; --i) { + q = q * term.root + term.coefficients[i]; + quotient[i - 1] += q; + } + } else { + for (size_t i = from; i > to; --i) { + q = q * term.root + term.coefficients[i]; + quotient[i - 1] += term.scalar * q; + } + } + }; + // Terms are processed in pairs so that two independent recurrences overlap + for (size_t j = 0; j < num_terms; j += 2) { + const auto& term_a = terms[j]; + const size_t end_a = std::max(std::min(hi, quotient_size(term_a)), lo); + Fr q_a = boundary_values[(chunk * num_terms) + j]; + if (j + 1 == num_terms) { + run_single(term_a, q_a, end_a, lo); + if (chunk == 0) { + lowest_coefficients[j] = q_a; + } + continue; + } + const auto& term_b = terms[j + 1]; + const size_t end_b = std::max(std::min(hi, quotient_size(term_b)), lo); + Fr q_b = boundary_values[(chunk * num_terms) + j + 1]; + // The longer term runs alone down to the end of the shorter one + const size_t common_end = std::min(end_a, end_b); + run_single(term_a, q_a, end_a, common_end); + run_single(term_b, q_b, end_b, common_end); + for (size_t i = common_end; i > lo; --i) { + q_a = q_a * term_a.root + term_a.coefficients[i]; + q_b = q_b * term_b.root + term_b.coefficients[i]; + quotient[i - 1] += (term_a.scalar * q_a) + (term_b.scalar * q_b); + } + if (chunk == 0) { + lowest_coefficients[j] = q_a; + lowest_coefficients[j + 1] = q_b; + } + } + }); + + for (size_t j = 0; j < num_terms; ++j) { + const auto& term = terms[j]; + if (!term.coefficients.empty() && !term.root.is_zero()) { + // Exact-division precondition: p(X) − v = (X − x)⋅q(X), i.e. p₀ − v + x⋅q₀ = 0 + BB_ASSERT(term.coefficients[0] - term.evaluation + (term.root * lowest_coefficients[j]) == Fr::zero()); + } + } +} + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp index 267c608..e2905fb 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp @@ -9,6 +9,7 @@ #include "barretenberg/commitment_schemes/claim.hpp" #include "barretenberg/commitment_schemes/claim_batcher.hpp" #include "barretenberg/common/bb_bench.hpp" +#include "barretenberg/common/thread.hpp" #include "barretenberg/polynomials/polynomial.hpp" #include "barretenberg/transcript/transcript.hpp" @@ -182,18 +183,32 @@ template class GeminiProver_ { batched, std::span>(sources), std::span(scalars)); }; - Polynomial full_batched(full_batched_size); - - if (has_unshifted()) { + const bool with_unshifted = has_unshifted(); + const bool with_shifted = has_to_be_shifted_by_one(); + if (with_unshifted) { batch(batched_unshifted, unshifted); - full_batched += batched_unshifted; } - - if (has_to_be_shifted_by_one()) { + if (with_shifted) { batch(batched_to_be_shifted_by_one, to_be_shifted_by_one); - full_batched += batched_to_be_shifted_by_one.shifted(); } + // A₀[i] = F[i] + G[i + 1], written in one pass; coefficients from actual_data_size_ on are zero + Polynomial full_batched(full_batched_size, Polynomial::DontZeroMemory::FLAG); + parallel_for_heuristic( + full_batched_size, + [&](size_t start, size_t end, BB_UNUSED size_t chunk_index) { + for (size_t i = start; i < end; ++i) { + if (i >= actual_data_size_) { + full_batched.at(i) = Fr::zero(); + continue; + } + const Fr f = with_unshifted ? batched_unshifted[i] : Fr::zero(); + const bool shifted_in_range = with_shifted && (i + 1 < actual_data_size_); + full_batched.at(i) = shifted_in_range ? f + batched_to_be_shifted_by_one[i + 1] : f; + } + }, + thread_heuristics::FF_ADDITION_COST + thread_heuristics::FF_COPY_COST); + return full_batched; } @@ -205,19 +220,25 @@ template class GeminiProver_ { */ std::pair compute_partially_evaluated_batch_polynomials(const Fr& r_challenge) { - Polynomial A_0_pos(actual_data_size_, full_batched_size); - - if (has_unshifted()) { - A_0_pos += batched_unshifted; - } - - Polynomial A_0_neg = A_0_pos; - - Fr r_inv = r_challenge.invert(); - if (has_to_be_shifted_by_one()) { - A_0_pos.add_scaled(batched_to_be_shifted_by_one, r_inv); - A_0_neg.add_scaled(batched_to_be_shifted_by_one, -r_inv); - } + // Every coefficient of A₀₊ and A₀₋ is written by the single pass below + Polynomial A_0_pos(actual_data_size_, full_batched_size, Polynomial::DontZeroMemory::FLAG); + Polynomial A_0_neg(actual_data_size_, full_batched_size, Polynomial::DontZeroMemory::FLAG); + + const Fr r_inv = r_challenge.invert(); + const bool with_unshifted = has_unshifted(); + const bool with_shifted = has_to_be_shifted_by_one(); + parallel_for_heuristic( + actual_data_size_, + [&](size_t start, size_t end, BB_UNUSED size_t chunk_index) { + for (size_t i = start; i < end; ++i) { + // A₀₊ = F + G/r, A₀₋ = F − G/r + const Fr f = with_unshifted ? batched_unshifted[i] : Fr::zero(); + const Fr g_over_r = with_shifted ? batched_to_be_shifted_by_one[i] * r_inv : Fr::zero(); + A_0_pos.at(i) = f + g_over_r; + A_0_neg.at(i) = f - g_over_r; + } + }, + thread_heuristics::FF_MULTIPLICATION_COST + (2 * thread_heuristics::FF_ADDITION_COST)); return { std::move(A_0_pos), std::move(A_0_neg) }; }; diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_impl.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_impl.hpp index eb434a5..23ce3f6 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_impl.hpp @@ -125,6 +125,7 @@ std::vector::Polynomial> GeminiProver_::com // beyond this extent, all values are zero and contribute nothing. // At minimum, the disabled head region must be covered (masking values live at rows 1..3). size_t actual_size = std::max(A_0.end_index(), static_cast(NUM_DISABLED_ROWS_IN_SUMCHECK)); + const bool fold_writes_all = A_0.end_index() >= static_cast(NUM_DISABLED_ROWS_IN_SUMCHECK); // Reserve space for the virtual_log_n - 1 Fold polynomials, the foldings of the full batched polynomial A₀ std::vector fold_polynomials; @@ -132,8 +133,10 @@ std::vector::Polynomial> GeminiProver_::com for (size_t l = 0; l < log_n - 1; ++l) { const size_t fold_size = (actual_size + 1) / 2; - // A_l_fold = Aₗ₊₁(X) = (1-uₗ)⋅even(Aₗ)(X) + uₗ⋅odd(Aₗ)(X) - fold_polynomials.emplace_back(Polynomial(fold_size)); + // A_l_fold = Aₗ₊₁(X) = (1-uₗ)⋅even(Aₗ)(X) + uₗ⋅odd(Aₗ)(X); unless A₀ is shorter than the disabled head + // region, every coefficient is written by the fold below + fold_polynomials.emplace_back(fold_writes_all ? Polynomial(fold_size, Polynomial::DontZeroMemory::FLAG) + : Polynomial(fold_size)); actual_size = fold_size; } diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp index fd7c25d..b0cadd1 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/kzg/kzg.hpp @@ -6,6 +6,7 @@ #pragma once +#include "barretenberg/commitment_schemes/batched_linear_quotient.hpp" #include "barretenberg/commitment_schemes/claim.hpp" #include "barretenberg/commitment_schemes/commitment_key.hpp" #include "barretenberg/commitment_schemes/pairing_points.hpp" @@ -46,17 +47,22 @@ template class KZG { const std::shared_ptr& prover_trancript) { BB_BENCH_NAME("KZG::compute_opening_proof"); - Polynomial quotient = opening_claim.polynomial; + const Polynomial& polynomial = opening_claim.polynomial; OpeningPair pair = opening_claim.opening_pair; Commitment quotient_commitment; - if (opening_claim.polynomial.is_empty()) { + if (polynomial.is_empty()) { // We treat the empty polynomial as the zero polynomial quotient_commitment = Commitment::infinity(); } else { - quotient.at(0) = quotient[0] - pair.evaluation; - // Computes the coefficients for the quotient polynomial q(X) = (p(X) - v) / (X - r) through an FFT - quotient.factor_roots(pair.challenge); + BB_ASSERT_EQ(polynomial.start_index(), size_t{ 0 }); + // Computes the coefficients for the quotient polynomial q(X) = (p(X) - v) / (X - r) + Polynomial quotient(polynomial.size()); + const std::array, 1> terms{ { { .coefficients = polynomial.coeffs(), + .root = pair.challenge, + .evaluation = pair.evaluation, + .scalar = Fr::one() } } }; + add_batched_linear_quotients(quotient.coeffs(), std::span>(terms)); quotient_commitment = ck.commit(quotient); } diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp index 1f67c17..4fe5567 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/shplonk/shplonk.hpp @@ -5,6 +5,7 @@ // ===================== #pragma once +#include "barretenberg/commitment_schemes/batched_linear_quotient.hpp" #include "barretenberg/commitment_schemes/claim.hpp" #include "barretenberg/commitment_schemes/commitment_key.hpp" #include "barretenberg/commitment_schemes/small_subgroup_ipa/small_subgroup_ipa_utils.hpp" @@ -72,30 +73,28 @@ template class ShplonkProver_ { } // Q(X) = ∑ⱼ νʲ ⋅ ( fⱼ(X) − vⱼ) / ( X − xⱼ ) Polynomial Q(max_poly_size); - Polynomial tmp(max_poly_size); + + std::vector> terms; + terms.reserve((2 * opening_claims.size()) + libra_opening_claims.size() + sumcheck_round_claims.size()); + auto add_term = + [&](const ProverOpeningClaim& claim, const Fr& root, const Fr& evaluation, Fr& nu_power) { + BB_ASSERT_EQ(claim.polynomial.start_index(), size_t{ 0 }); + terms.push_back({ .coefficients = claim.polynomial.coeffs(), + .root = root, + .evaluation = evaluation, + .scalar = nu_power }); + nu_power *= nu; + }; Fr current_nu = Fr::one(); size_t fold_idx = 0; for (const auto& claim : opening_claims) { - // Gemini Fold Polynomials have to be opened at -r^{2^j} and r^{2^j}. if (claim.gemini_fold) { - tmp = claim.polynomial; - tmp.at(0) = tmp[0] - gemini_fold_pos_evaluations[fold_idx++]; - tmp.factor_roots(-claim.opening_pair.challenge); - // Add the claim quotient to the batched quotient polynomial - Q.add_scaled(tmp, current_nu); - current_nu *= nu; + add_term(claim, -claim.opening_pair.challenge, gemini_fold_pos_evaluations[fold_idx++], current_nu); } - - // Compute individual claim quotient tmp = ( fⱼ(X) − vⱼ) / ( X − xⱼ ) - tmp = claim.polynomial; - tmp.at(0) = tmp[0] - claim.opening_pair.evaluation; - tmp.factor_roots(claim.opening_pair.challenge); - // Add the claim quotient to the batched quotient polynomial - Q.add_scaled(tmp, current_nu); - current_nu *= nu; + add_term(claim, claim.opening_pair.challenge, claim.opening_pair.evaluation, current_nu); } // Libra and sumcheck opening claims are batched immediately after the Gemini fold claims, reusing the same // batching challenge nu. They start at nu^{2 * virtual_log_n}. Guard on either Libra or sumcheck claims being @@ -105,29 +104,13 @@ template class ShplonkProver_ { // rounds, each opened at two points (±r^{2^i}), including the dummy padding folds. current_nu = nu.pow(2 * virtual_log_n); } - - for (const auto& claim : libra_opening_claims) { - // Compute individual claim quotient tmp = ( fⱼ(X) − vⱼ) / ( X − xⱼ ) - tmp = claim.polynomial; - tmp.at(0) = tmp[0] - claim.opening_pair.evaluation; - tmp.factor_roots(claim.opening_pair.challenge); - - // Add the claim quotient to the batched quotient polynomial - Q.add_scaled(tmp, current_nu); - current_nu *= nu; + for (const auto& claim_set : { libra_opening_claims, sumcheck_round_claims }) { + for (const auto& claim : claim_set) { + add_term(claim, claim.opening_pair.challenge, claim.opening_pair.evaluation, current_nu); + } } - for (const auto& claim : sumcheck_round_claims) { - - // Compute individual claim quotient tmp = ( fⱼ(X) − vⱼ) / ( X − xⱼ ) - tmp = claim.polynomial; - tmp.at(0) = tmp[0] - claim.opening_pair.evaluation; - tmp.factor_roots(claim.opening_pair.challenge); - - // Add the claim quotient to the batched quotient polynomial - Q.add_scaled(tmp, current_nu); - current_nu *= nu; - } + add_batched_linear_quotients(Q.coeffs(), std::span>(terms)); // Return batched quotient polynomial Q(X) return Q; }; @@ -182,24 +165,34 @@ template class ShplonkProver_ { // s.t. G(r) = 0 Polynomial G(std::move(batched_quotient_Q)); // G(X) = Q(X) + // G -= ∑ⱼ sⱼ⋅fⱼ(X) is applied in one batched pass; the constant ∑ⱼ sⱼ⋅vⱼ is accumulated separately. A Gemini + // fold polynomial opened at both ±r^{2^j} enters once, with the sum of its two scaling factors. + std::vector> sources; + std::vector scalars; + sources.reserve(num_opening_claims); + scalars.reserve(num_opening_claims); + Fr constant_term = Fr::zero(); + Fr current_nu = Fr::one(); size_t idx = 0; size_t fold_idx = 0; for (const auto& claim : opening_claims) { - + Fr claim_scaling_factor = Fr::zero(); if (claim.gemini_fold) { // G -= νʲ ⋅ ( fⱼ(X) − vⱼ₊) / ( z + xⱼ ), where vⱼ₊ is the positive fold evaluation Fr scaling_factor = current_nu * inverse_vanishing_evals[idx++]; // = νʲ / (z + xⱼ ) - G.add_scaled(claim.polynomial, -scaling_factor); - G.at(0) = G[0] + scaling_factor * gemini_fold_pos_evaluations[fold_idx++]; + claim_scaling_factor += scaling_factor; + constant_term += scaling_factor * gemini_fold_pos_evaluations[fold_idx++]; current_nu *= nu_challenge; } // G -= νʲ ⋅ ( fⱼ(X) − vⱼ) / ( z − xⱼ ) Fr scaling_factor = current_nu * inverse_vanishing_evals[idx++]; // = νʲ / (z − xⱼ ) - G.add_scaled(claim.polynomial, -scaling_factor); - G.at(0) = G[0] + scaling_factor * claim.opening_pair.evaluation; + claim_scaling_factor += scaling_factor; + constant_term += scaling_factor * claim.opening_pair.evaluation; + sources.emplace_back(claim.polynomial); + scalars.emplace_back(-claim_scaling_factor); current_nu *= nu_challenge; } @@ -213,20 +206,20 @@ template class ShplonkProver_ { current_nu = nu_challenge.pow(2 * virtual_log_n); } - for (const auto& claim : libra_opening_claims) { - // G -= νʲ ⋅ ( fⱼ(X) − vⱼ) / ( z − xⱼ ) - Fr scaling_factor = current_nu * inverse_vanishing_evals[idx++]; // = νʲ / (z − xⱼ ) - G.add_scaled(claim.polynomial, -scaling_factor); - G.at(0) = G[0] + scaling_factor * claim.opening_pair.evaluation; - current_nu *= nu_challenge; + for (const auto& claim_set : { libra_opening_claims, sumcheck_opening_claims }) { + for (const auto& claim : claim_set) { + // G -= νʲ ⋅ ( fⱼ(X) − vⱼ) / ( z − xⱼ ) + Fr scaling_factor = current_nu * inverse_vanishing_evals[idx++]; // = νʲ / (z − xⱼ ) + constant_term += scaling_factor * claim.opening_pair.evaluation; + sources.emplace_back(claim.polynomial); + scalars.emplace_back(-scaling_factor); + current_nu *= nu_challenge; + } } - for (const auto& claim : sumcheck_opening_claims) { - Fr scaling_factor = current_nu * inverse_vanishing_evals[idx++]; // = νʲ / (z − xⱼ ) - G.add_scaled(claim.polynomial, -scaling_factor); - G.at(0) = G[0] + scaling_factor * claim.opening_pair.evaluation; - current_nu *= nu_challenge; - } + add_scaled_batch(G, std::span>(sources), std::span(scalars)); + G.at(0) = G[0] + constant_term; + // Return opening pair (z, 0) and polynomial G(X) = Q(X) - Q_z(X) return { .polynomial = std::move(G), .opening_pair = { .challenge = z_challenge, .evaluation = Fr::zero() } }; }; diff --git a/barretenberg/cpp/src/barretenberg/common/cpu_supports.hpp b/barretenberg/cpp/src/barretenberg/common/cpu_supports.hpp new file mode 100644 index 0000000..a806418 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/cpu_supports.hpp @@ -0,0 +1,39 @@ +#pragma once + +#if defined(__x86_64__) && !defined(__wasm__) && (defined(__clang__) || defined(__GNUC__)) +#include +#include + +namespace bb { +/** Check every IFMA kernel feature and the OS-managed AVX-512 register state without compiler runtime symbols. */ +inline bool cpu_supports_avx512_ifma() noexcept +{ + unsigned int eax = 0; + unsigned int ebx = 0; + unsigned int ecx = 0; + unsigned int edx = 0; + if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0) { + return false; + } + // XGETBV is legal only when XSAVE and OSXSAVE are present. AVX is also required by the kernels. + constexpr unsigned int required_leaf1 = (1U << 26) | (1U << 27) | (1U << 28); + if ((ecx & required_leaf1) != required_leaf1) { + return false; + } + unsigned int xcr0_low = 0; + unsigned int xcr0_high = 0; + // Read XCR0 without requiring an xsave target attribute on this baseline-ISA dispatch function. + __asm__ volatile("xgetbv" : "=a"(xcr0_low), "=d"(xcr0_high) : "c"(0)); + // XMM, YMM, opmask, ZMM_Hi256 and Hi16_ZMM must all be enabled by the operating system. + constexpr unsigned int required_xcr0 = 0xe6U; + if ((xcr0_low & required_xcr0) != required_xcr0) { + return false; + } + if (__get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx) == 0) { + return false; + } + constexpr unsigned int required_leaf7 = (1U << 16) | (1U << 17) | (1U << 21) | (1U << 30) | (1U << 31); + return (ebx & required_leaf7) == required_leaf7; +} +} // namespace bb +#endif 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 25dbbf5..dc86674 100644 --- a/barretenberg/cpp/src/barretenberg/common/parallel_for_mutex_pool.cpp +++ b/barretenberg/cpp/src/barretenberg/common/parallel_for_mutex_pool.cpp @@ -4,11 +4,14 @@ #ifndef NO_MULTITHREADING #include "log.hpp" #include "thread.hpp" +#include #include +#include #include +#include #include +#include #include -#include #include #include @@ -27,6 +30,60 @@ alignas(16) thread_local char tls_alignment_pad[16] __attribute__((used)) = { 1 namespace { +// Separates the hot atomics so that workers claiming iterations do not invalidate the line holding the job description. +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. +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; + +inline void cpu_relax() +{ +#if defined(__x86_64__) || defined(__i386__) + __builtin_ia32_pause(); +#elif defined(__aarch64__) + asm volatile("yield" ::: "memory"); +#endif +} + +/** + * @brief Busy-waits until `done()` holds or SPIN_DURATION elapses. + * @return true if `done()` holds. + */ +template bool spin_until(const Done& done) +{ + auto deadline = std::chrono::steady_clock::now() + SPIN_DURATION; + for (size_t spins = 1;; ++spins) { + if (done()) { + return true; + } + if (spins % SPIN_CLOCK_INTERVAL == 0 && std::chrono::steady_clock::now() >= deadline) { + return done(); + } + cpu_relax(); + } +} + +/** + * @brief A pool of persistent workers that run the iterations of one parallel_for at a time together with the calling + * thread. + * + * @details A job is published through `work_`, which packs a 32-bit job generation (high half) with the index of the + * next unclaimed iteration (low half). Threads claim iterations by CAS on `work_`; a claim only succeeds while its + * generation is current, so a thread that is late to a finished job can never claim an iteration of a newer one. + * The bound checked before the CAS is read from `num_iterations_[generation % 2]`: the caller writes the next job's + * bound into the other slot, so a late thread still reads its own job's bound. The slot of generation g is rewritten + * (with release) only for generation g + 2, after generation g + 1 was published; a thread that acquires that value + * is ordered after the publication and its CAS against generation g fails. `task_` and `parent_` are only read after + * a successful claim and only rewritten once every iteration of the current job has completed. + * + * Idle workers spin briefly on `work_` before sleeping on `wake_condition_`; the caller likewise spins on `completed_` + * before sleeping on `done_condition_`. The sleeper counts and the published state are sequentially consistent so a + * publisher either sees a sleeper (and notifies under the mutex) or the sleeper sees the new state before blocking. + */ class ThreadPool { public: ThreadPool(size_t num_threads); @@ -39,58 +96,84 @@ class ThreadPool { void start_tasks(size_t num_iterations, const std::function& func) { - parent.store(bb::detail::GlobalBenchStatsContainer::parent); - { - std::unique_lock lock(tasks_mutex); - task_ = func; - num_iterations_ = num_iterations; - iteration_ = 0; - complete_ = 0; + BB_ASSERT_LT(num_iterations, size_t{ std::numeric_limits::max() }); + if (num_iterations == 0) { + return; + } + parent_.store(bb::detail::GlobalBenchStatsContainer::parent, std::memory_order_relaxed); + task_.store(&func, std::memory_order_relaxed); + completed_.store(0, std::memory_order_relaxed); + generation_++; + num_iterations_[generation_ % 2].store(num_iterations, std::memory_order_release); + work_.store(static_cast(generation_) << 32); + if (sleeping_workers_.load() > 0) { + std::unique_lock lock(mutex_); + wake_condition_.notify_all(); } - condition.notify_all(); - do_iterations(); + do_iterations(generation_); - { - // BB_BENCH_NAME("spinning main thread"); - std::unique_lock lock(tasks_mutex); - complete_condition_.wait(lock, [this] { return complete_ == num_iterations_; }); + auto done = [&] { return completed_.load() == num_iterations; }; + if (!spin_until(done)) { + std::unique_lock lock(mutex_); + caller_sleeping_.store(true); + done_condition_.wait(lock, done); + caller_sleeping_.store(false); } } private: - std::atomic parent = nullptr; + alignas(CACHE_LINE_SIZE) std::atomic work_ = 0; + alignas(CACHE_LINE_SIZE) std::atomic completed_ = 0; + alignas(CACHE_LINE_SIZE) std::atomic*> task_ = nullptr; + std::array, 2> num_iterations_{}; + std::atomic parent_ = nullptr; + std::atomic sleeping_workers_ = 0; + std::atomic caller_sleeping_ = false; + std::atomic stop_ = false; + // Only accessed by the owning (calling) thread. + uint32_t generation_ = 0; std::vector workers; - std::mutex tasks_mutex; - std::function task_; - size_t num_iterations_ = 0; - size_t iteration_ = 0; - size_t complete_ = 0; - std::condition_variable condition; - std::condition_variable complete_condition_; - bool stop = false; + std::mutex mutex_; + std::condition_variable wake_condition_; + std::condition_variable done_condition_; BB_NO_PROFILE void worker_loop(size_t thread_index); - void do_iterations() + static uint32_t generation_of(uint64_t work) { return static_cast(work >> 32); } + + /** + * @brief Claims and runs iterations of job `generation` until none are left. + * @return Whether at least one iteration was claimed. + */ + bool do_iterations(uint32_t generation) { + bool claimed_any = false; + uint64_t work = work_.load(std::memory_order_acquire); while (true) { - size_t iteration = 0; - { - std::unique_lock lock(tasks_mutex); - if (iteration_ == num_iterations_) { - return; - } - iteration = iteration_++; + if (generation_of(work) != generation) { + return claimed_any; } - task_(iteration); - { - std::unique_lock lock(tasks_mutex); - if (++complete_ == num_iterations_) { - complete_condition_.notify_one(); - return; - } + const size_t num_iterations = num_iterations_[generation % 2].load(std::memory_order_acquire); + const auto iteration = static_cast(static_cast(work)); + if (iteration >= num_iterations) { + return claimed_any; } + if (!work_.compare_exchange_weak(work, work + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { + continue; + } + if (!claimed_any) { + claimed_any = true; + // Make sure nested stats accounting works under multithreading + // Note: parent is a thread-local variable. + bb::detail::GlobalBenchStatsContainer::parent = parent_.load(std::memory_order_relaxed); + } + (*task_.load(std::memory_order_relaxed))(iteration); + if (completed_.fetch_add(1) + 1 == num_iterations && caller_sleeping_.load()) { + std::unique_lock lock(mutex_); + done_condition_.notify_one(); + } + work = work_.load(std::memory_order_acquire); } } }; @@ -106,10 +189,10 @@ ThreadPool::ThreadPool(size_t num_threads) ThreadPool::~ThreadPool() { { - std::unique_lock lock(tasks_mutex); - stop = true; + std::unique_lock lock(mutex_); + stop_.store(true); } - condition.notify_all(); + wake_condition_.notify_all(); for (auto& worker : workers) { worker.join(); } @@ -118,19 +201,20 @@ ThreadPool::~ThreadPool() void ThreadPool::worker_loop([[maybe_unused]] size_t thread_index) { // info("created worker ", thread_index); + uint32_t seen_generation = 0; while (true) { - { - std::unique_lock lock(tasks_mutex); - condition.wait(lock, [this] { return (iteration_ < num_iterations_) || stop; }); - - if (stop) { - break; - } + auto has_new_job = [&] { return generation_of(work_.load()) != seen_generation || stop_.load(); }; + if (!spin_until(has_new_job)) { + std::unique_lock lock(mutex_); + sleeping_workers_++; + wake_condition_.wait(lock, has_new_job); + sleeping_workers_--; + } + if (stop_.load()) { + break; } - // Make sure nested stats accounting works under multithreading - // Note: parent is a thread-local variable. - bb::detail::GlobalBenchStatsContainer::parent = parent.load(); - do_iterations(); + seen_generation = generation_of(work_.load(std::memory_order_acquire)); + do_iterations(seen_generation); } // info("worker exit ", worker_num); } @@ -138,8 +222,8 @@ void ThreadPool::worker_loop([[maybe_unused]] size_t thread_index) namespace bb { /** - * A thread pooled strategy that uses std::mutex for protection. Each worker increments the "iteration" and processes. - * The main thread acts as a worker also, and when it completes, it spins until thread workers are done. + * A thread pooled strategy with lock-free iteration claiming. Each worker claims the next iteration and processes it. + * The main thread acts as a worker also, and when it completes, it spins (then sleeps) until thread workers are done. */ void parallel_for_mutex_pool(size_t num_iterations, const std::function& func) { diff --git a/barretenberg/cpp/src/barretenberg/common/thread.test.cpp b/barretenberg/cpp/src/barretenberg/common/thread.test.cpp index a4843dd..fbe99de 100644 --- a/barretenberg/cpp/src/barretenberg/common/thread.test.cpp +++ b/barretenberg/cpp/src/barretenberg/common/thread.test.cpp @@ -175,4 +175,44 @@ TEST_F(ThreadTest, SpawnedThreadsCanUseParallelFor) } } } + +// Many back-to-back parallel_for calls of varying size and duration, including empty iterations and calls short enough +// that the caller finishes before the workers wake up. Every iteration must run exactly once per call. +TEST_F(ThreadTest, ManyConsecutiveParallelFors) +{ + constexpr size_t num_calls = 20000; + constexpr size_t max_iterations = 37; + std::vector> counts(max_iterations); + size_t expected_total = 0; + for (size_t call = 0; call < num_calls; ++call) { + const size_t num_iterations = call % max_iterations; + // Every 1000th call does enough work per iteration that idle threads fall back to sleeping. + const size_t work = (call % 1000 == 0) ? 200000 : (call % 7); + parallel_for(num_iterations, [&](size_t i) { + volatile size_t sink = 0; + for (size_t j = 0; j < work; ++j) { + sink = sink + j; + } + counts[i].fetch_add(1, std::memory_order_relaxed); + }); + expected_total += num_iterations; + if (call % 5000 == 0) { + // Leave the pool idle long enough for the workers to block. + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + } + size_t total = 0; + for (size_t i = 0; i < max_iterations; ++i) { + total += counts[i].load(); + } + EXPECT_EQ(total, expected_total); + for (size_t i = 0; i + 1 < max_iterations; ++i) { + // Iteration i runs in every call with num_iterations > i. + size_t expected = 0; + for (size_t call = 0; call < num_calls; ++call) { + expected += (call % max_iterations > i) ? 1 : 0; + } + EXPECT_EQ(counts[i].load(), expected); + } +} } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2_permutation.hpp b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2_permutation.hpp index d09a1d5..3e389f7 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2_permutation.hpp +++ b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/poseidon2_permutation.hpp @@ -41,6 +41,8 @@ template class Poseidon2Permutation { static constexpr MatrixDiagonal internal_matrix_diagonal_minus_one = Params::internal_matrix_diagonal_minus_one; static constexpr RoundConstantsContainer round_constants = Params::round_constants; + // D_0, the first diagonal entry of the internal matrix + static constexpr FF internal_matrix_diagonal_0 = internal_matrix_diagonal_minus_one[0] + FF(1); static constexpr void matrix_multiplication_4x4(State& input) { @@ -86,15 +88,21 @@ template class Poseidon2Permutation { { // for t = 4 // Computes: result[i] = (D_i - 1) * input[i] + sum = D_i * input[i] + (sum of other elements) - // where D_i are the actual diagonal values and internal_matrix_diagonal_minus_one[i] = D_i - 1 - auto sum = input[0]; - for (size_t i = 1; i < t; ++i) { - sum += input[i]; - } - for (size_t i = 0; i < t; ++i) { - input[i] *= internal_matrix_diagonal_minus_one[i]; - input[i] += sum; - } + // where D_i are the actual diagonal values and internal_matrix_diagonal_minus_one[i] = D_i - 1. + // result[0] is formed as D_0 * input[0] + (input[1] + input[2] + input[3]) so that it depends on input[0] + // through a single multiplication and addition. + static_assert(t == 4, "Only t=4 is supported"); + FF sum_rest = input[1] + input[2]; + sum_rest += input[3]; + const FF sum = input[0] + sum_rest; + const FF scaled_0 = input[0] * internal_matrix_diagonal_0; + const FF scaled_1 = input[1] * internal_matrix_diagonal_minus_one[1]; + const FF scaled_2 = input[2] * internal_matrix_diagonal_minus_one[2]; + const FF scaled_3 = input[3] * internal_matrix_diagonal_minus_one[3]; + input[0] = scaled_0 + sum_rest; + input[1] = scaled_1 + sum; + input[2] = scaled_2 + sum; + input[3] = scaled_3 + sum; } static constexpr void matrix_multiplication_external(State& input) @@ -118,43 +126,96 @@ template class Poseidon2Permutation { static constexpr void apply_sbox(State& input) { - for (auto& in : input) { - apply_single_sbox(in); - } + // The four S-boxes are evaluated stage by stage so that their independent multiplications interleave. + static_assert(t == 4, "Only t=4 is supported"); + FF x4_0 = input[0].sqr(); + FF x4_1 = input[1].sqr(); + FF x4_2 = input[2].sqr(); + FF x4_3 = input[3].sqr(); + x4_0.self_sqr(); + x4_1.self_sqr(); + x4_2.self_sqr(); + x4_3.self_sqr(); + input[0] *= x4_0; + input[1] *= x4_1; + input[2] *= x4_2; + input[3] *= x4_3; + } + + /** + * @brief One external round on a state held in locals: add round constants, S-box layer, external matrix. + */ + static constexpr void external_round(FF& s0, FF& s1, FF& s2, FF& s3, const RoundConstants& rc) + { + State state{ s0, s1, s2, s3 }; + add_round_constants(state, rc); + apply_sbox(state); + matrix_multiplication_external(state); + s0 = state[0]; + s1 = state[1]; + s2 = state[2]; + s3 = state[3]; } /** * @brief In-place Poseidon2 permutation from https://eprint.iacr.org/2023/323. * @details The permutation consists of one initial linear layer, then a set of external rounds, a set of internal * rounds, and a set of external rounds. + * + * The internal rounds compute the same values as `apply_single_sbox` followed by `matrix_multiplication_internal`, + * arranged to shorten the dependency chain through state[0]. With sb = (state[0] + c)^5 and + * t = state[1] + state[2] + state[3], the internal matrix gives + * state[0] <- D_0 * sb + t + * state[i] <- (D_i - 1) * state[i] + (sb + t) for i = 1, 2, 3 + * so only the S-box and one multiplication by D_0 lie on the round-to-round critical path; the three other + * diagonal multiplications are issued between the S-box steps, where they overlap with it. */ static constexpr void permutation_inplace(State& state) { + static_assert(t == 4, "Only t=4 is supported"); // Apply 1st linear layer matrix_multiplication_external(state); + FF s0 = state[0]; + FF s1 = state[1]; + FF s2 = state[2]; + FF s3 = state[3]; + // First set of external rounds constexpr size_t rounds_f_beginning = rounds_f / 2; for (size_t i = 0; i < rounds_f_beginning; ++i) { - add_round_constants(state, round_constants[i]); - apply_sbox(state); - matrix_multiplication_external(state); + external_round(s0, s1, s2, s3, round_constants[i]); } // Internal rounds constexpr size_t p_end = rounds_f_beginning + rounds_p; for (size_t i = rounds_f_beginning; i < p_end; ++i) { - state[0] += round_constants[i][0]; - apply_single_sbox(state[0]); - matrix_multiplication_internal(state); + const FF u = s0 + round_constants[i][0]; + FF u_4 = u.sqr(); + FF sum_rest = s1 + s2; + sum_rest += s3; + const FF s1_scaled = s1 * internal_matrix_diagonal_minus_one[1]; + u_4.self_sqr(); + const FF s2_scaled = s2 * internal_matrix_diagonal_minus_one[2]; + const FF sb = u * u_4; + const FF s3_scaled = s3 * internal_matrix_diagonal_minus_one[3]; + const FF sum = sb + sum_rest; + s0 = sb * internal_matrix_diagonal_0; + s0 += sum_rest; + s1 = s1_scaled + sum; + s2 = s2_scaled + sum; + s3 = s3_scaled + sum; } // Remaining external rounds for (size_t i = p_end; i < NUM_ROUNDS; ++i) { - add_round_constants(state, round_constants[i]); - apply_sbox(state); - matrix_multiplication_external(state); + external_round(s0, s1, s2, s3, round_constants[i]); } + + state[0] = s0; + state[1] = s1; + state[2] = s2; + state[3] = s3; } /** diff --git a/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.cpp b/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.cpp index 848bb18..898d3ac 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.cpp +++ b/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.cpp @@ -8,9 +8,17 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/net.hpp" #include +#include +#include #include #include +#if defined(__x86_64__) && !defined(__wasm__) && (defined(__clang__) || defined(__GNUC__)) +#define BB_SHA256_X86_SHA_NI 1 +#include +#include +#endif + namespace { // Initial hash values H[0..7] (FIPS 180-4 Section 5.3.3) @@ -45,6 +53,99 @@ constexpr uint32_t ror(uint32_t val, uint32_t shift) return (val >> (shift & 31U)) | (val << (32U - (shift & 31U))); } +#ifdef BB_SHA256_X86_SHA_NI +/** + * @brief Whether the CPU implements the x86 SHA extensions (and the SSSE3 / SSE4.1 shuffles the kernel uses). + */ +bool cpu_has_sha_ni() +{ + unsigned int eax = 0; + unsigned int ebx = 0; + unsigned int ecx = 0; + unsigned int edx = 0; + if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0) { + return false; + } + const bool has_ssse3 = (ecx & (1U << 9)) != 0; + const bool has_sse41 = (ecx & (1U << 19)) != 0; + if (__get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx) == 0) { + return false; + } + const bool has_sha = (ebx & (1U << 29)) != 0; + return has_ssse3 && has_sse41 && has_sha; +} + +const bool use_sha_ni = cpu_has_sha_ni(); + +/** + * @brief SHA-256 compression of consecutive 64-byte big-endian message blocks with the x86 SHA extensions. + * @details Computes the same function as repeated `sha256_block` calls. The state is kept in the (ABEF, CDGH) lane + * layout that SHA256RNDS2 operates on; each SHA256RNDS2 performs two rounds, and SHA256MSG1/SHA256MSG2 extend the + * message schedule four words at a time. + */ +__attribute__((target("sha,sse4.1,ssse3"))) void compress_blocks_sha_ni(std::array& state, + const uint8_t* data, + size_t num_blocks) +{ + // Byte-swaps each 32-bit word: message words are big-endian. + const __m128i byte_swap_mask = _mm_set_epi64x(0x0c0d0e0f08090a0bULL, 0x0405060700010203ULL); + const auto round_constants_at = [](size_t i) { + return _mm_loadu_si128(reinterpret_cast(&round_constants[i])); + }; + + // (a, b, c, d), (e, f, g, h) -> (a, b, e, f), (c, d, g, h) + __m128i tmp = _mm_loadu_si128(reinterpret_cast(&state[0])); + __m128i state1 = _mm_loadu_si128(reinterpret_cast(&state[4])); + tmp = _mm_shuffle_epi32(tmp, 0xB1); + state1 = _mm_shuffle_epi32(state1, 0x1B); + __m128i state0 = _mm_alignr_epi8(tmp, state1, 8); + state1 = _mm_blend_epi16(state1, tmp, 0xF0); + + for (size_t block = 0; block < num_blocks; ++block) { + const uint8_t* block_data = data + (block * 64); + const __m128i abef_save = state0; + const __m128i cdgh_save = state1; + + // msg[j] holds message words 4j..4j+3 of the current group of 16, extended in place. + std::array<__m128i, 4> msg; + for (size_t j = 0; j < 4; ++j) { + msg[j] = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast(block_data + (16 * j))), + byte_swap_mask); + } + + // Group g covers rounds 4g..4g+3 and uses msg[g % 4]. While it runs, the schedule words of later groups are + // advanced: SHA256MSG2 completes the words for group g+1 and SHA256MSG1 starts the words for group g+3. + for (size_t g = 0; g < 16; ++g) { + __m128i& current = msg[g % 4]; + __m128i& previous = msg[(g + 3) % 4]; + __m128i& next = msg[(g + 1) % 4]; + __m128i words = _mm_add_epi32(current, round_constants_at(4 * g)); + state1 = _mm_sha256rnds2_epu32(state1, state0, words); + if (g >= 3 && g <= 14) { + next = _mm_add_epi32(next, _mm_alignr_epi8(current, previous, 4)); + next = _mm_sha256msg2_epu32(next, current); + } + words = _mm_shuffle_epi32(words, 0x0E); + state0 = _mm_sha256rnds2_epu32(state0, state1, words); + if (g >= 1 && g <= 12) { + previous = _mm_sha256msg1_epu32(previous, current); + } + } + + state0 = _mm_add_epi32(state0, abef_save); + state1 = _mm_add_epi32(state1, cdgh_save); + } + + // (a, b, e, f), (c, d, g, h) -> (a, b, c, d), (e, f, g, h) + tmp = _mm_shuffle_epi32(state0, 0x1B); + state1 = _mm_shuffle_epi32(state1, 0xB1); + state0 = _mm_blend_epi16(tmp, state1, 0xF0); + state1 = _mm_alignr_epi8(state1, tmp, 8); + _mm_storeu_si128(reinterpret_cast<__m128i*>(&state[0]), state0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(&state[4]), state1); +} +#endif + } // namespace namespace bb::crypto { @@ -147,36 +248,55 @@ std::array sha256_block(const std::array& h_init, cons * @param input Message bytes to hash * @return 256-bit hash as 32 bytes */ -template Sha256Hash sha256(const ByteContainer& input) +/** + * @brief Apply the compression function to consecutive 64-byte message blocks (big-endian words). + */ +void sha256_compress_blocks(std::array& state, const uint8_t* data, size_t num_blocks) { - std::vector message_schedule; - - std::copy(input.begin(), input.end(), std::back_inserter(message_schedule)); - uint64_t l = message_schedule.size() * 8; - message_schedule.push_back(0x80); - - uint32_t num_zero_bytes = ((448U - (message_schedule.size() << 3U)) & 511U) >> 3U; - - for (size_t i = 0; i < num_zero_bytes; ++i) { - message_schedule.push_back(0x00); - } - for (size_t i = 0; i < 8; ++i) { - uint8_t byte = static_cast(l >> (uint64_t)(56 - (i * 8))); - message_schedule.push_back(byte); +#ifdef BB_SHA256_X86_SHA_NI + if (use_sha_ni) { + compress_blocks_sha_ni(state, data, num_blocks); + return; } - std::array rolling_hash; - prepare_constants(rolling_hash); - const size_t num_blocks = message_schedule.size() / 64; +#endif for (size_t i = 0; i < num_blocks; ++i) { std::array hash_input; - memcpy((void*)&hash_input[0], (void*)&message_schedule[i * 64], 64); + memcpy((void*)&hash_input[0], (const void*)(data + (i * 64)), 64); if (is_little_endian()) { for (size_t j = 0; j < hash_input.size(); ++j) { hash_input[j] = __builtin_bswap32(hash_input[j]); } } - rolling_hash = sha256_block(rolling_hash, hash_input); + state = sha256_block(state, hash_input); + } +} + +template Sha256Hash sha256(const ByteContainer& input) +{ + const auto* data = reinterpret_cast(std::data(input)); + const size_t size = std::size(input); + + std::array rolling_hash; + prepare_constants(rolling_hash); + + // Complete blocks are compressed straight from the input. + const size_t num_full_blocks = size / 64; + sha256_compress_blocks(rolling_hash, data, num_full_blocks); + + // Padding (FIPS 180-4 Section 5.1.1): the remaining bytes, 0x80, zeros, then the message length in bits as a + // big-endian 64-bit integer, filling one block, or two if fewer than 9 bytes are left after the remainder. + const size_t remainder = size - (num_full_blocks * 64); + std::array tail{}; + if (remainder > 0) { + memcpy((void*)&tail[0], (const void*)(data + (num_full_blocks * 64)), remainder); + } + tail[remainder] = 0x80; + const size_t num_tail_blocks = (remainder + 9 <= 64) ? 1 : 2; + const uint64_t l = static_cast(size) * 8; + for (size_t i = 0; i < 8; ++i) { + tail[(num_tail_blocks * 64) - 1 - i] = static_cast(l >> (8 * i)); } + sha256_compress_blocks(rolling_hash, tail.data(), num_tail_blocks); Sha256Hash output; memcpy((void*)&output[0], (void*)&rolling_hash[0], 32); diff --git a/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.hpp b/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.hpp index 0e1399c..572b98d 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.hpp +++ b/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.hpp @@ -9,6 +9,7 @@ #include "stdint.h" #include #include +#include #include #include #include @@ -20,6 +21,10 @@ using Sha256Hash = std::array; // SHA-256 compression function (FIPS 180-4 Section 6.2.2) std::array sha256_block(const std::array& h_init, const std::array& input); +// Applies the compression function to `num_blocks` consecutive 64-byte blocks of big-endian message words. Uses the +// x86 SHA extensions when the CPU has them. +void sha256_compress_blocks(std::array& state, const uint8_t* data, size_t num_blocks); + template Sha256Hash sha256(const T& input); inline bool operator==(Sha256Hash const& lhs, std::vector const& rhs) diff --git a/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.test.cpp b/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.test.cpp index e5670d8..152cc78 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.test.cpp +++ b/barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.test.cpp @@ -2,6 +2,7 @@ #include #include #include +#include using namespace bb; using namespace bb::crypto; @@ -123,3 +124,56 @@ TEST(misc_sha256, test_NIST_vector_five) EXPECT_EQ(result[i], expected[i]); } } + +// sha256 against a reference built from the portable `sha256_block` with explicit padding, over lengths that cover +// every tail size (one- and two-block padding) and inputs spanning many full blocks. +TEST(misc_sha256, matches_block_reference) +{ + const auto reference = [](const std::vector& message) { + std::vector padded = message; + padded.push_back(0x80); + while (padded.size() % 64 != 56) { + padded.push_back(0x00); + } + const uint64_t bit_length = static_cast(message.size()) * 8; + for (size_t i = 0; i < 8; ++i) { + padded.push_back(static_cast(bit_length >> (56 - (8 * i)))); + } + std::array state{ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; + for (size_t block = 0; block < padded.size() / 64; ++block) { + std::array words; + for (size_t j = 0; j < 16; ++j) { + const size_t offset = (block * 64) + (4 * j); + words[j] = (static_cast(padded[offset]) << 24) | + (static_cast(padded[offset + 1]) << 16) | + (static_cast(padded[offset + 2]) << 8) | static_cast(padded[offset + 3]); + } + state = sha256_block(state, words); + } + Sha256Hash out; + for (size_t j = 0; j < 8; ++j) { + for (size_t k = 0; k < 4; ++k) { + out[(4 * j) + k] = static_cast(state[j] >> (24 - (8 * k))); + } + } + return out; + }; + + std::vector message; + uint32_t seed = 1; + const auto next_byte = [&seed]() { + seed = (seed * 1103515245U) + 12345U; + return static_cast(seed >> 16); + }; + for (size_t length = 0; length <= 300; ++length) { + EXPECT_EQ(sha256(message), reference(message)) << "length " << length; + message.push_back(next_byte()); + } + message.resize((1 << 16) + 17); + for (auto& byte : message) { + byte = next_byte(); + } + EXPECT_EQ(sha256(message), reference(message)); + EXPECT_EQ(sha256(std::span(message)), reference(message)); +} diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp new file mode 100644 index 0000000..1f164d9 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp @@ -0,0 +1,217 @@ +/** + * @file acir_compact_decoder.test.cpp + * @brief The streaming msgpack-compact program decoder (circuit_buf_to_acir_format) must produce the same AcirFormat + * as converting the Acir::Circuit it encodes (circuit_serde_to_acir_format). + */ + +#include +#include + +#include "acir_to_constraint_buf.hpp" +#include "barretenberg/common/assert.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/serialize/msgpack_impl.hpp" +#include "serde/acir.hpp" + +using namespace acir_format; + +namespace { + +std::vector coefficient(const bb::fr& value) +{ + std::vector bytes(32); + bb::fr::serialize_to_buffer(value, bytes.data()); + return bytes; +} + +Acir::Expression expression(const std::vector>& mul_terms, + const std::vector>& linear_terms, + uint64_t constant) +{ + Acir::Expression expr; + for (const auto& [scaling, lhs, rhs] : mul_terms) { + expr.mul_terms.emplace_back(coefficient(bb::fr(scaling)), Acir::Witness{ lhs }, Acir::Witness{ rhs }); + } + for (const auto& [scaling, witness] : linear_terms) { + expr.linear_combinations.emplace_back(coefficient(-bb::fr(scaling)), Acir::Witness{ witness }); + } + expr.q_c = coefficient(bb::fr(constant)); + return expr; +} + +Acir::Opcode assert_zero(Acir::Expression expr) +{ + return Acir::Opcode{ .value = Acir::Opcode::AssertZero{ .value = std::move(expr) } }; +} + +Acir::Opcode range(Acir::FunctionInput input, uint32_t num_bits) +{ + return Acir::Opcode{ .value = Acir::Opcode::BlackBoxFuncCall{ + .value = + Acir::BlackBoxFuncCall{ .value = Acir::BlackBoxFuncCall::RANGE{ + .input = std::move(input), .num_bits = num_bits } } } }; +} + +Acir::Opcode memory_op(uint32_t block_id, bool is_write, uint32_t index, uint32_t value) +{ + return Acir::Opcode{ .value = Acir::Opcode::MemoryOp{ + .block_id = Acir::BlockId{ block_id }, + .op = Acir::MemOp{ .read = is_write, .index = { index }, .value = { value } } } }; +} + +std::vector serialize_program(const Acir::Circuit& circuit) +{ + msgpack::sbuffer sbuf; + msgpack::packer packer(sbuf); + // Program = [functions, unconstrained_functions] + packer.pack_array(2); + packer.pack_array(1); + packer.pack(circuit); + packer.pack_array(0); + + std::vector buf; + buf.push_back(0x03); // FORMAT_MSGPACK_COMPACT + buf.insert(buf.end(), sbuf.data(), sbuf.data() + sbuf.size()); + return buf; +} + +Acir::Circuit test_circuit() +{ + Acir::Circuit circuit; + auto& ops = circuit.opcodes; + + // AssertZero opcodes of every gate shape, with growing and shrinking term counts (exercises buffer reuse), + // duplicate linear witnesses and witness indices in every msgpack integer width. + ops.push_back(assert_zero(expression({}, { { 1, 1 }, { 1, 2 } }, 0))); + ops.push_back(assert_zero(expression({ { 1, 1, 2 } }, { { 1, 3 } }, 5))); + ops.push_back(assert_zero(expression({ { 2, 1, 2 }, { 3, 2, 4 } }, { { 1, 1 }, { 1, 4 }, { 1, 5 } }, 0))); + ops.push_back(assert_zero(expression( + { { 2, 1, 2 }, { 3, 3, 4 }, { 4, 5, 6 } }, { { 1, 7 }, { 1, 8 }, { 1, 9 }, { 1, 10 }, { 1, 11 } }, 7))); + ops.push_back(assert_zero(expression({}, { { 1, 200 } }, 3))); + ops.push_back(assert_zero(expression({ { 1, 300, 300 } }, { { 1, 300 }, { 2, 300 }, { 1, 70000 } }, 0))); + ops.push_back(assert_zero(expression({}, { { 1, 12 }, { 1, 13 }, { 1, 14 }, { 1, 15 }, { 1, 16 }, { 1, 17 } }, 1))); + ops.push_back(assert_zero(expression({ { 5, 18, 19 } }, {}, 0))); + ops.push_back(assert_zero(expression({}, { { 1, 20 }, { 1, 21 } }, 9))); + + // Range constraints on witnesses in different msgpack integer widths. + ops.push_back(range(Acir::FunctionInput{ .value = Acir::FunctionInput::Witness{ .value = { 22 } } }, 32)); + ops.push_back(range(Acir::FunctionInput{ .value = Acir::FunctionInput::Witness{ .value = { 100000 } } }, 254)); + + // Memory: MemoryInit goes through the generic decoder, MemoryOp reads and writes are decoded directly. + ops.push_back(Acir::Opcode{ + .value = Acir::Opcode::MemoryInit{ .block_id = { 0 }, + .init = { { 23 }, { 24 }, { 25 } }, + .block_type = Acir::BlockType{ .value = Acir::BlockType::Memory{} } } }); + ops.push_back(memory_op(0, false, 26, 27)); + ops.push_back(memory_op(0, true, 28, 29)); + + // Brillig calls only contribute their witness indices; the largest index of the circuit is in one. + ops.push_back(Acir::Opcode{ + .value = Acir::Opcode::BrilligCall{ + .id = 3, + .inputs = { Acir::BrilligInputs{ .value = + Acir::BrilligInputs::Single{ + .value = expression({ { 1, 30, 31 } }, { { 1, 32 } }, 0) } }, + Acir::BrilligInputs{ + .value = Acir::BrilligInputs::Array{ .value = { expression({}, { { 1, 33 } }, 0), + expression( + {}, { { 1, 34 }, { 1, 35 } }, 1) } } }, + Acir::BrilligInputs{ .value = Acir::BrilligInputs::MemoryArray{ .value = { 0 } } } }, + .outputs = { Acir::BrilligOutputs{ .value = Acir::BrilligOutputs::Simple{ .value = { 36 } } }, + Acir::BrilligOutputs{ .value = + Acir::BrilligOutputs::Array{ .value = { { 37 }, { 5000000 } } } } }, + .predicate = expression({}, {}, 1) } }); + ops.push_back(Acir::Opcode{ .value = Acir::Opcode::BrilligCall{ + .id = 0, .inputs = {}, .outputs = {}, .predicate = expression({}, {}, 1) } }); + + // An AssertZero after the generic and Brillig paths. + ops.push_back(assert_zero(expression({ { 1, 38, 39 } }, { { 1, 40 } }, 0))); + + // Skipped fields: a str8 function name, uint64 error selectors and nested expressions in the assert messages. + circuit.function_name = std::string(40, 'f'); + circuit.assert_messages.emplace_back( + Acir::OpcodeLocation{ .value = Acir::OpcodeLocation::Acir{ .value = 3 } }, + Acir::AssertionPayload{ + .error_selector = 14990209321349310352ULL, + .payload = { + Acir::ExpressionOrMemory{ + .value = Acir::ExpressionOrMemory::Expression{ .value = expression({}, { { 1, 2 } }, 0) } }, + Acir::ExpressionOrMemory{ .value = Acir::ExpressionOrMemory::Memory{ .value = { 0 } } } } }); + circuit.assert_messages.emplace_back(Acir::OpcodeLocation{ .value = Acir::OpcodeLocation::Acir{ .value = 70000 } }, + Acir::AssertionPayload{ .error_selector = 1, .payload = {} }); + circuit.private_parameters = { { 1 }, { 2 }, { 300 }, { 70000 } }; + circuit.public_parameters = Acir::PublicInputs{ .value = { { 3 }, { 4 } } }; + circuit.return_values = Acir::PublicInputs{ .value = { { 40 } } }; + return circuit; +} + +// mul_quad_, MemOp and BlockConstraint have no operator==, so AcirFormat's defaulted one is not usable. +auto quad_fields(const QuadConstraint& q) +{ + return std::make_tuple( + q.a, q.b, q.c, q.d, q.mul_scaling, q.a_scaling, q.b_scaling, q.c_scaling, q.d_scaling, q.const_scaling); +} + +void expect_same_quads(const std::vector& lhs, const std::vector& rhs) +{ + ASSERT_EQ(lhs.size(), rhs.size()); + for (size_t i = 0; i < lhs.size(); ++i) { + EXPECT_EQ(quad_fields(lhs[i]), quad_fields(rhs[i])); + } +} + +void expect_same_acir_format(const AcirFormat& lhs, const AcirFormat& rhs) +{ + EXPECT_EQ(lhs.max_witness_index, rhs.max_witness_index); + EXPECT_EQ(lhs.num_acir_opcodes, rhs.num_acir_opcodes); + EXPECT_EQ(lhs.public_inputs, rhs.public_inputs); + EXPECT_EQ(lhs.range_constraints, rhs.range_constraints); + expect_same_quads(lhs.quad_constraints, rhs.quad_constraints); + ASSERT_EQ(lhs.big_quad_constraints.size(), rhs.big_quad_constraints.size()); + for (size_t i = 0; i < lhs.big_quad_constraints.size(); ++i) { + expect_same_quads(lhs.big_quad_constraints[i], rhs.big_quad_constraints[i]); + } + EXPECT_EQ(lhs.bilinear_constraints, rhs.bilinear_constraints); + EXPECT_EQ(lhs.batched_eq_check_constraints, rhs.batched_eq_check_constraints); + ASSERT_EQ(lhs.block_constraints.size(), rhs.block_constraints.size()); + for (size_t i = 0; i < lhs.block_constraints.size(); ++i) { + const auto& lhs_block = lhs.block_constraints[i]; + const auto& rhs_block = rhs.block_constraints[i]; + EXPECT_EQ(lhs_block.init, rhs_block.init); + EXPECT_EQ(lhs_block.type, rhs_block.type); + EXPECT_EQ(lhs_block.calldata_id, rhs_block.calldata_id); + ASSERT_EQ(lhs_block.trace.size(), rhs_block.trace.size()); + for (size_t j = 0; j < lhs_block.trace.size(); ++j) { + EXPECT_EQ(lhs_block.trace[j].access_type, rhs_block.trace[j].access_type); + EXPECT_EQ(lhs_block.trace[j].index, rhs_block.trace[j].index); + EXPECT_EQ(lhs_block.trace[j].value, rhs_block.trace[j].value); + } + } + EXPECT_EQ(lhs.original_opcode_indices, rhs.original_opcode_indices); +} + +} // namespace + +TEST(AcirCompactDecoder, MatchesCircuitConversion) +{ + const Acir::Circuit circuit = test_circuit(); + for (const bool is_mega : { false, true }) { + const AcirFormat expected = circuit_serde_to_acir_format(circuit, is_mega); + const AcirFormat decoded = circuit_buf_to_acir_format(serialize_program(circuit), is_mega); + expect_same_acir_format(decoded, expected); + EXPECT_EQ(decoded.max_witness_index, 5000000U); + EXPECT_EQ(decoded.num_acir_opcodes, circuit.opcodes.size()); + EXPECT_FALSE(decoded.quad_constraints.empty()); + EXPECT_FALSE(decoded.big_quad_constraints.empty()); + EXPECT_EQ(decoded.range_constraints.size(), 2U); + EXPECT_EQ(decoded.block_constraints.size(), 1U); + } +} + +TEST(AcirCompactDecoder, RejectsTruncatedAssertMessages) +{ + std::vector buf = serialize_program(test_circuit()); + // The assert messages are the last field of the circuit; the empty unconstrained function list follows them. + buf.resize(buf.size() - 2); + EXPECT_THROW_WITH_MESSAGE(circuit_buf_to_acir_format(std::move(buf), /*is_mega=*/true), "malformed msgpack data"); +} diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/arithmetic_constraints.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/arithmetic_constraints.cpp index 20ff826..12407a3 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/arithmetic_constraints.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/arithmetic_constraints.cpp @@ -37,12 +37,20 @@ void check_mul_add_gate(Builder& builder, const QuadConstraint& mul_quad, const return; } + // Terms with a zero scaling are skipped: they add zero, and only result == 0 is checked. FF result = mul_quad.const_scaling + next_wire_w4; - result += builder.get_variable(mul_quad.a) * builder.get_variable(mul_quad.b) * mul_quad.mul_scaling; - result += builder.get_variable(mul_quad.a) * mul_quad.a_scaling; - result += builder.get_variable(mul_quad.b) * mul_quad.b_scaling; - result += builder.get_variable(mul_quad.c) * mul_quad.c_scaling; - result += builder.get_variable(mul_quad.d) * mul_quad.d_scaling; + if (!mul_quad.mul_scaling.is_zero()) { + result += builder.get_variable(mul_quad.a) * builder.get_variable(mul_quad.b) * mul_quad.mul_scaling; + } + auto add_linear_term = [&](uint32_t witness_index, const FF& scaling) { + if (!scaling.is_zero()) { + result += builder.get_variable(witness_index) * scaling; + } + }; + add_linear_term(mul_quad.a, mul_quad.a_scaling); + add_linear_term(mul_quad.b, mul_quad.b_scaling); + add_linear_term(mul_quad.c, mul_quad.c_scaling); + add_linear_term(mul_quad.d, mul_quad.d_scaling); if (result != FF::zero()) { builder.failure("mul_add_gate"); diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp index 68bf0db..4df9b60 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/acir.hpp @@ -56,22 +56,23 @@ struct Helpers { template static void conv_fld_from_array(msgpack::object_array const& array, std::string const& struct_name, - std::string const& field_name, + std::string_view field_name, T& field, uint32_t index) { if (index >= array.size) { - throw_or_abort("index out of bounds: " + struct_name + "::" + field_name + " at " + std::to_string(index)); + throw_or_abort("index out of bounds: " + struct_name + "::" + std::string(field_name) + " at " + + std::to_string(index)); } auto element = array.ptr[index]; if (element.type == msgpack::type::NIL) { - throw_or_abort("nil value for required field: " + struct_name + "::" + field_name); + throw_or_abort("nil value for required field: " + struct_name + "::" + std::string(field_name)); } try { element.convert(field); } catch (const msgpack::type_error&) { std::cerr << element << std::endl; - throw_or_abort("error converting into field " + struct_name + "::" + field_name); + throw_or_abort("error converting into field " + struct_name + "::" + std::string(field_name)); } } @@ -81,14 +82,14 @@ struct Helpers { template static void convert_or_throw(msgpack::object const& val, std::string const& struct_name, - std::string const& field_name, + std::string_view field_name, T& field) { try { val.convert(field); } catch (const msgpack::type_error&) { std::cerr << val << std::endl; - throw_or_abort("error converting into field " + struct_name + "::" + field_name); + throw_or_abort("error converting into field " + struct_name + "::" + std::string(field_name)); } } @@ -288,42 +289,42 @@ struct BinaryFieldOp { switch (tag) { case 0: { Add v; - value = v; + value = std::move(v); break; } case 1: { Sub v; - value = v; + value = std::move(v); break; } case 2: { Mul v; - value = v; + value = std::move(v); break; } case 3: { Div v; - value = v; + value = std::move(v); break; } case 4: { IntegerDiv v; - value = v; + value = std::move(v); break; } case 5: { Equals v; - value = v; + value = std::move(v); break; } case 6: { LessThan v; - value = v; + value = std::move(v); break; } case 7: { LessThanEquals v; - value = v; + value = std::move(v); break; } default: @@ -346,28 +347,28 @@ struct BinaryFieldOp { } if (tag == "Add") { Add v; - value = v; + value = std::move(v); } else if (tag == "Sub") { Sub v; - value = v; + value = std::move(v); } else if (tag == "Mul") { Mul v; - value = v; + value = std::move(v); } else if (tag == "Div") { Div v; - value = v; + value = std::move(v); } else if (tag == "IntegerDiv") { IntegerDiv v; - value = v; + value = std::move(v); } else if (tag == "Equals") { Equals v; - value = v; + value = std::move(v); } else if (tag == "LessThan") { LessThan v; - value = v; + value = std::move(v); } else if (tag == "LessThanEquals") { LessThanEquals v; - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BinaryFieldOp' enum variant: " + tag); @@ -558,62 +559,62 @@ struct BinaryIntOp { switch (tag) { case 0: { Add v; - value = v; + value = std::move(v); break; } case 1: { Sub v; - value = v; + value = std::move(v); break; } case 2: { Mul v; - value = v; + value = std::move(v); break; } case 3: { Div v; - value = v; + value = std::move(v); break; } case 4: { Equals v; - value = v; + value = std::move(v); break; } case 5: { LessThan v; - value = v; + value = std::move(v); break; } case 6: { LessThanEquals v; - value = v; + value = std::move(v); break; } case 7: { And v; - value = v; + value = std::move(v); break; } case 8: { Or v; - value = v; + value = std::move(v); break; } case 9: { Xor v; - value = v; + value = std::move(v); break; } case 10: { Shl v; - value = v; + value = std::move(v); break; } case 11: { Shr v; - value = v; + value = std::move(v); break; } default: @@ -636,40 +637,40 @@ struct BinaryIntOp { } if (tag == "Add") { Add v; - value = v; + value = std::move(v); } else if (tag == "Sub") { Sub v; - value = v; + value = std::move(v); } else if (tag == "Mul") { Mul v; - value = v; + value = std::move(v); } else if (tag == "Div") { Div v; - value = v; + value = std::move(v); } else if (tag == "Equals") { Equals v; - value = v; + value = std::move(v); } else if (tag == "LessThan") { LessThan v; - value = v; + value = std::move(v); } else if (tag == "LessThanEquals") { LessThanEquals v; - value = v; + value = std::move(v); } else if (tag == "And") { And v; - value = v; + value = std::move(v); } else if (tag == "Or") { Or v; - value = v; + value = std::move(v); } else if (tag == "Xor") { Xor v; - value = v; + value = std::move(v); } else if (tag == "Shl") { Shl v; - value = v; + value = std::move(v); } else if (tag == "Shr") { Shr v; - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BinaryIntOp' enum variant: " + tag); @@ -794,32 +795,32 @@ struct IntegerBitSize { switch (tag) { case 0: { U1 v; - value = v; + value = std::move(v); break; } case 1: { U8 v; - value = v; + value = std::move(v); break; } case 2: { U16 v; - value = v; + value = std::move(v); break; } case 3: { U32 v; - value = v; + value = std::move(v); break; } case 4: { U64 v; - value = v; + value = std::move(v); break; } case 5: { U128 v; - value = v; + value = std::move(v); break; } default: @@ -842,22 +843,22 @@ struct IntegerBitSize { } if (tag == "U1") { U1 v; - value = v; + value = std::move(v); } else if (tag == "U8") { U8 v; - value = v; + value = std::move(v); } else if (tag == "U16") { U16 v; - value = v; + value = std::move(v); } else if (tag == "U32") { U32 v; - value = v; + value = std::move(v); } else if (tag == "U64") { U64 v; - value = v; + value = std::move(v); } else if (tag == "U128") { U128 v; - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'IntegerBitSize' enum variant: " + tag); @@ -949,7 +950,7 @@ struct BitSize { switch (tag) { case 0: { Field v; - value = v; + value = std::move(v); break; } case 1: { @@ -960,7 +961,7 @@ struct BitSize { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BitSize::Integer'"); } - value = v; + value = std::move(v); break; } default: @@ -983,7 +984,7 @@ struct BitSize { } if (tag == "Field") { Field v; - value = v; + value = std::move(v); } else if (tag == "Integer") { Integer v; try { @@ -993,7 +994,7 @@ struct BitSize { throw_or_abort("error converting into enum variant 'BitSize::Integer'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BitSize' enum variant: " + tag); @@ -1102,7 +1103,7 @@ struct MemoryAddress { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'MemoryAddress::Direct'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -1113,7 +1114,7 @@ struct MemoryAddress { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'MemoryAddress::Relative'"); } - value = v; + value = std::move(v); break; } default: @@ -1143,7 +1144,7 @@ struct MemoryAddress { throw_or_abort("error converting into enum variant 'MemoryAddress::Direct'"); } - value = v; + value = std::move(v); } else if (tag == "Relative") { Relative v; try { @@ -1153,7 +1154,7 @@ struct MemoryAddress { throw_or_abort("error converting into enum variant 'MemoryAddress::Relative'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'MemoryAddress' enum variant: " + tag); @@ -1979,7 +1980,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::AES128Encrypt'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -1990,7 +1991,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::Blake2s'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -2001,7 +2002,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::Blake3'"); } - value = v; + value = std::move(v); break; } case 3: { @@ -2012,7 +2013,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::Keccakf1600'"); } - value = v; + value = std::move(v); break; } case 4: { @@ -2023,7 +2024,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::EcdsaSecp256k1'"); } - value = v; + value = std::move(v); break; } case 5: { @@ -2034,7 +2035,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::EcdsaSecp256r1'"); } - value = v; + value = std::move(v); break; } case 6: { @@ -2045,7 +2046,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::MultiScalarMul'"); } - value = v; + value = std::move(v); break; } case 7: { @@ -2056,7 +2057,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::EmbeddedCurveAdd'"); } - value = v; + value = std::move(v); break; } case 8: { @@ -2067,7 +2068,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::Poseidon2Permutation'"); } - value = v; + value = std::move(v); break; } case 9: { @@ -2078,7 +2079,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::Sha256Compression'"); } - value = v; + value = std::move(v); break; } case 10: { @@ -2089,7 +2090,7 @@ struct BlackBoxOp { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxOp::ToRadix'"); } - value = v; + value = std::move(v); break; } default: @@ -2119,7 +2120,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::AES128Encrypt'"); } - value = v; + value = std::move(v); } else if (tag == "Blake2s") { Blake2s v; try { @@ -2129,7 +2130,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::Blake2s'"); } - value = v; + value = std::move(v); } else if (tag == "Blake3") { Blake3 v; try { @@ -2139,7 +2140,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::Blake3'"); } - value = v; + value = std::move(v); } else if (tag == "Keccakf1600") { Keccakf1600 v; try { @@ -2149,7 +2150,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::Keccakf1600'"); } - value = v; + value = std::move(v); } else if (tag == "EcdsaSecp256k1") { EcdsaSecp256k1 v; try { @@ -2159,7 +2160,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::EcdsaSecp256k1'"); } - value = v; + value = std::move(v); } else if (tag == "EcdsaSecp256r1") { EcdsaSecp256r1 v; try { @@ -2169,7 +2170,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::EcdsaSecp256r1'"); } - value = v; + value = std::move(v); } else if (tag == "MultiScalarMul") { MultiScalarMul v; try { @@ -2179,7 +2180,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::MultiScalarMul'"); } - value = v; + value = std::move(v); } else if (tag == "EmbeddedCurveAdd") { EmbeddedCurveAdd v; try { @@ -2189,7 +2190,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::EmbeddedCurveAdd'"); } - value = v; + value = std::move(v); } else if (tag == "Poseidon2Permutation") { Poseidon2Permutation v; try { @@ -2199,7 +2200,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::Poseidon2Permutation'"); } - value = v; + value = std::move(v); } else if (tag == "Sha256Compression") { Sha256Compression v; try { @@ -2209,7 +2210,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::Sha256Compression'"); } - value = v; + value = std::move(v); } else if (tag == "ToRadix") { ToRadix v; try { @@ -2219,7 +2220,7 @@ struct BlackBoxOp { throw_or_abort("error converting into enum variant 'BlackBoxOp::ToRadix'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BlackBoxOp' enum variant: " + tag); @@ -2423,7 +2424,7 @@ struct HeapValueType { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'HeapValueType::Simple'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -2434,7 +2435,7 @@ struct HeapValueType { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'HeapValueType::Array'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -2445,7 +2446,7 @@ struct HeapValueType { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'HeapValueType::Vector'"); } - value = v; + value = std::move(v); break; } default: @@ -2475,7 +2476,7 @@ struct HeapValueType { throw_or_abort("error converting into enum variant 'HeapValueType::Simple'"); } - value = v; + value = std::move(v); } else if (tag == "Array") { Array v; try { @@ -2485,7 +2486,7 @@ struct HeapValueType { throw_or_abort("error converting into enum variant 'HeapValueType::Array'"); } - value = v; + value = std::move(v); } else if (tag == "Vector") { Vector v; try { @@ -2495,7 +2496,7 @@ struct HeapValueType { throw_or_abort("error converting into enum variant 'HeapValueType::Vector'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'HeapValueType' enum variant: " + tag); @@ -2674,7 +2675,7 @@ struct ValueOrArray { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'ValueOrArray::MemoryAddress'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -2685,7 +2686,7 @@ struct ValueOrArray { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'ValueOrArray::HeapArray'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -2696,7 +2697,7 @@ struct ValueOrArray { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'ValueOrArray::HeapVector'"); } - value = v; + value = std::move(v); break; } default: @@ -2726,7 +2727,7 @@ struct ValueOrArray { throw_or_abort("error converting into enum variant 'ValueOrArray::MemoryAddress'"); } - value = v; + value = std::move(v); } else if (tag == "HeapArray") { HeapArray v; try { @@ -2736,7 +2737,7 @@ struct ValueOrArray { throw_or_abort("error converting into enum variant 'ValueOrArray::HeapArray'"); } - value = v; + value = std::move(v); } else if (tag == "HeapVector") { HeapVector v; try { @@ -2746,7 +2747,7 @@ struct ValueOrArray { throw_or_abort("error converting into enum variant 'ValueOrArray::HeapVector'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'ValueOrArray' enum variant: " + tag); @@ -3825,7 +3826,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::BinaryFieldOp'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -3836,7 +3837,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::BinaryIntOp'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -3847,7 +3848,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Not'"); } - value = v; + value = std::move(v); break; } case 3: { @@ -3858,7 +3859,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Cast'"); } - value = v; + value = std::move(v); break; } case 4: { @@ -3869,7 +3870,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::JumpIf'"); } - value = v; + value = std::move(v); break; } case 5: { @@ -3880,7 +3881,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Jump'"); } - value = v; + value = std::move(v); break; } case 6: { @@ -3891,7 +3892,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::CalldataCopy'"); } - value = v; + value = std::move(v); break; } case 7: { @@ -3902,7 +3903,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Call'"); } - value = v; + value = std::move(v); break; } case 8: { @@ -3913,7 +3914,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Const'"); } - value = v; + value = std::move(v); break; } case 9: { @@ -3924,12 +3925,12 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::IndirectConst'"); } - value = v; + value = std::move(v); break; } case 10: { Return v; - value = v; + value = std::move(v); break; } case 11: { @@ -3940,7 +3941,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::ForeignCall'"); } - value = v; + value = std::move(v); break; } case 12: { @@ -3951,7 +3952,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Mov'"); } - value = v; + value = std::move(v); break; } case 13: { @@ -3962,7 +3963,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::ConditionalMov'"); } - value = v; + value = std::move(v); break; } case 14: { @@ -3973,7 +3974,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Load'"); } - value = v; + value = std::move(v); break; } case 15: { @@ -3984,7 +3985,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Store'"); } - value = v; + value = std::move(v); break; } case 16: { @@ -3995,7 +3996,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::BlackBox'"); } - value = v; + value = std::move(v); break; } case 17: { @@ -4006,7 +4007,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Trap'"); } - value = v; + value = std::move(v); break; } case 18: { @@ -4017,7 +4018,7 @@ struct BrilligOpcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOpcode::Stop'"); } - value = v; + value = std::move(v); break; } default: @@ -4047,7 +4048,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::BinaryFieldOp'"); } - value = v; + value = std::move(v); } else if (tag == "BinaryIntOp") { BinaryIntOp v; try { @@ -4057,7 +4058,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::BinaryIntOp'"); } - value = v; + value = std::move(v); } else if (tag == "Not") { Not v; try { @@ -4067,7 +4068,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Not'"); } - value = v; + value = std::move(v); } else if (tag == "Cast") { Cast v; try { @@ -4077,7 +4078,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Cast'"); } - value = v; + value = std::move(v); } else if (tag == "JumpIf") { JumpIf v; try { @@ -4087,7 +4088,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::JumpIf'"); } - value = v; + value = std::move(v); } else if (tag == "Jump") { Jump v; try { @@ -4097,7 +4098,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Jump'"); } - value = v; + value = std::move(v); } else if (tag == "CalldataCopy") { CalldataCopy v; try { @@ -4107,7 +4108,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::CalldataCopy'"); } - value = v; + value = std::move(v); } else if (tag == "Call") { Call v; try { @@ -4117,7 +4118,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Call'"); } - value = v; + value = std::move(v); } else if (tag == "Const") { Const v; try { @@ -4127,7 +4128,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Const'"); } - value = v; + value = std::move(v); } else if (tag == "IndirectConst") { IndirectConst v; try { @@ -4137,10 +4138,10 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::IndirectConst'"); } - value = v; + value = std::move(v); } else if (tag == "Return") { Return v; - value = v; + value = std::move(v); } else if (tag == "ForeignCall") { ForeignCall v; try { @@ -4150,7 +4151,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::ForeignCall'"); } - value = v; + value = std::move(v); } else if (tag == "Mov") { Mov v; try { @@ -4160,7 +4161,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Mov'"); } - value = v; + value = std::move(v); } else if (tag == "ConditionalMov") { ConditionalMov v; try { @@ -4170,7 +4171,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::ConditionalMov'"); } - value = v; + value = std::move(v); } else if (tag == "Load") { Load v; try { @@ -4180,7 +4181,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Load'"); } - value = v; + value = std::move(v); } else if (tag == "Store") { Store v; try { @@ -4190,7 +4191,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Store'"); } - value = v; + value = std::move(v); } else if (tag == "BlackBox") { BlackBox v; try { @@ -4200,7 +4201,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::BlackBox'"); } - value = v; + value = std::move(v); } else if (tag == "Trap") { Trap v; try { @@ -4210,7 +4211,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Trap'"); } - value = v; + value = std::move(v); } else if (tag == "Stop") { Stop v; try { @@ -4220,7 +4221,7 @@ struct BrilligOpcode { throw_or_abort("error converting into enum variant 'BrilligOpcode::Stop'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BrilligOpcode' enum variant: " + tag); @@ -4347,7 +4348,7 @@ struct FunctionInput { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'FunctionInput::Constant'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -4358,7 +4359,7 @@ struct FunctionInput { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'FunctionInput::Witness'"); } - value = v; + value = std::move(v); break; } default: @@ -4388,7 +4389,7 @@ struct FunctionInput { throw_or_abort("error converting into enum variant 'FunctionInput::Constant'"); } - value = v; + value = std::move(v); } else if (tag == "Witness") { Witness v; try { @@ -4398,7 +4399,7 @@ struct FunctionInput { throw_or_abort("error converting into enum variant 'FunctionInput::Witness'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'FunctionInput' enum variant: " + tag); @@ -5366,7 +5367,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::AES128Encrypt'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -5377,7 +5378,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::AND'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -5388,7 +5389,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::XOR'"); } - value = v; + value = std::move(v); break; } case 3: { @@ -5399,7 +5400,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::RANGE'"); } - value = v; + value = std::move(v); break; } case 4: { @@ -5410,7 +5411,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Blake2s'"); } - value = v; + value = std::move(v); break; } case 5: { @@ -5421,7 +5422,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Blake3'"); } - value = v; + value = std::move(v); break; } case 6: { @@ -5432,7 +5433,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::EcdsaSecp256k1'"); } - value = v; + value = std::move(v); break; } case 7: { @@ -5443,7 +5444,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::EcdsaSecp256r1'"); } - value = v; + value = std::move(v); break; } case 8: { @@ -5454,7 +5455,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::MultiScalarMul'"); } - value = v; + value = std::move(v); break; } case 9: { @@ -5465,7 +5466,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::EmbeddedCurveAdd'"); } - value = v; + value = std::move(v); break; } case 10: { @@ -5476,7 +5477,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Keccakf1600'"); } - value = v; + value = std::move(v); break; } case 11: { @@ -5487,7 +5488,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::RecursiveAggregation'"); } - value = v; + value = std::move(v); break; } case 12: { @@ -5498,7 +5499,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Poseidon2Permutation'"); } - value = v; + value = std::move(v); break; } case 13: { @@ -5509,7 +5510,7 @@ struct BlackBoxFuncCall { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Sha256Compression'"); } - value = v; + value = std::move(v); break; } default: @@ -5539,7 +5540,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::AES128Encrypt'"); } - value = v; + value = std::move(v); } else if (tag == "AND") { AND v; try { @@ -5549,7 +5550,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::AND'"); } - value = v; + value = std::move(v); } else if (tag == "XOR") { XOR v; try { @@ -5559,7 +5560,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::XOR'"); } - value = v; + value = std::move(v); } else if (tag == "RANGE") { RANGE v; try { @@ -5569,7 +5570,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::RANGE'"); } - value = v; + value = std::move(v); } else if (tag == "Blake2s") { Blake2s v; try { @@ -5579,7 +5580,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Blake2s'"); } - value = v; + value = std::move(v); } else if (tag == "Blake3") { Blake3 v; try { @@ -5589,7 +5590,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Blake3'"); } - value = v; + value = std::move(v); } else if (tag == "EcdsaSecp256k1") { EcdsaSecp256k1 v; try { @@ -5599,7 +5600,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::EcdsaSecp256k1'"); } - value = v; + value = std::move(v); } else if (tag == "EcdsaSecp256r1") { EcdsaSecp256r1 v; try { @@ -5609,7 +5610,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::EcdsaSecp256r1'"); } - value = v; + value = std::move(v); } else if (tag == "MultiScalarMul") { MultiScalarMul v; try { @@ -5619,7 +5620,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::MultiScalarMul'"); } - value = v; + value = std::move(v); } else if (tag == "EmbeddedCurveAdd") { EmbeddedCurveAdd v; try { @@ -5629,7 +5630,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::EmbeddedCurveAdd'"); } - value = v; + value = std::move(v); } else if (tag == "Keccakf1600") { Keccakf1600 v; try { @@ -5639,7 +5640,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Keccakf1600'"); } - value = v; + value = std::move(v); } else if (tag == "RecursiveAggregation") { RecursiveAggregation v; try { @@ -5649,7 +5650,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::RecursiveAggregation'"); } - value = v; + value = std::move(v); } else if (tag == "Poseidon2Permutation") { Poseidon2Permutation v; try { @@ -5659,7 +5660,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Poseidon2Permutation'"); } - value = v; + value = std::move(v); } else if (tag == "Sha256Compression") { Sha256Compression v; try { @@ -5669,7 +5670,7 @@ struct BlackBoxFuncCall { throw_or_abort("error converting into enum variant 'BlackBoxFuncCall::Sha256Compression'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BlackBoxFuncCall' enum variant: " + tag); @@ -5790,7 +5791,7 @@ struct BlockType { switch (tag) { case 0: { Memory v; - value = v; + value = std::move(v); break; } case 1: { @@ -5801,12 +5802,12 @@ struct BlockType { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BlockType::CallData'"); } - value = v; + value = std::move(v); break; } case 2: { ReturnData v; - value = v; + value = std::move(v); break; } default: @@ -5829,7 +5830,7 @@ struct BlockType { } if (tag == "Memory") { Memory v; - value = v; + value = std::move(v); } else if (tag == "CallData") { CallData v; try { @@ -5839,10 +5840,10 @@ struct BlockType { throw_or_abort("error converting into enum variant 'BlockType::CallData'"); } - value = v; + value = std::move(v); } else if (tag == "ReturnData") { ReturnData v; - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BlockType' enum variant: " + tag); @@ -6028,7 +6029,7 @@ struct BrilligInputs { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligInputs::Single'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -6039,7 +6040,7 @@ struct BrilligInputs { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligInputs::Array'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -6050,7 +6051,7 @@ struct BrilligInputs { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligInputs::MemoryArray'"); } - value = v; + value = std::move(v); break; } default: @@ -6080,7 +6081,7 @@ struct BrilligInputs { throw_or_abort("error converting into enum variant 'BrilligInputs::Single'"); } - value = v; + value = std::move(v); } else if (tag == "Array") { Array v; try { @@ -6090,7 +6091,7 @@ struct BrilligInputs { throw_or_abort("error converting into enum variant 'BrilligInputs::Array'"); } - value = v; + value = std::move(v); } else if (tag == "MemoryArray") { MemoryArray v; try { @@ -6100,7 +6101,7 @@ struct BrilligInputs { throw_or_abort("error converting into enum variant 'BrilligInputs::MemoryArray'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BrilligInputs' enum variant: " + tag); @@ -6209,7 +6210,7 @@ struct BrilligOutputs { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOutputs::Simple'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -6220,7 +6221,7 @@ struct BrilligOutputs { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'BrilligOutputs::Array'"); } - value = v; + value = std::move(v); break; } default: @@ -6250,7 +6251,7 @@ struct BrilligOutputs { throw_or_abort("error converting into enum variant 'BrilligOutputs::Simple'"); } - value = v; + value = std::move(v); } else if (tag == "Array") { Array v; try { @@ -6260,7 +6261,7 @@ struct BrilligOutputs { throw_or_abort("error converting into enum variant 'BrilligOutputs::Array'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'BrilligOutputs' enum variant: " + tag); @@ -6667,7 +6668,7 @@ struct Opcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'Opcode::AssertZero'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -6678,7 +6679,7 @@ struct Opcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'Opcode::BlackBoxFuncCall'"); } - value = v; + value = std::move(v); break; } case 2: { @@ -6689,7 +6690,7 @@ struct Opcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'Opcode::MemoryOp'"); } - value = v; + value = std::move(v); break; } case 3: { @@ -6700,7 +6701,7 @@ struct Opcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'Opcode::MemoryInit'"); } - value = v; + value = std::move(v); break; } case 4: { @@ -6711,7 +6712,7 @@ struct Opcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'Opcode::BrilligCall'"); } - value = v; + value = std::move(v); break; } case 5: { @@ -6722,7 +6723,7 @@ struct Opcode { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'Opcode::Call'"); } - value = v; + value = std::move(v); break; } default: @@ -6752,7 +6753,7 @@ struct Opcode { throw_or_abort("error converting into enum variant 'Opcode::AssertZero'"); } - value = v; + value = std::move(v); } else if (tag == "BlackBoxFuncCall") { BlackBoxFuncCall v; try { @@ -6762,7 +6763,7 @@ struct Opcode { throw_or_abort("error converting into enum variant 'Opcode::BlackBoxFuncCall'"); } - value = v; + value = std::move(v); } else if (tag == "MemoryOp") { MemoryOp v; try { @@ -6772,7 +6773,7 @@ struct Opcode { throw_or_abort("error converting into enum variant 'Opcode::MemoryOp'"); } - value = v; + value = std::move(v); } else if (tag == "MemoryInit") { MemoryInit v; try { @@ -6782,7 +6783,7 @@ struct Opcode { throw_or_abort("error converting into enum variant 'Opcode::MemoryInit'"); } - value = v; + value = std::move(v); } else if (tag == "BrilligCall") { BrilligCall v; try { @@ -6792,7 +6793,7 @@ struct Opcode { throw_or_abort("error converting into enum variant 'Opcode::BrilligCall'"); } - value = v; + value = std::move(v); } else if (tag == "Call") { Call v; try { @@ -6802,7 +6803,7 @@ struct Opcode { throw_or_abort("error converting into enum variant 'Opcode::Call'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'Opcode' enum variant: " + tag); @@ -6911,7 +6912,7 @@ struct ExpressionOrMemory { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'ExpressionOrMemory::Expression'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -6922,7 +6923,7 @@ struct ExpressionOrMemory { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'ExpressionOrMemory::Memory'"); } - value = v; + value = std::move(v); break; } default: @@ -6952,7 +6953,7 @@ struct ExpressionOrMemory { throw_or_abort("error converting into enum variant 'ExpressionOrMemory::Expression'"); } - value = v; + value = std::move(v); } else if (tag == "Memory") { Memory v; try { @@ -6962,7 +6963,7 @@ struct ExpressionOrMemory { throw_or_abort("error converting into enum variant 'ExpressionOrMemory::Memory'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'ExpressionOrMemory' enum variant: " + tag); @@ -7149,7 +7150,7 @@ struct OpcodeLocation { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'OpcodeLocation::Acir'"); } - value = v; + value = std::move(v); break; } case 1: { @@ -7160,7 +7161,7 @@ struct OpcodeLocation { std::cerr << o << std::endl; throw_or_abort("error converting into enum variant 'OpcodeLocation::Brillig'"); } - value = v; + value = std::move(v); break; } default: @@ -7190,7 +7191,7 @@ struct OpcodeLocation { throw_or_abort("error converting into enum variant 'OpcodeLocation::Acir'"); } - value = v; + value = std::move(v); } else if (tag == "Brillig") { Brillig v; try { @@ -7200,7 +7201,7 @@ struct OpcodeLocation { throw_or_abort("error converting into enum variant 'OpcodeLocation::Brillig'"); } - value = v; + value = std::move(v); } else { std::cerr << o << std::endl; throw_or_abort("unknown 'OpcodeLocation' enum variant: " + tag); diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/serde.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/serde.hpp index 970d64b..a420c6d 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/serde.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/serde.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/witness_stack.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/witness_stack.hpp index 67b45cd..651ac00 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/witness_stack.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/serde/witness_stack.hpp @@ -56,22 +56,23 @@ struct Helpers { template static void conv_fld_from_array(msgpack::object_array const& array, std::string const& struct_name, - std::string const& field_name, + std::string_view field_name, T& field, uint32_t index) { if (index >= array.size) { - throw_or_abort("index out of bounds: " + struct_name + "::" + field_name + " at " + std::to_string(index)); + throw_or_abort("index out of bounds: " + struct_name + "::" + std::string(field_name) + " at " + + std::to_string(index)); } auto element = array.ptr[index]; if (element.type == msgpack::type::NIL) { - throw_or_abort("nil value for required field: " + struct_name + "::" + field_name); + throw_or_abort("nil value for required field: " + struct_name + "::" + std::string(field_name)); } try { element.convert(field); } catch (const msgpack::type_error&) { std::cerr << element << std::endl; - throw_or_abort("error converting into field " + struct_name + "::" + field_name); + throw_or_abort("error converting into field " + struct_name + "::" + std::string(field_name)); } } @@ -81,14 +82,14 @@ struct Helpers { template static void convert_or_throw(msgpack::object const& val, std::string const& struct_name, - std::string const& field_name, + std::string_view field_name, T& field) { try { val.convert(field); } catch (const msgpack::type_error&) { std::cerr << val << std::endl; - throw_or_abort("error converting into field " + struct_name + "::" + field_name); + throw_or_abort("error converting into field " + struct_name + "::" + std::string(field_name)); } } diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/asm_macros.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/asm_macros.hpp index b477941..3ebb5e9 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/asm_macros.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/asm_macros.hpp @@ -453,24 +453,53 @@ "cmovnoq %%r11, %%r15 \n\t" +/** + * One Montgomery reduction step (ADX) on a 4-limb accumulator (u0, u1, u2, u3): k = u0 * r_inv mod 2^64, then + * u = (u + k * p) / 2^64. The new top limb is written into u0's register (u0 is zero after adding lo(k * p0)), so + * the accumulator becomes (u1, u2, u3, u0). + * + * k is computed with imulq, which clobbers the flags: no carry may be pending when this step starts. Both chains + * restart from a zeroing xor. Bounds: u < 2^256 on entry, so u + k * p < 2^256 + 2^64 * p < 2^320; neither chain + * carries out of the top limb, both flags are 0 on exit, and the new u < 2^192 + p. + * Uses rdi, rcx as scratch. + **/ +#define SQR_REDUCE_STEP(u0, u1, u2, u3) \ + "movq " u0 ", %%rdx \n\t" /* rdx = u[0] */ \ + "imulq %[r_inv], %%rdx \n\t" /* rdx = k = u[0] * r_inv mod 2^64 */ \ + "xorl %%edi, %%edi \n\t" /* CF = OF = 0 */ \ + "mulxq %[modulus_0], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k * p[0] */ \ + "adcxq %%rdi, " u0 " \n\t" /* u[0] += lo(k*p0) -> 0 mod 2^64 */ \ + "adoxq %%rcx, " u1 " \n\t" /* u[1] += hi(k*p0) */ \ + "mulxq %[modulus_1], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k * p[1] */ \ + "adcxq %%rdi, " u1 " \n\t" /* u[1] += lo(k*p1) + CF */ \ + "adoxq %%rcx, " u2 " \n\t" /* u[2] += hi(k*p1) + OF */ \ + "mulxq %[modulus_2], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k * p[2] */ \ + "adcxq %%rdi, " u2 " \n\t" /* u[2] += lo(k*p2) + CF */ \ + "adoxq %%rcx, " u3 " \n\t" /* u[3] += hi(k*p2) + OF */ \ + "mulxq %[modulus_3], %%rdi, " u0 " \n\t" /* (rdi, top) = k * p[3]; top replaces the zeroed u[0] */ \ + "adcxq %%rdi, " u3 " \n\t" /* u[3] += lo(k*p3) + CF */ \ + "adoxq %[zero_reference], " u0 " \n\t" /* top += OF (OF -> 0) */ \ + "adcxq %[zero_reference], " u0 " \n\t" /* top += CF (CF -> 0) */ + /** * Montgomery squaring (ADX): computes a^2 * R^{-1} mod p, with output in [0, 2p). * * Uses the identity a^2 = 2 * sum_{i zeroed mod 2^{64} */ \ - /* r[i+1] += hi(ki*p0) + lo(ki*p1) */ \ - /* r[i+2] += hi(ki*p1) + lo(ki*p2) */ \ - /* r[i+3] += hi(ki*p2) + lo(ki*p3) */ \ - /* r[i+4] += hi(ki*p3) */ \ - /* ===================================================================================== */ \ \ - /* --- Reduction round 0: reduce r[0] (r8) -------------------------------------------- */ \ - /* Register map: r8=r[0] r9=r[1] r10=r[2] r11=r[3] r12=r[4] r13=r[5] r14=r[6] r15=r[7] */ \ - /* */ \ - /* Per-limb totals for k0*p: */ \ - /* r[0] += lo(k0*p0) -> zeroed mod 2^{64} */ \ - /* r[1] += hi(k0*p0) + lo(k0*p1) */ \ - /* r[2] += hi(k0*p1) + lo(k0*p2) */ \ - /* r[3] += hi(k0*p2) + lo(k0*p3) */ \ - /* r[4] += hi(k0*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[4], r[5], r[6], r[7], then r[1], r[2], r[3] */ \ - /* adox sequence (OF): r[0], r[1], r[2], r[3] */ \ - /* {CF=CF10 from Phase 3, OF=OF12=0} */ \ - "movq %%r8, %%rdx \n\t" /* rdx = r[0] */ \ - "mulxq %[r_inv], %%rdx, %%rdi \n\t" /* rdx = k0 = r[0] * r_inv */ \ - "mulxq %[modulus_0], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k0 * p[0] */ \ - "adoxq %%rdi, %%r8 \n\t" /* r[0] += lo(k0*p0) + OF12=0 -> 0 mod 2^64 {OF->OF1} */ \ - "mulxq %[modulus_3], %%r8, %%rdi \n\t" /* (r8, rdi) = k0 * p[3] */ \ - "adcxq %%rdi, %%r12 \n\t" /* r[4] += hi(k0*p3) + CF10 {CF->CF1} */ \ - "adoxq %%rcx, %%r9 \n\t" /* r[1] += hi(k0*p0) + OF1 {OF->OF2} */ \ - "adcxq %[zero_reference], %%r13 \n\t" /* r[5] += CF1 {CF->CF2} */ \ - "adcxq %[zero_reference], %%r14 \n\t" /* r[6] += CF2 {CF->CF3} */ \ - "mulxq %[modulus_1], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k0 * p[1] */ \ - "adcxq %[zero_reference], %%r15 \n\t" /* r[7] += CF3 {CF->CF4} */ \ - /* adcx flushes CF through r[5..7]; CF4=0 since r[7] < 2^{62}+2+1 < 2^{64}. */ \ - "adoxq %%rcx, %%r10 \n\t" /* r[2] += hi(k0*p1) + OF2 {OF->OF3} */ \ - "adcxq %%rdi, %%r9 \n\t" /* r[1] += lo(k0*p1) + CF4=0 {CF->CF5} (CF4=0: safe) */ \ - "adoxq %%r8, %%r11 \n\t" /* r[3] += lo(k0*p3) + OF3 {OF->OF4} */ \ - "mulxq %[modulus_2], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k0 * p[2] */ \ - "adcxq %%rdi, %%r10 \n\t" /* r[2] += lo(k0*p2) + CF5 {CF->CF6} */ \ - "adcxq %%rcx, %%r11 \n\t" /* r[3] += hi(k0*p2) + CF6 {CF->CF7} */ \ - \ - /* --- Reduction round 1: reduce r[1] (r9) -------------------------------------------- */ \ - /* Per-limb totals for k1*p: */ \ - /* r[1] += lo(k1*p0) -> zeroed mod 2^{64} */ \ - /* r[2] += hi(k1*p0) + lo(k1*p1) */ \ - /* r[3] += hi(k1*p1) + lo(k1*p2) */ \ - /* r[4] += hi(k1*p2) + lo(k1*p3) */ \ - /* r[5] += hi(k1*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[4], r[5], r[6], r[7], then r[1], r[2], r[3] */ \ - /* adox sequence (OF): r[4], r[5], r[6], r[7], then r[2], r[3] */ \ - /* {CF=CF7, OF=OF4} */ \ - "movq %%r9, %%rdx \n\t" /* rdx = r[1] */ \ - "mulxq %[r_inv], %%rdx, %%rdi \n\t" /* rdx = k1 = r[1] * r_inv */ \ - "mulxq %[modulus_2], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k1 * p[2] */ \ - "adoxq %%rcx, %%r12 \n\t" /* r[4] += hi(k1*p2) + OF4 {OF->OF5} */ \ - "mulxq %[modulus_3], %%r8, %%rcx \n\t" /* (r8, rcx) = k1 * p[3] */ \ - "adcxq %%r8, %%r12 \n\t" /* r[4] += lo(k1*p3) + CF7 {CF->CF8} */ \ - "adoxq %%rcx, %%r13 \n\t" /* r[5] += hi(k1*p3) + OF5 {OF->OF6} */ \ - "adcxq %[zero_reference], %%r13 \n\t" /* r[5] += CF8 {CF->CF9} */ \ - "adoxq %[zero_reference], %%r14 \n\t" /* r[6] += OF6 {OF->OF7} */ \ - "adcxq %[zero_reference], %%r14 \n\t" /* r[6] += CF9 {CF->CF10} */ \ - "adoxq %[zero_reference], %%r15 \n\t" /* r[7] += OF7 {OF->OF8} */ \ - "adcxq %[zero_reference], %%r15 \n\t" /* r[7] += CF10 {CF->CF11} */ \ - /* adcx/adox flush CF/OF through r[5..7]. CF11=0 and OF8=0 because each */ \ - /* flush adds at most 1 to r[5..7], and r[7] < 2^{62}+2+4 < 2^{64}. */ \ - "mulxq %[modulus_0], %%r8, %%rcx \n\t" /* (r8, rcx) = k1 * p[0] */ \ - "adcxq %%r8, %%r9 \n\t" /* r[1] += lo(k1*p0) + CF11=0 -> 0 mod 2^64 {CF->CF12} */ \ - "adoxq %%rcx, %%r10 \n\t" /* r[2] += hi(k1*p0) + OF8=0 {OF->OF9} (OF8=0: safe) */ \ - "mulxq %[modulus_1], %%r8, %%rcx \n\t" /* (r8, rcx) = k1 * p[1] */ \ - "adcxq %%r8, %%r10 \n\t" /* r[2] += lo(k1*p1) + CF12 {CF->CF13} */ \ - "adoxq %%rcx, %%r11 \n\t" /* r[3] += hi(k1*p1) + OF9 {OF->OF10} */ \ - "adcxq %%rdi, %%r11 \n\t" /* r[3] += lo(k1*p2) + CF13 {CF->CF14} */ \ - \ - /* --- Reduction round 2: reduce r[2] (r10) ------------------------------------------- */ \ - /* Per-limb totals for k2*p: */ \ - /* r[2] += lo(k2*p0) -> zeroed mod 2^{64} */ \ - /* r[3] += hi(k2*p0) + lo(k2*p1) */ \ - /* r[4] += hi(k2*p1) + lo(k2*p2) */ \ - /* r[5] += hi(k2*p2) + lo(k2*p3) */ \ - /* r[6] += hi(k2*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[4], r[5], r[6], r[7], then r[2], r[3] */ \ - /* adox sequence (OF): r[4], r[5], r[6], r[7], then r[3], r[4], r[5] */ \ - /* {CF=CF14, OF=OF10} */ \ - "movq %%r10, %%rdx \n\t" /* rdx = r[2] */ \ - "mulxq %[r_inv], %%rdx, %%rdi \n\t" /* rdx = k2 = r[2] * r_inv */ \ - "mulxq %[modulus_1], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k2 * p[1] */ \ - "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k2 * p[2] */ \ - "adoxq %%rcx, %%r12 \n\t" /* r[4] += hi(k2*p1) + OF10 {OF->OF11} */ \ - "adcxq %%r8, %%r12 \n\t" /* r[4] += lo(k2*p2) + CF14 {CF->CF15} */ \ - "adoxq %%r9, %%r13 \n\t" /* r[5] += hi(k2*p2) + OF11 {OF->OF12} */ \ - "mulxq %[modulus_3], %%r8, %%r9 \n\t" /* (r8, r9) = k2 * p[3] */ \ - "adcxq %%r8, %%r13 \n\t" /* r[5] += lo(k2*p3) + CF15 {CF->CF16} */ \ - "adoxq %%r9, %%r14 \n\t" /* r[6] += hi(k2*p3) + OF12 {OF->OF13} */ \ - "adcxq %[zero_reference], %%r14 \n\t" /* r[6] += CF16 {CF->CF17} */ \ - "adoxq %[zero_reference], %%r15 \n\t" /* r[7] += OF13 {OF->OF14} */ \ - "adcxq %[zero_reference], %%r15 \n\t" /* r[7] += CF17 {CF->CF18} */ \ - /* adcx/adox flush CF/OF through r[6..7]. CF18=0 and OF14=0 because each */ \ - /* flush adds at most 1, and r[7] < 2^{62}+2+4+2 < 2^{64}. */ \ - "mulxq %[modulus_0], %%r8, %%r9 \n\t" /* (r8, r9) = k2 * p[0] */ \ - "adcxq %%r8, %%r10 \n\t" /* r[2] += lo(k2*p0) + CF18=0 -> 0 mod 2^64 {CF->CF19} */ \ - "adoxq %%r9, %%r11 \n\t" /* r[3] += hi(k2*p0) + OF14=0 {OF->OF15} (OF14=0: safe) */ \ - "adcxq %%rdi, %%r11 \n\t" /* r[3] += lo(k2*p1) + CF19 {CF->CF20} */ \ - "adoxq %[zero_reference], %%r12 \n\t" /* r[4] += OF15 {OF->OF16} */ \ - "adoxq %[zero_reference], %%r13 \n\t" /* r[5] += OF16 {OF->OF17} */ \ - \ - /* --- Reduction round 3: reduce r[3] (r11) ------------------------------------------- */ \ - /* Per-limb totals for k3*p: */ \ - /* r[3] += lo(k3*p0) -> zeroed mod 2^{64} */ \ - /* r[4] += hi(k3*p0) + lo(k3*p1) */ \ - /* r[5] += hi(k3*p1) + lo(k3*p2) */ \ - /* r[6] += hi(k3*p2) + lo(k3*p3) */ \ - /* r[7] += hi(k3*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[4], r[5], r[6], r[7] */ \ - /* adox sequence (OF): r[3], r[4], r[5], r[6], r[7] */ \ - /* {CF=CF20, OF=OF17} */ \ - /* OF17=0: OF15 (from r[3] += hi(k2*p0)) flushes through r[4] and r[5] at lines above, */ \ - /* dissipating to 0 since neither limb is near 2^64. */ \ - "movq %%r11, %%rdx \n\t" /* rdx = r[3] */ \ - "mulxq %[r_inv], %%rdx, %%rdi \n\t" /* rdx = k3 = r[3] * r_inv */ \ - "mulxq %[modulus_0], %%rdi, %%rcx \n\t" /* (rdi, rcx) = k3 * p[0] */ \ - "mulxq %[modulus_1], %%r8, %%r9 \n\t" /* (r8, r9) = k3 * p[1] */ \ - "adoxq %%rdi, %%r11 \n\t" /* r[3] += lo(k3*p0) + OF17 -> 0 mod 2^64 {OF->OF18} */ \ - "adcxq %%r8, %%r12 \n\t" /* r[4] += lo(k3*p1) + CF20 {CF->CF21} */ \ - "adoxq %%rcx, %%r12 \n\t" /* r[4] += hi(k3*p0) + OF18 {OF->OF19} */ \ - "adcxq %%r9, %%r13 \n\t" /* r[5] += hi(k3*p1) + CF21 {CF->CF22} */ \ - "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k3 * p[2] */ \ - "mulxq %[modulus_3], %%r10, %%r11 \n\t" /* (r10, r11) = k3 * p[3] */ \ - "adoxq %%r8, %%r13 \n\t" /* r[5] += lo(k3*p2) + OF19 {OF->OF20} */ \ - "adcxq %%r10, %%r14 \n\t" /* r[6] += lo(k3*p3) + CF22 {CF->CF23} */ \ - "adoxq %%r9, %%r14 \n\t" /* r[6] += hi(k3*p2) + OF20 {OF->OF21} */ \ - "adcxq %%r11, %%r15 \n\t" /* r[7] += hi(k3*p3) + CF23 {CF->CF24} */ \ - /* Result = (a^2 + K*p)/R < 2p < 2^{255}, so r[7] < 2^{63}. */ \ - /* Since r[7] + hi(k3*p3) + CF23 < 2^{63} + 2^{62} + 1 < 2^{64}, CF24 = 0. */ \ - "adoxq %[zero_reference], %%r15 \n\t" /* r[7] += OF21 {OF->OF22} */ \ - /* r[7] < 2^{63} + 1 < 2^{64}, so OF22 = 0. Both terminal flags are zero. */ \ - \ - /* Output in (r12, r13, r14, r15) = (r[4], r[5], r[6], r[7]). */ \ - /* Since S < 2p < 2^{255}, the top limb r[7] < 2^{63}. Valid input for another SQR/MUL. */ + /* Post-phase 3: CF10 is still pending into r[4]; propagate it through T_hi = (r12, r13, r14, r15). */ \ + "adcxq %[zero_reference], %%r12 \n\t" /* r[4] += CF10 */ \ + "adcxq %[zero_reference], %%r13 \n\t" /* r[5] += CF */ \ + "adcxq %[zero_reference], %%r14 \n\t" /* r[6] += CF */ \ + "adcxq %[zero_reference], %%r15 \n\t" /* r[7] += CF (r[7] < 2^62 + 3: CF -> 0) */ \ + \ + /* ==================================================================================== */ \ + /* PHASE 4: U = (T_lo + K*p) / R with T_lo = (r8, r9, r10, r11); result = T_hi + U. */ \ + /* ==================================================================================== */ \ + SQR_REDUCE_STEP("%%r8", "%%r9", "%%r10", "%%r11") \ + SQR_REDUCE_STEP("%%r9", "%%r10", "%%r11", "%%r8") \ + SQR_REDUCE_STEP("%%r10", "%%r11", "%%r8", "%%r9") \ + SQR_REDUCE_STEP("%%r11", "%%r8", "%%r9", "%%r10") \ + /* U = (r8, r9, r10, r11) <= p. Add T_hi: the sum is < 2p < 2^{255}, no carry out. */ \ + "addq %%r8, %%r12 \n\t" /* r[0] = U[0] + T_hi[0] */ \ + "adcq %%r9, %%r13 \n\t" /* r[1] = U[1] + T_hi[1] + CF */ \ + "adcq %%r10, %%r14 \n\t" /* r[2] = U[2] + T_hi[2] + CF */ \ + "adcq %%r11, %%r15 \n\t" /* r[3] = U[3] + T_hi[3] + CF */ \ + \ + /* Output in (r12, r13, r14, r15). Top limb < 2^{63}: valid input for another SQR/MUL. */ + +/** + * One CIOS product row (ADX): (t0, t1, t2, t3, t4) = (t0, t1, t2, t3) + ai * b, where t4 is a fresh top limb. + * + * The low halves of ai * b[j] are added on the CF chain, the high halves on the OF chain. Both chains start from a + * zeroing xor, so the row depends only on the register values of t and not on flags produced by earlier rows. + * Bounds: the accumulator is < 2^256 on entry and b[3] < 2^63, so t4 = hi(ai * b[3]) + CF + OF < 2^63 + 2 and + * neither chain carries out of t4; both flags are 0 on exit. + * Uses r8, r9 as scratch and r11 as a zero register. + **/ +#define MUL_ROW(ai, b, t0, t1, t2, t3, t4) \ + "xorl %%r11d, %%r11d \n\t" /* r11 = 0; CF = OF = 0 */ \ + "movq " ai ", %%rdx \n\t" /* rdx = a[i] */ \ + "mulxq 0(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[i] * b[0] */ \ + "adcxq %%r8, " t0 " \n\t" /* t[0] += lo(ai*b0) */ \ + "adoxq %%r9, " t1 " \n\t" /* t[1] += hi(ai*b0) */ \ + "mulxq 8(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[i] * b[1] */ \ + "adcxq %%r8, " t1 " \n\t" /* t[1] += lo(ai*b1) + CF */ \ + "adoxq %%r9, " t2 " \n\t" /* t[2] += hi(ai*b1) + OF */ \ + "mulxq 16(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[i] * b[2] */ \ + "adcxq %%r8, " t2 " \n\t" /* t[2] += lo(ai*b2) + CF */ \ + "adoxq %%r9, " t3 " \n\t" /* t[3] += hi(ai*b2) + OF */ \ + "mulxq 24(" b "), %%r8, " t4 " \n\t" /* (r8, t[4]) = a[i] * b[3] */ \ + "adcxq %%r8, " t3 " \n\t" /* t[3] += lo(ai*b3) + CF */ \ + "adoxq %%r11, " t4 " \n\t" /* t[4] += OF (OF -> 0) */ \ + "adcxq %%r11, " t4 " \n\t" /* t[4] += CF (CF -> 0) */ + +/** + * One CIOS reduction step (ADX) on (t0, t1, t2, t3, t4): k = t0 * r_inv mod 2^64, t += k * p. Afterwards t0 = 0 and + * the caller drops it, so the accumulator becomes (t1, t2, t3, t4). + * + * k is computed with imulq (lower latency than mulxq and only the low half is needed). imulq clobbers the flags, so + * no carry may be pending when this step starts; the step then restarts both chains from a zeroing xor. + * Bounds: t < 2^256 + 2^64 * 2p on entry (see MUL), so t + k * p < 2^64 * (2^256 / 2^64 + 3p) < 2^320: neither chain + * carries out of t4 and both flags are 0 on exit. + * Uses r8, r9 as scratch and r11 as a zero register. + **/ +#define MUL_REDUCE_STEP(t0, t1, t2, t3, t4) \ + "movq " t0 ", %%rdx \n\t" /* rdx = t[0] */ \ + "imulq %[r_inv], %%rdx \n\t" /* rdx = k = t[0] * r_inv mod 2^64 */ \ + "xorl %%r11d, %%r11d \n\t" /* r11 = 0; CF = OF = 0 */ \ + "mulxq %[modulus_0], %%r8, %%r9 \n\t" /* (r8, r9) = k * p[0] */ \ + "adcxq %%r8, " t0 " \n\t" /* t[0] += lo(k*p0) -> 0 mod 2^64 */ \ + "adoxq %%r9, " t1 " \n\t" /* t[1] += hi(k*p0) */ \ + "mulxq %[modulus_1], %%r8, %%r9 \n\t" /* (r8, r9) = k * p[1] */ \ + "adcxq %%r8, " t1 " \n\t" /* t[1] += lo(k*p1) + CF */ \ + "adoxq %%r9, " t2 " \n\t" /* t[2] += hi(k*p1) + OF */ \ + "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k * p[2] */ \ + "adcxq %%r8, " t2 " \n\t" /* t[2] += lo(k*p2) + CF */ \ + "adoxq %%r9, " t3 " \n\t" /* t[3] += hi(k*p2) + OF */ \ + "mulxq %[modulus_3], %%r8, %%r9 \n\t" /* (r8, r9) = k * p[3] */ \ + "adcxq %%r8, " t3 " \n\t" /* t[3] += lo(k*p3) + CF */ \ + "adoxq %%r9, " t4 " \n\t" /* t[4] += hi(k*p3) + OF (OF -> 0) */ \ + "adcxq %%r11, " t4 " \n\t" /* t[4] += CF (CF -> 0) */ /** * Montgomery multiplication (ADX): computes a * b * R^{-1} mod p, with output in [0, 2p). * - * Same CIOS algorithm as the non-ADX variant (see above), but uses the ADX extension to run - * two independent carry chains simultaneously: + * CIOS: for i = 0..3, t += a[i] * b (MUL_ROW), then t += k_i * p with k_i = t[i] * r_inv mod 2^64 and the zeroed + * low limb is dropped (MUL_REDUCE_STEP). Uses the ADX extension to run two independent carry chains: * - adcxq reads/writes only CF (carry flag) * - adoxq reads/writes only OF (overflow flag) * - mulxq, movq preserve both CF and OF - * - xorq clears both CF and OF to 0 - * - * This eliminates the need for addq resets between cross-terms, enabling better ILP. - * The partial products are computed in a different order than non-ADX (for parallelism), - * but the per-limb totals are identical. + * - xorl reg, reg clears both CF and OF and is a zeroing idiom, so it breaks the dependency on earlier flags * - * Flag management: within each round, adcx and adox instructions are interleaved to add - * partial products into accumulator limbs. The instruction order is chosen for ILP, not - * algebraic order — understand the flag state instruction-by-instruction. Each flag is - * simply consumed by the next adcx (CF) or adox (OF); flags do not "belong to" limbs. + * Every row and reduction step ends with both chains flushed into its top limb (each top limb provably does not + * overflow), and the next one restarts them with a zeroing xor. The only dependencies between steps are therefore + * the limb registers themselves, and the serial path of each round is t[i] -> k_i -> k_i * p[0..1] -> t[i+1]. * - * Modulus assumption: p < 2^{254}, so p[3] < 2^{62}. All bit-width bounds below rely on this. - * - * At certain points the top limb is known to be < 2^64, so the outgoing flag = 0; - * this is annotated inline and is critical for correctness of the subsequent additions. + * The k_i are the unique digits of K < R with a*b + K*p = 0 mod R, so the result (a*b + K*p) / R is bit-identical + * to any other CIOS/SOS schedule. * - * Cross-round flag propagation: rounds are NOT flag-independent. Each round's terminal - * (CF, OF) are consumed by the first (adcxq, adoxq) of the next round. Between rounds, - * only movq and mulxq appear, which preserve flags. + * Modulus assumption: p < 2^{254}, so p[3] < 2^{62}; inputs a, b < 2p < 2^{255}. + * Bounds: before row i the accumulator is < 2p (4 limbs); after the row it is < 2p + 2^64 * 2p, after the reduction + * step (before the shift) < 2^64 * 2^256, so the 5-limb accumulator never overflows. The result is < 2p. * - * Notation in flag trace comments: {CF=n, OF=n} tracks the flag state entering each - * instruction. "CF_i" / "OF_i" denotes the i-th flag value produced within the current round. - * - * Result is stored in (%%r12, %%r13, %%r14, %%r15) for STORE_FIELD_ELEMENT. + * Register map (rotating): round 0 uses t = (r13, r14, r15, r10, r12); round i uses the same registers rotated by + * i, and the result ends up in (r12, r13, r14, r15) for STORE_FIELD_ELEMENT. **/ #define MUL(a1, a2, a3, a4, b) \ - /* ===================================================================================== */ \ - /* ROUND 0: accumulate a[0]*b, then reduce by k0*p. Shift out r[0]. */ \ - /* Register map: r13=r[0] r14=r[1] r15=r[2] r10=r[3] r12=r[4] */ \ - /* ===================================================================================== */ \ - "movq " a1 ", %%rdx \n\t" /* rdx = a[0] */ \ - "xorq %%r8, %%r8 \n\t" /* clear r8; sets CF=0, OF=0 */ \ - \ - /* --- a[0] * b: four independent multiplies ------------------------------------------- */ \ - "mulxq 0(" b "), %%r13, %%r14 \n\t" /* (r13, r14) = a[0] * b[0] -> (r[0], r[1]) */ \ - "mulxq 8(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[0] * b[1] */ \ - "mulxq 16(" b "), %%r15, %%r10 \n\t" /* (r15, r10) = a[0] * b[2] -> (r[2], r[3]) */ \ - "mulxq 24(" b "), %%rdi, %%r12 \n\t" /* (rdi, r12) = a[0] * b[3] -> r12 = r[4] = hi(a0*b3) */ \ - \ - /* --- k0 computation ------------------------------------------------------------------ */ \ - "movq %%r13, %%rdx \n\t" /* rdx = r[0] */ \ - "mulxq %[r_inv], %%rdx, %%r11 \n\t" /* rdx = k0 = r[0] * r_inv mod 2^64 */ \ - \ - /* --- Assemble a[0]*b cross-terms + k0*p reduction ------------------------------------ */ \ - /* */ \ - /* Per-limb totals for a[0]*b (from cross-terms added by adcxq/adoxq): */ \ - /* r[1] += lo(a0*b1), r[2] += hi(a0*b1), r[3] += lo(a0*b3) */ \ - /* (hi(a0*b0), lo(a0*b2), hi(a0*b2), hi(a0*b3) already in r[1..4] from mulxq outputs) */ \ - /* */ \ - /* Per-limb totals for k0*p: */ \ - /* r[0] += lo(k0*p0) -> zeroed mod 2^64 */ \ - /* r[1] += hi(k0*p0) + lo(k0*p1) */ \ - /* r[2] += hi(k0*p1) + lo(k0*p2) */ \ - /* r[3] += hi(k0*p2) + lo(k0*p3) */ \ - /* r[4] += hi(k0*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[1], r[2], r[3], r[4], then r[1], r[2], r[3] */ \ - /* adox sequence (OF): r[3], r[4], r[0], r[1], r[2] */ \ - /* */ \ - /* {CF=0, OF=0} */ \ - "adcxq %%r8, %%r14 \n\t" /* r[1] += lo(a0*b1) {CF->CF1} */ \ - "adoxq %%rdi, %%r10 \n\t" /* r[3] += lo(a0*b3) {OF->OF1} */ \ - "adcxq %%r9, %%r15 \n\t" /* r[2] += hi(a0*b1) + CF1 {CF->CF2} */ \ - \ - "mulxq %[modulus_3], %%rdi, %%r11 \n\t" /* (rdi, r11) = k0 * p[3] */ \ - "mulxq %[modulus_0], %%r8, %%r9 \n\t" /* (r8, r9) = k0 * p[0] */ \ - "adcxq %%rdi, %%r10 \n\t" /* r[3] += lo(k0*p3) + CF2 {CF->CF3} */ \ - "adoxq %%r11, %%r12 \n\t" /* r[4] += hi(k0*p3) + OF1 {OF->OF2} */ \ - /* r[4] = hi(a0*b3) + hi(k0*p3) + OF1 < 2^63 + 2^62 + 1 < 2^64 (b[3],p[3]<2^63) */ \ - /* OF2 = 0. */ \ - "adcxq %[zero_reference], %%r12 \n\t" /* r[4] += CF3 {CF->CF4} */ \ - /* r[4] < 2^63 + 2^62 + 2 < 2^64, so CF4 = 0 */ \ - "adoxq %%r8, %%r13 \n\t" /* r[0] += lo(k0*p0) + OF2=0 -> 0 mod 2^64 {OF->OF3} */ \ - "adcxq %%r9, %%r14 \n\t" /* r[1] += hi(k0*p0) + CF4=0 {CF->CF5} (CF4=0: safe) */ \ - "mulxq %[modulus_1], %%rdi, %%r11 \n\t" /* (rdi, r11) = k0 * p[1] */ \ - "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k0 * p[2] */ \ - "adoxq %%rdi, %%r14 \n\t" /* r[1] += lo(k0*p1) + OF3 {OF->OF4} */ \ - "adcxq %%r11, %%r15 \n\t" /* r[2] += hi(k0*p1) + CF5 {CF->CF6} */ \ - "adoxq %%r8, %%r15 \n\t" /* r[2] += lo(k0*p2) + OF4 {OF->OF5} */ \ - "adcxq %%r9, %%r10 \n\t" /* r[3] += hi(k0*p2) + CF6 {CF->CF7} */ \ - \ - /* Post-round 0: terminal flags (CF7, OF5) flow into round 1. */ \ - /* Top limb r[4] <= 2^63 + 2^62 + 2 < 2^64 (same as non-ADX). */ \ - \ - /* ===================================================================================== */ \ - /* ROUND 1: accumulate a[1]*b, then reduce by k1*p. Shift out r[1]. */ \ - /* Register map: r14=r[1] r15=r[2] r10=r[3] r12=r[4] r13=r[5] */ \ - /* */ \ - /* Per-limb totals for a[1]*b: */ \ - /* r[1] += lo(a1*b0), r[2] += hi(a1*b0) + lo(a1*b1) */ \ - /* r[3] += hi(a1*b1) + lo(a1*b2), r[4] += hi(a1*b2) + lo(a1*b3) */ \ - /* r[5] = hi(a1*b3) */ \ - /* */ \ - /* Per-limb totals for k1*p (same decomposition, shifted by one): */ \ - /* r[1] += lo(k1*p0) -> zeroed mod 2^64 */ \ - /* r[2] += hi(k1*p0) + lo(k1*p1) */ \ - /* r[3] += hi(k1*p1) + lo(k1*p2) */ \ - /* r[4] += hi(k1*p2) + lo(k1*p3) */ \ - /* r[5] += hi(k1*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[4], r[5], r[1], r[2], r[3], r[4], r[5], r[2], r[3] */ \ - /* adox sequence (OF): r[3], r[4], r[5], r[2], r[3], r[4], r[5], r[1], r[2] */ \ - /* ===================================================================================== */ \ - "movq " a2 ", %%rdx \n\t" /* rdx = a[1] */ \ - "mulxq 16(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[1] * b[2] */ \ - "mulxq 24(" b "), %%rdi, %%r13 \n\t" /* (rdi, r13) = a[1] * b[3] -> r13 = r[5] = hi(a1*b3) */ \ - /* {CF=CF7 from R0, OF=OF5 from R0} */ \ - "adoxq %%r8, %%r10 \n\t" /* r[3] += lo(a1*b2) + OF {OF->OF1} */ \ - "adcxq %%rdi, %%r12 \n\t" /* r[4] += lo(a1*b3) + CF {CF->CF1} */ \ - "adoxq %%r9, %%r12 \n\t" /* r[4] += hi(a1*b2) + OF1 {OF->OF2} */ \ - "adcxq %[zero_reference], %%r13 \n\t" /* r[5] += CF1 {CF->CF2} */ \ - /* r[5] = hi(a1*b3) + CF1 < 2^63 + 1 < 2^64, so CF2 = 0 */ \ - "adoxq %[zero_reference], %%r13 \n\t" /* r[5] += OF2 {OF->OF3} */ \ - /* r[5] < 2^63 + 2 < 2^64, so OF3 = 0. Wrap-around is safe. */ \ - "mulxq 0(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[1] * b[0] */ \ - "mulxq 8(" b "), %%rdi, %%r11 \n\t" /* (rdi, r11) = a[1] * b[1] */ \ - "adcxq %%r8, %%r14 \n\t" /* r[1] += lo(a1*b0) + CF2=0 {CF->CF3} (CF2=0: safe) */ \ - "adoxq %%r9, %%r15 \n\t" /* r[2] += hi(a1*b0) + OF3=0 {OF->OF4} (OF3=0: safe) */ \ - "adcxq %%rdi, %%r15 \n\t" /* r[2] += lo(a1*b1) + CF3 {CF->CF4} */ \ - "adoxq %%r11, %%r10 \n\t" /* r[3] += hi(a1*b1) + OF4 {OF->OF5} */ \ - \ - /* --- k1 * p reduction ---------------------------------------------------------------- */ \ - "movq %%r14, %%rdx \n\t" /* rdx = r[1] */ \ - "mulxq %[r_inv], %%rdx, %%r8 \n\t" /* rdx = k1 = r[1] * r_inv mod 2^64 */ \ - "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k1 * p[2] */ \ - "mulxq %[modulus_3], %%rdi, %%r11 \n\t" /* (rdi, r11) = k1 * p[3] */ \ - "adcxq %%r8, %%r10 \n\t" /* r[3] += lo(k1*p2) + CF4 {CF->CF5} */ \ - "adoxq %%r9, %%r12 \n\t" /* r[4] += hi(k1*p2) + OF5 {OF->OF6} */ \ - "adcxq %%rdi, %%r12 \n\t" /* r[4] += lo(k1*p3) + CF5 {CF->CF6} */ \ - "adoxq %%r11, %%r13 \n\t" /* r[5] += hi(k1*p3) + OF6 {OF->OF7} */ \ - "adcxq %[zero_reference], %%r13 \n\t" /* r[5] += CF6 {CF->CF7} */ \ - /* r[5] <= 2^63 + 2^62 + 4 < 2^64, so CF7 = 0. Wrap safe. */ \ - "mulxq %[modulus_0], %%r8, %%r9 \n\t" /* (r8, r9) = k1 * p[0] */ \ - "mulxq %[modulus_1], %%rdi, %%r11 \n\t" /* (rdi, r11) = k1 * p[1] */ \ - "adoxq %%r8, %%r14 \n\t" /* r[1] += lo(k1*p0) + OF7 {OF->OF8} -> 0 mod 2^64 */ \ - "adcxq %%rdi, %%r15 \n\t" /* r[2] += lo(k1*p1) + CF7=0 {CF->CF8} (CF7=0: safe) */ \ - "adoxq %%r9, %%r15 \n\t" /* r[2] += hi(k1*p0) + OF8 {OF->OF9} */ \ - "adcxq %%r11, %%r10 \n\t" /* r[3] += hi(k1*p1) + CF8 {CF->CF9} */ \ - \ - /* Post-round 1: terminal (CF9, OF9) flow into round 2. */ \ - /* Top limb r[5] <= 2^63 + 2^62 + 4 < 2^64. Invariant holds. */ \ - \ - /* ===================================================================================== */ \ - /* ROUND 2: accumulate a[2]*b, then reduce by k2*p. Shift out r[2]. */ \ - /* Register map: r15=r[2] r10=r[3] r12=r[4] r13=r[5] r14=r[6] */ \ - /* */ \ - /* Per-limb totals for a[2]*b: */ \ - /* r[2] += lo(a2*b0), r[3] += hi(a2*b0) + lo(a2*b1) */ \ - /* r[4] += hi(a2*b1) + lo(a2*b2), r[5] += hi(a2*b2) + lo(a2*b3) */ \ - /* r[6] = hi(a2*b3) */ \ - /* */ \ - /* Per-limb totals for k2*p: */ \ - /* r[2] += lo(k2*p0) -> zeroed mod 2^64 */ \ - /* r[3] += hi(k2*p0) + lo(k2*p1) */ \ - /* r[4] += hi(k2*p1) + lo(k2*p2) */ \ - /* r[5] += hi(k2*p2) + lo(k2*p3) */ \ - /* r[6] += hi(k2*p3) */ \ - /* */ \ - /* adcx sequence (CF): r[4], r[5], r[6], r[2], r[3], r[4], r[5], r[6], r[3] */ \ - /* adox sequence (OF): r[3], r[4], r[5], r[6], r[3], r[4], r[5], r[6], r[2] */ \ - /* ===================================================================================== */ \ - "movq " a3 ", %%rdx \n\t" /* rdx = a[2] */ \ - "mulxq 8(" b "), %%rdi, %%r11 \n\t" /* (rdi, r11) = a[2] * b[1] */ \ - "mulxq 16(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[2] * b[2] */ \ - /* {CF=CF9 from R1, OF=OF9 from R1} */ \ - "adoxq %%rdi, %%r10 \n\t" /* r[3] += lo(a2*b1) + OF {OF->OF1} */ \ - "adcxq %%r11, %%r12 \n\t" /* r[4] += hi(a2*b1) + CF {CF->CF1} */ \ - "adoxq %%r8, %%r12 \n\t" /* r[4] += lo(a2*b2) + OF1 {OF->OF2} */ \ - "adcxq %%r9, %%r13 \n\t" /* r[5] += hi(a2*b2) + CF1 {CF->CF2} */ \ - "mulxq 24(" b "), %%rdi, %%r14 \n\t" /* (rdi, r14) = a[2] * b[3] -> r14 = r[6] = hi(a2*b3) */ \ - "mulxq 0(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[2] * b[0] */ \ - "adoxq %%rdi, %%r13 \n\t" /* r[5] += lo(a2*b3) + OF2 {OF->OF3} */ \ - "adcxq %[zero_reference], %%r14 \n\t" /* r[6] += CF2 {CF->CF3} */ \ - /* r[6] = hi(a2*b3) + CF2 < 2^63 + 1 < 2^64, so CF3 = 0 */ \ - "adoxq %[zero_reference], %%r14 \n\t" /* r[6] += OF3 {OF->OF4} */ \ - /* r[6] < 2^63 + 2 < 2^64, so OF4 = 0. Wrap-around is safe. */ \ - "adcxq %%r8, %%r15 \n\t" /* r[2] += lo(a2*b0) + CF3=0 {CF->CF4} (CF3=0: safe) */ \ - "adoxq %%r9, %%r10 \n\t" /* r[3] += hi(a2*b0) + OF4=0 {OF->OF5} (OF4=0: safe) */ \ - \ - /* --- k2 * p reduction ---------------------------------------------------------------- */ \ - "movq %%r15, %%rdx \n\t" /* rdx = r[2] */ \ - "mulxq %[r_inv], %%rdx, %%r8 \n\t" /* rdx = k2 = r[2] * r_inv mod 2^64 */ \ - "mulxq %[modulus_1], %%rdi, %%r11 \n\t" /* (rdi, r11) = k2 * p[1] */ \ - "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k2 * p[2] */ \ - "adcxq %%rdi, %%r10 \n\t" /* r[3] += lo(k2*p1) + CF4 {CF->CF5} */ \ - "adoxq %%r11, %%r12 \n\t" /* r[4] += hi(k2*p1) + OF5 {OF->OF6} */ \ - "adcxq %%r8, %%r12 \n\t" /* r[4] += lo(k2*p2) + CF5 {CF->CF6} */ \ - "adoxq %%r9, %%r13 \n\t" /* r[5] += hi(k2*p2) + OF6 {OF->OF7} */ \ - "mulxq %[modulus_3], %%rdi, %%r11 \n\t" /* (rdi, r11) = k2 * p[3] */ \ - "mulxq %[modulus_0], %%r8, %%r9 \n\t" /* (r8, r9) = k2 * p[0] */ \ - "adcxq %%rdi, %%r13 \n\t" /* r[5] += lo(k2*p3) + CF6 {CF->CF7} */ \ - "adoxq %%r11, %%r14 \n\t" /* r[6] += hi(k2*p3) + OF7 {OF->OF8} */ \ - "adcxq %[zero_reference], %%r14 \n\t" /* r[6] += CF7 {CF->CF8} */ \ - /* r[6] <= 2^63 + 2^62 + 4 < 2^64, so CF8 = 0. Wrap safe. */ \ - "adoxq %%r8, %%r15 \n\t" /* r[2] += lo(k2*p0) + OF8 {OF->OF9} -> 0 mod 2^64 */ \ - "adcxq %%r9, %%r10 \n\t" /* r[3] += hi(k2*p0) + CF8=0 {CF->CF9} (CF8=0: safe) */ \ - \ - /* Post-round 2: terminal (CF9, OF9) flow into round 3. */ \ - /* Top limb r[6] <= 2^63 + 2^62 + 4 < 2^64. Invariant holds. */ \ - \ - /* ===================================================================================== */ \ - /* ROUND 3: accumulate a[3]*b, then reduce by k3*p. Shift out r[3]. */ \ - /* Register map: r10=r[3] r12=r[4] r13=r[5] r14=r[6] r15=r[7] */ \ - /* Tighter bound: a[3] < 2^63 (not 2^64), so hi(a3*b3) < 2^62. */ \ - /* ===================================================================================== */ \ - "movq " a4 ", %%rdx \n\t" /* rdx = a[3] (< 2^63) */ \ - "mulxq 0(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[3] * b[0] */ \ - "mulxq 8(" b "), %%rdi, %%r11 \n\t" /* (rdi, r11) = a[3] * b[1] */ \ - /* {CF=CF9 from R2, OF=OF9 from R2} */ \ - "adoxq %%r8, %%r10 \n\t" /* r[3] += lo(a3*b0) + OF {OF->OF1} */ \ - "adcxq %%r9, %%r12 \n\t" /* r[4] += hi(a3*b0) + CF {CF->CF1} */ \ - "adoxq %%rdi, %%r12 \n\t" /* r[4] += lo(a3*b1) + OF1 {OF->OF2} */ \ - "adcxq %%r11, %%r13 \n\t" /* r[5] += hi(a3*b1) + CF1 {CF->CF2} */ \ - \ - "mulxq 16(" b "), %%r8, %%r9 \n\t" /* (r8, r9) = a[3] * b[2] */ \ - "mulxq 24(" b "), %%rdi, %%r15 \n\t" /* (rdi, r15) = a[3] * b[3] -> r15 = r[7] = hi(a3*b3) */ \ - "adoxq %%r8, %%r13 \n\t" /* r[5] += lo(a3*b2) + OF2 {OF->OF3} */ \ - "adcxq %%r9, %%r14 \n\t" /* r[6] += hi(a3*b2) + CF2 {CF->CF3} */ \ - "adoxq %%rdi, %%r14 \n\t" /* r[6] += lo(a3*b3) + OF3 {OF->OF4} */ \ - "adcxq %[zero_reference], %%r15 \n\t" /* r[7] += CF3 {CF->CF4} */ \ - /* r[7] = hi(a3*b3) + CF3 < 2^62 + 1 < 2^64, so CF4 = 0 */ \ - "adoxq %[zero_reference], %%r15 \n\t" /* r[7] += OF4 {OF->OF5} */ \ - /* r[7] < 2^62 + 2 < 2^64, so OF5 = 0. Wrap-around is safe. */ \ - \ - /* --- k3 * p reduction ---------------------------------------------------------------- */ \ - /* */ \ - /* Per-limb totals for k3*p: */ \ - /* r[3] += lo(k3*p0) -> zeroed mod 2^64 */ \ - /* r[4] += hi(k3*p0) + lo(k3*p1) */ \ - /* r[5] += hi(k3*p1) + lo(k3*p2) */ \ - /* r[6] += hi(k3*p2) + lo(k3*p3) */ \ - /* r[7] += hi(k3*p3) */ \ - "movq %%r10, %%rdx \n\t" /* rdx = r[3] */ \ - "mulxq %[r_inv], %%rdx, %%r8 \n\t" /* rdx = k3 = r[3] * r_inv mod 2^64 */ \ - "mulxq %[modulus_0], %%r8, %%r9 \n\t" /* (r8, r9) = k3 * p[0] */ \ - "mulxq %[modulus_1], %%rdi, %%r11 \n\t" /* (rdi, r11) = k3 * p[1] */ \ - /* {CF=CF4=0, OF=OF5=0} (both zero — see bounds on r[7] above) */ \ - "adoxq %%r8, %%r10 \n\t" /* r[3] += lo(k3*p0) + OF5=0 {OF->OF6} -> 0 mod 2^64 */ \ - "adcxq %%r9, %%r12 \n\t" /* r[4] += hi(k3*p0) + CF4=0 {CF->CF5} */ \ - "adoxq %%rdi, %%r12 \n\t" /* r[4] += lo(k3*p1) + OF6 {OF->OF7} */ \ - "adcxq %%r11, %%r13 \n\t" /* r[5] += hi(k3*p1) + CF5 {CF->CF6} */ \ - \ - "mulxq %[modulus_2], %%r8, %%r9 \n\t" /* (r8, r9) = k3 * p[2] */ \ - "mulxq %[modulus_3], %%rdi, %%rdx \n\t" /* (rdi, rdx) = k3 * p[3] (overwrites rdx; last mulxq) */ \ - "adoxq %%r8, %%r13 \n\t" /* r[5] += lo(k3*p2) + OF7 {OF->OF8} */ \ - "adcxq %%r9, %%r14 \n\t" /* r[6] += hi(k3*p2) + CF6 {CF->CF7} */ \ - "adoxq %%rdi, %%r14 \n\t" /* r[6] += lo(k3*p3) + OF8 {OF->OF9} */ \ - "adcxq %%rdx, %%r15 \n\t" /* r[7] += hi(k3*p3) + CF7 {CF->CF8} */ \ - /* r[7] < (2^62 + 2) + 2^62 + 1 = 2^63 + 3 < 2^64, so CF8 = 0 (p[3]<2^62) */ \ - "adoxq %[zero_reference], %%r15 \n\t" /* r[7] += OF9 {OF->OF10} */ \ - /* r[7] < 2^63 + 4 < 2^64, so OF10 = 0. Terminal flags are both 0. */ \ - \ - /* Output in (r12, r13, r14, r15) = (r[4], r[5], r[6], r[7]). */ \ - /* Since S < 2p < 2^255, the top limb r[7] < 2^63. Valid input for another MUL. */ + /* Round 0, row: (r13, r14, r15, r10, r12) = a[0] * b. A single carry chain suffices. */ \ + "xorl %%r11d, %%r11d \n\t" /* r11 = 0; CF = OF = 0 */ \ + "movq " a1 ", %%rdx \n\t" /* rdx = a[0] */ \ + "mulxq 0(" b "), %%r13, %%r14 \n\t" /* (t[0], t[1]) = a[0] * b[0] */ \ + "mulxq 8(" b "), %%r8, %%r15 \n\t" /* (r8, t[2]) = a[0] * b[1] */ \ + "adcxq %%r8, %%r14 \n\t" /* t[1] += lo(a0*b1) */ \ + "mulxq 16(" b "), %%r8, %%r10 \n\t" /* (r8, t[3]) = a[0] * b[2] */ \ + "adcxq %%r8, %%r15 \n\t" /* t[2] += lo(a0*b2) + CF */ \ + "mulxq 24(" b "), %%r8, %%r12 \n\t" /* (r8, t[4]) = a[0] * b[3] */ \ + "adcxq %%r8, %%r10 \n\t" /* t[3] += lo(a0*b3) + CF */ \ + "adcxq %%r11, %%r12 \n\t" /* t[4] += CF (t[4] < 2^63 + 1: CF -> 0) */ \ + MUL_REDUCE_STEP("%%r13", "%%r14", "%%r15", "%%r10", "%%r12") \ + /* Round 1: t = (r14, r15, r10, r12, r13) */ \ + MUL_ROW(a2, b, "%%r14", "%%r15", "%%r10", "%%r12", "%%r13") \ + MUL_REDUCE_STEP("%%r14", "%%r15", "%%r10", "%%r12", "%%r13") \ + /* Round 2: t = (r15, r10, r12, r13, r14) */ \ + MUL_ROW(a3, b, "%%r15", "%%r10", "%%r12", "%%r13", "%%r14") \ + MUL_REDUCE_STEP("%%r15", "%%r10", "%%r12", "%%r13", "%%r14") \ + /* Round 3: t = (r10, r12, r13, r14, r15) */ \ + MUL_ROW(a4, b, "%%r10", "%%r12", "%%r13", "%%r14", "%%r15") \ + MUL_REDUCE_STEP("%%r10", "%%r12", "%%r13", "%%r14", "%%r15") \ + \ + /* Output in (r12, r13, r14, r15) < 2p < 2^{255}: valid input for another MUL. */ #endif 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 diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/field_declarations.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/field_declarations.hpp index 7068879..b1412f6 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/field_declarations.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/field_declarations.hpp @@ -275,8 +275,18 @@ template struct alignas(32) field { } static constexpr field zero() { return field(0, 0, 0, 0); } - static constexpr field neg_one() { return -field(1); } - static constexpr field one() { return field(1); } + // The constexpr locals force the Montgomery conversion to happen at compile time; returning field(1) directly + // performs it at runtime on every call. + static constexpr field neg_one() + { + constexpr field result = -field(1); + return result; + } + static constexpr field one() + { + constexpr field result(1); + return result; + } static constexpr field coset_generator() { diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.hpp new file mode 100644 index 0000000..1aa9f87 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.hpp @@ -0,0 +1,566 @@ +// AVX-512 IFMA kernels for prover hot loops over BN254-sized prime fields (8 elements per 512-bit register). +// +// x86-64 only and runtime-dispatched: the build targets a baseline ISA, so every function that touches 512-bit +// registers carries a `target` attribute and is only entered after `available()` confirmed the CPU (and OS) support +// it. WASM and non-x86 builds compile none of this; callers keep their scalar loop as the fallback. +// +// Every kernel returns the same field values as the scalar code it replaces (exact arithmetic). Computed outputs are +// fully reduced into [0, p), values copied through unchanged keep their input form; both are valid representatives +// for bb's coarse [0, 2p) form. + +#pragma once + +#if defined(__x86_64__) && !defined(__wasm__) && (defined(__clang__) || defined(__GNUC__)) +#define BB_FIELD_IFMA 1 +#endif + +#ifdef BB_FIELD_IFMA + +#include "barretenberg/common/cpu_supports.hpp" + +#include + +#include +#include +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays, cppcoreguidelines-pro-bounds-constant-array-index) +// Clang 18-21 models 512-bit EVEX separately; Zig's baseline target can disable it explicitly. +// Other Clang versions and GCC retain their original target feature spelling. +#if defined(__clang__) && __clang_major__ >= 18 && __clang_major__ <= 21 +#define BB_FIELD_IFMA_TARGET __attribute__((target("avx512f,avx512ifma,avx512vl,avx512dq,avx512bw,evex512"))) +#else +#define BB_FIELD_IFMA_TARGET __attribute__((target("avx512f,avx512ifma,avx512vl,avx512dq,avx512bw"))) +#endif +#define BB_FIELD_IFMA_INLINE BB_FIELD_IFMA_TARGET __attribute__((always_inline)) inline + +namespace bb::field_ifma { + +/** + * @brief True when the CPU and OS support AVX-512F + IFMA. `BB_FIELD_NO_IFMA` (any value) forces false, which keeps + * the scalar loops reachable on IFMA hardware for A/B runs and tests. + */ +inline bool available() noexcept +{ + static const bool is_available = [] { + if (std::getenv("BB_FIELD_NO_IFMA") != nullptr) { + return false; + } + return bb::cpu_supports_avx512_ifma(); + }(); + return is_available; +} + +/** + * @brief Field elements as 5 limbs of 52 bits, 8 lanes per register. + * + * @details Montgomery multiplication uses R = 2^256, i.e. bb's own Montgomery domain: four 52-bit reduction steps and + * one 48-bit step, so values move between bb and the kernels by re-limbing only. Values stay loosely reduced; + * the bounds quoted below are in units of p and rely on p < 0.19 * 2^256, which gives + * mont_mul(a, b) < 0.19 * a * b / p + p. + */ +template struct Consts { + static constexpr uint64_t M52 = (uint64_t{ 1 } << 52) - 1; + static constexpr std::array MOD{ + Params::modulus_0, Params::modulus_1, Params::modulus_2, Params::modulus_3 + }; + + static constexpr std::array to52(const std::array& a) + { + return { a[0] & M52, + ((a[0] >> 52) | (a[1] << 12)) & M52, + ((a[1] >> 40) | (a[2] << 24)) & M52, + ((a[2] >> 28) | (a[3] << 36)) & M52, + a[3] >> 16 }; + } + // k * p in normalised 52-bit limbs (k small). + static constexpr std::array times(uint64_t k) + { + const std::array p = to52(MOD); + std::array r{}; + uint64_t carry = 0; + for (size_t i = 0; i < 5; ++i) { + const uint64_t v = (p[i] * k) + carry; + r[i] = (i < 4) ? (v & M52) : v; + carry = v >> 52; + } + return r; + } + static constexpr std::array P = times(1); + static constexpr std::array P2 = times(2); + static constexpr std::array P4 = times(4); + // -p^-1 mod 2^52. + static constexpr uint64_t PINV = Params::r_inv & M52; + // floor(2^52 / (floor(p / 2^208) + 1)): quotient estimate for `canonical`. + static constexpr uint64_t QK = (uint64_t{ 1 } << 52) / (P[4] + 1); + + // The bound analysis needs p < 0.19 * 2^256 (0.19 * 2^64 = 0x30a3d70a3d70a3d7). + static constexpr bool supported = Params::modulus_3 < 0x30a3d70a3d70a3d7ULL; +}; + +struct V5 { + __m512i l[5]; +}; + +BB_FIELD_IFMA_INLINE __m512i bcast(uint64_t v) +{ + return _mm512_set1_epi64(static_cast(v)); +} + +/** + * @brief r = a * b / 2^256 (mod p), r < 0.19 * a * b / p + p. Limbs of a and b must be < 2^52. + */ +template BB_FIELD_IFMA_INLINE V5 mont_mul(const V5& a, const V5& b) +{ + using C = Consts; + const __m512i z = _mm512_setzero_si512(); + const __m512i m52 = bcast(C::M52); + const __m512i pinv = bcast(C::PINV); + __m512i p[5]; + for (size_t j = 0; j < 5; ++j) { + p[j] = bcast(C::P[j]); + } + __m512i t[10]; + for (auto& ti : t) { + ti = z; + } + for (size_t i = 0; i < 5; ++i) { + for (size_t j = 0; j < 5; ++j) { + t[i + j] = _mm512_madd52lo_epu64(t[i + j], a.l[i], b.l[j]); + t[i + j + 1] = _mm512_madd52hi_epu64(t[i + j + 1], a.l[i], b.l[j]); + } + } + // Four 52-bit Montgomery steps: zero the low 52 bits of t[i] and carry them into t[i + 1]. + for (size_t i = 0; i < 4; ++i) { + const __m512i m = _mm512_madd52lo_epu64(z, t[i], pinv); + for (size_t j = 0; j < 5; ++j) { + t[i + j] = _mm512_madd52lo_epu64(t[i + j], m, p[j]); + t[i + j + 1] = _mm512_madd52hi_epu64(t[i + j + 1], m, p[j]); + } + t[i + 1] = _mm512_add_epi64(t[i + 1], _mm512_srli_epi64(t[i], 52)); + } + // One 48-bit step brings the total shift to 4 * 52 + 48 = 256. + { + const __m512i m = _mm512_and_si512(_mm512_madd52lo_epu64(z, t[4], pinv), bcast((uint64_t{ 1 } << 48) - 1)); + for (size_t j = 0; j < 5; ++j) { + t[4 + j] = _mm512_madd52lo_epu64(t[4 + j], m, p[j]); + t[5 + j] = _mm512_madd52hi_epu64(t[5 + j], m, p[j]); + } + } + for (size_t i = 4; i < 9; ++i) { + t[i + 1] = _mm512_add_epi64(t[i + 1], _mm512_srli_epi64(t[i], 52)); + t[i] = _mm512_and_si512(t[i], m52); + } + V5 r; + for (size_t j = 0; j < 4; ++j) { + r.l[j] = + _mm512_or_si512(_mm512_srli_epi64(t[4 + j], 48), _mm512_and_si512(_mm512_slli_epi64(t[5 + j], 4), m52)); + } + r.l[4] = _mm512_or_si512(_mm512_srli_epi64(t[8], 48), _mm512_slli_epi64(t[9], 4)); + return r; +} + +// Propagate signed per-limb carries so limbs 0..3 are in [0, 2^52). The represented value must be non-negative. +BB_FIELD_IFMA_INLINE void normalise(V5& r) +{ + const __m512i m52 = bcast((uint64_t{ 1 } << 52) - 1); + for (size_t i = 0; i < 4; ++i) { + r.l[i + 1] = _mm512_add_epi64(r.l[i + 1], _mm512_srai_epi64(r.l[i], 52)); + r.l[i] = _mm512_and_si512(r.l[i], m52); + } +} + +BB_FIELD_IFMA_INLINE V5 add(const V5& a, const V5& b) +{ + V5 r; + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_add_epi64(a.l[i], b.l[i]); + } + normalise(r); + return r; +} + +// a + k - b, with k a constant multiple of p (as normalised limbs) that is at least b. +BB_FIELD_IFMA_INLINE V5 sub_plus(const V5& a, const V5& b, const std::array& k) +{ + V5 r; + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_sub_epi64(_mm512_add_epi64(a.l[i], bcast(k[i])), b.l[i]); + } + normalise(r); + return r; +} + +// a + k - b - c, with k a constant multiple of p (as normalised limbs) that is at least b + c. +BB_FIELD_IFMA_INLINE V5 sub2_plus(const V5& a, const V5& b, const V5& c, const std::array& k) +{ + V5 r; + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_sub_epi64(_mm512_sub_epi64(_mm512_add_epi64(a.l[i], bcast(k[i])), b.l[i]), c.l[i]); + } + normalise(r); + return r; +} + +/** + * @brief Fully reduce v (normalised, v < 9p) into [0, p). + * + * @details q = floor(v4 * QK / 2^52), with v4 = floor(v / 2^208), never exceeds floor(v / p) and falls short of it by + * at most one for v < 9p, so v - q * p lies in [0, 2p); one conditional subtraction finishes. + */ +template BB_FIELD_IFMA_INLINE V5 canonical(const V5& v) +{ + using C = Consts; + const __m512i z = _mm512_setzero_si512(); + const __m512i q = _mm512_madd52hi_epu64(z, v.l[4], bcast(C::QK)); + V5 r; + __m512i carry_hi = z; + for (size_t i = 0; i < 5; ++i) { + const __m512i pi = bcast(C::P[i]); + const __m512i lo = _mm512_madd52lo_epu64(z, q, pi); + r.l[i] = _mm512_sub_epi64(_mm512_sub_epi64(v.l[i], lo), carry_hi); + carry_hi = _mm512_madd52hi_epu64(z, q, pi); + } + normalise(r); + V5 t; + for (size_t i = 0; i < 5; ++i) { + t.l[i] = _mm512_sub_epi64(r.l[i], bcast(C::P[i])); + } + normalise(t); + const __mmask8 negative = _mm512_movepi64_mask(t.l[4]); + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_mask_blend_epi64(negative, t.l[i], r.l[i]); + } + return r; +} + +// Four 64-bit limb columns (lane j of column i = limb i of one element) to 52-bit limbs. The value must be < 2^256. +BB_FIELD_IFMA_INLINE V5 from_columns(__m512i a0, __m512i a1, __m512i a2, __m512i a3) +{ + const __m512i m52 = bcast((uint64_t{ 1 } << 52) - 1); + V5 r; + r.l[0] = _mm512_and_si512(a0, m52); + r.l[1] = _mm512_and_si512(_mm512_or_si512(_mm512_srli_epi64(a0, 52), _mm512_slli_epi64(a1, 12)), m52); + r.l[2] = _mm512_and_si512(_mm512_or_si512(_mm512_srli_epi64(a1, 40), _mm512_slli_epi64(a2, 24)), m52); + r.l[3] = _mm512_and_si512(_mm512_or_si512(_mm512_srli_epi64(a2, 28), _mm512_slli_epi64(a3, 36)), m52); + r.l[4] = _mm512_srli_epi64(a3, 16); + return r; +} + +/** + * @brief Transpose four registers holding eight consecutive 4-limb elements (z_k = elements 2k, 2k + 1) into limb + * columns and re-limb them. Lane order is e0, e2, e1, e3, e4, e6, e5, e7; `store8` undoes it. + */ +BB_FIELD_IFMA_INLINE V5 transpose_in(__m512i z0, __m512i z1, __m512i z2, __m512i z3) +{ + const __m512i t0 = _mm512_unpacklo_epi64(z0, z1); // e0l0 e2l0 e0l2 e2l2 | e1l0 e3l0 e1l2 e3l2 + const __m512i t1 = _mm512_unpackhi_epi64(z0, z1); // limbs 1 and 3 of e0..e3 + const __m512i t2 = _mm512_unpacklo_epi64(z2, z3); + const __m512i t3 = _mm512_unpackhi_epi64(z2, z3); + return from_columns(_mm512_shuffle_i64x2(t0, t2, 0x88), + _mm512_shuffle_i64x2(t1, t3, 0x88), + _mm512_shuffle_i64x2(t0, t2, 0xDD), + _mm512_shuffle_i64x2(t1, t3, 0xDD)); +} + +// Load eight consecutive elements (32-byte 4-limb layout) starting at `src`. +BB_FIELD_IFMA_INLINE V5 load8(const uint64_t* src) +{ + return transpose_in(_mm512_loadu_si512(src), + _mm512_loadu_si512(src + 8), + _mm512_loadu_si512(src + 16), + _mm512_loadu_si512(src + 24)); +} + +/** + * @brief Load the eight even-indexed and the eight odd-indexed elements of the sixteen consecutive elements at `src`, + * both in `load8`'s lane order. + */ +BB_FIELD_IFMA_INLINE void load8_even_odd(const uint64_t* src, V5& even, V5& odd) +{ + __m512i z[8]; + for (size_t i = 0; i < 8; ++i) { + z[i] = _mm512_loadu_si512(src + (8 * i)); + } + // z[i] = elements 2i (even) and 2i + 1 (odd); regroup 256-bit halves. + even = transpose_in(_mm512_shuffle_i64x2(z[0], z[1], 0x44), + _mm512_shuffle_i64x2(z[2], z[3], 0x44), + _mm512_shuffle_i64x2(z[4], z[5], 0x44), + _mm512_shuffle_i64x2(z[6], z[7], 0x44)); + odd = transpose_in(_mm512_shuffle_i64x2(z[0], z[1], 0xEE), + _mm512_shuffle_i64x2(z[2], z[3], 0xEE), + _mm512_shuffle_i64x2(z[4], z[5], 0xEE), + _mm512_shuffle_i64x2(z[6], z[7], 0xEE)); +} + +// 52-bit limbs (normalised, value below 2^256) back to four 64-bit limb columns. +BB_FIELD_IFMA_INLINE void to_columns(const V5& v, __m512i& c0, __m512i& c1, __m512i& c2, __m512i& c3) +{ + c0 = _mm512_or_si512(v.l[0], _mm512_slli_epi64(v.l[1], 52)); + c1 = _mm512_or_si512(_mm512_srli_epi64(v.l[1], 12), _mm512_slli_epi64(v.l[2], 40)); + c2 = _mm512_or_si512(_mm512_srli_epi64(v.l[2], 24), _mm512_slli_epi64(v.l[3], 28)); + c3 = _mm512_or_si512(_mm512_srli_epi64(v.l[3], 36), _mm512_slli_epi64(v.l[4], 16)); +} + +// Inverse of `transpose_in` for a value below 2^256: z_k = elements 2k, 2k + 1 in the 4-limb layout. +BB_FIELD_IFMA_INLINE void transpose_out(const V5& v, __m512i* z) +{ + __m512i c0; + __m512i c1; + __m512i c2; + __m512i c3; + to_columns(v, c0, c1, c2, c3); + // Columns hold lanes e0 e2 e1 e3 e4 e6 e5 e7; rebuild the unpack stage of `transpose_in`. + const __m512i lo_idx = _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11); + const __m512i hi_idx = _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15); + const __m512i t0 = _mm512_permutex2var_epi64(c0, lo_idx, c2); + const __m512i t1 = _mm512_permutex2var_epi64(c1, lo_idx, c3); + const __m512i t2 = _mm512_permutex2var_epi64(c0, hi_idx, c2); + const __m512i t3 = _mm512_permutex2var_epi64(c1, hi_idx, c3); + z[0] = _mm512_unpacklo_epi64(t0, t1); + z[1] = _mm512_unpackhi_epi64(t0, t1); + z[2] = _mm512_unpacklo_epi64(t2, t3); + z[3] = _mm512_unpackhi_epi64(t2, t3); +} + +// Inverse of `load8` for a value below 2^256. +BB_FIELD_IFMA_INLINE void store8(const V5& v, uint64_t* dst) +{ + __m512i z[4]; + transpose_out(v, z); + for (size_t j = 0; j < 4; ++j) { + _mm512_storeu_si512(dst + (8 * j), z[j]); + } +} + +/** + * @brief Eight elements held limb-major, lane j of `limb[i]` being 64-bit limb i of element j (256 bytes, the same + * footprint as eight bb field elements). Stored values are below 2^256. + */ +struct alignas(64) Columns { + uint64_t limb[4][8]; +}; + +BB_FIELD_IFMA_INLINE V5 load_columns(const Columns& c) +{ + return from_columns(_mm512_load_si512(c.limb[0]), + _mm512_load_si512(c.limb[1]), + _mm512_load_si512(c.limb[2]), + _mm512_load_si512(c.limb[3])); +} + +// v must be normalised and below 2^256. +BB_FIELD_IFMA_INLINE void store_columns(const V5& v, Columns& c) +{ + __m512i c0; + __m512i c1; + __m512i c2; + __m512i c3; + to_columns(v, c0, c1, c2, c3); + _mm512_store_si512(c.limb[0], c0); + _mm512_store_si512(c.limb[1], c1); + _mm512_store_si512(c.limb[2], c2); + _mm512_store_si512(c.limb[3], c3); +} + +// One element broadcast to all lanes. `limbs` must be < 2^256. +BB_FIELD_IFMA_INLINE V5 broadcast(const uint64_t* limbs) +{ + return from_columns(bcast(limbs[0]), bcast(limbs[1]), bcast(limbs[2]), bcast(limbs[3])); +} + +/** + * @brief dst[k] = src[2k] + u * (src[2k + 1] - src[2k]) for k < n, on raw 4-limb elements in [0, 2p). n must be a + * multiple of 8. dst may alias src (dst == src): every iteration reads its sixteen inputs before writing. A + * block of eight bit-identical pairs is copied (src[2k]) like the scalar loop's per-pair short-cut. + */ +template +BB_FIELD_IFMA_TARGET void fold_stride2(const uint64_t* src, uint64_t* dst, size_t n, const uint64_t* u) +{ + using C = Consts; + const V5 uv = broadcast(u); + for (size_t k = 0; k < n; k += 8) { + V5 even; + V5 odd; + load8_even_odd(src + (8 * k), even, odd); + // Eight bit-identical neighbour pairs (constant selector runs, zero padding) fold to the even values. + __m512i diff = _mm512_setzero_si512(); + for (size_t i = 0; i < 5; ++i) { + diff = _mm512_or_si512(diff, _mm512_xor_si512(even.l[i], odd.l[i])); + } + if (_mm512_test_epi64_mask(diff, diff) == 0) { + store8(even, dst + (4 * k)); + continue; + } + // (odd - even + 2p) < 4p; times u < 2p gives < 2.52p; plus even < 4.52p. + const V5 r = add(mont_mul(sub_plus(odd, even, C::P2), uv), even); + store8(canonical(r), dst + (4 * k)); + } +} + +/** + * @brief Load the first N <= 8 elements at `src` (32-byte 4-limb layout) without touching memory past them; unused + * lanes are zero. Lane order as in `load8`. + */ +template BB_FIELD_IFMA_INLINE V5 load_n(const uint64_t* src) +{ + static_assert(N >= 1 && N <= 8); + __m512i z[4]; + for (size_t j = 0; j < 4; ++j) { + constexpr auto mask = [](size_t pair) { + return static_cast<__mmask8>(((2 * pair) < N ? 0x0FU : 0U) | ((2 * pair) + 1 < N ? 0xF0U : 0U)); + }; + z[j] = _mm512_maskz_loadu_epi64(mask(j), src + (8 * j)); + } + return transpose_in(z[0], z[1], z[2], z[3]); +} + +// Store the first N <= 8 lanes of `v` (value below 2^256) to `dst` without touching memory past them. +template BB_FIELD_IFMA_INLINE void store_n(const V5& v, uint64_t* dst) +{ + static_assert(N >= 1 && N <= 8); + __m512i z[4]; + transpose_out(v, z); + for (size_t j = 0; j < 4; ++j) { + constexpr auto mask = [](size_t pair) { + return static_cast<__mmask8>(((2 * pair) < N ? 0x0FU : 0U) | ((2 * pair) + 1 < N ? 0xF0U : 0U)); + }; + _mm512_mask_storeu_epi64(dst + (8 * j), mask(j), z[j]); + } +} + +/** + * @brief a[i] *= b[i] for i < N <= 8, on raw 4-limb elements in [0, 2p) (the results are below 1.8p). Element-wise + * products of short univariates in the sumcheck relations. + */ +template BB_FIELD_IFMA_TARGET void mul_assign_n(uint64_t* a, const uint64_t* b) +{ + store_n(mont_mul(load_n(a), load_n(b)), a); +} + +// a[i] *= s for i < N <= 8 (results below 1.8p). +template BB_FIELD_IFMA_TARGET void mul_assign_scalar_n(uint64_t* a, const uint64_t* s) +{ + store_n(mont_mul(load_n(a), broadcast(s)), a); +} + +// a[i] = a[i]^2 for i < N <= 8 (results below 1.8p). +template BB_FIELD_IFMA_TARGET void sqr_assign_n(uint64_t* a) +{ + const V5 v = load_n(a); + store_n(mont_mul(v, v), a); +} + +/** + * @brief Horner evaluation split over 16 interleaved chains: writes eight elements t_0 .. t_7 (in [0, p), 4-limb + * layout) to `out` whose sum is sum_i coeffs[i] * z^i for i < n. coeffs are raw 4-limb elements in [0, 2p) and + * n must be a multiple of 16; `z_pows` holds z^0 .. z^7, `z8` = z^8 and `z16` = z^16, each below 2p. + * + * @details Lane j of chain A accumulates sum_m coeffs[16m + j] z^(16m) and chain B sum_m coeffs[16m + 8 + j] z^(16m) + * by Horner's rule from the top, so two independent multiplications are in flight per step. Then + * t_j = z^j (A_j + z^8 B_j). + */ +template +BB_FIELD_IFMA_TARGET void evaluate( + const uint64_t* coeffs, size_t n, const uint64_t* z_pows, const uint64_t* z8, const uint64_t* z16, uint64_t* out) +{ + const V5 z16v = broadcast(z16); + V5 a; + V5 b; + for (size_t i = 0; i < 5; ++i) { + a.l[i] = _mm512_setzero_si512(); + b.l[i] = _mm512_setzero_si512(); + } + // The accumulators stay below 4.9p (fixed point of x -> 0.19 * 2x + 1 + 2). + for (size_t i = n; i != 0;) { + i -= 16; + a = add(mont_mul(a, z16v), load8(coeffs + (4 * i))); + b = add(mont_mul(b, z16v), load8(coeffs + (4 * (i + 8)))); + } + // a + z^8 b < 4.9p + 2.9p; reduce before the last multiplication. + const V5 lanes = canonical(add(a, mont_mul(b, broadcast(z8)))); + store8(canonical(mont_mul(lanes, load8(z_pows))), out); +} + +/** + * @brief One source of `add_scaled_batch_tile`: tile elements [begin, end) gain scalar * src, where `data` points at + * the source element for tile index `begin`. A unit scalar (`unit`) adds src without multiplying. + */ +struct ScaledSource { + const uint64_t* data; + size_t begin; + size_t end; + const uint64_t* scalar; + bool unit; +}; + +/** + * @brief dst[i] += sum over sources of scalar * src[i] for a tile of n <= MAX_TILE elements (n a multiple of 8), on raw + * 4-limb elements in [0, 2p). Outputs are in [0, p). + * + * @details The tile is held in 52-bit form for the whole batch, so every dst element is converted once. Blocks of + * eight source elements that are all zero (selector columns) are skipped, as are the lanes of a block outside + * the source's range (masked loads, which also never touch memory outside it). Each block is reduced after + * every third term, keeping it below 2p + 3 * 2p < 9p as `canonical` needs. + */ +inline constexpr size_t MAX_TILE = 256; + +template +BB_FIELD_IFMA_TARGET void add_scaled_batch_tile(uint64_t* dst, + size_t n, + const ScaledSource* sources, + size_t num_sources) +{ + const size_t num_blocks = n / 8; + V5 acc[MAX_TILE / 8]; + uint8_t terms[MAX_TILE / 8]; + for (size_t b = 0; b < num_blocks; ++b) { + acc[b] = load8(dst + (32 * b)); + terms[b] = 0; + } + for (size_t s = 0; s < num_sources; ++s) { + const ScaledSource& src = sources[s]; + const V5 scalar = broadcast(src.scalar); + for (size_t b = src.begin / 8; b * 8 < src.end; ++b) { + const size_t lo = b * 8; + // Mask of the 64-bit words of the block's eight elements that lie in [begin, end). + const size_t first = (src.begin > lo) ? src.begin - lo : 0; + const size_t last = std::min(8, src.end - lo); + const uint32_t elements = ((1U << last) - 1U) & ~((1U << first) - 1U); + // Element pointer arithmetic stays within the source when every lane is live. + const uint64_t* base = src.data - (4 * src.begin) + (4 * lo); + __m512i z[4]; + __m512i any = _mm512_setzero_si512(); + for (size_t j = 0; j < 4; ++j) { + const uint32_t pair = (elements >> (2 * j)) & 3U; + const __mmask8 words = + static_cast<__mmask8>(((pair & 1U) != 0 ? 0x0FU : 0U) | ((pair & 2U) != 0 ? 0xF0U : 0U)); + z[j] = _mm512_maskz_loadu_epi64(words, base + (8 * j)); + any = _mm512_or_si512(any, z[j]); + } + if (_mm512_test_epi64_mask(any, any) == 0) { + continue; + } + V5 v = transpose_in(z[0], z[1], z[2], z[3]); + if (!src.unit) { + v = mont_mul(v, scalar); + } + acc[b] = add(acc[b], v); + if (++terms[b] == 3) { + acc[b] = canonical(acc[b]); + terms[b] = 0; + } + } + } + for (size_t b = 0; b < num_blocks; ++b) { + store8(canonical(acc[b]), dst + (32 * b)); + } +} + +} // namespace bb::field_ifma + +// NOLINTEND(cppcoreguidelines-avoid-c-arrays, cppcoreguidelines-pro-bounds-constant-array-index) + +#endif // BB_FIELD_IFMA diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.test.cpp new file mode 100644 index 0000000..e11cfef --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/ifma_field.test.cpp @@ -0,0 +1,217 @@ +#include "barretenberg/ecc/fields/ifma_field.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/numeric/random/engine.hpp" + +#include + +#include +#include + +#ifdef BB_FIELD_IFMA + +using namespace bb; + +namespace { + +auto& engine = numeric::get_debug_randomness(); + +// A random element, sometimes an edge value (0, 1, p - 1) and sometimes in coarse form (value + p < 2p). +fr edge_or_random(size_t i) +{ + switch (i % 11) { + case 0: + return fr::zero(); + case 1: + return fr::one(); + case 2: + return -fr::one(); + case 3: { + // p - 1 + p: the largest coarse representative of -1 below 2p. + fr r = -fr::one(); + const uint256_t v = uint256_t{ r.data[0], r.data[1], r.data[2], r.data[3] } + fr::modulus; + r.data[0] = v.data[0]; + r.data[1] = v.data[1]; + r.data[2] = v.data[2]; + r.data[3] = v.data[3]; + return r; + } + default: + break; + } + // random_element is coarse ([0, 2p)); reduce it so that adding p stays below 2p. + fr r = fr::random_element(&engine).reduce_once(); + if (i % 3 == 0) { + const uint256_t v = uint256_t{ r.data[0], r.data[1], r.data[2], r.data[3] } + fr::modulus; + r.data[0] = v.data[0]; + r.data[1] = v.data[1]; + r.data[2] = v.data[2]; + r.data[3] = v.data[3]; + } + return r; +} + +// Same field value, and a valid bb representative (below 2p). +void expect_reduced_equal(const fr& expected, const fr& actual) +{ + EXPECT_EQ(expected, actual); + EXPECT_LT((uint256_t{ actual.data[0], actual.data[1], actual.data[2], actual.data[3] }), fr::modulus + fr::modulus); +} + +class FieldIfma : public ::testing::Test { + protected: + void SetUp() override + { + if (!field_ifma::available()) { + GTEST_SKIP() << "no AVX-512 IFMA on this CPU (or BB_FIELD_NO_IFMA set)"; + } + } +}; + +} // namespace + +TEST_F(FieldIfma, FoldStride2MatchesScalar) +{ + constexpr size_t N = 8 * 64; + std::vector src(2 * N); + for (size_t i = 0; i < src.size(); ++i) { + src[i] = edge_or_random(i); + } + // A block of bit-identical pairs and a block with a single differing pair. + for (size_t i = 64; i < 80; i += 2) { + src[i + 1] = src[i]; + } + for (size_t i = 96; i < 112; i += 2) { + src[i + 1] = src[i]; + } + src[105] = src[105] + fr::one(); + for (const fr& u : { fr::zero(), fr::one(), -fr::one(), fr::random_element(&engine) }) { + std::vector dst(N); + field_ifma::fold_stride2(&src[0].data[0], &dst[0].data[0], N, &u.data[0]); + for (size_t k = 0; k < N; ++k) { + expect_reduced_equal(src[2 * k] + u * (src[2 * k + 1] - src[2 * k]), dst[k]); + } + // In place. + std::vector inplace = src; + field_ifma::fold_stride2(&inplace[0].data[0], &inplace[0].data[0], N, &u.data[0]); + for (size_t k = 0; k < N; ++k) { + EXPECT_EQ(dst[k], inplace[k]); + } + } +} + +TEST_F(FieldIfma, EvaluateMatchesHorner) +{ + for (const size_t n : { size_t{ 16 }, size_t{ 160 }, size_t{ 1024 } }) { + std::vector coeffs(n); + for (size_t i = 0; i < n; ++i) { + coeffs[i] = edge_or_random(i); + } + for (const fr& z : { fr::zero(), fr::one(), -fr::one(), fr::random_element(&engine) }) { + fr expected = fr::zero(); + for (size_t i = n; i > 0; --i) { + expected = (expected * z) + coeffs[i - 1]; + } + std::array z_pows; + z_pows[0] = fr::one(); + for (size_t j = 1; j < 8; ++j) { + z_pows[j] = z_pows[j - 1] * z; + } + const fr z8 = z_pows[7] * z; + const fr z16 = z8.sqr(); + std::array terms; + field_ifma::evaluate( + &coeffs[0].data[0], n, &z_pows[0].data[0], &z8.data[0], &z16.data[0], &terms[0].data[0]); + fr sum = fr::zero(); + for (const fr& t : terms) { + EXPECT_LT((uint256_t{ t.data[0], t.data[1], t.data[2], t.data[3] }), fr::modulus); + sum += t; + } + EXPECT_EQ(sum, expected); + } + } +} + +TEST_F(FieldIfma, AddScaledBatchTileMatchesScalar) +{ + constexpr size_t TILE = field_ifma::MAX_TILE; + constexpr size_t NUM_SOURCES = 23; + std::vector> sources(NUM_SOURCES, std::vector(TILE)); + std::vector scalars(NUM_SOURCES); + std::vector begins(NUM_SOURCES); + std::vector ends(NUM_SOURCES); + for (size_t k = 0; k < NUM_SOURCES; ++k) { + for (size_t i = 0; i < TILE; ++i) { + // Every fourth source is zero over most of the tile (selector-like), exercising the zero-block skip. + sources[k][i] = (k % 4 == 0 && i < 200) ? fr::zero() : edge_or_random(i + k); + } + scalars[k] = (k % 5 == 0) ? fr::one() : edge_or_random(k); + // Ranges with unaligned and empty-tail ends, including the full tile. + begins[k] = (k == 0) ? 0 : (k * 13) % 61; + ends[k] = (k == 1) ? TILE : TILE - ((k * 7) % 53); + } + std::vector dst(TILE); + for (size_t i = 0; i < TILE; ++i) { + dst[i] = edge_or_random(i + 3); + } + std::vector expected = dst; + std::vector scaled; + for (size_t k = 0; k < NUM_SOURCES; ++k) { + for (size_t i = begins[k]; i < ends[k]; ++i) { + expected[i] += scalars[k] * sources[k][i]; + } + scaled.push_back({ .data = &sources[k][begins[k]].data[0], + .begin = begins[k], + .end = ends[k], + .scalar = &scalars[k].data[0], + .unit = scalars[k] == fr::one() }); + } + field_ifma::add_scaled_batch_tile(&dst[0].data[0], TILE, scaled.data(), scaled.size()); + for (size_t i = 0; i < TILE; ++i) { + expect_reduced_equal(expected[i], dst[i]); + } +} + +template void check_small_products() +{ + for (size_t trial = 0; trial < 64; ++trial) { + std::array a; + std::array b; + for (size_t i = 0; i < N; ++i) { + a[i] = edge_or_random((trial * N) + i); + b[i] = edge_or_random((trial * N) + i + 7); + } + const fr s = edge_or_random(trial + 3); + // Guard elements around the arrays must be left untouched by the masked stores. + struct alignas(32) Guarded { + fr before; + std::array values; + fr after; + }; + Guarded prod{ fr(17), a, fr(19) }; + Guarded scaled{ fr(17), a, fr(19) }; + Guarded squared{ fr(17), a, fr(19) }; + field_ifma::mul_assign_n(&prod.values[0].data[0], &b[0].data[0]); + field_ifma::mul_assign_scalar_n(&scaled.values[0].data[0], &s.data[0]); + field_ifma::sqr_assign_n(&squared.values[0].data[0]); + for (size_t i = 0; i < N; ++i) { + expect_reduced_equal(a[i] * b[i], prod.values[i]); + expect_reduced_equal(a[i] * s, scaled.values[i]); + expect_reduced_equal(a[i].sqr(), squared.values[i]); + } + for (const Guarded* g : { &prod, &scaled, &squared }) { + EXPECT_EQ(g->before, fr(17)); + EXPECT_EQ(g->after, fr(19)); + } + } +} + +TEST_F(FieldIfma, SmallElementwiseProductsMatchScalar) +{ + check_small_products<4>(); + check_small_products<5>(); + check_small_products<6>(); + check_small_products<7>(); + check_small_products<8>(); +} + +#endif // BB_FIELD_IFMA diff --git a/barretenberg/cpp/src/barretenberg/ecc/groups/affine_element.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/groups/affine_element.test.cpp index b0e0cd4..1d459f6 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/groups/affine_element.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/groups/affine_element.test.cpp @@ -351,12 +351,15 @@ template class TestAffineElement : public testing::Test { // frequently equals ±(the next digit·base) — exactly the doubling/addition edge (shared // x-coordinate, or a result at infinity) where the unsafe batch-affine formulas are invalid and // the schedule must fall back to the safe (Jacobian) ops. The values below are chosen to land in - // that regime; the naive cross-check then guarantees the fallback path is itself correct. + // that regime; the naive cross-check then guarantees the fallback path is itself correct. t = 23 also runs the + // fallback over full SIMD groups (not only the sub-group tail) on the WASM packed path. static void test_two_round_fold_small_challenges() { - for (uint64_t s1 : { 1ULL, 2ULL, 3ULL, 8ULL, 15ULL, 16ULL }) { - for (uint64_t s2 : { 1ULL, 2ULL, 4ULL, 7ULL, 16ULL }) { - check_two_round_fold_against_naive(4, Fr(s1), Fr(s2)); + for (size_t t : { size_t{ 4 }, size_t{ 23 } }) { + for (uint64_t s1 : { 1ULL, 2ULL, 3ULL, 8ULL, 15ULL, 16ULL }) { + for (uint64_t s2 : { 1ULL, 2ULL, 4ULL, 7ULL, 16ULL }) { + check_two_round_fold_against_naive(t, Fr(s1), Fr(s2)); + } } } } diff --git a/barretenberg/cpp/src/barretenberg/ecc/groups/element_impl.hpp b/barretenberg/cpp/src/barretenberg/ecc/groups/element_impl.hpp index e1a98bb..86d95a2 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/groups/element_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/groups/element_impl.hpp @@ -8,8 +8,10 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/groups/affine_add_packed.hpp" #include "barretenberg/ecc/groups/booth_recode.hpp" #include "barretenberg/ecc/groups/element.hpp" +#include "barretenberg/ecc/groups/two_round_fold_ifma.hpp" #include "element.hpp" #include @@ -1305,6 +1307,219 @@ void element::batch_affine_add(const std::span +void two_round_fold_range_packed(std::span points, + const size_t t, + std::span ops, + const size_t start, + const size_t end, + AffineElement* out) +{ + using Params = typename Fq::Params; + using Vec = VectorField; + using PointSpan = VectorAffineElementPushSpan; + constexpr size_t W = Vec::SIZE; + constexpr size_t NUM_TERMS = 4; + constexpr size_t NUM_MULTIPLIED_BASES = 3; + constexpr size_t LOOKUP_SIZE = BOOTH_ENDO_LOOKUP_SIZE; + + const size_t num_groups = (end - start) / W; + // Coordinate columns: x and y of every lookup-table entry, of the accumulator and of the operand, plus the four + // batch-affine scratch columns. + constexpr size_t NUM_COLUMNS = (2 * NUM_MULTIPLIED_BASES * LOOKUP_SIZE) + 2 + 2 + 4; + std::vector backing(NUM_COLUMNS * num_groups); + size_t next_column = 0; + const auto column = [&]() { + std::span col(backing.data() + (next_column * num_groups), num_groups); + ++next_column; + return col; + }; + const auto make_point_span = [&]() { + auto x_col = column(); + auto y_col = column(); + return PointSpan(x_col, y_col); + }; + + std::array, NUM_MULTIPLIED_BASES> tables; + for (auto& base_table : tables) { + for (auto& entry : base_table) { + entry = make_point_span(); + } + } + PointSpan accum = make_point_span(); + PointSpan to_add = make_point_span(); + const std::array, 4> scratch_columns{ column(), column(), column(), column() }; + BatchAffineAddScratch add_scratch{ VectorFieldPushSpan(scratch_columns[0]), + VectorFieldPushSpan(scratch_columns[1]), + VectorFieldPushSpan(scratch_columns[2]), + VectorFieldPushSpan(scratch_columns[3]) }; + BatchAffineDoubleScratch dbl_scratch{ VectorFieldPushSpan(scratch_columns[0]), + VectorFieldPushSpan(scratch_columns[1]), + VectorFieldPushSpan(scratch_columns[3]) }; + + const auto pack_quarter = [&](size_t quarter, PointSpan& dst) { + dst.reset(); + for (size_t i = start; i < end; ++i) { + const AffineElement& p = points[(quarter * t) + i]; + dst.push_point(p.x, p.y); + } + }; + + // Lookup tables [1·B, ..., 8·B] for the three multiplied bases. + for (size_t base = 0; base < NUM_MULTIPLIED_BASES; ++base) { + auto& table = tables[base]; + pack_quarter(base, table[0]); + batch_affine_double(table[0], table[1], dbl_scratch); + for (size_t j = 2; j < LOOKUP_SIZE; ++j) { + batch_affine_add(table[0], table[j - 1], table[j], add_scratch); + } + } + + // dst = ±magnitude·B for the op's term; term 2 is φ applied to base 0 (x scaled by β). + constexpr Fq beta = Fq::cube_root_of_unity(); + const Vec beta_vec = Vec::broadcast(beta); + const auto fill_to_add = [&](size_t term, uint32_t digit, PointSpan& dst) { + const uint32_t magnitude = digit & 0x7FFFFFFFU; + const bool flip_y = ((digit >> 31) != 0) ^ (term == 2); + static constexpr std::array term_to_base{ 0, 1, 0, 2 }; + const PointSpan& entry = tables[term_to_base[term]][magnitude - 1]; + zip_for_each(entry.x, entry.y, dst.x, dst.y, [&](const auto& tx, const auto& ty, auto& ox, auto& oy) { + if (term == 2) { + if constexpr (std::is_same_v, Vec>) { + ox = tx * beta_vec; + } else { + ox = tx * beta; + } + } else { + ox = tx; + } + oy = flip_y ? -ty : ty; + }); + }; + + // accum ← 2·accum + operand (dbl = true) or accum + operand, per point with the projective formulas. + const auto pointwise_safe = [&](const PointSpan& operand, bool dbl) { + const auto step = [&](Fq& ax, Fq& ay, const Fq& bx, const Fq& by) { + Element acc{ AffineElement(ax, ay) }; + if (dbl) { + acc.self_dbl(); + } + acc += AffineElement(bx, by); + const AffineElement result(acc); + ax = result.x; + ay = result.y; + }; + for (size_t g = 0; g < accum.num_full_vectors(); ++g) { + auto ax = accum.x[g].to_array(); + auto ay = accum.y[g].to_array(); + const auto bx = operand.x[g].to_array(); + const auto by = operand.y[g].to_array(); + for (size_t lane = 0; lane < W; ++lane) { + step(ax[lane], ay[lane], bx[lane], by[lane]); + } + accum.x[g] = Vec(ax); + accum.y[g] = Vec(ay); + } + for (size_t i = 0; i < accum.tail(); ++i) { + step(accum.x.tail_elem(i), accum.y.tail_elem(i), operand.x.tail_elem(i), operand.y.tail_elem(i)); + } + }; + + // accum ← 2·accum + operand via the chord-only path of batch_affine_combined_double_add_impl: + // λ1 = (y2 − y1) / (x2 − x1), x3 = λ1² − x1 − x2, λ2 = −λ1 − 2·y1 / (x3 − x1), + // x4 = λ2² − x1 − x3, y4 = λ2·(x1 − x4) − y1. + auto& s = add_scratch; + const auto combined_double_add = [&](const PointSpan& operand) { + zip_for_each( + accum.x, + accum.y, + operand.x, + operand.y, + s.dx, + s.dy, + s.xsum, + [](const auto& x1, const auto& y1, const auto& x2, const auto& y2, auto& dx, auto& dy, auto& xsum) { + dx = x2 - x1; + dy = y2 - y1; + xsum = x1 + x2; + }); + batch_invert(s.dx, s.inv); + // dy ← λ1, dx ← x3 − x1. + zip_for_each(accum.x, + s.inv, + s.xsum, + s.dy, + s.dx, + [](const auto& x1, const auto& inv, const auto& xsum, auto& dy, auto& dx) { + const auto lambda1 = dy * inv; + dy = lambda1; + dx = lambda1 * lambda1 - xsum - x1; + }); + batch_invert(s.dx, s.inv); + zip_for_each(accum.x, + accum.y, + s.dy, + s.dx, + s.inv, + [](auto& x1, auto& y1, const auto& lambda1, const auto& x3_minus_x1, const auto& inv) { + const auto lambda2 = -lambda1 - ((y1 + y1) * inv); + const auto x4 = lambda2 * lambda2 - x1 - (x3_minus_x1 + x1); + const auto y4 = lambda2 * (x1 - x4) - y1; + x1 = x4; + y1 = y4; + }); + }; + + for (const FoldOp& op : ops) { + switch (op.kind) { + case FoldOpKind::DBL: + batch_affine_double(accum, accum, dbl_scratch); + break; + case FoldOpKind::SEED: + fill_to_add(op.term, op.digit, accum); + break; + case FoldOpKind::COMBINED: + fill_to_add(op.term, op.digit, to_add); + if (op.safe) { + pointwise_safe(to_add, /*dbl=*/true); + } else { + combined_double_add(to_add); + } + break; + case FoldOpKind::ADD: + fill_to_add(op.term, op.digit, to_add); + if (op.safe) { + pointwise_safe(to_add, /*dbl=*/false); + } else { + batch_affine_add(to_add, accum, accum, add_scratch); + } + break; + } + } + + // Constant tail: + P3. + pack_quarter(3, to_add); + batch_affine_add(to_add, accum, accum, add_scratch); + + accum.for_each_point([&](const Fq& x, const Fq& y, size_t k) { out[start + k] = AffineElement(x, y); }); +} +} // namespace detail + template std::vector> element::batch_two_round_fold( const std::span>& points, const Fr& u1, const Fr& u2) noexcept @@ -1520,6 +1735,24 @@ std::vector> element::batch_two_round_fold( return work_elements; } +#ifdef BB_FIELD_IFMA + if constexpr (field_ifma::Consts::supported && !T::has_a) { + if (field_ifma::available()) { + detail::two_round_fold_ifma( + points, t, ops, work_elements.data()); + return work_elements; + } + } +#endif + + if constexpr (simd_available_v && !T::has_a) { + parallel_for_range(t, [&](size_t start, size_t end) { + detail::two_round_fold_range_packed( + points, t, ops, start, end, work_elements.data()); + }); + return work_elements; + } + std::vector scratch_space(3 * t); Fq* const scratch_a = &scratch_space[0]; Fq* const scratch_b = &scratch_space[t]; diff --git a/barretenberg/cpp/src/barretenberg/ecc/groups/two_round_fold_ifma.hpp b/barretenberg/cpp/src/barretenberg/ecc/groups/two_round_fold_ifma.hpp new file mode 100644 index 0000000..6889b1a --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/groups/two_round_fold_ifma.hpp @@ -0,0 +1,449 @@ +// AVX-512 IFMA replay of `element::batch_two_round_fold`'s op schedule (the IPA SRS fold), runtime-dispatched. +// +// x86-64 only: compiled under BB_FIELD_IFMA (see ecc/fields/ifma_field.hpp) and entered only after +// `field_ifma::available()`. WASM and non-x86 builds compile none of this. + +#pragma once + +#include "barretenberg/ecc/fields/ifma_field.hpp" + +#ifdef BB_FIELD_IFMA + +#include "barretenberg/common/thread.hpp" +#include "barretenberg/common/throw_or_abort.hpp" + +#include +#include +#include +#include +#include +#include + +namespace bb::group_elements::detail { + +namespace fold_ifma { + +using field_ifma::Columns; +using field_ifma::V5; + +// Columns of the x and y coordinates of a group of points (lane j of group g is point 8g + j of the range). +struct PointColumns { + Columns* x; + Columns* y; +}; + +/** + * @brief An operand column pair read with an optional endomorphism twist (x scaled by β) and an optional negation of + * y, as the op schedule's lookups need. + */ +struct Operand { + const Columns* x; + const Columns* y; + bool beta; + bool negate_y; +}; + +/** + * @brief Per-lane inverses of the eight lanes of acc (Montgomery batching around one field inversion), in [0, p). + */ +template BB_FIELD_IFMA_INLINE V5 invert_lanes(const V5& acc, const char* what) +{ + using Params = typename Fq::Params; + alignas(64) Columns c; + field_ifma::store_columns(field_ifma::canonical(acc), c); + std::array lane; + std::array prefix; + Fq running = Fq::one(); + for (size_t l = 0; l < 8; ++l) { + lane[l] = Fq{ c.limb[0][l], c.limb[1][l], c.limb[2][l], c.limb[3][l] }; + prefix[l] = running; + running *= lane[l]; + } + if (running.is_zero()) { + throw_or_abort(what); + } + running = running.invert(); + for (size_t l = 8; l-- > 0;) { + const Fq inv = (running * prefix[l]).reduce_once(); + running *= lane[l]; + for (size_t i = 0; i < 4; ++i) { + c.limb[i][l] = inv.data[i]; + } + } + return field_ifma::load_columns(c); +} + +/** + * @brief Batch-affine group operations over `num_groups` groups of eight points, one field inversion per call. + * + * @details Stored coordinates are always fully reduced ([0, p)). Each pass multiplies the running prefix product + * (stored to `pre`) forward, inverts the eight lane products, and walks back, recomputing the cheap operands + * (differences, sums, the operand's twist) instead of storing them. Bounds are in units of p and follow from + * mont_mul(a, b) < 0.19 * a * b / p + p: running products stay below 1.7p, lane inverses 1.5p, slopes 2.1p. + */ +template struct Kernels { + using Params = typename Fq::Params; + using C = field_ifma::Consts; + + size_t num_groups; + // Running prefix products, one column. + Columns* pre; + // β in every lane, in [0, p). + const Columns* beta; + + BB_FIELD_IFMA_INLINE static V5 load(const Columns& c) { return field_ifma::load_columns(c); } + BB_FIELD_IFMA_INLINE static V5 one() + { + static constexpr Fq ONE = Fq::one(); + return field_ifma::broadcast(&ONE.data[0]); + } + BB_FIELD_IFMA_INLINE static V5 zero() + { + const __m512i z = _mm512_setzero_si512(); + return field_ifma::from_columns(z, z, z, z); + } + + BB_FIELD_IFMA_INLINE void load_operand(const Operand& op, size_t g, V5& x, V5& y) const + { + x = load(op.x[g]); + if (op.beta) { + x = field_ifma::canonical(field_ifma::mont_mul(x, load(*beta))); + } + y = load(op.y[g]); + if (op.negate_y) { + // p - y lies in [1, p]. + y = field_ifma::canonical(field_ifma::sub_plus(zero(), y, C::P)); + } + } + + // dst <- the operand, twisted as requested. + BB_FIELD_IFMA_TARGET void copy(const Operand& op, PointColumns dst) const + { + for (size_t g = 0; g < num_groups; ++g) { + V5 x; + V5 y; + load_operand(op, g, x, y); + field_ifma::store_columns(x, dst.x[g]); + field_ifma::store_columns(y, dst.y[g]); + } + } + + // acc <- acc + op, for acc.x != op.x in every lane. + BB_FIELD_IFMA_TARGET void add(const Operand& op, PointColumns acc) const + { + V5 run = one(); + for (size_t g = 0; g < num_groups; ++g) { + V5 x2; + V5 y2; + load_operand(op, g, x2, y2); + const V5 dx = field_ifma::sub_plus(x2, load(acc.x[g]), C::P); + field_ifma::store_columns(run, pre[g]); + run = field_ifma::mont_mul(run, dx); + } + V5 inv = invert_lanes(run, "attempted to invert zero in two_round_fold_range_ifma (add)"); + for (size_t g = num_groups; g-- > 0;) { + V5 x2; + V5 y2; + load_operand(op, g, x2, y2); + const V5 x1 = load(acc.x[g]); + const V5 y1 = load(acc.y[g]); + const V5 dx = field_ifma::sub_plus(x2, x1, C::P); + const V5 inv_dx = field_ifma::mont_mul(inv, load(pre[g])); + inv = field_ifma::mont_mul(inv, dx); + // lambda < 1.6p; lambda^2 + 2p - (x1 + x2) < 3.5p; lambda (x1 - x3 + p) + p - y1 < 2.6p. + const V5 lambda = field_ifma::mont_mul(field_ifma::sub_plus(y2, y1, C::P), inv_dx); + const V5 x3 = field_ifma::canonical( + field_ifma::sub_plus(field_ifma::mont_mul(lambda, lambda), field_ifma::add(x1, x2), C::P2)); + const V5 y3 = field_ifma::canonical(field_ifma::sub_plus( + field_ifma::mont_mul(lambda, field_ifma::sub_plus(x1, x3, C::P)), y1, C::P)); + field_ifma::store_columns(x3, acc.x[g]); + field_ifma::store_columns(y3, acc.y[g]); + } + } + + // acc <- 2 acc on a curve with a = 0, for acc.y != 0 in every lane. + BB_FIELD_IFMA_TARGET void dbl(PointColumns acc) const + { + V5 run = one(); + for (size_t g = 0; g < num_groups; ++g) { + const V5 y = load(acc.y[g]); + field_ifma::store_columns(run, pre[g]); + run = field_ifma::mont_mul(run, field_ifma::add(y, y)); + } + V5 inv = invert_lanes(run, "attempted to invert zero in two_round_fold_range_ifma (dbl)"); + for (size_t g = num_groups; g-- > 0;) { + const V5 x = load(acc.x[g]); + const V5 y = load(acc.y[g]); + const V5 inv_2y = field_ifma::mont_mul(inv, load(pre[g])); + inv = field_ifma::mont_mul(inv, field_ifma::add(y, y)); + // 3x^2 < 3.6p; lambda < 2.1p; lambda^2 + 2p - 2x < 3.8p; lambda (x - x3 + p) + p - y < 2.8p. + const V5 xx = field_ifma::mont_mul(x, x); + const V5 lambda = field_ifma::mont_mul(field_ifma::add(field_ifma::add(xx, xx), xx), inv_2y); + const V5 x3 = field_ifma::canonical( + field_ifma::sub_plus(field_ifma::mont_mul(lambda, lambda), field_ifma::add(x, x), C::P2)); + const V5 y3 = field_ifma::canonical( + field_ifma::sub_plus(field_ifma::mont_mul(lambda, field_ifma::sub_plus(x, x3, C::P)), y, C::P)); + field_ifma::store_columns(x3, acc.x[g]); + field_ifma::store_columns(y3, acc.y[g]); + } + } + + /** + * @brief acc <- 2 acc + op via the chord-only path of batch_affine_combined_double_add_impl: + * l1 = (y2 - y1) / (x2 - x1), x3 = l1^2 - x1 - x2, l2 = -l1 - 2 y1 / (x3 - x1), x4 = l2^2 - x1 - x3, + * y4 = l2 (x1 - x4) - y1. `lambda1` and `x3` are scratch columns. + */ + BB_FIELD_IFMA_TARGET void combined_double_add(const Operand& op, + PointColumns acc, + Columns* lambda1, + Columns* x3s) const + { + V5 run = one(); + for (size_t g = 0; g < num_groups; ++g) { + V5 x2; + V5 y2; + load_operand(op, g, x2, y2); + const V5 dx = field_ifma::sub_plus(x2, load(acc.x[g]), C::P); + field_ifma::store_columns(run, pre[g]); + run = field_ifma::mont_mul(run, dx); + } + V5 inv = invert_lanes(run, "attempted to invert zero in two_round_fold_range_ifma (combined, phase 1)"); + for (size_t g = num_groups; g-- > 0;) { + V5 x2; + V5 y2; + load_operand(op, g, x2, y2); + const V5 x1 = load(acc.x[g]); + const V5 y1 = load(acc.y[g]); + const V5 dx = field_ifma::sub_plus(x2, x1, C::P); + const V5 inv_dx = field_ifma::mont_mul(inv, load(pre[g])); + inv = field_ifma::mont_mul(inv, dx); + const V5 l1 = field_ifma::mont_mul(field_ifma::sub_plus(y2, y1, C::P), inv_dx); + const V5 x3 = field_ifma::canonical( + field_ifma::sub_plus(field_ifma::mont_mul(l1, l1), field_ifma::add(x1, x2), C::P2)); + field_ifma::store_columns(l1, lambda1[g]); + field_ifma::store_columns(x3, x3s[g]); + } + run = one(); + for (size_t g = 0; g < num_groups; ++g) { + const V5 d = field_ifma::sub_plus(load(x3s[g]), load(acc.x[g]), C::P); + field_ifma::store_columns(run, pre[g]); + run = field_ifma::mont_mul(run, d); + } + inv = invert_lanes(run, "attempted to invert zero in two_round_fold_range_ifma (combined, phase 2)"); + for (size_t g = num_groups; g-- > 0;) { + const V5 x1 = load(acc.x[g]); + const V5 y1 = load(acc.y[g]); + const V5 x3 = load(x3s[g]); + const V5 d = field_ifma::sub_plus(x3, x1, C::P); + const V5 inv_d = field_ifma::mont_mul(inv, load(pre[g])); + inv = field_ifma::mont_mul(inv, d); + // 2 y1 / (x3 - x1) < 1.6p; l2 = 4p - l1 - that < 4p; l2^2 + 2p - x1 - x3 < 6.1p; + // l2 (x1 - x4 + p) + p - y1 < 3.6p. + const V5 t = field_ifma::mont_mul(field_ifma::add(y1, y1), inv_d); + const V5 l2 = field_ifma::sub2_plus(zero(), load(lambda1[g]), t, C::P4); + const V5 x4 = field_ifma::canonical( + field_ifma::sub2_plus(field_ifma::mont_mul(l2, l2), x1, x3, C::P2)); + const V5 y4 = field_ifma::canonical( + field_ifma::sub_plus(field_ifma::mont_mul(l2, field_ifma::sub_plus(x1, x4, C::P)), y1, C::P)); + field_ifma::store_columns(x4, acc.x[g]); + field_ifma::store_columns(y4, acc.y[g]); + } + } +}; + +} // namespace fold_ifma + +// Lookup-table columns (x, y per entry for three bases), the accumulator, and the scratch columns pre, lambda1, x3. +template inline constexpr size_t TWO_ROUND_FOLD_IFMA_COLUMNS = (2 * 3 * LOOKUP_SIZE) + 2 + 3; + +/** + * @brief Replay batch_two_round_fold's op schedule over the output range [start, end) (start a multiple of 8) on IFMA + * kernels. `backing` holds TWO_ROUND_FOLD_IFMA_COLUMNS columns of `total_groups` groups each; the range uses + * groups start / 8 onwards of every column. + * + * @details Same structure as two_round_fold_range_packed: every coordinate column is held limb-major in groups of + * eight points for the whole schedule, packed once on entry and unpacked once on exit. Each op runs its field + * arithmetic eight points per register with one field inversion. A partial last group is padded with copies of the + * range's last point, whose results are dropped. The `safe` ops run the projective formulas per point. The group + * operations are exact, so every output is the same affine point as on the scalar path (with fully reduced + * coordinates). + */ +template +void two_round_fold_range_ifma(std::span points, + const size_t t, + std::span ops, + const size_t start, + const size_t end, + field_ifma::Columns* backing, + const size_t total_groups, + AffineElement* out) +{ + using field_ifma::Columns; + using OpKind = decltype(FoldOp{}.kind); + constexpr size_t NUM_TERMS = 4; + constexpr size_t NUM_MULTIPLIED_BASES = 3; + + const size_t n = end - start; + const size_t num_groups = (n + 7) / 8; + size_t next_column = 0; + const auto column = [&]() { return backing + ((next_column++) * total_groups) + (start / 8); }; + const auto point_columns = [&]() { + Columns* x = column(); + return fold_ifma::PointColumns{ x, column() }; + }; + std::array, NUM_MULTIPLIED_BASES> tables; + for (auto& base_table : tables) { + for (auto& entry : base_table) { + entry = point_columns(); + } + } + const fold_ifma::PointColumns accum = point_columns(); + Columns* const pre = column(); + Columns* const scratch_a = column(); + Columns* const scratch_b = column(); + + // Lane j of group g holds point min(start + 8g + j, end - 1) of a quarter, coordinates reduced into [0, p). + const auto pack_quarter = [&](size_t quarter, fold_ifma::PointColumns dst) { + for (size_t k = 0; k < num_groups * 8; ++k) { + const AffineElement& p = points[(quarter * t) + start + std::min(k, n - 1)]; + const Fq x = p.x.reduce_once(); + const Fq y = p.y.reduce_once(); + for (size_t i = 0; i < 4; ++i) { + dst.x[k / 8].limb[i][k % 8] = x.data[i]; + dst.y[k / 8].limb[i][k % 8] = y.data[i]; + } + } + }; + const auto lane_point = [](const fold_ifma::PointColumns& c, size_t k) { + return AffineElement(Fq{ c.x[k / 8].limb[0][k % 8], + c.x[k / 8].limb[1][k % 8], + c.x[k / 8].limb[2][k % 8], + c.x[k / 8].limb[3][k % 8] }, + Fq{ c.y[k / 8].limb[0][k % 8], + c.y[k / 8].limb[1][k % 8], + c.y[k / 8].limb[2][k % 8], + c.y[k / 8].limb[3][k % 8] }); + }; + const auto set_lane_point = [](const fold_ifma::PointColumns& c, size_t k, const AffineElement& p) { + const Fq x = p.x.reduce_once(); + const Fq y = p.y.reduce_once(); + for (size_t i = 0; i < 4; ++i) { + c.x[k / 8].limb[i][k % 8] = x.data[i]; + c.y[k / 8].limb[i][k % 8] = y.data[i]; + } + }; + + alignas(64) Columns beta_lanes; + constexpr Fq beta = Fq::cube_root_of_unity(); + const Fq beta_reduced = beta.reduce_once(); + for (size_t i = 0; i < 4; ++i) { + for (size_t l = 0; l < 8; ++l) { + beta_lanes.limb[i][l] = beta_reduced.data[i]; + } + } + const fold_ifma::Kernels kernels{ num_groups, pre, &beta_lanes }; + + const auto as_operand = [](const fold_ifma::PointColumns& c) { + return fold_ifma::Operand{ c.x, c.y, false, false }; + }; + + // Lookup tables [1·B, ..., 8·B] for the three multiplied bases. + for (size_t base = 0; base < NUM_MULTIPLIED_BASES; ++base) { + auto& table = tables[base]; + pack_quarter(base, table[0]); + kernels.copy(as_operand(table[0]), table[1]); + kernels.dbl(table[1]); + for (size_t j = 2; j < LOOKUP_SIZE; ++j) { + kernels.copy(as_operand(table[j - 1]), table[j]); + kernels.add(as_operand(table[0]), table[j]); + } + } + + // ±magnitude·B for the op's term; term 2 is φ applied to base 0 (x scaled by β). + const auto operand_for = [&](size_t term, uint32_t digit) { + const uint32_t magnitude = digit & 0x7FFFFFFFU; + const bool flip_y = ((digit >> 31) != 0) ^ (term == 2); + static constexpr std::array term_to_base{ 0, 1, 0, 2 }; + const fold_ifma::PointColumns& entry = tables[term_to_base[term]][magnitude - 1]; + return fold_ifma::Operand{ entry.x, entry.y, term == 2, flip_y }; + }; + + // accum ← 2·accum + operand (dbl = true) or accum + operand, per point with the projective formulas. + const fold_ifma::PointColumns operand_scratch{ scratch_a, scratch_b }; + const auto pointwise_safe = [&](const fold_ifma::Operand& operand, bool dbl) { + kernels.copy(operand, operand_scratch); + for (size_t k = 0; k < num_groups * 8; ++k) { + Element acc{ lane_point(accum, k) }; + if (dbl) { + acc.self_dbl(); + } + acc += lane_point(operand_scratch, k); + set_lane_point(accum, k, AffineElement(acc)); + } + }; + + for (const FoldOp& op : ops) { + switch (op.kind) { + case OpKind::DBL: + kernels.dbl(accum); + break; + case OpKind::SEED: + kernels.copy(operand_for(op.term, op.digit), accum); + break; + case OpKind::COMBINED: + if (op.safe) { + pointwise_safe(operand_for(op.term, op.digit), /*dbl=*/true); + } else { + kernels.combined_double_add(operand_for(op.term, op.digit), accum, scratch_a, scratch_b); + } + break; + case OpKind::ADD: + if (op.safe) { + pointwise_safe(operand_for(op.term, op.digit), /*dbl=*/false); + } else { + kernels.add(operand_for(op.term, op.digit), accum); + } + break; + } + } + + // Constant tail: + P3. + pack_quarter(3, operand_scratch); + kernels.add(as_operand(operand_scratch), accum); + + for (size_t k = 0; k < n; ++k) { + out[start + k] = lane_point(accum, k); + } +} + +/** + * @brief batch_two_round_fold's IFMA path for curves with a = 0 over a field the kernels support: writes the t folded + * points to `out`. + * + * @details The coordinate columns of all ranges live in one allocation made here, as the scalar path's tables are: + * 55 columns of 32 bytes per point, the scalar path's footprint. (Per-range allocations in the worker threads would be + * served from per-thread malloc arenas that keep the memory resident after the fold.) Ranges are split at multiples of + * eight points so that each owns whole groups. + */ +template +void two_round_fold_ifma(std::span points, + const size_t t, + std::span ops, + AffineElement* out) +{ + const size_t total_groups = (t + 7) / 8; + std::vector backing(TWO_ROUND_FOLD_IFMA_COLUMNS * total_groups); + const size_t num_ranges = std::min(get_num_cpus(), total_groups); + parallel_for(num_ranges, [&](size_t r) { + const size_t start = 8 * ((total_groups * r) / num_ranges); + const size_t end = std::min(t, 8 * ((total_groups * (r + 1)) / num_ranges)); + if (start < end) { + two_round_fold_range_ifma( + points, t, ops, start, end, backing.data(), total_groups, out); + } + }); +} + +} // namespace bb::group_elements::detail + +#endif // BB_FIELD_IFMA diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_affine_ifma.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_affine_ifma.hpp new file mode 100644 index 0000000..057dd69 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_affine_ifma.hpp @@ -0,0 +1,457 @@ +// AVX-512 IFMA batch-affine drain for the native Stage-6a tree reduce. +// +// x86-64 only and runtime-dispatched: the build targets a baseline ISA, so every function that touches 512-bit +// registers carries a `target` attribute and is only entered after `ifma_available()` confirmed the CPU (and OS) +// support it. WASM and non-x86 builds compile none of this. + +#pragma once + +#if defined(__x86_64__) && !defined(__wasm__) && (defined(__clang__) || defined(__GNUC__)) +#define BB_MSM_IFMA 1 +#endif + +#ifdef BB_MSM_IFMA + +#include "barretenberg/common/throw_or_abort.hpp" + +#include "barretenberg/common/cpu_supports.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays, cppcoreguidelines-pro-bounds-constant-array-index) +// Clang 18-21 models 512-bit EVEX separately; Zig's baseline target can disable it explicitly. +// Other Clang versions and GCC retain their original target feature spelling. +#if defined(__clang__) && __clang_major__ >= 18 && __clang_major__ <= 21 +#define BB_IFMA_TARGET __attribute__((target("avx512f,avx512ifma,avx512vl,avx512dq,avx512bw,evex512"))) +#else +#define BB_IFMA_TARGET __attribute__((target("avx512f,avx512ifma,avx512vl,avx512dq,avx512bw"))) +#endif +#define BB_IFMA_INLINE BB_IFMA_TARGET __attribute__((always_inline)) inline + +namespace bb::scalar_multiplication::ifma { + +/** + * @brief True when the CPU and OS support AVX-512F + IFMA. `BB_MSM_NO_IFMA` (any value) forces false, which keeps the + * portable drain reachable on IFMA hardware for A/B runs and tests. + */ +inline bool ifma_available() noexcept +{ + static const bool available = [] { + if (std::getenv("BB_MSM_NO_IFMA") != nullptr) { + return false; + } + return bb::cpu_supports_avx512_ifma(); + }(); + return available; +} + +/** + * @brief Field elements as 5 limbs of 52 bits, 8 lanes per register (one lane per independent element). + * + * @details The Montgomery multiplication below uses R = 2^256, i.e. bb's own Montgomery domain: four 52-bit + * reduction steps followed by one 48-bit step. Values are kept loosely reduced. The bounds quoted in this file + * are in units of p and rely on p < 0.19 * 2^256 (both BN254 fields), which gives + * mont_mul(a, b) < 0.19 * a * b / p + p; every value stays far below the 2^260 the limbs can hold. + */ +template struct Consts { + static constexpr uint64_t M52 = (uint64_t{ 1 } << 52) - 1; + static constexpr std::array MOD{ + Params::modulus_0, Params::modulus_1, Params::modulus_2, Params::modulus_3 + }; + + static constexpr std::array to52(const std::array& a) + { + return { a[0] & M52, + ((a[0] >> 52) | (a[1] << 12)) & M52, + ((a[1] >> 40) | (a[2] << 24)) & M52, + ((a[2] >> 28) | (a[3] << 36)) & M52, + a[3] >> 16 }; + } + // k * p in normalised 52-bit limbs (k small). + static constexpr std::array times(uint64_t k) + { + const std::array p = to52(MOD); + std::array r{}; + uint64_t carry = 0; + for (size_t i = 0; i < 5; ++i) { + const uint64_t v = (p[i] * k) + carry; + r[i] = (i < 4) ? (v & M52) : v; + carry = v >> 52; + } + return r; + } + static constexpr std::array P = times(1); + static constexpr std::array P2 = times(2); + static constexpr std::array P4 = times(4); + // -p^-1 mod 2^52. + static constexpr uint64_t PINV = Params::r_inv & M52; + // floor(2^52 / (floor(p / 2^208) + 1)): quotient estimate for `canonical`. + static constexpr uint64_t QK = (uint64_t{ 1 } << 52) / (P[4] + 1); + + // The bound analysis needs p < 0.19 * 2^256 (0.19 * 2^64 = 0x30a3d70a3d70a3d7). + static constexpr bool supported = Params::modulus_3 < 0x30a3d70a3d70a3d7ULL; +}; + +struct V5 { + __m512i l[5]; +}; + +BB_IFMA_INLINE __m512i bcast(uint64_t v) +{ + return _mm512_set1_epi64(static_cast(v)); +} + +/** + * @brief r = a * b / 2^256 (mod p), r < 0.19 * a * b / p + p. Limbs of a and b must be < 2^52. + */ +template BB_IFMA_INLINE V5 mont_mul(const V5& a, const V5& b) +{ + using C = Consts; + const __m512i z = _mm512_setzero_si512(); + const __m512i m52 = bcast(C::M52); + const __m512i pinv = bcast(C::PINV); + __m512i p[5]; + for (size_t j = 0; j < 5; ++j) { + p[j] = bcast(C::P[j]); + } + __m512i t[10]; + for (auto& ti : t) { + ti = z; + } + for (size_t i = 0; i < 5; ++i) { + for (size_t j = 0; j < 5; ++j) { + t[i + j] = _mm512_madd52lo_epu64(t[i + j], a.l[i], b.l[j]); + t[i + j + 1] = _mm512_madd52hi_epu64(t[i + j + 1], a.l[i], b.l[j]); + } + } + // Four 52-bit Montgomery steps: zero the low 52 bits of t[i] and carry them into t[i + 1]. + for (size_t i = 0; i < 4; ++i) { + const __m512i m = _mm512_madd52lo_epu64(z, t[i], pinv); + for (size_t j = 0; j < 5; ++j) { + t[i + j] = _mm512_madd52lo_epu64(t[i + j], m, p[j]); + t[i + j + 1] = _mm512_madd52hi_epu64(t[i + j + 1], m, p[j]); + } + t[i + 1] = _mm512_add_epi64(t[i + 1], _mm512_srli_epi64(t[i], 52)); + } + // One 48-bit step brings the total shift to 4 * 52 + 48 = 256. + { + const __m512i m = _mm512_and_si512(_mm512_madd52lo_epu64(z, t[4], pinv), bcast((uint64_t{ 1 } << 48) - 1)); + for (size_t j = 0; j < 5; ++j) { + t[4 + j] = _mm512_madd52lo_epu64(t[4 + j], m, p[j]); + t[5 + j] = _mm512_madd52hi_epu64(t[5 + j], m, p[j]); + } + } + for (size_t i = 4; i < 9; ++i) { + t[i + 1] = _mm512_add_epi64(t[i + 1], _mm512_srli_epi64(t[i], 52)); + t[i] = _mm512_and_si512(t[i], m52); + } + V5 r; + for (size_t j = 0; j < 4; ++j) { + r.l[j] = + _mm512_or_si512(_mm512_srli_epi64(t[4 + j], 48), _mm512_and_si512(_mm512_slli_epi64(t[5 + j], 4), m52)); + } + r.l[4] = _mm512_or_si512(_mm512_srli_epi64(t[8], 48), _mm512_slli_epi64(t[9], 4)); + return r; +} + +// Propagate signed per-limb carries so limbs 0..3 are in [0, 2^52). The represented value must be non-negative. +BB_IFMA_INLINE void normalise(V5& r) +{ + const __m512i m52 = bcast((uint64_t{ 1 } << 52) - 1); + for (size_t i = 0; i < 4; ++i) { + r.l[i + 1] = _mm512_add_epi64(r.l[i + 1], _mm512_srai_epi64(r.l[i], 52)); + r.l[i] = _mm512_and_si512(r.l[i], m52); + } +} + +// a + k - b, with k a constant multiple of p (as normalised limbs) that is at least b. +BB_IFMA_INLINE V5 sub_plus(const V5& a, const V5& b, const std::array& k) +{ + V5 r; + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_sub_epi64(_mm512_add_epi64(a.l[i], bcast(k[i])), b.l[i]); + } + normalise(r); + return r; +} + +// a + k - b - c. +BB_IFMA_INLINE V5 sub2_plus(const V5& a, const V5& b, const V5& c, const std::array& k) +{ + V5 r; + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_sub_epi64(_mm512_sub_epi64(_mm512_add_epi64(a.l[i], bcast(k[i])), b.l[i]), c.l[i]); + } + normalise(r); + return r; +} + +/** + * @brief Fully reduce v (normalised, v < 2^256 + 2^255 suffices) into [0, p). + * + * @details q = floor(v4 * QK / 2^52), with v4 = floor(v / 2^208), never exceeds floor(v / p) and falls short of it by + * at most one for the inputs used here (v < 9p), so v - q * p lies in [0, 2p); one conditional subtraction finishes. + */ +template BB_IFMA_INLINE V5 canonical(const V5& v) +{ + using C = Consts; + const __m512i z = _mm512_setzero_si512(); + const __m512i q = _mm512_madd52hi_epu64(z, v.l[4], bcast(C::QK)); + V5 r; + __m512i carry_hi = z; + for (size_t i = 0; i < 5; ++i) { + const __m512i pi = bcast(C::P[i]); + const __m512i lo = _mm512_madd52lo_epu64(z, q, pi); + r.l[i] = _mm512_sub_epi64(_mm512_sub_epi64(v.l[i], lo), carry_hi); + carry_hi = _mm512_madd52hi_epu64(z, q, pi); + } + normalise(r); + V5 t; + for (size_t i = 0; i < 5; ++i) { + t.l[i] = _mm512_sub_epi64(r.l[i], bcast(C::P[i])); + } + normalise(t); + const __mmask8 negative = _mm512_movepi64_mask(t.l[4]); + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_mask_blend_epi64(negative, t.l[i], r.l[i]); + } + return r; +} + +// Load 8 consecutive elements from four limb-major 64-bit columns (each a bb field element's data[i]). +BB_IFMA_INLINE V5 load64(const uint64_t* l0, const uint64_t* l1, const uint64_t* l2, const uint64_t* l3) +{ + const __m512i m52 = bcast((uint64_t{ 1 } << 52) - 1); + const __m512i a0 = _mm512_load_si512(l0); + const __m512i a1 = _mm512_load_si512(l1); + const __m512i a2 = _mm512_load_si512(l2); + const __m512i a3 = _mm512_load_si512(l3); + V5 r; + r.l[0] = _mm512_and_si512(a0, m52); + r.l[1] = _mm512_and_si512(_mm512_or_si512(_mm512_srli_epi64(a0, 52), _mm512_slli_epi64(a1, 12)), m52); + r.l[2] = _mm512_and_si512(_mm512_or_si512(_mm512_srli_epi64(a1, 40), _mm512_slli_epi64(a2, 24)), m52); + r.l[3] = _mm512_and_si512(_mm512_or_si512(_mm512_srli_epi64(a2, 28), _mm512_slli_epi64(a3, 36)), m52); + r.l[4] = _mm512_srli_epi64(a3, 16); + return r; +} + +// Inverse of load64 for a value below 2^256. +BB_IFMA_INLINE void store64(const V5& v, uint64_t* l0, uint64_t* l1, uint64_t* l2, uint64_t* l3) +{ + _mm512_store_si512(l0, _mm512_or_si512(v.l[0], _mm512_slli_epi64(v.l[1], 52))); + _mm512_store_si512(l1, _mm512_or_si512(_mm512_srli_epi64(v.l[1], 12), _mm512_slli_epi64(v.l[2], 40))); + _mm512_store_si512(l2, _mm512_or_si512(_mm512_srli_epi64(v.l[2], 24), _mm512_slli_epi64(v.l[3], 28))); + _mm512_store_si512(l3, _mm512_or_si512(_mm512_srli_epi64(v.l[3], 36), _mm512_slli_epi64(v.l[4], 16))); +} + +BB_IFMA_INLINE V5 load52(const uint64_t* base, size_t stride) +{ + V5 r; + for (size_t i = 0; i < 5; ++i) { + r.l[i] = _mm512_load_si512(base + (i * stride)); + } + return r; +} + +BB_IFMA_INLINE void store52(const V5& v, uint64_t* base, size_t stride) +{ + for (size_t i = 0; i < 5; ++i) { + _mm512_store_si512(base + (i * stride), v.l[i]); + } +} + +/** + * @brief Queue and scratch for one worker's IFMA drain: up to CAP pairs (lhs, rhs) held limb-major, so lane k of + * column `lx[i]` is limb i of pair k's lhs.x. dx and the prefix products are kept as 52-bit limbs. + */ +template struct DrainBuffer { + static_assert(CAP % 8 == 0); + alignas(64) uint64_t lx[4][CAP]; + alignas(64) uint64_t ly[4][CAP]; + alignas(64) uint64_t rx[4][CAP]; + alignas(64) uint64_t ry[4][CAP]; + alignas(64) uint64_t dx[5][CAP]; + alignas(64) uint64_t pre[5][CAP]; + uint32_t pair_dest[CAP]; + + template + void push(size_t k, const BaseField& x1, const BaseField& y1, const BaseField& x2, const BaseField& y2) noexcept + { + for (size_t i = 0; i < 4; ++i) { + lx[i][k] = x1.data[i]; + ly[i][k] = y1.data[i]; + rx[i][k] = x2.data[i]; + ry[i][k] = y2.data[i]; + } + } +}; + +/** + * @brief Batch affine addition with one shared inversion: sink(k, x3, y3) receives lhs[k] + rhs[k] for each of the n + * pairs queued in `buf`. + * + * @details The pairs are spread over 8 independent Montgomery prefix chains, one per lane: pair k belongs to lane k % 8 + * at step k / 8. The forward pass forms dx and the running prefix products, the 8 chain products are inverted + * with scalar Montgomery batching around one field inversion, and the backward pass peels off each 1 / dx and + * finishes the affine addition. The backward pass has enough independent work per step to hide the latency + * of its two chained multiplications, so more chains do not pay. Every output coordinate is fully reduced + * into [0, p). The caller guarantees lhs.x != rhs.x for every pair (so no dx is zero), as for the scalar + * drain. + */ +template +BB_IFMA_TARGET void drain_vector(DrainBuffer& buf, size_t n, Sink&& sink) +{ + using Params = typename BaseField::Params; + using C = Consts; + const size_t steps = (n + 7) / 8; + const size_t padded = steps * 8; + + // Padding pairs (0, 0) + (1, 0): dx = 1, so they leave the chain products unchanged. Their outputs are dropped. + const BaseField one = BaseField::one(); + for (size_t k = n; k < padded; ++k) { + for (size_t i = 0; i < 4; ++i) { + buf.lx[i][k] = 0; + buf.ly[i][k] = 0; + buf.rx[i][k] = one.data[i]; + buf.ry[i][k] = 0; + } + } + + alignas(64) uint64_t lanes[4][8]; + for (size_t i = 0; i < 4; ++i) { + for (auto& o : lanes[i]) { + o = one.data[i]; + } + } + V5 acc = load64(lanes[0], lanes[1], lanes[2], lanes[3]); + + // Forward: dx = rx - lx + 2p (< 4p); prefix products bounded by ~4.1p. + for (size_t k = 0; k < padded; k += 8) { + const V5 x1 = load64(&buf.lx[0][k], &buf.lx[1][k], &buf.lx[2][k], &buf.lx[3][k]); + const V5 x2 = load64(&buf.rx[0][k], &buf.rx[1][k], &buf.rx[2][k], &buf.rx[3][k]); + const V5 dx = sub_plus(x2, x1, C::P2); + store52(dx, &buf.dx[0][k], CAP); + store52(acc, &buf.pre[0][k], CAP); + acc = mont_mul(acc, dx); + } + + // Invert the 8 chain products. + store64(canonical(acc), lanes[0], lanes[1], lanes[2], lanes[3]); + { + std::array lane; + std::array prefix; + BaseField running = BaseField::one(); + for (size_t l = 0; l < 8; ++l) { + lane[l] = BaseField{ lanes[0][l], lanes[1][l], lanes[2][l], lanes[3][l] }; + prefix[l] = running; + running *= lane[l]; + } + if (running.is_zero()) { + throw_or_abort("batch_invert: attempted to invert zero"); + } + running = running.invert(); + for (size_t l = 8; l-- > 0;) { + const BaseField inv = (running * prefix[l]).reduce_once(); + running *= lane[l]; + for (size_t i = 0; i < 4; ++i) { + lanes[i][l] = inv.data[i]; + } + } + } + acc = load64(lanes[0], lanes[1], lanes[2], lanes[3]); + + // Backward: acc holds 1 / (dx_0 ... dx_s) per chain; times the prefix it gives 1 / dx_s, times dx_s it steps back + // one pair. Bounds (units of p): 1/dx, slope ~4.2; slope^2 ~4.3; x3 before reduction < 8.3; y3 < 5.4. + alignas(64) uint64_t ox[4][8]; + alignas(64) uint64_t oy[4][8]; + for (size_t k = padded; k != 0;) { + k -= 8; + const V5 inv_dx = mont_mul(acc, load52(&buf.pre[0][k], CAP)); + acc = mont_mul(acc, load52(&buf.dx[0][k], CAP)); + const V5 x1 = load64(&buf.lx[0][k], &buf.lx[1][k], &buf.lx[2][k], &buf.lx[3][k]); + const V5 y1 = load64(&buf.ly[0][k], &buf.ly[1][k], &buf.ly[2][k], &buf.ly[3][k]); + const V5 x2 = load64(&buf.rx[0][k], &buf.rx[1][k], &buf.rx[2][k], &buf.rx[3][k]); + const V5 y2 = load64(&buf.ry[0][k], &buf.ry[1][k], &buf.ry[2][k], &buf.ry[3][k]); + const V5 slope = mont_mul(sub_plus(y2, y1, C::P2), inv_dx); + const V5 x3 = canonical(sub2_plus(mont_mul(slope, slope), x1, x2, C::P4)); + const V5 y3 = canonical(sub_plus(mont_mul(slope, sub_plus(x1, x3, C::P)), y1, C::P2)); + store64(x3, ox[0], ox[1], ox[2], ox[3]); + store64(y3, oy[0], oy[1], oy[2], oy[3]); + const size_t live = std::min(8, n - k); + for (size_t l = 0; l < live; ++l) { + sink(k + l, + BaseField{ ox[0][l], ox[1][l], ox[2][l], ox[3][l] }, + BaseField{ oy[0][l], oy[1][l], oy[2][l], oy[3][l] }); + } + } +} + +// Below this many pairs the vector drain's fixed cost (lane padding, the 8-lane batch around the inversion) exceeds +// what it saves; such drains run the scalar formulas on the same queue. +inline constexpr size_t SMALL_DRAIN_MAX_PAIRS = 6; + +template +void drain_small(const DrainBuffer& buf, size_t n, Sink&& sink) +{ + const auto lhs_x = [&](size_t k) { return BaseField{ buf.lx[0][k], buf.lx[1][k], buf.lx[2][k], buf.lx[3][k] }; }; + const auto rhs_x = [&](size_t k) { return BaseField{ buf.rx[0][k], buf.rx[1][k], buf.rx[2][k], buf.rx[3][k] }; }; + std::array dxs; + std::array prefix; + BaseField acc = BaseField::one(); + for (size_t k = 0; k < n; ++k) { + dxs[k] = rhs_x(k) - lhs_x(k); + prefix[k] = acc; + acc *= dxs[k]; + } + if (acc.is_zero()) { + throw_or_abort("batch_invert: attempted to invert zero"); + } + acc = acc.invert(); + for (size_t k = n; k-- > 0;) { + const BaseField inv = acc * prefix[k]; + acc *= dxs[k]; + const BaseField x1 = lhs_x(k); + const BaseField y1{ buf.ly[0][k], buf.ly[1][k], buf.ly[2][k], buf.ly[3][k] }; + const BaseField y2{ buf.ry[0][k], buf.ry[1][k], buf.ry[2][k], buf.ry[3][k] }; + const BaseField slope = (y2 - y1) * inv; + const BaseField x3 = slope.sqr() - (x1 + rhs_x(k)); + sink(k, x3, slope * (x1 - x3) - y1); + } +} + +/** + * @brief sink(k, x3, y3) receives lhs[k] + rhs[k] (affine) for each of the n queued pairs; one shared inversion. + */ +template void drain(DrainBuffer& buf, size_t n, Sink&& sink) +{ + if (n <= SMALL_DRAIN_MAX_PAIRS) { + drain_small(buf, n, sink); + } else { + drain_vector(buf, n, sink); + } +} + +/** + * @brief out[pair_dest[k]] = lhs[k] + rhs[k] for the n queued pairs, `out` an array of affine elements. + */ +template +void drain_to(DrainBuffer& buf, size_t n, AffineElement* out) +{ + drain(buf, n, [&](size_t k, const BaseField& x, const BaseField& y) { + AffineElement& dst = out[buf.pair_dest[k]]; + dst.x = x; + dst.y = y; + }); +} + +} // namespace bb::scalar_multiplication::ifma +// NOLINTEND(cppcoreguidelines-avoid-c-arrays, cppcoreguidelines-pro-bounds-constant-array-index) + +#endif // BB_MSM_IFMA diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.test.cpp index 5a60eef..354d69f 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.test.cpp @@ -4,6 +4,7 @@ #include "barretenberg/ecc/curves/bn254/bn254.hpp" #include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" #include "barretenberg/ecc/curves/types.hpp" +#include "barretenberg/ecc/scalar_multiplication/batch_affine_ifma.hpp" #include "barretenberg/ecc/scalar_multiplication/pippenger_arena_layout.hpp" #include "barretenberg/numeric/random/engine.hpp" #include "barretenberg/polynomials/polynomial.hpp" @@ -2408,3 +2409,140 @@ TEST(ScalarMultiplication, SmallInputsExplicit) EXPECT_EQ(result, grumpkin::g1::affine_element(expected)); } + +#ifdef BB_MSM_IFMA +// The IFMA drain must produce the affine sums, fully reduced, for every batch size (scalar small-batch path, partial +// lane groups, full queue) and for operands in coarse form [p, 2p). +template void ifma_drain_matches_affine_add() +{ + using AffineElement = typename Curve::AffineElement; + using Element = typename Curve::Element; + using BaseField = typename Curve::BaseField; + if (!scalar_multiplication::ifma::ifma_available()) { + GTEST_SKIP() << "CPU lacks AVX-512 IFMA"; + } + constexpr size_t CAP = 256; + auto buf = std::make_unique>(); + const uint256_t modulus = BaseField::modulus; + // Raw (Montgomery-form) value + p, i.e. the same element in coarse form, when that stays below 2p. + const auto coarse = [&](const BaseField& f) { + const BaseField r = f.reduce_once(); + const uint256_t v = uint256_t(r.data[0], r.data[1], r.data[2], r.data[3]) + modulus; + return BaseField{ v.data[0], v.data[1], v.data[2], v.data[3] }; + }; + for (size_t n : { 1UL, 2UL, 5UL, 6UL, 7UL, 8UL, 9UL, 15UL, 16UL, 17UL, 63UL, 64UL, 65UL, 200UL, CAP }) { + std::vector lhs(n); + std::vector rhs(n); + std::vector out(2 * n); + for (size_t k = 0; k < n; ++k) { + lhs[k] = AffineElement(Element::random_element(&engine)); + rhs[k] = AffineElement(Element::random_element(&engine)); + AffineElement l = lhs[k]; + AffineElement r = rhs[k]; + if (k % 3 == 1) { + l.x = coarse(l.x); + r.y = coarse(r.y); + } + buf->push(k, l.x, l.y, r.x, r.y); + buf->pair_dest[k] = static_cast((2 * n) - 1 - (2 * k)); // scattered destinations + } + scalar_multiplication::ifma::drain_to(*buf, n, out.data()); + for (size_t k = 0; k < n; ++k) { + const AffineElement& got = out[(2 * n) - 1 - (2 * k)]; + EXPECT_EQ(got, AffineElement(Element(lhs[k]) + Element(rhs[k]))) << "n=" << n << " k=" << k; + if (n > scalar_multiplication::ifma::SMALL_DRAIN_MAX_PAIRS) { + EXPECT_LT(uint256_t(got.x.data[0], got.x.data[1], got.x.data[2], got.x.data[3]), modulus); + EXPECT_LT(uint256_t(got.y.data[0], got.y.data[1], got.y.data[2], got.y.data[3]), modulus); + } + } + } +} + +// Structured operands: consecutive multiples of the generator (small, highly correlated coordinates), negated points +// (y close to p), P + (-2P), and every coordinate in coarse form [p, 2p), across every batch-size path. +template void ifma_drain_matches_affine_add_edge_cases() +{ + using AffineElement = typename Curve::AffineElement; + using Element = typename Curve::Element; + using BaseField = typename Curve::BaseField; + if (!scalar_multiplication::ifma::ifma_available()) { + GTEST_SKIP() << "CPU lacks AVX-512 IFMA"; + } + constexpr size_t CAP = 256; + auto buf = std::make_unique>(); + const uint256_t modulus = BaseField::modulus; + const auto coarse = [&](const BaseField& f) { + const BaseField r = f.reduce_once(); + const uint256_t v = uint256_t(r.data[0], r.data[1], r.data[2], r.data[3]) + modulus; + return BaseField{ v.data[0], v.data[1], v.data[2], v.data[3] }; + }; + const Element g = Curve::Group::one; + for (size_t n : { 1UL, 6UL, 7UL, 8UL, 9UL, 31UL, 64UL, 129UL, CAP }) { + std::vector lhs(n); + std::vector rhs(n); + std::vector out(n); + Element acc = g + g; // p_k = (k + 2)·G, so no pair is a doubling or a cancellation + for (size_t k = 0; k < n; ++k) { + const AffineElement p_k(acc); + switch (k % 4) { + case 0: // P + G + lhs[k] = p_k; + rhs[k] = AffineElement(g); + break; + case 1: // -P + G: negated y + lhs[k] = -p_k; + rhs[k] = AffineElement(g); + break; + case 2: // P + (-2P) = -P + lhs[k] = p_k; + rhs[k] = AffineElement(-(acc + acc)); + break; + default: // P + random + lhs[k] = p_k; + rhs[k] = AffineElement(Element::random_element(&engine)); + break; + } + acc += g; + AffineElement l = lhs[k]; + AffineElement r = rhs[k]; + if (k % 2 == 0) { + l.x = coarse(l.x); + l.y = coarse(l.y); + r.x = coarse(r.x); + r.y = coarse(r.y); + } + for (size_t i = 0; i < 4; ++i) { + buf->lx[i][k] = l.x.data[i]; + buf->ly[i][k] = l.y.data[i]; + buf->rx[i][k] = r.x.data[i]; + buf->ry[i][k] = r.y.data[i]; + } + buf->pair_dest[k] = static_cast(k); + } + scalar_multiplication::ifma::drain_to(*buf, n, out.data()); + for (size_t k = 0; k < n; ++k) { + EXPECT_EQ(out[k], AffineElement(Element(lhs[k]) + Element(rhs[k]))) << "n=" << n << " k=" << k; + } + } +} + +TEST(ScalarMultiplicationIfma, DrainEdgeCasesBn254) +{ + ifma_drain_matches_affine_add_edge_cases(); +} + +TEST(ScalarMultiplicationIfma, DrainEdgeCasesGrumpkin) +{ + ifma_drain_matches_affine_add_edge_cases(); +} + +TEST(ScalarMultiplicationIfma, DrainMatchesAffineAddBn254) +{ + ifma_drain_matches_affine_add(); +} + +TEST(ScalarMultiplicationIfma, DrainMatchesAffineAddGrumpkin) +{ + ifma_drain_matches_affine_add(); +} +#endif 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..de980ed 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 @@ -1,5 +1,6 @@ #include "./scalar_multiplication_fast.hpp" +#include "./batch_affine_ifma.hpp" #include "./pippenger_arena_layout.hpp" #include "./pippenger_constantine.hpp" #include "./pippenger_dedup.hpp" @@ -294,8 +295,231 @@ 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; +} + +#ifdef BB_MSM_IFMA +// Pairs per IFMA drain. The queue (operands held limb-major for the vector kernel) lives in a per-thread heap buffer +// rather than in the MSM arena, so the arena layout is the same with and without IFMA. +inline constexpr size_t IFMA_BATCH_CAPACITY = 256; + +inline ifma::DrainBuffer& ifma_drain_buffer() +{ + static thread_local std::unique_ptr> thread_buffer; + if (!thread_buffer) { + thread_buffer = std::make_unique>(); + } + return *thread_buffer; +} + +/** + * @brief tree_reduce_in_place's level walk with the batch-affine drain run by the AVX-512 IFMA kernel + * (`ifma::drain`). Identical pairing and compaction; only the drain arithmetic differs. + */ +template void tree_reduce_in_place_ifma(ThreadScratch& s, size_t initial_len) noexcept +{ + using BaseField = typename Curve::BaseField; + using AffineElement = typename Curve::AffineElement; + auto& buf = ifma_drain_buffer(); + AffineElement* pts = s.curr_pts.data(); + 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]) { + buf.push(pair_count, pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y); + s.curr_buckets[next_len] = s.curr_buckets[i]; + buf.pair_dest[pair_count] = static_cast(next_len); + ++next_len; + ++pair_count; + i += 2; + made_pair = true; + + if (pair_count >= IFMA_BATCH_CAPACITY) { + ifma::drain_to(buf, pair_count, pts); + pair_count = 0; + } + } else { + pts[next_len] = pts[i]; + s.curr_buckets[next_len] = s.curr_buckets[i]; + ++next_len; + ++i; + } + } + + if (pair_count > 0) { + ifma::drain_to(buf, pair_count, pts); + } + + if (!made_pair) { + break; + } + + curr_len = next_len; + } + + s.result_len = curr_len; +} + +/** + * @brief Stage 6b twin of batch_affine_add_indexed_scalar on the IFMA drain: (x, y)[dst] += (x, y)[src] for every + * (dst, src) pair, one inversion per IFMA_BATCH_CAPACITY pairs. + * + * @details Same preconditions as the scalar kernel (distinct x per pair, distinct dst indices, dst set disjoint from + * src set), so draining in chunks never reads a slot an earlier chunk wrote. + */ +template +void batch_affine_add_indexed_ifma(BaseField* x, + BaseField* y, + const std::pair* pairs, + size_t num_pairs) noexcept +{ + auto& buf = ifma_drain_buffer(); + for (size_t base = 0; base < num_pairs; base += IFMA_BATCH_CAPACITY) { + const size_t n = std::min(IFMA_BATCH_CAPACITY, num_pairs - base); + const auto* chunk = pairs + base; + for (size_t k = 0; k < n; ++k) { + const auto [dst, src] = chunk[k]; + buf.push(k, x[src], y[src], x[dst], y[dst]); + } + ifma::drain(buf, n, [&](size_t k, const BaseField& x3, const BaseField& y3) { + x[chunk[k].first] = x3; + y[chunk[k].first] = y3; + }); + } +} +#endif + 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) { +#ifdef BB_MSM_IFMA + if constexpr (ifma::Consts::supported) { + if (ifma::ifma_available()) { + tree_reduce_in_place_ifma(s, initial_len); + return; + } + } +#endif + 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 @@ -719,6 +943,14 @@ void recursive_affine_bucket_reduce_strided(ThreadScratch& s, return; } } +#ifdef BB_MSM_IFMA + if constexpr (ifma::Consts::supported) { + if (ifma::ifma_available()) { + batch_affine_add_indexed_ifma(dense_x, dense_y, reals, count); + return; + } + } +#endif bb::group_elements::batch_affine_add_indexed_scalar(s.dense_buckets, reals, count, inv_scratch); }; auto batched_double = [&](size_t count) { diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm.test.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm.test.cpp index 7dc9b5e..a4470c3 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm.test.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm.test.cpp @@ -660,3 +660,89 @@ TEST_F(ECCVMTests, WitnessPolynomialsMasked) check_masked(polynomials.z_perm, "z_perm"); check_masked(polynomials.lookup_inverses, "lookup_inverses"); } + +/** + * @brief The narrow row getters used by the grand product and log-derivative inverse computations read every column + * their relations use (for both the full and the short-monomial relations): on every row they produce the same + * relation values as the full get_row, and every row at or beyond the grand product zero-row start produces the values + * of that start row. + */ +TEST_F(ECCVMTests, NarrowRowGettersMatchFullRow) +{ + ECCVMCircuitBuilder builder = generate_circuit(&engine); + ECCVMFlavor::ProverPolynomials polynomials(builder); + const auto params = RelationParameters::get_random(); + const size_t num_rows = polynomials.get_polynomial_size(); + const size_t zero_row_start = polynomials.get_grand_product_zero_row_start(); + EXPECT_LT(zero_row_start, num_rows); + + const auto check_relations = [&]() { + using SetAccumulator = std::tuple_element_t<0, typename SetRelation::SumcheckArrayOfValuesOverSubrelations>; + using LookupAccumulator = typename LookupRelation::ValueAccumulator0; + const auto set_values = [&](const auto& row) { + return std::array{ + SetRelation::template compute_grand_product_numerator(row, params), + SetRelation::template compute_grand_product_denominator(row, params) + }; + }; + const auto lookup_values = [&](const auto& row) { + std::array values; + values[0] = FF(static_cast(LookupRelation::operation_exists_at_row(row))); + bb::constexpr_for<0, LookupRelation::NUM_LOOKUP_TERMS, 1>([&]() { + values[1 + i] = LookupRelation::template compute_lookup_term(row, params); + }); + bb::constexpr_for<0, LookupRelation::NUM_TABLE_TERMS, 1>([&]() { + values[1 + LookupRelation::NUM_LOOKUP_TERMS + i] = + LookupRelation::template compute_table_term(row, params); + }); + return values; + }; + + const auto zero_row_values = set_values(polynomials.get_row_for_grand_product(zero_row_start)); + for (size_t row_idx = 0; row_idx < num_rows; ++row_idx) { + const auto full_row = polynomials.get_row(row_idx); + const auto full_set_values = set_values(full_row); + ASSERT_EQ(full_set_values, set_values(polynomials.get_row_for_grand_product(row_idx))) << "row " << row_idx; + ASSERT_EQ(lookup_values(full_row), lookup_values(polynomials.get_row_for_logderivative_inverse(row_idx))) + << "row " << row_idx; + if (row_idx >= zero_row_start) { + ASSERT_EQ(full_set_values, zero_row_values) << "row " << row_idx; + } + } + }; + check_relations.template operator(), ECCVMFlavor::LookupRelation>(); + check_relations.template operator(), ECCVMShortMonomialFlavor::LookupRelation>(); +} + +/** + * @brief The ECCVM prover's grand product and log-derivative inverses (narrow rows, zero-tail extension) equal the + * generic full-row computations. + */ +TEST_F(ECCVMTests, ProverGrandProductAndInversesMatchGeneric) +{ + using Flavor = ECCVMShortMonomialFlavor; + ECCVMCircuitBuilder builder = generate_circuit(&engine); + Flavor::ProverPolynomials polynomials(builder); + auto params = RelationParameters::get_random(); + const size_t num_rows = polynomials.get_polynomial_size(); + + compute_logderivative_inverse( + polynomials, params, Flavor::TRACE_OFFSET); + const Polynomial expected_inverses = polynomials.lookup_inverses.full(); + compute_grand_products(polynomials, params); + const Polynomial expected_z_perm = polynomials.z_perm.full(); + + for (size_t i = Flavor::TRACE_OFFSET; i < num_rows; ++i) { + polynomials.lookup_inverses.at(i) = 0; + polynomials.z_perm.at(i) = 0; + } + Flavor::LogDerivativeInverseView lookup_view{ polynomials, polynomials.lookup_inverses }; + compute_logderivative_inverse( + lookup_view, params, Flavor::TRACE_OFFSET); + ECCVMProver::compute_grand_product(polynomials, params); + + for (size_t i = 0; i < num_rows; ++i) { + ASSERT_EQ(polynomials.lookup_inverses.get(i), expected_inverses[i]) << "row " << i; + ASSERT_EQ(polynomials.z_perm.get(i), expected_z_perm[i]) << "row " << i; + } +} diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_flavor.hpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_flavor.hpp index 634ea78..d307949 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_flavor.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_flavor.hpp @@ -556,6 +556,105 @@ class ECCVMFlavor { */ using ExtendedEdges = ProverUnivariates; + /** + * @brief The entities read by the numerator and denominator of ECCVMSetRelation. + */ + template static auto get_grand_product_entities(Entities& entities) + { + return RefArray{ entities.lagrange_first, + entities.msm_accumulator_x_shift, + entities.msm_accumulator_y_shift, + entities.msm_add1, + entities.msm_add2, + entities.msm_add3, + entities.msm_add4, + entities.msm_count, + entities.msm_pc, + entities.msm_pc_shift, + entities.msm_round, + entities.msm_size_of_msm, + entities.msm_slice1, + entities.msm_slice2, + entities.msm_slice3, + entities.msm_slice4, + entities.msm_transition_shift, + entities.precompute_pc, + entities.precompute_point_transition, + entities.precompute_round, + entities.precompute_s1hi, + entities.precompute_s1lo, + entities.precompute_s2hi, + entities.precompute_s2lo, + entities.precompute_s3hi, + entities.precompute_s3lo, + entities.precompute_s4hi, + entities.precompute_s4lo, + entities.precompute_scalar_sum, + entities.precompute_select, + entities.precompute_skew, + entities.precompute_tx, + entities.precompute_ty, + entities.transcript_Px, + entities.transcript_Py, + entities.transcript_base_infinity, + entities.transcript_msm_count, + entities.transcript_msm_transition, + entities.transcript_msm_x, + entities.transcript_msm_y, + entities.transcript_mul, + entities.transcript_pc, + entities.transcript_pc_shift, + entities.transcript_z1, + entities.transcript_z1zero, + entities.transcript_z2, + entities.transcript_z2zero }; + } + + /** + * @brief The entities read by ECCVMLookupRelation when computing the log-derivative inverses (operation + * existence, lookup terms and table terms). + */ + template static auto get_logderivative_inverse_entities(Entities& entities) + { + return RefArray{ entities.msm_add, + entities.msm_skew, + entities.msm_pc, + entities.msm_count, + entities.msm_slice1, + entities.msm_slice2, + entities.msm_slice3, + entities.msm_slice4, + entities.msm_x1, + entities.msm_x2, + entities.msm_x3, + entities.msm_x4, + entities.msm_y1, + entities.msm_y2, + entities.msm_y3, + entities.msm_y4, + entities.precompute_select, + entities.precompute_pc, + entities.precompute_tx, + entities.precompute_ty, + entities.precompute_round }; + } + + /** + * @brief Returns the first row index from which every given polynomial is zero. + */ + static size_t get_zero_row_start(const auto& polynomials) + { + size_t zero_row_start = 0; + for (const Polynomial& polynomial : polynomials) { + size_t end = polynomial.end_index(); + while (end > zero_row_start && end > polynomial.start_index() && polynomial.get(end - 1).is_zero()) { + --end; + } + zero_row_start = std::max(zero_row_start, end); + } + return zero_row_start; + } + /** * @brief A container for the prover polynomials. */ @@ -585,6 +684,44 @@ class ECCVMFlavor { } return result; } + /** + * @brief Returns, at one point of the boolean hypercube, only the evaluations read by the numerator and + * denominator of ECCVMSetRelation (the grand product computation). All other entries of the returned AllValues + * are left uninitialized. + */ + [[nodiscard]] AllValues get_row_for_grand_product(const size_t row_idx) const + { + AllValues result; + for (auto [result_field, polynomial] : + zip_view(get_grand_product_entities(result), get_grand_product_entities(*this))) { + result_field = polynomial.get(row_idx); + } + return result; + } + + /** + * @brief Returns the first row index from which every polynomial read by get_row_for_grand_product is zero. + * All rows at or beyond it are identical, so they share one grand product numerator and denominator. + */ + [[nodiscard]] size_t get_grand_product_zero_row_start() const + { + return get_zero_row_start(get_grand_product_entities(*this)); + } + + /** + * @brief Returns, at one point of the boolean hypercube, only the evaluations read by ECCVMLookupRelation when + * computing the log-derivative inverses. All other entries of the returned AllValues are left uninitialized. + */ + [[nodiscard]] AllValues get_row_for_logderivative_inverse(const size_t row_idx) const + { + AllValues result; + for (auto [result_field, polynomial] : + zip_view(get_logderivative_inverse_entities(result), get_logderivative_inverse_entities(*this))) { + result_field = polynomial.get(row_idx); + } + return result; + } + // Set all shifted polynomials based on their to-be-shifted counterpart void set_shifted() { @@ -940,6 +1077,20 @@ class ECCVMFlavor { } }; + /** + * @brief The prover polynomials as seen by compute_logderivative_inverse: rows carry only the columns that + * ECCVMLookupRelation reads to compute the inverses. + */ + struct LogDerivativeInverseView { + const ProverPolynomials& polynomials; + Polynomial& lookup_inverses; + + [[nodiscard]] AllValues get_row(const size_t row_idx) const + { + return polynomials.get_row_for_logderivative_inverse(row_idx); + } + }; + /** * @brief A container for storing the partially evaluated multivariates produced by sumcheck. */ diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp index 6f79c03..b27cb55 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.cpp @@ -112,12 +112,13 @@ void ECCVMProver::execute_log_derivative_commitments_round() (gamma + beta_sqr + beta_sqr + first_term_tag) * (gamma + beta_sqr + beta_sqr + beta_sqr + first_term_tag); relation_parameters.eccvm_set_permutation_delta = relation_parameters.eccvm_set_permutation_delta.invert(); - // Compute inverse polynomial for our logarithmic-derivative lookup method - // Skip the disabled head region to preserve masking values + // Compute inverse polynomial for our logarithmic-derivative lookup method, fetching only the columns the lookup + // relation reads. Skip the disabled head region to preserve masking values + typename Flavor::LogDerivativeInverseView lookup_view{ key->polynomials, key->polynomials.lookup_inverses }; compute_logderivative_inverse(key->polynomials, relation_parameters, Flavor::TRACE_OFFSET); + typename Flavor::LogDerivativeInverseView, + true>(lookup_view, relation_parameters, Flavor::TRACE_OFFSET); auto& li = key->polynomials.lookup_inverses; commitments.lookup_inverses = key->commitment_key.commit(li); transcript->send_to_verifier(commitment_labels.lookup_inverses, commitments.lookup_inverses); @@ -131,13 +132,47 @@ void ECCVMProver::execute_grand_product_computation_round() { BB_BENCH_NAME("ECCVMProver::execute_grand_product_computation_round"); // Compute permutation grand product (starts after disabled head region via gp_start) - compute_grand_products(key->polynomials, relation_parameters); + compute_grand_product(key->polynomials, relation_parameters); auto& zp = key->polynomials.z_perm; // set has_duplicates_hint for Z_PERM (empty row = duplicate Z value) commitments.z_perm = key->commitment_key.commit(zp, /*has_duplicates_hint=*/true); transcript->send_to_verifier(commitment_labels.z_perm, commitments.z_perm); } +/** + * @brief Compute the z_perm grand product of the ECCVMSetRelation. + * @details Every row from `get_grand_product_zero_row_start()` on reads only zeros, so all of them share one + * numerator/denominator ratio r. The generic grand product is computed up to the first such row, and the rest of z_perm + * is extended from there by z_perm[i] = z_perm[i - 1] * r, which is the same field element the generic computation + * produces. + */ +void ECCVMProver::compute_grand_product(Flavor::ProverPolynomials& polynomials, + bb::RelationParameters& relation_parameters) +{ + using GrandProductRelation = std::tuple_element_t<0, Flavor::GrandProductRelations>; + using Accumulator = std::tuple_element_t<0, typename GrandProductRelation::SumcheckArrayOfValuesOverSubrelations>; + static_assert(std::tuple_size_v == 1); + + const size_t domain_size = polynomials.get_polynomial_size(); + const size_t zero_row_start = std::max(polynomials.get_grand_product_zero_row_start(), Flavor::TRACE_OFFSET + 1); + if (zero_row_start + 1 >= domain_size) { + compute_grand_products(polynomials, relation_parameters); + return; + } + // z_perm[i] is fixed by rows < i, so z_perm[0..zero_row_start] needs only rows before the zero rows. + compute_grand_products(polynomials, relation_parameters, /*size_override=*/zero_row_start + 1); + + const auto zero_row = polynomials.get_row_for_grand_product(zero_row_start); + const FF ratio = + GrandProductRelation::template compute_grand_product_numerator(zero_row, relation_parameters) * + GrandProductRelation::template compute_grand_product_denominator(zero_row, relation_parameters) + .invert(); + auto& z_perm = polynomials.z_perm; + for (size_t i = zero_row_start + 1; i < domain_size; ++i) { + z_perm.at(i) = z_perm[i - 1] * ratio; + } +} + /** * @brief Run Sumcheck resulting in u = (u_1,...,u_d) challenges and all evaluations at u being calculated. * diff --git a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp index 03bd00e..822cb64 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/eccvm_prover.hpp @@ -53,6 +53,9 @@ class ECCVMProver { Proof export_proof(); Proof construct_proof(); + static void compute_grand_product(Flavor::ProverPolynomials& polynomials, + bb::RelationParameters& relation_parameters); + // The ECCVM PCS pipeline collects all univariate opening claims, reduces them with one Shplonk, then opens the // sumcheck multilinears and reduced univariate claim with TripleIPA. void append_libra_opening_claims(); diff --git a/barretenberg/cpp/src/barretenberg/eccvm/msm_builder.hpp b/barretenberg/cpp/src/barretenberg/eccvm/msm_builder.hpp index bf4094b..003ed50 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/msm_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/msm_builder.hpp @@ -261,8 +261,9 @@ class ECCVMMSMMBuilder { std::span p3_trace(&points_to_normalize[num_point_adds_and_doubles * 2], num_point_adds_and_doubles); // `is_double_or_add` records whether an entry in the p1/p2/p3 trace represents a point addition or // doubling. if it is `true`, then we are doubling (i.e., the condition is that `p3 = p1.dbl()`), else we are - // adding (i.e., the condition is that `p3 = p1 + p2`). - std::vector is_double_or_add(num_point_adds_and_doubles); + // adding (i.e., the condition is that `p3 = p1 + p2`). One byte per entry, so that MSMs filled in parallel + // never write to a shared word. + std::vector is_double_or_add(num_point_adds_and_doubles); // accumulator_trace tracks the value of the ECCVM accumulator for each row std::span accumulator_trace(&points_to_normalize[num_point_adds_and_doubles * 3], num_accumulators); @@ -270,10 +271,10 @@ class ECCVMMSMMBuilder { constexpr auto offset_generator = get_precomputed_generators()[0]; accumulator_trace[0] = offset_generator; - // TODO(https://github.com/AztecProtocol/barretenberg/issues/973): Reinstate multitreading? // populate point trace, and the components of the MSM execution trace that do not relate to affine point - // operations - for (size_t msm_idx = 0; msm_idx < msms.size(); msm_idx++) { + // operations. Each MSM starts from the offset generator and owns a disjoint range of rows and trace entries, + // so the MSMs are processed in parallel. + parallel_for(msms.size(), [&](size_t msm_idx) { Element accumulator = offset_generator; // for every MSM, we start with the same `offset_generator` const auto& msm = msms[msm_idx]; // which MSM we are processing. This is of type `std::vector`. size_t msm_row_index = msm_row_counts[msm_idx]; // the row where the given MSM starts @@ -327,7 +328,7 @@ class ECCVMMSMMBuilder { p1_trace[trace_index] = p1; p2_trace[trace_index] = p2; p3_trace[trace_index] = accumulator; - is_double_or_add[trace_index] = false; + is_double_or_add[trace_index] = 0; trace_index++; } // Now, `row.add_state` has been fully processed and we fill in the rest of the members of `row`. @@ -367,7 +368,7 @@ class ECCVMMSMMBuilder { p2_trace[trace_index] = accumulator; // dummy accumulator = accumulator.dbl(); p3_trace[trace_index] = accumulator; - is_double_or_add[trace_index] = true; + is_double_or_add[trace_index] = 1; trace_index++; } accumulator_trace[msm_row_index] = accumulator; @@ -401,7 +402,7 @@ class ECCVMMSMMBuilder { p1_trace[trace_index] = p1; p2_trace[trace_index] = add_state.point; p3_trace[trace_index] = accumulator; - is_double_or_add[trace_index] = false; + is_double_or_add[trace_index] = 0; trace_index++; } row.q_add = false; @@ -416,7 +417,7 @@ class ECCVMMSMMBuilder { } } } - } + }); // Normalize the points in the point trace parallel_for_range(points_to_normalize.size(), [&](size_t start, size_t end) { @@ -441,7 +442,7 @@ class ECCVMMSMMBuilder { // complete the computation of the ECCVM execution trace, by adding the affine intermediate point data // i.e. row.accumulator_x, row.accumulator_y, row.add_state[0...3].collision_inverse, // row.add_state[0...3].lambda - for (size_t msm_idx = 0; msm_idx < msms.size(); msm_idx++) { + parallel_for(msms.size(), [&](size_t msm_idx) { const auto& msm = msms[msm_idx]; size_t trace_index = ((msm_row_counts[msm_idx] - 1) * ADDITIONS_PER_ROW); size_t msm_row_index = msm_row_counts[msm_idx]; @@ -522,7 +523,7 @@ class ECCVMMSMMBuilder { } } } - } + }); // populate the final row in the MSM execution trace. // we always require 1 extra row at the end of the trace, because the x and y coordinates of the accumulator for diff --git a/barretenberg/cpp/src/barretenberg/eccvm/transcript_builder.hpp b/barretenberg/cpp/src/barretenberg/eccvm/transcript_builder.hpp index 8964f5d..b90982b 100644 --- a/barretenberg/cpp/src/barretenberg/eccvm/transcript_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/eccvm/transcript_builder.hpp @@ -7,6 +7,7 @@ #pragma once #include "./eccvm_builder_types.hpp" +#include "barretenberg/common/thread.hpp" #include "barretenberg/ecc/groups/precomputed_generators_bn254_impl.hpp" #include "barretenberg/op_queue/ecc_ops_table.hpp" @@ -191,6 +192,17 @@ class ECCVMTranscriptBuilder { msm_count_at_transition_inverse_trace[0] = 0; } + // The scalar multiplications P * mul_scalar_full do not depend on the VM state, so compute them up front in + // parallel; the sequential pass below only accumulates them. + std::vector mul_products(num_vm_entries); + parallel_for_range(num_vm_entries, [&](size_t start, size_t end) { + for (size_t i = std::max(start, 1); i < end; ++i) { + if (vm_operations[i].op_code.mul) { + mul_products[i] = Element(vm_operations[i].base_point) * vm_operations[i].mul_scalar_full; + } + } + }); + // during the first iteration over the ECCOpQueue, the operations are being performed using Jacobian (a.k.a. // projective) coordinates and the base point coordinates are recorded in the transcript. at the same time, the // transcript logic is being populated (starting from index 1, since index 0 is the hiding op handled above) @@ -243,7 +255,7 @@ class ECCVMTranscriptBuilder { // then finally if this is an add. note that this mutates `updated_state`. (note that the middle option // depends on the first.) if (is_mul) { - process_mul(entry, updated_state, state); + process_mul(mul_products[i], updated_state, state); } if (msm_transition) { @@ -398,19 +410,17 @@ class ECCVMTranscriptBuilder { /** * @brief Process scalar multiplication from the ECCOpQueue. * - * @details If the entry indicates a multiplication operation, the - * base point from the ECCOpQueue is multiplied by the corresponding full scalar. The result is added to the - * 'msm_accumulator' field of the updated state. + * @details If the entry indicates a multiplication operation, the product of its base point and full scalar is + * added to the 'msm_accumulator' field of the updated state. * - * @param entry Current ECCOpQueue entry + * @param mul_product The base point of the current ECCOpQueue entry multiplied by its full scalar * @param updated_state The state of the ECCVM to be updated with the result of the multiplication * @param state The current state of the ECCVM */ - static void process_mul(const ECCVMOperation& entry, VMState& updated_state, const VMState& state) + static void process_mul(const Element& mul_product, VMState& updated_state, const VMState& state) { - const auto P = typename CycleGroup::element(entry.base_point); const auto R = typename CycleGroup::element(state.msm_accumulator); - updated_state.msm_accumulator = R + P * entry.mul_scalar_full; + updated_state.msm_accumulator = R + mul_product; } /** diff --git a/barretenberg/cpp/src/barretenberg/flavor/partially_evaluated_multivariates.hpp b/barretenberg/cpp/src/barretenberg/flavor/partially_evaluated_multivariates.hpp index 07db6c3..9696cb3 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/partially_evaluated_multivariates.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/partially_evaluated_multivariates.hpp @@ -6,6 +6,7 @@ #pragma once #include "barretenberg/common/zip_view.hpp" +#include "barretenberg/polynomials/fold_stride2.hpp" #include "barretenberg/polynomials/polynomial.hpp" namespace bb { @@ -30,20 +31,44 @@ class PartiallyEvaluatedMultivariatesBase : public AllEntitiesBase { size_t row_skip_active_prefix_end = 0; /** - * @brief Construct from full polynomials, allocating based on their actual sizes. - * @details After the initial sumcheck round, the new size is CEIL(size/2). + * @brief Construct from full polynomials, allocating based on their actual backed ranges. + * @details After `num_folds` (1 or 2) sumcheck rounds, a polynomial backed on [start, end) is backed on + * [FLOOR(start/2^num_folds), CEIL(end/2^num_folds)). */ - PartiallyEvaluatedMultivariatesBase(const ProverPolynomialsType& full_polynomials, size_t circuit_size) + PartiallyEvaluatedMultivariatesBase(const ProverPolynomialsType& full_polynomials, + size_t circuit_size, + size_t num_folds = 1) { + BB_ASSERT(num_folds == 1 || num_folds == 2); for (auto [poly, full_poly] : zip_view(this->get_all(), full_polynomials.get_all())) { - // After the initial sumcheck round, the new size is CEIL(size/2). - size_t desired_size = (full_poly.end_index() / 2) + (full_poly.end_index() % 2); - // partially_evaluate writes to [0, desired_size) before any read; backing memory can be left uninitialized. - poly = Polynomial(desired_size, circuit_size / 2, 0, Polynomial::DontZeroMemory::FLAG); + const auto [start, end] = + num_folds == 1 ? folded_backed_range(full_poly) : twice_folded_backed_range(full_poly); + // partially_evaluate writes to [start, end) before any read; backing memory can be left uninitialized. + poly = Polynomial(end - start, circuit_size / 2, start, Polynomial::DontZeroMemory::FLAG); } if constexpr (requires { full_polynomials.row_skip_active_prefix_end; }) { - row_skip_active_prefix_end = - (full_polynomials.row_skip_active_prefix_end / 2) + (full_polynomials.row_skip_active_prefix_end % 2); + row_skip_active_prefix_end = full_polynomials.row_skip_active_prefix_end; + for (size_t fold = 0; fold < num_folds; fold++) { + row_skip_active_prefix_end = (row_skip_active_prefix_end / 2) + (row_skip_active_prefix_end % 2); + } + } + } +}; + +/** + * @brief The prover polynomials folded at the first sumcheck challenge, as `FoldedPolynomialView`s computed on access. + * @details Lets the second sumcheck round read the first round's partial evaluations without materializing them; the + * tables are then built directly after two folds (see SumcheckProver::partially_evaluate_first_two_rounds). + * + * @tparam AllViewsBase The AllEntities> type from the flavor + */ +template +class FoldedMultivariatesBase : public AllViewsBase { + public: + FoldedMultivariatesBase(const ProverPolynomialsType& full_polynomials, const FF& challenge) + { + for (auto [view, full_poly] : zip_view(this->get_all(), full_polynomials.get_all())) { + view = FoldedPolynomialView(full_poly, challenge); } } }; diff --git a/barretenberg/cpp/src/barretenberg/honk/execution_trace/execution_trace_block.hpp b/barretenberg/cpp/src/barretenberg/honk/execution_trace/execution_trace_block.hpp index 5191c40..e86fe25 100644 --- a/barretenberg/cpp/src/barretenberg/honk/execution_trace/execution_trace_block.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/execution_trace/execution_trace_block.hpp @@ -802,6 +802,9 @@ template class ExecutionTraceBlockStorage { */ void free_data() { + if (data_freed_) { + return; + } cached_size_ = num_rows_; data_freed_ = true; tiles.clear(); 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..ed75285 100644 --- a/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/library/grand_product_library.hpp @@ -13,6 +13,7 @@ #include "barretenberg/constants.hpp" #include "barretenberg/flavor/flavor.hpp" +#include "barretenberg/relations/permutation_relation.hpp" #include "barretenberg/relations/relation_parameters.hpp" #include "barretenberg/trace_to_polynomials/trace_to_polynomials.hpp" @@ -59,10 +60,9 @@ namespace bb { * B(h) * * Step 1) Compute 2 length-n polynomials A, B - * Step 2) Compute 2 length-n polynomials numerator = ∏ A(j), denominator = ∏ B(j) - * Step 3) Compute Z_perm[i + 1] = numerator[i] / denominator[i] - * - * Note: Step (3) utilizes Montgomery batch inversion, performed at the end of Step (2). + * Step 2) Compute the ratios A(j) / B(j) (Montgomery batch inversion of B) and their running products per thread + * Step 3) Compute Z_perm[i + 1] = ∏_{j<=i} A(j) / B(j) by scaling each thread's running products by the products of + * the preceding threads * * @tparam Flavor * @tparam GrandProdRelation @@ -122,8 +122,20 @@ void compute_grand_product(typename Flavor::ProverPolynomials& full_polynomials, for (size_t i = start; i < end; ++i) { const size_t poly_idx = i + gp_start; // TODO: consider avoiding get_row if possible. - if constexpr (IsUltraOrMegaHonk) { - row = full_polynomials.get_row_for_permutation_arg(poly_idx); + if constexpr (std::is_same_v>) { + // Write the permutation argument's columns (wires, ids, sigmas) straight into the reused row + // rather than building and copying a whole row; the relation reads no other entries. + for (auto [row_value, polynomial] : zip_view(row.get_wires(), full_polynomials.get_wires())) { + row_value = polynomial[poly_idx]; + } + for (auto [row_value, polynomial] : zip_view(row.get_ids(), full_polynomials.get_ids())) { + row_value = polynomial[poly_idx]; + } + for (auto [row_value, polynomial] : zip_view(row.get_sigmas(), full_polynomials.get_sigmas())) { + row_value = polynomial[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); } @@ -152,70 +164,53 @@ void compute_grand_product(typename Flavor::ProverPolynomials& full_polynomials, DEBUG_LOG_ALL(denominator.coeffs()); // Step (2) - // Compute the accumulating product of the numerator and denominator terms. - // This step is split into three parts for efficient multithreading: - // (i) compute ∏ A(j), ∏ B(j) subproducts for each thread - // (ii) compute scaling factor required to convert each subproduct into a single running product - // (ii) combine subproducts into a single running product + // Compute the running product of the ratios numerator[i] / denominator[i]. + // This step is split into two parts for efficient multithreading: + // (i) each thread batch-inverts its slice of the denominator and overwrites its slice of the numerator with the + // running product of the ratios over the slice + // (ii) (in Step 3) each thread scales its running products by the product of the preceding threads' totals // - // For example, consider 4 threads and a size-8 numerator { a0, a1, a2, a3, a4, a5, a6, a7 } - // (i) Each thread computes 1 element of N = {{ a0, a0a1 }, { a2, a2a3 }, { a4, a4a5 }, { a6, a6a7 }} - // (ii) Take partial products P = { 1, a0a1, a2a3, a4a5 } - // (iii) Each thread j computes N[i][j]*P[j]= - // {{a0,a0a1},{a0a1a2,a0a1a2a3},{a0a1a2a3a4,a0a1a2a3a4a5},{a0a1a2a3a4a5a6,a0a1a2a3a4a5a6a7}} - std::vector partial_numerators(thread_data.num_threads); - std::vector partial_denominators(thread_data.num_threads); - - parallel_for(thread_data.num_threads, [&](size_t thread_idx) { - BB_BENCH_TRACY_NAME("GrandProduct::step2a_subproducts"); - const size_t start = thread_data.start[thread_idx]; - const size_t end = thread_data.end[thread_idx]; - for (size_t i = start; i < end - 1; ++i) { - numerator.at(i + 1) *= numerator[i]; - denominator.at(i + 1) *= denominator[i]; - } - partial_numerators[thread_idx] = numerator[end - 1]; - partial_denominators[thread_idx] = denominator[end - 1]; - }); - - DEBUG_LOG_ALL(partial_numerators); - DEBUG_LOG_ALL(partial_denominators); + // For example, consider 4 threads and size-8 ratios { r0, r1, r2, r3, r4, r5, r6, r7 } + // (i) Each thread computes 2 elements of N = {{ r0, r0r1 }, { r2, r2r3 }, { r4, r4r5 }, { r6, r6r7 }} + // (ii) Each thread j computes N[j][i] * ∏_{k partial_products(thread_data.num_threads); parallel_for(thread_data.num_threads, [&](size_t thread_idx) { - BB_BENCH_TRACY_NAME("GrandProduct::step2b_scale_and_invert"); + BB_BENCH_TRACY_NAME("GrandProduct::step2_ratio_subproducts"); const size_t start = thread_data.start[thread_idx]; const size_t end = thread_data.end[thread_idx]; - if (thread_idx > 0) { - FF numerator_scaling = 1; - FF denominator_scaling = 1; - - for (size_t j = 0; j < thread_idx; ++j) { - numerator_scaling *= partial_numerators[j]; - denominator_scaling *= partial_denominators[j]; - } - for (size_t i = start; i < end; ++i) { - numerator.at(i) = numerator[i] * numerator_scaling; - denominator.at(i) = denominator[i] * denominator_scaling; - } - } - - // Final step: invert denominator FF::batch_invert(std::span{ &denominator.data()[start], end - start }); + numerator.at(start) *= denominator[start]; + for (size_t i = start + 1; i < end; ++i) { + numerator.at(i) = numerator[i] * denominator[i] * numerator[i - 1]; + } + partial_products[thread_idx] = numerator[end - 1]; }); + DEBUG_LOG_ALL(partial_products); DEBUG_LOG_ALL(numerator.coeffs()); - DEBUG_LOG_ALL(denominator.coeffs()); // Step (3) Compute grand_product_polynomial[i] = numerator[i] / denominator[i] // The caller initializes z_perm[gp_start] = 0; lagrange_first supplies the initial 1 in the relation. - // Compute grand product values: z_perm[gp_start + i + 1] = numerator[i] / denominator[i] + // Compute grand product values: z_perm[gp_start + i + 1] = running product of the ratios up to row i parallel_for(thread_data.num_threads, [&](size_t thread_idx) { - BB_BENCH_TRACY_NAME("GrandProduct::step3_quotient"); + BB_BENCH_TRACY_NAME("GrandProduct::step3_scale"); const size_t start = thread_data.start[thread_idx]; const size_t end = thread_data.end[thread_idx]; + if (thread_idx == 0) { + for (size_t i = start; i < end; ++i) { + grand_product_polynomial.at(gp_start + i + 1) = numerator[i]; + } + return; + } + FF scaling = partial_products[0]; + for (size_t j = 1; j < thread_idx; ++j) { + scaling *= partial_products[j]; + } for (size_t i = start; i < end; ++i) { - grand_product_polynomial.at(gp_start + i + 1) = numerator[i] * denominator[i]; + grand_product_polynomial.at(gp_start + i + 1) = numerator[i] * scaling; } }); diff --git a/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp index 858412c..87c29ef 100644 --- a/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp @@ -14,6 +14,7 @@ #include "barretenberg/common/thread.hpp" #include "barretenberg/common/tuple.hpp" +#include #include #include @@ -31,7 +32,10 @@ namespace bb { * */ template -void compute_logderivative_inverse(Polynomials& polynomials, auto& relation_parameters, const size_t start_index = 0) +void compute_logderivative_inverse(Polynomials& polynomials, + auto& relation_parameters, + const size_t start_index = 0, + const size_t end_index = std::numeric_limits::max()) { BB_BENCH_NAME("compute_logderivative_inverse"); using Accumulator = typename Relation::ValueAccumulator0; @@ -41,7 +45,8 @@ void compute_logderivative_inverse(Polynomials& polynomials, auto& relation_para auto& inverse_polynomial = Relation::get_inverse_polynomial(polynomials); const size_t offset = std::max(inverse_polynomial.start_index(), start_index); // Clamp to the polynomial's actual (non-virtual) data extent; beyond end_index() everything is virtual zero. - const size_t actual_size = inverse_polynomial.end_index() > offset ? inverse_polynomial.end_index() - offset : 0; + const size_t actual_end = std::min(inverse_polynomial.end_index(), end_index); + const size_t actual_size = actual_end > offset ? actual_end - offset : 0; const auto compute_inverses = [&](size_t start, size_t end) { for (size_t i = start; i < end; ++i) { const size_t row_idx = i + offset; diff --git a/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.test.cpp b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.test.cpp new file mode 100644 index 0000000..3516308 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.test.cpp @@ -0,0 +1,111 @@ +// Test bounded inverse rows against whole-range and individual native inversions. +#include "barretenberg/honk/proof_system/logderivative_library.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include +#include +#include + +namespace { +using FF = bb::fr; +struct InverseChunkRow { + FF selector; + FF a; + FF b; +}; +struct InverseChunkParameters { + FF beta = FF(7); + FF gamma = FF(13); +}; +struct InverseChunkPolynomials { + std::vector rows; + bb::Polynomial inverse; + explicit InverseChunkPolynomials(size_t n, size_t offset = 0) + : rows(n + offset) + , inverse(n, n + offset, offset) + { + for (size_t i = 0; i < rows.size(); ++i) { + rows[i] = { FF(i % 5 == 0 ? 0 : 1), FF(i + 1), FF(3 * i + 2) }; + if (i % 11 == 0) { + rows[i].a = -FF(7); // Active zero denominators retain the existing zero policy. + } + } + } + InverseChunkRow get_row(size_t i) const { return rows[i]; } +}; +struct InverseChunkRelation { + using ValueAccumulator0 = FF; + static constexpr size_t NUM_LOOKUP_TERMS = 1; + static constexpr size_t NUM_TABLE_TERMS = 1; + static auto& get_inverse_polynomial(InverseChunkPolynomials& p) { return p.inverse; } + static bool operation_exists_at_row(const InverseChunkRow& r) { return r.selector != FF(0); } + template + static FF compute_lookup_term(const InverseChunkRow& r, const InverseChunkParameters& p) + { + return r.a + p.beta; + } + template + static FF compute_table_term(const InverseChunkRow& r, const InverseChunkParameters& p) + { + return r.b + p.gamma; + } +}; +FF inverse_chunk_oracle(const InverseChunkRow& row, const InverseChunkParameters& params) +{ + if (row.selector == FF(0)) { + return FF(0); + } + const FF denominator = (row.a + params.beta) * (row.b + params.gamma); + return denominator.is_zero() ? FF(0) : denominator.invert(); +} +} // namespace + +TEST(AvmInverseChunkPrototype, MatchesWholeRangeAndIndividualInversion) +{ + InverseChunkParameters params; + for (size_t n : std::array{ 0, 1, 2, 7, 31, 257 }) { + InverseChunkPolynomials whole(n); + bb::compute_logderivative_inverse(whole, params); + for (size_t chunk_size : std::array{ 1, 3, 8, 64 }) { + InverseChunkPolynomials chunked(n); + for (size_t start = 0; start < n;) { + const size_t end = start + std::min(chunk_size, n - start); + bb::compute_logderivative_inverse(chunked, params, start, end); + start = end; + } + for (size_t i = 0; i < n; ++i) { + EXPECT_EQ(chunked.inverse[i], whole.inverse[i]); + EXPECT_EQ(chunked.inverse[i], inverse_chunk_oracle(chunked.rows[i], params)); + } + } + } +} + +TEST(AvmInverseChunkPrototype, ExclusiveBoundsLeaveOtherRowsUntouched) +{ + InverseChunkParameters params; + InverseChunkPolynomials p(17); + for (size_t i = 0; i < 17; ++i) { + p.inverse.at(i) = (i >= 5 && i < 9) ? FF(0) : FF(41); + } + bb::compute_logderivative_inverse(p, params, 5, 9); + bb::compute_logderivative_inverse(p, params, 13, 12); // Empty range. + for (size_t i = 0; i < 17; ++i) { + EXPECT_EQ(p.inverse[i], (i >= 5 && i < 9) ? inverse_chunk_oracle(p.rows[i], params) : FF(41)); + } +} + +TEST(AvmInverseChunkPrototype, BoundsRespectShiftedBackingAndPhysicalEnd) +{ + InverseChunkParameters params; + InverseChunkPolynomials p(23, 1); + for (size_t i = 1; i < 24; ++i) { + p.inverse.at(i) = i < 4 || i >= 20 ? FF(0) : FF(41); + } + // The helper must clamp the first range to physical start and the last to physical end. + bb::compute_logderivative_inverse(p, params, 0, 4); + bb::compute_logderivative_inverse(p, params, 20, 100); + for (size_t i = 1; i < 24; ++i) { + EXPECT_EQ(p.inverse[i], i < 4 || i >= 20 ? inverse_chunk_oracle(p.rows[i], params) : FF(41)); + } +} diff --git a/barretenberg/cpp/src/barretenberg/ipc/socket_server.cpp b/barretenberg/cpp/src/barretenberg/ipc/socket_server.cpp index 62c8bf6..693ac91 100644 --- a/barretenberg/cpp/src/barretenberg/ipc/socket_server.cpp +++ b/barretenberg/cpp/src/barretenberg/ipc/socket_server.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -107,9 +108,16 @@ bool SocketServer::send(int client_id, const void* data, size_t len) void SocketServer::release(int client_id, size_t message_size) { - // No-op for sockets - message already consumed from kernel buffer during receive() - (void)client_id; + // The message was already consumed from the kernel buffer during receive(); only a large receive buffer is freed. (void)message_size; + if (client_id < 0 || static_cast(client_id) >= recv_buffers_.size()) { + return; + } + auto& buffer = recv_buffers_[static_cast(client_id)]; + if (buffer.capacity > MAX_RETAINED_RECV_BUFFER_SIZE) { + buffer.data.reset(); + buffer.capacity = 0; + } } std::span SocketServer::receive(int client_id) @@ -146,20 +154,21 @@ std::span SocketServer::receive(int client_id) total_read += static_cast(n); } - // Resize buffer if needed to fit length prefix + message + // Grow buffer if needed to fit length prefix + message (the previous contents are not needed) size_t total_size = sizeof(uint32_t) + msg_len; - if (recv_buffers_[client_idx].size() < total_size) { - recv_buffers_[client_idx].resize(total_size); + auto& buffer = recv_buffers_[client_idx]; + if (buffer.capacity < total_size) { + buffer.data = std::make_unique_for_overwrite(total_size); + buffer.capacity = total_size; } // Store length prefix in buffer - std::memcpy(recv_buffers_[client_idx].data(), &msg_len, sizeof(uint32_t)); + std::memcpy(buffer.data.get(), &msg_len, sizeof(uint32_t)); // Read message data - must loop until all bytes received (MSG_WAITALL unreliable on macOS) total_read = 0; while (total_read < msg_len) { - ssize_t n = - ::recv(fd, recv_buffers_[client_idx].data() + sizeof(uint32_t) + total_read, msg_len - total_read, 0); + ssize_t n = ::recv(fd, buffer.data.get() + sizeof(uint32_t) + total_read, msg_len - total_read, 0); if (n < 0) { if (errno == EINTR) { continue; // Interrupted, retry @@ -175,7 +184,7 @@ std::span SocketServer::receive(int client_id) total_read += static_cast(n); } - return std::span(recv_buffers_[client_idx].data() + sizeof(uint32_t), msg_len); + return std::span(buffer.data.get() + sizeof(uint32_t), msg_len); } #ifdef __APPLE__ diff --git a/barretenberg/cpp/src/barretenberg/ipc/socket_server.hpp b/barretenberg/cpp/src/barretenberg/ipc/socket_server.hpp index 1d1dd94..0d68869 100644 --- a/barretenberg/cpp/src/barretenberg/ipc/socket_server.hpp +++ b/barretenberg/cpp/src/barretenberg/ipc/socket_server.hpp @@ -3,6 +3,7 @@ #include "barretenberg/ipc/ipc_server.hpp" #include #include +#include #include #include #include @@ -45,10 +46,18 @@ class SocketServer : public IpcServer { std::string socket_path_; int initial_max_clients_; int listen_fd_ = -1; - int fd_ = -1; // kqueue or epoll fd - std::vector client_fds_; // client_id -> fd - std::unordered_map fd_to_client_id_; // fd -> client_id (for fast lookup) - std::vector> recv_buffers_; // client_id -> recv buffer + int fd_ = -1; // kqueue or epoll fd + std::vector client_fds_; // client_id -> fd + std::unordered_map fd_to_client_id_; // fd -> client_id (for fast lookup) + // Per-client receive buffer. Its contents are overwritten by each message, so it is allocated uninitialised. + struct RecvBuffer { + std::unique_ptr data; + size_t capacity = 0; + }; + // Receive buffers larger than this are freed once their message has been handled, so a large request (e.g. a + // circuit's bytecode) does not stay resident for the rest of the session. + static constexpr size_t MAX_RETAINED_RECV_BUFFER_SIZE = static_cast(1024 * 1024); + std::vector recv_buffers_; // client_id -> recv buffer int num_clients_ = 0; }; 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 9eb897e..adf4cf9 100644 --- a/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/multilinear_batching/multilinear_batching_prover.cpp @@ -104,21 +104,29 @@ template MultilinearBatchingProverClaim MultilinearBatchingPro new_shifted_evaluation += scalars[idx] * sumcheck_output.claimed_evaluations.shifted(idx); } - new_non_shifted_polynomial = std::move(key.polynomials.non_shifted(largest_non_shifted_idx)); - new_non_shifted_polynomial *= scalars[largest_non_shifted_idx]; - for (size_t idx = 0; idx < Flavor::NUM_CLAIMS; ++idx) { - if (idx != largest_non_shifted_idx) { - new_non_shifted_polynomial.add_scaled(key.polynomials.non_shifted(idx), scalars[idx]); + // Merge into the largest polynomial in place: scale it (claim 0 has scalar 1) and add the others in one pass + auto merge_into_largest = [&](bb::Polynomial& merged, size_t largest_idx, auto&& get_polynomial) { + merged = std::move(get_polynomial(largest_idx)); + if (scalars[largest_idx] != FF(1)) { + merged *= scalars[largest_idx]; } - } - - new_shifted_polynomial = std::move(key.preshifted_polynomials[largest_shifted_idx]); - new_shifted_polynomial *= scalars[largest_shifted_idx]; - for (size_t idx = 0; idx < Flavor::NUM_CLAIMS; ++idx) { - if (idx != largest_shifted_idx) { - new_shifted_polynomial.add_scaled(key.preshifted_polynomials[idx], scalars[idx]); + std::vector> sources; + std::vector source_scalars; + for (size_t idx = 0; idx < Flavor::NUM_CLAIMS; ++idx) { + if (idx != largest_idx) { + sources.emplace_back(get_polynomial(idx)); + source_scalars.emplace_back(scalars[idx]); + } } - } + add_scaled_batch( + merged, std::span>(sources), std::span(source_scalars)); + }; + merge_into_largest(new_non_shifted_polynomial, largest_non_shifted_idx, [&](size_t idx) -> bb::Polynomial& { + return key.polynomials.non_shifted(idx); + }); + merge_into_largest(new_shifted_polynomial, largest_shifted_idx, [&](size_t idx) -> bb::Polynomial& { + return key.preshifted_polynomials[idx]; + }); auto new_non_shifted_commitment = Commitment::batch_mul(key.non_shifted_commitments, scalars); auto new_shifted_commitment = Commitment::batch_mul(key.shifted_commitments, scalars); 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 } diff --git a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp index bbbb856..7fd207c 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp +++ b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp @@ -348,3 +348,33 @@ TEST(uintx, BarrettReductionRegression) EXPECT_EQ(quotient_result, quotient_expected); EXPECT_EQ(remainder_result, remainder_expected); } + +TEST(uintx, Bn254ReciprocalDivisionBoundaries) +{ + const uint1024_t modulus(uint256_t{ "0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47" }); + const auto check = [&](const uint1024_t& value) { EXPECT_EQ(value.divmod(modulus), value.divmod_base(modulus)); }; + check(0); + check(1); + check(modulus - 1); + check(modulus); + check(modulus + 1); + check(~uint1024_t(0)); + for (size_t bit = 1; bit < 1024; ++bit) { + const uint1024_t boundary = uint1024_t(1) << bit; + check(boundary - 1); + check(boundary); + check(boundary + 1); + } + for (size_t i = 0; i < 512; ++i) { + const auto value = engine.get_random_uint1024(); + check(value); + check(value >> (1024 - 576)); + check(value >> (1024 - 544)); + check(value >> 512); + const auto quotient = value >> 704; + const auto multiple = quotient * modulus; + check(multiple - 1); + check(multiple); + check(multiple + 1); + } +} diff --git a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx_impl.hpp b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx_impl.hpp index 7ec76df..88d6915 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx_impl.hpp @@ -130,17 +130,27 @@ template uintx uintx::operator-() const template uintx uintx::operator*(const uintx& other) const { const auto lolo = lo.mul_extended(other.lo); - const auto lohi = lo.mul_extended(other.hi); - const auto hilo = hi.mul_extended(other.lo); - base_uint top = lolo.second + hilo.first + lohi.first; - base_uint bottom = lolo.first; - return { bottom, top }; + // The cross terms only reach the top half, where they wrap; skip the ones with a zero factor (operands are often + // much narrower than the type, e.g. bigfield products of ~256-bit values held in a uint1024). + base_uint top = lolo.second; + if (other.hi != base_uint(0)) { + top += lo * other.hi; + } + if (hi != base_uint(0)) { + top += hi * other.lo; + } + return { lolo.first, top }; } template std::pair, uintx> uintx::mul_extended(const uintx& other) const { + if (hi == base_uint(0) && other.hi == base_uint(0)) { + const auto lolo = lo.mul_extended(other.lo); + return { uintx(lolo.first, lolo.second), uintx(0) }; + } + const auto lolo = lo.mul_extended(other.lo); const auto lohi = lo.mul_extended(other.hi); const auto hilo = hi.mul_extended(other.lo); @@ -243,6 +253,27 @@ template std::pair, uintx> uintx> 64) == base_uint(0)) { + static const base_uint reciprocal = (uintx(1) << 576).divmod_base(uintx(BN254FQMODULUS256)).first.lo; + const auto low_product = lo.mul_extended(reciprocal); + // x = lo + 2^512 * hi. Since hi < 2^64 and mu < 2^323, + // this sum fits in 388 bits, and the discarded low half cannot + // affect the result after shifting by 576 bits. + const base_uint middle = low_product.second + hi * reciprocal; + base_uint quotient = middle >> 64; + const auto product = quotient.mul_extended(base_uint(BN254FQMODULUS256)); + uintx remainder = *this - uintx(product.first, product.second); + if (remainder >= uintx(BN254FQMODULUS256)) { + quotient += 1; + remainder -= uintx(BN254FQMODULUS256); + } + return { uintx(quotient), remainder }; + } + } return (*this).template barrett_reduction(); } if (b == uintx(SECP256K1FQMODULUS256)) { @@ -275,7 +306,10 @@ std::pair, uintx> uintx::barrett_reductio constexpr size_t k = base_uint::length() - 1; // N.B. computation of redc_parameter requires division operation - if this cannot be precomputed (or amortized over // multiple reductions over the same modulus), barrett_reduction is much slower than divmod - static const uintx redc_parameter = ((uintx(1) << (k * 2)).divmod_base(uintx(modulus))).first; + // Work on a separate constant copy of the modulus: the template parameter object is not guaranteed to honour + // base_uint's alignment, and the arithmetic below may use aligned vector loads on it. + static constexpr base_uint modulus_value = modulus; + static const uintx redc_parameter = ((uintx(1) << (k * 2)).divmod_base(uintx(modulus_value))).first; const auto x = *this; @@ -293,8 +327,8 @@ std::pair, uintx> uintx::barrett_reductio // compute remainder by determining value of x - quotient * modulus uintx qm_lo(0); { - const auto lolo = quotient.lo.mul_extended(modulus); - const auto lohi = quotient.hi.mul_extended(modulus); + const auto lolo = quotient.lo.mul_extended(modulus_value); + const auto lohi = quotient.hi.mul_extended(modulus_value); base_uint t0 = lolo.first; base_uint t1 = lolo.second; t1 = t1 + lohi.first; @@ -306,9 +340,9 @@ std::pair, uintx> uintx::barrett_reductio // when k = ceil(log2(modulus)) and x < modulus^2. Here k = base_uint::length() - 1 (a fixed, // conservative choice), so x / 2^{2k} can be up to 3, giving an error bound of 4. size_t i = 0; - while (remainder >= uintx(modulus)) { + while (remainder >= uintx(modulus_value)) { BB_ASSERT_LT(i, 4U); - remainder = remainder - modulus; + remainder = remainder - modulus_value; quotient = quotient + 1; i++; } diff --git a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp index 4709491..cd7a376 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp @@ -1,13 +1,32 @@ #pragma once +#include "barretenberg/ecc/fields/ifma_field.hpp" #include "barretenberg/ecc/fields/vector_field.hpp" #include "barretenberg/ecc/fields/vectorized_for.hpp" #include "barretenberg/polynomials/polynomial.hpp" +#include +#include #include +#include +#include namespace bb { +/** + * @brief One output of the fold: `even + challenge * (odd - even)`. Equal neighbours (constant selector runs, zero + * padding inside the active extent) fold to themselves, so the multiplication is skipped; only bit-identical + * representations are short-cut. + */ +template inline Fr fold_pair(const Fr& even, const Fr& odd, const Fr& challenge) +{ + 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]) { + return even; + } + return even + challenge * (odd - even); +} + /** * @brief Stride-2 linear-interpolation fold: `dst[k] = src[2k] + challenge * (src[2k+1] - src[2k])` * for every output index `k` in `[begin, end)`. @@ -48,16 +67,153 @@ void fold_stride2( using Vec = VectorField; const Vec challenge_vec = Vec::broadcast(challenge); for (; k + WIDTH <= end; k += WIDTH) { + // A block whose WIDTH source pairs are all bit-identical (constant selector runs, zero padding) folds to + // the even values; copy them instead of packing and multiplying. + if (2 * k >= src.start_index() && 2 * (k + WIDTH) <= src.end_index()) { + const Fr* pairs = src.data() + (2 * k - src.start_index()); + uint64_t diff = 0; + for (size_t j = 0; j < 2 * WIDTH; j += 2) { + diff |= (pairs[j].data[0] ^ pairs[j + 1].data[0]) | (pairs[j].data[1] ^ pairs[j + 1].data[1]) | + (pairs[j].data[2] ^ pairs[j + 1].data[2]) | (pairs[j].data[3] ^ pairs[j + 1].data[3]); + } + if (diff == 0) { + std::array evens; + for (size_t lane = 0; lane < WIDTH; ++lane) { + evens[lane] = pairs[2 * lane]; + } + for (size_t lane = 0; lane < WIDTH; ++lane) { + dst[ScalarIndex{ k + lane }] = evens[lane]; + } + continue; + } + } const Vec even = Vec::from_lanes([&](size_t lane) { return src[2 * (k + lane)]; }); const Vec odd = Vec::from_lanes([&](size_t lane) { return src[2 * (k + lane) + 1]; }); dst[ContiguousVectorIndex{ k }] = even + (odd - even) * challenge_vec; } } #endif - for (; k < end; ++k) { - const Fr even = src[2 * k]; - dst[ScalarIndex{ k }] = even + challenge * (src[2 * k + 1] - even); + const auto fold_scalar = [&](const size_t from, const size_t to) { + for (size_t i = from; i < to; ++i) { + dst[ScalarIndex{ i }] = fold_pair(src[2 * i], src[(2 * i) + 1], challenge); + } + }; +#ifdef BB_FIELD_IFMA + // AVX-512 IFMA bulk over the outputs whose source pairs and destination lie inside the backing memory; the + // virtual-zero prefix and the tail keep the scalar loop. Outputs are produced in increasing k as in the scalar + // loop, which keeps the in-place case (src aliasing dst) safe. + if constexpr (field_ifma::Consts::supported) { + if (field_ifma::available()) { + const size_t bulk_begin = std::min(end, std::max({ k, (src.start_index() + 1) / 2, dst.start_index() })); + const size_t bulk_limit = std::max(bulk_begin, std::min({ end, src.end_index() / 2, dst.end_index() })); + const size_t bulk_end = bulk_begin + ((bulk_limit - bulk_begin) & ~size_t{ 7 }); + if (bulk_end > bulk_begin) { + fold_scalar(k, bulk_begin); + field_ifma::fold_stride2(&src.data()[(2 * bulk_begin) - src.start_index()].data[0], + &dst.data()[bulk_begin - dst.start_index()].data[0], + bulk_end - bulk_begin, + &challenge.data[0]); + k = bulk_end; + } + } + } +#endif + fold_scalar(k, end); +} + +/** + * @brief Backed range [⌊start/2⌋, ⌈end/2⌉) of the fold of a polynomial backed on [start, end); empty if the source is. + */ +template std::pair folded_backed_range(const Polynomial& src) +{ + if (src.size() == 0) { + return { 0, 0 }; + } + return { src.start_index() / 2, (src.end_index() / 2) + (src.end_index() % 2) }; +} + +/** + * @brief Backed range [⌊start/4⌋, ⌈end/4⌉) of two successive folds of a polynomial backed on [start, end). + */ +template std::pair twice_folded_backed_range(const Polynomial& src) +{ + if (src.size() == 0) { + return { 0, 0 }; + } + return { src.start_index() / 4, (src.end_index() / 4) + (src.end_index() % 4 != 0 ? 1 : 0) }; +} + +/** + * @brief Fold `src` at `first_challenge` and the result at `second_challenge` in one pass, without materializing the + * intermediate fold: `dst[k] = fold(fold(src[4k], src[4k+1]), fold(src[4k+2], src[4k+3]))` for k in + * `twice_folded_backed_range(src)`. Every output is computed exactly as two `fold_stride2_backed` calls would. + * @details `dst` is a distinct polynomial backed on a range that starts at the twice-folded start and covers the + * twice-folded end; its end index is shrunk to the latter. + */ +template +void fold_stride4_backed(const Polynomial& src, + Polynomial& dst, + const Fr& first_challenge, + const Fr& second_challenge) +{ + const auto [begin, end] = twice_folded_backed_range(src); + if (begin == end) { + return; + } + for (size_t k = begin; 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); + } + dst.shrink_end_index(end); +} + +/** + * @brief Read-only view of a polynomial folded at a challenge, `view[k] = fold(src[2k], src[2k+1])`, computed on + * access. Stands in for a partially evaluated table that is never materialized. + */ +template class FoldedPolynomialView { + public: + FoldedPolynomialView() = default; + FoldedPolynomialView(const Polynomial& source, const Fr& challenge) + : source(&source) + , challenge(challenge) + , range(folded_backed_range(source)) + {} + + Fr operator[](const size_t k) const { return fold_pair((*source)[2 * k], (*source)[(2 * k) + 1], challenge); } + 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; } + + private: + const Polynomial* source = nullptr; + Fr challenge{}; + std::pair range{ 0, 0 }; +}; + +/** + * @brief Fold `src` at `challenge` over its whole support: writes `dst[k]` for k in `folded_backed_range(src)`. + * @details `dst` is either a distinct polynomial backed on a range that starts at the folded start and covers the + * folded end (its end index is shrunk to the folded end), or `src` itself. In the in-place case the backed range is + * moved down to the folded range over the same buffer: output k is stored at offset k - ⌊start/2⌋ while iteration k + * reads offsets 2k - start and 2k + 1 - start, and k - ⌊start/2⌋ < 2k - start + 2 for every k >= ⌊start/2⌋, so no + * output overwrites a source slot a later iteration still reads. + */ +template void fold_stride2_backed(const Polynomial& src, Polynomial& dst, const Fr& challenge) +{ + const auto [begin, end] = folded_backed_range(src); + if (&src == &dst) { + const Polynomial source = src.share(); + dst.rebase_backed_range(begin, end); + fold_stride2(source, dst, begin, end, challenge); + return; + } + if (begin == end) { + return; } + fold_stride2(src, dst, begin, end, challenge); + dst.shrink_end_index(end); } } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.test.cpp b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.test.cpp new file mode 100644 index 0000000..5f3c7dd --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.test.cpp @@ -0,0 +1,92 @@ +#include "barretenberg/polynomials/fold_stride2.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/polynomials/polynomial.hpp" + +#include + +#include + +using namespace bb; + +namespace { +auto& engine = numeric::get_debug_randomness(); + +// Random coefficients with runs of bit-identical neighbour pairs (the fold's copy short-cut). +Polynomial random_poly(size_t size, size_t virtual_size, size_t start_index) +{ + Polynomial p(size, virtual_size, start_index); + for (size_t i = start_index; i < start_index + size; ++i) { + p.at(i) = ((i / 32) % 3 == 1 && i > start_index) ? p.at(i - 1) : fr::random_element(&engine); + } + return p; +} +} // namespace + +// The fold (IFMA bulk on capable CPUs, scalar elsewhere) against the formula on virtual-zero-aware reads, for +// shiftable sources, odd extents, partial output ranges and the in-place case. +TEST(FoldStride2, MatchesFormula) +{ + const fr u = fr::random_element(&engine); + for (const size_t start : { size_t{ 0 }, size_t{ 1 } }) { + for (const size_t size : { size_t{ 7 }, size_t{ 64 }, size_t{ 255 }, size_t{ 1000 } }) { + const size_t virtual_size = 2048; + const Polynomial src = random_poly(size, virtual_size, start); + const size_t limit = src.end_index(); + const size_t num_outputs = (limit / 2) + (limit % 2); + for (const size_t begin : { size_t{ 0 }, size_t{ 3 } }) { + if (begin >= num_outputs) { + continue; + } + Polynomial dst(num_outputs, virtual_size / 2); + fold_stride2(src, dst, begin, num_outputs, u); + for (size_t k = begin; k < num_outputs; ++k) { + EXPECT_EQ(dst[k], src[2 * k] + u * (src[2 * k + 1] - src[2 * k])) + << start << " " << size << " " << k; + } + } + Polynomial expected(num_outputs, virtual_size / 2); + fold_stride2(src, expected, 0, num_outputs, u); + Polynomial copy(src); + if (start == 0) { + fold_stride2(copy, copy, 0, num_outputs, u); + for (size_t k = 0; k < num_outputs; ++k) { + EXPECT_EQ(copy[k], expected[k]); + } + } + } + } +} + +TEST(AddScaledBatch, MatchesSequentialAddScaled) +{ + const size_t n = 3000; + std::vector> sources; + std::vector scalars; + for (size_t k = 0; k < 9; ++k) { + const size_t start = (k * 37) % 300; + const size_t size = n - start - ((k * 101) % 700); + Polynomial p(size, n, start); + for (size_t i = start; i < start + size; ++i) { + // Zero stretches like selector columns. + p.at(i) = (k % 3 == 0 && (i / 64) % 2 == 0) ? fr::zero() : fr::random_element(&engine); + } + sources.push_back(std::move(p)); + scalars.push_back(k == 0 ? fr::one() : fr::random_element(&engine)); + } + Polynomial dst(n, n); + for (size_t i = 0; i < n; ++i) { + dst.at(i) = fr::random_element(&engine); + } + std::vector expected(n); + for (size_t i = 0; i < n; ++i) { + expected[i] = dst[i]; + for (size_t k = 0; k < sources.size(); ++k) { + expected[i] += scalars[k] * sources[k][i]; + } + } + add_scaled_batch(dst, sources, std::span(scalars)); + for (size_t i = 0; i < n; ++i) { + EXPECT_EQ(dst[i], expected[i]) << i; + } +} diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.cpp index 390fd28..9b604b2 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.cpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.cpp @@ -8,11 +8,13 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/fields/ifma_field.hpp" #include "barretenberg/numeric/bitop/get_msb.hpp" #include "barretenberg/numeric/bitop/pow.hpp" #include "barretenberg/polynomials/backing_memory.hpp" #include "barretenberg/polynomials/shared_shifted_virtual_zeroes_array.hpp" #include "polynomial_arithmetic.hpp" +#include #include #include #include @@ -23,6 +25,7 @@ #include #include #include +#include namespace bb { @@ -205,6 +208,14 @@ template void Polynomial::shrink_end_index(const size_t new_en coefficients_.end_ = new_end_index; } +template void Polynomial::rebase_backed_range(const size_t new_start, const size_t new_end) +{ + BB_ASSERT_LTE(new_start, new_end); + BB_ASSERT_LTE(new_end - new_start, size()); + coefficients_.start_ = new_start; + coefficients_.end_ = new_end; +} + template Polynomial Polynomial::full() const { Polynomial result; @@ -260,27 +271,102 @@ void add_scaled_batch(Polynomial& dst, BB_ASSERT_LTE(dst.start_index(), min_start); BB_ASSERT_GTE(dst.end_index(), max_end); - const size_t union_size = max_end - min_start; - parallel_for([&](const ThreadChunk& chunk) { + // Split the index range so that every thread visits the same number of source entries: sources of different + // lengths overlap mostly at low indices, so equal index ranges would leave the low chunks with most of the work. + auto work_below = [&](size_t idx) { + size_t work = 0; + for (const auto& src : sources) { + work += std::clamp(idx, src.start_index, src.end_index()) - src.start_index; + } + return work; + }; + const size_t num_threads = get_num_cpus(); + const size_t total_work = work_below(max_end); + std::vector chunk_starts(num_threads + 1, max_end); + chunk_starts[0] = min_start; + for (size_t chunk = 1; chunk < num_threads; ++chunk) { + const size_t target = (total_work / num_threads) * chunk; + size_t lo = chunk_starts[chunk - 1]; + size_t hi = max_end; + while (lo < hi) { + const size_t mid = lo + ((hi - lo) / 2); + if (work_below(mid) < target) { + lo = mid + 1; + } else { + hi = mid; + } + } + chunk_starts[chunk] = lo; + } + + parallel_for(num_threads, [&](size_t thread_idx) { BB_BENCH_TRACY_NAME("add_scaled_batch/chunk"); - auto chunk_indices = chunk.range(union_size, min_start); - if (chunk_indices.empty()) { + const size_t chunk_start = chunk_starts[thread_idx]; + const size_t chunk_end = chunk_starts[thread_idx + 1]; + if (chunk_start >= chunk_end) { return; } - auto chunk_start = chunk_indices.front(); - auto chunk_end = chunk_indices.back(); - - for (size_t k = 0; k < sources.size(); ++k) { - const auto& src = sources[k]; - const Fr& c = scalars[k]; - const size_t src_start = src.start_index; - const size_t src_end = src.end_index(); - const size_t idx_start = std::max(chunk_start, src_start); - const size_t idx_end = std::min(chunk_end + 1, src_end); - - for (size_t i = idx_start; i < idx_end; ++i) { - dst.at(i) += c * src[i]; + // Walk the chunk in L1-sized tiles and apply every source to a tile before moving on, so each dst + // element is loaded and stored once per tile rather than once per source. + constexpr size_t TILE_SIZE = 256; +#ifdef BB_FIELD_IFMA + constexpr bool ifma_supported = field_ifma::Consts::supported; + static_assert(!ifma_supported || TILE_SIZE <= field_ifma::MAX_TILE); + const bool use_ifma = ifma_supported && field_ifma::available(); + std::vector tile_sources; + if (use_ifma) { + tile_sources.reserve(sources.size()); + } +#endif + for (size_t tile_start = chunk_start; tile_start < chunk_end; tile_start += TILE_SIZE) { + const size_t tile_end = std::min(tile_start + TILE_SIZE, chunk_end); + // Elements of the tile before `scalar_start` are already done by the IFMA kernel. + size_t scalar_start = tile_start; +#ifdef BB_FIELD_IFMA + if constexpr (ifma_supported) { + const size_t vector_size = (tile_end - tile_start) & ~size_t{ 7 }; + if (use_ifma && vector_size != 0) { + const size_t vector_end = tile_start + vector_size; + tile_sources.clear(); + for (size_t k = 0; k < sources.size(); ++k) { + const auto& src = sources[k]; + const size_t idx_start = std::max(tile_start, src.start_index); + const size_t idx_end = std::min(vector_end, src.end_index()); + if (idx_start < idx_end) { + tile_sources.push_back({ .data = &src[idx_start].data[0], + .begin = idx_start - tile_start, + .end = idx_end - tile_start, + .scalar = &scalars[k].data[0], + .unit = scalars[k] == Fr::one() }); + } + } + field_ifma::add_scaled_batch_tile( + &dst.at(tile_start).data[0], vector_size, tile_sources.data(), tile_sources.size()); + scalar_start = vector_end; + } + } +#endif + for (size_t k = 0; k < sources.size(); ++k) { + const auto& src = sources[k]; + const Fr& c = scalars[k]; + const size_t idx_start = std::max(scalar_start, src.start_index); + const size_t idx_end = std::min(tile_end, src.end_index()); + + // A unit scalar needs no multiplication + if (c == Fr::one()) { + for (size_t i = idx_start; i < idx_end; ++i) { + dst.at(i) += src[i]; + } + continue; + } + // Zero coefficients (common in selector columns) contribute nothing, so skip their multiply. + for (size_t i = idx_start; i < idx_end; ++i) { + const Fr& value = src[i]; + if (!value.is_zero()) { + dst.at(i) += c * value; + } + } } } }); diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp index 5f02e0e..4f62bfc 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp @@ -573,6 +573,13 @@ template class Polynomial { */ void shrink_end_index(const size_t new_end_index); + /** + * @brief Move the memory-backed range to [new_start, new_end) without moving any data: the element stored at + * offset i now represents index new_start + i. The new range must fit in the current backed size. + * @details Lets an in-place fold write its outputs, which occupy a lower index range, over the same buffer. + */ + void rebase_backed_range(const size_t new_start, const size_t new_end); + /** * @brief Copys the polynomial, but with the whole address space usable. * The value of the polynomial remains the same, but defined memory region differs. diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.cpp index 30722b7..62fb467 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.cpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.cpp @@ -8,10 +8,12 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/mem.hpp" #include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/fields/ifma_field.hpp" #include "barretenberg/ecc/fields/vectorized_for.hpp" #include "barretenberg/numeric/bitop/get_msb.hpp" #include "barretenberg/polynomials/accumulator.hpp" #include "barretenberg/polynomials/polynomial.hpp" +#include #include #include @@ -168,13 +170,56 @@ template Fr evaluate(const Fr* coeffs, const Fr& z, const size_t n if (range.empty()) { return; } - size_t start = *range.begin(); - Fr z_acc = z.pow(static_cast(start)); - for (size_t i : range) { - Fr work_var = z_acc * coeffs[i]; - evaluations[chunk.thread_index] += work_var; - z_acc *= z; + // Horner's rule over the chunk gives sum_i coeffs[start + i] * z^i with one multiplication per + // coefficient; scaling by z^start then places the chunk. The two halves of the chunk are evaluated + // interleaved so that their multiplication chains overlap. Accumulate locally and store once so threads + // do not write to adjacent elements of `evaluations` on every iteration. + const size_t start = *range.begin(); +#ifdef BB_FIELD_IFMA + // AVX-512 IFMA: sixteen interleaved Horner chains over the largest multiple of 16 coefficients, the rest by + // scalar Horner, then the chunk is placed at z^start as below. + if constexpr (field_ifma::Consts::supported) { + if (field_ifma::available()) { + const size_t bulk_size = range.size() & ~size_t{ 15 }; + std::array z_pows; + z_pows[0] = Fr::one(); + for (size_t j = 1; j < 8; ++j) { + z_pows[j] = z_pows[j - 1] * z; + } + const Fr z8 = z_pows[7] * z; + const Fr z16 = z8.sqr(); + std::array terms; + field_ifma::evaluate(&coeffs[start].data[0], + bulk_size, + &z_pows[0].data[0], + &z8.data[0], + &z16.data[0], + &terms[0].data[0]); + Fr tail_eval = Fr::zero(); + for (size_t i = range.size(); i > bulk_size; --i) { + tail_eval = (tail_eval * z) + coeffs[start + i - 1]; + } + Fr chunk_eval = tail_eval * z.pow(static_cast(bulk_size)); + for (const Fr& term : terms) { + chunk_eval += term; + } + evaluations[chunk.thread_index] = chunk_eval * z.pow(static_cast(start)); + return; + } + } +#endif + const size_t low_size = range.size() / 2; + const size_t high_size = range.size() - low_size; + const Fr* low = coeffs + start; + const Fr* high = low + low_size; + Fr low_eval = Fr::zero(); + Fr high_eval = (high_size > low_size) ? high[low_size] : Fr::zero(); + for (size_t i = low_size; i > 0; --i) { + low_eval = (low_eval * z) + low[i - 1]; + high_eval = (high_eval * z) + high[i - 1]; } + evaluations[chunk.thread_index] = + (low_eval + high_eval * z.pow(static_cast(low_size))) * z.pow(static_cast(start)); }); Fr r = Fr::zero(); diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.test.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.test.cpp index 070dc36..ed85f29 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.test.cpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_arithmetic.test.cpp @@ -536,3 +536,21 @@ TEST(polynomials, FftInnerParallelInPlaceAsserts) polynomial_arithmetic::fft_inner_parallel(coeffs.data(), coeffs.data(), domain, FF(), domain.get_round_roots()), ".*"); } + +// evaluate (IFMA chains on capable CPUs, two scalar Horner chains elsewhere) against a single Horner chain, for sizes +// that leave every possible remainder in the per-thread chunks. +TEST(polynomials, evaluate_matches_horner) +{ + for (const size_t n : { size_t{ 1 }, size_t{ 17 }, size_t{ 64 }, size_t{ 1000 }, size_t{ 5003 } }) { + std::vector coeffs(n); + for (auto& c : coeffs) { + c = fr::random_element(); + } + const fr z = fr::random_element(); + fr expected = fr::zero(); + for (size_t i = n; i > 0; --i) { + expected = (expected * z) + coeffs[i - 1]; + } + EXPECT_EQ(polynomial_arithmetic::evaluate(coeffs.data(), z, n), expected) << n; + } +} diff --git a/barretenberg/cpp/src/barretenberg/polynomials/univariate.hpp b/barretenberg/cpp/src/barretenberg/polynomials/univariate.hpp index 48711f5..3244084 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/univariate.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/univariate.hpp @@ -8,15 +8,34 @@ #include #include +#include #include #include "barretenberg/common/assert.hpp" #include "barretenberg/common/serialize.hpp" +#include "barretenberg/ecc/fields/field.hpp" +#include "barretenberg/ecc/fields/ifma_field.hpp" #include "barretenberg/polynomials/barycentric.hpp" #include "barretenberg/polynomials/univariate_coefficient_basis.hpp" namespace bb { +#ifdef BB_FIELD_IFMA +/** + * @brief Whether element-wise products of a Univariate go through the AVX-512 IFMA kernels: native fields + * the kernels support, for lengths where eight-lane registers pay off. + */ +template constexpr bool univariate_uses_ifma() +{ + if constexpr (requires { typename Fr::Params; }) { + if constexpr (std::is_same_v>) { + return field_ifma::Consts::supported && length >= 4 && length <= 8; + } + } + return false; +} +#endif + /** * @brief A view of a univariate, also used to truncate univariates. * @@ -40,6 +59,10 @@ template class Univariate { std::array evaluations; +#ifdef BB_FIELD_IFMA + static constexpr bool use_ifma_v = univariate_uses_ifma(); +#endif + Univariate() = default; explicit Univariate(const std::array& evaluations) @@ -162,6 +185,15 @@ template class Univariate { } Univariate& operator*=(const Univariate& other) { +#ifdef BB_FIELD_IFMA + if constexpr (use_ifma_v) { + if (field_ifma::available()) { + field_ifma::mul_assign_n(&evaluations[0].data[0], + &other.evaluations[0].data[0]); + return *this; + } + } +#endif for (size_t i = 0; i < LENGTH; ++i) { evaluations[i] *= other.evaluations[i]; } @@ -169,6 +201,14 @@ template class Univariate { } Univariate& self_sqr() { +#ifdef BB_FIELD_IFMA + if constexpr (use_ifma_v) { + if (field_ifma::available()) { + field_ifma::sqr_assign_n(&evaluations[0].data[0]); + return *this; + } + } +#endif for (size_t i = 0; i < LENGTH; ++i) { evaluations[i].self_sqr(); } @@ -228,6 +268,14 @@ template class Univariate { } Univariate& operator*=(const Fr& scalar) { +#ifdef BB_FIELD_IFMA + if constexpr (use_ifma_v) { + if (field_ifma::available()) { + field_ifma::mul_assign_scalar_n(&evaluations[0].data[0], &scalar.data[0]); + return *this; + } + } +#endif for (auto& eval : evaluations) { eval *= scalar; } diff --git a/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp index b2b5a62..d16bd88 100644 --- a/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/databus_lookup_relation.hpp @@ -7,6 +7,7 @@ #pragma once #include #include +#include #include "barretenberg/common/thread.hpp" #include "barretenberg/polynomials/univariate.hpp" @@ -62,9 +63,11 @@ class SingleBusLookupRelationImpl { template inline static bool skip(const AllEntities& in) { - // Skip when the row is not a read gate, has no read counts on this column, and carries no - // value: subrelation (4) is non-trivial on any row with a non-zero value off the support. - return in[AllEntities::EntityId::q_busread].is_zero() && in[ReadCountsId].is_zero() && in[ValueId].is_zero(); + // Skip when the row is not a read gate of this column (q_busread · selector vanishes), has no read counts on + // this column, and carries no value: subrelation (4) is non-trivial on any row with a non-zero value off the + // support. + return (in[AllEntities::EntityId::q_busread].is_zero() || in[SelectorId].is_zero()) && + in[ReadCountsId].is_zero() && in[ValueId].is_zero(); } /** @@ -126,27 +129,71 @@ class SingleBusLookupRelationImpl { const auto& column_selector = polynomials[SelectorId]; const auto& read_counts = polynomials[ReadCountsId]; - const size_t num_rows = circuit_size - start_index; + const auto& q_busread = polynomials.q_busread(); + const auto& w_l = polynomials.w_l(); + const auto& w_r = polynomials.w_r(); + const auto& databus_id = polynomials.databus_id(); + const auto& value_column = polynomials[ValueId]; + const FF& gamma = relation_parameters.gamma; + const FF& beta = relation_parameters.beta; + + // A row needs an inverse only if it is a read gate (q_busread != 0) or has a non-zero read count, so only + // rows inside the backing ranges of q_busread and read_counts are visited; both are zero elsewhere. Each + // thread handles a slice of the inverse polynomial's backing range (which covers both) and then inverts the + // non-zero entries of its slice; inverses are unique, so this matches a whole-polynomial batch inversion. + const size_t backing_start = inverse_polynomial.start_index(); + const size_t backing_size = inverse_polynomial.size(); size_t min_iterations_per_thread = 1 << 6; - size_t num_threads = bb::calculate_num_threads(num_rows, min_iterations_per_thread); + size_t num_threads = bb::calculate_num_threads(backing_size, min_iterations_per_thread); parallel_for(num_threads, [&](ThreadChunk chunk) { BB_BENCH_TRACY_NAME("Databus::compute_inverses/chunk"); - for (size_t j : chunk.range(num_rows)) { - size_t i = j + start_index; - const bool is_read = polynomials.q_busread()[i] == 1 && column_selector[i] == 1; + auto range = chunk.range(backing_size, backing_start); + if (range.empty()) { + return; + } + const size_t chunk_begin = *range.begin(); + const size_t chunk_end = chunk_begin + range.size(); + const size_t row_begin = std::max(chunk_begin, start_index); + const size_t row_end = std::min(chunk_end, circuit_size); + + const auto compute_row = [&](size_t i) { + const bool is_read = q_busread[i] == 1 && column_selector[i] == 1; const bool nonzero_read_count = read_counts[i] > 0; if (is_read || nonzero_read_count) { - // TODO(https://github.com/AztecProtocol/barretenberg/issues/940): avoid get_row if possible. - auto row = polynomials.get_row(i); - auto value = compute_lookup_term(row, relation_parameters) * - compute_table_term(row, relation_parameters); - inverse_polynomial.at(i) = value; + // compute_lookup_term · compute_table_term at row i, reading only the four columns they use + const FF lookup_term = (w_r[i] * beta) + w_l[i] + gamma; + const FF table_term = (databus_id[i] * beta) + value_column[i] + gamma; + inverse_polynomial.at(i) = lookup_term * table_term; + } + }; + const size_t read_begin = std::max(row_begin, q_busread.start_index()); + const size_t read_end = std::min(row_end, q_busread.end_index()); + for (size_t i = read_begin; i < read_end; ++i) { + compute_row(i); + } + const size_t count_begin = std::max(row_begin, read_counts.start_index()); + const size_t count_end = std::min(row_end, read_counts.end_index()); + for (size_t i = count_begin; i < count_end; ++i) { + if (i < read_begin || i >= read_end) { + compute_row(i); } } - }); - FF::batch_invert(inverse_polynomial.coeffs()); + // Invert the non-zero entries of the slice in place (zeroes are left as they are). + std::vector nonzero_indices; + std::vector nonzero_values; + for (size_t i = chunk_begin; i < chunk_end; ++i) { + if (!inverse_polynomial[i].is_zero()) { + nonzero_indices.push_back(i); + nonzero_values.push_back(inverse_polynomial[i]); + } + } + FF::batch_invert(nonzero_values); + for (size_t k = 0; k < nonzero_indices.size(); ++k) { + inverse_polynomial.at(nonzero_indices[k]) = nonzero_values[k]; + } + }); }; /** @@ -169,6 +216,54 @@ class SingleBusLookupRelationImpl { const auto inverses_m = CoefficientAccumulator(in[InversesId]); const auto read_counts_m = CoefficientAccumulator(in[ReadCountsId]); + if constexpr (IsProverAccumulator) { + // A row is typically either a read gate of this column or one of its data rows with a read count, so the + // terms carrying the other (identically zero) factor are dropped. + const auto q_busread_m = CoefficientAccumulator(in[AllEntities::EntityId::q_busread]); + const auto column_selector_m = CoefficientAccumulator(in[SelectorId]); + const bool is_read = !q_busread_m.is_zero() && !column_selector_m.is_zero(); + const bool has_read_counts = !read_counts_m.is_zero(); + + const Accumulator inverses(inverses_m); + const auto lookup_term = compute_lookup_term(in, params); + const auto table_term = compute_table_term(in, params); + // I·L·T − 1 + const auto common = lookup_term * table_term * inverses - FF(1); + + Accumulator tmp(0); + if (is_read) { + const auto read_selector_m = q_busread_m * column_selector_m; + // (1a) (I·L·T − 1) · is_read + std::get<0>(accumulator) += common * Accumulator(read_selector_m * scaling_factor); + tmp = Accumulator(read_selector_m) * table_term; + } + if (has_read_counts) { + // (1b) (I·L·T − 1) · count + std::get<1>(accumulator) += common * Accumulator(read_counts_m * scaling_factor); + tmp -= Accumulator(read_counts_m) * lookup_term; + // (3) (1 − indicator) · count + using ShortAccumulator = typename std::tuple_element_t<3, ContainerOverSubrelations>; + const auto indicator_m = CoefficientAccumulator(in[IndicatorId]); + const ShortAccumulator indicator_short(indicator_m); + const ShortAccumulator read_counts_short(read_counts_m); + std::get<3>(accumulator) += (read_counts_short - indicator_short * read_counts_short) * scaling_factor; + } + // (2) (is_read·T − count·L) · I + tmp *= inverses; + std::get<2>(accumulator) += tmp; + // (4) (1 − indicator) · value: 6.0.0's value locality, on every row the fast path takes (added when + // porting to 6.0.0, which introduced this subrelation; as 6.0.0's accumulate computes it). + { + using ValueLocalityAccumulator = typename std::tuple_element_t<4, ContainerOverSubrelations>; + const auto indicator_vm = CoefficientAccumulator(in[IndicatorId]); + const auto value_vm = CoefficientAccumulator(in[ValueId]); + const ValueLocalityAccumulator indicator_v(indicator_vm); + const ValueLocalityAccumulator value_v(value_vm); + std::get<4>(accumulator) += (value_v - indicator_v * value_v) * scaling_factor; + } + return; + } + const Accumulator inverses(inverses_m); const Accumulator read_counts(read_counts_m); const auto lookup_term = compute_lookup_term(in, params); 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 7c6830a..6e93673 100644 --- a/barretenberg/cpp/src/barretenberg/relations/delta_range_constraint_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/delta_range_constraint_relation.hpp @@ -103,6 +103,59 @@ template class DeltaRangeConstraintRelationImpl { tmp_4 *= q_delta_range_scaled; std::get<3>(accumulators) += tmp_4; }; + + /** + * @brief Prover-only constants of the separator-weighted sum of the four subrelations (see + * HasProverSubrelationBatching): the weights themselves. + */ + struct SubrelationBatchingConstants { + std::array weights; + }; + + static SubrelationBatchingConstants compute_subrelation_batching_constants(const std::array& weights) + { + return SubrelationBatchingConstants{ weights }; + } + + /** + * @brief Prover-only: add \f$ q \cdot \text{scaling} \cdot \sum_k w_k D_k (D_k + 2) \f$, with + * \f$ D_k = \delta_k (\delta_k - 3) \f$, into the first subrelation accumulator. + * @details \f$ D_k \f$ is formed in the degree-2 coefficient basis and each weight is folded into the factor + * \f$ D_k + 2 \f$ there, so the selector and scaling multiply the weighted sum once instead of each subrelation. + */ + template + static void accumulate_with_subrelation_batching(ContainerOverSubrelations& accumulators, + const AllEntities& in, + const Parameters& /*params*/, + const FF& scaling_factor, + const SubrelationBatchingConstants& constants) + { + using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; + using CoefficientAccumulator = typename Accumulator::CoefficientAccumulator; + + auto w_1 = CoefficientAccumulator(in[AllEntities::EntityId::w_l]); + auto w_2 = CoefficientAccumulator(in[AllEntities::EntityId::w_r]); + auto w_3 = CoefficientAccumulator(in[AllEntities::EntityId::w_o]); + auto w_4 = CoefficientAccumulator(in[AllEntities::EntityId::w_4]); + auto w_1_shift = CoefficientAccumulator(in[AllEntities::EntityId::w_l_shift]); + auto q_delta_range_m = CoefficientAccumulator(in[AllEntities::EntityId::q_delta_range]); + + // D = delta (delta - 3) = delta^2 - 3 delta + auto range_term = [](const auto& delta) { return delta.sqr() - (delta + delta + delta); }; + + // The first weight is 1 (each weight is relative to the first subrelation's separator). + const auto range_1 = range_term(w_2 - w_1); + auto body = Accumulator(range_1) * Accumulator(range_1 + FF(2)); + const auto range_2 = range_term(w_3 - w_2); + body += Accumulator(range_2) * Accumulator((range_2 + FF(2)) * constants.weights[1]); + const auto range_3 = range_term(w_4 - w_3); + body += Accumulator(range_3) * Accumulator((range_3 + FF(2)) * constants.weights[2]); + const auto range_4 = range_term(w_1_shift - w_4); + body += Accumulator(range_4) * Accumulator((range_4 + FF(2)) * constants.weights[3]); + + body *= Accumulator(q_delta_range_m * scaling_factor); + std::get<0>(accumulators) += body; + } }; template using DeltaRangeConstraintRelation = Relation>; diff --git a/barretenberg/cpp/src/barretenberg/relations/logderiv_lookup_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/logderiv_lookup_relation.hpp index 2c1d546..57dd22a 100644 --- a/barretenberg/cpp/src/barretenberg/relations/logderiv_lookup_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/logderiv_lookup_relation.hpp @@ -203,6 +203,43 @@ template class LogDerivLookupRelationImpl { return Accumulator(result); } + /** + * @brief Prover-only variant of compute_lookup_term: the same degree-2 polynomial, with the challenge powers + * applied to the degree-2 coefficient forms before the single conversion to evaluations. + */ + template + static Accumulator compute_lookup_term_in_coefficient_basis(const AllEntities& in, const Parameters& params) + { + using ParameterCoefficientAccumulator = typename Parameters::DataType::CoefficientAccumulator; + using CoefficientAccumulator = typename Accumulator::CoefficientAccumulator; + + const auto gamma = ParameterCoefficientAccumulator(params.gamma); + + auto w_1 = CoefficientAccumulator(in[AllEntities::EntityId::w_l]); + auto w_2 = CoefficientAccumulator(in[AllEntities::EntityId::w_r]); + auto w_3 = CoefficientAccumulator(in[AllEntities::EntityId::w_o]); + + auto w_1_shift = CoefficientAccumulator(in[AllEntities::EntityId::w_l_shift]); + auto w_2_shift = CoefficientAccumulator(in[AllEntities::EntityId::w_r_shift]); + auto w_3_shift = CoefficientAccumulator(in[AllEntities::EntityId::w_o_shift]); + + auto table_index = CoefficientAccumulator(in[AllEntities::EntityId::q_o]); + auto negative_column_1_step_size = CoefficientAccumulator(in[AllEntities::EntityId::q_r]); + auto negative_column_2_step_size = CoefficientAccumulator(in[AllEntities::EntityId::q_m]); + auto negative_column_3_step_size = CoefficientAccumulator(in[AllEntities::EntityId::q_c]); + + auto derived_table_entry_1 = (negative_column_1_step_size * w_1_shift) + (w_1 + gamma); + auto derived_table_entry_2 = (negative_column_2_step_size * w_2_shift) + w_2; + auto derived_table_entry_3 = (negative_column_3_step_size * w_3_shift) + w_3; + auto table_index_entry = table_index * params.beta_cube; + + auto result = derived_table_entry_2 * params.beta; + result += derived_table_entry_3 * params.beta_sqr; + result += derived_table_entry_1; + result += table_index_entry; + return Accumulator(result); + } + template static Accumulator compute_lookup_term(const AllEntities& in, const Parameters& params) { @@ -267,14 +304,24 @@ template class LogDerivLookupRelationImpl { BB_BENCH_NAME("Lookup::compute_logderivative_inverse"); auto& inverse_polynomial = get_inverse_polynomial(polynomials); - const size_t num_rows = circuit_size - start_index; + // Lookup gates and read tags only occur inside the inverse polynomial's backing range (it is allocated to + // cover both the lookup block and the table data). Each thread fills a slice of that range and then inverts + // it in place; inverses are unique, so slice-wise batch inversion matches a whole-polynomial one. + const size_t backing_start = inverse_polynomial.start_index(); + const size_t backing_size = inverse_polynomial.size(); size_t min_iterations_per_thread = 1 << 6; // min number of iterations for which we'll spin up a unique thread - size_t num_threads = bb::calculate_num_threads(num_rows, min_iterations_per_thread); + size_t num_threads = bb::calculate_num_threads(backing_size, min_iterations_per_thread); parallel_for(num_threads, [&](ThreadChunk chunk) { BB_BENCH_TRACY_NAME("Lookup::compute_inverses/chunk"); - for (size_t j : chunk.range(num_rows)) { - size_t i = j + start_index; + auto range = chunk.range(backing_size, backing_start); + if (range.empty()) { + return; + } + const size_t chunk_begin = *range.begin(); + const size_t row_begin = std::max(chunk_begin, start_index); + const size_t row_end = std::min(chunk_begin + range.size(), circuit_size); + for (size_t i = row_begin; i < row_end; ++i) { // We only compute the inverse if this row contains a lookup gate or data that has been looked up if (polynomials.q_lookup().get(i) == 1 || polynomials.lookup_read_tags().get(i) == 1) { // TODO(https://github.com/AztecProtocol/barretenberg/issues/940): avoid get_row if possible. @@ -284,10 +331,9 @@ template class LogDerivLookupRelationImpl { inverse_polynomial.at(i) = value; } } + // Compute the inverse polynomial I in place on this slice by inverting the product at each row + FF::batch_invert(std::span(&inverse_polynomial.at(chunk_begin), range.size())); }); - - // Compute inverse polynomial I in place by inverting the product at each row - FF::batch_invert(inverse_polynomial.coeffs()); }; /** @@ -323,6 +369,44 @@ template class LogDerivLookupRelationImpl { const auto read_counts_m = CoefficientAccumulator(in[AllEntities::EntityId::lookup_read_counts]); // Degree 1 const auto read_selector_m = CoefficientAccumulator(in[AllEntities::EntityId::q_lookup]); // Degree 1 + // Prover fast path (guarded on ::LENGTH so it never enters the verifiers, which keep the straight-line + // computation below). A row is typically either a lookup gate (q_lookup) or a table row (read counts / tags), + // so the terms carrying an identically-zero read selector, read count or read tag are exact zeros and are + // dropped; the lookup term's challenge powers are applied in the coefficient basis. + if constexpr (IsProverAccumulator) { + const auto read_tag_m = CoefficientAccumulator(in[AllEntities::EntityId::lookup_read_tags]); + const bool has_read_selector = !read_selector_m.is_zero(); + const bool has_read_counts = !read_counts_m.is_zero(); + const bool has_read_tag = !read_tag_m.is_zero(); + + const auto lookup_term = compute_lookup_term_in_coefficient_basis(in, params); + const auto table_term = compute_table_term(in, params); + const Accumulator inverse_exists = + has_read_tag ? compute_inverse_exists(in) : Accumulator(read_selector_m); + + const Accumulator logderiv_first_term = + (lookup_term * table_term * inverses - inverse_exists) * scaling_factor; + std::get<0>(accumulator) += ShortView(logderiv_first_term); + + Accumulator tmp; + if (has_read_selector) { + tmp = Accumulator(read_selector_m) * table_term; + if (has_read_counts) { + tmp -= (Accumulator(read_counts_m) * lookup_term); + } + } else { + tmp = -(Accumulator(read_counts_m) * lookup_term); + } + tmp *= inverses; + std::get<1>(accumulator) += tmp; + + if (has_read_tag) { + const auto read_tag = BooleanCheckerAccumulator(read_tag_m); + std::get<2>(accumulator) += (read_tag * read_tag - read_tag) * scaling_factor; + } + return; + } + const auto inverse_exists = compute_inverse_exists(in); // Degree 2 const auto lookup_term = compute_lookup_term(in, params); // Degree 2 const auto table_term = compute_table_term(in, params); // Degree 1 diff --git a/barretenberg/cpp/src/barretenberg/relations/memory_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/memory_relation.hpp index 91c4de9..6d1534d 100644 --- a/barretenberg/cpp/src/barretenberg/relations/memory_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/memory_relation.hpp @@ -112,6 +112,115 @@ template class MemoryRelationImpl { auto q_memory_m = CoefficientAccumulator(in[AllEntities::EntityId::q_memory]); + // Prover fast path (guarded on ::LENGTH so it never enters the verifiers, which keep the straight-line + // computation below). Each memory gate type is identified by a selector product (ROM consistency: q_1 q_2, + // RAM consistency: q_3, RAM timestamp: q_1 q_4, memory record: q_1 q_m, ROM-LogUp table/read: + // q_2 (1 - q_1) / q_4 (1 - q_1)). A product of univariates is identically zero iff one of its factors is, so + // the terms of gate types absent from this edge are exact zeros and are not computed. The remaining terms are + // the same field values as in the general path, summed in a different grouping. + if constexpr (IsProverAccumulator) { + const bool q_1_is_zero = q_1_m.is_zero(); + const auto one_minus_q_1_m = -q_1_m + FF(1); + const bool one_minus_q_1_is_zero = one_minus_q_1_m.is_zero(); + const bool is_rom_consistency = !q_1_is_zero && !q_2_m.is_zero(); + const bool is_ram_consistency = !q_3_m.is_zero(); + const bool is_ram_timestamp = !q_1_is_zero && !q_4_m.is_zero(); + const bool is_memory_record = !q_1_is_zero && !q_m_m.is_zero(); + const bool is_logup_table = !one_minus_q_1_is_zero && !q_2_m.is_zero(); + const bool is_logup_read = !one_minus_q_1_is_zero && !q_4_m.is_zero(); + + const auto q_memory_by_scaling_m = q_memory_m * scaling_factor; + const Accumulator q_memory_by_scaling(q_memory_by_scaling_m); + + const auto neg_index_delta_m = w_1_m - w_1_shift_m; + const auto index_delta_is_zero_m = neg_index_delta_m + FF(1); + + // Contribution of the q_memory-scaled gate types to subrelation 0. + Accumulator memory_identity(FF(0)); + if (is_rom_consistency || is_ram_consistency || is_memory_record) { + auto partial_record_check_m = w_3_m * eta_three_m; + partial_record_check_m += w_2_m * eta_two_m; + partial_record_check_m += w_1_m * eta_m; + partial_record_check_m += q_c_m; + const auto memory_record_check = Accumulator(partial_record_check_m - w_4_m); + + if (is_rom_consistency || is_ram_consistency) { + const Accumulator index_increases_by_zero_or_one(neg_index_delta_m.sqr() + neg_index_delta_m); + if (is_rom_consistency) { + const auto record_delta_m = w_4_shift_m - w_4_m; + const auto adjacent_values_match_if_adjacent_indices_match = + Accumulator(index_delta_is_zero_m * record_delta_m); + const auto q_one_by_two = Accumulator(q_1_m * q_2_m); + const auto q_one_by_two_by_memory_by_scaling = q_one_by_two * q_memory_by_scaling; + std::get<1>(accumulators) += + adjacent_values_match_if_adjacent_indices_match * q_one_by_two_by_memory_by_scaling; + std::get<2>(accumulators) += index_increases_by_zero_or_one * q_one_by_two_by_memory_by_scaling; + memory_identity += memory_record_check * q_one_by_two; + } + if (is_ram_consistency) { + // The access type is read from the record check: -access = partial record check - w_4. + const auto& neg_access_type = memory_record_check; + const auto access_check = neg_access_type.sqr() + neg_access_type; + + auto neg_next_gate_access_type_m = w_3_shift_m * eta_three_m; + neg_next_gate_access_type_m += w_2_shift_m * eta_two_m; + neg_next_gate_access_type_m += w_1_shift_m * eta_m; + neg_next_gate_access_type_m = neg_next_gate_access_type_m - w_4_shift_m; + const Accumulator neg_next_gate_access_type(neg_next_gate_access_type_m); + const auto value_delta_m = w_3_shift_m - w_3_m; + const auto adjacent_values_match_if_adjacent_indices_match_and_next_access_is_a_read_operation = + Accumulator(index_delta_is_zero_m * value_delta_m) * + Accumulator(neg_next_gate_access_type_m + FF(1)); + const auto next_gate_access_type_is_boolean = + neg_next_gate_access_type.sqr() + neg_next_gate_access_type; + + const auto q_3_by_memory_and_scaling = Accumulator(q_3_m * q_memory_by_scaling_m); + std::get<3>(accumulators) += + adjacent_values_match_if_adjacent_indices_match_and_next_access_is_a_read_operation * + q_3_by_memory_and_scaling; + std::get<4>(accumulators) += index_increases_by_zero_or_one * q_3_by_memory_and_scaling; + std::get<5>(accumulators) += next_gate_access_type_is_boolean * q_3_by_memory_and_scaling; + // RAM consistency enters subrelation 0 already scaled by q_memory. + std::get<0>(accumulators) += access_check * q_3_by_memory_and_scaling; + } + } + if (is_memory_record) { + memory_identity += memory_record_check * Accumulator(q_m_m * q_1_m); + } + } + if (is_ram_timestamp) { + const auto timestamp_delta_m = w_2_shift_m - w_2_m; + const auto RAM_timestamp_check_identity_m = index_delta_is_zero_m * timestamp_delta_m - w_3_m; + memory_identity += Accumulator(RAM_timestamp_check_identity_m) * Accumulator(q_4_m * q_1_m); + } + if (is_rom_consistency || is_ram_timestamp || is_memory_record) { + memory_identity *= q_memory_by_scaling; + std::get<0>(accumulators) += memory_identity; + } + + if (is_logup_table || is_logup_read) { + const Accumulator q_logup_table = + is_logup_table ? Accumulator(q_2_m * one_minus_q_1_m) : Accumulator(FF(0)); + const Accumulator q_logup_read = + is_logup_read ? Accumulator(q_4_m * one_minus_q_1_m) : Accumulator(FF(0)); + const Accumulator q_logup_any = q_logup_table + q_logup_read; + + const Accumulator denom(w_1_m + w_2_m * eta_m + q_c_m * eta_two_m + rom_logup_gamma_m); + const Accumulator w_4_acc(w_4_m); + + std::get<6>(accumulators) += q_memory_by_scaling * q_logup_any * (w_4_acc * denom - FF(1)); + + Accumulator logup_sum_contribution = q_logup_read; + if (is_logup_table) { + logup_sum_contribution -= q_logup_table * Accumulator(w_3_m); + } + logup_sum_contribution *= w_4_acc; + logup_sum_contribution *= Accumulator(q_memory_m); + std::get<7>(accumulators) += logup_sum_contribution; + } + return; + } + /** * MEMORY * 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/relations/ultra_arithmetic_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/ultra_arithmetic_relation.hpp index b40f00f..55eb7a7 100644 --- a/barretenberg/cpp/src/barretenberg/relations/ultra_arithmetic_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/ultra_arithmetic_relation.hpp @@ -79,6 +79,31 @@ template class ArithmeticRelationImpl { auto q_m_m = CoefficientAccumulator(in[AllEntities::EntityId::q_m]); auto q_arith_sub_1 = q_arith_m - FF(1); + + // Prover fast path (guarded on ::LENGTH so it never enters the verifiers, which keep the straight-line + // computation below) for the common case q_arith == 1 on the whole edge: subrelation 2 carries the factor + // q_arith - 1 and vanishes, (q_arith - 3) * (-1/2) == 1, the w_4_shift term drops and the q_arith scaling is + // the gate separator itself. The q_m product is identically zero (and skipped) when q_m vanishes on the edge. + if constexpr (IsProverAccumulator) { + if (q_arith_sub_1.is_zero()) { + auto w_r_m = CoefficientAccumulator(in[AllEntities::EntityId::w_r]); + auto w_o_m = CoefficientAccumulator(in[AllEntities::EntityId::w_o]); + auto q_l_m = CoefficientAccumulator(in[AllEntities::EntityId::q_l]); + auto q_r_m = CoefficientAccumulator(in[AllEntities::EntityId::q_r]); + auto q_o_m = CoefficientAccumulator(in[AllEntities::EntityId::q_o]); + auto q_4_m = CoefficientAccumulator(in[AllEntities::EntityId::q_4]); + auto q_c_m = CoefficientAccumulator(in[AllEntities::EntityId::q_c]); + + auto linear_terms = (q_l_m * w_l_m) + (q_r_m * w_r_m) + (q_o_m * w_o_m) + (q_4_m * w_4_m) + q_c_m; + auto identity = Accumulator(linear_terms); + if (!q_m_m.is_zero()) { + identity += Accumulator(w_r_m * w_l_m) * Accumulator(q_m_m); + } + std::get<0>(evals) += identity * scaling_factor; + return; + } + } + auto scaled_q_arith = q_arith_m * scaling_factor; // Subrelation 1 { diff --git a/barretenberg/cpp/src/barretenberg/serialize/msgpack_impl.hpp b/barretenberg/cpp/src/barretenberg/serialize/msgpack_impl.hpp index 7c86a5d..3ff8935 100644 --- a/barretenberg/cpp/src/barretenberg/serialize/msgpack_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/serialize/msgpack_impl.hpp @@ -47,6 +47,17 @@ inline std::pair msgpack_encode_buffer(auto&& obj, return { output, buffer.size() }; } +/** + * @brief msgpack reference function for unpacking an input buffer that stays alive while the unpacked object and + * everything converted from it are in use: strings and binary blobs are referenced in the input buffer instead of being + * copied into the unpacked object's zone. + */ +inline bool msgpack_reference_input(msgpack::type::object_type type, std::size_t /*size*/, void* /*user_data*/) +{ + // Borrow only the desired string/binary blobs. EXT retains its original copy and unpack-limit path. + return type == msgpack::type::STR || type == msgpack::type::BIN; +} + // This function is intended to bind a function to a MessagePack-formatted input data, // perform the function with the unpacked data, then pack the result back into MessagePack format. // Note: output_out and output_len_out are IN-OUT parameters: @@ -62,8 +73,11 @@ inline void msgpack_cbind_impl(const auto& func, // The function to be ap // Args: the parameter types of the function as a tuple. typename FuncTraits::Args params; - // Unpack the input data into the parameter tuple. - msgpack::unpack(reinterpret_cast(input_in), input_len_in).get().convert(params); + // Unpack the input data into the parameter tuple. The input outlives the call, so blobs are referenced in place + // while being converted. + msgpack::unpack(reinterpret_cast(input_in), input_len_in, msgpack_reference_input) + .get() + .convert(params); // Read IN values: caller-provided scratch buffer uint8_t* scratch_buf = *output_out; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp index 4e485f7..9b1cac2 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp @@ -17,6 +17,64 @@ namespace bb::stdlib { using namespace bb::plookup; +namespace { +/** + * @brief Append the plookup rows for one run of slices of `normalize_and_rotate` (see the table in that method) + * @details Each row records the running input (C1) and normalized (C2) accumulators, the most significant normalized + * digit of the slice (C3) and the slice's key/value lookup entry, then divides both accumulators by 11^{bit_slice}. + * This is a runtime loop: it runs for every lane of every round, and a compact body keeps it in the instruction cache. + * + * @param input running input accumulator, shared by the right and left runs (updated) + * @param normalized normalized value of this run's slices + * @param limb_bits number of base-11 digits in this run + * @param num_lookups number of slices (lookup rows) in this run + * @param max_bits_per_table maximum number of base-11 digits per slice + */ +void append_normalize_lookup_rows(plookup::ReadData& lookup, + uint256_t& input, + uint256_t normalized, + const size_t limb_bits, + const size_t num_lookups, + const size_t max_bits_per_table) +{ + constexpr uint64_t base = 11; + for (size_t i = 0; i < num_lookups; ++i) { + const size_t num_bits_processed = i * max_bits_per_table; + + // How many bits can this slice contain? + // We want to implicitly range-constrain `normalized < 11^{limb_bits}`, + // which means potentially using a lookup table that is not of size 11^{max_bits_per_table} + // for the most-significant slice + const size_t bit_slice = + (num_bits_processed + max_bits_per_table > limb_bits) ? limb_bits % max_bits_per_table : max_bits_per_table; + + // current column values are tracked via 'input' and 'normalized' + lookup[ColumnIdx::C1].push_back(input); + lookup[ColumnIdx::C2].push_back(normalized); + + const uint64_t divisor = numeric::pow64(base, bit_slice); + const uint64_t msb_divisor = divisor / base; + + // compute the value of the most significant bit of this slice and store in C3 + const auto [normalized_quotient, normalized_slice] = normalized.divmod(divisor); + + // 256-bit divisions are expensive! cast to u64s when we don't need the extra bits + const uint64_t normalized_msb = (static_cast(normalized_slice) / msb_divisor); + lookup[ColumnIdx::C3].push_back(normalized_msb); + + // We need to provide a key/value object for this lookup in order for the Builder + // to compute the plookup sorted list commitment + const auto [input_quotient, input_slice] = input.divmod(divisor); + lookup.lookup_entries.push_back( + { { static_cast(input_slice), 0 }, { normalized_slice, normalized_msb } }); + + // reduce the input and output by 11^{bit_slice} + input = input_quotient; + normalized = normalized_quotient; + } +} +} // namespace + /** * @brief Normalize a base-11 limb and left-rotate by keccak::ROTATIONS[lane_index] bits. * This method also extracts the most significant bit of the normalised limb. @@ -53,8 +111,7 @@ field_t keccak::normalize_and_rotate(const field_ct& limb, fie // get the numerical value of the left and right bit slices // (lookup table input values derived from left / right) uint256_t input = limb.get_value(); - constexpr uint256_t slice_divisor = BASE.pow(right_bits); - const auto [left, right] = input.divmod(slice_divisor); + const auto [left, right] = divmod_base_power(input); // compute the normalized values for the left and right bit slices // (lookup table output values derived from left_normalised / right_normalized) @@ -102,53 +159,15 @@ field_t keccak::normalize_and_rotate(const field_ct& limb, fie **/ plookup::ReadData lookup; - // compute plookup witness values for a given slice - // (same lambda can be used to compute witnesses for left and right slices) - auto compute_lookup_witnesses_for_limb = [&](uint256_t& normalized) { - // (use a constexpr loop to make some pow and div operations compile-time) - bb::constexpr_for<0, num_lookups, 1>([&] { - constexpr size_t num_bits_processed = i * max_bits_per_table; - - // How many bits can this slice contain? - // We want to implicitly range-constrain `normalized < 11^{limb_bits}`, - // which means potentially using a lookup table that is not of size 11^{max_bits_per_table} - // for the most-significant slice - constexpr size_t bit_slice = (num_bits_processed + max_bits_per_table > limb_bits) - ? limb_bits % max_bits_per_table - : max_bits_per_table; - - // current column values are tracked via 'input' and 'normalized' - lookup[ColumnIdx::C1].push_back(input); - lookup[ColumnIdx::C2].push_back(normalized); - - constexpr uint64_t divisor = numeric::pow64(static_cast(BASE), bit_slice); - constexpr uint64_t msb_divisor = divisor / static_cast(BASE); - - // compute the value of the most significant bit of this slice and store in C3 - const auto [normalized_quotient, normalized_slice] = normalized.divmod(divisor); - - // 256-bit divisions are expensive! cast to u64s when we don't need the extra bits - const uint64_t normalized_msb = (static_cast(normalized_slice) / msb_divisor); - lookup[ColumnIdx::C3].push_back(normalized_msb); - - // We need to provide a key/value object for this lookup in order for the Builder - // to compute the plookup sorted list commitment - const auto [input_quotient, input_slice] = input.divmod(divisor); - lookup.lookup_entries.push_back( - { { static_cast(input_slice), 0 }, { normalized_slice, normalized_msb } }); - - // reduce the input and output by 11^{bit_slice} - input = input_quotient; - normalized = normalized_quotient; - }); - }; - - // template lambda syntax is a little funky. - // Need to explicitly write `.template operator()` (instead of just `()`). - // Otherwise compiler cannot distinguish between `>` symbol referring to closing the template parameter list, - // OR `>` being a greater-than operator :/ - compute_lookup_witnesses_for_limb.template operator()(right_normalized); - compute_lookup_witnesses_for_limb.template operator()(left_normalized); + constexpr size_t num_lookups = num_right_tables + num_left_tables; + for (auto& column : lookup.columns) { + column.reserve(num_lookups); + } + lookup.lookup_entries.reserve(num_lookups); + + // compute plookup witness values for the right slices, then the left slices + append_normalize_lookup_rows(lookup, input, right_normalized, right_bits, num_right_tables, max_bits_per_table); + append_normalize_lookup_rows(lookup, input, left_normalized, left_bits, num_left_tables, max_bits_per_table); // Call builder method to create plookup constraints. // The MultiTable table index can be derived from `lane_idx` @@ -299,12 +318,10 @@ template void keccak::theta(keccak_state& internal) * KECCAK_THETA_OUTPUT currently splices its input into 16 4-bit slices (in base 11 i.e. from 0 to 11^4 - 1) * This ensures that sliced_D is correctly range constrained to be < 11^64 = 11^{KECCAK_LANE_SIZE} */ - static constexpr uint256_t divisor = BASE.pow(KECCAK_LANE_SIZE); for (size_t i = 0; i < 5; ++i) { uint256_t D_native = D[i].get_value(); const auto [D_quotient, lo_native] = D_native.divmod(BASE); - const uint256_t hi_native = D_quotient / divisor; - const uint256_t mid_native = D_quotient - hi_native * divisor; + const auto [hi_native, mid_native] = divmod_base_power(D_quotient); field_ct hi(witness_ct(internal.context, hi_native)); field_ct mid(witness_ct(internal.context, mid_native)); diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.hpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.hpp index 86f54ca..5f55cfa 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 @@ -79,6 +80,36 @@ template class keccak { return output; }; + // Number of base-11 digits whose place value fits in a single uint256_t limb (in 32 bits on wasm, where only + // 64-bit native division is available), so dividing by BASE^BASE_CHUNK_DIGITS takes the single-limb divmod path. +#if defined(__wasm__) + static constexpr size_t BASE_CHUNK_DIGITS = 9; +#else + static constexpr size_t BASE_CHUNK_DIGITS = 18; +#endif + + /** + * @brief Compute input.divmod(BASE^exponent) for a divisor that may span several limbs + * @details floor(floor(x / a) / b) = floor(x / (a * b)), so dividing by BASE^exponent in single-limb chunks of + * BASE^BASE_CHUNK_DIGITS gives the same quotient as one wide division, without the bitwise shift-subtract loop a + * multi-limb divisor needs. The remainder is recovered from the quotient. + * + * @return {input / BASE^exponent, input % BASE^exponent} + */ + template + static constexpr std::pair divmod_base_power(const uint256_t& input) + { + uint256_t quotient = input; + size_t remaining = exponent; + while (remaining > 0) { + const size_t chunk_digits = remaining < BASE_CHUNK_DIGITS ? remaining : BASE_CHUNK_DIGITS; + quotient = quotient.divmod(numeric::pow64(static_cast(BASE), chunk_digits)).first; + remaining -= chunk_digits; + } + constexpr uint256_t divisor = BASE.pow(exponent); + return { quotient, input - quotient * divisor }; + } + /** * @brief Normalize a base-11 integer where each base value can be > 1 * @@ -92,19 +123,26 @@ 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 BASE_CHUNK_DIGITS so that only one wide division is needed per + // chunk and the per-digit work is native 64-bit arithmetic. + constexpr size_t NORMALIZE_CHUNK_DIGITS = BASE_CHUNK_DIGITS; + 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; } diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp index c0e2dac..26e3b07 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp @@ -670,17 +670,20 @@ template class bigfield { * @details We need it for division. If we always add this element during division, then we never run into the * formula-breaking situation */ - static constexpr bigfield unreduced_zero() + static bigfield unreduced_zero() { - uint512_t multiple_of_modulus = ((get_maximum_unreduced_value() / modulus_u512) + 1) * modulus_u512; - auto msb = multiple_of_modulus.get_msb(); + // The multiple of the modulus is a fixed value, so it is computed once + static const uint512_t multiple_of_modulus = + ((get_maximum_unreduced_value() / modulus_u512) + 1) * modulus_u512; + static const uint256_t prime_basis_value = (multiple_of_modulus % uint512_t(field_t::modulus)).lo; + const auto msb = multiple_of_modulus.get_msb(); bigfield result(nullptr, uint256_t(0)); result.binary_basis_limbs[0] = Limb(bb::fr(multiple_of_modulus.slice(0, NUM_LIMB_BITS).lo)); result.binary_basis_limbs[1] = Limb(bb::fr(multiple_of_modulus.slice(NUM_LIMB_BITS, 2 * NUM_LIMB_BITS).lo)); result.binary_basis_limbs[2] = Limb(bb::fr(multiple_of_modulus.slice(2 * NUM_LIMB_BITS, 3 * NUM_LIMB_BITS).lo)); result.binary_basis_limbs[3] = Limb(bb::fr(multiple_of_modulus.slice(3 * NUM_LIMB_BITS, msb + 1).lo)); - result.prime_basis_limb = field_t((multiple_of_modulus % uint512_t(field_t::modulus)).lo); + result.prime_basis_limb = field_t(prime_basis_value); return result; } @@ -788,7 +791,14 @@ template class bigfield { return start_index; } - static constexpr uint512_t get_maximum_unreduced_value() + static uint512_t get_maximum_unreduced_value() + { + // The bound only depends on the moduli, so it is computed once + static const uint512_t maximum_unreduced_value = compute_maximum_unreduced_value(); + return maximum_unreduced_value; + } + + static uint512_t compute_maximum_unreduced_value() { // This = `T * n = 2^272 * |BN(Fr)|` So this equals n*2^t uint1024_t maximum_product = get_maximum_crt_product(); @@ -818,12 +828,15 @@ template class bigfield { } // If we encounter this maximum value of a bigfield we stop execution - static constexpr uint512_t get_prohibited_value() + static uint512_t get_prohibited_value() { - uint1024_t maximum_product = get_maximum_crt_product(); - uint64_t maximum_product_bits = maximum_product.get_msb() - 1; - const size_t arbitrary_secure_margin = 20; - return (uint512_t(1) << ((maximum_product_bits >> 1) + arbitrary_secure_margin)) - uint512_t(1); + static const uint512_t prohibited_value = [] { + uint1024_t maximum_product = get_maximum_crt_product(); + uint64_t maximum_product_bits = maximum_product.get_msb() - 1; + const size_t arbitrary_secure_margin = 20; + return (uint512_t(1) << ((maximum_product_bits >> 1) + arbitrary_secure_margin)) - uint512_t(1); + }(); + return prohibited_value; } /** @@ -835,12 +848,50 @@ template class bigfield { * * @return uint1024_t Maximum product of two bigfield elements in CRT form */ - static constexpr uint1024_t get_maximum_crt_product() + static uint1024_t get_maximum_crt_product() { - uint1024_t maximum_product = uint1024_t(binary_basis.modulus) * uint1024_t(prime_basis.modulus); + static const uint1024_t maximum_product = uint1024_t(binary_basis.modulus) * uint1024_t(prime_basis.modulus); return maximum_product; } + /** + * @brief Compute sum_i limbs[i] * 2^(i * NUM_LIMB_BITS) for limbs below 2^256 + * @details Each shifted limb is assembled from two 256-bit shifts by compile-time amounts, which is cheaper than + * shifting 512-bit integers. + */ + static uint512_t combine_limbs(const std::array& limbs) + { + static_assert(NUM_LIMB_BITS * (NUM_LIMBS - 1) < 256); + uint512_t result(limbs[0]); + result += uint512_t(limbs[1] << NUM_LIMB_BITS, limbs[1] >> (256 - NUM_LIMB_BITS)); + result += uint512_t(limbs[2] << (NUM_LIMB_BITS * 2), limbs[2] >> (256 - (NUM_LIMB_BITS * 2))); + result += uint512_t(limbs[3] << (NUM_LIMB_BITS * 3), limbs[3] >> (256 - (NUM_LIMB_BITS * 3))); + return result; + } + + /** + * @brief Split the low NUM_LIMBS * NUM_LIMB_BITS bits of a value into NUM_LIMB_BITS-bit limbs + * @details Equivalent to value.slice(i * NUM_LIMB_BITS, (i + 1) * NUM_LIMB_BITS) for each limb, using 256-bit + * operations. + */ + static std::array split_into_limbs(const uint512_t& value) + { + static_assert(NUM_LIMB_BITS * (NUM_LIMBS - 1) < 256 && NUM_LIMB_BITS * NUM_LIMBS > 256); + constexpr uint256_t limb_mask = (uint256_t(1) << NUM_LIMB_BITS) - 1; + return { value.lo & limb_mask, + (value.lo >> NUM_LIMB_BITS) & limb_mask, + (value.lo >> (NUM_LIMB_BITS * 2)) & limb_mask, + ((value.lo >> (NUM_LIMB_BITS * 3)) | (value.hi << (256 - (NUM_LIMB_BITS * 3)))) & limb_mask }; + } + + /** + * @brief Reduce a value modulo the target modulus, skipping the division when it is already reduced + */ + static uint512_t reduce_value(const uint512_t& value) + { + return (value < modulus_u512) ? value : value % modulus_u512; + } + /** * @brief Compute the maximum number of bits for quotient range proof to protect against CRT underflow * @@ -858,8 +909,21 @@ template class bigfield { for (const auto& r : remainders_max) { base -= r; } - base /= modulus_u512; - return static_cast(base.get_msb() - 1); + const auto quotient_max_bits = [](const uint1024_t& remainder_bound) { + return static_cast((remainder_bound / modulus_u512).get_msb() - 1); + }; + // The bounds for a single default remainder and for no remainder are fixed, so their bit lengths are computed + // once + static const uint1024_t default_remainder_base = get_maximum_crt_product() - DEFAULT_MAXIMUM_REMAINDER; + static const size_t default_remainder_bits = quotient_max_bits(default_remainder_base); + static const size_t zero_remainder_bits = quotient_max_bits(get_maximum_crt_product()); + if (base == default_remainder_base) { + return default_remainder_bits; + } + if (base == get_maximum_crt_product()) { + return zero_remainder_bits; + } + return quotient_max_bits(base); } /** @@ -1039,17 +1103,6 @@ template class bigfield { static std::pair compute_quotient_remainder_values(const bigfield& a, const bigfield& b, const std::vector& to_add); - /** - * @brief Compute the maximum possible value of quotient of a*b+\sum(to_add) - * - * @param as Multiplicands - * @param bs Multipliers - * @param to_add Added elements - * @return uint512_t The maximum value of quotient - */ - static uint512_t compute_maximum_quotient_value(const std::vector& as, - const std::vector& bs, - const std::vector& to_add); /** * @brief Check for 2 conditions (CRT modulus is overflown or the maximum quotient doesn't fit into range proof). diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_impl.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_impl.hpp index 999edd5..9bb903e 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_impl.hpp @@ -145,11 +145,7 @@ bigfield bigfield::create_from_u512_as_witness(Builder* { BB_ASSERT((can_overflow == true && maximum_bitlength == 0) || (can_overflow == false && (maximum_bitlength == 0 || maximum_bitlength > (3 * NUM_LIMB_BITS)))); - std::array limbs; - limbs[0] = value.slice(0, NUM_LIMB_BITS).lo; - limbs[1] = value.slice(NUM_LIMB_BITS, NUM_LIMB_BITS * 2).lo; - limbs[2] = value.slice(NUM_LIMB_BITS * 2, NUM_LIMB_BITS * 3).lo; - limbs[3] = value.slice(NUM_LIMB_BITS * 3, NUM_LIMB_BITS * 4).lo; + const std::array limbs = split_into_limbs(value); field_t limb_0(ctx); field_t limb_1(ctx); @@ -303,20 +299,18 @@ template bigfield& bigfield uint512_t bigfield::get_value() const { - uint512_t t0 = uint256_t(binary_basis_limbs[0].element.get_value()); - uint512_t t1 = uint256_t(binary_basis_limbs[1].element.get_value()); - uint512_t t2 = uint256_t(binary_basis_limbs[2].element.get_value()); - uint512_t t3 = uint256_t(binary_basis_limbs[3].element.get_value()); - return t0 + (t1 << (NUM_LIMB_BITS)) + (t2 << (2 * NUM_LIMB_BITS)) + (t3 << (3 * NUM_LIMB_BITS)); + return combine_limbs({ uint256_t(binary_basis_limbs[0].element.get_value()), + uint256_t(binary_basis_limbs[1].element.get_value()), + uint256_t(binary_basis_limbs[2].element.get_value()), + uint256_t(binary_basis_limbs[3].element.get_value()) }); } template uint512_t bigfield::get_maximum_value() const { - uint512_t t0 = uint512_t(binary_basis_limbs[0].maximum_value); - uint512_t t1 = uint512_t(binary_basis_limbs[1].maximum_value) << NUM_LIMB_BITS; - uint512_t t2 = uint512_t(binary_basis_limbs[2].maximum_value) << (NUM_LIMB_BITS * 2); - uint512_t t3 = uint512_t(binary_basis_limbs[3].maximum_value) << (NUM_LIMB_BITS * 3); - return t0 + t1 + t2 + t3; + return combine_limbs({ binary_basis_limbs[0].maximum_value, + binary_basis_limbs[1].maximum_value, + binary_basis_limbs[2].maximum_value, + binary_basis_limbs[3].maximum_value }); } template @@ -500,8 +494,8 @@ bigfield bigfield::operator-(const bigfield& other) cons other.reduction_check(); if (is_constant() && other.is_constant()) { - uint512_t left = get_value() % modulus_u512; - uint512_t right = other.get_value() % modulus_u512; + uint512_t left = reduce_value(get_value()); + uint512_t right = reduce_value(other.get_value()); uint512_t out = (left + modulus_u512 - right) % modulus_u512; auto result = bigfield(ctx, uint256_t(out.lo)); @@ -510,8 +504,8 @@ bigfield bigfield::operator-(const bigfield& other) cons } if (other.is_constant()) { - uint512_t right = other.get_value() % modulus_u512; - uint512_t neg_right = (modulus_u512 - right) % modulus_u512; + uint512_t right = reduce_value(other.get_value()); + uint512_t neg_right = (right == 0) ? uint512_t(0) : modulus_u512 - right; bigfield summand = bigfield(ctx, uint256_t(neg_right.lo)); summand.set_origin_tag(OriginTag(other.get_origin_tag())); return operator+(summand); @@ -570,9 +564,11 @@ bigfield bigfield::operator-(const bigfield& other) cons * * Start by setting constant_to_add = p **/ - uint1024_t constant_to_add_factor = - (uint1024_t(limb_3_maximum_value) << (NUM_LIMB_BITS * 3)) / uint1024_t(modulus_u512) + uint1024_t(1); - uint512_t constant_to_add = constant_to_add_factor.lo * modulus_u512; + // (limb_3_maximum_value < 2^256, so the shifted value fits in 256 + 3 * NUM_LIMB_BITS < 512 bits) + static_assert(256 + (NUM_LIMB_BITS * 3) < 512); + uint512_t constant_to_add_factor = + (uint512_t(limb_3_maximum_value) << (NUM_LIMB_BITS * 3)) / modulus_u512 + uint512_t(1); + uint512_t constant_to_add = constant_to_add_factor * modulus_u512; /** * Step 3: Compute offset terms t0, t1, t2, t3 that we add to our result to ensure each limb is positive @@ -1493,7 +1489,7 @@ bigfield bigfield::msub_div(const std::vector& { // Check the basics BB_ASSERT_EQ(mul_left.size(), mul_right.size()); - BB_ASSERT((divisor.get_value() % modulus_u512) != 0, "bigfield: Division by zero in msub_div"); + BB_ASSERT(reduce_value(divisor.get_value()) != 0, "bigfield: Division by zero in msub_div"); OriginTag new_tag = divisor.get_origin_tag(); for (auto [left_element, right_element] : zip_view(mul_left, mul_right)) { @@ -1539,8 +1535,8 @@ bigfield bigfield::msub_div(const std::vector& // Compute the sum of products for (size_t i = 0; i < num_multiplications; ++i) { - const native mul_left_native(uint512_t(mul_left[i].get_value() % modulus_u512).lo); - const native mul_right_native(uint512_t(mul_right[i].get_value() % modulus_u512).lo); + const native mul_left_native(reduce_value(mul_left[i].get_value()).lo); + const native mul_right_native(reduce_value(mul_right[i].get_value()).lo); product_native += (mul_left_native * -mul_right_native); products_constant = products_constant && mul_left[i].is_constant() && mul_right[i].is_constant(); } @@ -1549,11 +1545,11 @@ bigfield bigfield::msub_div(const std::vector& native sub_native(0); bool sub_constant = true; for (const auto& sub : to_sub) { - sub_native += (uint512_t(sub.get_value() % modulus_u512).lo); + sub_native += (reduce_value(sub.get_value()).lo); sub_constant = sub_constant && sub.is_constant(); } - native divisor_native(uint512_t(divisor.get_value() % modulus_u512).lo); + native divisor_native(reduce_value(divisor.get_value()).lo); // Compute the result const native result_native = (product_native - sub_native) / divisor_native; @@ -1715,8 +1711,8 @@ bigfield bigfield::conditional_select(const bigfield& ot template bool_t bigfield::operator==(const bigfield& other) const { Builder* ctx = context ? context : other.get_context(); - auto lhs = get_value() % modulus_u512; - auto rhs = other.get_value() % modulus_u512; + auto lhs = reduce_value(get_value()); + auto rhs = reduce_value(other.get_value()); bool is_equal_raw = (lhs == rhs); if (is_constant() && other.is_constant()) { return is_equal_raw; @@ -1730,7 +1726,7 @@ template bool_t bigfield::op is_equal.set_origin_tag(OriginTag(get_origin_tag(), other.get_origin_tag())); bigfield diff = (*this) - other; - native diff_native = native((diff.get_value() % modulus_u512).lo); + native diff_native = native(reduce_value(diff.get_value()).lo); native inverse_native = is_equal_raw ? 0 : diff_native.invert(); bigfield inverse = bigfield::from_witness(ctx, inverse_native); @@ -1756,7 +1752,7 @@ template bool_t bigfield::op template void bigfield::reduction_check() const { if (is_constant()) { - uint256_t reduced_value = (get_value() % modulus_u512).lo; + uint256_t reduced_value = reduce_value(get_value()).lo; bigfield reduced(context, uint256_t(reduced_value)); // Save tags const auto origin_tags = std::vector({ binary_basis_limbs[0].element.get_origin_tag(), @@ -1837,7 +1833,7 @@ void bigfield::assert_less_than(const uint256_t& upper_limit, std::s { // For constant bigfields, just verify the value is in range (no circuit constraints needed) if (is_constant()) { - BB_ASSERT((get_value() % modulus_u512).lo < upper_limit, msg); + BB_ASSERT(reduce_value(get_value()).lo < upper_limit, msg); return; } @@ -2039,8 +2035,8 @@ void bigfield::assert_equal(const bigfield& other, std::string const return; } else { // Catch the error if the reduced value of the two elements are not equal - uint512_t lhs_reduced_value = get_value() % modulus_u512; - uint512_t rhs_reduced_value = other.get_value() % modulus_u512; + uint512_t lhs_reduced_value = reduce_value(get_value()); + uint512_t rhs_reduced_value = reduce_value(other.get_value()); if ((lhs_reduced_value != rhs_reduced_value) && !get_context()->failed()) { get_context()->failure(msg); } @@ -2772,29 +2768,6 @@ std::pair bigfield::compute_quotient_remainder return { quotient_1024.lo, remainder_1024.lo }; } -template -uint512_t bigfield::compute_maximum_quotient_value(const std::vector& as, - const std::vector& bs, - const std::vector& to_add) -{ - BB_ASSERT_EQ(as.size(), bs.size()); - BB_ASSERT_LTE(to_add.size(), MAXIMUM_SUMMAND_COUNT); - - uint512_t add_values(0); - for (const auto& add_element : to_add) { - add_values += add_element; - } - uint1024_t product_sum(0); - for (size_t i = 0; i < as.size(); i++) { - product_sum += uint1024_t(as[i]) * uint1024_t(bs[i]); - } - const uint1024_t add_right(add_values); - const uint1024_t modulus(target_basis.modulus); - - const auto [quotient_1024, remainder_1024] = (product_sum + add_right).divmod(modulus); - - return quotient_1024.lo; -} template std::pair bigfield::get_quotient_reduction_info(const std::vector& as_max, const std::vector& bs_max, @@ -2816,11 +2789,17 @@ std::pair bigfield::get_quotient_reduction_info(const for (auto& added_element : to_add) { to_add_max.push_back(added_element.get_maximum_value()); } - // Get maximum value of quotient - const uint512_t maximum_quotient = compute_maximum_quotient_value(as_max, bs_max, to_add_max); - - // Check if the quotient can fit into the range proof - if (maximum_quotient >= (uint512_t(1) << num_quotient_bits)) { + // Check if the maximum quotient floor((sum as_max * bs_max + sum to_add_max) / p) can fit into the range proof. + // floor(x / p) >= 2^k exactly when x >= p * 2^k, so no division is needed. + uint1024_t maximum_product_sum(0); + for (size_t i = 0; i < as_max.size(); i++) { + maximum_product_sum += uint1024_t(as_max[i]) * uint1024_t(bs_max[i]); + } + uint512_t maximum_add_sum(0); + for (const auto& add_max : to_add_max) { + maximum_add_sum += add_max; + } + if (maximum_product_sum + uint1024_t(maximum_add_sum) >= (uint1024_t(modulus_u512) << num_quotient_bits)) { return std::pair(true, 0); } return std::pair(false, num_quotient_bits); diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.cpp index 04341a2..f1bb794 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.cpp @@ -21,7 +21,7 @@ template field_t::field_t(Builder* parent_context) : context(parent_context) , additive_constant(bb::fr::zero()) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -31,7 +31,7 @@ template field_t::field_t(const witness_t& value) : context(value.context) , additive_constant(bb::fr::zero()) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(value.witness_index) { set_free_witness_tag(); @@ -41,7 +41,7 @@ template field_t::field_t(Builder* parent_context, const bb::fr& value) : context(parent_context) , additive_constant(value) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -53,12 +53,12 @@ field_t::field_t(const bool_t& other) { if (other.is_constant()) { additive_constant = other.get_value(); - multiplicative_constant = bb::fr::one(); + multiplicative_constant = ONE; witness_index = IS_CONSTANT; } else { witness_index = other.witness_index; - additive_constant = other.witness_inverted ? bb::fr::one() : bb::fr::zero(); - multiplicative_constant = other.witness_inverted ? bb::fr::neg_one() : bb::fr::one(); + additive_constant = other.witness_inverted ? ONE : bb::fr::zero(); + multiplicative_constant = other.witness_inverted ? NEG_ONE : ONE; } tag = other.tag; } @@ -87,17 +87,17 @@ template field_t::operator bool_t() const // After ensuring that `additive_constant` \in {0, 1}, we set the `.witness_bool` field of `result` to match the // value of `additive_constant`. if (is_constant()) { - BB_ASSERT(additive_constant == bb::fr::one() || additive_constant == bb::fr::zero(), + BB_ASSERT(additive_constant == ONE || additive_constant == bb::fr::zero(), "Attempting to create a bool_t from a witness_t not satisfying x^2 - x = 0"); bool_t result(context); - result.witness_bool = (additive_constant == bb::fr::one()); + result.witness_bool = (additive_constant == ONE); result.set_origin_tag(tag); return result; } const bool add_constant_check = (additive_constant == bb::fr::zero()); - const bool mul_constant_check = (multiplicative_constant == bb::fr::one()); - const bool inverted_check = (additive_constant == bb::fr::one()) && (multiplicative_constant == bb::fr::neg_one()); + const bool mul_constant_check = (multiplicative_constant == ONE); + const bool inverted_check = (additive_constant == ONE) && (multiplicative_constant == NEG_ONE); bool result_inverted = false; // Process the elements of the form // a = a.v * 1 + 0 and a = a.v * (-1) + 1 @@ -115,9 +115,9 @@ template field_t::operator bool_t() const } // Get the normalized value of the witness bb::fr witness = context->get_variable(witness_idx); - BB_ASSERT(witness == bb::fr::zero() || witness == bb::fr::one(), + BB_ASSERT(witness == bb::fr::zero() || witness == ONE, "Attempting to create a bool_t from a witness_t not satisfying x^2 - x = 0"); - bool_t result(context, witness == bb::fr::one()); + bool_t result(context, witness == ONE); result.witness_inverted = result_inverted; result.witness_index = witness_idx; context->create_bool_gate(witness_idx); @@ -173,7 +173,7 @@ template field_t field_t::operator+(const f .c = result.witness_index, .a_scaling = multiplicative_constant, .b_scaling = other.multiplicative_constant, - .c_scaling = bb::fr::neg_one(), + .c_scaling = NEG_ONE, .const_scaling = (additive_constant + other.additive_constant) }); } result.tag = OriginTag(tag, other.tag); @@ -289,7 +289,7 @@ template field_t field_t::operator*(const f .q_m = q_m, .q_l = q_l, .q_r = q_r, - .q_o = bb::fr::neg_one(), + .q_o = NEG_ONE, .q_c = q_c }); } result.tag = OriginTag(tag, other.tag); @@ -329,7 +329,7 @@ template field_t field_t::divide_no_zero_ch // Ensure that non-constant circuit elements can not be divided without context BB_ASSERT(ctx || (is_constant() && other.is_constant())); - bb::fr additive_multiplier = bb::fr::one(); + bb::fr additive_multiplier = ONE; if (is_constant() && other.is_constant()) { // Both inputs are constant, the result is given by @@ -433,7 +433,7 @@ template field_t field_t::pow(const uint32_ return field_t(get_value().pow(exponent)); } if (exponent == 0) { - return field_t(bb::fr::one()); + return field_t(ONE); } bool accumulator_initialized = false; @@ -501,8 +501,8 @@ field_t field_t::pow(const field_t& exponent) const exponent.assert_equal(exponent_accumulator, "field_t::pow exponent accumulator incorrect"); // Compute the result of exponentiation - field_t accumulator(ctx, bb::fr::one()); - const field_t one(bb::fr::one()); + field_t accumulator(ctx, ONE); + const field_t one(ONE); for (size_t i = 0; i < num_bits; ++i) { accumulator *= accumulator; // If current bit == 1, multiply by the base, else propagate the accumulator @@ -572,7 +572,7 @@ template field_t field_t::madd(const field_ .a_scaling = a_scaling, .b_scaling = b_scaling, .c_scaling = c_scaling, - .d_scaling = bb::fr::neg_one(), + .d_scaling = NEG_ONE, .const_scaling = const_scaling, }); result.tag = OriginTag(tag, to_mul.tag, to_add.tag); @@ -631,7 +631,7 @@ template field_t field_t::add_two(const fie .a_scaling = a_scaling, .b_scaling = b_scaling, .c_scaling = c_scaling, - .d_scaling = bb::fr::neg_one(), + .d_scaling = NEG_ONE, .const_scaling = const_scaling, }); result.tag = OriginTag(tag, add_b.tag, add_c.tag); @@ -660,7 +660,7 @@ template field_t field_t::normalize() const result.witness_index = context->add_variable(value * multiplicative_constant + additive_constant); result.additive_constant = bb::fr::zero(); - result.multiplicative_constant = bb::fr::one(); + result.multiplicative_constant = ONE; // The aim of a new `add` gate is to constrain // this.v * this.mul + this.add == result.v @@ -677,7 +677,7 @@ template field_t field_t::normalize() const .c = result.witness_index, .a_scaling = multiplicative_constant, .b_scaling = bb::fr::zero(), - .c_scaling = bb::fr::neg_one(), + .c_scaling = NEG_ONE, .const_scaling = additive_constant }); result.tag = tag; return result; @@ -752,7 +752,7 @@ template void field_t::assert_is_not_zero(std::strin .q_l = bb::fr::zero(), // a * 0 .q_r = additive_constant, // b * mul_const .q_o = bb::fr::zero(), // c * 0 - .q_c = bb::fr::neg_one(), // -1 + .q_c = NEG_ONE, // -1 }); } @@ -797,7 +797,7 @@ template bool_t field_t::is_zero() const bool_t is_zero = witness_t(context, is_zero_raw); // This can be done out of circuit, as `is_zero = true` implies `I = 1`. - bb::fr inverse_native = (is_zero_raw) ? bb::fr::one() : native_value.invert(); + bb::fr inverse_native = (is_zero_raw) ? ONE : native_value.invert(); field_t inverse = witness_t(context, inverse_native); @@ -813,7 +813,7 @@ template bool_t field_t::is_zero() const // c_scaling := 1; // d_scaling := 0; // const_scaling := a.add * I.add + is_zero.add - 1; - field_t::evaluate_polynomial_identity(*this, inverse, is_zero, bb::fr::neg_one()); + field_t::evaluate_polynomial_identity(*this, inverse, is_zero, NEG_ONE); // To check that `-is_zero * I + is_zero = 0`, create a `big_mul_gate` given by the equation: // is_zero.v * (-I).v * mul_scaling + is_zero.v * a_scaling + (-I).v * b_scaling + is_zero.v * c_scaling + 0 * @@ -841,7 +841,7 @@ template bb::fr field_t::get_value() const BB_ASSERT(context); return (multiplicative_constant * context->get_variable(witness_index)) + additive_constant; } - BB_ASSERT_DEBUG(multiplicative_constant == bb::fr::one()); + BB_ASSERT_DEBUG(multiplicative_constant == ONE); // A constant field_t's value is tracked wholly by its additive_constant member. return additive_constant; } diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp index 26cb034..8d6326f 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp @@ -49,6 +49,11 @@ template class field_t { static constexpr size_t PUBLIC_INPUTS_SIZE = FR_PUBLIC_INPUTS_SIZE; + // Montgomery-form 1 and -1, evaluated at compile time. Outside a constant expression bb::fr::one() and + // bb::fr::neg_one() convert to Montgomery form at runtime, and every constructor needs the constant 1. + static constexpr bb::fr ONE = bb::fr::one(); + static constexpr bb::fr NEG_ONE = bb::fr::neg_one(); + // Friend declarations for classes that need direct witness_index access template friend class bool_t; template friend class bigfield; @@ -153,7 +158,7 @@ template class field_t { field_t(const int value) : context(nullptr) , additive_constant(bb::fr(value)) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -163,7 +168,7 @@ template class field_t { field_t(const unsigned long long value) : context(nullptr) , additive_constant(bb::fr(value)) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -172,7 +177,7 @@ template class field_t { field_t(const unsigned int value) : context(nullptr) , additive_constant(bb::fr(value)) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -182,7 +187,7 @@ template class field_t { field_t(const unsigned long value) : context(nullptr) , additive_constant(bb::fr(value)) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -192,7 +197,7 @@ template class field_t { field_t(const bb::fr& value) : context(nullptr) , additive_constant(value) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -202,7 +207,7 @@ template class field_t { field_t(const uint256_t& value) : context(nullptr) , additive_constant(value) - , multiplicative_constant(bb::fr::one()) + , multiplicative_constant(ONE) , witness_index(IS_CONSTANT) { tag = OriginTag::constant(); @@ -334,7 +339,7 @@ template class field_t { // `divide_no_zero_check`, hence we can safely apply the latter instead of `/` operator. if (is_constant()) { BB_ASSERT(!get_value().is_zero(), "field_t::invert denominator is constant 0"); - return field_t(fr::one()).divide_no_zero_check(*this); + return field_t(ONE).divide_no_zero_check(*this); } auto* ctx = get_context(); @@ -342,7 +347,7 @@ template class field_t { ctx->failure("field_t::invert denominator is 0"); } - return field_t(fr::one()).divide_no_zero_check(*this); + return field_t(ONE).divide_no_zero_check(*this); } field_t operator-() const @@ -455,7 +460,7 @@ template class field_t { bool is_constant() const { return witness_index == IS_CONSTANT; } bool is_normalized() const { - return (is_constant() || ((multiplicative_constant == bb::fr::one()) && (additive_constant == bb::fr::zero()))); + return (is_constant() || ((multiplicative_constant == ONE) && (additive_constant == bb::fr::zero()))); }; uint32_t set_public() const { diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp index 38e827d..df3fc55 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp @@ -308,6 +308,9 @@ template class SumcheckProver { // both inherit from AllEntities using ProverPolynomials = typename Flavor::ProverPolynomials; using PartiallyEvaluatedMultivariates = typename Flavor::PartiallyEvaluatedMultivariates; + // Native Ultra/Mega flavors run the second round on the full polynomials folded on access, so their partially + // evaluated tables are first built after two rounds, at a quarter of the trace size instead of half. + static constexpr bool DEFERS_FIRST_FOLD = HasLazyShortEdges && !Flavor::HasZK; using ClaimedEvaluations = typename Flavor::AllValues; using ZKData = ZKSumcheckData; using Transcript = typename Flavor::Transcript; @@ -406,7 +409,10 @@ template class SumcheckProver { multivariate_challenge.reserve(virtual_log_n); // In the first round, we compute the first univariate polynomial and populate the book-keeping table of - // #partially_evaluated_polynomials, which has \f$ n/2 \f$ rows and \f$ N \f$ columns. + // #partially_evaluated_polynomials, which has \f$ n/2 \f$ rows and \f$ N \f$ columns. Flavors that defer the + // first fold also run the second round here, on the full polynomials folded on access, and populate the table + // after it with \f$ n/4 \f$ rows. + size_t first_table_round = 1; PartiallyEvaluatedMultivariates partially_evaluated_polynomials = [&] { BB_BENCH_NAME("sumcheck loop 0"); auto round_univariate = @@ -417,13 +423,39 @@ template class SumcheckProver { FF round_challenge = transcript->template get_challenge("Sumcheck:u_0"); multivariate_challenge.emplace_back(round_challenge); + if constexpr (DEFERS_FIRST_FOLD) { + if (multivariate_d > 1) { + gate_separators.partially_evaluate(round_challenge); + round.advance_round(); + + using FoldedMultivariates = + FoldedMultivariatesBase>, + ProverPolynomials, + FF>; + const FoldedMultivariates folded_polynomials(full_polynomials, round_challenge); + round_univariate = + round.compute_univariate(folded_polynomials, relation_parameters, gate_separators, alphas); + transcript->send_to_verifier("Sumcheck:univariate_1", round_univariate); + const FF second_challenge = transcript->template get_challenge("Sumcheck:u_1"); + multivariate_challenge.emplace_back(second_challenge); + + // Populate the book-keeping table + auto result = + partially_evaluate_first_two_rounds(full_polynomials, round_challenge, second_challenge); + gate_separators.partially_evaluate(second_challenge); + round.advance_round(); + first_table_round = 2; + return result; + } + } + // Populate the book-keeping table auto result = partially_evaluate_first_round(full_polynomials, round_challenge); gate_separators.partially_evaluate(round_challenge); round.advance_round(); return result; }(); - for (size_t round_idx = 1; round_idx < multivariate_d; round_idx++) { + for (size_t round_idx = first_table_round; round_idx < multivariate_d; round_idx++) { BB_BENCH_NAME("sumcheck loop"); // Write the round univariate to the transcript @@ -653,8 +685,8 @@ template class SumcheckProver { * * Per polynomial, output k folds the adjacent source pair: dst[k] = src[2k] + r * (src[2k+1] - src[2k]). * The per-output kernel (scalar tail + WASM SIMD bulk, virtual-zero prefix handling, in-place aliasing) - * lives in `bb::fold_stride2`; this method just halves each polynomial's active extent around it. The - * number of outputs is ceil(limit/2) = (limit / 2) + (limit % 2), matching the shrunk end index. + * lives in `bb::fold_stride2`; this method just halves each polynomial's backed range [start, end) to + * [floor(start/2), ceil(end/2)) around it (see `bb::fold_stride2_backed`). */ static void partially_evaluate(auto& source_polynomials, PartiallyEvaluatedMultivariates& dest_polynomials, @@ -664,14 +696,9 @@ template class SumcheckProver { auto dest_view = dest_polynomials.get_all(); parallel_for(source_view.size(), [&](size_t j) { BB_BENCH_TRACY_NAME("Sumcheck::partially_evaluate"); - const auto& poly = source_view[j]; - auto& dest = dest_view[j]; - const size_t limit = poly.end_index(); - // One output per source pair (2k, 2k+1); when limit is odd the last source slot is unpaired - // and folds against an implicit zero, so we round up: ceil(limit / 2). - const size_t num_outputs = (limit / 2) + (limit % 2); - fold_stride2(poly, dest, /*begin=*/0, /*end=*/num_outputs, round_challenge); - dest.shrink_end_index(num_outputs); + // One output per source pair (2k, 2k+1); an unpaired slot at either end of the backed range folds + // against an implicit zero. + fold_stride2_backed(source_view[j], dest_view[j], round_challenge); }); // Halve the active-row prefix to track the folded trace; the loop above leaves the member untouched, so this // reads the pre-round value even when source and dest alias (see partially_evaluate_in_place). @@ -698,6 +725,26 @@ template class SumcheckProver { return partially_evaluated_polynomials; } + /** + * @brief Build the book-keeping table after the first two rounds directly from the full polynomials. + * @details Each entry equals what partially_evaluate_first_round followed by partially_evaluate_in_place would + * store (see `bb::fold_stride4_backed`), without materializing the table of the first round. + */ + PartiallyEvaluatedMultivariates partially_evaluate_first_two_rounds(ProverPolynomials& full_polynomials, + const FF& first_challenge, + const FF& second_challenge) + { + PartiallyEvaluatedMultivariates partially_evaluated_polynomials( + full_polynomials, multivariate_n, /*num_folds=*/2); + auto source_view = full_polynomials.get_all(); + auto dest_view = partially_evaluated_polynomials.get_all(); + parallel_for(source_view.size(), [&](size_t j) { + BB_BENCH_TRACY_NAME("Sumcheck::partially_evaluate"); + fold_stride4_backed(source_view[j], dest_view[j], first_challenge, second_challenge); + }); + return partially_evaluated_polynomials; + } + /** * @brief Evaluate at the round challenge in-place. */ 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