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/bb/cli.cpp b/barretenberg/cpp/src/barretenberg/bb/cli.cpp index 44c0690..38944e3 100644 --- a/barretenberg/cpp/src/barretenberg/bb/cli.cpp +++ b/barretenberg/cpp/src/barretenberg/bb/cli.cpp @@ -28,6 +28,7 @@ #include "barretenberg/bbapi/c_bind.hpp" #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/get_bytecode.hpp" +#include "barretenberg/common/malloc_policy.hpp" #include "barretenberg/common/memory_profile.hpp" #include "barretenberg/common/thread.hpp" #include "barretenberg/common/version.hpp" @@ -860,6 +861,16 @@ int parse_and_run_cli_command(int argc, char* argv[]) bb_log_level = LogLevel::VERBOSE; } slow_low_memory = flags.slow_low_memory; + // AVM and UltraHonk proving keep freed heap memory for reuse instead of trimming it on one thread mid-proof (see + // command_keeps_heap()); every other command, Chonk included, and --slow_low_memory leave the settings in force + // untouched. This runs before any worker the command creates (mallopt is not thread-safe). + std::string_view command; + for (const CLI::App* subcommand : app.get_subcommands()) { + if (subcommand->parsed()) { + command = subcommand->get_name(); + } + } + configure_process_malloc_and_log(command_keeps_heap(command, flags.scheme, flags.slow_low_memory)); #if !defined(__wasm__) || defined(ENABLE_WASM_BENCH) if (!flags.storage_budget.empty()) { storage_budget = parse_size_string(flags.storage_budget); diff --git a/barretenberg/cpp/src/barretenberg/bb/main.cpp b/barretenberg/cpp/src/barretenberg/bb/main.cpp index eeb0879..5945787 100644 --- a/barretenberg/cpp/src/barretenberg/bb/main.cpp +++ b/barretenberg/cpp/src/barretenberg/bb/main.cpp @@ -1,4 +1,5 @@ #include "barretenberg/bb/cli.hpp" +#include "barretenberg/common/exit_release.hpp" #ifdef _WIN32 #include @@ -14,5 +15,14 @@ int main(int argc, char* argv[]) _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); #endif - return bb::parse_and_run_cli_command(argc, argv); + const int rc = bb::parse_and_run_cli_command(argc, argv); + if (rc == 0) { + // On success, skip the single-core teardown of the process's memory. Every output file (proof, VK, public + // inputs through write_file's open/write/close; --bench_out*, traces, --memory_profile_out through scoped + // std::ofstream) is closed by now. What a normal exit still writes is written first: the BB_BENCH report of + // ~GlobalBenchStatsContainer, the one writing destructor (bb has no atexit hook), and the buffered streams. + // Whenever that cannot be done safely it returns, and the normal exit runs. + bb::release_memory_and_exit(rc); + } + return rc; } 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/commitment_key.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp index 8e13eb5..a724783 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/commitment_key.hpp @@ -131,6 +131,34 @@ template class CommitmentKey { return std::vector(results.begin(), results.end()); }; + /** + * @brief batch_commit with an explicit small-member MSM schedule; the commitments equal batch_commit's. + */ + std::vector batch_commit(RefSpan> polynomials, + std::span dedup_infos, + scalar_multiplication::SmallMsmSchedule schedule) const + { + BB_BENCH_NAME("CommitmentKey::batch_commit"); + + std::vector> scalar_spans; + scalar_spans.reserve(polynomials.size()); + + for (auto& polynomial : polynomials) { + const size_t consumed_srs = polynomial.start_index() + polynomial.size(); + if (consumed_srs > get_monomial_size()) { + throw_or_abort(format("Attempting to commit to a polynomial that needs ", + consumed_srs, + " points with an SRS of size ", + get_monomial_size())); + } + scalar_spans.emplace_back(polynomial.start_index(), polynomial.coeffs()); + } + + auto results = scalar_multiplication::MSM::batch_multi_scalar_mul( + get_monomial_points(), scalar_spans, dedup_infos, schedule); + return std::vector(results.begin(), results.end()); + }; + // helper builder struct for constructing a batch to commit at once struct CommitBatch { CommitmentKey* key; @@ -149,6 +177,16 @@ template class CommitmentKey { return commitments; } + std::vector commit_and_send_to_verifier(auto transcript, + scalar_multiplication::SmallMsmSchedule schedule) + { + std::vector commitments = key->batch_commit(wires, dedup_infos, schedule); + for (size_t i = 0; i < commitments.size(); ++i) { + transcript->send_to_verifier(labels[i], commitments[i]); + } + return commitments; + } + void add_to_batch(Polynomial& poly, const std::string& label, bool has_duplicates_hint = false, 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/bb_bench.cpp b/barretenberg/cpp/src/barretenberg/common/bb_bench.cpp index cef6a65..73baf0f 100644 --- a/barretenberg/cpp/src/barretenberg/common/bb_bench.cpp +++ b/barretenberg/cpp/src/barretenberg/common/bb_bench.cpp @@ -237,6 +237,11 @@ AggregateData GlobalBenchStatsContainer::aggregate() const } GlobalBenchStatsContainer::~GlobalBenchStatsContainer() +{ + print_exit_report_if_requested(); +} + +void GlobalBenchStatsContainer::print_exit_report_if_requested() const { if (std::getenv("BB_BENCH") != nullptr) { print_aggregate_counts_hierarchical(std::cerr); diff --git a/barretenberg/cpp/src/barretenberg/common/bb_bench.hpp b/barretenberg/cpp/src/barretenberg/common/bb_bench.hpp index 17ed87c..c1e9c13 100644 --- a/barretenberg/cpp/src/barretenberg/common/bb_bench.hpp +++ b/barretenberg/cpp/src/barretenberg/common/bb_bench.hpp @@ -122,6 +122,8 @@ struct GlobalBenchStatsContainer { void print_stats_recursive(const OperationKey& key, const TimeStats* stats, const std::string& indent) const; void print_aggregate_counts(std::ostream&, size_t) const; void print_aggregate_counts_hierarchical(std::ostream&) const; + // The report written at exit when BB_BENCH is set (by the destructor, or by an exit that skips destructors). + void print_exit_report_if_requested() const; void serialize_aggregate_data_json(std::ostream&) const; // Chrome Trace Event Format output for Perfetto / chrome://tracing. // serialize_trace_events_json emits every captured per-call event (requires 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/exit_release.cpp b/barretenberg/cpp/src/barretenberg/common/exit_release.cpp new file mode 100644 index 0000000..5daaa60 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/exit_release.cpp @@ -0,0 +1,443 @@ +#include "barretenberg/common/exit_release.hpp" + +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) && !defined(__wasm__) && !defined(NO_MULTITHREADING) +#define BB_EXIT_RELEASE_SUPPORTED 1 +#endif +// Sanitizers report from exit handlers, which _exit skips. +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) +#undef BB_EXIT_RELEASE_SUPPORTED +#endif +#if defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || __has_feature(memory_sanitizer) +#undef BB_EXIT_RELEASE_SUPPORTED +#endif +#endif + +#ifdef BB_EXIT_RELEASE_SUPPORTED +#include "barretenberg/common/bb_bench.hpp" +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/thread.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Coverage runtimes write their data from exit handlers, which _exit skips; with one linked in, exit the normal way. +extern "C" int __llvm_profile_write_file(void) __attribute__((weak)); +extern "C" void __gcov_dump(void) __attribute__((weak)); +extern ElfW(Dyn) _DYNAMIC[] __attribute__((weak)); +#endif + +namespace bb { + +std::optional> select_exit_release_ranges(std::string_view maps, + std::span excluded, + std::span pinned, + size_t min_bytes) +{ + std::vector out; + while (!maps.empty()) { + const size_t eol = maps.find('\n'); + const std::string line(maps.substr(0, eol)); + maps.remove_prefix(eol == std::string_view::npos ? maps.size() : eol + 1); + if (line.empty()) { + continue; + } + // "begin-end perms offset dev inode [path]" + uintptr_t begin = 0; + uintptr_t end = 0; + char perms[5] = {}; + int path_at = -1; + if (std::sscanf(line.c_str(), "%" SCNxPTR "-%" SCNxPTR " %4s %*s %*s %*s%n", &begin, &end, perms, &path_at) != + 3 || + path_at < 0 || end <= begin || std::strlen(perms) < 4) { + return std::nullopt; + } + const size_t path_start = line.find_first_not_of(' ', static_cast(path_at)); + const std::string_view path = + path_start == std::string::npos ? std::string_view{} : std::string_view(line).substr(path_start); + const bool private_writable = perms[1] == 'w' && perms[3] == 'p'; + const bool anonymous = path.empty() || path == "[heap]" || path.starts_with("[anon:"); + if (!private_writable || !anonymous || + std::ranges::any_of(pinned, [&](uintptr_t a) { return a >= begin && a < end; })) { + continue; + } + std::vector pieces{ { begin, end } }; + for (const MemoryRange& cut : excluded) { + std::vector next; + for (const MemoryRange& piece : pieces) { + if (cut.end <= piece.begin || cut.begin >= piece.end) { + next.push_back(piece); + continue; + } + if (cut.begin > piece.begin) { + next.push_back({ piece.begin, cut.begin }); + } + if (cut.end < piece.end) { + next.push_back({ cut.end, piece.end }); + } + } + pieces = std::move(next); + } + for (const MemoryRange& piece : pieces) { + if (piece.end - piece.begin >= min_bytes) { + out.push_back(piece); + } + } + } + return out; +} + +#ifndef BB_EXIT_RELEASE_SUPPORTED +ExitReleaseSystem default_exit_release_system() +{ + return { nullptr, nullptr, nullptr, nullptr }; +} + +bool release_memory_and_exit(int /*code*/, const ExitReleaseSystem& /*system*/) +{ + return false; +} +#else +namespace { +constexpr size_t MIN_MAPPING_BYTES = size_t{ 2 } << 20; +constexpr size_t MIN_TOTAL_BYTES = size_t{ 64 } << 20; // below this the serial exit is a few ms +constexpr size_t BYTES_PER_WORKER = size_t{ 32 } << 20; +constexpr uint32_t MAX_WORKERS = 16; +constexpr size_t WORKER_STACK_BYTES = size_t{ 256 } << 10; +constexpr size_t MAX_RANGES = 8192; +// Covers the calling thread's TCB (stack-protector canary included) next to its static TLS blocks. +constexpr uintptr_t TLS_WINDOW_BYTES = uintptr_t{ 64 } << 10; +// How long the thread count may take to reach what is expected (a joined thread stays counted until the kernel +// releases it) before the normal exit is taken instead. +constexpr auto THREAD_COUNT_WAIT = std::chrono::milliseconds(2); + +enum : uint32_t { WAIT = 0, RELEASE = 1, ABORT = 2 }; + +// Everything the release threads read lives in the scratch mapping, which is never released. +struct ReleaseState { + std::atomic ready{ 0 }; + std::atomic go{ WAIT }; + std::atomic done{ 0 }; + std::atomic failed{ 0 }; // madvise calls that returned an error (exit frees those pages) + uint32_t num_workers = 0; + uint64_t page_bytes = 0; + uint64_t total_bytes = 0; + size_t num_ranges = 0; + MemoryRange ranges[MAX_RANGES]; +}; +struct WorkerArg { + ReleaseState* state; + uint32_t index; +}; +constexpr size_t SCRATCH_BYTES = + (MAX_WORKERS * WORKER_STACK_BYTES) + sizeof(ReleaseState) + (MAX_WORKERS * sizeof(WorkerArg)); + +// Releases worker `index`'s equal, page-aligned share of the ranges' bytes. +void release_share(ReleaseState& s, uint32_t index) +{ + const uint64_t pages = s.total_bytes / s.page_bytes; + const uint64_t lo = (pages * index / s.num_workers) * s.page_bytes; + const uint64_t hi = (pages * (index + 1) / s.num_workers) * s.page_bytes; + uint64_t offset = 0; + for (size_t i = 0; i < s.num_ranges && offset < hi; ++i) { + const uint64_t bytes = s.ranges[i].end - s.ranges[i].begin; + const uint64_t from = std::max(lo, offset); + const uint64_t to = std::min(hi, offset + bytes); + if (from < to && + madvise(reinterpret_cast(s.ranges[i].begin + (from - offset)), to - from, MADV_DONTNEED) != 0) { + s.failed.fetch_add(1, std::memory_order_relaxed); + } + offset += bytes; + } +} + +void* release_worker(void* arg) +{ + const auto* a = static_cast(arg); + ReleaseState& s = *a->state; + s.ready.fetch_add(1, std::memory_order_release); + uint32_t go = WAIT; + while ((go = s.go.load(std::memory_order_acquire)) == WAIT) { + sched_yield(); + } + if (go == ABORT) { + return nullptr; // nothing was released: an ordinary thread exit is safe + } + release_share(s, a->index); + s.done.fetch_add(1, std::memory_order_release); + // Signals are blocked, so this sleeps until _exit ends the process, touching only this thread's stack. + for (;;) { + pause(); + } +} + +// st_nlink of /proc/self/task is 2 plus the kernel's thread count (proc_task_getattr), the Threads: of +// /proc/self/status; 0 when it cannot be read. It rises in clone before the new thread runs and drops only when an +// exiting thread is released, after it has left the address space (exit_mm). It counts this thread group only, not a +// process sharing the memory without being a thread (CLONE_VM without CLONE_THREAD) nor I/O in flight. +size_t count_threads_default() +{ + struct stat st{}; + return stat("/proc/self/task", &st) == 0 && st.st_nlink > 2 ? static_cast(st.st_nlink - 2) : 0; +} + +// Polls until the thread count reads `expected`. A matching count ends the wait whenever it comes; after one that does +// not, the wait gives up once THREAD_COUNT_WAIT has passed, so a slow stat or sleep can carry it past that. Yielding +// lets an exiting thread queued on this CPU run; an occasional short sleep frees the CPU when a yield does not. +bool wait_for_thread_count(const ExitReleaseSystem& system, size_t expected, size_t& counts) +{ + const auto deadline = std::chrono::steady_clock::now() + THREAD_COUNT_WAIT; + for (counts = 1; system.count_threads() != expected; ++counts) { + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + if (counts % 8 == 0) { + const timespec step{ 0, 20'000 }; + nanosleep(&step, nullptr); + } else { + sched_yield(); + } + } + return true; +} + +// The calls made after the release (madvise, sched_yield, pause, write, _exit) go through this object's PLT; a lazy +// slot would enter the dynamic resolver, whose link maps live in anonymous memory the release may have zeroed. _DYNAMIC +// is the dynamic section of the object this code is linked into; a static binary has none and binds nothing lazily. +bool binds_immediately_default() +{ + bool lazy_slots = false; + for (const ElfW(Dyn)* d = _DYNAMIC; d != nullptr && d->d_tag != DT_NULL; ++d) { + if (d->d_tag == DT_BIND_NOW || (d->d_tag == DT_FLAGS && (d->d_un.d_val & DF_BIND_NOW) != 0) || + (d->d_tag == DT_FLAGS_1 && (d->d_un.d_val & DF_1_NOW) != 0)) { + return true; + } + lazy_slots = lazy_slots || d->d_tag == DT_JMPREL; + } + return !lazy_slots; +} + +void* map_scratch_default(size_t bytes) +{ + void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + return p == MAP_FAILED ? nullptr : p; +} + +int start_thread_default(void* handle, void* stack, size_t stack_bytes, void* (*fn)(void*), void* arg) +{ + pthread_attr_t attr; + if (pthread_attr_init(&attr) != 0) { + return -1; + } + int rc = pthread_attr_setstack(&attr, stack, stack_bytes); + if (rc == 0) { + rc = pthread_create(static_cast(handle), &attr, fn, arg); + } + pthread_attr_destroy(&attr); + return rc; +} + +MemoryRange page_align_out(uintptr_t lo, uintptr_t hi, uintptr_t page) +{ + return { lo & ~(page - 1), (hi + page - 1) & ~(page - 1) }; +} + +// The data and bss of bb, libc and the loader hold the allocator's and the threads library's state. +int add_loaded_object(struct dl_phdr_info* info, size_t /*size*/, void* excluded) +{ + const auto page = static_cast(sysconf(_SC_PAGESIZE)); + for (size_t i = 0; i < info->dlpi_phnum; ++i) { + if (const auto& ph = info->dlpi_phdr[i]; ph.p_type == PT_LOAD) { + const uintptr_t lo = info->dlpi_addr + ph.p_vaddr; + static_cast*>(excluded)->push_back(page_align_out(lo, lo + ph.p_memsz, page)); + } + } + return 0; +} + +thread_local char tls_marker; +} // namespace + +ExitReleaseSystem default_exit_release_system() +{ + if (__llvm_profile_write_file != nullptr || __gcov_dump != nullptr) { + return { nullptr, nullptr, nullptr, nullptr }; + } + return { count_threads_default, binds_immediately_default, map_scratch_default, start_thread_default }; +} + +namespace { +// Writes what the normal exit would have written, then releases and exits. noexcept: an exception while writing the +// BB_BENCH report ends the process here exactly as it would from ~GlobalBenchStatsContainer. +[[noreturn]] void release_and_exit(int code, ReleaseState& state, uint32_t started) noexcept +{ + detail::GLOBAL_BENCH_STATS.print_exit_report_if_requested(); + std::cout.flush(); + std::clog.flush(); + std::cerr.flush(); + std::fflush(nullptr); + + // From here this thread touches only its stack, its TLS, the scratch mapping and loaded objects' data. + state.go.store(RELEASE, std::memory_order_release); + release_share(state, 0); + while (state.done.load(std::memory_order_acquire) != started) { + sched_yield(); + } + if (const uint32_t failed = state.failed.load(); failed != 0 && LogLevel::VERBOSE <= bb_log_level) { + char note[64] = "exit: madvise failed "; + char* end = std::to_chars(note + 21, note + 52, failed).ptr; + std::memcpy(end, " times\n", 7); + static_cast(write(STDERR_FILENO, note, static_cast(end + 7 - note))); + } + _exit(code); +} +} // namespace + +bool release_memory_and_exit(int code, const ExitReleaseSystem& system) +{ + if (__llvm_profile_write_file != nullptr || __gcov_dump != nullptr) { + return false; + } + // 1. Signals stay blocked until _exit, so no handler runs on this thread (it could start a thread or touch released + // memory); the release threads inherit the mask. Every return below restores it. + sigset_t all; + sigset_t previous; + sigfillset(&all); + if (pthread_sigmask(SIG_BLOCK, &all, &previous) != 0) { + return false; + } + uint8_t* scratch = nullptr; + size_t scratch_bytes = 0; + const auto normal_exit = [&](const char* why) noexcept { + if (scratch != nullptr) { + munmap(scratch, scratch_bytes); + } + const bool restored = pthread_sigmask(SIG_SETMASK, &previous, nullptr) == 0; + try { + vinfo("exit: normal teardown (", why, restored ? ")" : "; signal mask not restored)"); + } catch (...) { + } + return false; + }; + ReleaseState* state = nullptr; + try { + // 2. Only this thread may run. The kernel's count must first equal this thread plus its parallel_for workers, + // which shows that /proc counts threads (an emulated one that does not fails here), then come down to one + // once they are stopped and joined. With one thread, whose signals are blocked, no thread can run or start. + // bb starts no process sharing its memory and no asynchronous I/O, which the count would not show. + const size_t workers = parallel_for_num_workers(); + size_t counts = 0; + if (workers == 0 || !wait_for_thread_count(system, workers + 1, counts)) { + return normal_exit("thread count does not match the workers"); + } + parallel_for_stop_workers(); + const auto counting_since = std::chrono::steady_clock::now(); + if (!wait_for_thread_count(system, 1, counts)) { + return normal_exit("another thread is alive"); + } + const auto wait = std::chrono::steady_clock::now() - counting_since; + if (!system.binds_immediately()) { + return normal_exit("lazy symbol binding"); + } + // 3. The scratch mapping, a whole number of pages, mapped before /proc/self/maps is read so the selection + // excludes it by address. + const auto page = static_cast(sysconf(_SC_PAGESIZE)); + scratch_bytes = (SCRATCH_BYTES + page - 1) & ~(page - 1); + scratch = static_cast(system.map_scratch(scratch_bytes)); + if (scratch == nullptr) { + return normal_exit("no scratch mapping"); + } + // 4. What may not be released: loaded objects, the scratch mapping, and this thread's stack and TLS. + const auto scratch_lo = reinterpret_cast(scratch); + std::vector excluded; + dl_iterate_phdr(add_loaded_object, &excluded); + excluded.push_back({ scratch_lo, scratch_lo + scratch_bytes }); + int stack_marker = 0; + const uintptr_t tls_lo = + std::min(reinterpret_cast(&tls_marker), reinterpret_cast(&errno)); + const uintptr_t tls_hi = + std::max(reinterpret_cast(&tls_marker), reinterpret_cast(&errno)); + excluded.push_back(page_align_out(tls_lo - TLS_WINDOW_BYTES, tls_hi + TLS_WINDOW_BYTES, page)); + const uintptr_t pinned[] = { reinterpret_cast(&stack_marker), tls_lo, tls_hi }; + std::stringstream maps; + maps << std::ifstream("/proc/self/maps").rdbuf(); + const auto ranges = select_exit_release_ranges(maps.str(), excluded, pinned, MIN_MAPPING_BYTES); + if (!ranges || ranges->size() > MAX_RANGES) { + return normal_exit("memory map not usable"); + } + uint64_t total = 0; + for (const MemoryRange& r : *ranges) { + total += r.end - r.begin; + } + if (total < MIN_TOTAL_BYTES) { + return normal_exit("little memory to release"); + } + state = new (scratch + (MAX_WORKERS * WORKER_STACK_BYTES)) ReleaseState(); + std::ranges::copy(*ranges, state->ranges); + state->num_ranges = ranges->size(); + state->total_bytes = total; + state->page_bytes = page; + state->num_workers = static_cast( + std::clamp(std::min(total / BYTES_PER_WORKER, get_num_cpus()), 2, MAX_WORKERS)); + vinfo("exit: releasing ", + total >> 20, + " MiB in ", + ranges->size(), + " ranges on ", + state->num_workers, + " threads (one thread after ", + counts, + " counts, ", + std::chrono::duration_cast(wait).count(), + " us)"); + } catch (...) { + return normal_exit("exception while preparing"); + } + + // 5. Release threads on stacks inside the scratch mapping. + auto* args = reinterpret_cast(state + 1); + pthread_t handles[MAX_WORKERS]; + uint32_t started = 0; + for (uint32_t i = 1; i < state->num_workers; ++i) { + args[i] = { state, i }; + if (system.start_thread(&handles[started], + scratch + ((i - 1) * WORKER_STACK_BYTES), + WORKER_STACK_BYTES, + release_worker, + &args[i]) != 0) { + state->go.store(ABORT, std::memory_order_release); + for (uint32_t t = 0; t < started; ++t) { + pthread_join(handles[t], nullptr); + } + return normal_exit("release thread did not start"); + } + ++started; + } + while (state->ready.load(std::memory_order_acquire) != started) { + sched_yield(); + } + release_and_exit(code, *state, started); +} +#endif + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/exit_release.hpp b/barretenberg/cpp/src/barretenberg/common/exit_release.hpp new file mode 100644 index 0000000..4cca5cc --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/exit_release.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace bb { + +struct MemoryRange { + uintptr_t begin; + uintptr_t end; + bool operator==(const MemoryRange&) const = default; +}; + +/** + * @brief The address ranges to release before exiting, chosen from the text of /proc/self/maps. + * + * @details Kept: private, writable mappings with no backing file (anonymous memory and the brk heap). A mapping that + * contains any address in `pinned` is dropped whole; the parts of a kept mapping that overlap `excluded` are cut out. + * Pieces under `min_bytes` are dropped. Pure: it reads only its arguments. Returns nullopt on a line it cannot parse. + */ +std::optional> select_exit_release_ranges(std::string_view maps, + std::span excluded, + std::span pinned, + size_t min_bytes); + +/** The system calls the exit path depends on, replaceable so tests can make each one fail. */ +struct ExitReleaseSystem { + size_t (*count_threads)(); // the kernel's thread count for this thread group; 0 when unreadable + bool (*binds_immediately)(); // the PLT of the object holding this code was bound at load time + void* (*map_scratch)(size_t bytes); // nullptr on failure + int (*start_thread)(void* thread_handle, void* stack, size_t stack_bytes, void* (*fn)(void*), void* arg); +}; +ExitReleaseSystem default_exit_release_system(); + +/** + * @brief Ends the process with `code`, first handing its private memory back to the kernel from several threads. + * + * @details At exit the kernel frees every resident page on one core; madvise(MADV_DONTNEED) on disjoint ranges runs + * concurrently and leaves exit mostly empty mappings. The released memory includes the allocator's, so once the release + * starts nothing may run but the release and _exit. Before releasing anything it therefore blocks signals; requires + * the kernel's thread count to equal this thread plus its parallel_for workers, and then, once it has stopped them, + * one (each within about 2 ms); requires immediate symbol binding; and writes what a normal exit would write (the + * BB_BENCH report, buffered streams). The count covers this thread group only: the caller must not share its memory + * with another process (CLONE_VM) or have asynchronous I/O in flight. Release threads + * run on stacks in a private scratch mapping; this thread's stack and TLS and every loaded object's data are never + * released. + * + * Returns false, having released nothing, restored the signal mask and written at most a verbose log line, when any of + * that cannot be established or preparing it throws; the caller then exits the normal way. Never returns otherwise. + */ +bool release_memory_and_exit(int code, const ExitReleaseSystem& system = default_exit_release_system()); + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/exit_release.test.cpp b/barretenberg/cpp/src/barretenberg/common/exit_release.test.cpp new file mode 100644 index 0000000..3e772ee --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/exit_release.test.cpp @@ -0,0 +1,211 @@ +#include "barretenberg/common/exit_release.hpp" +#include "barretenberg/common/thread.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace bb; + +namespace { +constexpr uintptr_t MiB = uintptr_t{ 1 } << 20; + +constexpr const char* MAPS = "00400000-00600000 r-xp 00000000 08:01 123 /usr/bin/bb\n" + "00600000-00a00000 rw-p 00200000 08:01 123 /usr/bin/bb\n" + "00a00000-04a00000 rw-p 00000000 00:00 0 [heap]\n" + "7f0000000000-7f0004000000 rw-p 00000000 00:00 0 \n" + "7f0004000000-7f0004100000 rw-p 00000000 00:00 0 \n" + "7f0005000000-7f0009000000 r--p 00000000 00:00 0 \n" + "7f0010000000-7f0014000000 rw-s 00000000 00:05 77 /dev/zero (deleted)\n" + "7f0020000000-7f0024000000 rw-p 00000000 00:00 0 [anon:glibc: malloc arena]\n" + "7ffc00000000-7ffc00800000 rw-p 00000000 00:00 0 [stack]\n" + "7ffc10000000-7ffc10002000 r--p 00000000 00:00 0 [vvar]\n"; +} // namespace + +TEST(ExitRelease, SelectsPrivateWritableAnonymousMappingsAboveTheFloor) +{ + // Dropped: file-backed (text and data), the 1 MiB mapping (floor), read-only, shared, [stack], [vvar]. + const auto ranges = select_exit_release_ranges(MAPS, {}, {}, 2 * MiB); + ASSERT_TRUE(ranges.has_value()); + const std::vector expected{ { 0x00a00000, 0x04a00000 }, + { 0x7f0000000000, 0x7f0004000000 }, + { 0x7f0020000000, 0x7f0024000000 } }; + EXPECT_EQ(*ranges, expected); +} + +TEST(ExitRelease, CutsExcludedRangesAndDropsPinnedMappings) +{ + const std::vector excluded{ + { 0x7f0001000000, 0x7f0001400000 }, // splits the anonymous mapping + { 0x7f0003f00000, 0x7f0004000000 }, // trims its tail + { 0x00b00000, 0x04900000 }, // leaves two 1 MiB pieces of [heap], both under the floor + }; + const std::vector pinned{ 0x7f0020001000 }; // inside the arena mapping: dropped whole + const auto ranges = select_exit_release_ranges(MAPS, excluded, pinned, 2 * MiB); + ASSERT_TRUE(ranges.has_value()); + const std::vector expected{ { 0x7f0000000000, 0x7f0001000000 }, { 0x7f0001400000, 0x7f0003f00000 } }; + EXPECT_EQ(*ranges, expected); +} + +TEST(ExitRelease, RejectsUnparsableMaps) +{ + EXPECT_FALSE(select_exit_release_ranges("not a maps line\n", {}, {}, 0).has_value()); + EXPECT_FALSE(select_exit_release_ranges("00a00000-00900000 rw-p 00000000 00:00 0\n", {}, {}, 0).has_value()); + EXPECT_FALSE(select_exit_release_ranges("00a00000-00b00000 rw-p\n", {}, {}, 0).has_value()); +} + +#if defined(__linux__) && !defined(__wasm__) && !defined(NO_MULTITHREADING) +// Every condition the fast exit cannot establish leaves the process exactly as it was, having written nothing, so the +// caller's normal return runs the destructors and writes the BB_BENCH report itself. Each fake below fails before +// anything is released; a fake that did not fail would end this test binary with exit code 99. A fake count of this +// thread plus its parallel_for workers passes the thread check, since stopping the workers brings it to one. +class ExitReleaseProcess : public ::testing::Test { + protected: + void SetUp() override + { + setenv("BB_BENCH", "1", 1); + saved_cerr = std::cerr.rdbuf(captured.rdbuf()); + pthread_sigmask(SIG_SETMASK, nullptr, &mask_before); + parallel_for(64, [](size_t) {}); // the call stops this thread's workers; they must come back + ballast.assign(256 * MiB, uint8_t{ 1 }); // enough private memory to get past the size check + } + void TearDown() override + { + std::cerr.rdbuf(saved_cerr); + unsetenv("BB_BENCH"); + } + void expect_normal_exit_path(bool released) + { + EXPECT_FALSE(released); + EXPECT_EQ(captured.str(), ""); // no BB_BENCH report: the destructor still owes it + sigset_t mask_after; + pthread_sigmask(SIG_SETMASK, nullptr, &mask_after); + for (int sig = 1; sig < NSIG; ++sig) { + EXPECT_EQ(sigismember(&mask_after, sig), sigismember(&mask_before, sig)) << "signal " << sig; + } + EXPECT_TRUE(std::ranges::all_of(ballast, [](uint8_t b) { return b == 1; })); + std::atomic iterations = 0; + parallel_for(64, [&](size_t) { iterations++; }); + EXPECT_EQ(iterations.load(), 64U); + } + std::stringstream captured; + std::streambuf* saved_cerr = nullptr; + sigset_t mask_before{}; + std::vector ballast; +}; + +TEST_F(ExitReleaseProcess, AnotherThreadAlive) +{ + std::atomic stop = false; + std::thread other([&] { + while (!stop.load()) { + std::this_thread::yield(); + } + }); + const bool released = release_memory_and_exit(99); + stop.store(true); + other.join(); + expect_normal_exit_path(released); +} + +TEST_F(ExitReleaseProcess, UncountedThreadsLazyBindingScratchFailureAndThrowingPreparation) +{ + std::vector systems(4, default_exit_release_system()); + for (ExitReleaseSystem& system : systems) { + system.count_threads = [] { return parallel_for_num_workers() + 1; }; + } + systems[3].count_threads = [] { return size_t{ 1 }; }; // a /proc that does not count threads + systems[0].binds_immediately = [] { return false; }; + systems[1].map_scratch = [](size_t) -> void* { return nullptr; }; + systems[2].map_scratch = [](size_t) -> void* { throw std::bad_alloc(); }; + for (const ExitReleaseSystem& system : systems) { + expect_normal_exit_path(release_memory_and_exit(99, system)); + } +} + +TEST_F(ExitReleaseProcess, SecondReleaseThreadFailsToStart) +{ + static int starts = 0; + static std::atomic first_tid = 0; + static void* (*first_fn)(void*) = nullptr; + starts = 0; + first_tid = 0; + ExitReleaseSystem system = default_exit_release_system(); + system.count_threads = [] { return parallel_for_num_workers() + 1; }; + system.binds_immediately = [] { return true; }; + system.start_thread = [](void* handle, void* stack, size_t bytes, void* (*fn)(void*), void* arg) { + if (++starts == 2) { + return -1; + } + first_fn = fn; + const auto recording = [](void* a) -> void* { + first_tid = gettid(); + return first_fn(a); + }; + return default_exit_release_system().start_thread(handle, stack, bytes, recording, arg); + }; + const size_t cpus = get_num_cpus(); + set_parallel_for_concurrency(16); // at least three release threads, so a second start is attempted + const bool released = release_memory_and_exit(99, system); + set_parallel_for_concurrency(cpus); + if (starts == 0) { + expect_normal_exit_path(released); + GTEST_SKIP() << "the release is compiled out (sanitizer or coverage build)"; + } + EXPECT_EQ(starts, 2); + ASSERT_NE(first_tid.load(), 0); + // The thread that did start was joined: it leaves /proc once the kernel finishes its exit. + const std::string task = "/proc/self/task/" + std::to_string(first_tid.load()); + for (int i = 0; i < 1000 && std::filesystem::exists(task); ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + EXPECT_FALSE(std::filesystem::exists(task)); + expect_normal_exit_path(released); +} + +TEST_F(ExitReleaseProcess, FastPathInAFreshProcessExitsWithItsCodeAfterItsOutput) +{ + const ExitReleaseSystem system = default_exit_release_system(); + if (system.count_threads == nullptr || !system.binds_immediately() || get_num_cpus() < 2) { + GTEST_SKIP() << "the release is compiled out, or this binary binds lazily, or there is one CPU"; + } + // The threadsafe style re-runs this binary up to the statement, so the child is a fresh process whose only other + // threads are the workers SetUp started. The child reads the output path from the environment. + const char* inherited = std::getenv("BB_EXIT_RELEASE_TEST_OUT"); + const std::string out = + inherited != nullptr ? inherited : ::testing::TempDir() + "exit_release_" + std::to_string(getpid()); + setenv("BB_EXIT_RELEASE_TEST_OUT", out.c_str(), 1); + std::string bytes(MiB, '\0'); + for (size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(i * 131 % 251); + } + GTEST_FLAG_SET(death_test_style, "threadsafe"); + EXPECT_EXIT( + { + std::ofstream(out, std::ios::binary) << bytes; + std::cerr.rdbuf(saved_cerr); // BB_BENCH is set: the report must reach the real stderr before the release + release_memory_and_exit(0); + std::_Exit(3); // the normal exit was taken + }, + ::testing::ExitedWithCode(0), + "enchmark"); + unsetenv("BB_EXIT_RELEASE_TEST_OUT"); + std::stringstream written; + written << std::ifstream(out, std::ios::binary).rdbuf(); + EXPECT_TRUE(written.str() == bytes); + std::filesystem::remove(out); +} +#endif diff --git a/barretenberg/cpp/src/barretenberg/common/malloc_policy.cpp b/barretenberg/cpp/src/barretenberg/common/malloc_policy.cpp new file mode 100644 index 0000000..734bb5d --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/malloc_policy.cpp @@ -0,0 +1,133 @@ +#include "barretenberg/common/malloc_policy.hpp" +#include "barretenberg/common/log.hpp" + +#include + +#if defined(__linux__) && defined(__GLIBC__) && !defined(__wasm__) +#define BB_MALLOC_POLICY_SUPPORTED 1 +#endif +// Sanitizer runtimes replace malloc, so glibc's settings would not reach the allocator in use. +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) || defined(__SANITIZE_HWADDRESS__) +#undef BB_MALLOC_POLICY_SUPPORTED +#endif +#if defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || __has_feature(memory_sanitizer) || \ + __has_feature(hwaddress_sanitizer) +#undef BB_MALLOC_POLICY_SUPPORTED +#endif +#endif + +#ifdef BB_MALLOC_POLICY_SUPPORTED +#include +#include +#endif + +namespace bb { + +bool environment_configures_malloc(const char* const* environment) +{ + constexpr std::string_view tunables_prefix = "GLIBC_TUNABLES="; + for (; environment != nullptr && *environment != nullptr; ++environment) { + const std::string_view entry(*environment); + if (entry.starts_with("MALLOC_")) { + return true; + } + if (!entry.starts_with(tunables_prefix)) { + continue; + } + // GLIBC_TUNABLES holds name=value pairs separated by ':'. + std::string_view rest = entry.substr(tunables_prefix.size()); + while (!rest.empty()) { + const size_t end = rest.find(':'); + if (rest.substr(0, end).starts_with("glibc.malloc.")) { + return true; + } + if (end == std::string_view::npos) { + break; + } + rest.remove_prefix(end + 1); + } + } + return false; +} + +bool process_malloc_policy_supported() +{ +#ifdef BB_MALLOC_POLICY_SUPPORTED + return true; +#else + return false; +#endif +} + +bool command_keeps_heap(std::string_view command, std::string_view scheme, bool slow_low_memory) +{ + return !slow_low_memory && (command == "avm_prove" || (command == "prove" && scheme == "ultra_honk")); +} + +MallocPolicy configure_process_malloc(bool keeps_heap, const char* const* environment, MallocParameterSetter set) +{ + if (!keeps_heap) { + return MallocPolicy::NOT_THIS_COMMAND; + } +#ifdef BB_MALLOC_POLICY_SUPPORTED + if (environment_configures_malloc(environment)) { + return MallocPolicy::LEFT_TO_ENVIRONMENT; + } + // Each setting also turns off glibc's dynamic thresholds (mp_.no_dyn_threshold), which otherwise raise the mmap + // threshold to each freed mapped block's size, up to 32 MiB, and the trim threshold to twice that. Both are set: + // either alone freezes the other at its starting 128 KiB. The mmap threshold goes first, so that a refusal leaves + // both untouched; glibc accepts any trim value. + if (set(M_MMAP_THRESHOLD, static_cast(PROCESS_MMAP_THRESHOLD)) != 1) { + return MallocPolicy::REFUSED; + } + // mallopt's int -1 becomes (unsigned long)-1 inside glibc, the value its malloc.c documents as disabling + // trimming. An explicit malloc_trim() still trims. + if (set(M_TRIM_THRESHOLD, PROCESS_TRIM_THRESHOLD) != 1) { + return MallocPolicy::REFUSED; + } + return MallocPolicy::APPLIED; +#else + static_cast(environment); + static_cast(set); + return MallocPolicy::UNSUPPORTED; +#endif +} + +MallocPolicy configure_process_malloc_and_log(bool keeps_heap, + const char* const* environment, + MallocParameterSetter set) +{ + // Outside vinfo, whose arguments are evaluated only when verbose logging is on. + const MallocPolicy policy = configure_process_malloc(keeps_heap, environment, set); + vinfo(malloc_policy_message(policy)); + return policy; +} + +MallocPolicy configure_process_malloc_and_log(bool keeps_heap) +{ +#ifdef BB_MALLOC_POLICY_SUPPORTED + return configure_process_malloc_and_log(keeps_heap, environ, &mallopt); +#else + return configure_process_malloc_and_log(keeps_heap, nullptr, nullptr); +#endif +} + +std::string_view malloc_policy_message(MallocPolicy policy) +{ + switch (policy) { + case MallocPolicy::APPLIED: + return "malloc policy: applied (no heap trim, mmap threshold 32 MiB)"; + case MallocPolicy::NOT_THIS_COMMAND: + return "malloc policy: unchanged (not applied to this command or with --slow_low_memory)"; + case MallocPolicy::LEFT_TO_ENVIRONMENT: + return "malloc policy: left to the environment (GLIBC_TUNABLES glibc.malloc.* or MALLOC_*)"; + case MallocPolicy::UNSUPPORTED: + return "malloc policy: not built in"; + case MallocPolicy::REFUSED: + return "malloc policy: refused by glibc"; + } + return "malloc policy: unknown"; +} + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/malloc_policy.hpp b/barretenberg/cpp/src/barretenberg/common/malloc_policy.hpp new file mode 100644 index 0000000..786655d --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/malloc_policy.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include + +namespace bb { + +/** The mmap threshold configure_process_malloc() pins: glibc's ceiling for its dynamic threshold on 64-bit targets. */ +inline constexpr size_t PROCESS_MMAP_THRESHOLD = size_t{ 32 } << 20; + +/** The trim threshold configure_process_malloc() sets: mallopt's -1, which glibc takes as no trimming at all. */ +inline constexpr int PROCESS_TRIM_THRESHOLD = -1; + +enum class MallocPolicy : uint8_t { + APPLIED, ///< heap trimming is off and the mmap threshold is pinned + NOT_THIS_COMMAND, ///< outside command_keeps_heap(): nothing was set, whatever is in force stays + LEFT_TO_ENVIRONMENT, ///< the environment configures malloc, so nothing was set + UNSUPPORTED, ///< not a native glibc build, or a sanitizer build: nothing was set + REFUSED, ///< glibc rejected a setting +}; + +/** Sets one allocator parameter and returns 1 on success, as glibc's mallopt. */ +using MallocParameterSetter = int (*)(int parameter, int value); + +/** + * @brief Whether an environment configures glibc's malloc: a GLIBC_TUNABLES entry named glibc.malloc.*, or any + * variable whose name starts with MALLOC_ (glibc's aliases such as MALLOC_ARENA_MAX and MALLOC_TRIM_THRESHOLD_). + * Other tunables, such as glibc.pthread.rseq, do not count. + * @param environment A null-terminated array of NAME=value strings, as environ; null counts as empty. + */ +bool environment_configures_malloc(const char* const* environment); + +/** Whether this build can apply the settings: native Linux on glibc, without a sanitizer. */ +bool process_malloc_policy_supported(); + +/** + * @brief Whether a bb command keeps freed heap memory: `avm_prove`, and `prove` with scheme ultra_honk, unless the + * user asked for --slow_low_memory. + * @details An empirical policy per prover family, read from the command and the scheme only, never from an input. + * For AVM and UltraHonk proving, kept heap measured faster at a peak cost of a few MB to a few percent. For Chonk + * (`prove --scheme chonk`), which proves many circuits in turn, it measured faster at a much larger peak cost, so + * Chonk is left out. msgpack run serves many requests from one process, so it is left out too. + * @param command The top-level subcommand as typed (`msgpack` for msgpack run); empty when there is none. + * @param scheme The parsed --scheme value. + * @param slow_low_memory Whether --slow_low_memory was given: a setting that trades memory for time never applies. + */ +bool command_keeps_heap(std::string_view command, std::string_view scheme, bool slow_low_memory); + +/** + * @brief When @p keeps_heap (see command_keeps_heap()), sets M_MMAP_THRESHOLD to PROCESS_MMAP_THRESHOLD and then + * M_TRIM_THRESHOLD to PROCESS_TRIM_THRESHOLD through @p set. Sets nothing otherwise, nor when @p environment + * configures malloc. + * @details Freed heap memory then stays with the process until it exits, and serves later allocations of any size + * that fit in it. A block of PROCESS_MMAP_THRESHOLD bytes or more gets its own mapping, unmapped by free(), only + * when no free heap space holds it. A refused mmap threshold stops before the trim setting. glibc's mallopt is not + * thread-safe: call this before the command starts its workers. + */ +MallocPolicy configure_process_malloc(bool keeps_heap, const char* const* environment, MallocParameterSetter set); + +/** + * @brief configure_process_malloc(), then its outcome on the verbose log. The settings are applied at every log + * level; only the line depends on it. + */ +MallocPolicy configure_process_malloc_and_log(bool keeps_heap, + const char* const* environment, + MallocParameterSetter set); + +/** configure_process_malloc_and_log() on this process's environment, through glibc's mallopt. */ +MallocPolicy configure_process_malloc_and_log(bool keeps_heap); + +/** One line for the verbose log: "malloc policy: " and the outcome. */ +std::string_view malloc_policy_message(MallocPolicy policy); + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/malloc_policy.test.cpp b/barretenberg/cpp/src/barretenberg/common/malloc_policy.test.cpp new file mode 100644 index 0000000..2ae3bab --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/malloc_policy.test.cpp @@ -0,0 +1,173 @@ +#include "barretenberg/common/malloc_policy.hpp" +#include "barretenberg/common/log.hpp" + +#include +#include +#include +#include +#include +#include + +#if defined(__GLIBC__) +#include +#endif + +using namespace bb; + +namespace { + +std::vector> recorded_settings; +int setter_result = 1; + +int record_setting(int parameter, int value) +{ + recorded_settings.emplace_back(parameter, value); + return setter_result; +} + +// These tests record the settings through record_setting; none applies them to this process. +class MallocPolicyTest : public ::testing::Test { + protected: + void SetUp() override + { + recorded_settings.clear(); + setter_result = 1; + } +}; + +const std::array UNRELATED_TUNABLE{ "GLIBC_TUNABLES=glibc.pthread.rseq=0", nullptr }; + +} // namespace + +TEST(MallocPolicy, EnvironmentConfiguresMallocOnlyThroughMallocTunablesOrMallocVariables) +{ + const std::array plain{ "PATH=/usr/bin", "MALLOCATOR=1", nullptr }; + const std::array other_tunables{ "GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.cpu.x86_ibt=off", + nullptr }; + const std::array empty_tunables{ "GLIBC_TUNABLES=", nullptr }; + const std::array malloc_tunable{ "HOME=/root", + "GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.arena_max=2", + nullptr }; + const std::array malloc_variable{ "MALLOC_ARENA_MAX=4", nullptr }; + const std::array empty{ nullptr }; + + EXPECT_FALSE(environment_configures_malloc(nullptr)); + EXPECT_FALSE(environment_configures_malloc(empty.data())); + EXPECT_FALSE(environment_configures_malloc(plain.data())); + EXPECT_FALSE(environment_configures_malloc(other_tunables.data())); + EXPECT_FALSE(environment_configures_malloc(empty_tunables.data())); + EXPECT_TRUE(environment_configures_malloc(malloc_tunable.data())); + EXPECT_TRUE(environment_configures_malloc(malloc_variable.data())); +} + +TEST(MallocPolicy, OnlyAvmProveAndUltraHonkProveWithoutLowMemoryKeepHeap) +{ + EXPECT_TRUE(command_keeps_heap("avm_prove", "ultra_honk", false)); + EXPECT_TRUE(command_keeps_heap("avm_prove", "", false)); + EXPECT_TRUE(command_keeps_heap("prove", "ultra_honk", false)); + + EXPECT_FALSE(command_keeps_heap("avm_prove", "ultra_honk", true)); + EXPECT_FALSE(command_keeps_heap("prove", "ultra_honk", true)); + EXPECT_FALSE(command_keeps_heap("prove", "chonk", false)); + EXPECT_FALSE(command_keeps_heap("prove", "avm", false)); + EXPECT_FALSE(command_keeps_heap("msgpack", "ultra_honk", false)); // msgpack run + EXPECT_FALSE(command_keeps_heap("write_vk", "ultra_honk", false)); + EXPECT_FALSE(command_keeps_heap("verify", "ultra_honk", false)); + EXPECT_FALSE(command_keeps_heap("", "ultra_honk", false)); +} + +TEST_F(MallocPolicyTest, ACommandOutsideTheRuleGetsNoSetting) +{ + EXPECT_EQ(configure_process_malloc( + command_keeps_heap("prove", "chonk", false), UNRELATED_TUNABLE.data(), &record_setting), + MallocPolicy::NOT_THIS_COMMAND); + EXPECT_TRUE(recorded_settings.empty()); +} + +TEST_F(MallocPolicyTest, AnEnvironmentThatConfiguresMallocGetsNoSetting) +{ + const std::array environment{ "MALLOC_TRIM_THRESHOLD_=131072", nullptr }; + EXPECT_EQ(configure_process_malloc(true, environment.data(), &record_setting), + process_malloc_policy_supported() ? MallocPolicy::LEFT_TO_ENVIRONMENT : MallocPolicy::UNSUPPORTED); + EXPECT_TRUE(recorded_settings.empty()); +} + +#if defined(__GLIBC__) +TEST_F(MallocPolicyTest, ACommandInTheRuleGetsTheMmapThresholdThenNoTrimming) +{ + if (!process_malloc_policy_supported()) { + GTEST_SKIP() << "the settings are compiled out of this build"; + } + EXPECT_EQ(configure_process_malloc(true, UNRELATED_TUNABLE.data(), &record_setting), MallocPolicy::APPLIED); + const std::vector> expected{ { M_MMAP_THRESHOLD, static_cast(PROCESS_MMAP_THRESHOLD) }, + { M_TRIM_THRESHOLD, PROCESS_TRIM_THRESHOLD } }; + EXPECT_EQ(recorded_settings, expected); +} + +TEST_F(MallocPolicyTest, ARefusedMmapThresholdStopsBeforeTheTrimSetting) +{ + if (!process_malloc_policy_supported()) { + GTEST_SKIP() << "the settings are compiled out of this build"; + } + setter_result = 0; + EXPECT_EQ(configure_process_malloc(true, UNRELATED_TUNABLE.data(), &record_setting), MallocPolicy::REFUSED); + const std::vector> expected{ { M_MMAP_THRESHOLD, static_cast(PROCESS_MMAP_THRESHOLD) } }; + EXPECT_EQ(recorded_settings, expected); +} + +// The CLI calls configure_process_malloc_and_log() at whatever log level the command set. At the default (INFO) the +// settings must still be applied, and nothing is printed; with verbose logging the outcome line is printed. +TEST_F(MallocPolicyTest, StartUpAppliesTheSettingsAtEveryLogLevelAndPrintsOnlyWhenVerbose) +{ + if (!process_malloc_policy_supported()) { + GTEST_SKIP() << "the settings are compiled out of this build"; + } + std::vector lines; + // Restores the log level and sink (which points at lines) even when an assertion returns early. + struct RestoreLogging { + LogLevel level = bb_log_level; + LogFunction function = log_function; + RestoreLogging() = default; + RestoreLogging(const RestoreLogging&) = delete; + RestoreLogging& operator=(const RestoreLogging&) = delete; + RestoreLogging(RestoreLogging&&) = delete; + RestoreLogging& operator=(RestoreLogging&&) = delete; + ~RestoreLogging() + { + set_log_function(function); + bb_log_level = level; + } + } restore; + set_log_function([&lines](LogLevel /*level*/, const std::string& message) { lines.push_back(message); }); + + bb_log_level = LogLevel::INFO; + EXPECT_EQ(configure_process_malloc_and_log(true, UNRELATED_TUNABLE.data(), &record_setting), MallocPolicy::APPLIED); + EXPECT_EQ(recorded_settings.size(), 2U); + EXPECT_TRUE(lines.empty()); + + recorded_settings.clear(); + bb_log_level = LogLevel::VERBOSE; + EXPECT_EQ(configure_process_malloc_and_log(true, UNRELATED_TUNABLE.data(), &record_setting), MallocPolicy::APPLIED); + EXPECT_EQ(recorded_settings.size(), 2U); + ASSERT_EQ(lines.size(), 1U); + EXPECT_EQ(lines[0].rfind(std::string(malloc_policy_message(MallocPolicy::APPLIED)), 0), 0U); +} + +namespace { +[[noreturn]] void apply_through_glibc() +{ + std::_Exit(configure_process_malloc(true, UNRELATED_TUNABLE.data(), &mallopt) == MallocPolicy::APPLIED ? 0 : 1); +} +} // namespace + +// glibc's mallopt accepts both values. Run in a fresh process (the threadsafe style re-runs this binary), so this +// test process keeps its own allocator settings. +TEST(MallocPolicy, GlibcAcceptsBothSettings) +{ + if (!process_malloc_policy_supported()) { + GTEST_SKIP() << "the settings are compiled out of this build"; + } + GTEST_FLAG_SET(death_test_style, "threadsafe"); + EXPECT_EXIT(apply_through_glibc(), ::testing::ExitedWithCode(0), ""); +} +#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..0f91763 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,15 @@ #ifndef NO_MULTITHREADING #include "log.hpp" #include "thread.hpp" +#include #include +#include #include +#include #include +#include #include -#include +#include #include #include @@ -27,6 +31,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); @@ -37,60 +95,88 @@ class ThreadPool { ThreadPool& operator=(const ThreadPool& other) = delete; ThreadPool& operator=(ThreadPool&& other) = delete; + size_t num_workers() const { return workers.size(); } + 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 +192,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,28 +204,48 @@ 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_--; } - // Make sure nested stats accounting works under multithreading - // Note: parent is a thread-local variable. - bb::detail::GlobalBenchStatsContainer::parent = parent.load(); - do_iterations(); + if (stop_.load()) { + break; + } + seen_generation = generation_of(work_.load(std::memory_order_acquire)); + do_iterations(seen_generation); } // info("worker exit ", worker_num); } } // namespace namespace bb { +namespace { +// The calling thread's workers (on wasm, the process's), created by its first parallel_for. +#ifdef __wasm__ +std::optional calling_thread_workers; +#else +thread_local std::optional calling_thread_workers; +#endif +} // namespace + +size_t parallel_for_num_workers() +{ + return calling_thread_workers ? calling_thread_workers->num_workers() : 0; +} + +void parallel_for_stop_workers() +{ + calling_thread_workers.reset(); +} + /** - * 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) { @@ -149,7 +255,10 @@ void parallel_for_mutex_pool(size_t num_iterations, const std::function +#include +#include +#if !defined(__wasm__) && !defined(_WIN32) && !defined(NO_MULTITHREADING) +#include +#include +#include +#include +#endif + +namespace bb { + +/** + * @brief Before a large block is freed, hand its pages back to the OS from several threads at once. + * + * @details Freeing a multi-megabyte block unmaps it on the calling thread, and the kernel then frees its pages one at a + * time (on the order of 0.1 ms per MiB), so gigabytes of polynomials take a noticeable serial pause to tear down. + * madvise(MADV_DONTNEED) on disjoint ranges runs concurrently, after which the free only unmaps an empty range. Only + * whole pages strictly inside [ptr, ptr + bytes) are released, so allocator metadata next to the block is never + * touched. The block's contents are lost: call this only immediately before freeing it. Blocks under + * MIN_PARALLEL_RELEASE_BYTES are left to the allocator. Uses short-lived threads rather than the parallel_for pool, so + * it is safe from destructors running on any thread, including inside a parallel_for. + */ +inline void release_pages_in_parallel([[maybe_unused]] void* ptr, [[maybe_unused]] size_t bytes) +{ +#if !defined(__wasm__) && !defined(_WIN32) && !defined(NO_MULTITHREADING) && defined(MADV_DONTNEED) + constexpr size_t MIN_PARALLEL_RELEASE_BYTES = size_t{ 64 } << 20; + constexpr size_t BYTES_PER_THREAD = size_t{ 16 } << 20; + constexpr size_t MAX_THREADS = 16; + if (ptr == nullptr || bytes < MIN_PARALLEL_RELEASE_BYTES) { + return; + } + const auto page = static_cast(sysconf(_SC_PAGESIZE)); + const auto begin = (reinterpret_cast(ptr) + page - 1) & ~(page - 1); + const auto end = (reinterpret_cast(ptr) + bytes) & ~(page - 1); + if (end <= begin) { + return; + } + const size_t num_pages = (end - begin) / page; + const size_t num_threads = std::clamp((end - begin) / BYTES_PER_THREAD, 1, MAX_THREADS); + struct Slice { + uintptr_t lo; + uintptr_t hi; + }; + std::array slices{}; + for (size_t t = 0; t < num_threads; ++t) { + slices[t] = { begin + (((num_pages * t) / num_threads) * page), + begin + (((num_pages * (t + 1)) / num_threads) * page) }; + } + auto release_slice = [](void* arg) -> void* { + const auto* slice = static_cast(arg); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,performance-no-int-to-ptr) + static_cast(madvise(reinterpret_cast(slice->lo), slice->hi - slice->lo, MADV_DONTNEED)); + return nullptr; + }; + // pthread_create reports failure by its return value and the handles live in a fixed array, so nothing here can + // throw, including a failed allocation: this runs inside deleters and noexcept releases. + std::array threads{}; + size_t spawned = 1; + while (spawned < num_threads && pthread_create(&threads[spawned], nullptr, release_slice, &slices[spawned]) == 0) { + ++spawned; + } + // Out of threads: this thread releases the slices nobody took. + for (size_t t = spawned; t < num_threads; ++t) { + release_slice(&slices[t]); + } + release_slice(slices.data()); + for (size_t t = 1; t < spawned; ++t) { + pthread_join(threads[t], nullptr); + } +#endif +} + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/thread.cpp b/barretenberg/cpp/src/barretenberg/common/thread.cpp index 6f9a1ca..818c3ae 100644 --- a/barretenberg/cpp/src/barretenberg/common/thread.cpp +++ b/barretenberg/cpp/src/barretenberg/common/thread.cpp @@ -128,6 +128,14 @@ void parallel_for(size_t num_iterations, const std::function& func #endif } +#ifdef NO_MULTITHREADING +size_t parallel_for_num_workers() +{ + return 0; +} +void parallel_for_stop_workers() {} +#endif + /** * @brief Split a loop into several loops running in parallel * diff --git a/barretenberg/cpp/src/barretenberg/common/thread.hpp b/barretenberg/cpp/src/barretenberg/common/thread.hpp index e21bbc8..1414376 100644 --- a/barretenberg/cpp/src/barretenberg/common/thread.hpp +++ b/barretenberg/cpp/src/barretenberg/common/thread.hpp @@ -35,6 +35,10 @@ inline size_t get_num_cpus_pow2() * The size will be chosen based on the hardware concurrency (i.e., env or cpus). */ void parallel_for(size_t num_iterations, const std::function& func); +/** The calling thread's parallel_for pool workers now: 0 before its first parallel_for, and always 0 under OpenMP. */ +size_t parallel_for_num_workers(); +/** Stops and joins the calling thread's parallel_for workers; its next parallel_for starts new ones. */ +void parallel_for_stop_workers(); void parallel_for_range(size_t num_points, const std::function& func, size_t no_multhreading_if_less_or_equal = 0); 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/poseidon2/sponge/sponge.hpp b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp index 0812158..af53dd7 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp +++ b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge/sponge.hpp @@ -12,6 +12,7 @@ #include #include +#include "barretenberg/common/assert.hpp" #include "barretenberg/numeric/uint256/uint256.hpp" namespace bb::crypto { @@ -136,5 +137,46 @@ template +class FieldSponge::AbsorbedPrefix { + public: + AbsorbedPrefix(size_t input_length, std::span prefix) + : sponge(FF(static_cast(input_length) << 64)) + , remaining(input_length - prefix.size()) + { + BB_ASSERT_LTE(prefix.size(), input_length, "the prefix is longer than the input"); + for (const FF& element : prefix) { + sponge.absorb(element); + } + } + + /** + * @brief Absorbs the rest of the input, which must complete its length, and returns the hash. + */ + FF finish(std::span rest) const + { + BB_ASSERT_EQ(rest.size(), remaining, "the rest does not complete the input"); + FieldSponge completed = sponge; + for (const FF& element : rest) { + completed.absorb(element); + } + return completed.squeeze(); + } + + size_t remaining_length() const { return remaining; } + + private: + FieldSponge sponge; + size_t remaining; }; } // namespace bb::crypto diff --git a/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge_prefix.test.cpp b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge_prefix.test.cpp new file mode 100644 index 0000000..61f478f --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/crypto/poseidon2/sponge_prefix.test.cpp @@ -0,0 +1,42 @@ +#include "barretenberg/crypto/poseidon2/poseidon2_params.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "poseidon2.hpp" +#include +#include +#include +#include + +using namespace bb; + +namespace { +auto& engine = numeric::get_debug_randomness(); + +using Sponge = crypto::Poseidon2::Sponge; + +bool same_limbs(const fr& a, const fr& b) +{ + return std::memcmp(a.data, b.data, sizeof(a.data)) == 0; +} +} // namespace + +// Every split of every input length around the rate (3), including an empty input, an empty prefix and an empty rest, +// must give hash_internal's result limb for limb. +TEST(Poseidon2SpongePrefix, FinishMatchesHashInternalForEverySplit) +{ + for (size_t length = 0; length <= 13; ++length) { + std::vector input(length); + for (auto& element : input) { + element = fr::random_element(&engine); + } + const fr expected = Sponge::hash_internal(input); + const std::span all(input); + for (size_t split = 0; split <= length; ++split) { + SCOPED_TRACE("length " + std::to_string(length) + " split " + std::to_string(split)); + const Sponge::AbsorbedPrefix prefix(length, all.first(split)); + EXPECT_EQ(prefix.remaining_length(), length - split); + EXPECT_TRUE(same_limbs(prefix.finish(all.subspan(split)), expected)); + // finish works on a copy of the sponge, so it can be called again with the same result. + EXPECT_TRUE(same_limbs(prefix.finish(all.subspan(split)), expected)); + } + } +} 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/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/batch_msm_concurrent_chunks.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_msm_concurrent_chunks.test.cpp new file mode 100644 index 0000000..3e09654 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_msm_concurrent_chunks.test.cpp @@ -0,0 +1,115 @@ +#include "barretenberg/common/serialize.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/bn254/bn254.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include "scalar_multiplication.hpp" +#include + +using namespace bb; + +namespace { +auto& engine = numeric::get_randomness(); + +class ConcurrencyScope { + size_t prev_; + + public: + explicit ConcurrencyScope(size_t n) + : prev_(get_num_cpus()) + { + set_parallel_for_concurrency(n); + } + ~ConcurrencyScope() { set_parallel_for_concurrency(prev_); } + ConcurrencyScope(const ConcurrencyScope&) = delete; + ConcurrencyScope& operator=(const ConcurrencyScope&) = delete; + ConcurrencyScope(ConcurrencyScope&&) = delete; + ConcurrencyScope& operator=(ConcurrencyScope&&) = delete; +}; +} // namespace + +template class BatchMsmConcurrentChunksTest : public ::testing::Test {}; + +using CurveTypes = ::testing::Types; +TYPED_TEST_SUITE(BatchMsmConcurrentChunksTest, CurveTypes); + +// Batches with more than 100 members, all at or above the large-member bound and none wider than Σn / pool_width, +// run their members concurrently; members wider than 2^16 points are split into chunks whose partial sums are added +// back. Each member must match a stand-alone MSM byte for byte, and its scalars must be restored. +TYPED_TEST(BatchMsmConcurrentChunksTest, MatchesStandaloneMsm) +{ +#if defined(__wasm__) || defined(NO_MULTITHREADING) + GTEST_SKIP() << "no concurrent large-member path without threads"; +#else + using AffineElement = typename TypeParam::AffineElement; + using ScalarField = typename TypeParam::ScalarField; + + constexpr size_t CHUNK = size_t{ 1 } << 16; + const std::vector wide = { CHUNK, CHUNK + 1, (2 * CHUNK) + 12345 }; + const size_t max_wide = wide.back(); + + // Independent random points and scalars: the affine batch addition assumes no two partial sums in a bucket + // coincide, which structured points under repeated scalars can violate. + std::vector points(max_wide); + std::vector pool(max_wide); + parallel_for_range(max_wide, [&](size_t start, size_t end) { + for (size_t i = start; i < end; ++i) { + points[i] = AffineElement::random_element(&engine); + pool[i] = ScalarField::random_element(&engine); + } + }); + + const uint256_t high_bit(0, 0, 0, uint64_t{ 1 } << (200 - 192)); + for (const size_t pool_width : { size_t{ 4 }, size_t{ 8 } }) { + ConcurrencyScope concurrency(pool_width); + constexpr size_t NUM_FILLERS = 101; + const size_t filler = std::max(scalar_multiplication::MSM_MIN_PTS_PER_THREAD * pool_width, + ((pool_width * max_wide) / NUM_FILLERS) + 1); + std::vector sizes(NUM_FILLERS, filler); + sizes.insert(sizes.end(), wide.begin(), wide.end()); + + const size_t num_msms = sizes.size(); + std::vector> batch_scalars(num_msms); + std::vector> spans; + std::vector dedup_infos(num_msms, 0); + std::vector expected(num_msms); + for (size_t k = 0; k < num_msms; ++k) { + // Fillers cycle through dense, sparse and duplicate-heavy scalars; the wide members are, in order, + // sparse, duplicate-heavy with a measured count, and dense with a bare dedup hint. + const size_t kind = k < NUM_FILLERS ? k % 4 : (k - NUM_FILLERS) + 1; + batch_scalars[k].resize(sizes[k]); + uint32_t dup_count = 0; + for (size_t i = 0; i < sizes[k]; ++i) { + const ScalarField& random = pool[((k * 31) + i) % max_wide]; + if (kind == 1) { + batch_scalars[k][i] = (i % 3 == 0) ? random : ScalarField::zero(); + } else if (kind == 2) { + batch_scalars[k][i] = ScalarField(high_bit + uint256_t((i / 8) + 1)); + dup_count += static_cast(i % 8 != 0); + } else { + batch_scalars[k][i] = random; + } + } + if (kind == 2) { + dedup_infos[k] = (k >= NUM_FILLERS || k % 8 == 2) ? dup_count : uint32_t{ 1 }; + } else if (kind == 3 && k >= NUM_FILLERS) { + dedup_infos[k] = 1; + } + spans.emplace_back(0, std::span(batch_scalars[k])); + expected[k] = scalar_multiplication::MSM::msm( + points, PolynomialSpan(0, std::span(batch_scalars[k]))); + } + + const auto original_scalars = batch_scalars; + const auto result = scalar_multiplication::MSM::batch_multi_scalar_mul( + points, spans, /*handle_edge_cases=*/false, dedup_infos); + for (size_t k = 0; k < num_msms; ++k) { + // Serialized, as commitments reach the transcript and the proof. + EXPECT_EQ(to_buffer(result[k]), to_buffer(expected[k])) + << "pool " << pool_width << ", MSM " << k << " (n=" << sizes[k] << ")"; + EXPECT_EQ(batch_scalars[k], original_scalars[k]) << "scalars of MSM " << k << " not restored"; + } + } +#endif +} diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_msm_split_by_cost.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_msm_split_by_cost.test.cpp new file mode 100644 index 0000000..81929b3 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/batch_msm_split_by_cost.test.cpp @@ -0,0 +1,487 @@ +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/serialize.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/bn254/bn254.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include "scalar_multiplication.hpp" +#include + +#include +#include + +using namespace bb; +using scalar_multiplication::SmallMsmSchedule; +using scalar_multiplication::round_parallel_detail::COST_SEGMENTS; +using scalar_multiplication::round_parallel_detail::MIN_SPLIT_PART_POINTS; +using scalar_multiplication::round_parallel_detail::MsmPart; +using scalar_multiplication::round_parallel_detail::plan_cost_split_parts; +using scalar_multiplication::round_parallel_detail::SegmentBits; + +namespace { +auto& engine = numeric::get_randomness(); + +// Each member's parts tile [0, length); every part of a split member has MIN_SPLIT_PART_POINTS points and a +// non-zero estimated cost. +void expect_tiling(const std::vector& parts, + std::span members, + std::span lengths, + const std::string& context) +{ + std::vector sorted = parts; + std::sort(sorted.begin(), sorted.end(), [](const MsmPart& a, const MsmPart& b) { + return a.member != b.member ? a.member < b.member : a.offset < b.offset; + }); + size_t i = 0; + for (size_t k = 0; k < members.size(); ++k) { + size_t next = 0; + size_t count = 0; + while (i < sorted.size() && sorted[i].member == members[k]) { + EXPECT_EQ(sorted[i].offset, next) << context << ": member " << members[k] << " has a gap or overlap"; + EXPECT_GT(sorted[i].length, 0U) << context; + next = sorted[i].offset + sorted[i].length; + ++count; + ++i; + } + EXPECT_EQ(next, lengths[k]) << context << ": member " << members[k] << " not covered"; + if (count > 1) { + for (const MsmPart& p : parts) { + if (p.member == members[k]) { + EXPECT_GE(p.length, MIN_SPLIT_PART_POINTS) << context << ": member " << members[k]; + EXPECT_GT(p.cost, 0U) << context << ": member " << members[k] << " has a zero-cost part"; + } + } + } + } + EXPECT_EQ(i, sorted.size()) << context << ": parts of unknown members"; +} + +size_t part_count(const std::vector& parts, size_t member) +{ + return static_cast( + std::count_if(parts.begin(), parts.end(), [member](const MsmPart& p) noexcept { return p.member == member; })); +} + +// The plan a batch makes at `pool_width` workers (empty when it makes none): its small members are those below +// MSM_MIN_PTS_PER_THREAD * pool_width points, there must be two of them, and one must fit two parts. +template +std::vector batch_plan(const std::vector>& scalars, size_t pool_width) +{ + std::vector ids; + std::vector lengths; + std::vector bits; + bool splittable = false; + for (size_t k = 0; k < scalars.size(); ++k) { + const size_t n = scalars[k].size(); + if (pool_width > 1 && n != 0 && n < scalar_multiplication::MSM_MIN_PTS_PER_THREAD * pool_width) { + ids.push_back(k); + lengths.push_back(n); + bits.push_back(scalar_multiplication::round_parallel_detail::sample_segment_bits(scalars[k])); + splittable |= n >= 2 * MIN_SPLIT_PART_POINTS; + } + } + if (ids.size() < 2 || !splittable) { + return {}; + } + return plan_cost_split_parts(ids, lengths, bits, pool_width); +} + +template std::vector random_points(size_t n) +{ + // Serial: the debug RNG is shared and not thread-safe. + std::vector points(n); + for (auto& p : points) { + p = AffineElement::random_element(&engine); + } + return points; +} + +template std::vector random_scalars(size_t n) +{ + std::vector s(n); + for (auto& x : s) { + x = ScalarField::random_element(&engine); + } + return s; +} + +// Scalars of exactly the field's bit length, so every sample weighs the same and a plan's cut points are fixed. +template std::vector full_width_scalars(size_t n) +{ + constexpr size_t BITS = ScalarField::modulus.get_msb() + 1; + std::vector s(n); + for (auto& x : s) { + do { + x = ScalarField::random_element(&engine); + } while (static_cast(x).get_msb() + 1 != BITS); + } + return s; +} + +// Runs one batch on a fresh thread whose pool has `pool_width` workers (native); where the pool is process-wide, at +// its current width. +template +std::vector run_batch(std::span points, + std::vector>& scalars, + std::span starts, + std::span dedup_infos, + SmallMsmSchedule schedule, + [[maybe_unused]] size_t pool_width) +{ + std::vector> spans; + for (size_t k = 0; k < scalars.size(); ++k) { + spans.emplace_back(starts[k], std::span(scalars[k])); + } + std::vector out; +#if defined(NO_MULTITHREADING) || defined(__wasm__) + out = scalar_multiplication::MSM::batch_multi_scalar_mul(points, spans, dedup_infos, schedule); +#else + std::thread worker([&] { + set_parallel_for_concurrency(pool_width); + out = scalar_multiplication::MSM::batch_multi_scalar_mul(points, spans, dedup_infos, schedule); + }); + worker.join(); +#endif + return out; +} +} // namespace + +// The planner splits only members above the fair share, at most min(length / MIN_SPLIT_PART_POINTS, pool_width) +// ways, tiles every member exactly, and orders parts by cost, then member, then offset. +TEST(BatchMsmSplitByCostPlanner, TilesSplitsAndOrders) +{ + SegmentBits full{}; + full.fill(254); + // Cost in the first eight segments and the last one: the only cut after the head that keeps every part + // non-empty in cost and MIN_SPLIT_PART_POINTS long is the first boundary past MIN_SPLIT_PART_POINTS. + SegmentBits head{}; + for (size_t j = 0; j < 8; ++j) { + head[j] = 254; + } + head[COST_SEGMENTS - 1] = 254; + SegmentBits none{}; + + const std::vector members = { 3, 5, 8, 9, 11 }; + const std::vector lengths = { 16000, 300, 16383, 9000, 4095 }; + const std::vector bits = { full, full, head, none, full }; + for (const size_t pool_width : { size_t{ 1 }, size_t{ 2 }, size_t{ 4 }, size_t{ 64 } }) { + const std::string context = "pool " + std::to_string(pool_width); + const std::vector parts = plan_cost_split_parts(members, lengths, bits, pool_width); + expect_tiling(parts, members, lengths, context); + for (size_t s = 1; s < parts.size(); ++s) { + const MsmPart& a = parts[s - 1]; + const MsmPart& b = parts[s]; + const bool ordered = + a.cost != b.cost ? a.cost > b.cost : (a.member != b.member ? a.member < b.member : a.offset < b.offset); + EXPECT_TRUE(ordered) << context << ": parts " << s - 1 << " and " << s; + } + EXPECT_EQ(part_count(parts, 5), 1U) << context << ": a member below MIN_SPLIT_PART_POINTS splits"; + EXPECT_EQ(part_count(parts, 9), 1U) << context << ": a zero-cost member splits"; + EXPECT_EQ(part_count(parts, 11), 1U) << context << ": a member below 2 * MIN_SPLIT_PART_POINTS splits"; + EXPECT_LE(part_count(parts, 3), std::min(pool_width, 16000 / MIN_SPLIT_PART_POINTS)) << context; + if (pool_width == 1) { + EXPECT_EQ(parts.size(), members.size()) << context << ": one worker splits nothing"; + } + } + + // At 64 workers the dense member takes the most parts allowed, and the head-and-tail member is cut once, at the + // first segment boundary past MIN_SPLIT_PART_POINTS, so its tail part carries only the last segment's cost. + const std::vector parts = plan_cost_split_parts(members, lengths, bits, 64); + EXPECT_EQ(part_count(parts, 3), 16000 / MIN_SPLIT_PART_POINTS); + ASSERT_EQ(part_count(parts, 8), 2U); + for (const MsmPart& p : parts) { + if (p.member == 8 && p.offset != 0) { + EXPECT_EQ(p.offset, 2303U); + EXPECT_EQ(p.cost, uint64_t{ 254 } * (16383 - ((16383 * (COST_SEGMENTS - 1)) / COST_SEGMENTS))); + } + } +} + +template class BatchMsmSplitByCostTest : public ::testing::Test {}; + +using CurveTypes = ::testing::Types; +TYPED_TEST_SUITE(BatchMsmSplitByCostTest, CurveTypes); + +// SPLIT_BY_COST must give every member the commitment the existing schedule and the edge-case-safe single MSM give, +// byte for byte after serialization, and restore every scalar, at 1, 4, 32 and 64 workers. The members cover dense, +// narrow, sparse, all-zero, a single non-zero, a part holding a single non-zero, duplicates with a measured count, a +// member that sums to infinity while its parts do not, a part that sums to infinity on its own, and members on the +// shared doubled-point table. Every part of a split member holds a non-zero sampled scalar, but its result can still +// be infinity (member 10). +TYPED_TEST(BatchMsmSplitByCostTest, MatchesUnsplitAndSafeMsm) +{ + using AffineElement = typename TypeParam::AffineElement; + using ScalarField = typename TypeParam::ScalarField; + + // Region A, a shared prefix as in a wire batch: members 0-6. Region B: member 7, whose last point is chosen. + // Region C: members 8-9, at most GLV_SMALL_N_THRESHOLD points, so their group uses the shared doubled-point table. + // Region D: member 10, whose first part's last point is chosen. + constexpr size_t REGION_A = 16383; + constexpr size_t CANCEL_N = 15000; + constexpr size_t GLV_N = scalar_multiplication::round_parallel_detail::GLV_SMALL_N_THRESHOLD; + constexpr size_t PART_CANCEL_N = 6000; + constexpr size_t START_B = REGION_A; + constexpr size_t START_C = START_B + CANCEL_N; + constexpr size_t START_D = START_C + GLV_N; + std::vector points = random_points(START_D + PART_CANCEL_N); + + std::vector> scalars; + std::vector starts; + std::vector dedup_infos; + auto add = [&](size_t start, std::vector s, uint32_t info) { + starts.push_back(start); + scalars.push_back(std::move(s)); + dedup_infos.push_back(info); + }; + auto msm_safe = [&](size_t start, std::span s) { + return scalar_multiplication::MSM::msm( + points, PolynomialSpan(start, s), /*handle_edge_cases=*/true); + }; + + add(0, random_scalars(16000), 0); // 0: dense, full width + add(0, random_scalars(300), 0); // 1: narrow + { + std::vector s(12000, ScalarField::zero()); // 2: sparse + for (size_t i = 0; i < s.size(); i += 7) { + s[i] = ScalarField::random_element(&engine); + } + add(0, std::move(s), 0); + } + add(0, std::vector(5000, ScalarField::zero()), 0); // 3: all zero + // 4: dense in its first eight segments, and one non-zero scalar at the last segment's sample point; it splits + // once after the head, so its tail part holds that single non-zero. + constexpr size_t TAIL_NONZERO = (REGION_A * ((2 * COST_SEGMENTS) - 1)) / (2 * COST_SEGMENTS); + { + std::vector s(REGION_A, ScalarField::zero()); + for (size_t i = 0; i < (8 * REGION_A) / COST_SEGMENTS; ++i) { + s[i] = ScalarField::random_element(&engine); + } + s[TAIL_NONZERO] = ScalarField::random_element(&engine); + add(0, std::move(s), 0); + } + { + // 5: a single non-zero scalar off every sample point (estimated cost 0, one part). + std::vector s(10000, ScalarField::zero()); + s[7777] = ScalarField::random_element(&engine); + add(0, std::move(s), 0); + } + { + // 6: runs of 8 equal scalars with their measured duplicate count, shared out across its parts. + const uint256_t high_bit(0, 0, 0, uint64_t{ 1 } << (200 - 192)); + std::vector s(14000); + uint32_t dup_count = 0; + for (size_t i = 0; i < s.size(); ++i) { + s[i] = ScalarField(high_bit + uint256_t((i / 8) + 1)); + dup_count += static_cast(i % 8 != 0); + } + add(0, std::move(s), dup_count); + } + { + // 7: dense, and its last point is minus the sum of the rest, so the member is infinity while no part is. + std::vector s = random_scalars(CANCEL_N); + s.back() = ScalarField::one(); + points[START_B + CANCEL_N - 1] = -msm_safe(START_B, std::span(s.data(), CANCEL_N - 1)); + add(START_B, std::move(s), 0); + } + add(START_C, random_scalars(GLV_N), 1); // 8: dense, shared doubled-point table, dedup hint + // 9: same group, half width. A 4,096-point member has one legal two-way cut, at its middle, taken only when the + // first half's sampled cost reaches half the total; equal-width scalars make the halves weigh the same. + add(START_C, full_width_scalars(GLV_N / 2), 0); + add(START_D, random_scalars(PART_CANCEL_N), 0); + + // 10: dense, cut in two at 32 and 64 workers. The last point of its first part is minus the sum of the rest of + // that part, so that part alone is infinity. The cut lies on a segment boundary and the changed scalar sits just + // before it, off every sample point, so the change leaves the plan as it is. WASM classifies small members by a + // fixed bound and never reaches these plans; there any cut gives a valid member. +#ifdef __wasm__ + const size_t cut = PART_CANCEL_N / 2; +#else + const std::vector plan64 = batch_plan(scalars, 64); + size_t cut = 0; + for (const MsmPart& p : plan64) { + if (p.member == 10 && p.offset == 0) { + cut = p.length; + } + } + ASSERT_EQ(part_count(plan64, 10), 2U); +#endif + scalars[10][cut - 1] = ScalarField::one(); + points[START_D + cut - 1] = -msm_safe(START_D, std::span(scalars[10].data(), cut - 1)); + EXPECT_TRUE(msm_safe(START_D, std::span(scalars[10].data(), cut)).is_point_at_infinity()); + + const size_t num_msms = scalars.size(); + std::vector expected(num_msms); + for (size_t k = 0; k < num_msms; ++k) { + expected[k] = msm_safe(starts[k], scalars[k]); + } + EXPECT_TRUE(expected[7].is_point_at_infinity()); + +#ifndef __wasm__ + // The plans the batch makes at 64 and 32 workers. + { + const std::vector plan = batch_plan(scalars, 64); + ASSERT_EQ(plan.size(), plan64.size()); + std::vector ids(num_msms); + std::vector lengths(num_msms); + for (size_t k = 0; k < num_msms; ++k) { + ids[k] = k; + lengths[k] = scalars[k].size(); + } + expect_tiling(plan, ids, lengths, "plan at 64"); + for (const size_t k : { size_t{ 0 }, size_t{ 6 }, size_t{ 7 }, size_t{ 8 }, size_t{ 10 } }) { + EXPECT_GT(part_count(plan, k), 1U) << "member " << k << " is not split at 64 workers"; + } + EXPECT_EQ(part_count(plan, 3), 1U); + EXPECT_EQ(part_count(plan, 5), 1U); + ASSERT_EQ(part_count(plan, 4), 2U); + for (const MsmPart& p : plan) { + if (p.member == 4 && p.offset != 0) { + const auto& s = scalars[4]; + const auto nonzero = std::count_if(s.begin() + static_cast(p.offset), + s.end(), + [](const ScalarField& x) noexcept { return !x.is_zero(); }); + EXPECT_EQ(nonzero, 1) << "member 4's tail part does not hold exactly one non-zero"; + } + if (p.member == 10 && p.offset == 0) { + EXPECT_EQ(p.length, cut) << "member 10's plan moved"; + } + } + + // At 32 workers only members under 8,192 points are small; members 9 and 10 split, and member 10 at the same + // cut, since a two-part cut sits at the cost median whatever the worker count. + const std::vector plan32 = batch_plan(scalars, 32); + EXPECT_EQ(part_count(plan32, 9), 2U); + ASSERT_EQ(part_count(plan32, 10), 2U); + for (const MsmPart& p : plan32) { + if (p.member == 10 && p.offset == 0) { + EXPECT_EQ(p.length, cut); + } + } + } +#endif + +#if defined(NO_MULTITHREADING) || defined(__wasm__) + const std::vector widths = { get_num_cpus() }; +#else + const std::vector widths = { 1, 4, 32, 64 }; +#endif + for (const size_t pool_width : widths) { + const auto original = scalars; + const std::vector split = + run_batch(points, scalars, starts, dedup_infos, SmallMsmSchedule::SPLIT_BY_COST, pool_width); + EXPECT_EQ(scalars, original) << "pool " << pool_width << ": scalars changed"; + const std::vector whole = + run_batch(points, scalars, starts, dedup_infos, SmallMsmSchedule::WHOLE, pool_width); + ASSERT_EQ(split.size(), num_msms); + ASSERT_EQ(whole.size(), num_msms); + for (size_t k = 0; k < num_msms; ++k) { + EXPECT_EQ(to_buffer(split[k]), to_buffer(expected[k])) << "pool " << pool_width << ", member " << k; + EXPECT_EQ(to_buffer(split[k]), to_buffer(whole[k])) << "pool " << pool_width << ", member " << k; + } + } +} + +// Without edge-case handling, a batch assumes no two partial sums it adds share an x coordinate, and aborts on the zero +// denominator otherwise. Here two equal (or opposite) points carry the scalar 2^100 and every other scalar is below +// 2^20, so in the window holding bit 100 those two points are their bucket's only entries and the affine tree adds them +// directly (with the dedup pre-pass, its cluster sum does). Scalars below 2^127 skip the GLV split (k1 = k, k2 = 0), so +// this holds with and without the doubled-point table. Both points sit inside one part: both schedules must abort. +// Death tests need a native process with threads. +#if !defined(__wasm__) && !defined(NO_MULTITHREADING) +TEST(BatchMsmSplitByCostDeathTest, CoincidingPointsInOneBucketAbort) +{ + GTEST_FLAG_SET(death_test_style, "threadsafe"); + using Curve = curve::BN254; + using AffineElement = Curve::AffineElement; + using ScalarField = Curve::ScalarField; + + constexpr size_t POOL = 32; + constexpr size_t N = 6000; + constexpr size_t FILLER = 300; + constexpr size_t A = 100; + const std::vector base_points = random_points(N + FILLER); + auto small_scalars = [](size_t n) { + std::vector s(n); + for (auto& x : s) { + x = ScalarField(1 + (engine.get_random_uint32() % ((1U << 20) - 1))); + } + return s; + }; + std::vector> scalars = { small_scalars(N), small_scalars(FILLER) }; + const ScalarField pair_scalar = ScalarField(uint256_t(1) << 100); + scalars[0][A] = pair_scalar; + scalars[0][A + 1] = pair_scalar; + ASSERT_EQ(ScalarField::split_into_endomorphism_scalars(pair_scalar.from_montgomery_form()).second, + (std::array{ 0, 0 })); + const std::vector starts = { 0, N }; + const std::vector plan = batch_plan(scalars, POOL); + ASSERT_EQ(part_count(plan, 0), 2U); + for (const MsmPart& p : plan) { + if (p.member == 0 && p.offset == 0) { + ASSERT_GT(p.length, A + 1) << "the pair must share the first part"; + } + } + + struct Case { + bool opposite; + uint32_t dedup; + }; + for (const Case c : { Case{ false, 0 }, Case{ true, 1 } }) { + std::vector points = base_points; + points[A + 1] = c.opposite ? -points[A] : points[A]; + const std::vector dedup_infos = { c.dedup, 0 }; + auto run = [&](SmallMsmSchedule schedule) { + static_cast(run_batch(points, scalars, starts, dedup_infos, schedule, POOL)); + }; + SCOPED_TRACE(std::string(c.opposite ? "opposite" : "equal") + (c.dedup != 0 ? ", dedup" : "")); + EXPECT_DEATH(run(SmallMsmSchedule::WHOLE), "invert zero"); + EXPECT_DEATH(run(SmallMsmSchedule::SPLIT_BY_COST), "invert zero"); + } +} +#endif + +// Not run by default (it prints, it does not check): the cost of SPLIT_BY_COST's planning on 4,000 small members, +// against the existing schedule, at 64 workers. With no member long enough for two parts the planner returns before +// sampling; with one such member (all zero, so nothing splits) every small member is sampled and planned. +#if !defined(__wasm__) && !defined(NO_MULTITHREADING) +TEST(BatchMsmSplitByCostPlanner, DISABLED_PlanningCost) +{ + using Curve = curve::BN254; + using ScalarField = Curve::ScalarField; + constexpr size_t TINY = 4000; + const std::vector points = random_points(2 * MIN_SPLIT_PART_POINTS); + for (const bool with_splittable : { false, true }) { + std::vector> scalars; + for (size_t k = 0; k < TINY; ++k) { + scalars.push_back(random_scalars(16 + (k % 49))); + } + if (with_splittable) { + scalars.emplace_back(2 * MIN_SPLIT_PART_POINTS, ScalarField::zero()); + } + const std::vector starts(scalars.size(), 0); + const std::vector dedup_infos(scalars.size(), 0); + auto best_us = [&](SmallMsmSchedule schedule) { + double best = 1e30; + for (size_t rep = 0; rep < 20; ++rep) { + const auto t0 = std::chrono::steady_clock::now(); + static_cast(run_batch(points, scalars, starts, dedup_infos, schedule, 64)); + const auto t1 = std::chrono::steady_clock::now(); + best = std::min(best, std::chrono::duration(t1 - t0).count()); + } + return best; + }; + const double whole = best_us(SmallMsmSchedule::WHOLE); + const double split = best_us(SmallMsmSchedule::SPLIT_BY_COST); + info("planning cost, ", + scalars.size(), + " small members", + with_splittable ? " (one splittable)" : " (none splittable)", + ": whole ", + whole, + " us, split ", + split, + " us, best of 20"); + } +} +#endif diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp index b24c549..5117268 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp @@ -34,7 +34,7 @@ template struct BatchMsmGlvGroup { namespace { // NOLINTNEXTLINE(readability-function-size, readability-function-cognitive-complexity, // google-readability-function-size) -template +template void pippenger_round_parallel_batched(std::span> scalar_arrays, std::span> point_arrays, std::vector& out_results, @@ -251,9 +251,86 @@ void pippenger_round_parallel_batched(std::span> ranges; + ranges.reserve(large_members.size()); + for (size_t m : large_members) { + const auto begin = reinterpret_cast(scalar_arrays[m].data()); + ranges.emplace_back(begin, begin + (n_input[m] * sizeof(ScalarField))); + } + std::sort(ranges.begin(), ranges.end()); + for (size_t i = 1; i < ranges.size(); ++i) { + if (ranges[i].first < ranges[i - 1].second) { + return false; + } + } + return true; + }; const bool large_members_concurrent = pool_width >= CONCURRENT_MIN_POOL_WIDTH && large_members.size() > CONCURRENT_MIN_MEMBERS && - max_large_n <= total_large_n / pool_width; + max_large_n <= total_large_n / pool_width && scalar_spans_disjoint(); +#endif + + // A few independent large native MSMs can instead share the CPU budget, + // each using a private multi-threaded arena. Keep the established wide-AVM + // single-thread-per-member policy above unchanged. + size_t large_job_count = 0; + [[maybe_unused]] size_t threads_per_large_job = 0; + [[maybe_unused]] size_t large_job_arena_bytes = 0; +#if !defined(__wasm__) && !defined(NO_MULTITHREADING) && SIZE_MAX > UINT32_MAX + constexpr size_t MIN_LARGE_JOB_THREADS = 4; + constexpr size_t MAX_LARGE_JOBS = 4; + // Admission cap on canonical arena payload only, not expected allocation or + // a process RSS bound (GLV storage, sort scratch and thread stacks are extra). + constexpr size_t LARGE_JOB_ARENA_PAYLOAD_CAP = size_t{ 16 } << 30; + if (!large_members_concurrent && large_members.size() >= 2 && pool_width >= 2 * MIN_LARGE_JOB_THREADS && + total_large_n >= (size_t{ 1 } << 18)) { + // The kernel temporarily converts scalar backing in place and restores + // it. Sequential large members allowed repeated/overlapping spans, so + // preserve that path unless every concurrent mutable span is disjoint. + bool disjoint_scalars = true; + for (size_t i = 0; i < large_members.size() && disjoint_scalars; ++i) { + const size_t a = large_members[i]; + if (n_input[a] > std::numeric_limits::max() / sizeof(ScalarField)) { + disjoint_scalars = false; + break; + } + const uintptr_t first = reinterpret_cast(scalar_arrays[a].data()); + const size_t first_bytes = n_input[a] * sizeof(ScalarField); + for (size_t j = 0; j < i; ++j) { + const size_t b = large_members[j]; + const uintptr_t second = reinterpret_cast(scalar_arrays[b].data()); + const size_t second_bytes = n_input[b] * sizeof(ScalarField); + if (first <= second ? second - first < first_bytes : first - second < second_bytes) { + disjoint_scalars = false; + break; + } + } + } + const size_t max_jobs = std::min({ MAX_LARGE_JOBS, large_members.size(), pool_width / MIN_LARGE_JOB_THREADS }); + for (size_t jobs = disjoint_scalars ? max_jobs : 0; jobs >= 2; --jobs) { + const size_t average = total_large_n / jobs; + // Avoid assigning most of the work to one independently capped job. + if (max_large_n > average + average / 2) { + continue; + } + const size_t threads = pool_width / jobs; + size_t arena_bytes = 0; + for (size_t m : large_members) { + const bool ext_glv = !external_glv_for(m, n_input[m]).empty(); + arena_bytes = std::max(arena_bytes, + compute_arena_bytes_for_msm(n_input[m], ext_glv, info_for(m), threads)); + } + if (arena_bytes <= LARGE_JOB_ARENA_PAYLOAD_CAP / jobs) { + large_job_count = jobs; + threads_per_large_job = threads; + large_job_arena_bytes = arena_bytes; + break; + } + } + } #endif // Shared dynamically-sized arena for the sequential (large-member) calls. Sized to @@ -264,7 +341,7 @@ void pippenger_round_parallel_batched(std::span shared_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) std::span shared_arena; - if (!large_members_concurrent) { + if (!large_members_concurrent && large_job_count == 0) { for (size_t m : large_members) { const bool ext_glv = !external_glv_for(m, n_input[m]).empty(); // The internal short-circuits to trivial_msm_threaded for tiny MSMs, so the hint @@ -279,6 +356,99 @@ void pippenger_round_parallel_batched(std::span(shared_arena_owner.get(), shared_arena_bytes); } } + // Cost-split small-member dispatch: the same per-worker pool, over parts instead of whole members (see + // round_parallel_detail::plan_cost_split_parts). A part is a member's contiguous range, so it runs exactly as a + // concurrent chunk does: its own scalars (converted and restored in place by its own call, never shared), the + // aligned slice of the shared GLV buffer, and a share of the member's duplicate count. Partials are summed per + // member in offset order with the complete addition, which handles infinity, doubling and cancellation. When no + // small member is long enough for two parts, nothing is sampled and the whole-member pool below runs as is. + if constexpr (SMALL_SCHEDULE == SmallMsmSchedule::SPLIT_BY_COST) { + const bool any_splittable = std::any_of(small_members.begin(), small_members.end(), [&](size_t m) noexcept { + return n_input[m] >= 2 * round_parallel_detail::MIN_SPLIT_PART_POINTS; + }); + if (any_splittable) { + BB_BENCH_NAME("MSM_fast::pippenger_round_parallel_batched/small_members_split_by_cost"); + using round_parallel_detail::MsmPart; + std::vector lengths(small_members.size()); + std::vector bits(small_members.size()); + bb::parallel_for(pool_width, [&](const ThreadChunk& chunk) { + for (size_t s : chunk.range(small_members.size())) { + const size_t m = small_members[s]; + lengths[s] = n_input[m]; + bits[s] = round_parallel_detail::sample_segment_bits( + std::span(scalar_arrays[m].data(), n_input[m])); + } + }); + const std::vector parts = + round_parallel_detail::plan_cost_split_parts(small_members, lengths, bits, pool_width); + + auto part_info = [&](const MsmPart& p) noexcept -> size_t { + const size_t info = info_for(p.member); + const size_t n = n_input[p.member]; + return (info < 2 || p.length == n) ? info : std::max(2, (info * p.length) / n); + }; + auto part_glv = [&](const MsmPart& p) noexcept -> std::span { + const std::span glv = external_glv_for(p.member, n_input[p.member]); + return glv.empty() ? glv : glv.subspan(2 * p.offset, 2 * p.length); + }; + + size_t part_arena_bytes = 0; + for (const MsmPart& p : parts) { + part_arena_bytes = + std::max(part_arena_bytes, + compute_arena_bytes_for_msm(p.length, !part_glv(p).empty(), part_info(p) != 0, 1)); + } +#ifdef __wasm__ + constexpr size_t aggregate_arena_budget = round_parallel_detail::BATCH_MEM_BUDGET; +#else + constexpr size_t aggregate_arena_budget = 2ULL * 1024ULL * 1024ULL * 1024ULL; +#endif + const size_t workers_by_budget = part_arena_bytes > 0 + ? std::max(1, aggregate_arena_budget / part_arena_bytes) + : std::numeric_limits::max(); + const size_t num_workers = std::min({ pool_width, parts.size(), workers_by_budget }); + std::unique_ptr part_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) + if (part_arena_bytes > 0) { + part_arena_owner = std::make_unique_for_overwrite( + num_workers * part_arena_bytes); // NOLINT(cppcoreguidelines-avoid-c-arrays) + } + const bool release_slices = num_workers * part_arena_bytes >= (size_t{ 64 } << 20); + std::vector partials(parts.size()); + std::atomic next_part{ 0 }; + bb::parallel_for(num_workers, [&](size_t tid) { + std::span worker_arena; + if (part_arena_bytes > 0) { + worker_arena = { part_arena_owner.get() + (tid * part_arena_bytes), part_arena_bytes }; + } + while (true) { + const size_t s = next_part.fetch_add(1, std::memory_order_relaxed); + if (s >= parts.size()) { + break; + } + const MsmPart& p = parts[s]; + PolynomialSpan sp( + 0, std::span(scalar_arrays[p.member].data() + p.offset, p.length)); + partials[s] = pippenger_round_parallel( + sp, point_arrays[p.member].subspan(p.offset), part_info(p), part_glv(p), worker_arena, 1); + } + if (release_slices) { + round_parallel_detail::release_arena_slice(worker_arena); + } + }); + + std::vector by_offset(parts.size()); + std::iota(by_offset.begin(), by_offset.end(), size_t{ 0 }); + std::sort(by_offset.begin(), by_offset.end(), [&](size_t a, size_t b) { + return parts[a].member != parts[b].member ? parts[a].member < parts[b].member + : parts[a].offset < parts[b].offset; + }); + for (size_t s : by_offset) { + out_results[parts[s].member] += partials[s]; + } + small_members.clear(); + } + } + // Concurrent small-member dispatch: workers pull members off an atomic cursor and run // each with a thread-capped pipeline (max_threads=1, so the member never re-enters the // pool) out of a per-worker arena sized for the capped layout. The GLV-doubled buffer @@ -293,17 +463,30 @@ void pippenger_round_parallel_batched(std::span 0 ? std::max(1, round_parallel_detail::BATCH_MEM_BUDGET / small_arena_bytes) - : std::numeric_limits::max(); + // Native servers may keep more independent small MSMs busy at once. This aggregate + // allowance does not change any individual MSM's 32 MiB window/layout budget. + // 2 GiB bounds this experiment to 64 such budgets; it is not a tuned optimum. + // Compared with the old aggregate cap, the arena block can grow by at most 2016 MiB. + // Other worker/TLS allocations and RSS must still be measured separately. +#ifdef __wasm__ + constexpr size_t aggregate_arena_budget = round_parallel_detail::BATCH_MEM_BUDGET; +#else + constexpr size_t aggregate_arena_budget = 2ULL * 1024ULL * 1024ULL * 1024ULL; +#endif + const size_t workers_by_budget = small_arena_bytes > 0 + ? std::max(1, aggregate_arena_budget / small_arena_bytes) + : std::numeric_limits::max(); const size_t num_workers = std::min({ pool_width, small_members.size(), workers_by_budget }); std::unique_ptr small_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) if (small_arena_bytes > 0) { small_arena_owner = std::make_unique_for_overwrite( num_workers * small_arena_bytes); // NOLINT(cppcoreguidelines-avoid-c-arrays) } + // A block this large is normally mapped on its own, so its free unmaps every resident page on this thread. The + // workers discard their slices' interior pages first, which leaves that free little to unmap. glibc still + // serves the block from the heap when free heap space holds it; the next allocation there then faults the + // discarded pages back in. The floor is release_pages_in_parallel's. + const bool release_slices = num_workers * small_arena_bytes >= (size_t{ 64 } << 20); std::atomic next_member{ 0 }; bb::parallel_for(num_workers, [&](size_t tid) { std::span worker_arena; @@ -321,35 +504,127 @@ void pippenger_round_parallel_batched(std::span( sp, point_arrays[m], info_for(m), external_glv_for(m, n), worker_arena, /*max_threads=*/1); } + if (release_slices) { + round_parallel_detail::release_arena_slice(worker_arena); + } }); } if (large_members_concurrent) { - // Workers pull members off an atomic cursor. Each member runs single-threaded - // (max_threads=1). This skips the member's cross-thread reduction. It also keeps the member - // off the pool, so there is no nested parallel_for. The gate above guarantees at least - // pool_width members, so every worker stays busy. Each call self-allocates its arena (empty - // span), because a shared num_workers × max-member arena would exceed BATCH_MEM_BUDGET and - // cap num_workers below pool_width. Members run largest-first (longest-processing-time - // order) to bound the tail imbalance. + // Workers pull work off an atomic cursor and run it single-threaded (max_threads=1). This skips the + // member's cross-thread reduction. It also keeps the member off the pool, so there is no nested + // parallel_for. The gate above guarantees at least pool_width members, so every worker starts busy. Each + // call self-allocates its arena (empty span), because a shared num_workers × max-member arena would + // exceed BATCH_MEM_BUDGET and cap num_workers below pool_width. + // + // A member's cost tracks its non-zero scalars, not its span, so the span-based gate admits batches in + // which a few dense members each take longer on one thread than the rest of the batch takes on all of + // them. Members wider than CONCURRENT_CHUNK_POINTS therefore run as contiguous chunks of at most that + // many points: an MSM is a sum over its terms, so a member's result is the sum of its chunks' results. + // Chunks run longest-first to bound the tail. BB_BENCH_NAME("MSM_fast::pippenger_round_parallel_batched/large_members_concurrent"); - std::sort( - large_members.begin(), large_members.end(), [&](size_t a, size_t b) { return n_input[a] > n_input[b]; }); - const size_t num_workers = std::min(pool_width, large_members.size()); - std::atomic next_large{ 0 }; + constexpr size_t CONCURRENT_CHUNK_POINTS = size_t{ 1 } << 16; + struct Chunk { + size_t member; + size_t offset; + size_t length; + }; + std::vector chunks; + for (size_t m : large_members) { + const size_t n = n_input[m]; + const size_t parts = (n + CONCURRENT_CHUNK_POINTS - 1) / CONCURRENT_CHUNK_POINTS; + for (size_t k = 0; k < parts; ++k) { + const size_t begin = (n * k) / parts; + chunks.push_back({ m, begin, ((n * (k + 1)) / parts) - begin }); + } + } + std::sort(chunks.begin(), chunks.end(), [](const Chunk& a, const Chunk& b) { + if (a.length != b.length) { + return a.length > b.length; + } + return a.member != b.member ? a.member < b.member : a.offset < b.offset; + }); + std::vector partials(chunks.size()); + const size_t num_workers = std::min(pool_width, chunks.size()); + std::atomic next_chunk{ 0 }; bb::parallel_for(num_workers, [&](size_t) { while (true) { - const size_t s = next_large.fetch_add(1, std::memory_order_relaxed); - if (s >= large_members.size()) { + const size_t c = next_chunk.fetch_add(1, std::memory_order_relaxed); + if (c >= chunks.size()) { break; } - const size_t m = large_members[s]; + const auto [m, offset, length] = chunks[c]; const size_t n = n_input[m]; - PolynomialSpan sp(0, std::span(scalar_arrays[m].data(), n)); - out_results[m] = pippenger_round_parallel( - sp, point_arrays[m], info_for(m), external_glv_for(m, n), {}, /*max_threads=*/1); + // A measured duplicate count describes the whole member; each chunk gets its share. + const size_t info = info_for(m) >= 2 ? std::max(2, (info_for(m) * length) / n) : info_for(m); + std::span glv = external_glv_for(m, n); + if (!glv.empty()) { + glv = glv.subspan(2 * offset, 2 * length); + } + PolynomialSpan sp( + 0, std::span(scalar_arrays[m].data() + offset, length)); + partials[c] = pippenger_round_parallel( + sp, point_arrays[m].subspan(offset), info, glv, {}, /*max_threads=*/1); } }); + // out_results starts at infinity; summing in chunk order keeps the result deterministic. + for (size_t c = 0; c < chunks.size(); ++c) { + out_results[chunks[c].member] += partials[c]; + } +#if !defined(__wasm__) && !defined(NO_MULTITHREADING) && SIZE_MAX > UINT32_MAX + } else if (large_job_count != 0) { + BB_BENCH_NAME("MSM_fast::pippenger_round_parallel_batched/large_member_jobs"); + std::sort( + large_members.begin(), large_members.end(), [&](size_t a, size_t b) { return n_input[a] > n_input[b]; }); + std::atomic next_large{ 0 }; + auto* const bench_parent = bb::detail::GlobalBenchStatsContainer::parent; + std::vector jobs; + jobs.reserve(large_job_count); + for (size_t job = 0; job < large_job_count; ++job) { + try { + jobs.emplace_back([&] { + // A new caller thread owns a new TLS pool. Set its width + // BEFORE the first MSM dispatch; active job widths together + // never exceed the original caller's pool_width. + bb::set_parallel_for_concurrency(threads_per_large_job); + bb::detail::GlobalBenchStatsContainer::parent = bench_parent; + std::unique_ptr owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) + std::span arena; + if (large_job_arena_bytes != 0) { + owner = std::make_unique_for_overwrite(large_job_arena_bytes); + arena = { owner.get(), large_job_arena_bytes }; + } + while (true) { + const size_t index = next_large.fetch_add(1, std::memory_order_relaxed); + if (index >= large_members.size()) { + break; + } + const size_t m = large_members[index]; + const size_t n = n_input[m]; + PolynomialSpan sp(0, + std::span(scalar_arrays[m].data(), n)); + out_results[m] = pippenger_round_parallel( + sp, point_arrays[m], info_for(m), external_glv_for(m, n), arena, threads_per_large_job); + } + }); + } catch (const std::system_error&) { + // Any successfully created jobs still drain the complete queue. + // If none could start, use the original per-member fallback below. + break; + } + } + for (auto& job : jobs) { + job.join(); + } + if (jobs.empty()) { + for (size_t m : large_members) { + const size_t n = n_input[m]; + PolynomialSpan sp(0, std::span(scalar_arrays[m].data(), n)); + out_results[m] = + pippenger_round_parallel(sp, point_arrays[m], info_for(m), external_glv_for(m, n)); + } + } +#endif } else { // Sequential large-member dispatch: one member at a time, each running the full single- // MSM_fast pipeline (its own from-Mont and to-Mont, schedule, Stage 1-6b) across the whole @@ -415,3 +690,37 @@ std::vector MSM_fast::batch_multi_scalar_m } return results; } + +template +std::vector MSM_fast::batch_multi_scalar_mul( + std::span points, + std::span> scalars, + std::span dedup_infos, + SmallMsmSchedule schedule) noexcept +{ + if (schedule == SmallMsmSchedule::WHOLE) { + return batch_multi_scalar_mul(points, scalars, /*handle_edge_cases=*/false, dedup_infos); + } + BB_BENCH_NAME("MSM_fast::batch_multi_scalar_mul/split_by_cost"); + const size_t k = scalars.size(); + std::vector> point_subspans; + std::vector> scalar_subspans; + point_subspans.reserve(k); + scalar_subspans.reserve(k); + for (size_t i = 0; i < k; ++i) { + const size_t start_i = scalars[i].start_index; + BB_ASSERT_LTE(start_i, points.size(), "scalars[m].start_index exceeds shared points span"); + point_subspans.push_back(points.subspan(start_i, points.size() - start_i)); + scalar_subspans.push_back(scalars[i].span); + } + + std::vector per_msm_jac; + pippenger_round_parallel_batched( + scalar_subspans, point_subspans, per_msm_jac, dedup_infos); + + std::vector results(k); + for (size_t i = 0; i < k; ++i) { + results[i] = AffineElement(per_msm_jac[i]); + } + return results; +} diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.cpp index a0e48c4..72bded5 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.cpp @@ -727,6 +727,22 @@ std::vector MSM::batch_multi_scalar_mul( return MSM_fast::batch_multi_scalar_mul(points, scalars, handle_edge_cases, dedup_infos); } +template +std::vector MSM::batch_multi_scalar_mul( + std::span points, + std::span> scalars, + std::span dedup_infos, + SmallMsmSchedule schedule) +{ + for (const auto& member : scalars) { + check_msm_points_cover_scalars(member.start_index, member.size(), points.size()); + } + if (schedule == SmallMsmSchedule::WHOLE || use_legacy_msm()) { + return batch_multi_scalar_mul(points, scalars, /*handle_edge_cases=*/false, dedup_infos); + } + return MSM_fast::batch_multi_scalar_mul(points, scalars, dedup_infos, schedule); +} + template curve::BN254::Element pippenger(PolynomialSpan scalars, std::span points, bool handle_edge_cases, diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.hpp index 39389ec..0aed00a 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication.hpp @@ -470,6 +470,15 @@ template class MSM { std::span> scalars, bool handle_edge_cases = true, std::span dedup_infos = {}); + + /** + * @brief The batch MSM without edge-case handling, with an explicit small-member schedule (see SmallMsmSchedule). + * @details WHOLE, or the legacy MSM, is exactly `batch_multi_scalar_mul(points, scalars, false, dedup_infos)`. + */ + static std::vector batch_multi_scalar_mul(std::span points, + std::span> scalars, + std::span dedup_infos, + SmallMsmSchedule schedule); }; extern template class MSM; 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..5611222 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" @@ -19,8 +20,17 @@ #include #include #include +#include #include #include +#if !defined(__wasm__) && !defined(NO_MULTITHREADING) && SIZE_MAX > UINT32_MAX +#include +#include +#endif +#if !defined(__wasm__) && !defined(_WIN32) +#include +#include +#endif #ifdef __wasm_simd128__ #include @@ -46,6 +56,23 @@ size_t window_bits_tuning_oversub_factor(size_t n_input) namespace round_parallel_detail { +// Returns the whole pages inside one worker's slice of a shared arena block to the OS, from that worker, so the slices +// are released concurrently and the block's later free has fewer resident pages to unmap. Pages that straddle a slice +// boundary stay resident, as does the whole slice if the advice fails (failures are ignored). The slice's contents are +// lost. +inline void release_arena_slice([[maybe_unused]] std::span slice) +{ +#if !defined(__wasm__) && !defined(_WIN32) && defined(MADV_DONTNEED) + const auto page = static_cast(sysconf(_SC_PAGESIZE)); + const auto begin = reinterpret_cast(slice.data()); + const uintptr_t lo = (begin + page - 1) & ~(page - 1); + const uintptr_t hi = (begin + slice.size()) & ~(page - 1); + if (hi > lo) { + static_cast(madvise(reinterpret_cast(lo), hi - lo, MADV_DONTNEED)); + } +#endif +} + // Anonymous namespace gives all TU-private helpers in `round_parallel_detail` internal // linkage (clang-tidy `misc-use-anonymous-namespace`). It is briefly closed and reopened // around `pippenger_round_parallel_jacobian_fast`, which has external linkage via @@ -294,8 +321,232 @@ 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 +[[maybe_unused]] 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 +[[maybe_unused]] 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 +970,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/ecc/scalar_multiplication/scalar_multiplication_fast.hpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.hpp index e51d707..9c61480 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/scalar_multiplication_fast.hpp @@ -6,6 +6,8 @@ #include "barretenberg/polynomials/polynomial.hpp" #include +#include +#include #include #include #include @@ -130,6 +132,17 @@ extern template curve::Grumpkin::Element pippenger_unsafe_fast( std::span points, size_t dedup_info) noexcept; +/** + * @brief How a batch MSM schedules its small members (those run one per worker, single-threaded). + * @details WHOLE runs each small member as one task. SPLIT_BY_COST estimates each small member's cost from a sample + * of its scalars and runs any member above the pool's fair share as contiguous parts, whose results are + * summed per member in offset order. Both produce the same group elements. + */ +enum class SmallMsmSchedule : uint8_t { + WHOLE, + SPLIT_BY_COST, +}; + template class MSM_fast { public: using Element = typename Curve::Element; @@ -180,6 +193,15 @@ template class MSM_fast { std::span> scalars, bool handle_edge_cases = true, std::span dedup_infos = {}) noexcept; + + /** + * @brief The batch driver without edge-case handling, with an explicit small-member schedule. + * @details WHOLE is exactly `batch_multi_scalar_mul(points, scalars, false, dedup_infos)`. + */ + static std::vector batch_multi_scalar_mul(std::span points, + std::span> scalars, + std::span dedup_infos, + SmallMsmSchedule schedule) noexcept; }; extern template class MSM_fast; @@ -225,6 +247,113 @@ inline constexpr size_t GLV_SMALL_N_THRESHOLD = size_t{ 1 } << 16; inline constexpr size_t GLV_SMALL_N_THRESHOLD = size_t{ 1 } << 13; #endif +// SmallMsmSchedule::SPLIT_BY_COST samples one scalar per equal segment of a member; a part never ends inside a segment. +inline constexpr size_t COST_SEGMENTS = 64; +// Below this many points a part's fixed setup outweighs what splitting saves. +inline constexpr size_t MIN_SPLIT_PART_POINTS = size_t{ 1 } << 11; + +using SegmentBits = std::array; + +/// Contiguous points [offset, offset + length) of batch member `member`, with its estimated cost. +struct MsmPart { + size_t member; + size_t offset; + size_t length; + uint64_t cost; +}; + +/// First point of segment j of a member of n points. +inline size_t cost_segment_begin(size_t n, size_t j) noexcept +{ + return (n * j) / COST_SEGMENTS; +} + +/** + * @brief Bit length of the scalar at the middle of each of a member's COST_SEGMENTS segments (0 for zero). + * @details A segment's estimated cost is its sampled bit length times its point count: an MSM's work tracks its + * non-zero scalars times their bits, not its span. Reads only. + */ +template SegmentBits sample_segment_bits(std::span scalars) noexcept +{ + SegmentBits bits{}; + const size_t n = scalars.size(); + for (size_t j = 0; j < COST_SEGMENTS && n != 0; ++j) { + const ScalarField& s = scalars[(n * ((2 * j) + 1)) / (2 * COST_SEGMENTS)]; + if (!s.is_zero()) { + bits[j] = static_cast(static_cast(s).get_msb() + 1); + } + } + return bits; +} + +/** + * @brief Cuts members into parts of roughly equal estimated cost, ordered for costliest-first claiming. + * @param members Batch member indices; lengths[k] and bits[k] describe members[k]. + * @details A member whose cost exceeds the batch's fair share (total / pool_width) becomes up to + * min(ceil(cost / fair), length / MIN_SPLIT_PART_POINTS, pool_width) parts, cut at the first segment boundary + * where the running cost reaches the next quantile (i / parts of the cost). Every part of a split member has + * at least MIN_SPLIT_PART_POINTS points and a non-zero estimated cost, so it holds a non-zero scalar. Other + * members are one part. The parts of a member tile [0, length) exactly. Order: cost descending, then + * member, then offset. + */ +inline std::vector plan_cost_split_parts(std::span members, + std::span lengths, + std::span bits, + size_t pool_width) noexcept +{ + auto segment_cost = [&](size_t k, size_t j) noexcept -> uint64_t { + const size_t n = lengths[k]; + return uint64_t{ bits[k][j] } * (cost_segment_begin(n, j + 1) - cost_segment_begin(n, j)); + }; + std::vector member_cost(members.size(), 0); + uint64_t total = 0; + for (size_t k = 0; k < members.size(); ++k) { + for (size_t j = 0; j < COST_SEGMENTS; ++j) { + member_cost[k] += segment_cost(k, j); + } + total += member_cost[k]; + } + const uint64_t fair = std::max(1, total / std::max(1, pool_width)); + + std::vector parts; + parts.reserve(members.size()); + for (size_t k = 0; k < members.size(); ++k) { + const size_t n = lengths[k]; + const uint64_t cost = member_cost[k]; + const size_t max_parts = std::min({ pool_width, n / MIN_SPLIT_PART_POINTS, COST_SEGMENTS }); + const size_t wanted = cost > fair ? static_cast((cost + fair - 1) / fair) : 1; + const size_t num_parts = std::min(wanted, max_parts); + if (num_parts <= 1) { + parts.push_back({ members[k], 0, n, cost }); + continue; + } + size_t begin = 0; + size_t made = 0; + uint64_t cum = 0; + uint64_t cum_at_begin = 0; + for (size_t j = 0; j < COST_SEGMENTS && made + 1 < num_parts; ++j) { + cum += segment_cost(k, j); + const size_t end = cost_segment_begin(n, j + 1); + const uint64_t quantile = ((cost * (made + 1)) + num_parts - 1) / num_parts; + if (cum >= quantile && cum > cum_at_begin && cum < cost && end - begin >= MIN_SPLIT_PART_POINTS && + n - end >= MIN_SPLIT_PART_POINTS) { + parts.push_back({ members[k], begin, end - begin, cum - cum_at_begin }); + begin = end; + cum_at_begin = cum; + ++made; + } + } + parts.push_back({ members[k], begin, n - begin, cost - cum_at_begin }); + } + std::sort(parts.begin(), parts.end(), [](const MsmPart& a, const MsmPart& b) { + if (a.cost != b.cost) { + return a.cost > b.cost; + } + return a.member != b.member ? a.member < b.member : a.offset < b.offset; + }); + return parts; +} + /** * @brief Single-MSM_fast, no-affine-trick Pippenger over window_bits-wide windows. * diff --git a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/small_member_pool_slice_release.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/small_member_pool_slice_release.test.cpp new file mode 100644 index 0000000..5e4d1b3 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/small_member_pool_slice_release.test.cpp @@ -0,0 +1,120 @@ +#include "barretenberg/common/serialize.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/bn254/bn254.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include "scalar_multiplication.hpp" +#include +#include + +using namespace bb; + +namespace { +auto& engine = numeric::get_randomness(); + +class ConcurrencyScope { + size_t prev_; + + public: + explicit ConcurrencyScope(size_t n) + : prev_(get_num_cpus()) + { + set_parallel_for_concurrency(n); + } + ~ConcurrencyScope() { set_parallel_for_concurrency(prev_); } + ConcurrencyScope(const ConcurrencyScope&) = delete; + ConcurrencyScope& operator=(const ConcurrencyScope&) = delete; + ConcurrencyScope(ConcurrencyScope&&) = delete; + ConcurrencyScope& operator=(ConcurrencyScope&&) = delete; +}; + +// Independent random points and scalars: the affine batch addition assumes no two partial sums in a bucket coincide, +// which structured points under repeated scalars can violate. Every draw stays on this thread, since under +// BBERG_DEBUG_LOG the engine is one shared unsynchronised generator; only the point arithmetic runs in parallel. +template +void random_points_and_scalars(size_t n, + std::vector& points, + std::vector& scalars) +{ + using ScalarField = typename Curve::ScalarField; + std::vector discrete_logs(n); + scalars.resize(n); + for (size_t i = 0; i < n; ++i) { + discrete_logs[i] = ScalarField::random_element(&engine); + scalars[i] = ScalarField::random_element(&engine); + } + points.resize(n); + parallel_for_range(n, [&](size_t start, size_t end) { + for (size_t i = start; i < end; ++i) { + points[i] = Curve::Group::one * discrete_logs[i]; + } + }); +} +} // namespace + +template class SmallMemberPoolSliceReleaseTest : public ::testing::Test {}; + +using CurveTypes = ::testing::Types; +TYPED_TEST_SUITE(SmallMemberPoolSliceReleaseTest, CurveTypes); + +// Once the small-member pool's block of per-worker arena slices reaches 64 MiB, each worker releases its slice after +// its last member. Members just below the small-member bound, MSM_MIN_PTS_PER_THREAD * pool width, at a pool wide +// enough to reach that block size, must still match their stand-alone MSMs and get their scalars back. A second batch +// over the same scalars, whose block may land on the released pages, must return the same results. The test checks +// results with the release active on a qualifying block; it does not observe the advice itself, so it would also pass +// if no slice were released. +TYPED_TEST(SmallMemberPoolSliceReleaseTest, SmallMembersMatchStandaloneMsmWhenTheirSlicesAreReleased) +{ +#if defined(__wasm__) || defined(NO_MULTITHREADING) + GTEST_SKIP() << "no concurrent small-member pool without threads"; +#else + using AffineElement = typename TypeParam::AffineElement; + using ScalarField = typename TypeParam::ScalarField; + + constexpr size_t RELEASE_FLOOR = size_t{ 64 } << 20; + size_t pool_width = 0; + size_t n = 0; + for (const size_t width : { size_t{ 64 }, size_t{ 128 } }) { + const size_t n_try = (scalar_multiplication::MSM_MIN_PTS_PER_THREAD * width) - 1; + // The pool sizes its slices by the GLV variant the batch uses; the smaller one bounds both. + const size_t with_glv = scalar_multiplication::compute_arena_bytes_for_msm(n_try, true, false, 1); + const size_t without_glv = + scalar_multiplication::compute_arena_bytes_for_msm(n_try, false, false, 1); + if (std::min(with_glv, without_glv) * width >= RELEASE_FLOOR) { + pool_width = width; + n = n_try; + break; + } + } + ASSERT_GT(pool_width, 0U) << "no pool width reaches the release floor"; + + std::vector points; + std::vector pool; + random_points_and_scalars(n, points, pool); + ConcurrencyScope concurrency(pool_width); + const size_t num_members = pool_width; + std::vector> scalars(num_members, std::vector(n)); + std::vector expected(num_members); + for (size_t k = 0; k < num_members; ++k) { + for (size_t i = 0; i < n; ++i) { + scalars[k][i] = pool[((k * 29) + i) % n]; + } + expected[k] = scalar_multiplication::MSM::msm( + points, PolynomialSpan(0, std::span(scalars[k]))); + } + const auto original = scalars; + for (size_t call = 0; call < 2; ++call) { + std::vector> spans; + for (auto& member : scalars) { + spans.emplace_back(0, std::span(member)); + } + const auto result = scalar_multiplication::MSM_fast::batch_multi_scalar_mul( + points, spans, /*handle_edge_cases=*/false); + for (size_t k = 0; k < num_members; ++k) { + EXPECT_EQ(to_buffer(result[k]), to_buffer(expected[k])) << "call " << call << ", MSM " << k; + EXPECT_EQ(scalars[k], original[k]) << "call " << call << ", scalars of MSM " << k << " not restored"; + } + } +#endif +} 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/flavor_concepts.hpp b/barretenberg/cpp/src/barretenberg/flavor/flavor_concepts.hpp index c8a1af5..3c724a5 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/flavor_concepts.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/flavor_concepts.hpp @@ -2,8 +2,11 @@ // Establish concepts for testing flavor attributes #include "barretenberg/common/type_traits.hpp" +#include "barretenberg/common/zip_view.hpp" #include "barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp" #include +#include +#include #include #include namespace bb { @@ -84,11 +87,29 @@ template concept IsGrumpkinFlavor = IsAnyOf concept UsesCommittedSumcheck = IsGrumpkinFlavor; +template struct SpanValueType { using type = void; }; +template struct SpanValueType> { using type = std::remove_cv_t; }; + template inline std::string flavor_get_label(Container&& container, const Element& element) { - for (auto [label, data] : zip_view(container.get_labels(), container.get_all())) { - if (&data == &element) { - return label; + using All = std::remove_cvref_t; + if constexpr (std::is_same_v::type, std::remove_cv_t>) { + // Entities held in one span: an element's position is its address offset, an O(1) lookup. The zip_view keeps + // the check that there is one label per entity. + const auto labels = container.get_labels(); + const auto all = container.get_all(); + [[maybe_unused]] const zip_view one_label_per_entity(labels, all); + const auto first = reinterpret_cast(all.data()); + const auto address = reinterpret_cast(&element); + if (address >= first && (address - first) % sizeof(Element) == 0 && + (address - first) / sizeof(Element) < all.size()) { + return labels[(address - first) / sizeof(Element)]; + } + } else { + for (auto [label, data] : zip_view(container.get_labels(), container.get_all())) { + if (&data == &element) { + return label; + } } } return "(unknown label)"; diff --git a/barretenberg/cpp/src/barretenberg/flavor/flavor_get_label.test.cpp b/barretenberg/cpp/src/barretenberg/flavor/flavor_get_label.test.cpp new file mode 100644 index 0000000..4920270 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/flavor/flavor_get_label.test.cpp @@ -0,0 +1,67 @@ +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/ref_vector.hpp" +#include "barretenberg/flavor/flavor_concepts.hpp" +#include +#include +#include +#include +#include +#include + +using namespace bb; + +namespace { +// Entities held in one array, labelled in the same order, as the AVM flavor holds them. +struct SpanEntities { + std::array entities{}; + std::array labels{ "a", "b", "c", "d" }; + std::span get_all() { return entities; } + std::span get_labels() const { return labels; } +}; + +// A view of the same entities that starts at the second one, as the AVM proving key exposes its unshifted entities. +struct SpanTail { + SpanEntities& base; + std::span get_all() { return std::span(base.entities).subspan(1); } + std::span get_labels() const { return std::span(base.labels).subspan(1); } +}; + +// Entities gathered by reference, as the other flavors expose them. +struct RefEntities { + int x = 0; + int y = 0; + std::vector get_labels() const { return { "x", "y" }; } + RefVector get_all() { return { x, y }; } +}; + +// One label short of the entities. +struct MislabelledEntities { + std::array entities{}; + std::array labels{ "a" }; + std::span get_all() { return entities; } + std::span get_labels() const { return labels; } +}; +} // namespace + +TEST(FlavorGetLabel, FindsEachEntity) +{ + SpanEntities all; + for (size_t i = 0; i < all.entities.size(); ++i) { + EXPECT_EQ(flavor_get_label(all, all.entities[i]), all.labels[i]); + } + SpanTail tail{ all }; + EXPECT_EQ(flavor_get_label(tail, all.entities[2]), "c"); + EXPECT_EQ(flavor_get_label(tail, all.entities[0]), "(unknown label)"); + const int outside = 0; + EXPECT_EQ(flavor_get_label(all, outside), "(unknown label)"); + + RefEntities refs; + EXPECT_EQ(flavor_get_label(refs, refs.y), "y"); + EXPECT_EQ(flavor_get_label(refs, outside), "(unknown label)"); +} + +TEST(FlavorGetLabel, RequiresOneLabelPerEntity) +{ + MislabelledEntities entities; + EXPECT_THROW_OR_ABORT(flavor_get_label(entities, entities.entities[0]), ".*Assertion failed.*"); +} 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/composer/composer_lib.hpp b/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp index 616ff88..9a4fb46 100644 --- a/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/composer/composer_lib.hpp @@ -52,11 +52,20 @@ void construct_lookup_read_counts(typename Flavor::Polynomial& read_counts, { // loop over all tables used in the circuit; each table records the row read by every lookup gate made on it size_t table_offset = circuit.blocks.lookup.trace_offset(); + std::vector counts; for (auto& table : circuit.get_lookup_tables()) { + // count the reads of each row as integers, then add each non-zero count to the polynomial once + counts.assign(table.size(), 0); for (const uint32_t index_in_table : table.lookup_gate_rows) { - // increment the read count at the corresponding index in the full polynomial + counts.at(index_in_table)++; + } + for (size_t index_in_table = 0; index_in_table < counts.size(); ++index_in_table) { + if (counts[index_in_table] == 0) { + continue; + } + // add the read count at the corresponding index in the full polynomial size_t index_in_poly = table_offset + index_in_table; - read_counts.at(index_in_poly)++; + read_counts.at(index_in_poly) += counts[index_in_table]; read_tags.at(index_in_poly) = 1; // tag is 1 if entry has been read 1 or more times } table_offset += table.size(); // set the offset of the next table within the polynomials 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..08e945d 100644 --- a/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/logderivative_library.hpp @@ -14,7 +14,10 @@ #include "barretenberg/common/thread.hpp" #include "barretenberg/common/tuple.hpp" +#include +#include #include +#include #include namespace bb { @@ -30,8 +33,17 @@ namespace bb { * If a given row does not contain a lookup gate, the inverse polynomial is set to zero. * */ -template -void compute_logderivative_inverse(Polynomials& polynomials, auto& relation_parameters, const size_t start_index = 0) +template +void compute_logderivative_inverse(Polynomials& polynomials, + auto& relation_parameters, + const size_t start_index = 0, + const size_t end_index = std::numeric_limits::max(), + const size_t lookup_zero_from = std::numeric_limits::max(), + const size_t table_zero_from = std::numeric_limits::max()) { BB_BENCH_NAME("compute_logderivative_inverse"); using Accumulator = typename Relation::ValueAccumulator0; @@ -41,8 +53,19 @@ 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; + static_assert(!UseVirtualZeroTails || + (NUM_LOOKUP_TERMS == 1 && NUM_TABLE_TERMS == 1 && std::is_same_v)); + struct EmptyTailCache {}; + struct ZeroTailCache { + std::optional lookup; + std::optional table; + }; const auto compute_inverses = [&](size_t start, size_t end) { + // Opt-in callers prove that all inputs to a basic term are virtual raw zero beyond its bound. + // Evaluate the original term once there, preserving even its raw representative. + [[maybe_unused]] std::conditional_t zero_terms; for (size_t i = start; i < end; ++i) { const size_t row_idx = i + offset; // TODO(https://github.com/AztecProtocol/barretenberg/issues/940): avoid get_row if possible. @@ -53,13 +76,33 @@ void compute_logderivative_inverse(Polynomials& polynomials, auto& relation_para } FF denominator = 1; bb::constexpr_for<0, NUM_LOOKUP_TERMS, 1>([&] { - auto denominator_term = - Relation::template compute_lookup_term(row, relation_parameters); + const auto denominator_term = [&]() { + if constexpr (UseVirtualZeroTails) { + if (row_idx >= lookup_zero_from) { + if (!zero_terms.lookup.has_value()) { + zero_terms.lookup = Relation::template compute_lookup_term( + row, relation_parameters); + } + return *zero_terms.lookup; + } + } + return Relation::template compute_lookup_term(row, relation_parameters); + }(); denominator *= denominator_term; }); bb::constexpr_for<0, NUM_TABLE_TERMS, 1>([&] { - auto denominator_term = - Relation::template compute_table_term(row, relation_parameters); + const auto denominator_term = [&]() { + if constexpr (UseVirtualZeroTails) { + if (row_idx >= table_zero_from) { + if (!zero_terms.table.has_value()) { + zero_terms.table = Relation::template compute_table_term( + row, relation_parameters); + } + return *zero_terms.table; + } + } + return Relation::template compute_table_term(row, relation_parameters); + }(); denominator *= denominator_term; }); inverse_polynomial.at(row_idx) = denominator; @@ -133,11 +176,16 @@ void _accumulate_logderivative_subrelation_contributions(ContainerOverSubrelatio // (lookup_term_1 * .. * lookup_term_(i-1)) * lookup_inverse * (lookup_term_(i+1) * .. * table_term_m) // Collect all the terms in a single vector, first the lookup terms, then the table terms - bb::constexpr_for<0, NUM_LOOKUP_TERMS, 1>( - [&]() { lookup_terms[i] = Relation::template compute_lookup_term(in, params); }); - bb::constexpr_for<0, NUM_TABLE_TERMS, 1>([&]() { - lookup_terms[i + NUM_LOOKUP_TERMS] = Relation::template compute_table_term(in, params); - }); + if constexpr (NUM_LOOKUP_TERMS == 1 && NUM_TABLE_TERMS == 1 && + requires { in.template compress_lookup_pair(params); }) { + lookup_terms = in.template compress_lookup_pair(params); + } else { + bb::constexpr_for<0, NUM_LOOKUP_TERMS, 1>( + [&]() { lookup_terms[i] = Relation::template compute_lookup_term(in, params); }); + bb::constexpr_for<0, NUM_TABLE_TERMS, 1>([&]() { + lookup_terms[i + NUM_LOOKUP_TERMS] = Relation::template compute_table_term(in, params); + }); + } // 1) Construct the successive products bb::constexpr_for<0, NUM_TOTAL_TERMS, 1>([&]() { denominator_accumulator[i] = lookup_terms[i]; }); @@ -151,6 +199,18 @@ void _accumulate_logderivative_subrelation_contributions(ContainerOverSubrelatio std::get<0>(accumulator) += (denominator_accumulator[NUM_TOTAL_TERMS - 1] * lookup_inverses - inverse_exists) * scaling_factor; +#ifndef __wasm__ + // The inverse check above remains mandatory, even when both accumulation + // contributions vanish. Only the exact AVM linear-edge adapter provides this proof. + if constexpr (!IsPermutation && NUM_LOOKUP_TERMS == 1 && NUM_TABLE_TERMS == 1 && requires { + in.lookup_accumulation_is_zero(std::type_identity{}); + }) { + if (in.lookup_accumulation_is_zero(std::type_identity{})) { + return; + } + } +#endif + // 3) Iteratively compute the single inverses for (size_t i = NUM_TOTAL_TERMS - 1; i > 0; --i) { // Take the cumulative product up to the previous index and multiply by the current inverse accumulator 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/honk/proof_system/zero_tuple_tail.test.cpp b/barretenberg/cpp/src/barretenberg/honk/proof_system/zero_tuple_tail.test.cpp new file mode 100644 index 0000000..ff06442 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/honk/proof_system/zero_tuple_tail.test.cpp @@ -0,0 +1,182 @@ +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/honk/proof_system/logderivative_library.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include +#include +#include +#include +#include + +namespace { +using FF = bb::fr; +struct ZeroTailRow { + FF selector; + FF a; + FF b; +}; +struct ZeroTailParams { + FF beta = FF(7); + FF gamma = FF(13); + mutable size_t lookup_calls = 0; + mutable size_t table_calls = 0; +}; +struct ZeroTailPolynomials { + std::vector rows; + bb::Polynomial inverse; + ZeroTailPolynomials(size_t n, size_t source_end, size_t destination_end, 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), + i < source_end ? FF(i + 1) : FF(0), + i < destination_end ? FF(3 * i + 2) : FF(0) }; + } + } + ZeroTailRow get_row(size_t i) const { return rows[i]; } +}; +struct ZeroTailRelation { + using ValueAccumulator0 = FF; + static constexpr size_t NUM_LOOKUP_TERMS = 1; + static constexpr size_t NUM_TABLE_TERMS = 1; + static auto& get_inverse_polynomial(ZeroTailPolynomials& p) { return p.inverse; } + static bool operation_exists_at_row(const ZeroTailRow& r) { return r.selector != FF(0); } + template static FF compute_lookup_term(const ZeroTailRow& r, const ZeroTailParams& p) + { + ++p.lookup_calls; + return r.a + p.beta; // Deliberately not gamma: reuse the original result, never substitute a formula. + } + template static FF compute_table_term(const ZeroTailRow& r, const ZeroTailParams& p) + { + ++p.table_calls; + return r.b + p.gamma; + } +}; +} // namespace + +TEST(AvmZeroTupleTail, PreservesRawInversesAtIdenticalChunkBoundaries) +{ + for (size_t n : std::array{ 0, 1, 7, 65, 257 }) { + for (size_t source_end : std::array{ 0, 3, n + 5 }) { + for (size_t destination_end : std::array{ 0, 17, n + 5 }) { + for (size_t offset : std::array{ 0, 1 }) { + ZeroTailPolynomials original(n, source_end, destination_end, offset); + ZeroTailPolynomials cached(n, source_end, destination_end, offset); + ZeroTailParams p, q; + for (size_t start = 0; start < n + offset;) { + const size_t end = std::min(start + 7, n + offset); + bb::compute_logderivative_inverse(original, p, start, end); + bb::compute_logderivative_inverse( + cached, q, start, end, source_end, destination_end); + start = end; + } + for (size_t i = offset; i < n + offset; ++i) { + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(cached.inverse[i].data[limb], original.inverse[i].data[limb]); + } + } + EXPECT_LE(q.lookup_calls, p.lookup_calls); + EXPECT_LE(q.table_calls, p.table_calls); + } + } + } + } +} + +TEST(AvmZeroTupleTail, InitializesOnlyOnActiveSuffixRows) +{ + ZeroTailPolynomials p(65, 3, 17); + ZeroTailParams params; + bb::compute_logderivative_inverse(p, params, 0, 65, 3, 17); + EXPECT_EQ(params.lookup_calls, 3U); // Active prefix rows1,2 then the first active zero tuple at3. + EXPECT_EQ(params.table_calls, 14U); // Thirteen active prefix rows before17, then one zero tuple. + + ZeroTailPolynomials inactive(65, 3, 17); + for (size_t i = 3; i < 65; ++i) { + inactive.rows[i].selector = FF(0); + } + ZeroTailParams inactive_params; + bb::compute_logderivative_inverse( + inactive, inactive_params, 0, 65, 3, 17); + EXPECT_EQ(inactive_params.lookup_calls, 2U); + EXPECT_EQ(inactive_params.table_calls, 2U); +} + +TEST(AvmZeroTupleTail, DefaultModeIgnoresOptionalBounds) +{ + ZeroTailPolynomials p(31, 31, 31), q(31, 31, 31); + ZeroTailParams a, b; + bb::compute_logderivative_inverse(p, a); + bb::compute_logderivative_inverse(q, b, 0, 31, 0, 0); + for (size_t i = 0; i < 31; ++i) { + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(p.inverse[i].data[limb], q.inverse[i].data[limb]); + } + } + EXPECT_EQ(a.lookup_calls, b.lookup_calls); + EXPECT_EQ(a.table_calls, b.table_calls); +} + +namespace { +struct ShiftedZeroTailPolynomials { + bb::Polynomial source; + bb::Polynomial shifted_source; + bb::Polynomial destination; + bb::Polynomial inverse; + ShiftedZeroTailPolynomials() + : source(6, 32, 1) + , destination(3, 32) + , inverse(16, 32) + { + for (size_t i = 1; i < 7; ++i) { + source.at(i) = FF(i + 2); + } + for (size_t i = 0; i < 3; ++i) { + destination.at(i) = FF(2 * i + 1); + } + shifted_source = source.shifted(); + } + ZeroTailRow get_row(size_t i) const { return { FF(1), shifted_source[i], destination[i] }; } +}; +struct ShiftedZeroTailRelation : ZeroTailRelation { + static auto& get_inverse_polynomial(ShiftedZeroTailPolynomials& p) { return p.inverse; } +}; +} // namespace + +TEST(AvmZeroTupleTail, UsesActualEndOfShiftedTupleViews) +{ + ShiftedZeroTailPolynomials original, cached; + ASSERT_EQ(original.source.start_index(), 1U); + ASSERT_EQ(original.source.end_index(), 7U); + ASSERT_EQ(original.shifted_source.start_index(), 0U); + ASSERT_EQ(original.shifted_source.end_index(), 6U); + ZeroTailParams p, q; + for (const auto& range : std::array, 2>{ { { 0, 5 }, { 5, 16 } } }) { + bb::compute_logderivative_inverse(original, p, range.first, range.second); + bb::compute_logderivative_inverse( + cached, q, range.first, range.second, cached.shifted_source.end_index(), cached.destination.end_index()); + } + for (size_t i = 0; i < 16; ++i) { + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(cached.inverse[i].data[limb], original.inverse[i].data[limb]); + } + } + EXPECT_LT(q.lookup_calls, p.lookup_calls); + EXPECT_LT(q.table_calls, p.table_calls); +} + +TEST(AvmZeroTupleTail, CachesZeroTermsWithoutChangingZeroDenominators) +{ + ZeroTailPolynomials original(31, 3, 5), cached(31, 3, 5); + ZeroTailParams p, q; + p.beta = p.gamma = q.beta = q.gamma = FF(0); + bb::compute_logderivative_inverse(original, p); + bb::compute_logderivative_inverse(cached, q, 0, 31, 3, 5); + for (size_t i = 0; i < 31; ++i) { + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(cached.inverse[i].data[limb], original.inverse[i].data[limb]); + } + } + EXPECT_LT(q.lookup_calls, p.lookup_calls); + EXPECT_LT(q.table_calls, p.table_calls); +} 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/backing_memory.cpp b/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.cpp index 5b468eb..c5fd843 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.cpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.cpp @@ -11,6 +11,14 @@ #include #include #include +#if !defined(__wasm__) && !defined(_WIN32) && !defined(NO_MULTITHREADING) && !defined(BB_NO_EXCEPTIONS) +#include "barretenberg/common/thread.hpp" +#include +#include +#include +#include +#define BB_POLYNOMIAL_MEMORY_RELEASE 1 +#endif // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool slow_low_memory = @@ -97,3 +105,105 @@ size_t storage_budget = parse_storage_budget(); std::atomic current_storage_usage{ 0 }; #endif // !defined(__wasm__) || defined(ENABLE_WASM_BENCH) + +namespace bb { +#ifdef BB_POLYNOMIAL_MEMORY_RELEASE +namespace { +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +thread_local PolynomialMemoryRelease* active_release = nullptr; + +// Splits the whole pages of all ranges evenly over the tasks; each task walks the ranges its share overlaps. +void release_in_parallel(const std::vector>& ranges, size_t page) +{ + constexpr size_t BYTES_PER_TASK = size_t{ 16 } << 20; + constexpr size_t MAX_TASKS = 16; + std::vector first_page(ranges.size()); + size_t total_pages = 0; + for (size_t r = 0; r < ranges.size(); ++r) { + first_page[r] = total_pages; + total_pages += ranges[r].second; + } + const size_t num_tasks = std::min((total_pages * page) / BYTES_PER_TASK, MAX_TASKS); + if (num_tasks < 2) { + return; + } + parallel_for(num_tasks, [&](size_t t) { + size_t lo = (total_pages * t) / num_tasks; + const size_t hi = (total_pages * (t + 1)) / num_tasks; + auto r = + static_cast(std::upper_bound(first_page.begin(), first_page.end(), lo) - first_page.begin()) - 1; + while (lo < hi) { + const size_t offset = lo - first_page[r]; + const size_t count = std::min(hi - lo, ranges[r].second - offset); + // NOLINTNEXTLINE(performance-no-int-to-ptr) + static_cast( + madvise(reinterpret_cast(ranges[r].first + (offset * page)), count * page, MADV_DONTNEED)); + lo += count; + ++r; + } + }); +} +} // namespace +#endif + +bool PolynomialMemoryRelease::defer_free([[maybe_unused]] void* ptr, + [[maybe_unused]] size_t bytes, + [[maybe_unused]] void (*free_block)(void*)) noexcept +{ +#ifdef BB_POLYNOMIAL_MEMORY_RELEASE + PolynomialMemoryRelease* scope = active_release; + if (scope == nullptr) { + return false; + } + try { + scope->blocks_.push_back({ ptr, bytes, free_block }); + } catch (...) { + return false; + } + return true; +#else + return false; +#endif +} + +void PolynomialMemoryRelease::activate() +{ +#ifdef BB_POLYNOMIAL_MEMORY_RELEASE + if (!active_) { + previous_ = active_release; + active_release = this; + active_ = true; + } +#endif +} + +PolynomialMemoryRelease::~PolynomialMemoryRelease() +{ +#ifdef BB_POLYNOMIAL_MEMORY_RELEASE + if (!active_) { + return; + } + active_release = previous_; + // Only whole pages strictly inside each block, so the allocator's chunk headers next to it stay intact. + try { + const auto page = static_cast(sysconf(_SC_PAGESIZE)); + std::vector> ranges; + ranges.reserve(blocks_.size()); + for (const auto& block : blocks_) { + const auto start = reinterpret_cast(block.ptr); + const uintptr_t begin = (start + page - 1) & ~(page - 1); + const uintptr_t end = (start + block.bytes) & ~(page - 1); + if (end > begin) { + ranges.emplace_back(begin, (end - begin) / page); + } + } + release_in_parallel(ranges, page); + } catch (...) { + // Without the release the blocks are simply freed below. + } + for (const auto& block : blocks_) { + block.free_block(block.ptr); + } +#endif +} +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp b/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp index 36f8276..38cfd34 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #if !defined(__wasm__) && !defined(_WIN32) #include #endif @@ -29,6 +30,44 @@ extern std::atomic current_storage_usage; // Parse storage size string (e.g., "500m", "2g", "1024k") size_t parse_size_string(const std::string& size_str); +namespace bb { +/** + * @brief Releases the memory of polynomials freed together from several threads at once. + * + * @details A block freed into the allocator's arenas stays resident, and the kernel later frees its pages one at a + * time on a single thread, when an arena is trimmed or when the process exits; a block the allocator mapped on its own + * is unmapped page by page on the thread that frees it. After activate(), every polynomial backing block whose last + * owner is dropped on this thread is collected instead of freed. When the scope ends, if the collected blocks hold at + * least 32 MiB, the whole pages inside them are handed back with madvise(MADV_DONTNEED) from up to 16 parallel_for + * tasks, and then the blocks are freed as before. Only blocks that are already being freed are touched. The scope must + * end on the thread that activated it. Builds without threads or exceptions (WASM) free at once, as before. + */ +class PolynomialMemoryRelease { + public: + PolynomialMemoryRelease() = default; + PolynomialMemoryRelease(const PolynomialMemoryRelease&) = delete; + PolynomialMemoryRelease& operator=(const PolynomialMemoryRelease&) = delete; + PolynomialMemoryRelease(PolynomialMemoryRelease&&) = delete; + PolynomialMemoryRelease& operator=(PolynomialMemoryRelease&&) = delete; + ~PolynomialMemoryRelease(); + + void activate(); + + // Takes the block if a scope is active on this thread; otherwise the caller frees it. + static bool defer_free(void* ptr, size_t bytes, void (*free_block)(void*)) noexcept; + + private: + struct Block { + void* ptr; + size_t bytes; + void (*free_block)(void*); + }; + std::vector blocks_; + [[maybe_unused]] PolynomialMemoryRelease* previous_ = nullptr; + [[maybe_unused]] bool active_ = false; +}; +} // namespace bb + template struct BackingMemory { // Common raw data pointer used by all storage types Fr* raw_data = nullptr; @@ -118,7 +157,11 @@ template struct BackingMemory { return; } Fr* ptr = new Fr[size]; - memory.aligned_memory = std::shared_ptr(ptr, [](Fr* p) { delete[] p; }); + memory.aligned_memory = std::shared_ptr(ptr, [bytes = size * sizeof(Fr)](Fr* p) { + if (!bb::PolynomialMemoryRelease::defer_free(p, bytes, [](void* q) { delete[] static_cast(q); })) { + delete[] p; + } + }); memory.raw_data = ptr; } 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/gate_separator_prefix.test.cpp b/barretenberg/cpp/src/barretenberg/polynomials/gate_separator_prefix.test.cpp new file mode 100644 index 0000000..a0f9ad2 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/polynomials/gate_separator_prefix.test.cpp @@ -0,0 +1,52 @@ +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/numeric/bitop/get_msb.hpp" +#include "gate_separator.hpp" + +#include +#include +#include + +using namespace bb; + +// A table of 2^k entries, k = ceil(log2 E_0), returns the full table's value at every index the sumcheck rounds read. +// Round r reads the even edges below E_r = min(2^(d-r), W_r rounded up to even), where W_r is the largest polynomial +// end index in that round and folding takes W_{r+1} = ceil(W_r / 2). +TEST(GateSeparatorPolynomial, PrefixTableMatchesFullTableOnEveryRoundRead) +{ + constexpr size_t d = 10; + std::vector betas(d); + for (auto& beta : betas) { + beta = fr::random_element(); + } + const GateSeparatorPolynomial full_table(betas, d); + + constexpr std::array largest_ends{ 0, 1, 2, 5, 6, 64, 65, 66, 129, 1000, 1023, 1024 }; + for (const size_t largest_end : largest_ends) { + const size_t initial_rows = largest_end + (largest_end % 2); + const size_t log_size = initial_rows <= 1 ? 0 : numeric::get_msb(initial_rows - 1) + 1; + GateSeparatorPolynomial full(betas, d); + GateSeparatorPolynomial prefix(betas, log_size); + ASSERT_EQ(prefix.beta_products.size(), size_t{ 1 } << log_size); + + size_t end = largest_end; + for (size_t round = 0; round < d; ++round) { + const size_t rows = std::min(size_t{ 1 } << (d - round), end + (end % 2)); + ASSERT_TRUE(rows == 0 || ((rows / 2) - 1) * prefix.periodicity < prefix.beta_products.size()) + << "largest end " << largest_end << ", round " << round; + for (size_t idx = 0; idx < rows; idx += 2) { + ASSERT_EQ(prefix[idx], full[idx]) << "largest end " << largest_end << ", round " << round; + } + const fr challenge = fr::random_element(); + full.partially_evaluate(challenge); + prefix.partially_evaluate(challenge); + ASSERT_EQ(prefix.partial_evaluation_result, full.partial_evaluation_result); + end = (end + 1) / 2; + } + } + + // The prefix is the full table's first entries, so no index below it depends on the betas it leaves out. + const GateSeparatorPolynomial prefix(betas, 4); + for (size_t i = 0; i < prefix.beta_products.size(); ++i) { + EXPECT_EQ(prefix.beta_products.at(i), full_table.beta_products.at(i)); + } +} diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.cpp index 390fd28..bf38b74 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 { @@ -74,6 +77,10 @@ template Polynomial::Polynomial(size_t size, size_t virtual_si { BB_BENCH_NAME("Polynomial::Polynomial(size_t, size_t, size_t)"); allocate_backing_memory(size, virtual_size, start_index); + // Nothing to zero, and the dispatch below would still wake every pool thread. + if (size == 0) { + return; + } parallel_for([&](const ThreadChunk& chunk) { auto range = chunk.range(size); @@ -205,6 +212,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 +275,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/polynomial_empty.test.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_empty.test.cpp new file mode 100644 index 0000000..8ad4208 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_empty.test.cpp @@ -0,0 +1,35 @@ +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include +#include + +namespace bb { +namespace { + +TEST(PolynomialEmpty, ZeroingConstructorOfAnEmptyPolynomialStartsNoWorkers) +{ + size_t workers_after = 1; + size_t size = 1; + size_t virtual_size = 0; + // A fresh thread has no workers yet, so constructing the polynomial must not be what starts them. + std::thread caller([&] { + const Polynomial empty(0, 1024); + size = empty.size(); + virtual_size = empty.virtual_size(); + workers_after = parallel_for_num_workers(); + }); + caller.join(); + + EXPECT_EQ(size, 0U); + EXPECT_EQ(virtual_size, 1024U); +#ifdef __wasm__ + // On wasm the pool is process-wide, so an earlier test in this binary may already have started it. + (void)workers_after; +#else + EXPECT_EQ(workers_after, 0U); +#endif +} + +} // namespace +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial_memory_release.test.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_memory_release.test.cpp new file mode 100644 index 0000000..f4bcd9a --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_memory_release.test.cpp @@ -0,0 +1,140 @@ +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/polynomials/backing_memory.hpp" +#include "barretenberg/polynomials/polynomial.hpp" +#include +#include +#include + +// The condition under which backing_memory.cpp builds the release. +#if !defined(__wasm__) && !defined(_WIN32) && !defined(NO_MULTITHREADING) && !defined(BB_NO_EXCEPTIONS) +#define RELEASE_IS_BUILT 1 +#include +#include +#include +#include +#include +#include +#include +#endif + +using namespace bb; + +namespace { +using Fr = bb::fr; +constexpr size_t SIZE = size_t{ 1 } << 21; // 64 MiB per polynomial, enough for the release to run in parallel + +Polynomial make_polynomial(uint64_t seed) +{ + Polynomial poly(SIZE); + parallel_for_range(SIZE, [&](size_t start, size_t end) { + for (size_t i = start; i < end; ++i) { + poly.at(i) = Fr(seed + i); + } + }); + return poly; +} + +// Polynomials dropped inside an active scope are freed when it ends; a block that still has an owner outside the scope +// is never released, so its contents survive. +void expect_shared_block_survives(const std::string& label) +{ + std::optional> kept; + { + PolynomialMemoryRelease release; + auto dropped = make_polynomial(1); + auto shared = make_polynomial(2); + kept = shared.share(); + auto dropped_after = make_polynomial(3); + release.activate(); + } + ASSERT_TRUE(kept.has_value()); + size_t mismatches = 0; + for (size_t i = 0; i < SIZE; ++i) { + mismatches += static_cast(kept->get(i) != Fr(2 + i)); + } + EXPECT_EQ(mismatches, 0U) << label; +} + +#ifdef RELEASE_IS_BUILT +constexpr size_t BLOCK_BYTES = size_t{ 64 } << 20; + +struct FreedBlock { + size_t frees = 0; + size_t nonzero_interior_bytes = 0; +}; +// The scope frees its blocks on its own thread. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +thread_local FreedBlock freed_block; + +void inspect_and_free(void* ptr) +{ + auto* bytes = static_cast(ptr); + const auto page = static_cast(sysconf(_SC_PAGESIZE)); + const auto start = reinterpret_cast(ptr); + const uintptr_t begin = ((start + page - 1) & ~(page - 1)) - start; + const uintptr_t end = ((start + BLOCK_BYTES) & ~(page - 1)) - start; + freed_block.nonzero_interior_bytes += + static_cast(std::count_if(bytes + begin, bytes + end, [](uint8_t b) { return b != 0; })); + ++freed_block.frees; + delete[] bytes; +} + +// A collected block is freed exactly once, when the scope ends, after every whole page inside it has been released. +void expect_collected_block_released(const std::string& label) +{ + auto* block = new uint8_t[BLOCK_BYTES]; + std::memset(block, 0xAB, BLOCK_BYTES); + freed_block = {}; + { + PolynomialMemoryRelease release; + release.activate(); + if (!PolynomialMemoryRelease::defer_free(block, BLOCK_BYTES, inspect_and_free)) { + delete[] block; + FAIL() << label << ": the active scope did not collect the block"; + } + EXPECT_EQ(freed_block.frees, 0U) << label; + } + EXPECT_EQ(freed_block.frees, 1U) << label; +#ifdef __linux__ + // Linux discards private anonymous pages on MADV_DONTNEED, so released pages read back as zero; Darwin keeps them. + EXPECT_EQ(freed_block.nonzero_interior_bytes, 0U) << label; +#endif +} + +// Number of distinct threads that run iterations of a parallel_for on the calling thread's pool. +size_t threads_in_pool() +{ + constexpr size_t ITERATIONS = 48; + std::mutex mutex; + std::set ids; + parallel_for(ITERATIONS, [&](size_t) { + const std::lock_guard lock(mutex); + ids.insert(std::this_thread::get_id()); + }); + return ids.size(); +} +#endif +} // namespace + +TEST(PolynomialMemoryRelease, ReleasesCollectedBlocksAndKeepsSharedOnes) +{ +#ifndef RELEASE_IS_BUILT + expect_shared_block_survives("release not built"); +#else + // The concurrency setting and the parallel_for pool are both per thread, and the pool is sized by the thread's + // first parallel_for, so each setting is applied on a fresh thread before anything else runs there. The outcomes + // prove the release: one free per collected block, its whole interior pages zero on Linux, a shared block intact. + // How many pool threads join in depends on scheduling, so only the upper bound is checked. + for (const size_t concurrency : { size_t{ 16 }, size_t{ 3 }, size_t{ 1 } }) { + std::thread([concurrency] { + set_parallel_for_concurrency(concurrency); + const std::string label = "concurrency " + std::to_string(concurrency); + EXPECT_EQ(get_num_cpus(), concurrency) << label; + EXPECT_LE(threads_in_pool(), concurrency) << label; + expect_shared_block_survives(label); + expect_collected_block_released(label); + }).join(); + } +#endif +} 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/generic_lookup/generic_lookup_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp index 392671e..e276697 100644 --- a/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/generic_lookup/generic_lookup_relation.hpp @@ -7,6 +7,7 @@ #pragma once #include #include +#include #include "barretenberg/common/constexpr_utils.hpp" #include "barretenberg/honk/proof_system/logderivative_library.hpp" @@ -246,6 +247,13 @@ template class GenericLookupRelationImpl { static constexpr size_t NUM_LOOKUP_TERMS = Settings::NUM_LOOKUP_TERMS; static constexpr size_t NUM_TABLE_TERMS = Settings::NUM_TABLE_TERMS; + // Only ordinary single read/write terms are linear tuple compressions. + using LinearLookupSettings = std::conditional_t; + /** * When performing a basic lookup, we batch columns for efficiency. This constant represents the number of columns diff --git a/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp index 7dd9ee1..043e296 100644 --- a/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/generic_permutation/generic_permutation_relation.hpp @@ -69,6 +69,7 @@ template class GenericPermutationRelationImpl public: using FF = FF_; using PolynomialStructure = PermutationPolynomialStructure; + using LinearLookupSettings = Settings; // The term counts should stay set to 1 unless we want to permute several columns at once as accumulated // sets (not as tuples). 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/srs/factories/get_bn254_crs.cpp b/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.cpp index a5af9ea..3f4ab8e 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.cpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.cpp @@ -1,6 +1,7 @@ #include "get_bn254_crs.hpp" #include "barretenberg/api/file_io.hpp" #include "barretenberg/common/flock.hpp" +#include "barretenberg/common/release_pages.hpp" #include "barretenberg/common/serialize.hpp" #include "barretenberg/common/thread.hpp" #include "barretenberg/crypto/sha256/sha256.hpp" @@ -9,8 +10,19 @@ #include "bn254_crs_data.hpp" #include "bn254_g1_chunk_hashes.hpp" #include "http_download.hpp" +#include "pread.hpp" #include +#include +#include +#include +#include +#include #include +#include +#if !defined(__wasm__) && !defined(_WIN32) +#include +#include +#endif namespace { // Primary CRS URL (Cloudflare R2) @@ -35,21 +47,90 @@ void write_uncompressed_g1_points(const std::vector& poi bb::write_file(path, buf); } +#if !defined(__wasm__) && !defined(_WIN32) +/** + * @brief Read `num_points` uncompressed G1 points (64 bytes each) from a file into `dst`, which may be uninitialised. + * + * @details Each thread preads its own contiguous slice of the file into a small buffer and deserializes straight into + * `dst`, so the file is never staged whole in a separate buffer, the reads proceed in parallel, and each output page is + * first touched by the thread that fills it. Every point is parsed by the same `from_buffer` from the same bytes. + */ +void read_uncompressed_g1_points_into(const std::filesystem::path& path, bb::g1::affine_element* dst, size_t num_points) +{ + const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + throw_or_abort("Unable to open " + path.string() + ": " + strerror(errno)); + } + // Closed on every exit, including an exception from starting the workers. + const auto close_fd = [](const int* owned) { ::close(*owned); }; + const std::unique_ptr fd_owner(&fd, close_fd); + std::atomic read_failed{ false }; + std::exception_ptr parse_error; + std::mutex parse_error_mutex; + bb::parallel_for([&](bb::ThreadChunk chunk) { +#ifndef BB_NO_EXCEPTIONS + try { +#endif + constexpr size_t POINTS_PER_READ = 1024; + std::vector buf(POINTS_PER_READ * UNCOMPRESSED_POINT_SIZE); + auto range = chunk.range(num_points); + if (range.empty()) { + return; + } + const size_t begin = *range.begin(); + const size_t end = begin + range.size(); + for (size_t first = begin; first < end; first += POINTS_PER_READ) { + const size_t count = std::min(POINTS_PER_READ, end - first); + if (!bb::srs::pread_exact( + fd, buf.data(), count * UNCOMPRESSED_POINT_SIZE, first * UNCOMPRESSED_POINT_SIZE)) { + read_failed.store(true, std::memory_order_relaxed); + return; + } + for (size_t k = 0; k < count; ++k) { + dst[first + k] = from_buffer(buf, k * UNCOMPRESSED_POINT_SIZE); + } + } +#ifndef BB_NO_EXCEPTIONS + } catch (...) { + // from_buffer rejects a point off the curve. Caught here so that every worker is done with the + // descriptor before the first error is rethrown. + const std::lock_guard lock(parse_error_mutex); + if (!parse_error) { + parse_error = std::current_exception(); + } + } +#endif + }); +#ifndef BB_NO_EXCEPTIONS + if (parse_error) { + std::rethrow_exception(parse_error); + } +#endif + if (read_failed.load()) { + throw_or_abort("Failed to read " + std::to_string(num_points) + " points from " + path.string()); + } +} +#endif + /** * @brief Read uncompressed G1 points (64 bytes each) from a file. */ std::vector read_uncompressed_g1_points(const std::filesystem::path& path, size_t num_points) { + std::vector points(num_points); +#if defined(__wasm__) || defined(_WIN32) auto data = bb::read_file(path, num_points * UNCOMPRESSED_POINT_SIZE); if (num_points > data.size() / UNCOMPRESSED_POINT_SIZE) { throw_or_abort("Truncated uncompressed BN254 CRS"); } - std::vector points(num_points); bb::parallel_for([&](bb::ThreadChunk chunk) { for (auto i : chunk.range(num_points)) { points[i] = from_buffer(data, i * UNCOMPRESSED_POINT_SIZE); } }); +#else + read_uncompressed_g1_points_into(path, points.data(), num_points); +#endif return points; } @@ -291,6 +372,43 @@ std::vector get_bn254_g1_data(const std::filesystem::path& p return get_bn254_g1_data(path, num_points, allow_download, CRS_PRIMARY_URL, CRS_FALLBACK_URL); } +Bn254G1Points load_bn254_g1_points(const std::filesystem::path& path, size_t num_points, bool allow_download) +{ + // As in get_bn254_g1_data: a verification key can only be computed from whole pinned chunks. + num_points = round_up_to_chunk_boundary(num_points); +#if !defined(__wasm__) && !defined(_WIN32) + // Fast path, the cached uncompressed file: read straight into uninitialised storage. new T[n] default-initialises, + // which for the trivially constructible affine_element leaves the memory untouched. + static_assert(std::is_trivially_default_constructible_v); + auto allocate = [](size_t n) { + return std::shared_ptr(new g1::affine_element[n], [n](g1::affine_element* p) { + release_pages_in_parallel(p, n * sizeof(g1::affine_element)); + delete[] p; + }); + }; + { + BB_BENCH_NAME("get_bn254_g1_data"); + std::filesystem::create_directories(path); + const auto uncompressed_path = path / "bn254_g1.dat"; + FileLockGuard lock((path / "crs.lock").string()); + // As in get_bn254_g1_data: the uncompressed cache has no pinned hashes, so a BB_VERIFY_CRS load skips it. + if (std::getenv("BB_VERIFY_CRS") == nullptr && + get_file_size(uncompressed_path) / UNCOMPRESSED_POINT_SIZE >= num_points) { + vinfo("using cached uncompressed bn254 crs at ", uncompressed_path); + Bn254G1Points result{ allocate(num_points), num_points }; + read_uncompressed_g1_points_into(uncompressed_path, result.points.get(), num_points); + return result; + } + } +#endif + // Decompression and download paths are rare (they populate the cache); reuse them as they are. + // The vector stays the owner (aliasing constructor), so its points are not copied. + auto points = + std::make_shared>(get_bn254_g1_data(path, num_points, allow_download)); + const size_t size = points->size(); + return { std::shared_ptr(points, points->data()), size }; +} + // Loads the canonical 128-byte serialization of [x]_2 from disk and verifies it against the pinned // SHA-256 and the BN254 G2 prime-order subgroup. g2::affine_element get_bn254_g2_data(const std::filesystem::path& path) diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.hpp b/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.hpp index 38893ea..de69edf 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.hpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.hpp @@ -4,6 +4,7 @@ #include #include #include +#include namespace bb { std::vector get_bn254_g1_data(const std::filesystem::path& path, @@ -17,5 +18,19 @@ std::vector get_bn254_g1_data(const std::filesystem::path& p const std::string& primary_url, const std::string& fallback_url); +/** + * @brief The first `size` BN254 G1 CRS points in an owned array, as loaded by load_bn254_g1_points. + */ +struct Bn254G1Points { + std::shared_ptr points; + size_t size = 0; +}; + +/** + * @brief Same points as get_bn254_g1_data, in storage that is never zero-filled first: from the cached uncompressed + * file, threads deserialize straight into freshly allocated memory. + */ +Bn254G1Points load_bn254_g1_points(const std::filesystem::path& path, size_t num_points, bool allow_download = true); + g2::affine_element get_bn254_g2_data(const std::filesystem::path& path); } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/get_grumpkin_crs.cpp b/barretenberg/cpp/src/barretenberg/srs/factories/get_grumpkin_crs.cpp index 2b94c9d..4f62d59 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/get_grumpkin_crs.cpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/get_grumpkin_crs.cpp @@ -1,12 +1,16 @@ #include "get_grumpkin_crs.hpp" #include "barretenberg/api/file_io.hpp" #include "barretenberg/common/flock.hpp" +#include "barretenberg/common/thread.hpp" #include "barretenberg/common/throw_or_abort.hpp" #include "barretenberg/common/try_catch_shim.hpp" #include "barretenberg/crypto/sha256/sha256.hpp" #include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" #include "grumpkin_crs_data.hpp" #include "grumpkin_srs_gen.hpp" +#include "pread.hpp" +#include +#include namespace bb { @@ -47,16 +51,28 @@ std::vector get_grumpkin_g1_data(const std::file // A short cache cannot authenticate even a smaller requested prefix against the chunk pins. if (get_file_size(g1_path) >= verify_bytes) { vinfo("using cached grumpkin crs with num points ", num_points, " at: ", g1_path); +#if !defined(__wasm__) && !defined(_WIN32) + // Uninitialised: the reads write every byte. + const std::unique_ptr storage(new uint8_t[verify_bytes]); + if (!srs::pread_prefix_in_parallel(g1_path, storage.get(), verify_bytes)) { + throw_or_abort("Truncated Grumpkin CRS"); + } + const std::span data(storage.get(), verify_bytes); +#else const auto data = read_file(g1_path, verify_bytes); if (data.size() != verify_bytes) { throw_or_abort("Truncated Grumpkin CRS"); } +#endif // Not hashed here: the CRS constructor checks every point against the pinned chunk hashes, and accepts only // whole chunks. std::vector points(verify_points); - for (size_t i = 0; i < verify_points; ++i) { - points[i] = from_buffer(data, i * sizeof(curve::Grumpkin::AffineElement)); - } + parallel_for([&](ThreadChunk chunk) { + for (auto i : chunk.range(verify_points)) { + points[i] = + from_buffer(data, i * sizeof(curve::Grumpkin::AffineElement)); + } + }); return points; } diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.cpp b/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.cpp index abbd3a9..32e8891 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.cpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.cpp @@ -7,6 +7,8 @@ #include "bn254_crs_data.hpp" #include "crs_integrity.hpp" #include +#include +#include namespace { @@ -22,11 +24,12 @@ class MemBn254Crs : public Crs { MemBn254Crs& operator=(const MemBn254Crs&) = delete; MemBn254Crs& operator=(MemBn254Crs&&) = delete; - MemBn254Crs(std::vector points, g2::affine_element const& g2_point) + MemBn254Crs(std::shared_ptr points, size_t num_points, g2::affine_element const& g2_point) : g2_x(g2_point) , precomputed_g2_lines( static_cast(aligned_alloc(64, sizeof(bb::pairing::miller_lines) * 2))) - , monomials_(std::move(points)) + , monomials_owner_(std::move(points)) + , monomials_(monomials_owner_.get(), num_points) { bb::pairing::precompute_miller_lines(bb::g2::one, precomputed_g2_lines[0]); bb::pairing::precompute_miller_lines(g2_x, precomputed_g2_lines[1]); @@ -54,16 +57,35 @@ class MemBn254Crs : public Crs { private: g2::affine_element g2_x; pairing::miller_lines* precomputed_g2_lines; - std::vector monomials_; + // The points live in a shared array, so the native loader can fill uninitialised storage in parallel and points that + // arrive in a vector are aliased rather than copied. + std::shared_ptr monomials_owner_; + std::span monomials_; std::atomic points_verified_{ false }; }; +/** A vector of points as a shared array that keeps the vector as its owner (aliasing constructor): no copy. */ +std::shared_ptr share_points(std::vector&& points) +{ + const auto owner = std::make_shared>(std::move(points)); + return { owner, owner->data() }; +} + } // namespace namespace bb::srs::factories { MemBn254CrsFactory::MemBn254CrsFactory(std::vector points, g2::affine_element const& g2_point) - : crs_(std::make_shared(std::move(points), g2_point)) +{ + const size_t num_points = points.size(); + crs_ = std::make_shared(share_points(std::move(points)), num_points, g2_point); + vinfo("Initialized ", curve::BN254::name, " CRS from memory with num points = ", crs_->get_monomial_size()); +} + +MemBn254CrsFactory::MemBn254CrsFactory(std::shared_ptr points, + size_t num_points, + g2::affine_element const& g2_point) + : crs_(std::make_shared(std::move(points), num_points, g2_point)) { vinfo("Initialized ", curve::BN254::name, " CRS from memory with num points = ", crs_->get_monomial_size()); } @@ -71,7 +93,7 @@ MemBn254CrsFactory::MemBn254CrsFactory(std::vector points, g template <> std::shared_ptr> CrsFactory::get_verifier_crs() { static const std::shared_ptr> verifier_crs = - std::make_shared(std::vector{}, srs::get_bn254_g2_crs_element()); + std::make_shared(nullptr, 0, srs::get_bn254_g2_crs_element()); return verifier_crs; } diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.hpp b/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.hpp index 581b2c3..4c9fa8f 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.hpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/mem_bn254_crs_factory.hpp @@ -4,6 +4,7 @@ #include "barretenberg/ecc/curves/bn254/g2.hpp" #include "crs_factory.hpp" #include +#include #include namespace bb::srs::factories { @@ -16,6 +17,9 @@ namespace bb::srs::factories { class MemBn254CrsFactory : public CrsFactory { public: MemBn254CrsFactory(std::vector points, g2::affine_element const& g2_point); + MemBn254CrsFactory(std::shared_ptr points, + size_t num_points, + g2::affine_element const& g2_point); std::shared_ptr> get_crs(size_t degree) override; diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/native_crs_factory.cpp b/barretenberg/cpp/src/barretenberg/srs/factories/native_crs_factory.cpp index 5edab23..18f40cb 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/native_crs_factory.cpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/native_crs_factory.cpp @@ -16,9 +16,9 @@ namespace bb::srs::factories { */ MemBn254CrsFactory init_bn254_crs(const std::filesystem::path& path, size_t dyadic_circuit_size, bool allow_download) { - auto bn254_g1_data = get_bn254_g1_data(path, dyadic_circuit_size, allow_download); + auto bn254_g1_data = load_bn254_g1_points(path, dyadic_circuit_size, allow_download); auto bn254_g2_data = srs::get_bn254_g2_crs_element(); - return { std::move(bn254_g1_data), bn254_g2_data }; + return { std::move(bn254_g1_data.points), bn254_g1_data.size, bn254_g2_data }; } /** diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/pread.hpp b/barretenberg/cpp/src/barretenberg/srs/factories/pread.hpp new file mode 100644 index 0000000..38f97ab --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/srs/factories/pread.hpp @@ -0,0 +1,60 @@ +#pragma once +#if !defined(__wasm__) && !defined(_WIN32) +#include "barretenberg/common/thread.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bb::srs { + +/** + * @brief pread exactly `size` bytes at `offset`, retrying short reads and EINTR. Returns false on error or EOF. + */ +inline bool pread_exact(int fd, uint8_t* dst, size_t size, size_t offset) +{ + while (size > 0) { + const ssize_t got = ::pread(fd, dst, size, static_cast(offset)); + if (got < 0 && errno == EINTR) { + continue; + } + if (got <= 0) { + return false; + } + dst += got; + size -= static_cast(got); + offset += static_cast(got); + } + return true; +} + +/** + * @brief Reads the first `size` bytes of a file into `dst`, which may be uninitialised, one contiguous slice per + * thread, so the reads proceed in parallel and each page is first touched by the thread that fills it. + * @return false if the file cannot be opened or holds fewer than `size` bytes. + */ +inline bool pread_prefix_in_parallel(const std::filesystem::path& path, uint8_t* dst, size_t size) +{ + const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return false; + } + // Closed on every exit, including an exception from starting the workers. + const auto close_fd = [](const int* owned) { ::close(*owned); }; + const std::unique_ptr fd_owner(&fd, close_fd); + std::atomic failed{ false }; + parallel_for([&](ThreadChunk chunk) { + const auto range = chunk.range(size); + if (!range.empty() && !pread_exact(fd, dst + *range.begin(), range.size(), *range.begin())) { + failed.store(true, std::memory_order_relaxed); + } + }); + return !failed.load(); +} + +} // namespace bb::srs +#endif 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..c26b1e7 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; @@ -402,13 +405,36 @@ template class SumcheckProver { // Given gate challenges β = (β₀, ..., β_{d−1}) and d = `multivariate_d`, compute the evaluations of // GateSeparator_β (X₀, ..., X_{d−1}) = ∏ₖ₌₀^{d−1} (1 − Xₖ + Xₖ · βₖ) // on the boolean hypercube. - GateSeparatorPolynomial gate_separators(gate_challenges, multivariate_d); + // AVM rounds read the table only below 2^k, k = ceil(log2) of round 0's effective round size, and its first + // 2^k entries are the products of β₀, ..., β_{k−1} alone, so AVM computes only those. All d betas are kept for + // the partial evaluations. + size_t gate_separator_log_size = multivariate_d; + if constexpr (isAvmFlavor) { + const size_t active_rows = round.compute_effective_round_size(full_polynomials); + gate_separator_log_size = + active_rows <= 1 ? 0 : std::min(multivariate_d, numeric::get_msb(active_rows - 1) + 1); + vinfo("sumcheck: gate separator table of 2^", gate_separator_log_size, " entries"); + } + GateSeparatorPolynomial gate_separators(gate_challenges, gate_separator_log_size); + // The largest index a round reads is (E/2 - 1) * periodicity, E being its effective round size. + const auto check_gate_separator_table = [&]([[maybe_unused]] const auto& polynomials) { + if constexpr (isAvmFlavor) { + const size_t active_rows = round.compute_effective_round_size(polynomials); + BB_ASSERT(active_rows == 0 || ((active_rows / 2) - 1) * gate_separators.periodicity < + gate_separators.beta_products.size(), + "Sumcheck: the gate separator table does not cover this round's active rows"); + } + }; 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"); + check_gate_separator_table(full_polynomials); auto round_univariate = round.compute_univariate(full_polynomials, relation_parameters, gate_separators, alphas); @@ -417,15 +443,43 @@ 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); + check_gate_separator_table(folded_polynomials); + 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"); + check_gate_separator_table(partially_evaluated_polynomials); // Write the round univariate to the transcript auto round_univariate = round.compute_univariate(partially_evaluated_polynomials, relation_parameters, gate_separators, alphas); @@ -653,8 +707,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 +718,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 +747,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..a1c6ef5 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck_round.hpp @@ -21,7 +21,10 @@ #include #include #include +#include #include +#include +#include namespace bb { @@ -46,6 +49,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