diff --git a/barretenberg/cpp/src/barretenberg/bbapi/bbapi_circuit_prove_release.test.cpp b/barretenberg/cpp/src/barretenberg/bbapi/bbapi_circuit_prove_release.test.cpp new file mode 100644 index 0000000..3cd3980 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/bbapi/bbapi_circuit_prove_release.test.cpp @@ -0,0 +1,112 @@ +#include "barretenberg/bbapi/bbapi_prove_instance.hpp" +#include "barretenberg/special_public_inputs/special_public_inputs.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" +#include "barretenberg/ultra_honk/prover_instance.hpp" +#include "barretenberg/ultra_honk/ultra_prover.hpp" +#include "barretenberg/ultra_honk/ultra_verifier.hpp" + +#include + +namespace bb::bbapi { +namespace { + +using Flavor = UltraFlavor; +using Builder = UltraCircuitBuilder; +using ProverInstance = ProverInstance_; +using VerificationKey = Flavor::VerificationKey; + +/** + * @brief An Ultra circuit with arithmetic, public-input, lookup, range and ROM/RAM rows, built without randomness so + * that two builds are identical. + */ +Builder build_circuit() +{ + Builder builder; + for (uint64_t i = 0; i < 16; ++i) { + const uint32_t a_idx = builder.add_public_variable(fr(i + 1)); + const uint32_t b_idx = builder.add_variable(fr((2 * i) + 3)); + const uint32_t c_idx = builder.add_variable(fr(7)); + const uint32_t d_idx = builder.add_variable(fr(i + 1) + fr((2 * i) + 3) + fr(7)); + builder.create_big_add_gate({ a_idx, b_idx, c_idx, d_idx, fr(1), fr(1), fr(1), fr(-1), fr(0) }); + } + + constexpr auto UINT32_XOR = plookup::MultiTableId::UINT32_XOR; + for (uint32_t i = 0; i < 8; ++i) { + const fr left = fr{ 0x9e3779b9U * (i + 1), 0, 0, 0 }.to_montgomery_form(); + const fr right = fr{ 0x85ebca6bU ^ i, 0, 0, 0 }.to_montgomery_form(); + const uint32_t left_idx = builder.add_variable(left); + const uint32_t right_idx = builder.add_variable(right); + const auto accumulators = plookup::get_lookup_accumulators(UINT32_XOR, left, right, /*is_2_to_1_lookup=*/true); + builder.create_gates_from_plookup_accumulators(UINT32_XOR, accumulators, left_idx, right_idx); + } + + for (uint64_t i = 0; i < 16; ++i) { + builder.create_dyadic_range_constraint(builder.add_variable(fr(i * 1000)), 16, "range"); + } + + const size_t rom_id = builder.create_ROM_array(4); + for (size_t i = 0; i < 4; ++i) { + builder.set_ROM_element(rom_id, i, builder.add_variable(fr((i * i) + 1))); + } + builder.read_ROM_array(rom_id, builder.add_variable(fr(2))); + + const size_t ram_id = builder.create_RAM_array(2); + builder.init_RAM_element(ram_id, 0, builder.add_variable(fr(5))); + builder.init_RAM_element(ram_id, 1, builder.add_variable(fr(9))); + builder.write_RAM_array(ram_id, builder.add_variable(fr(1)), builder.add_variable(fr(11))); + builder.read_RAM_array(ram_id, builder.add_variable(fr(1))); + + DefaultIO::add_default(builder); + return builder; +} + +class CircuitProveCopiedCircuitData : public ::testing::Test { + protected: + static void SetUpTestSuite() { srs::init_file_crs_factory(srs::bb_crs_path()); } +}; + +/** + * @brief The instance CircuitProve builds frees the circuit's blocks and lookup tables, keeps their sizes and offsets, + * and proves the same bytes as an instance that keeps them. + */ +TEST_F(CircuitProveCopiedCircuitData, FreesTheCircuitAndProvesTheSameBytes) +{ + Builder kept = build_circuit(); + Builder released = build_circuit(); + auto kept_instance = std::make_shared(kept, CopiedCircuitData::KEEP); + auto released_instance = circuit_prove_instance(released); + + EXPECT_FALSE(kept.get_lookup_tables().empty()); + EXPECT_TRUE(released.get_lookup_tables().empty()); + auto kept_blocks = kept.blocks.get(); + auto released_blocks = released.blocks.get(); + size_t num_freed_blocks = 0; + for (size_t i = 0; i < kept_blocks.size(); ++i) { + EXPECT_FALSE(kept_blocks[i].data_freed_); + EXPECT_EQ(released_blocks[i].size(), kept_blocks[i].size()); + EXPECT_EQ(released_blocks[i].trace_offset(), kept_blocks[i].trace_offset()); + // A block without rows has no chunk in the copying pass, so nothing frees it. + EXPECT_EQ(released_blocks[i].data_freed_, kept_blocks[i].size() > 0); + if (released_blocks[i].data_freed_) { + ++num_freed_blocks; + } + } + // Arithmetic, public inputs, lookup, delta range and memory at least. + EXPECT_GE(num_freed_blocks, 5U); + + auto vk = std::make_shared(kept_instance->get_precomputed()); + EXPECT_EQ(VerificationKey(released_instance->get_precomputed()), *vk); + UltraProver_ kept_prover(kept_instance, vk); + UltraProver_ released_prover(released_instance, vk); + const auto kept_proof = kept_prover.construct_proof(); + const auto released_proof = released_prover.construct_proof(); + EXPECT_EQ(released_proof, kept_proof); + + UltraVerifier_ verifier(std::make_shared(vk)); + EXPECT_TRUE(verifier.verify_proof(released_proof).result); +} + +} // namespace +} // namespace bb::bbapi diff --git a/barretenberg/cpp/src/barretenberg/bbapi/bbapi_prove_instance.hpp b/barretenberg/cpp/src/barretenberg/bbapi/bbapi_prove_instance.hpp new file mode 100644 index 0000000..f4edc39 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/bbapi/bbapi_prove_instance.hpp @@ -0,0 +1,18 @@ +#pragma once +#include "barretenberg/trace_to_polynomials/copied_circuit_data.hpp" +#include "barretenberg/ultra_honk/prover_instance.hpp" +#include + +namespace bb::bbapi { + +/** + * @brief Builds the prover instance a CircuitProve proof is made from. The request reads nothing from the circuit + * afterwards, so each trace block and lookup table is freed as soon as it has been copied into the polynomials. + */ +template +std::shared_ptr> circuit_prove_instance(typename Flavor::CircuitBuilder& circuit) +{ + return std::make_shared>(circuit, CopiedCircuitData::RELEASE); +} + +} // namespace bb::bbapi diff --git a/barretenberg/cpp/src/barretenberg/bbapi/bbapi_ultra_honk.cpp b/barretenberg/cpp/src/barretenberg/bbapi/bbapi_ultra_honk.cpp index 28dcab4..a7e707f 100644 --- a/barretenberg/cpp/src/barretenberg/bbapi/bbapi_ultra_honk.cpp +++ b/barretenberg/cpp/src/barretenberg/bbapi/bbapi_ultra_honk.cpp @@ -1,4 +1,5 @@ #include "barretenberg/bbapi/bbapi_ultra_honk.hpp" +#include "barretenberg/bbapi/bbapi_prove_instance.hpp" #include "barretenberg/bbapi/bbapi_shared.hpp" #include "barretenberg/common/serialize.hpp" #include "barretenberg/dsl/acir_format/acir_to_constraint_buf.hpp" @@ -35,25 +36,28 @@ Circuit _compute_circuit(std::vector&& bytecode, std::vector&& template std::shared_ptr> _compute_prover_instance(std::vector&& bytecode, - std::vector&& witness) + std::vector&& witness, + const bool for_proof = false) { // Measure function time and debug print auto initial_time = std::chrono::high_resolution_clock::now(); typename Flavor::CircuitBuilder builder = _compute_circuit(std::move(bytecode), std::move(witness)); - auto prover_instance = std::make_shared>(builder); + // The VK path keeps the circuit as it was; a proof's instance frees it while copying it. + auto prover_instance = + for_proof ? circuit_prove_instance(builder) : std::make_shared>(builder); auto final_time = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(final_time - initial_time); info("CircuitProve: Proving key computed in ", duration.count(), " ms"); // Validate consistency between IO type and IPA proof presence // IO::HasIPA indicates the circuit type requires IPA accumulation (rollup circuits) - // prover_instance->ipa_proof contains the actual IPA proof data from the circuit + // has_ipa_proof() also counts a proof still being computed, without waiting for it if constexpr (IO::HasIPA) { - BB_ASSERT(!prover_instance->ipa_proof.empty(), + BB_ASSERT(prover_instance->has_ipa_proof(), "RollupIO circuit expected IPA proof but none was provided. " "Ensure the circuit includes IPA accumulation data."); } else { - BB_ASSERT(prover_instance->ipa_proof.empty(), + BB_ASSERT(!prover_instance->has_ipa_proof(), "Non-rollup circuit should not have IPA proof. " "Use ipa_accumulation=true in settings for rollup circuits."); } @@ -110,7 +114,8 @@ CircuitProve::Response _prove(std::vector&& bytecode, using Proof = typename Flavor::Transcript::Proof; using VerificationKey = typename Flavor::VerificationKey; - auto prover_instance = _compute_prover_instance(std::move(bytecode), std::move(witness)); + auto prover_instance = + _compute_prover_instance(std::move(bytecode), std::move(witness), /*for_proof=*/true); // Create or deserialize VK std::shared_ptr vk; @@ -169,6 +174,8 @@ CircuitComputeVk::Response CircuitComputeVk::execute(BB_UNUSED const BBApiReques return dispatch_by_settings(settings, [&]() { auto prover_instance = _compute_prover_instance(std::move(circuit.bytecode), {}); auto vk = std::make_shared(prover_instance->get_precomputed()); + // No proof is exported here, so wait for a pending IPA proof now: its failure must fail the request. + prover_instance->resolve_ipa_proof(); return CircuitComputeVk::Response{ .bytes = to_buffer(*vk), .fields = vk_to_uint256_fields(*vk), .hash = to_buffer(vk->hash()) }; @@ -190,6 +197,8 @@ CircuitStats::Response _stats(std::vector&& bytecode, bool include_gate acir_format::AcirProgram program{ std::move(constraint_system), {} }; auto builder = acir_format::create_circuit(program, metadata); builder.finalize_circuit(); + // No proof is exported here, so wait for a pending IPA proof now: its failure must fail the request. + builder.resolve_ipa_proof(); response.num_gates = static_cast(builder.get_finalized_total_circuit_size()); response.num_gates_dyadic = static_cast(builder.get_circuit_subgroup_size(response.num_gates)); diff --git a/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range.test.cpp b/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range.test.cpp index d4b3b41..a2c165c 100644 --- a/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range.test.cpp +++ b/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range.test.cpp @@ -1,7 +1,10 @@ #include "barretenberg/circuit_checker/circuit_checker.hpp" #include "barretenberg/numeric/uint256/uint256.hpp" +#include "barretenberg/stdlib_circuit_builders/bounded_range_sort.hpp" #include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" +#include +#include #include using namespace bb; @@ -156,3 +159,90 @@ TEST(UltraCircuitBuilder, RangeChecksOnDuplicates) } } // namespace bb + +namespace bb { + +TEST(BoundedRangeSort, MatchesGeneralSortAndPreservesFallbackInputs) +{ + for (const uint64_t maximum : std::array{ 0, 1, 15, 255, 16383, 65535, 65536 }) { + for (const size_t count : std::array{ 0, 1, 255, 256, 257, 16384, 65536 }) { + for (const size_t shape : std::array{ 0, 1, 2, 3, 4 }) { + std::vector values(count); + uint64_t state = 0x9e3779b97f4a7c15ULL; + for (size_t i = 0; i < count; ++i) { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + values[i] = static_cast(state % (maximum + 1)); + } + if (shape == 1) + std::sort(values.begin(), values.end()); + if (shape == 2) + std::sort(values.begin(), values.end(), std::greater()); + if (shape == 3) + std::fill(values.begin(), values.end(), static_cast(maximum)); + if (shape == 4 && !values.empty()) + values[count / 2] = static_cast(maximum + 1); + const auto original = values; + auto expected = values; + std::sort(expected.begin(), expected.end()); + const bool eligible = + maximum < 65536 && count >= 256 && count >= maximum + 1 && + std::all_of(original.begin(), original.end(), [&](uint32_t value) { return value <= maximum; }); + const bool admitted = range_sort::try_counting_sort(values, maximum); + EXPECT_EQ(admitted, eligible); + if (admitted) { + EXPECT_EQ(values, expected); + } else { + EXPECT_EQ(values, original); + std::sort(values.begin(), values.end()); + EXPECT_EQ(values, expected); + } + } + } + } +} + +TEST(UltraCircuitBuilder, BoundedRangeSortValidAndInvalidWitnesses) +{ + for (const size_t shape : std::array{ 0, 1, 2 }) { + UltraCircuitBuilder builder; + std::vector indices; + for (size_t i = 0; i < 512; ++i) { + const uint32_t value = shape == 1 && i == 17 ? uint32_t(256) : static_cast((i * 17) % 256); + const fr field_value = shape == 2 && i == 17 ? fr(uint256_t(1) << 128) + fr(1) : fr(value); + const uint32_t index = builder.add_variable(field_value); + indices.push_back(index); + builder.create_small_range_constraint(index, 255); + } + builder.assert_equal(indices[0], indices[256]); // Equal values with distinct original witness indices. + builder.create_unconstrained_gates(indices); + EXPECT_EQ(CircuitChecker::check(builder), shape == 0); + } +} + +} // namespace bb + +namespace bb { +TEST(UltraCircuitBuilder, NativeSubLimbAdmissionPreservesRangeChecks) +{ + for (const uint64_t bits : std::array{ 14, 15, 28, 68, 253 }) { + for (const size_t shape : std::array{ 0, 1, 2 }) { + UltraCircuitBuilder builder; + const uint256_t value = + shape == 0 ? uint256_t(0) : (shape == 1 ? (uint256_t(1) << bits) - 1 : uint256_t(1) << bits); + const uint32_t index = builder.add_variable(fr(value)); + const auto limbs = builder.create_limbed_range_constraint(index, bits, 14, "native-limb-test"); + EXPECT_EQ(limbs.size(), (bits + 13) / 14); + for (size_t i = 0; i < limbs.size(); ++i) { + EXPECT_EQ(builder.get_variable(limbs[i]), fr((value >> (i * 14)).data[0] & uint64_t(16383))); + } + EXPECT_EQ(builder.failed(), shape == 2); + if (shape == 2) { + EXPECT_EQ(builder.err(), "native-limb-test"); + } + EXPECT_EQ(CircuitChecker::check(builder), shape != 2); + } + } +} +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range_equivalence.test.cpp b/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range_equivalence.test.cpp new file mode 100644 index 0000000..ac73b1c --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range_equivalence.test.cpp @@ -0,0 +1,470 @@ +#include "barretenberg/circuit_checker/circuit_checker.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/numeric/uint256/uint256.hpp" +#include "barretenberg/stdlib_circuit_builders/bounded_range_sort.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include +#include +#include +#include +#include + +/** + * The range-constraint paths of UltraCircuitBuilder (range_constrain_two_limbs, create_limbed_range_constraint, range + * list processing) must build exactly the circuit that the straightforward compositions of public builder methods + * below build: same variables, tags, copy cycles, range lists, gates, gate count and failure message. + */ + +namespace bb { +namespace { + +using Builder = UltraCircuitBuilder; +using Row = Builder::GateRowT; + +auto& engine = numeric::get_debug_randomness(); + +uint256_t random_below_pow2(const uint64_t num_bits) +{ + return num_bits == 0 ? uint256_t(0) : engine.get_random_uint256() & ((uint256_t(1) << num_bits) - 1); +} + +struct IntegerSelectors { + int q_m = 0; + int q_c = 0; + int q_1 = 0; + int q_2 = 0; + int q_3 = 0; + int q_4 = 0; +}; + +// A gate row whose selectors are converted from integers at run time (its gate kind is given when it's appended). +Row integer_selector_row(const int gate_value, const IntegerSelectors& selectors) +{ + Row row{}; + row.gate_value = gate_value; + row.q_m = selectors.q_m; + row.q_c = selectors.q_c; + row.q_1 = selectors.q_1; + row.q_2 = selectors.q_2; + row.q_3 = selectors.q_3; + row.q_4 = selectors.q_4; + return row; +} + +void reference_range_constrain_two_limbs(Builder& builder, + const uint32_t lo_idx, + const uint32_t hi_idx, + const size_t lo_limb_bits, + const size_t hi_limb_bits, + const std::string& msg) +{ + if (uint256_t(builder.get_variable(lo_idx)) >= (uint256_t(1) << lo_limb_bits) && !builder.failed()) { + builder.failure(msg + ": lo limb."); + } + if (uint256_t(builder.get_variable(hi_idx)) >= (uint256_t(1) << hi_limb_bits) && !builder.failed()) { + builder.failure(msg + ": hi limb."); + } + const auto masks = [](const size_t limb_bits) { + std::array result{}; + for (size_t i = 0; i < 5; ++i) { + const size_t low = 14 * i; + const size_t bits = limb_bits > low ? std::min(limb_bits - low, 14) : 0; + result[i] = (1ULL << bits) - 1; + } + return result; + }; + const auto sublimbs = [&](const uint32_t limb_idx, const std::array& limb_masks) { + const uint256_t limb(builder.get_variable(limb_idx)); + std::array indices{}; + for (size_t i = 0; i < 5; ++i) { + indices[i] = limb_masks[i] != 0 ? builder.add_variable(fr((limb >> (14 * i)) & ((uint256_t(1) << 14) - 1))) + : builder.zero_idx(); + } + return indices; + }; + const auto lo_masks = masks(lo_limb_bits); + const auto hi_masks = masks(hi_limb_bits); + const auto lo = sublimbs(lo_idx, lo_masks); + const auto hi = sublimbs(hi_idx, hi_masks); + + Row row = integer_selector_row(1, { .q_3 = 1, .q_4 = 1 }); + row.wires = { lo[0], lo[1], lo[2], lo_idx }; + builder.blocks.nnf.append_gate(row); + row = integer_selector_row(1, { .q_m = 1, .q_3 = 1 }); + row.wires = { lo[3], lo[4], hi[0], hi[1] }; + builder.blocks.nnf.append_gate(row); + row = integer_selector_row(0, {}); + row.wires = { hi[2], hi[3], hi[4], hi_idx }; + builder.blocks.nnf.append_gate(row); + builder.increment_num_gates(3); + + for (size_t i = 0; i < 5; ++i) { + if (lo_masks[i] != 0) { + builder.create_small_range_constraint( + lo[i], lo_masks[i], "ultra_circuit_builder: sublimb of low too large"); + } + if (hi_masks[i] != 0) { + builder.create_small_range_constraint(hi[i], hi_masks[i], "ultra_circuit_builder: sublimb of hi too large"); + } + } +} + +std::vector reference_create_limbed_range_constraint(Builder& builder, + const uint32_t variable_index, + const uint64_t num_bits, + const uint64_t target_range_bitnum, + const std::string& msg) +{ + const uint256_t val(builder.get_variable(variable_index)); + if (val.get_msb() >= num_bits && !builder.failed()) { + builder.failure(msg); + } + const uint64_t sublimb_mask = (1ULL << target_range_bitnum) - 1; + const bool has_remainder_bits = (num_bits % target_range_bitnum != 0); + const uint64_t num_limbs = (num_bits / target_range_bitnum) + (has_remainder_bits ? 1U : 0U); + const uint64_t last_limb_range = (1ULL << (num_bits % target_range_bitnum)) - 1; + + std::vector sublimbs; + uint256_t accumulator = val; + for (uint64_t j = 0; j < num_limbs; ++j) { + sublimbs.push_back(accumulator.data[0] & sublimb_mask); + accumulator = accumulator >> target_range_bitnum; + } + std::vector sublimb_indices; + for (uint64_t j = 0; j < num_limbs; ++j) { + const uint32_t limb_idx = builder.add_variable(fr(sublimbs[j])); + sublimb_indices.push_back(limb_idx); + const bool is_remainder_limb = has_remainder_bits && (j == num_limbs - 1); + builder.create_small_range_constraint( + limb_idx, is_remainder_limb ? last_limb_range : sublimb_mask, "create_small_range_constraint"); + } + + const uint64_t num_limb_triples = (num_limbs + 2) / 3; + accumulator = val; + uint32_t accumulator_idx = variable_index; + for (uint64_t i = 0; i < num_limb_triples; ++i) { + const bool is_last_triple = (i == num_limb_triples - 1); + std::array limbs{}; + std::array values{}; + std::array shifts{}; + for (uint64_t k = 0; k < 3; ++k) { + const uint64_t j = (3 * i) + k; + limbs[k] = j < num_limbs ? sublimb_indices[j] : builder.zero_idx(); + values[k] = j < num_limbs ? sublimbs[j] : 0; + shifts[k] = target_range_bitnum * j; + } + const uint256_t new_accumulator = accumulator - (uint256_t(values[0]) << shifts[0]) - + (uint256_t(values[1]) << shifts[1]) - (uint256_t(values[2]) << shifts[2]); + builder.create_big_add_gate({ limbs[0], + limbs[1], + limbs[2], + accumulator_idx, + fr(uint256_t(1) << shifts[0]), + fr(uint256_t(1) << shifts[1]), + fr(uint256_t(1) << shifts[2]), + fr(-1), + fr(0) }, + !is_last_triple); + if (!is_last_triple) { + accumulator_idx = builder.add_variable(fr(new_accumulator)); + accumulator = new_accumulator; + } + } + return sublimb_indices; +} + +void reference_process_range_list(Builder& builder, Builder::RangeList& list) +{ + for (uint32_t& x : list.variable_indices) { + x = builder.real_variable_index[x]; + } + std::sort(list.variable_indices.begin(), list.variable_indices.end()); + list.variable_indices.erase(std::unique(list.variable_indices.begin(), list.variable_indices.end()), + list.variable_indices.end()); + + std::vector sorted_list; + bool values_in_range = true; + for (const uint32_t variable_index : list.variable_indices) { + const uint256_t value(builder.get_variable(variable_index)); + values_in_range = values_in_range && value <= uint256_t(list.target_range); + sorted_list.push_back(static_cast(value.data[0])); + } + if (!values_in_range || !range_sort::try_counting_sort(sorted_list, list.target_range)) { + std::sort(sorted_list.begin(), sorted_list.end()); + } + + constexpr size_t gate_width = Builder::NUM_WIRES; + size_t padding = (gate_width - (list.variable_indices.size() % gate_width)) % gate_width; + if (list.variable_indices.size() <= gate_width) { + padding += gate_width; + } + std::vector indices(padding, builder.zero_idx()); + for (const uint32_t sorted_value : sorted_list) { + const uint32_t index = builder.add_variable(fr(sorted_value)); + builder.assign_tag(index, list.tau_tag); + indices.push_back(index); + } + builder.create_sort_constraint_with_edges(indices, fr(0), fr(list.target_range)); +} + +void reference_finalize_circuit(Builder& builder) +{ + builder.process_non_native_field_multiplications(); + builder.rom_ram_logic.process_ROM_arrays(&builder); + builder.rom_ram_logic.process_RAM_arrays(&builder); + for (auto& [target_range, list] : builder.range_lists) { + reference_process_range_list(builder, list); + } + builder.populate_public_inputs_block(); + builder.circuit_finalized = true; +} + +void expect_same_circuit(const Builder& actual, const Builder& expected) +{ + // The base comparison covers variables, copy cycles, tags, tau, gate count, public inputs and failure state. + EXPECT_TRUE(static_cast&>(actual) == + static_cast&>(expected)); + EXPECT_EQ(actual.get_num_variables(), expected.get_num_variables()); + EXPECT_EQ(actual.num_gates(), expected.num_gates()); + EXPECT_EQ(actual.err(), expected.err()); + EXPECT_TRUE(actual.real_variable_tags == expected.real_variable_tags); + EXPECT_TRUE(actual.range_lists == expected.range_lists); + EXPECT_TRUE(actual.blocks == expected.blocks); +} + +// Builds the same inputs into an actual and a reference builder and compares them before and after finalization. +class RangeEquivalence : public ::testing::TestWithParam { + protected: + Builder actual{ GetParam() }; + Builder expected{ GetParam() }; + + std::pair add_variable(const fr& value) + { + return { actual.add_variable(value), expected.add_variable(value) }; + } + + void two_limbs(const uint256_t& lo, const uint256_t& hi, const size_t lo_bits, const size_t hi_bits) + { + const auto [lo_actual, lo_expected] = add_variable(fr(lo)); + const auto [hi_actual, hi_expected] = add_variable(fr(hi)); + ASSERT_EQ(lo_actual, lo_expected); + ASSERT_EQ(hi_actual, hi_expected); + actual.range_constrain_two_limbs(lo_actual, hi_actual, lo_bits, hi_bits, "two limbs"); + reference_range_constrain_two_limbs(expected, lo_expected, hi_expected, lo_bits, hi_bits, "two limbs"); + } + + void limbed(const uint256_t& value, const uint64_t num_bits, const uint64_t bitnum) + { + const auto [idx_actual, idx_expected] = add_variable(fr(value)); + ASSERT_EQ(idx_actual, idx_expected); + const auto limbs_actual = actual.create_limbed_range_constraint(idx_actual, num_bits, bitnum, "limbed"); + const auto limbs_expected = + reference_create_limbed_range_constraint(expected, idx_expected, num_bits, bitnum, "limbed"); + EXPECT_EQ(limbs_actual, limbs_expected); + } + + void small(const uint64_t value, const uint64_t target_range) + { + const auto [idx_actual, idx_expected] = add_variable(fr(value)); + actual.create_unconstrained_gate( + actual.blocks.arithmetic, idx_actual, actual.zero_idx(), actual.zero_idx(), actual.zero_idx()); + expected.create_unconstrained_gate( + expected.blocks.arithmetic, idx_expected, expected.zero_idx(), expected.zero_idx(), expected.zero_idx()); + actual.create_small_range_constraint(idx_actual, target_range, "small"); + expected.create_small_range_constraint(idx_expected, target_range, "small"); + } + + void expect_same_before_and_after_finalization(const bool expect_valid) + { + expect_same_circuit(actual, expected); + EXPECT_EQ(actual.failed(), !expect_valid) << actual.err(); + if (!GetParam()) { + EXPECT_EQ(CircuitChecker::check(actual), expect_valid); + } + actual.finalize_circuit(); + reference_finalize_circuit(expected); + expect_same_circuit(actual, expected); + } +}; + +TEST_P(RangeEquivalence, TwoLimbs) +{ + const std::array, 8> limb_bits{ + { { 68, 68 }, { 70, 70 }, { 14, 28 }, { 1, 57 }, { 0, 13 }, { 56, 42 }, { 69, 3 }, { 15, 70 } } + }; + for (const auto& [lo_bits, hi_bits] : limb_bits) { + for (size_t i = 0; i < 8; ++i) { + two_limbs(random_below_pow2(lo_bits), random_below_pow2(hi_bits), lo_bits, hi_bits); + } + // Largest in-range values. + two_limbs((uint256_t(1) << lo_bits) - 1, (uint256_t(1) << hi_bits) - 1, lo_bits, hi_bits); + } + expect_same_before_and_after_finalization(true); +} + +TEST_P(RangeEquivalence, Limbed) +{ + const std::array bitnums{ Builder::DEFAULT_PLOOKUP_RANGE_BITNUM, 16, 8, 3, 1 }; + const std::array bit_counts{ 1, 2, 13, 14, 15, 27, 28, 29, 41, 42, + 43, 64, 68, 70, 100, 128, 136, 252, 253 }; + for (const uint64_t bitnum : bitnums) { + for (const uint64_t num_bits : bit_counts) { + limbed(random_below_pow2(num_bits), num_bits, bitnum); + limbed((uint256_t(1) << num_bits) - 1, num_bits, bitnum); + limbed(0, num_bits, bitnum); + } + } + expect_same_before_and_after_finalization(true); +} + +TEST_P(RangeEquivalence, MixedSequence) +{ + // Interleaves the paths so that range lists are created by each of them first and shared afterwards, including + // small ranges equal to sublimb ranges and constraints on sublimbs that already carry a range tag. + const std::array small_ranges{ (1U << 14) - 1, (1U << 12) - 1, (1U << 6) - 1, 7, 255, 1 }; + for (size_t i = 0; i < 300; ++i) { + switch (engine.get_random_uint8() % 4U) { + case 0: { + const size_t lo_bits = engine.get_random_uint8() % 71U; + const size_t hi_bits = engine.get_random_uint8() % 71U; + two_limbs(random_below_pow2(lo_bits), random_below_pow2(hi_bits), lo_bits, hi_bits); + break; + } + case 1: { + const uint64_t num_bits = 1 + (engine.get_random_uint8() % Builder::MAX_NUM_BITS_RANGE_CONSTRAINT); + const uint64_t bitnum = (engine.get_random_uint8() % 2) == 0 ? Builder::DEFAULT_PLOOKUP_RANGE_BITNUM + : 1U + (engine.get_random_uint8() % 16U); + limbed(random_below_pow2(num_bits), num_bits, bitnum); + break; + } + case 2: { + const uint64_t target_range = small_ranges[engine.get_random_uint8() % small_ranges.size()]; + small(engine.get_random_uint64() % (target_range + 1), target_range); + break; + } + default: { + // Re-constrain the last sublimb created to a smaller range: the generic path copies the witness. + const auto [idx_actual, idx_expected] = add_variable(fr(5)); + const auto limbs_actual = actual.create_limbed_range_constraint(idx_actual, 20, 14, "limbed"); + const auto limbs_expected = + reference_create_limbed_range_constraint(expected, idx_expected, 20, 14, "limbed"); + ASSERT_EQ(limbs_actual, limbs_expected); + actual.create_small_range_constraint(limbs_actual.front(), 7, "smaller"); + expected.create_small_range_constraint(limbs_expected.front(), 7, "smaller"); + break; + } + } + } + expect_same_before_and_after_finalization(true); +} + +TEST_P(RangeEquivalence, OutOfRangeValuesKeepTheFirstFailure) +{ + // Each call below fails; only the first failure message is kept, and the circuit is still built the same way. + two_limbs(uint256_t(1) << 68, 3, 68, 68); + two_limbs(3, uint256_t(1) << 68, 68, 68); + two_limbs(engine.get_random_uint256(), engine.get_random_uint256(), 70, 70); + limbed(uint256_t(1) << 100, 100, 14); + limbed(engine.get_random_uint256(), 253, 14); + limbed(uint256_t(1) << 20, 20, 4); + EXPECT_EQ(actual.err(), "two limbs: lo limb."); + expect_same_before_and_after_finalization(false); +} + +TEST_P(RangeEquivalence, OutOfRangeLimbedFailureMessage) +{ + limbed(uint256_t(1) << 40, 40, 14); + EXPECT_EQ(actual.err(), "limbed"); + two_limbs(uint256_t(1) << 68, uint256_t(1) << 68, 68, 68); + expect_same_before_and_after_finalization(false); +} + +TEST_P(RangeEquivalence, OutOfRangeHiLimbFailureMessage) +{ + two_limbs(5, uint256_t(1) << 50, 68, 50); + EXPECT_EQ(actual.err(), "two limbs: hi limb."); + expect_same_before_and_after_finalization(false); +} + +INSTANTIATE_TEST_SUITE_P(UltraCircuitBuilder, RangeEquivalence, ::testing::Values(false, true)); + +TEST(UltraCircuitBuilderRangeEquivalence, SelectorRowsMatchIntegerSelectors) +{ + const Builder builder; + using NNF = Builder::NNF_SELECTORS; + using MEM = Builder::MEMORY_SELECTORS; + EXPECT_TRUE(builder.nnf_selectors_row(NNF::NNF_NONE) == integer_selector_row(0, {})); + EXPECT_TRUE(builder.nnf_selectors_row(NNF::LIMB_ACCUMULATE_1) == + integer_selector_row(1, { .q_3 = 1, .q_4 = 1 })); + EXPECT_TRUE(builder.nnf_selectors_row(NNF::LIMB_ACCUMULATE_2) == + integer_selector_row(1, { .q_m = 1, .q_3 = 1 })); + EXPECT_TRUE(builder.nnf_selectors_row(NNF::NON_NATIVE_FIELD_1) == + integer_selector_row(1, { .q_2 = 1, .q_3 = 1 })); + EXPECT_TRUE(builder.nnf_selectors_row(NNF::NON_NATIVE_FIELD_2) == + integer_selector_row(1, { .q_2 = 1, .q_4 = 1 })); + EXPECT_TRUE(builder.nnf_selectors_row(NNF::NON_NATIVE_FIELD_3) == + integer_selector_row(1, { .q_m = 1, .q_2 = 1 })); + + EXPECT_TRUE(builder.memory_selectors_row(MEM::MEM_NONE) == integer_selector_row(0, {})); + EXPECT_TRUE(builder.memory_selectors_row(MEM::ROM_CONSISTENCY_CHECK) == + integer_selector_row(1, { .q_1 = 1, .q_2 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::RAM_CONSISTENCY_CHECK) == + integer_selector_row(1, { .q_3 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::RAM_TIMESTAMP_CHECK) == + integer_selector_row(1, { .q_1 = 1, .q_4 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::ROM_READ) == + integer_selector_row(1, { .q_m = 1, .q_1 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::RAM_READ) == + integer_selector_row(1, { .q_m = 1, .q_1 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::RAM_WRITE) == + integer_selector_row(1, { .q_m = 1, .q_c = 1, .q_1 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::ROM_LOGUP_TABLE) == + integer_selector_row(1, { .q_2 = 1 })); + EXPECT_TRUE(builder.memory_selectors_row(MEM::ROM_LOGUP_READ) == + integer_selector_row(1, { .q_4 = 1 })); +} + +TEST(UltraCircuitBuilderRangeEquivalence, GateConstructorsUseIntegerSelectors) +{ + Builder builder; + const uint32_t a = builder.add_variable(fr(3)); + const uint32_t b = builder.add_variable(fr(5)); + const auto last_row = [](auto& block) { + Row row{}; + const size_t idx = block.size() - 1; + row.wires = { block.w_l()[idx], block.w_r()[idx], block.w_o()[idx], block.w_4()[idx] }; + row.q_m = block.q_m()[idx]; + row.q_c = block.q_c()[idx]; + row.q_1 = block.q_1()[idx]; + row.q_2 = block.q_2()[idx]; + row.q_3 = block.q_3()[idx]; + row.q_4 = block.q_4()[idx]; + return row; + }; + const auto expect_arith_row = [&](const IntegerSelectors& selectors, const int gate_value) { + const auto& block = builder.blocks.arithmetic; + const size_t idx = block.size() - 1; + Row expected_row = integer_selector_row(0, selectors); + Row actual_row = last_row(builder.blocks.arithmetic); + expected_row.wires = actual_row.wires; + EXPECT_TRUE(actual_row == expected_row); + EXPECT_EQ(read_gate_selector(block, GateKind::Arith, idx), fr(gate_value)); + }; + + builder.create_bool_gate(a); + expect_arith_row({ .q_m = 1, .q_1 = -1 }, 1); + builder.create_big_add_gate({ a, b, a, b, 1, 1, -1, -1, 0 }, true); + expect_arith_row({ .q_1 = 1, .q_2 = 1, .q_3 = -1, .q_4 = -1 }, 2); + builder.create_big_add_gate({ a, b, a, b, 1, 1, -1, -1, 0 }, false); + expect_arith_row({ .q_1 = 1, .q_2 = 1, .q_3 = -1, .q_4 = -1 }, 1); + builder.create_big_mul_add_gate({ a, b, a, b, 1, 0, 0, -1, 0, 0 }, true); + expect_arith_row({ .q_m = 2, .q_3 = -1 }, 2); + builder.create_add_gate({ a, b, a, 1, 1, -1, 0 }); + expect_arith_row({ .q_1 = 1, .q_2 = 1, .q_3 = -1 }, 1); + builder.fix_witness(a, fr(3)); + expect_arith_row({ .q_c = -3, .q_1 = 1 }, 1); +} + +} // namespace +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range_list_processing.test.cpp b/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range_list_processing.test.cpp new file mode 100644 index 0000000..0c48d75 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/circuit_checker/ultra_circuit_builder_range_list_processing.test.cpp @@ -0,0 +1,426 @@ +#include "barretenberg/circuit_checker/circuit_checker.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/numeric/uint256/uint256.hpp" +#include "barretenberg/stdlib_circuit_builders/bounded_range_sort.hpp" +#include "barretenberg/stdlib_circuit_builders/mega_circuit_builder.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * finalize_circuit must build exactly the circuit that the serial range-list processing below builds, at every + * parallel_for concurrency and in both builder modes: same variables, copy cycles, tags, range lists, gates, gate count + * and failure state. + */ + +namespace bb { +namespace { + +// The parallel_for concurrencies every case runs at, highest first so that a worker pool created here has workers. +std::vector concurrencies() +{ +#ifdef NO_MULTITHREADING + return { 1 }; +#else + return { 16, 5, 2, 1 }; +#endif +} + +// Sets the parallel_for concurrency of this thread for its lifetime. +class ConcurrencyScope { + public: + explicit ConcurrencyScope([[maybe_unused]] const size_t concurrency) + { +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(concurrency); +#endif + } + ~ConcurrencyScope() + { +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(previous_); +#endif + } + ConcurrencyScope(const ConcurrencyScope&) = delete; + ConcurrencyScope& operator=(const ConcurrencyScope&) = delete; + ConcurrencyScope(ConcurrencyScope&&) = delete; + ConcurrencyScope& operator=(ConcurrencyScope&&) = delete; + + private: + size_t previous_ = get_num_cpus(); +}; + +template Builder make_builder(const bool is_write_vk_mode) +{ + if constexpr (std::is_same_v) { + return Builder(std::make_shared(), is_write_vk_mode); + } else { + return Builder(is_write_vk_mode); + } +} + +template +void reference_append_delta_range_rows(Builder& builder, const std::vector& indices) +{ + for (size_t i = 0; i < indices.size(); i += Builder::NUM_WIRES) { + builder.increment_num_gates(); + typename Builder::GateRowT row{}; + row.wires = { indices[i], indices[i + 1], indices[i + 2], indices[i + 3] }; + row.gate_value = fr(1); + builder.blocks.delta_range.template append_gate(row); + } +} + +template void reference_enforce_small_deltas(Builder& builder, const std::vector& indices) +{ + reference_append_delta_range_rows(builder, indices); + builder.create_unconstrained_gate( + builder.blocks.delta_range, indices.back(), builder.zero_idx(), builder.zero_idx(), builder.zero_idx()); +} + +template +void reference_create_sort_constraint_with_edges(Builder& builder, + const std::vector& indices, + const fr& start, + const fr& end) +{ + const uint32_t zero = builder.zero_idx(); + builder.create_add_gate({ indices[0], zero, zero, 1, 0, 0, -start }); + reference_append_delta_range_rows(builder, indices); + builder.create_unconstrained_gate(builder.blocks.delta_range, indices.back(), zero, zero, zero); + builder.create_add_gate({ indices.back(), zero, zero, 1, 0, 0, -end }); +} + +// Serial range-list processing: one add_variable call per sorted value. Any sort of the values gives the same sequence. +template void reference_process_range_list(Builder& builder, typename Builder::RangeList& list) +{ + for (uint32_t& x : list.variable_indices) { + x = builder.real_variable_index[x]; + } + std::sort(list.variable_indices.begin(), list.variable_indices.end()); + list.variable_indices.erase(std::unique(list.variable_indices.begin(), list.variable_indices.end()), + list.variable_indices.end()); + + std::vector sorted_list; + for (const uint32_t variable_index : list.variable_indices) { + const uint256_t value(builder.get_variable(variable_index)); + sorted_list.push_back(static_cast(value.data[0])); + } + std::sort(sorted_list.begin(), sorted_list.end()); + + constexpr size_t gate_width = Builder::NUM_WIRES; + size_t padding = (gate_width - (list.variable_indices.size() % gate_width)) % gate_width; + if (list.variable_indices.size() <= gate_width) { + padding += gate_width; + } + std::vector indices(padding, builder.zero_idx()); + for (const uint32_t sorted_value : sorted_list) { + const uint32_t index = builder.add_variable(fr(sorted_value)); + builder.real_variable_tags[index] = list.tau_tag; + indices.push_back(index); + } + reference_create_sort_constraint_with_edges(builder, indices, fr(0), fr(list.target_range)); +} + +template void reference_finalize_circuit(Builder& builder) +{ + builder.process_non_native_field_multiplications(); + builder.rom_ram_logic.process_ROM_arrays(&builder); + builder.rom_ram_logic.process_RAM_arrays(&builder); + for (auto& [target_range, list] : builder.range_lists) { + reference_process_range_list(builder, list); + } + builder.populate_public_inputs_block(); + builder.circuit_finalized = true; +} + +template void expect_same_circuit(const Builder& actual, const Builder& expected) +{ + // The base comparison covers variables, copy cycles, tags, tau, gate count, public inputs and failure state. + EXPECT_TRUE(static_cast&>(actual) == + static_cast&>(expected)); + EXPECT_TRUE(actual.get_variables() == expected.get_variables()); + EXPECT_EQ(actual.real_variable_index, expected.real_variable_index); + EXPECT_EQ(actual.real_variable_tags, expected.real_variable_tags); + EXPECT_EQ(actual.num_gates(), expected.num_gates()); + EXPECT_EQ(actual.failed(), expected.failed()); + EXPECT_EQ(actual.err(), expected.err()); + EXPECT_TRUE(actual.range_lists == expected.range_lists); + EXPECT_TRUE(actual.blocks == expected.blocks); + EXPECT_EQ(actual.memory_read_records, expected.memory_read_records); + EXPECT_EQ(actual.memory_write_records, expected.memory_write_records); +} + +struct RangeListSpec { + uint64_t target_range; + // Range-constrained variables created by the circuit; the first two take the values 0 and target_range. + size_t num_entries; + // Entries joined by assert_equal into the variables of the list's initial staircase that share their value. + size_t num_merged_into_staircase = 0; + // Range-constrained copies of earlier entries joined to them by assert_equal. + size_t num_duplicates = 0; + // Entries whose class is joined into a later, untagged variable, which becomes its real variable. + size_t num_relocated = 0; + // Entries with a value above target_range, among them one with a value of more than 64 bits. + size_t num_out_of_range = 0; +}; + +struct CircuitSpec { + std::vector lists; + // Variables created before the lists, which spread the lists' entries over more variables. + size_t num_filler_variables = 0; + bool with_memory = false; + uint64_t seed = 1; +}; + +template void build_circuit(Builder& builder, const CircuitSpec& spec) +{ + std::mt19937_64 rng(spec.seed); + const uint32_t zero = builder.zero_idx(); + for (size_t i = 0; i < spec.num_filler_variables; ++i) { + builder.add_variable(fr(rng())); + } + const auto add_entry = [&](const uint256_t& value, const uint64_t target_range) { + const uint32_t index = builder.add_variable(fr(value)); + builder.create_unconstrained_gate(builder.blocks.arithmetic, index, zero, zero, zero); + builder.create_small_range_constraint(index, target_range, "range list entry"); + return index; + }; + + // The entries of the lists are created interleaved. + std::vector> entries(spec.lists.size()); + size_t max_entries = 0; + for (const auto& list : spec.lists) { + max_entries = std::max(max_entries, list.num_entries); + } + for (size_t k = 0; k < max_entries; ++k) { + for (size_t l = 0; l < spec.lists.size(); ++l) { + const uint64_t target_range = spec.lists[l].target_range; + if (k < spec.lists[l].num_entries) { + const uint64_t value = k == 0 ? 0 : k == 1 ? target_range : rng() % (target_range + 1); + entries[l].push_back(add_entry(value, target_range)); + } + } + } + + for (size_t l = 0; l < spec.lists.size(); ++l) { + const RangeListSpec& list = spec.lists[l]; + // The staircase entries lead the list's indices. + const std::vector staircase = [&] { + const auto& indices = builder.range_lists.at(list.target_range).variable_indices; + return std::vector( + indices.begin(), indices.begin() + static_cast(indices.size() - list.num_entries)); + }(); + for (size_t k = 0; k < std::min(list.num_merged_into_staircase, entries[l].size()); ++k) { + for (const uint32_t stair : staircase) { + if (builder.get_variable(stair) == builder.get_variable(entries[l][k])) { + builder.assert_equal(stair, entries[l][k]); + } + } + } + for (size_t d = 0; d < list.num_duplicates; ++d) { + const uint32_t original = entries[l][rng() % entries[l].size()]; + const uint32_t copy = add_entry(uint256_t(builder.get_variable(original)), list.target_range); + builder.assert_equal(original, copy); + } + for (size_t r = 0; r < list.num_relocated; ++r) { + const uint32_t entry = entries[l][rng() % entries[l].size()]; + const uint32_t holder = builder.add_variable(builder.get_variable(entry)); + builder.create_unconstrained_gate(builder.blocks.arithmetic, holder, zero, zero, zero); + builder.assert_equal(holder, entry); + } + for (size_t o = 0; o < list.num_out_of_range; ++o) { + // 2^64 + 3 passes the registration check, which reads the low 64 bits, and still fails the full-value range + // check of the list's processing. + const uint256_t value = o == 0 ? (uint256_t(1) << 64) + 3 + : o == 1 ? (uint256_t(1) << 40) + 7 + : uint256_t(list.target_range + 1 + (rng() % 5)); + add_entry(value, list.target_range); + } + } + + if (spec.with_memory) { + const size_t rom_id = builder.create_ROM_array(4); + const size_t ram_id = builder.create_RAM_array(4); + for (size_t i = 0; i < 4; ++i) { + builder.set_ROM_element(rom_id, i, builder.add_variable(fr(rng() % 1000))); + builder.init_RAM_element(ram_id, i, builder.add_variable(fr(rng() % 1000))); + } + for (size_t j = 0; j < 12; ++j) { + builder.read_ROM_array(rom_id, builder.add_variable(fr(rng() % 4))); + const uint32_t ram_index = builder.add_variable(fr(rng() % 4)); + if (j % 3 == 0) { + builder.write_RAM_array(ram_id, ram_index, builder.add_variable(fr(rng() % 1000))); + } else { + builder.read_RAM_array(ram_id, ram_index); + } + } + } +} + +template class RangeListProcessing : public ::testing::Test { + protected: + // `expect_failed`: building the circuit records a failure. `expect_valid`: the finalized circuit is satisfied. + static void expect_same_finalization(const CircuitSpec& spec, const bool expect_valid, const bool expect_failed) + { + for (const bool is_write_vk_mode : { false, true }) { + for (const size_t concurrency : concurrencies()) { + SCOPED_TRACE("write_vk_mode " + std::to_string(static_cast(is_write_vk_mode)) + ", concurrency " + + std::to_string(concurrency)); + const ConcurrencyScope scope(concurrency); + auto actual = make_builder(is_write_vk_mode); + auto expected = make_builder(is_write_vk_mode); + build_circuit(actual, spec); + build_circuit(expected, spec); + expect_same_circuit(actual, expected); + EXPECT_EQ(actual.failed(), expect_failed) << actual.err(); + if (expect_valid && !is_write_vk_mode && concurrency == concurrencies().front()) { + EXPECT_TRUE(CircuitChecker::check(actual)); + } + actual.finalize_circuit(); + reference_finalize_circuit(expected); + expect_same_circuit(actual, expected); + } + } + } +}; + +using Builders = ::testing::Types; +TYPED_TEST_SUITE(RangeListProcessing, Builders); + +TYPED_TEST(RangeListProcessing, ListSizesAroundThePadding) +{ + // A range of 0 merged into its staircase leaves one real variable; a range of 1 leaves two plus the unmerged + // entries. Together they cover deduplicated lists of 1 to 9 entries. + for (size_t num_entries = 1; num_entries <= 9; ++num_entries) { + SCOPED_TRACE("entries " + std::to_string(num_entries)); + const CircuitSpec spec{ + .lists = { { .target_range = 0, .num_entries = num_entries, .num_merged_into_staircase = num_entries }, + { .target_range = 1, .num_entries = num_entries, .num_merged_into_staircase = 2 }, + { .target_range = 7, .num_entries = num_entries }, + { .target_range = 1000, .num_entries = num_entries } }, + .seed = num_entries + }; + TestFixture::expect_same_finalization(spec, true, false); + } +} + +TYPED_TEST(RangeListProcessing, DuplicatesAndRelocatedEntries) +{ + const CircuitSpec spec{ + .lists = { { .target_range = 3, .num_entries = 40, .num_duplicates = 30, .num_relocated = 10 }, + { .target_range = 255, + .num_entries = 3000, + .num_merged_into_staircase = 50, + .num_duplicates = 400, + .num_relocated = 300 }, + { .target_range = (1U << 14) - 1, + .num_entries = 2500, + .num_duplicates = 100, + .num_relocated = 100 } }, + .with_memory = true, + .seed = 11 + }; + TestFixture::expect_same_finalization(spec, true, false); +} + +TYPED_TEST(RangeListProcessing, SparseListsAmongManyVariables) +{ + // Lists far smaller than the variable count, next to a dense one. + const CircuitSpec spec{ + .lists = { { .target_range = 7, .num_entries = 20, .num_duplicates = 5, .num_relocated = 5 }, + { .target_range = 100, .num_entries = 200, .num_relocated = 20 }, + { .target_range = 15, .num_entries = 60000, .num_duplicates = 50 } }, + .num_filler_variables = 300000, + .seed = 12 + }; + TestFixture::expect_same_finalization(spec, true, false); +} + +TYPED_TEST(RangeListProcessing, LargeLists) +{ + // Long enough for several chunks in each pass, including several counting chunks for the range of 255. + const CircuitSpec spec{ + .lists = { { .target_range = 255, .num_entries = 140000, .num_duplicates = 2000, .num_relocated = 2000 }, + { .target_range = (1U << 14) - 1, .num_entries = 30000, .num_relocated = 500 }, + { .target_range = (1U << 16) - 1, .num_entries = 2000, .num_duplicates = 20 } }, + .seed = 13 + }; + TestFixture::expect_same_finalization(spec, true, false); +} + +TYPED_TEST(RangeListProcessing, OutOfRangeValues) +{ + const CircuitSpec spec{ + .lists = { { .target_range = 255, .num_entries = 20000, .num_relocated = 100, .num_out_of_range = 6 }, + { .target_range = 9, .num_entries = 7, .num_out_of_range = 3 }, + { .target_range = 1, .num_entries = 2, .num_out_of_range = 1 } }, + .seed = 14 + }; + TestFixture::expect_same_finalization(spec, false, true); + + // The value of more than 64 bits alone passes registration; only the processing of the list sees it out of range. + // The list is sparse among the variables. + const CircuitSpec high_bits_only{ .lists = { { .target_range = 255, .num_entries = 30, .num_out_of_range = 1 } }, + .num_filler_variables = 300000, + .seed = 15 }; + TestFixture::expect_same_finalization(high_bits_only, false, false); +} + +TEST(RangeListProcessingPrimitives, DeltaRangeRowsMatchTheSerialRows) +{ + UltraCircuitBuilder actual; + UltraCircuitBuilder expected; + std::vector indices; + for (uint32_t value = 0; value < 16; ++value) { + indices.push_back(actual.add_variable(fr(value))); + EXPECT_EQ(expected.add_variable(fr(value)), indices.back()); + } + actual.enforce_small_deltas(indices); + reference_enforce_small_deltas(expected, indices); + actual.create_sort_constraint_with_edges(indices, fr(0), fr(15)); + reference_create_sort_constraint_with_edges(expected, indices, fr(0), fr(15)); + expect_same_circuit(actual, expected); +} + +TEST(RangeListProcessingPrimitives, CountingSortAtEveryConcurrency) +{ + std::mt19937_64 rng(21); + for (const uint64_t maximum : { uint64_t{ 3 }, uint64_t{ 255 }, uint64_t{ (1U << 14) - 1 }, uint64_t{ 65535 } }) { + for (const size_t size : { size_t{ 300 }, size_t{ 70000 }, size_t{ 600000 } }) { + std::vector values(size); + for (auto& value : values) { + value = static_cast(rng() % (maximum + 1)); + } + auto expected = values; + std::sort(expected.begin(), expected.end()); + auto out_of_range = values; + out_of_range[(size * 2) / 3] = static_cast(maximum + 1); + for (const size_t concurrency : concurrencies()) { + SCOPED_TRACE("maximum " + std::to_string(maximum) + ", size " + std::to_string(size) + + ", concurrency " + std::to_string(concurrency)); + const ConcurrencyScope scope(concurrency); + auto sorted = values; + if (range_sort::try_counting_sort(sorted, maximum)) { + EXPECT_EQ(sorted, expected); + } else { + EXPECT_LT(size, maximum + 1); + EXPECT_EQ(sorted, values); + } + auto rejected = out_of_range; + EXPECT_FALSE(range_sort::try_counting_sort(rejected, maximum)); + EXPECT_EQ(rejected, out_of_range); + } + } + } +} + +} // namespace +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp index e2905fb..df4b818 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini.hpp @@ -192,16 +192,13 @@ template class GeminiProver_ { batch(batched_to_be_shifted_by_one, to_be_shifted_by_one); } - // 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); + // A₀[i] = F[i] + G[i + 1], written in one pass. Coefficients from actual_data_size_ on are zero and stay + // virtual, so the folds and their commitments cover only the data extent. + Polynomial full_batched(actual_data_size_, full_batched_size, Polynomial::DontZeroMemory::FLAG); parallel_for_heuristic( - full_batched_size, + actual_data_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; diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_data_extent.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_data_extent.test.cpp new file mode 100644 index 0000000..34c13b3 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/gemini/gemini_data_extent.test.cpp @@ -0,0 +1,70 @@ +#include "barretenberg/commitment_schemes/gemini/gemini.hpp" +#include "barretenberg/commitment_schemes/kzg/kzg.hpp" +#include "barretenberg/commitment_schemes/pcs_test_utils.hpp" +#include "barretenberg/commitment_schemes/shplonk/shplemini.hpp" +#include "barretenberg/commitment_schemes/small_subgroup_ipa/small_subgroup_ipa_utils.hpp" +#include "barretenberg/ecc/curves/bn254/bn254.hpp" +#include "barretenberg/transcript/transcript.hpp" + +#include +#include +#include +#include + +// A₀ backed on the data extent against the same claims batched without one (A₀ zero-filled to the dyadic size): the +// serialised proof (fold commitments and evaluations, Shplonk and KZG commitments) must be identical, for short, odd +// and full extents, a shifted source, a source only on the masking rows 1-3, with and without virtual rounds and ZK +// claims. +TEST(GeminiDataExtent, BatchMatchesZeroPaddedProof) +{ + using Curve = bb::curve::BN254; + using FF = bb::fr; + using Polynomial = bb::Polynomial; + using PolynomialBatcher = bb::GeminiProver_::PolynomialBatcher; + constexpr size_t log_n = 5; + constexpr size_t n = 1UL << log_n; + const auto ck = bb::create_commitment_key>(2 * n); + + // The grand-sum slot is opened at 1 against 0, so it is (X - 1) q(X). + std::array libra = { Polynomial::random(8), + Polynomial(8), + Polynomial::random(8) }; + const Polynomial q = Polynomial::random(7); + libra[1].at(0) = -q[0]; + for (size_t i = 1; i < 7; ++i) { + libra[1].at(i) = q[i - 1] - q[i]; + } + libra[1].at(7) = q[6]; + + for (const size_t extent : { size_t{ 3 }, size_t{ 4 }, size_t{ 17 }, size_t{ 31 }, n }) { + std::vector polys; + polys.push_back(Polynomial::random(extent, n, 0)); + polys.push_back(Polynomial::random(std::min(extent, 4) - 1, n, 1)); + polys.push_back(Polynomial::random(extent - 1, n, 1)); + for (const size_t virtual_log_n : { log_n, log_n + 2 }) { + for (const bool zk : { false, true }) { + std::vector challenge(virtual_log_n); + for (auto& u : challenge) { + u = FF::random_element(); + } + auto prove = [&](size_t data_extent) { + PolynomialBatcher batcher(n, data_extent); + batcher.set_unshifted(bb::RefVector(polys)); + batcher.set_to_be_shifted_by_one(bb::RefVector(polys[2])); + auto transcript = bb::NativeTranscript::test_prover_init_empty(); + const auto claim = bb::ShpleminiProver_::prove( + n, + batcher, + challenge, + ck, + transcript, + zk ? libra : std::array{}); + bb::KZG::compute_opening_proof(ck, claim, transcript); + return transcript->export_proof(); + }; + EXPECT_EQ(prove(extent), prove(n)) + << "extent " << extent << ", virtual_log_n " << virtual_log_n << ", zk " << zk; + } + } + } +} diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp index dd458c5..7991dda 100644 --- a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa.hpp @@ -10,6 +10,7 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/container.hpp" +#include "barretenberg/common/deferred_value.hpp" #include "barretenberg/common/thread.hpp" #include "barretenberg/common/throw_or_abort.hpp" #include "barretenberg/constants.hpp" @@ -19,13 +20,75 @@ #include "barretenberg/stdlib/honk_verifier/ipa_accumulator.hpp" #include "barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp" #include "barretenberg/transcript/transcript.hpp" +#include +#include #include #include +#include +#include #include #include #include namespace bb { +template struct IpaOpeningProofTask; + +namespace detail { +// batch_two_round_fold's scratch is proportional to its number of output points, so the SRS fold is cut into blocks. +inline constexpr size_t SRS_FOLD_BLOCK = 2048; + +/** + * @brief Folds an SRS two IPA rounds at once, in place: for q = G.size() / 4 and every i < q, + * G[i] ← u1·u2·G[i] + u1·G[i+q] + u2·G[i+2q] + G[i+3q]. + * @details Calls `Curve::Element::batch_two_round_fold` on at most `block` output points at a time, so the fold's + * scratch memory is proportional to `block` rather than to q. Each output point depends only on its four inputs and + * the challenges, so the result is that of a single call on the whole span. Entries [q, 4q) are left unchanged. + * @param G 4q affine points, none at infinity; q need not be a power of two. + * @param u1 First-round challenge, below 2^127. + * @param u2 Second-round challenge, below 2^127. + * @param block Maximum number of output points per fold call; must be positive. + */ +template +void two_round_fold_srs(std::span G, + const typename Curve::ScalarField& u1, + const typename Curve::ScalarField& u2, + size_t block = SRS_FOLD_BLOCK) +{ + using Commitment = typename Curve::AffineElement; + using GroupElement = typename Curve::Element; + BB_ASSERT_EQ(G.size() % 4, 0U, "the two-round SRS fold needs four equal quarters"); + BB_ASSERT_GT(block, 0U, "the SRS fold block must hold at least one output point"); + const size_t quarter = G.size() / 4; + + if (quarter <= block) { + auto G_folded = + GroupElement::batch_two_round_fold(std::span{ G.data(), 4 * quarter }, u1, u2); + parallel_for_heuristic( + quarter, [&](size_t idx) { G[idx] = G_folded[idx]; }, thread_heuristics::FF_COPY_COST * 2); + return; + } + + std::vector block_inputs(4 * block); + for (size_t start = 0; start < quarter; start += block) { + const size_t len = std::min(block, quarter - start); + parallel_for_heuristic( + len, + [&](size_t idx) { + for (size_t k = 0; k < 4; ++k) { + block_inputs[(k * len) + idx] = G[(k * quarter) + start + idx]; + } + }, + thread_heuristics::FF_COPY_COST * 8); + auto G_folded = + GroupElement::batch_two_round_fold(std::span{ block_inputs.data(), 4 * len }, u1, u2); + // Writing G[start, start + len) in place is safe: later blocks read only G[s, s + len') for s ≥ start + len + // and entries of the quarters [q, 4q), which are never written. + parallel_for_heuristic( + len, [&](size_t idx) { G[start + idx] = G_folded[idx]; }, thread_heuristics::FF_COPY_COST * 2); + } +} +} // namespace detail + /** * @brief IPA (inner product argument) commitment scheme class. * @@ -98,6 +161,8 @@ template class IPA // accumulation claim. using VerifierAccumulator = stdlib::recursion::honk::IpaAccumulator; + using OpeningProofTask = IpaOpeningProofTask; + /** * @brief Deferred native IPA verification state — the native counterpart of `VerifierAccumulator`. * @details The cheap IPA group relation has been checked against the prover-claimed commitment to the challenge @@ -366,10 +431,7 @@ template class IPA // Step 6.e, fused: G_vec_new[i] = u1·u2·G[i] + u1·G[i+q] + u2·G[i+2q] + G[i+3q]. // Round challenges are 127-bit limbs (transcript split_challenge); batch_two_round_fold // BB_ASSERTs that precondition. - auto G_folded = GroupElement::batch_two_round_fold( - std::span{ G_vec_local.data(), 4 * quarter }, u1, u2); - parallel_for_heuristic( - quarter, [&](size_t idx) { G_vec_local[idx] = G_folded[idx]; }, thread_heuristics::FF_COPY_COST * 2); + detail::two_round_fold_srs(std::span{ G_vec_local.data(), 4 * quarter }, u1, u2); round_size = quarter; round_idx += 2; @@ -412,6 +474,20 @@ template class IPA // calling the `send_to_verifier` method, as the verifier knows them. const auto commitment = ck.commit(polynomial); + add_claim_to_hash_buffer(commitment, opening_claim, transcript); + } + + /** + * @brief Add the opening claim to the hash buffer, given the commitment to its polynomial. + * + * @param commitment Must equal `ck.commit(opening_claim.polynomial)`; the hash buffer is then the same as with the + * overload that computes it. + */ + template + static void add_claim_to_hash_buffer(const Commitment& commitment, + const ProverOpeningClaim& opening_claim, + const std::shared_ptr& transcript) + { transcript->add_to_hash_buffer("IPA:commitment", commitment); transcript->add_to_hash_buffer("IPA:challenge", opening_claim.opening_pair.challenge); transcript->add_to_hash_buffer("IPA:evaluation", opening_claim.opening_pair.evaluation); @@ -736,6 +812,22 @@ template class IPA compute_opening_proof_internal(ck, opening_claim, transcript); } + /** + * @brief Compute an IPA opening proof for a caller that already holds the commitment to the polynomial. + * + * @param commitment Must equal `ck.commit(opening_claim.polynomial)`; the proof is then identical to the one from + * the overload that computes it, without its MSM. + */ + template + static void compute_opening_proof(const CK& ck, + const ProverOpeningClaim& opening_claim, + const Commitment& commitment, + const std::shared_ptr& transcript) + { + add_claim_to_hash_buffer(commitment, opening_claim, transcript); + compute_opening_proof_internal(ck, opening_claim, transcript); + } + /** * @brief Natively verify the correctness of an IPA Proof * @@ -999,28 +1091,34 @@ template class IPA } /** - * @brief Prove a native IPA opening of `challenge_poly` at the (challenge, evaluation) carried by `output_claim`, - * returning `output_claim` paired with the generated proof. Shared tail of `accumulate` and - * `prove_accumulator_claim`. + * @brief Run the native opening proof of a deferred (claim, proof task) pair on the calling thread. */ - static std::pair, HonkProof> prove_challenge_poly_opening( - const CommitmentKey& ck, - OpeningClaim output_claim, - const Polynomial& challenge_poly) + static std::pair, HonkProof> prove_now( + std::pair, OpeningProofTask> deferred) + { + HonkProof proof = deferred.second.prove(); + return { std::move(deferred.first), std::move(proof) }; + } + + /** + * @brief Set up the native IPA opening of `challenge_poly` at the (challenge, evaluation) carried by + * `output_claim`, returning `output_claim` paired with the task that proves it. Shared tail of + * `accumulate_deferred` and `prove_accumulator_claim_deferred`. + */ + static std::pair, OpeningProofTask> defer_challenge_poly_opening( + const CommitmentKey& ck, OpeningClaim output_claim, Polynomial challenge_poly) requires Curve::is_stdlib_type { using NativeCurve = curve::Grumpkin; - auto prover_transcript = std::make_shared(); const OpeningPair opening_pair{ bb::fq(output_claim.opening_pair.challenge.get_value()), bb::fq(output_claim.opening_pair.evaluation.get_value()) }; BB_ASSERT_EQ(challenge_poly.evaluate(opening_pair.challenge), opening_pair.evaluation, "Opening claim does not hold for challenge polynomial."); - IPA::compute_opening_proof( - ck, { challenge_poly, opening_pair }, prover_transcript); output_claim.opening_pair.evaluation.self_reduce(); - return { output_claim, prover_transcript->export_proof() }; + return { std::move(output_claim), + OpeningProofTask{ ck, { std::move(challenge_poly), opening_pair }, std::nullopt } }; } /** @@ -1036,6 +1134,18 @@ template class IPA VerifierAccumulator verifier_accumulator_1, VerifierAccumulator verifier_accumulator_2) requires Curve::is_stdlib_type + { + return prove_now(accumulate_deferred(ck, std::move(verifier_accumulator_1), std::move(verifier_accumulator_2))); + } + + /** + * @brief `accumulate` with the native opening proof returned as a task instead of computed. + */ + static std::pair, OpeningProofTask> accumulate_deferred( + const CommitmentKey& ck, + VerifierAccumulator verifier_accumulator_1, + VerifierAccumulator verifier_accumulator_2) + requires Curve::is_stdlib_type { static_assert(IsAnyOf); @@ -1067,7 +1177,7 @@ template class IPA Polynomial challenge_poly = create_challenge_poly(native_u_challenges_inv_1, native_u_challenges_inv_2, bb::fq(alpha.get_value())); - return prove_challenge_poly_opening(ck, std::move(output_claim), challenge_poly); + return defer_challenge_poly_opening(ck, std::move(output_claim), std::move(challenge_poly)); } /** @@ -1080,6 +1190,16 @@ template class IPA static std::pair, HonkProof> prove_accumulator_claim(const CommitmentKey& ck, VerifierAccumulator verifier_accumulator) requires Curve::is_stdlib_type + { + return prove_now(prove_accumulator_claim_deferred(ck, std::move(verifier_accumulator))); + } + + /** + * @brief `prove_accumulator_claim` with the native opening proof returned as a task instead of computed. + */ + static std::pair, OpeningProofTask> prove_accumulator_claim_deferred( + const CommitmentKey& ck, VerifierAccumulator verifier_accumulator) + requires Curve::is_stdlib_type { static_assert(IsAnyOf); @@ -1100,7 +1220,7 @@ template class IPA Polynomial challenge_poly = construct_poly_from_u_challenges_inv(std::span(native_u_challenges_inv)); - return prove_challenge_poly_opening(ck, std::move(output_claim), challenge_poly); + return defer_challenge_poly_opening(ck, std::move(output_claim), std::move(challenge_poly)); } /** @@ -1167,32 +1287,111 @@ template class IPA return all_relations_succeeded; } + /** + * @brief Draw the random polynomial, then the random evaluation point, opened by + * create_random_valid_ipa_claim_and_proof. + * @details Separate from the proving so that a caller can reproduce the draws without proving. + */ + static std::pair, bb::fq> sample_random_opening(numeric::RNG* engine = nullptr) + requires Curve::is_stdlib_type + { + if (engine == nullptr) { + engine = &numeric::get_randomness(); + } + // Each coefficient is bb::fq::random_element(engine): the engine is read serially, in the same order (lo then + // hi per coefficient), and only the conversion of the drawn words into field elements runs in parallel. + constexpr bb::fq pow_2_256 = bb::fq(uint256_t(1) << 128).sqr(); + constexpr size_t block_size = std::min(poly_length, size_t{ 1 } << 12); + Polynomial poly(poly_length); + std::vector> draws(block_size); + for (size_t start = 0; start < poly_length; start += block_size) { + for (auto& [lo, hi] : draws) { + lo = engine->get_random_uint256(); + hi = engine->get_random_uint256(); + } + parallel_for_heuristic( + block_size, + [&](size_t k) { poly.at(start + k) = bb::fq(draws[k][0]) + (pow_2_256 * bb::fq(draws[k][1])); }, + thread_heuristics::FF_MULTIPLICATION_COST * 4); + } + const bb::fq x = bb::fq::random_element(engine); + return { std::move(poly), x }; + } + static std::pair, HonkProof> create_random_valid_ipa_claim_and_proof( UltraCircuitBuilder& builder) requires Curve::is_stdlib_type + { + const auto [poly, x] = sample_random_opening(); + return create_valid_ipa_claim_and_proof(builder, poly, x); + } + + /** + * @brief Natively prove the opening of poly at x and add the claim to the builder as witnesses. + */ + static std::pair, HonkProof> create_valid_ipa_claim_and_proof(UltraCircuitBuilder& builder, + const Polynomial& poly, + const bb::fq& x) + requires Curve::is_stdlib_type + { + return prove_now(create_valid_ipa_claim_deferred(builder, poly, x)); + } + + /** + * @brief `create_valid_ipa_claim_and_proof` with the native opening proof returned as a task instead of computed. + */ + static std::pair, OpeningProofTask> create_valid_ipa_claim_deferred( + UltraCircuitBuilder& builder, const Polynomial& poly, const bb::fq& x) + requires Curve::is_stdlib_type { using NativeCurve = curve::Grumpkin; using Builder = typename Curve::Builder; using Curve = stdlib::grumpkin; - auto ipa_transcript = std::make_shared(); + // Built on the calling thread rather than by the task: the global CRS factory is not safe to use concurrently. CommitmentKey ipa_commitment_key(poly_length); - size_t n = poly_length; - auto poly = Polynomial(n); - for (size_t i = 0; i < n; i++) { - poly.at(i) = bb::fq::random_element(); - } - bb::fq x = bb::fq::random_element(); bb::fq eval = poly.evaluate(x); auto commitment = ipa_commitment_key.commit(poly); const OpeningPair opening_pair = { x, eval }; - IPA::compute_opening_proof(ipa_commitment_key, { poly, opening_pair }, ipa_transcript); auto stdlib_comm = Curve::Group::from_witness(&builder, commitment); auto stdlib_x = Curve::ScalarField::from_witness(&builder, x); auto stdlib_eval = Curve::ScalarField::from_witness(&builder, eval); OpeningClaim stdlib_opening_claim{ { stdlib_x, stdlib_eval }, stdlib_comm }; - return { stdlib_opening_claim, ipa_transcript->export_proof() }; + return { stdlib_opening_claim, + OpeningProofTask{ std::move(ipa_commitment_key), { poly, opening_pair }, commitment } }; + } +}; + +/** + * @brief A native IPA opening proof whose inputs are fixed but which has not been computed yet. + * @details Owns everything it reads, draws no randomness and touches no circuit builder, so it can be proven on any + * thread. + */ +template struct IpaOpeningProofTask { + CommitmentKey ck; + ProverOpeningClaim claim; + // The commitment to claim.polynomial when the caller already holds it, so that the prover need not recompute it. + std::optional commitment; + + HonkProof prove() const + { + using NativeIPA = IPA; + auto transcript = std::make_shared(); + if (commitment.has_value()) { + NativeIPA::compute_opening_proof(ck, claim, *commitment, transcript); + } else { + NativeIPA::compute_opening_proof(ck, claim, transcript); + } + return transcript->export_proof(); + } + + /** + * @brief Compute the proof on a background thread. + */ + DeferredValue launch() && + { + return DeferredValue::launch([task = std::move(*this)] { return task.prove(); }); } }; diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa_known_commitment.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa_known_commitment.test.cpp new file mode 100644 index 0000000..3b55878 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa_known_commitment.test.cpp @@ -0,0 +1,28 @@ +#include "barretenberg/commitment_schemes/ipa/ipa.hpp" +#include "barretenberg/commitment_schemes/pcs_test_utils.hpp" + +#include + +using namespace bb; + +TEST(IPAKnownCommitment, ProofEqualsProofWithRecomputedCommitment) +{ + using Curve = curve::Grumpkin; + using Fr = Curve::ScalarField; + constexpr size_t log_n = 7; + constexpr size_t n = 1UL << log_n; + using PCS = IPA; + + const auto ck = create_commitment_key>(n); + const auto poly = bb::Polynomial::random(n); + const Fr x = Fr::random_element(); + const ProverOpeningClaim claim{ poly, { x, poly.evaluate(x) } }; + + auto recomputing_transcript = std::make_shared(); + PCS::compute_opening_proof(ck, claim, recomputing_transcript); + + auto known_commitment_transcript = std::make_shared(); + PCS::compute_opening_proof(ck, claim, ck.commit(poly), known_commitment_transcript); + + EXPECT_EQ(known_commitment_transcript->export_proof(), recomputing_transcript->export_proof()); +} diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa_srs_fold.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa_srs_fold.test.cpp new file mode 100644 index 0000000..6004f3c --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes/ipa/ipa_srs_fold.test.cpp @@ -0,0 +1,149 @@ +#include "barretenberg/commitment_schemes/ipa/ipa.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" + +#include +#include +#include + +using namespace bb; + +namespace { +using Curve = curve::Grumpkin; +using Fq = Curve::BaseField; +using Fr = Curve::ScalarField; +using Element = Curve::Element; +using Commitment = Curve::AffineElement; + +// IPA round challenges are 127-bit transcript limbs, and batch_two_round_fold asserts that bound. +Fr random_127_bit_challenge() +{ + uint256_t challenge = Fr::random_element(); + challenge.data[1] &= 0x7FFFFFFFFFFFFFFFULL; + challenge.data[2] = 0; + challenge.data[3] = 0; + return Fr(challenge); +} + +// Independent random points: four of them satisfy a relation that makes the fold add equal or opposite points only with +// negligible probability. Only the x draws use the shared RNG, which is not thread-safe; the square roots, the bulk of +// the cost, run in parallel. +std::vector random_points(size_t num_points) +{ + std::vector xs(num_points); + for (auto& x : xs) { + x = Fq::random_element(); + } + std::vector points(num_points); + parallel_for_range(num_points, [&](size_t start, size_t end) { + for (size_t i = start; i < end; ++i) { + const bool sign_bit = (i & 1) != 0; + Fq x = xs[i]; + std::optional point = Commitment::derive_from_x_coordinate(x, sign_bit); + while (!point.has_value()) { + x += Fq::one(); + point = Commitment::derive_from_x_coordinate(x, sign_bit); + } + points[i] = *point; + } + }); + return points; +} + +// EXPECT_EQ on affine points compares coordinate values: the same point can be held in a coarse-reduced form whose +// limbs differ. +void expect_same_points(const std::vector& actual, const std::vector& expected, size_t count) +{ + ASSERT_GE(actual.size(), count); + ASSERT_GE(expected.size(), count); + for (size_t i = 0; i < count; ++i) { + EXPECT_EQ(actual[i], expected[i]) << "index " << i; + } +} + +void check_blocked_fold_matches_single_call(size_t quarter, size_t block) +{ + SCOPED_TRACE(testing::Message() << "quarter " << quarter << ", block " << block); + const std::vector srs = random_points(4 * quarter); + const Fr u1 = random_127_bit_challenge(); + const Fr u2 = random_127_bit_challenge(); + + const std::vector expected = Element::batch_two_round_fold(srs, u1, u2); + ASSERT_EQ(expected.size(), quarter); + + std::vector folded = srs; + detail::two_round_fold_srs(folded, u1, u2, block); + + expect_same_points(folded, expected, quarter); + for (size_t i = quarter; i < 4 * quarter; ++i) { + EXPECT_EQ(folded[i], srs[i]) << "untouched index " << i; + } +} + +class ConcurrencyGuard { + public: + ConcurrencyGuard() = default; + ConcurrencyGuard(const ConcurrencyGuard&) = delete; + ConcurrencyGuard(ConcurrencyGuard&&) = delete; + ConcurrencyGuard& operator=(const ConcurrencyGuard&) = delete; + ConcurrencyGuard& operator=(ConcurrencyGuard&&) = delete; + ~ConcurrencyGuard() { set_parallel_for_concurrency(saved_); } + + private: + size_t saved_ = get_num_cpus(); +}; +} // namespace + +TEST(IpaSrsFold, BlockedFoldMatchesSingleCall) +{ + constexpr size_t block = 8; + check_blocked_fold_matches_single_call(1, block); + check_blocked_fold_matches_single_call(5, block); + check_blocked_fold_matches_single_call(block, block); + check_blocked_fold_matches_single_call(block + 1, block); + check_blocked_fold_matches_single_call(4 * block, block); + check_blocked_fold_matches_single_call(61, block); +} + +TEST(IpaSrsFold, DefaultBlockMatchesSingleCall) +{ + check_blocked_fold_matches_single_call(64, detail::SRS_FOLD_BLOCK); +} + +TEST(IpaSrsFold, DefaultBlockJustAboveOneBlockMatchesSingleCall) +{ + check_blocked_fold_matches_single_call(detail::SRS_FOLD_BLOCK + 1, detail::SRS_FOLD_BLOCK); +} + +// The first fold of a Grumpkin IPA opening, whose only size is 2^CONST_ECCVM_LOG_N points. +TEST(IpaSrsFold, DefaultBlockAtTheFirstProductionFoldMatchesSingleCall) +{ + check_blocked_fold_matches_single_call((size_t{ 1 } << CONST_ECCVM_LOG_N) / 4, detail::SRS_FOLD_BLOCK); +} + +#ifndef NO_MULTITHREADING +// batch_two_round_fold splits its batched inversions by thread ranges, so the split differs between thread counts. +TEST(IpaSrsFold, SameResultAtDifferentThreadCounts) +{ + constexpr size_t quarter = 100; + const std::vector srs = random_points(4 * quarter); + const Fr u1 = random_127_bit_challenge(); + const Fr u2 = random_127_bit_challenge(); + const std::vector expected = Element::batch_two_round_fold(srs, u1, u2); + + for (const size_t block : { size_t{ 32 }, detail::SRS_FOLD_BLOCK }) { + SCOPED_TRACE(testing::Message() << "block " << block); + std::vector one_thread = srs; + std::vector five_threads = srs; + { + const ConcurrencyGuard guard; + set_parallel_for_concurrency(1); + detail::two_round_fold_srs(one_thread, u1, u2, block); + set_parallel_for_concurrency(5); + detail::two_round_fold_srs(five_threads, u1, u2, block); + } + expect_same_points(one_thread, five_threads, quarter); + expect_same_points(one_thread, expected, quarter); + } +} +#endif diff --git a/barretenberg/cpp/src/barretenberg/commitment_schemes_recursion/ipa_sample_random_opening.test.cpp b/barretenberg/cpp/src/barretenberg/commitment_schemes_recursion/ipa_sample_random_opening.test.cpp new file mode 100644 index 0000000..9e2fb00 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/commitment_schemes_recursion/ipa_sample_random_opening.test.cpp @@ -0,0 +1,51 @@ +#include "barretenberg/commitment_schemes/ipa/ipa.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/stdlib/primitives/curves/grumpkin.hpp" +#include + +using namespace bb; + +namespace { +template void check_matches_serial_draws() +{ + using RecursiveIPA = IPA, log_n>; + constexpr size_t n = size_t{ 1 } << log_n; + constexpr uint64_t seed = 0x5eed; + + // Reference: the engine read one bb::fq::random_element at a time, then the next raw draw. + auto& engine = numeric::get_debug_randomness(/*reset=*/true, seed); + std::vector expected_coefficients(n); + for (auto& coefficient : expected_coefficients) { + coefficient = fq::random_element(&engine); + } + const fq expected_x = fq::random_element(&engine); + const uint64_t expected_next = engine.get_random_uint64(); + + const size_t original_concurrency = get_num_cpus(); + for (const size_t concurrency : { size_t{ 1 }, size_t{ 3 }, size_t{ 16 } }) { + set_parallel_for_concurrency(concurrency); + numeric::get_debug_randomness(/*reset=*/true, seed); + const auto [poly, x] = RecursiveIPA::sample_random_opening(&engine); + ASSERT_EQ(poly.size(), n); + for (size_t i = 0; i < n; ++i) { + ASSERT_EQ(poly[i], expected_coefficients[i]) << "concurrency " << concurrency << ", index " << i; + } + EXPECT_EQ(x, expected_x); + EXPECT_EQ(engine.get_random_uint64(), expected_next) << "engine state after sampling differs"; + } + set_parallel_for_concurrency(original_concurrency); +} +} // namespace + +// The sampled opening must equal the serial random_element draws, in order, at any parallel_for concurrency, and leave +// the engine where the serial draws leave it. +TEST(IPASampleRandomOpening, MatchesSerialDrawsRollupSize) +{ + check_matches_serial_draws(); +} + +TEST(IPASampleRandomOpening, MatchesSerialDrawsBelowOneBlock) +{ + check_matches_serial_draws<3>(); +} diff --git a/barretenberg/cpp/src/barretenberg/common/address_space_reserve.hpp b/barretenberg/cpp/src/barretenberg/common/address_space_reserve.hpp new file mode 100644 index 0000000..438c591 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/address_space_reserve.hpp @@ -0,0 +1,119 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#if defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(hwaddress_sanitizer) || __has_feature(memory_sanitizer) || \ + __has_feature(thread_sanitizer) +#define BB_ADDRESS_SPACE_SANITIZED 1 +#endif +#endif +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_HWADDRESS__) || defined(__SANITIZE_THREAD__) +#define BB_ADDRESS_SPACE_SANITIZED 1 +#endif + +// Reservation needs 64-bit Linux with glibc, exceptions, and none of the address, hwaddress, memory and thread +// sanitizers, whose allocators can abort on a failed allocation instead of throwing. +#if defined(__linux__) && defined(__GLIBC__) && !defined(__wasm__) && UINTPTR_MAX == UINT64_MAX && \ + defined(__cpp_exceptions) && !defined(BB_NO_EXCEPTIONS) && !defined(BB_ADDRESS_SPACE_SANITIZED) +#define BB_ADDRESS_SPACE_RESERVE 1 +#include +#include +#include +#endif + +namespace bb { + +struct AddressSpaceFacts { + std::optional overcommit_mode; // /proc/sys/vm/overcommit_memory; nullopt when unreadable + bool address_space_unlimited = false; + bool allocator_env_set = false; // MALLOC_PERTURB_ or GLIBC_TUNABLES is in the environment +}; + +/** + * @brief Heuristic (0) or always (1) overcommit, no RLIMIT_AS, and no allocator settings in the environment. Otherwise + * a reservation is charged against the budget of every later real allocation, or the environment configures the + * allocator (perturbation writes every block it hands out). None of these facts is read from the input. + */ +constexpr bool address_space_reservation_policy(const AddressSpaceFacts& facts) noexcept +{ + return facts.overcommit_mode.has_value() && (*facts.overcommit_mode == 0 || *facts.overcommit_mode == 1) && + facts.address_space_unlimited && !facts.allocator_env_set; +} + +#ifdef BB_ADDRESS_SPACE_RESERVE +namespace address_space_detail { + +inline std::optional read_overcommit_mode() noexcept +{ + const int fd = ::open("/proc/sys/vm/overcommit_memory", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return std::nullopt; + } + char text[8] = {}; + const ssize_t length = ::read(fd, text, sizeof(text)); + ::close(fd); + if (length < 1 || text[0] < '0' || text[0] > '9' || (length > 1 && text[1] != '\n')) { + return std::nullopt; + } + return text[0] - '0'; +} + +inline bool address_space_unlimited() noexcept +{ + rlimit limit{}; + return ::getrlimit(RLIMIT_AS, &limit) == 0 && limit.rlim_cur == RLIM_INFINITY; +} + +} // namespace address_space_detail +#endif + +/** + * @brief address_space_reservation_policy over this process's facts, read once, at the first call: later changes to + * RLIMIT_AS, the overcommit sysctl or the environment are not seen. Always false where reservation is compiled out. + */ +inline bool address_space_reservation_allowed() noexcept +{ +#ifdef BB_ADDRESS_SPACE_RESERVE + static const bool allowed = address_space_reservation_policy( + { .overcommit_mode = address_space_detail::read_overcommit_mode(), + .address_space_unlimited = address_space_detail::address_space_unlimited(), + .allocator_env_set = std::getenv("MALLOC_PERTURB_") != nullptr || std::getenv("GLIBC_TUNABLES") != nullptr }); + return allowed; +#else + return false; +#endif +} + +/** + * @brief Reserves `capacity` elements in each of `vecs`, in order, all or nothing; false, touching nothing, when any + * of them already has capacity. + * @details On std::bad_alloc or std::length_error every vector is left empty with zero capacity and false returned: + * neither exception escapes, and nothing reserved stays allocated. Where reservation is compiled out, returns false. + */ +template +bool try_reserve_address_space([[maybe_unused]] size_t capacity, [[maybe_unused]] Vectors&... vecs) +{ +#ifdef BB_ADDRESS_SPACE_RESERVE + if (((vecs.capacity() != 0) || ...)) { + return false; + } + try { + (vecs.reserve(capacity), ...); + return true; + } catch (const std::bad_alloc&) { // NOLINT(bugprone-empty-catch): released below + } catch (const std::length_error&) { // NOLINT(bugprone-empty-catch): released below + } + (Vectors(vecs.get_allocator()).swap(vecs), ...); + return false; +#else + return false; +#endif +} + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/address_space_reserve.test.cpp b/barretenberg/cpp/src/barretenberg/common/address_space_reserve.test.cpp new file mode 100644 index 0000000..b62ebc9 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/address_space_reserve.test.cpp @@ -0,0 +1,107 @@ +#include "barretenberg/common/address_space_reserve.hpp" + +#include +#include +#include +#include +#include +#include +#include + +using namespace bb; + +#ifdef BB_ADDRESS_SPACE_RESERVE +namespace { + +// Throws std::bad_alloc for any allocation above BUDGET_BYTES. +template struct BudgetAllocator { + static constexpr size_t BUDGET_BYTES = 2048; + using value_type = T; + BudgetAllocator() = default; + template BudgetAllocator(const BudgetAllocator& /*other*/) noexcept {} + T* allocate(size_t n) + { + if (n > BUDGET_BYTES / sizeof(T)) { + throw std::bad_alloc(); + } + return std::allocator{}.allocate(n); + } + void deallocate(T* p, size_t n) noexcept { std::allocator{}.deallocate(p, n); } + bool operator==(const BudgetAllocator& /*other*/) const noexcept { return true; } +}; + +} // namespace +#endif + +TEST(AddressSpaceReserve, PolicyNeedsEveryFact) +{ + const std::array, 6> rows{ { + { { 0, true, false }, true }, + { { 1, true, false }, true }, + { { 2, true, false }, false }, + { { std::nullopt, true, false }, false }, + { { 0, false, false }, false }, + { { 0, true, true }, false }, + } }; + for (const auto& [facts, allowed] : rows) { + EXPECT_EQ(address_space_reservation_policy(facts), allowed); + } +} + +TEST(AddressSpaceReserve, RefusalReleasesEveryVector) +{ +#ifdef BB_ADDRESS_SPACE_RESERVE + using Narrow = std::vector>; + Narrow a; + Narrow b; + Narrow c; + Narrow d; + std::vector> wide; + // 512 entries fit the budget as uint32_t, not as uint64_t. + EXPECT_FALSE(try_reserve_address_space(512, a, b, c, d, wide)); + EXPECT_EQ((std::array{ a.capacity(), b.capacity(), c.capacity(), d.capacity(), wide.capacity() }), + (std::array{})); + a.reserve(64); + b.reserve(64); + c.reserve(64); + d.reserve(64); + wide.reserve(64); + EXPECT_GE(std::min({ a.capacity(), b.capacity(), c.capacity(), d.capacity(), wide.capacity() }), 64U); + + Narrow e; + std::vector> f; + EXPECT_TRUE(try_reserve_address_space(256, e, f)); + EXPECT_TRUE(e.capacity() >= 256 && f.capacity() >= 256); +#else + GTEST_SKIP() << "address-space reservation is compiled out"; +#endif +} + +TEST(AddressSpaceReserve, RefusesVectorsThatHaveCapacity) +{ + std::vector empty; + std::vector filled{ 1, 2, 3 }; + const size_t filled_capacity = filled.capacity(); + EXPECT_FALSE(try_reserve_address_space(512, empty, filled)); + EXPECT_EQ(empty.capacity(), 0U); + EXPECT_EQ(filled.capacity(), filled_capacity); + EXPECT_EQ(filled, (std::vector{ 1, 2, 3 })); +} + +TEST(AddressSpaceReserve, AllowedReadsThisProcess) +{ +#ifdef BB_ADDRESS_SPACE_RESERVE + AddressSpaceFacts facts; + std::ifstream overcommit("/proc/sys/vm/overcommit_memory"); + int mode = 0; + if (overcommit >> mode) { + facts.overcommit_mode = mode; + } + rlimit limit{}; + facts.address_space_unlimited = ::getrlimit(RLIMIT_AS, &limit) == 0 && limit.rlim_cur == RLIM_INFINITY; + facts.allocator_env_set = std::getenv("MALLOC_PERTURB_") != nullptr || std::getenv("GLIBC_TUNABLES") != nullptr; + EXPECT_EQ(address_space_reservation_allowed(), address_space_reservation_policy(facts)); +#else + EXPECT_FALSE(address_space_reservation_allowed()); +#endif +} diff --git a/barretenberg/cpp/src/barretenberg/common/debug_log.hpp b/barretenberg/cpp/src/barretenberg/common/debug_log.hpp index ef06822..a6969c8 100644 --- a/barretenberg/cpp/src/barretenberg/common/debug_log.hpp +++ b/barretenberg/cpp/src/barretenberg/common/debug_log.hpp @@ -67,8 +67,8 @@ std::string _summarize(const T* x) */ template void _debug_log(const char* func_name, const char* arg_string, const FuncArgs&... args) { - // shut off recursive DEBUG_LOG - static size_t debug_log_calls = 0; + // shut off recursive DEBUG_LOG; per thread, since threads log concurrently + static thread_local size_t debug_log_calls = 0; if (debug_log_calls > 0) { return; } diff --git a/barretenberg/cpp/src/barretenberg/common/deferred_value.hpp b/barretenberg/cpp/src/barretenberg/common/deferred_value.hpp new file mode 100644 index 0000000..de14dbd --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/deferred_value.hpp @@ -0,0 +1,136 @@ +#pragma once +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/thread.hpp" +#include +#include +#include +#include +#include + +// wasm runs inline even with threads: its parallel_for pool is one process-wide pool, not one per calling thread. +#if !defined(NO_MULTITHREADING) && !defined(__wasm__) +#define BB_DEFERRED_VALUE_THREADED 1 +#include +#include +#include +#endif + +namespace bb { + +// With glibc's allocator, where this was measured, each pool worker allocates from a malloc arena of its own, which +// keeps its memory after the task ends; a task beside the launching thread's own work gains little from a wider pool. +inline constexpr size_t MAX_BACKGROUND_TASK_THREADS = 16; + +/** + * @brief The parallel_for thread count of a background task: that of the thread launching it, at most + * MAX_BACKGROUND_TASK_THREADS. + * @details The count is per thread and a new thread starts from the process default, so a run limited to k threads + * stays limited to k only if the task is handed k explicitly. + */ +inline size_t background_task_concurrency() +{ + return std::min(get_num_cpus(), MAX_BACKGROUND_TASK_THREADS); +} + +/** + * @brief The result of a callable run on a thread of its own, shared by every copy of the handle. + * @details The thread is joined by `get()` or, at the latest, when the last copy of the handle is destroyed, so the + * callable must own everything it reads. Without native threads the callable runs inside `launch`. + */ +template class DeferredValue { + public: + DeferredValue() = default; + + template static DeferredValue launch(Fn&& fn) + { + DeferredValue handle; + handle.state_ = std::make_shared(); +#ifdef BB_DEFERRED_VALUE_THREADED + State* state = handle.state_.get(); + const size_t num_threads = background_task_concurrency(); + state->worker = std::thread([state, num_threads, fn = std::forward(fn)]() mutable { + set_parallel_for_concurrency(num_threads); +#ifdef __cpp_exceptions + try { + state->value.emplace(fn()); + } catch (...) { + state->error = std::current_exception(); + } +#else + state->value.emplace(fn()); +#endif + }); +#else + handle.state_->value.emplace(fn()); +#endif + return handle; + } + + bool valid() const { return state_ != nullptr; } + + /** + * @brief Waits for the callable and returns its value, or rethrows what it threw. + */ + const T& get() const + { + BB_ASSERT(valid(), "DeferredValue::get() called on an empty handle"); + State& state = *state_; +#ifdef BB_DEFERRED_VALUE_THREADED + { + std::lock_guard lock(state.join_mutex); + if (state.worker.joinable()) { + state.worker.join(); + } + } +#ifdef __cpp_exceptions + if (state.error) { + std::rethrow_exception(state.error); + } +#endif +#endif + return *state.value; + } + + private: + struct State { + std::optional value; +#ifdef BB_DEFERRED_VALUE_THREADED + std::exception_ptr error; + std::mutex join_mutex; + std::thread worker; + + State() = default; + State(const State&) = delete; + State(State&&) = delete; + State& operator=(const State&) = delete; + State& operator=(State&&) = delete; + ~State() + { + if (worker.joinable()) { + worker.join(); + } + } +#endif + }; + + std::shared_ptr state_; +}; + +/** + * @brief Waits for `pending` if it is set, copies its value into an empty `target`, and clears `pending`. + * @details Whoever sets a pending value clears `target`, so a non-empty `target` was assigned after it and is kept, as + * the later of two assignments. Rethrows what the pending callable threw. + */ +template const T& resolve_into(T& target, DeferredValue& pending) +{ + if (pending.valid()) { + const T& value = pending.get(); + if (target.empty()) { + target = value; + } + pending = {}; + } + return target; +} + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/deferred_value.test.cpp b/barretenberg/cpp/src/barretenberg/common/deferred_value.test.cpp new file mode 100644 index 0000000..197a460 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/deferred_value.test.cpp @@ -0,0 +1,364 @@ +#include "barretenberg/common/deferred_value.hpp" +#include "barretenberg/common/thread.hpp" + +#include +#include +#include +#include +#include + +#ifdef BB_DEFERRED_VALUE_THREADED +#include +#include +#include +#include +#include +#endif + +using namespace bb; + +namespace { + +#ifndef NO_MULTITHREADING +class ConcurrencyGuard { + public: + ConcurrencyGuard() = default; + ConcurrencyGuard(const ConcurrencyGuard&) = delete; + ConcurrencyGuard(ConcurrencyGuard&&) = delete; + ConcurrencyGuard& operator=(const ConcurrencyGuard&) = delete; + ConcurrencyGuard& operator=(ConcurrencyGuard&&) = delete; + ~ConcurrencyGuard() { set_parallel_for_concurrency(saved_); } + + private: + size_t saved_ = get_num_cpus(); +}; +#endif + +#ifdef __cpp_exceptions +struct TaskError : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +constexpr const char* TASK_ERROR_MESSAGE = "background task failed"; + +int throw_task_error() +{ + throw TaskError(TASK_ERROR_MESSAGE); +} +#endif + +#ifdef BB_DEFERRED_VALUE_THREADED +// A single-use countdown: wait() blocks, without a deadline, until count_down() has been called `count` times. +class Countdown { + public: + explicit Countdown(size_t count) + : remaining_(count) + {} + + void count_down() + { + { + const std::lock_guard lock(mutex_); + --remaining_; + } + condition_.notify_all(); + } + + void wait() + { + std::unique_lock lock(mutex_); + condition_.wait(lock, [this] { return remaining_ == 0; }); + } + + private: + std::mutex mutex_; + std::condition_variable condition_; + size_t remaining_; +}; + +// Counts `countdown` down when destroyed. Declared after a handle it is destroyed first, so a waiter learns that the +// scope's destruction has begun while the handle is still alive. +class CountDownOnDestruction { + public: + explicit CountDownOnDestruction(Countdown& countdown) + : countdown_(countdown) + {} + CountDownOnDestruction(const CountDownOnDestruction&) = delete; + CountDownOnDestruction(CountDownOnDestruction&&) = delete; + CountDownOnDestruction& operator=(const CountDownOnDestruction&) = delete; + CountDownOnDestruction& operator=(CountDownOnDestruction&&) = delete; + ~CountDownOnDestruction() { countdown_.count_down(); } + + private: + Countdown& countdown_; +}; + +#ifdef __cpp_exceptions +void expect_task_error(const DeferredValue& handle) +{ + try { + (void)handle.get(); + ADD_FAILURE() << "get() did not throw"; + } catch (const TaskError& error) { + EXPECT_STREQ(error.what(), TASK_ERROR_MESSAGE); + } catch (...) { + ADD_FAILURE() << "get() threw an exception of another type"; + } +} +#endif +#endif + +} // namespace + +TEST(DeferredValue, GetReturnsTheCallablesValue) +{ + const DeferredValue empty; + EXPECT_FALSE(empty.valid()); + + const auto handle = DeferredValue::launch([] { return 42; }); + EXPECT_TRUE(handle.valid()); + const int& first = handle.get(); + const int& second = handle.get(); + EXPECT_EQ(first, 42); + EXPECT_EQ(&first, &second); + EXPECT_TRUE(handle.valid()); +} + +TEST(DeferredValue, CopiesShareOneResult) +{ + const auto handle = DeferredValue>::launch([] { return std::vector{ 1, 2, 3 }; }); + const DeferredValue> copy = handle; + EXPECT_EQ(copy.get(), (std::vector{ 1, 2, 3 })); + EXPECT_EQ(©.get(), &handle.get()); +} + +TEST(DeferredValue, ResolveIntoFillsAnEmptyTarget) +{ + std::vector target; + auto pending = DeferredValue>::launch([] { return std::vector{ 1, 2, 3 }; }); + const std::vector& resolved = resolve_into(target, pending); + EXPECT_EQ(&resolved, &target); + EXPECT_EQ(target, (std::vector{ 1, 2, 3 })); + EXPECT_FALSE(pending.valid()); +} + +TEST(DeferredValue, ResolveIntoKeepsANonEmptyTarget) +{ + std::vector target{ 9 }; + auto pending = DeferredValue>::launch([] { return std::vector{ 1, 2, 3 }; }); + resolve_into(target, pending); + EXPECT_EQ(target, (std::vector{ 9 })); + EXPECT_FALSE(pending.valid()); +} + +TEST(DeferredValue, ResolveIntoWithoutAPendingValueReturnsTheTarget) +{ + std::vector target{ 4 }; + DeferredValue> pending; + EXPECT_EQ(&resolve_into(target, pending), &target); + EXPECT_EQ(target, (std::vector{ 4 })); +} + +// Holds whether the callable runs on a thread of its own or inline in launch(). +TEST(DeferredValue, CallableNeverSeesMoreThreadsThanTheLauncher) +{ + const size_t launcher_threads = get_num_cpus(); + const auto handle = DeferredValue::launch([] { return get_num_cpus(); }); + EXPECT_GE(handle.get(), 1U); + EXPECT_LE(handle.get(), launcher_threads); +} + +#ifndef NO_MULTITHREADING +TEST(DeferredValue, CallableRunsAtTheLaunchersThreadCount) +{ + const ConcurrencyGuard guard; + set_parallel_for_concurrency(3); + const size_t expected = background_task_concurrency(); + ASSERT_EQ(expected, 3U); + const auto handle = DeferredValue::launch([] { return get_num_cpus(); }); + EXPECT_EQ(handle.get(), expected); +} +#endif + +#ifdef BB_DEFERRED_VALUE_THREADED +TEST(DeferredValue, CallableThreadCountIsCapped) +{ + const ConcurrencyGuard guard; + set_parallel_for_concurrency(MAX_BACKGROUND_TASK_THREADS + 4); + const auto handle = DeferredValue::launch([] { return get_num_cpus(); }); + EXPECT_EQ(handle.get(), MAX_BACKGROUND_TASK_THREADS); +} + +TEST(DeferredValue, LastHandleDestructionJoinsTheThread) +{ + Countdown release(1); + Countdown scope_destruction_begun(1); + std::atomic finished{ false }; + // The release waits for the scope's destruction to begin, so the task is unfinished when it does. That the handle's + // destructor is already inside join() when the release comes is only likely; the delay makes it so, and never + // decides the outcome for a joining destructor. + std::thread releaser([&release, &scope_destruction_begun] { + scope_destruction_begun.wait(); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + release.count_down(); + }); + { + const auto handle = DeferredValue::launch([&release, &finished] { + release.wait(); + finished.store(true); + return 1; + }); + const CountDownOnDestruction signal(scope_destruction_begun); + } + EXPECT_TRUE(finished.load()); + releaser.join(); +} + +TEST(DeferredValue, DestroyingACopyNeitherWaitsNorLosesTheResult) +{ + Countdown release(1); + std::atomic finished{ false }; + const auto survivor = DeferredValue::launch([&release, &finished] { + release.wait(); + finished.store(true); + return 42; + }); + // A copy whose destructor waits for the callable never returns from this scope, which the runner's timeout catches. + { + const DeferredValue copy = survivor; + EXPECT_TRUE(copy.valid()); + } + EXPECT_FALSE(finished.load()); + release.count_down(); + EXPECT_EQ(survivor.get(), 42); +} + +TEST(DeferredValue, GetFromTwoThreadsOnTwoCopiesReturnsTheSameValue) +{ + Countdown release(1); + Countdown getters_ready(2); + const auto first = DeferredValue::launch([&release] { + release.wait(); + return 7; + }); + const DeferredValue second = first; + + int from_first = 0; + int from_second = 0; + std::thread first_getter([&] { + getters_ready.count_down(); + from_first = first.get(); + }); + std::thread second_getter([&] { + getters_ready.count_down(); + from_second = second.get(); + }); + // Both getter threads have started before the release. That their joins overlap is only likely; the delay makes it + // so, and never decides the outcome. + getters_ready.wait(); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + release.count_down(); + first_getter.join(); + second_getter.join(); + + EXPECT_EQ(from_first, 7); + EXPECT_EQ(from_second, 7); + EXPECT_EQ(&first.get(), &second.get()); +} + +#ifdef __cpp_exceptions +TEST(DeferredValue, GetRethrowsOnEveryCallAndFromEveryCopy) +{ + const auto handle = DeferredValue::launch([] { return throw_task_error(); }); + const DeferredValue copy = handle; + expect_task_error(handle); + expect_task_error(handle); + expect_task_error(copy); + expect_task_error(copy); +} + +TEST(DeferredValue, DestroyingAFailedHandleWithoutGetDoesNotTerminate) +{ + std::atomic started{ false }; + { + const auto handle = DeferredValue::launch([&started] { + started.store(true); + return throw_task_error(); + }); + } + EXPECT_TRUE(started.load()); +} + +TEST(DeferredValue, CallerUnwindingJoinsARunningTaskAndKeepsTheCallersException) +{ + struct CallerError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + constexpr const char* CALLER_ERROR_MESSAGE = "caller failed while its task ran"; + constexpr int TRACKED_VALUE = 5; + + struct Tracked { + explicit Tracked(std::atomic& destroyed_flag) + : destroyed(destroyed_flag) + {} + ~Tracked() { destroyed.store(true); } + std::atomic& destroyed; + int value = TRACKED_VALUE; + }; + + Countdown release(1); + Countdown unwinding_begun(1); + std::atomic tracked_destroyed{ false }; + std::atomic destroyed_when_read{ true }; + std::atomic value_read{ 0 }; + std::atomic finished{ false }; + auto tracked = std::make_shared(tracked_destroyed); + + // The task reads what it captured only after the unwinding has begun. That the handle's destructor is already + // inside join() when the release comes is only likely; the delay makes it so, and never decides the outcome. + std::thread releaser([&release, &unwinding_begun] { + unwinding_begun.wait(); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + release.count_down(); + }); + bool caught = false; + try { + const auto handle = DeferredValue::launch( + [&release, &tracked_destroyed, &destroyed_when_read, &value_read, &finished, tracked = std::move(tracked)] { + release.wait(); + destroyed_when_read.store(tracked_destroyed.load()); + value_read.store(tracked->value); + finished.store(true); + return tracked->value; + }); + const CountDownOnDestruction signal(unwinding_begun); + throw CallerError(CALLER_ERROR_MESSAGE); + } catch (const CallerError& error) { + caught = true; + EXPECT_STREQ(error.what(), CALLER_ERROR_MESSAGE); + EXPECT_TRUE(finished.load()); + } catch (...) { + ADD_FAILURE() << "the caller's exception was replaced by one of another type"; + } + releaser.join(); + EXPECT_TRUE(caught); + EXPECT_FALSE(destroyed_when_read.load()); + EXPECT_EQ(value_read.load(), TRACKED_VALUE); +} + +TEST(DeferredValue, ResolveIntoPropagatesTheException) +{ + std::vector target; + auto pending = + DeferredValue>::launch([]() -> std::vector { throw TaskError(TASK_ERROR_MESSAGE); }); + EXPECT_THROW(resolve_into(target, pending), TaskError); + EXPECT_TRUE(target.empty()); +} +#endif +#elif defined(__cpp_exceptions) +// Without native threads the callable runs inside launch(), so its exception leaves launch() itself. +TEST(DeferredValue, InlineLaunchPropagatesTheException) +{ + EXPECT_THROW((void)DeferredValue::launch([] { return throw_task_error(); }), TaskError); +} +#endif diff --git a/barretenberg/cpp/src/barretenberg/common/get_bytecode.cpp b/barretenberg/cpp/src/barretenberg/common/get_bytecode.cpp index a1c98bb..450c6ab 100644 --- a/barretenberg/cpp/src/barretenberg/common/get_bytecode.cpp +++ b/barretenberg/cpp/src/barretenberg/common/get_bytecode.cpp @@ -7,24 +7,70 @@ #ifndef __wasm__ #include #include +#include #include #include #endif +#ifndef __wasm__ namespace { -std::vector gzip_decompress([[maybe_unused]] const std::vector& compressed) +// A deflate stream expands its input at most 1032-fold (RFC 1951: a 258-byte match costs at least 2 bits), so a size +// claim above that bound is wrong and is not tried. +constexpr size_t DEFLATE_MAX_EXPANSION = 1032; +constexpr size_t GZIP_TRAILER_ISIZE_BYTES = 4; +constexpr size_t GZIP_MIN_MEMBER_BYTES = 18; // 10-byte header + 8-byte trailer + +GzipScratch allocate_gzip_scratch(size_t size) +{ + // new[] of uint8_t default-initialises: pages stay untouched, so not resident, until something is written to them. + return { new (std::nothrow) uint8_t[size], [](uint8_t* p) { delete[] p; } }; +} + +} // namespace +#endif + +std::vector gzip_decompress([[maybe_unused]] const std::vector& compressed, + [[maybe_unused]] GzipScratch (*scratch)(size_t)) { #ifdef __wasm__ throw_or_abort("gzip_decompress not supported in WASM"); #else + auto decompressor = + std::unique_ptr{ libdeflate_alloc_decompressor(), + libdeflate_free_decompressor }; + + // A gzip member ends with ISIZE, the uncompressed size modulo 2^32 (RFC 1952, section 2.3.1). Inflating once into + // storage of that size avoids restarting from the first byte after every doubling of a small guess. In a + // multi-member stream ISIZE describes the last member while libdeflate inflates only the first, so the result is + // kept only when that one member spans the whole input. The storage is not zero-filled, so a wrong guess costs only + // the pages the first member writes; if it cannot be had, or the guess is wrong, the doubling loop runs as before. + if (compressed.size() >= GZIP_MIN_MEMBER_BYTES) { + const uint8_t* isize_bytes = compressed.data() + compressed.size() - GZIP_TRAILER_ISIZE_BYTES; + const size_t isize = static_cast(isize_bytes[0]) | (static_cast(isize_bytes[1]) << 8) | + (static_cast(isize_bytes[2]) << 16) | (static_cast(isize_bytes[3]) << 24); + if (isize > 0 && (isize + DEFLATE_MAX_EXPANSION - 1) / DEFLATE_MAX_EXPANSION <= compressed.size()) { + const GzipScratch buffer = (scratch != nullptr ? scratch : allocate_gzip_scratch)(isize); + size_t consumed = 0; + size_t actual_size = 0; + if (buffer != nullptr && + libdeflate_gzip_decompress_ex(decompressor.get(), + compressed.data(), + compressed.size(), + buffer.get(), + isize, + &consumed, + &actual_size) == LIBDEFLATE_SUCCESS && + consumed == compressed.size()) { + return std::vector(buffer.get(), buffer.get() + actual_size); + } + } + } + std::vector decompressed; decompressed.resize(1024ULL * 128ULL); // Initial size guess for (;;) { - auto decompressor = std::unique_ptr{ - libdeflate_alloc_decompressor(), libdeflate_free_decompressor - }; size_t actual_size = 0; libdeflate_result result = libdeflate_gzip_decompress(decompressor.get(), compressed.data(), @@ -46,7 +92,6 @@ std::vector gzip_decompress([[maybe_unused]] const std::vector return decompressed; #endif } -} // namespace std::vector decode_bytecode(const std::string& base64_bytecode) { @@ -83,7 +128,20 @@ std::vector gunzip([[maybe_unused]] const std::string& path) throw std::runtime_error("Failed to open file: " + path); } - std::vector compressed((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + // One bulk read when the size is known; pipes and other unseekable inputs are streamed. + file.seekg(0, std::ios::end); + const std::streamoff file_size = file.tellg(); + if (file_size < 0) { + file.clear(); + std::vector compressed((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + return gzip_decompress(compressed); + } + file.seekg(0, std::ios::beg); + std::vector compressed(static_cast(file_size)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + if (!file.read(reinterpret_cast(compressed.data()), file_size)) { + throw std::runtime_error("Failed to read file: " + path); + } return gzip_decompress(compressed); #endif } diff --git a/barretenberg/cpp/src/barretenberg/common/get_bytecode.hpp b/barretenberg/cpp/src/barretenberg/common/get_bytecode.hpp index 78719bd..71a4fae 100644 --- a/barretenberg/cpp/src/barretenberg/common/get_bytecode.hpp +++ b/barretenberg/cpp/src/barretenberg/common/get_bytecode.hpp @@ -1,10 +1,22 @@ #pragma once +#include #include #include #include +#include #include #include +// Storage for the decompression attempt sized from the gzip trailer; nullptr if it cannot be obtained. +using GzipScratch = std::unique_ptr; + +/** + * @brief Decompresses the first member of a gzip stream, as libdeflate_gzip_decompress does. + * @param scratch Supplies the storage of the attempt sized from the gzip trailer (by default uninitialised new[], or + * nullptr when that fails). Tests substitute their own to see what that attempt writes. + */ +std::vector gzip_decompress(const std::vector& compressed, GzipScratch (*scratch)(size_t) = nullptr); + // Parse JSON file and extract base64-encoded gzipped bytecode std::vector get_bytecode_from_json(const std::string& json_path); diff --git a/barretenberg/cpp/src/barretenberg/common/get_bytecode.test.cpp b/barretenberg/cpp/src/barretenberg/common/get_bytecode.test.cpp new file mode 100644 index 0000000..ea105e3 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/get_bytecode.test.cpp @@ -0,0 +1,84 @@ +#include "barretenberg/common/get_bytecode.hpp" +#include +#include +#include +#include + +#ifndef __wasm__ +#include +#include + +namespace { + +std::vector gzip(const std::vector& data) +{ + auto compressor = + std::unique_ptr{ libdeflate_alloc_compressor(6), + libdeflate_free_compressor }; + std::vector out(libdeflate_gzip_compress_bound(compressor.get(), data.size())); + out.resize(libdeflate_gzip_compress(compressor.get(), data.data(), data.size(), out.data(), out.size())); + return out; +} + +std::vector pattern(size_t size, uint8_t seed) +{ + std::vector data(size); + for (size_t i = 0; i < size; ++i) { + data[i] = static_cast((i * 31) + seed); + } + return data; +} + +// Scratch storage the test can inspect afterwards: filled with a sentinel, so bytes the attempt never wrote keep it. +constexpr uint8_t SENTINEL = 0xA5; +std::vector& observed_scratch() +{ + static std::vector storage; + return storage; +} +GzipScratch sentinel_scratch(size_t size) +{ + observed_scratch().assign(size, SENTINEL); + return { observed_scratch().data(), [](uint8_t*) {} }; +} +GzipScratch failing_scratch(size_t /*size*/) +{ + return { nullptr, [](uint8_t*) {} }; +} + +} // namespace + +TEST(GzipDecompress, SingleMemberIsSizedFromItsTrailer) +{ + const auto data = pattern(size_t{ 3 } << 20, 7); + const auto out = gzip_decompress(gzip(data)); + EXPECT_EQ(out, data); + EXPECT_EQ(out.capacity(), data.size()); +} + +// libdeflate inflates only the first member, while the trailer at the end of the input is the last member's. The +// attempt sized from that trailer must write no more than the first member, so it costs only the pages it fills. +TEST(GzipDecompress, ConcatenatedMembersTouchOnlyTheFirstMembersShareOfTheTrailerSizedAttempt) +{ + const auto first = pattern(size_t{ 1 } << 10, 1); + const auto last = pattern(size_t{ 16 } << 20, 2); + auto gz = gzip(first); + const auto gz_last = gzip(last); + gz.insert(gz.end(), gz_last.begin(), gz_last.end()); + + EXPECT_EQ(gzip_decompress(gz, sentinel_scratch), first); + const auto& scratch = observed_scratch(); + ASSERT_EQ(scratch.size(), last.size()); + // The inflater's fast path may overrun its output position by a few hundred bytes within the buffer. + constexpr size_t OVERRUN_SLACK = 4096; + EXPECT_TRUE(std::all_of(scratch.begin() + static_cast(first.size() + OVERRUN_SLACK), + scratch.end(), + [](uint8_t b) { return b == SENTINEL; })); +} + +TEST(GzipDecompress, UnavailableScratchFallsBackToDoubling) +{ + const auto data = pattern(size_t{ 3 } << 20, 9); + EXPECT_EQ(gzip_decompress(gzip(data), failing_scratch), data); +} +#endif diff --git a/barretenberg/cpp/src/barretenberg/common/release_pages.hpp b/barretenberg/cpp/src/barretenberg/common/release_pages.hpp index 7764243..55e5ad7 100644 --- a/barretenberg/cpp/src/barretenberg/common/release_pages.hpp +++ b/barretenberg/cpp/src/barretenberg/common/release_pages.hpp @@ -1,10 +1,11 @@ #pragma once #include +#include #include #include +#include #if !defined(__wasm__) && !defined(_WIN32) && !defined(NO_MULTITHREADING) -#include #include #include #include @@ -13,48 +14,150 @@ namespace bb { /** - * @brief Before a large block is freed, hand its pages back to the OS from several threads at once. + * @brief A block of memory whose pages may be handed back to the OS just before it is freed. + */ +struct PageBlock { + void* ptr = nullptr; + // The allocation's size, which decides whether the block is large enough to release. + size_t bytes = 0; + // The bytes in use from ptr, at most `bytes`; only pages inside them are released and counted. + size_t used_bytes = 0; + + constexpr PageBlock() noexcept = default; + constexpr PageBlock(void* block, size_t block_bytes) noexcept + : PageBlock(block, block_bytes, block_bytes) + {} + constexpr PageBlock(void* block, size_t block_bytes, size_t block_used_bytes) noexcept + : ptr(block) + , bytes(block_bytes) + , used_bytes(std::min(block_used_bytes, block_bytes)) + {} +}; + +/** + * @brief The smallest block the list form of release_pages_in_parallel releases. + * @details glibc gives a block a mapping of its own only at or above its dynamic mmap threshold, which rises to at most + * 32 MiB on 64-bit. A smaller block may sit inside a malloc arena, where free() would not unmap it, and releasing its + * pages only makes the next allocation that reuses that memory fault them in again. + */ +inline constexpr size_t MIN_PAGE_RELEASE_BLOCK_BYTES = size_t{ 32 } << 20; + +namespace release_pages_detail { + +inline constexpr size_t MIN_PARALLEL_RELEASE_BYTES = size_t{ 64 } << 20; +inline constexpr size_t BYTES_PER_THREAD = size_t{ 16 } << 20; +inline constexpr size_t MAX_THREADS = 16; + +} // namespace release_pages_detail + +/** + * @brief The sizes below which the list form of release_pages_in_parallel leaves memory to the allocator. + */ +struct PageReleaseFloors { + // A block whose allocation is smaller is skipped. + size_t min_block_bytes = MIN_PAGE_RELEASE_BLOCK_BYTES; + // Nothing is released when the used bytes of the blocks that are not skipped total less. + size_t min_total_bytes = release_pages_detail::MIN_PARALLEL_RELEASE_BYTES; +}; + +namespace release_pages_detail { + +#if !defined(__wasm__) && !defined(_WIN32) && !defined(NO_MULTITHREADING) && defined(MADV_DONTNEED) +struct PageRange { + uintptr_t begin = 0; + uintptr_t end = 0; +}; + +// The whole pages strictly inside an eligible block's used bytes, never allocator metadata next to the block. +inline PageRange whole_pages(const PageBlock& block, uintptr_t page, size_t min_block_bytes) +{ + if (block.ptr == nullptr || block.bytes < min_block_bytes) { + return {}; + } + const auto lo = reinterpret_cast(block.ptr); + const uintptr_t begin = (lo + page - 1) & ~(page - 1); + const uintptr_t end = (lo + std::min(block.used_bytes, block.bytes)) & ~(page - 1); + return end > begin ? PageRange{ begin, end } : PageRange{}; +} + +// Pages [first_page, end_page) of the eligible blocks' whole pages, numbered consecutively across blocks. +struct Slice { + const PageBlock* blocks = nullptr; + size_t num_blocks = 0; + size_t min_block_bytes = 0; + uintptr_t page = 0; + size_t first_page = 0; + size_t end_page = 0; +}; + +inline void* release_slice(void* arg) +{ + const auto* slice = static_cast(arg); + size_t block_first_page = 0; + for (size_t i = 0; i < slice->num_blocks && block_first_page < slice->end_page; ++i) { + const PageRange range = whole_pages(slice->blocks[i], slice->page, slice->min_block_bytes); + const size_t num_pages = (range.end - range.begin) / slice->page; + const size_t lo = std::max(block_first_page, slice->first_page); + const size_t hi = std::min(block_first_page + num_pages, slice->end_page); + if (lo < hi) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,performance-no-int-to-ptr) + auto* start = reinterpret_cast(range.begin + ((lo - block_first_page) * slice->page)); + static_cast(madvise(start, (hi - lo) * slice->page, MADV_DONTNEED)); + } + block_first_page += num_pages; + } + return nullptr; +} +#endif + +} // namespace release_pages_detail + +/** + * @brief Before large blocks are freed, hand their pages back to the OS from one team of threads. * * @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. + * time (on the order of 0.1 ms per MiB), so gigabytes of memory take a noticeable serial pause to tear down. + * madvise(MADV_DONTNEED) on disjoint ranges runs concurrently, after which each free only unmaps an empty range. Only + * whole pages strictly inside each block's used bytes are released, split evenly over up to 16 threads, one per 16 MiB, + * whatever the block boundaries. Blocks whose allocation is under MIN_PAGE_RELEASE_BLOCK_BYTES (32 MiB) are skipped, + * since the allocator may keep them in a malloc arena rather than unmap them on free, and nothing is released when the + * used bytes of the remaining blocks total under 64 MiB, so a large reserve that was never written starts no threads. + * Both floors can be lowered through `floors`. The released blocks' contents are lost: call this only immediately + * before freeing them. Never throws, and 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. A no-op without native threads. + * + * @return Whether the release was attempted: true once the qualifying pages have been handed to madvise, whether or not + * every call succeeded, so the caller need not release them again; false when nothing qualified or without native + * threads. */ -inline void release_pages_in_parallel([[maybe_unused]] void* ptr, [[maybe_unused]] size_t bytes) +inline bool release_pages_in_parallel([[maybe_unused]] std::span blocks, + [[maybe_unused]] const PageReleaseFloors& floors = {}) noexcept { #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; - } + using namespace release_pages_detail; 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; + size_t eligible_bytes = 0; + size_t num_pages = 0; + for (const PageBlock& block : blocks) { + const PageRange range = whole_pages(block, page, floors.min_block_bytes); + if (range.end > range.begin) { + eligible_bytes += std::min(block.used_bytes, block.bytes); + num_pages += (range.end - range.begin) / page; + } } - 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; - }; + if (eligible_bytes < floors.min_total_bytes || num_pages == 0) { + return false; + } + const size_t num_threads = std::clamp((num_pages * page) / BYTES_PER_THREAD, 1, MAX_THREADS); 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) }; + slices[t] = { blocks.data(), + blocks.size(), + floors.min_block_bytes, + page, + (num_pages * t) / num_threads, + (num_pages * (t + 1)) / num_threads }; } - 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{}; @@ -70,7 +173,109 @@ inline void release_pages_in_parallel([[maybe_unused]] void* ptr, [[maybe_unused for (size_t t = 1; t < spawned; ++t) { pthread_join(threads[t], nullptr); } + return true; +#else + return false; #endif } +/** + * @brief Before a large block is freed, hand its pages back to the OS from several threads at once. + * + * @details The single-block form of release_pages_in_parallel above, for a block of at least 64 MiB; smaller blocks are + * left to the allocator. + */ +inline void release_pages_in_parallel(void* ptr, size_t bytes) +{ + if (ptr == nullptr || bytes < release_pages_detail::MIN_PARALLEL_RELEASE_BYTES) { + return; + } + const PageBlock block{ ptr, bytes }; + static_cast(release_pages_in_parallel(std::span(&block, 1))); +} + +/** + * @brief A fixed-capacity list of blocks for the list form of release_pages_in_parallel; adding never allocates or + * throws, so it can be filled inside destructors. + */ +template class PageBlockList { + public: + constexpr PageBlockList() noexcept = default; + constexpr explicit PageBlockList(const PageReleaseFloors& floors) noexcept + : floors_(floors) + {} + + /** + * @brief Adds a block of `bytes` whose first `used_bytes` are in use, if the block reaches the list's block floor + * (MIN_PAGE_RELEASE_BLOCK_BYTES by default) and the list has room; only pages inside the used bytes are released. + * @return Whether the block was added; a block that was not is left to the allocator. + */ + bool add(void* ptr, size_t bytes, size_t used_bytes) noexcept + { + if (ptr == nullptr || bytes < floors_.min_block_bytes || size_ == N) { + return false; + } + blocks_[size_++] = PageBlock{ ptr, bytes, used_bytes }; + return true; + } + + /** + * @brief Adds a block that is in use in full; see the three-argument add. + */ + bool add(void* ptr, size_t bytes) noexcept { return add(ptr, bytes, bytes); } + + /** + * @brief Releases the pages of every added block (see release_pages_in_parallel); call it only immediately before + * freeing them. + * @return Whether the release was attempted (see release_pages_in_parallel). + */ + bool release() const noexcept + { + return release_pages_in_parallel(std::span(blocks_.data(), size_), floors_); + } + + bool full() const noexcept { return size_ == N; } + + void clear() noexcept { size_ = 0; } + + private: + PageReleaseFloors floors_{}; + std::array blocks_{}; + size_t size_ = 0; +}; + +/** + * @brief A PageBlockList that releases its blocks whenever it is full, so it takes any number of blocks; adding never + * allocates or throws. + */ +template class BatchedPageRelease { + public: + constexpr explicit BatchedPageRelease(const PageReleaseFloors& floors) noexcept + : list_(floors) + {} + + /** + * @brief Adds a block as PageBlockList::add does, first releasing the blocks added so far if the list is full. + */ + void add(void* ptr, size_t bytes, size_t used_bytes) noexcept + { + if (list_.full()) { + release(); + } + list_.add(ptr, bytes, used_bytes); + } + + /** + * @brief Releases the blocks added since the last release; call it only immediately before freeing them. + */ + void release() noexcept + { + list_.release(); + list_.clear(); + } + + private: + PageBlockList list_; +}; + } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/common/release_pages.test.cpp b/barretenberg/cpp/src/barretenberg/common/release_pages.test.cpp new file mode 100644 index 0000000..38f61b4 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/release_pages.test.cpp @@ -0,0 +1,175 @@ +#include "barretenberg/common/release_pages.hpp" + +#include +#include +#include +#include +#include +#include + +// Released anonymous pages read back as zeros only on Linux. +#if defined(__linux__) && !defined(NO_MULTITHREADING) +#define BB_RELEASE_PAGES_TESTABLE 1 +#include +#include +#endif + +using namespace bb; + +namespace { + +#ifdef BB_RELEASE_PAGES_TESTABLE +constexpr unsigned char FILL = 0xAB; +constexpr size_t MIB = size_t{ 1 } << 20; + +class Mapping { + public: + explicit Mapping(size_t bytes) + : bytes_(bytes) + , base_(static_cast( + mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0))) + { + if (base_ == MAP_FAILED) { + base_ = nullptr; + ADD_FAILURE() << "mmap failed"; + return; + } + std::memset(base_, FILL, bytes_); + } + Mapping(const Mapping&) = delete; + Mapping(Mapping&&) = delete; + Mapping& operator=(const Mapping&) = delete; + Mapping& operator=(Mapping&&) = delete; + ~Mapping() + { + if (base_ != nullptr) { + munmap(base_, bytes_); + } + } + + unsigned char* at(size_t offset) const { return base_ + offset; } + size_t size() const { return bytes_; } + + private: + size_t bytes_; + unsigned char* base_; +}; + +size_t page_size() +{ + return static_cast(sysconf(_SC_PAGESIZE)); +} + +// Checks page by page that exactly the whole pages strictly inside the used bytes of `released` read as zero and every +// other byte of the mapping still holds FILL. +void expect_only_whole_pages_released(const Mapping& mapping, const std::vector& released) +{ + ASSERT_NE(mapping.at(0), nullptr); + const size_t page = page_size(); + const std::vector filled(page, FILL); + const std::vector zeros(page, 0); + const auto base = reinterpret_cast(mapping.at(0)); + for (size_t offset = 0; offset < mapping.size(); offset += page) { + const uintptr_t lo = base + offset; + bool is_released = false; + for (const PageBlock& block : released) { + const auto begin = reinterpret_cast(block.ptr); + is_released = is_released || (lo >= begin && lo + page <= begin + block.used_bytes); + } + const auto& expected = is_released ? zeros : filled; + ASSERT_EQ(std::memcmp(mapping.at(offset), expected.data(), page), 0) + << "page at offset " << offset << " expected " << (is_released ? "released" : "untouched"); + } +} +#endif + +} // namespace + +TEST(ReleasePages, ListReleasesWholePagesOfLargeBlocksOnly) +{ +#ifndef BB_RELEASE_PAGES_TESTABLE + GTEST_SKIP() << "needs Linux and native threads"; +#else + const size_t page = page_size(); + const size_t large = (32 * MIB) + (4 * page); + Mapping mapping((2 * large) + MIB + (2 * page)); + + // Both large blocks start and end mid-page; the small one is page aligned but under the per-block floor. + const PageBlock first{ mapping.at(100), (32 * MIB) + 1234 }; + const PageBlock second{ mapping.at(large + 7), (32 * MIB) + (2 * page) }; + const PageBlock small{ mapping.at(2 * large), MIB }; + const PageBlock empty{ mapping.at(0), 0 }; + const PageBlock null_block{ nullptr, 64 * MIB }; + + PageBlockList<3> list; + EXPECT_FALSE(list.add(empty.ptr, empty.bytes)); + EXPECT_TRUE(list.add(first.ptr, first.bytes)); + EXPECT_FALSE(list.add(small.ptr, small.bytes)); + EXPECT_FALSE(list.add(null_block.ptr, null_block.bytes)); + EXPECT_TRUE(list.add(second.ptr, second.bytes)); + EXPECT_TRUE(list.release()); + expect_only_whole_pages_released(mapping, { first, second }); + + // The list form applies the same rules to blocks it is handed directly. + Mapping again((2 * large) + MIB + (2 * page)); + const std::vector blocks{ { again.at(2 * large), MIB }, + { again.at(100), (32 * MIB) + 1234 }, + { nullptr, 64 * MIB }, + { again.at(0), 0 }, + { again.at(large + 7), (32 * MIB) + (2 * page) } }; + EXPECT_TRUE(release_pages_in_parallel(std::span(blocks))); + expect_only_whole_pages_released(again, { blocks[1], blocks[4] }); +#endif +} + +TEST(ReleasePages, SmallTotalsAndFullListsAreLeftAlone) +{ +#ifndef BB_RELEASE_PAGES_TESTABLE + GTEST_SKIP() << "needs Linux and native threads"; +#else + Mapping mapping(64 * MIB); + + // One eligible block of 40 MiB plus a block under the floor total less than the 64 MiB minimum. + const std::vector blocks{ { mapping.at(0), 40 * MIB }, { mapping.at(40 * MIB), 24 * MIB } }; + EXPECT_FALSE(release_pages_in_parallel(std::span(blocks))); + expect_only_whole_pages_released(mapping, {}); + + // A full list drops the extra block rather than growing; one 32 MiB block is again under the minimum. + PageBlockList<1> list; + EXPECT_TRUE(list.add(mapping.at(0), 32 * MIB)); + EXPECT_FALSE(list.add(mapping.at(32 * MIB), 32 * MIB)); + EXPECT_FALSE(list.release()); + expect_only_whole_pages_released(mapping, {}); + + // The single-block form keeps its own 64 MiB minimum. + release_pages_in_parallel(mapping.at(1), (64 * MIB) - 1); + expect_only_whole_pages_released(mapping, {}); +#endif +} + +TEST(ReleasePages, BlocksQualifyByCapacityButReleaseOnlyTheirUsedBytes) +{ +#ifndef BB_RELEASE_PAGES_TESTABLE + GTEST_SKIP() << "needs Linux and native threads"; +#else + { + // `sparse` qualifies by its capacity and its used bytes end mid-page; with `full` they just reach the minimum. + Mapping mapping(96 * MIB); + const PageBlock sparse{ mapping.at(100), 32 * MIB, (8 * MIB) + 1234 }; + const PageBlock full{ mapping.at(40 * MIB), 56 * MIB }; + PageBlockList<2> list; + EXPECT_TRUE(list.add(sparse.ptr, sparse.bytes, sparse.used_bytes)); + EXPECT_TRUE(list.add(full.ptr, full.bytes)); + EXPECT_TRUE(list.release()); + expect_only_whole_pages_released(mapping, { sparse, full }); + } + + // Capacities reaching the minimum do not count; the used bytes are under it. + Mapping mapping(64 * MIB); + PageBlockList<2> list; + EXPECT_TRUE(list.add(mapping.at(0), 32 * MIB, 16 * MIB)); + EXPECT_TRUE(list.add(mapping.at(32 * MIB), 32 * MIB, 16 * MIB)); + EXPECT_FALSE(list.release()); + expect_only_whole_pages_released(mapping, {}); +#endif +} diff --git a/barretenberg/cpp/src/barretenberg/common/scratch_array.hpp b/barretenberg/cpp/src/barretenberg/common/scratch_array.hpp new file mode 100644 index 0000000..60a7e7d --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/common/scratch_array.hpp @@ -0,0 +1,66 @@ +#pragma once + +#include "barretenberg/common/release_pages.hpp" +#include +#include +#include +#include +#include + +namespace bb { + +/** + * @brief Fixed-size heap array whose elements start uninitialised, for large buffers that are filled in parallel. + * + * @details std::vector(n) value-initialises: one thread zero-fills every byte, and so takes every page fault of a + * fresh mapping, before parallel code overwrites it. Here no element is written until the caller writes it, so the + * first touch of each page happens wherever the caller's parallel fill runs. Every element must be written before it + * is read. The pages are released from several threads when the array is freed (see release_pages_in_parallel). + */ +template class ScratchArray { + static_assert(std::is_trivially_default_constructible_v && std::is_trivially_destructible_v); + + public: + ScratchArray() = default; + explicit ScratchArray(size_t size) + : data_(size == 0 ? nullptr : new T[size]) + , size_(size) + {} + ScratchArray(const ScratchArray&) = delete; + ScratchArray& operator=(const ScratchArray&) = delete; + ScratchArray(ScratchArray&& other) noexcept + : data_(std::move(other.data_)) + , size_(std::exchange(other.size_, 0)) + {} + ScratchArray& operator=(ScratchArray&& other) noexcept + { + if (this != &other) { + release(); + data_ = std::move(other.data_); + size_ = std::exchange(other.size_, 0); + } + return *this; + } + ~ScratchArray() { release(); } + + T* data() noexcept { return data_.get(); } + const T* data() const noexcept { return data_.get(); } + size_t size() const noexcept { return size_; } + T& operator[](size_t i) noexcept { return data_[i]; } + const T& operator[](size_t i) const noexcept { return data_[i]; } + std::span span() noexcept { return { data_.get(), size_ }; } + std::span span() const noexcept { return { data_.get(), size_ }; } + + private: + void release() noexcept + { + release_pages_in_parallel(data_.get(), size_ * sizeof(T)); + data_.reset(); + size_ = 0; + } + + std::unique_ptr data_; + size_t size_ = 0; +}; + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp new file mode 100644 index 0000000..1f164d9 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_compact_decoder.test.cpp @@ -0,0 +1,217 @@ +/** + * @file acir_compact_decoder.test.cpp + * @brief The streaming msgpack-compact program decoder (circuit_buf_to_acir_format) must produce the same AcirFormat + * as converting the Acir::Circuit it encodes (circuit_serde_to_acir_format). + */ + +#include +#include + +#include "acir_to_constraint_buf.hpp" +#include "barretenberg/common/assert.hpp" +#include "barretenberg/ecc/curves/bn254/fr.hpp" +#include "barretenberg/serialize/msgpack_impl.hpp" +#include "serde/acir.hpp" + +using namespace acir_format; + +namespace { + +std::vector coefficient(const bb::fr& value) +{ + std::vector bytes(32); + bb::fr::serialize_to_buffer(value, bytes.data()); + return bytes; +} + +Acir::Expression expression(const std::vector>& mul_terms, + const std::vector>& linear_terms, + uint64_t constant) +{ + Acir::Expression expr; + for (const auto& [scaling, lhs, rhs] : mul_terms) { + expr.mul_terms.emplace_back(coefficient(bb::fr(scaling)), Acir::Witness{ lhs }, Acir::Witness{ rhs }); + } + for (const auto& [scaling, witness] : linear_terms) { + expr.linear_combinations.emplace_back(coefficient(-bb::fr(scaling)), Acir::Witness{ witness }); + } + expr.q_c = coefficient(bb::fr(constant)); + return expr; +} + +Acir::Opcode assert_zero(Acir::Expression expr) +{ + return Acir::Opcode{ .value = Acir::Opcode::AssertZero{ .value = std::move(expr) } }; +} + +Acir::Opcode range(Acir::FunctionInput input, uint32_t num_bits) +{ + return Acir::Opcode{ .value = Acir::Opcode::BlackBoxFuncCall{ + .value = + Acir::BlackBoxFuncCall{ .value = Acir::BlackBoxFuncCall::RANGE{ + .input = std::move(input), .num_bits = num_bits } } } }; +} + +Acir::Opcode memory_op(uint32_t block_id, bool is_write, uint32_t index, uint32_t value) +{ + return Acir::Opcode{ .value = Acir::Opcode::MemoryOp{ + .block_id = Acir::BlockId{ block_id }, + .op = Acir::MemOp{ .read = is_write, .index = { index }, .value = { value } } } }; +} + +std::vector serialize_program(const Acir::Circuit& circuit) +{ + msgpack::sbuffer sbuf; + msgpack::packer packer(sbuf); + // Program = [functions, unconstrained_functions] + packer.pack_array(2); + packer.pack_array(1); + packer.pack(circuit); + packer.pack_array(0); + + std::vector buf; + buf.push_back(0x03); // FORMAT_MSGPACK_COMPACT + buf.insert(buf.end(), sbuf.data(), sbuf.data() + sbuf.size()); + return buf; +} + +Acir::Circuit test_circuit() +{ + Acir::Circuit circuit; + auto& ops = circuit.opcodes; + + // AssertZero opcodes of every gate shape, with growing and shrinking term counts (exercises buffer reuse), + // duplicate linear witnesses and witness indices in every msgpack integer width. + ops.push_back(assert_zero(expression({}, { { 1, 1 }, { 1, 2 } }, 0))); + ops.push_back(assert_zero(expression({ { 1, 1, 2 } }, { { 1, 3 } }, 5))); + ops.push_back(assert_zero(expression({ { 2, 1, 2 }, { 3, 2, 4 } }, { { 1, 1 }, { 1, 4 }, { 1, 5 } }, 0))); + ops.push_back(assert_zero(expression( + { { 2, 1, 2 }, { 3, 3, 4 }, { 4, 5, 6 } }, { { 1, 7 }, { 1, 8 }, { 1, 9 }, { 1, 10 }, { 1, 11 } }, 7))); + ops.push_back(assert_zero(expression({}, { { 1, 200 } }, 3))); + ops.push_back(assert_zero(expression({ { 1, 300, 300 } }, { { 1, 300 }, { 2, 300 }, { 1, 70000 } }, 0))); + ops.push_back(assert_zero(expression({}, { { 1, 12 }, { 1, 13 }, { 1, 14 }, { 1, 15 }, { 1, 16 }, { 1, 17 } }, 1))); + ops.push_back(assert_zero(expression({ { 5, 18, 19 } }, {}, 0))); + ops.push_back(assert_zero(expression({}, { { 1, 20 }, { 1, 21 } }, 9))); + + // Range constraints on witnesses in different msgpack integer widths. + ops.push_back(range(Acir::FunctionInput{ .value = Acir::FunctionInput::Witness{ .value = { 22 } } }, 32)); + ops.push_back(range(Acir::FunctionInput{ .value = Acir::FunctionInput::Witness{ .value = { 100000 } } }, 254)); + + // Memory: MemoryInit goes through the generic decoder, MemoryOp reads and writes are decoded directly. + ops.push_back(Acir::Opcode{ + .value = Acir::Opcode::MemoryInit{ .block_id = { 0 }, + .init = { { 23 }, { 24 }, { 25 } }, + .block_type = Acir::BlockType{ .value = Acir::BlockType::Memory{} } } }); + ops.push_back(memory_op(0, false, 26, 27)); + ops.push_back(memory_op(0, true, 28, 29)); + + // Brillig calls only contribute their witness indices; the largest index of the circuit is in one. + ops.push_back(Acir::Opcode{ + .value = Acir::Opcode::BrilligCall{ + .id = 3, + .inputs = { Acir::BrilligInputs{ .value = + Acir::BrilligInputs::Single{ + .value = expression({ { 1, 30, 31 } }, { { 1, 32 } }, 0) } }, + Acir::BrilligInputs{ + .value = Acir::BrilligInputs::Array{ .value = { expression({}, { { 1, 33 } }, 0), + expression( + {}, { { 1, 34 }, { 1, 35 } }, 1) } } }, + Acir::BrilligInputs{ .value = Acir::BrilligInputs::MemoryArray{ .value = { 0 } } } }, + .outputs = { Acir::BrilligOutputs{ .value = Acir::BrilligOutputs::Simple{ .value = { 36 } } }, + Acir::BrilligOutputs{ .value = + Acir::BrilligOutputs::Array{ .value = { { 37 }, { 5000000 } } } } }, + .predicate = expression({}, {}, 1) } }); + ops.push_back(Acir::Opcode{ .value = Acir::Opcode::BrilligCall{ + .id = 0, .inputs = {}, .outputs = {}, .predicate = expression({}, {}, 1) } }); + + // An AssertZero after the generic and Brillig paths. + ops.push_back(assert_zero(expression({ { 1, 38, 39 } }, { { 1, 40 } }, 0))); + + // Skipped fields: a str8 function name, uint64 error selectors and nested expressions in the assert messages. + circuit.function_name = std::string(40, 'f'); + circuit.assert_messages.emplace_back( + Acir::OpcodeLocation{ .value = Acir::OpcodeLocation::Acir{ .value = 3 } }, + Acir::AssertionPayload{ + .error_selector = 14990209321349310352ULL, + .payload = { + Acir::ExpressionOrMemory{ + .value = Acir::ExpressionOrMemory::Expression{ .value = expression({}, { { 1, 2 } }, 0) } }, + Acir::ExpressionOrMemory{ .value = Acir::ExpressionOrMemory::Memory{ .value = { 0 } } } } }); + circuit.assert_messages.emplace_back(Acir::OpcodeLocation{ .value = Acir::OpcodeLocation::Acir{ .value = 70000 } }, + Acir::AssertionPayload{ .error_selector = 1, .payload = {} }); + circuit.private_parameters = { { 1 }, { 2 }, { 300 }, { 70000 } }; + circuit.public_parameters = Acir::PublicInputs{ .value = { { 3 }, { 4 } } }; + circuit.return_values = Acir::PublicInputs{ .value = { { 40 } } }; + return circuit; +} + +// mul_quad_, MemOp and BlockConstraint have no operator==, so AcirFormat's defaulted one is not usable. +auto quad_fields(const QuadConstraint& q) +{ + return std::make_tuple( + q.a, q.b, q.c, q.d, q.mul_scaling, q.a_scaling, q.b_scaling, q.c_scaling, q.d_scaling, q.const_scaling); +} + +void expect_same_quads(const std::vector& lhs, const std::vector& rhs) +{ + ASSERT_EQ(lhs.size(), rhs.size()); + for (size_t i = 0; i < lhs.size(); ++i) { + EXPECT_EQ(quad_fields(lhs[i]), quad_fields(rhs[i])); + } +} + +void expect_same_acir_format(const AcirFormat& lhs, const AcirFormat& rhs) +{ + EXPECT_EQ(lhs.max_witness_index, rhs.max_witness_index); + EXPECT_EQ(lhs.num_acir_opcodes, rhs.num_acir_opcodes); + EXPECT_EQ(lhs.public_inputs, rhs.public_inputs); + EXPECT_EQ(lhs.range_constraints, rhs.range_constraints); + expect_same_quads(lhs.quad_constraints, rhs.quad_constraints); + ASSERT_EQ(lhs.big_quad_constraints.size(), rhs.big_quad_constraints.size()); + for (size_t i = 0; i < lhs.big_quad_constraints.size(); ++i) { + expect_same_quads(lhs.big_quad_constraints[i], rhs.big_quad_constraints[i]); + } + EXPECT_EQ(lhs.bilinear_constraints, rhs.bilinear_constraints); + EXPECT_EQ(lhs.batched_eq_check_constraints, rhs.batched_eq_check_constraints); + ASSERT_EQ(lhs.block_constraints.size(), rhs.block_constraints.size()); + for (size_t i = 0; i < lhs.block_constraints.size(); ++i) { + const auto& lhs_block = lhs.block_constraints[i]; + const auto& rhs_block = rhs.block_constraints[i]; + EXPECT_EQ(lhs_block.init, rhs_block.init); + EXPECT_EQ(lhs_block.type, rhs_block.type); + EXPECT_EQ(lhs_block.calldata_id, rhs_block.calldata_id); + ASSERT_EQ(lhs_block.trace.size(), rhs_block.trace.size()); + for (size_t j = 0; j < lhs_block.trace.size(); ++j) { + EXPECT_EQ(lhs_block.trace[j].access_type, rhs_block.trace[j].access_type); + EXPECT_EQ(lhs_block.trace[j].index, rhs_block.trace[j].index); + EXPECT_EQ(lhs_block.trace[j].value, rhs_block.trace[j].value); + } + } + EXPECT_EQ(lhs.original_opcode_indices, rhs.original_opcode_indices); +} + +} // namespace + +TEST(AcirCompactDecoder, MatchesCircuitConversion) +{ + const Acir::Circuit circuit = test_circuit(); + for (const bool is_mega : { false, true }) { + const AcirFormat expected = circuit_serde_to_acir_format(circuit, is_mega); + const AcirFormat decoded = circuit_buf_to_acir_format(serialize_program(circuit), is_mega); + expect_same_acir_format(decoded, expected); + EXPECT_EQ(decoded.max_witness_index, 5000000U); + EXPECT_EQ(decoded.num_acir_opcodes, circuit.opcodes.size()); + EXPECT_FALSE(decoded.quad_constraints.empty()); + EXPECT_FALSE(decoded.big_quad_constraints.empty()); + EXPECT_EQ(decoded.range_constraints.size(), 2U); + EXPECT_EQ(decoded.block_constraints.size(), 1U); + } +} + +TEST(AcirCompactDecoder, RejectsTruncatedAssertMessages) +{ + std::vector buf = serialize_program(test_circuit()); + // The assert messages are the last field of the circuit; the empty unconstrained function list follows them. + buf.resize(buf.size() - 2); + EXPECT_THROW_WITH_MESSAGE(circuit_buf_to_acir_format(std::move(buf), /*is_mega=*/true), "malformed msgpack data"); +} diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp index 1e00e84..b32caa9 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.cpp @@ -11,6 +11,8 @@ #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/log.hpp" #include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/dsl/acir_format/recursion_splice.hpp" +#include "barretenberg/dsl/acir_format/sha256_splice.hpp" #include "barretenberg/flavor/flavor.hpp" #include "barretenberg/honk/prover_instance_inspector.hpp" #include "barretenberg/stdlib/eccvm_verifier/verifier_commitment_key.hpp" @@ -26,6 +28,7 @@ #include #include #include +#include #include namespace acir_format { @@ -124,6 +127,18 @@ void translate_opcodes(Translation_& translation, template void build_constraints(Builder& builder, AcirFormat& constraints, const ProgramMetadata& metadata) { + // Scratch builds of the leading Honk recursion constraints and of the SHA-256 compression chunks start before any + // opcode reaches the builder, so they overlap with everything built before those constraints. Per-opcode gate + // counts need every compression built in place. + std::unique_ptr splicer; + std::unique_ptr sha256_splicer; + if constexpr (std::is_same_v) { + splicer = RecursionSplicer::launch(builder, constraints.honk_recursion_constraints); + if (!metadata.collect_gates_per_opcode) { + sha256_splicer = Sha256RunSplicer::launch(builder, constraints.sha256_compression, metadata.sha256_run); + } + } + bool collect_gates_per_opcode = metadata.collect_gates_per_opcode; if (collect_gates_per_opcode) { @@ -224,11 +239,23 @@ void build_constraints(Builder& builder, AcirFormat& constraints, const ProgramM [](auto& target, auto& constraint) { create_aes128_constraints(target, constraint); }); // Add sha256 constraints - translate_opcodes<"acir::sha256_compression", GateKind::Lookup>( - translation, - constraints.sha256_compression, - opcode_indices.sha256_compression, - [](auto& target, auto& constraint) { create_sha256_compression_constraints(target, constraint); }); + if constexpr (std::is_same_v) { + BB_ASSERT_EQ(constraints.sha256_compression.size(), + opcode_indices.sha256_compression.size(), + "Each ACIR constraint must carry the index of the opcode it came from."); + BB_BENCH_ONLY_NAME("acir::sha256_compression"); + build_sha256_compressions( + builder, constraints.sha256_compression, sha256_splicer.get(), metadata.sha256_run, [&](const size_t i) { + gate_counter.track_diff(constraints.gates_per_opcode, opcode_indices.sha256_compression[i]); + }); + sha256_splicer.reset(); + } else { + translate_opcodes<"acir::sha256_compression", GateKind::Lookup>( + translation, + constraints.sha256_compression, + opcode_indices.sha256_compression, + [](auto& target, auto& constraint) { create_sha256_compression_constraints(target, constraint); }); + } // Add ECDSA k1 constraints translate_opcodes<"acir::ecdsa_k1_constraints", GateKind::Nnf>( @@ -322,7 +349,9 @@ void build_constraints(Builder& builder, AcirFormat& constraints, const ProgramM /*hn_recursion_data=*/ { constraints.hn_recursion_constraints, constraints.original_opcode_indices.hn_recursion_constraints }, /*chonk_recursion_data=*/ - { constraints.chonk_recursion_constraints, constraints.original_opcode_indices.chonk_recursion_constraints }); + { constraints.chonk_recursion_constraints, constraints.original_opcode_indices.chonk_recursion_constraints }, + splicer.get()); + splicer.reset(); // Process the result of adding recursion constraints and propagate the public inputs as needed output.finalize(builder, is_hn_recursion_constraints, metadata.has_ipa_claim); diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp index 5f564cc..a62af05 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/acir_format.hpp @@ -26,6 +26,7 @@ #include "range_constraint.hpp" #include "recursion_constraint.hpp" #include "sha256_constraint.hpp" +#include "sha256_splice.hpp" #include #include #include @@ -138,6 +139,7 @@ struct AcirProgram { * 2. When we add constraints to rollup circuits, we need to know whether the circuit should propagate an IPA claim or * recursively verify it. The boolean has_ipa_claim specifies what the circuit should do with an IPA claim. * 3. If we wish to collect the number of gates added by each opcode, we set collect_gates_per_opcode to true. + * 4. sha256_run decides how an Ultra circuit's SHA-256 compressions are cut into chunks built on scratch threads. */ struct ProgramMetadata { // An IVC instance; needed to construct a circuit from IVC recursion constraints @@ -148,6 +150,7 @@ struct ProgramMetadata { // should propagate an IPA claim. In our codebase, circuits that propagate IPA claims are the ones whose // proof is constructed/verified using Rollup flavors. bool collect_gates_per_opcode = false; + Sha256RunOptions sha256_run; }; /** diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/honk_recursion_constraint.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/honk_recursion_constraint.cpp index f2c3b2b..19ebcc9 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/honk_recursion_constraint.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/honk_recursion_constraint.cpp @@ -78,6 +78,17 @@ HonkRecursionConstraintOutput create_honk_recur /*acir_public_inputs_size=*/input.public_inputs.size())); } + // Steps 2 and 3 read the proof and vk only in write vk mode or under a witness predicate, so skip constructing + // them otherwise. Later random draws become witness values, so make the same draws construction would; that + // is possible only without ZK, as a ZK prover draws masking values of its own. + if constexpr (!NativeFlavor::HasZK) { + if (predicate.is_constant()) { + discard_arbitrary_valid_honk_proof_randomness( + /*acir_public_inputs_size=*/input.public_inputs.size()); + return {}; + } + } + return construct_arbitrary_valid_honk_proof_and_vk( /*acir_public_inputs_size=*/input.public_inputs.size()); }(); diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.cpp index 3436771..fc10caf 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.cpp @@ -1,14 +1,18 @@ #include "mock_verifier_inputs.hpp" +#include "barretenberg/commitment_schemes/ipa/ipa.hpp" #include "barretenberg/commitment_schemes/small_subgroup_ipa/small_subgroup_ipa_utils.hpp" #include "barretenberg/common/throw_or_abort.hpp" #include "barretenberg/constants.hpp" #include "barretenberg/flavor/flavor.hpp" #include "barretenberg/flavor/multilinear_batching_flavor.hpp" #include "barretenberg/stdlib/primitives/curves/bn254.hpp" +#include "barretenberg/stdlib/primitives/curves/grumpkin.hpp" #include "barretenberg/ultra_honk/ultra_prover.hpp" #include "barretenberg/ultra_honk/ultra_verifier.hpp" #include "barretenberg/vm2/constraining/flavor.hpp" +#include + namespace acir_format { using namespace bb; @@ -49,6 +53,8 @@ template HonkProof create_mock_oink_proof( for (const auto& pub : builder.public_inputs()) { proof.emplace_back(builder.get_variable(pub)); } + // The builder is discarded here, so wait for a pending IPA proof now: its failure must not go unnoticed. + builder.resolve_ipa_proof(); // Populate mock witness polynomial commitments populate_field_elements_for_mock_commitments(proof, Flavor::NUM_WITNESS_ENTITIES); @@ -223,21 +229,60 @@ HonkProof create_mock_avm_proof_without_pub_inputs() return proof; } +namespace { + +/** + * @brief The random values from which construct_arbitrary_valid_honk_proof_and_vk builds its circuit + */ +struct ArbitraryCircuitRandomness { + std::array gate_inputs{}; + std::vector public_inputs; + Polynomial ipa_polynomial; // drawn only when the IO carries an IPA claim + fq ipa_challenge = fq::zero(); +}; + +/** + * @brief Draw the random values of construct_arbitrary_valid_honk_proof_and_vk + * @details construct_arbitrary_valid_honk_proof_and_vk and discard_arbitrary_valid_honk_proof_randomness draw only + * through this function, so both leave the engine in the same state. + */ +template +ArbitraryCircuitRandomness draw_arbitrary_circuit_randomness(const size_t acir_public_inputs_size, numeric::RNG* engine) +{ + ArbitraryCircuitRandomness randomness; + for (fr& value : randomness.gate_inputs) { + value = fr::random_element(engine); + } + randomness.public_inputs.reserve(acir_public_inputs_size); + for (size_t i = 0; i < acir_public_inputs_size; ++i) { + randomness.public_inputs.emplace_back(fr::random_element(engine)); + } + if constexpr (IO::HasIPA) { + auto [polynomial, challenge] = IPA>::sample_random_opening(engine); + randomness.ipa_polynomial = std::move(polynomial); + randomness.ipa_challenge = challenge; + } + return randomness; +} + +} // namespace + template std::pair> construct_arbitrary_valid_honk_proof_and_vk( - const size_t acir_public_inputs_size) + const size_t acir_public_inputs_size, numeric::RNG* engine) { using ProverInstance = ProverInstance_; using InnerProver = bb::UltraProver_; using VerificationKey = Flavor::VerificationKey; using Builder = typename Flavor::CircuitBuilder; + const ArbitraryCircuitRandomness randomness = + draw_arbitrary_circuit_randomness(acir_public_inputs_size, engine); + // Construct a circuit with a single gate Builder builder; - fr a = fr::random_element(); - fr b = fr::random_element(); - fr c = fr::random_element(); + const auto& [a, b, c] = randomness.gate_inputs; fr d = a + b + c; uint32_t a_idx = builder.add_variable(a); @@ -248,11 +293,15 @@ std::pair> construc builder.create_big_add_gate({ a_idx, b_idx, c_idx, d_idx, fr(1), fr(1), fr(1), fr(-1), fr(0) }); // Add the public inputs - for (size_t i = 0; i < acir_public_inputs_size; ++i) { - builder.add_public_variable(fr::random_element()); + for (const fr& public_input : randomness.public_inputs) { + builder.add_public_variable(public_input); } - IO::add_default(builder); + if constexpr (IO::HasIPA) { + IO::add_default(builder, randomness.ipa_polynomial, randomness.ipa_challenge); + } else { + IO::add_default(builder); + } // prove the circuit constructed above // Create the decider proving key @@ -265,6 +314,13 @@ std::pair> construc return std::pair(honk_proof, vk); } +template +void discard_arbitrary_valid_honk_proof_randomness(const size_t acir_public_inputs_size, numeric::RNG* engine) + requires(!Flavor::HasZK) +{ + draw_arbitrary_circuit_randomness(acir_public_inputs_size, engine); +} + Goblin::MergeProof create_mock_merge_proof() { Goblin::MergeProof proof; @@ -650,12 +706,19 @@ template HonkProof create_mock_honk_proof> construct_arbitrary_valid_honk_proof_and_vk>( - const size_t); + const size_t, numeric::RNG*); template std::pair> construct_arbitrary_valid_honk_proof_and_vk>( - const size_t); + const size_t, numeric::RNG*); template std::pair> -construct_arbitrary_valid_honk_proof_and_vk(const size_t); +construct_arbitrary_valid_honk_proof_and_vk(const size_t, + numeric::RNG*); + +template void discard_arbitrary_valid_honk_proof_randomness>( + const size_t, numeric::RNG*); +template void discard_arbitrary_valid_honk_proof_randomness( + const size_t, numeric::RNG*); template HonkProof create_mock_sumcheck_to_accumulator_proof>(); diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.hpp index 1ab158f..1dd297c 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs.hpp @@ -7,6 +7,7 @@ #pragma once #include "barretenberg/chonk/chonk.hpp" #include "barretenberg/goblin/goblin.hpp" +#include "barretenberg/numeric/random/engine.hpp" #include namespace acir_format { @@ -93,10 +94,21 @@ bb::HonkProof create_mock_avm_proof_without_pub_inputs(); * @tparam IO The IO type that determines public inputs handling and whether IPA proof is included * @param acir_public_inputs_size Number of public inputs coming from the ACIR constraints * @param make_proof_invalid If true, the proof is an invalid proof + * @param engine Source of the circuit's random values; the default engine if null. A ZK prover draws its masking + * values from the default engine regardless. */ template std::pair> construct_arbitrary_valid_honk_proof_and_vk( - size_t acir_public_inputs_size); + size_t acir_public_inputs_size, bb::numeric::RNG* engine = nullptr); + +/** + * @brief Make exactly the random draws of construct_arbitrary_valid_honk_proof_and_vk, without building or proving. + * @details For callers that do not need the proof but must leave the engine where constructing it would. Only + * non-ZK flavors qualify: their provers draw nothing, whereas a ZK prover draws masking values, some on worker threads. + */ +template +void discard_arbitrary_valid_honk_proof_randomness(size_t acir_public_inputs_size, bb::numeric::RNG* engine = nullptr) + requires(!Flavor::HasZK); /** * @brief Create a mock merge proof which has the correct structure but is not necessarily valid diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs_randomness.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs_randomness.test.cpp new file mode 100644 index 0000000..5243efa --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/mock_verifier_inputs_randomness.test.cpp @@ -0,0 +1,68 @@ +#include "barretenberg/dsl/acir_format/mock_verifier_inputs.hpp" +#include "barretenberg/flavor/ultra_flavor.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp" + +#include +#include + +using namespace acir_format; +using namespace bb; + +namespace { + +/** + * @brief Reset the debug engine to a fixed state and return it + * @details The default engine (numeric::get_randomness) reads the OS CSPRNG and cannot be reset, so the functions under + * test are given this engine explicitly. + */ +numeric::RNG& reset_debug_engine() +{ + return numeric::get_debug_randomness(/*reset=*/true, /*seed=*/4321U); +} + +fr next_debug_draw() +{ + return fr::random_element(&numeric::get_debug_randomness()); +} + +} // namespace + +template class MockVerifierInputsRandomnessTest : public ::testing::Test { + public: + static void SetUpTestSuite() { bb::srs::init_file_crs_factory(bb::srs::bb_crs_path()); } +}; + +using IOTypes = + ::testing::Types, stdlib::recursion::honk::RollupIO>; +TYPED_TEST_SUITE(MockVerifierInputsRandomnessTest, IOTypes); + +/** + * @brief Discarding the randomness of an arbitrary valid proof leaves the engine where constructing the proof does + * @details Construction is also checked to depend on no randomness beyond the given engine: two constructions from + * the same engine state produce the same proof and VK, which they would not if the prover drew masking values from + * the default engine. + */ +TYPED_TEST(MockVerifierInputsRandomnessTest, DiscardDrawsAsConstructionDoes) +{ + using IO = TypeParam; + + for (const size_t num_public_inputs : std::array{ 0, 5 }) { + const auto [proof, vk] = + construct_arbitrary_valid_honk_proof_and_vk(num_public_inputs, &reset_debug_engine()); + const fr draw_after_construction = next_debug_draw(); + + const auto [proof_again, vk_again] = + construct_arbitrary_valid_honk_proof_and_vk(num_public_inputs, &reset_debug_engine()); + EXPECT_EQ(proof, proof_again); + EXPECT_EQ(*vk, *vk_again); + + discard_arbitrary_valid_honk_proof_randomness(num_public_inputs, &reset_debug_engine()); + const fr draw_after_discard = next_debug_draw(); + + EXPECT_EQ(draw_after_discard, draw_after_construction) << "num_public_inputs = " << num_public_inputs; + // Both paths draw from the given engine, so the next draw is not its first one. + EXPECT_NE(draw_after_discard, fr::random_element(&reset_debug_engine())); + } +} diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.cpp index 7289228..25bf0a5 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.cpp @@ -10,6 +10,7 @@ #include "barretenberg/dsl/acir_format/chonk_recursion_constraints.hpp" #include "barretenberg/dsl/acir_format/honk_recursion_constraint.hpp" #include "barretenberg/dsl/acir_format/hypernova_recursion_constraint.hpp" +#include "barretenberg/dsl/acir_format/recursion_splice.hpp" #include "barretenberg/dsl/acir_format/utils.hpp" namespace acir_format { @@ -25,7 +26,8 @@ HonkRecursionConstraintsOutput create_recursion_constraints( const RecursionConstraintData& honk_recursion_data, const RecursionConstraintData& avm_recursion_data, const RecursionConstraintData& hn_recursion_data, - const RecursionConstraintData& chonk_recursion_data) + const RecursionConstraintData& chonk_recursion_data, + [[maybe_unused]] RecursionSplicer* splicer) { static_assert(IsMegaBuilder, "the Ultra arithmetization has its own specialization"); bool has_honk_recursion_constraints = !honk_recursion_data.first.empty(); @@ -87,6 +89,28 @@ HonkRecursionConstraintsOutput create_recursion_constraints( return output; } +HonkRecursionConstraintOutput create_ultra_honk_recursion_constraint( + UltraCircuitBuilder& builder, const RecursionConstraint& constraint) +{ + if (constraint.proof_type == HONK_ZK) { + return create_honk_recursion_constraints, + stdlib::recursion::honk::DefaultIO>(builder, + constraint); + } + if (constraint.proof_type == HONK) { + return create_honk_recursion_constraints, + stdlib::recursion::honk::DefaultIO>(builder, + constraint); + } + if (constraint.proof_type == ROLLUP_HONK || constraint.proof_type == ROOT_ROLLUP_HONK) { + // Use UltraRecursiveFlavor with RollupIO for rollup proofs (IO determines IPA handling) + return create_honk_recursion_constraints, + stdlib::recursion::honk::RollupIO>(builder, constraint); + } + bb::assert_failure("Invalid Honk proof type"); + return {}; +} + template <> HonkRecursionConstraintsOutput create_recursion_constraints( UltraCircuitBuilder& builder, @@ -96,7 +120,8 @@ HonkRecursionConstraintsOutput create_recursion_constraints const RecursionConstraintData& honk_recursion_data, const RecursionConstraintData& avm_recursion_data, const RecursionConstraintData& hn_recursion_data, - const RecursionConstraintData& chonk_recursion_data) + const RecursionConstraintData& chonk_recursion_data, + RecursionSplicer* splicer) { bool has_honk_recursion_constraints = !honk_recursion_data.first.empty(); bool has_avm_recursion_constraints = !avm_recursion_data.first.empty(); @@ -116,26 +141,20 @@ HonkRecursionConstraintsOutput create_recursion_constraints HonkRecursionConstraintsOutput output; - for (const auto& [constraint, opcode_idx] : zip_view(honk_recursion_data.first, honk_recursion_data.second)) { - HonkRecursionConstraintOutput honk_recursion_constraint; - - if (constraint.proof_type == HONK_ZK) { - honk_recursion_constraint = - create_honk_recursion_constraints, - stdlib::recursion::honk::DefaultIO>(builder, - constraint); - } else if (constraint.proof_type == HONK) { - honk_recursion_constraint = - create_honk_recursion_constraints, - stdlib::recursion::honk::DefaultIO>(builder, - constraint); - } else if (constraint.proof_type == ROLLUP_HONK || constraint.proof_type == ROOT_ROLLUP_HONK) { - // Use UltraRecursiveFlavor with RollupIO for rollup proofs (IO determines IPA handling) - honk_recursion_constraint = - create_honk_recursion_constraints, - stdlib::recursion::honk::RollupIO>(builder, constraint); - } else { - bb::assert_failure("Invalid Honk proof type"); + for (size_t index = 0; index < honk_recursion_data.first.size(); ++index) { + const RecursionConstraint& constraint = honk_recursion_data.first[index]; + const size_t opcode_idx = honk_recursion_data.second.at(index); + if (RecursionSpliceTestHooks::before_constraint) { + RecursionSpliceTestHooks::before_constraint(builder, constraint, index); + } + + std::optional> spliced = + splicer != nullptr ? splicer->take(index, constraint, builder) : std::nullopt; + HonkRecursionConstraintOutput honk_recursion_constraint = + spliced.has_value() ? std::move(*spliced) : create_ultra_honk_recursion_constraint(builder, constraint); + + if (RecursionSpliceTestHooks::after_constraint) { + RecursionSpliceTestHooks::after_constraint(builder, constraint, index); } // Update output @@ -146,6 +165,10 @@ HonkRecursionConstraintsOutput create_recursion_constraints gate_counter.track_diff(gates_per_opcode, opcode_idx); } + // No scratch builder outlives the Honk recursion constraints. + if (splicer != nullptr) { + splicer->finish(); + } BB_ASSERT( !(output.is_root_rollup && output.nested_ipa_claims.size() + output.nested_triple_ipa_openings.size() != 2), "Root rollup must accumulate two IPA proofs."); @@ -297,7 +320,8 @@ template HonkRecursionConstraintsOutput create_recursion_con const RecursionConstraintData&, const RecursionConstraintData&, const RecursionConstraintData&, - const RecursionConstraintData&); + const RecursionConstraintData&, + RecursionSplicer*); template HonkRecursionConstraintsOutput create_recursion_constraints( MegaAppCircuitBuilder&, GateCounter&, @@ -306,7 +330,8 @@ template HonkRecursionConstraintsOutput create_recursion_ const RecursionConstraintData&, const RecursionConstraintData&, const RecursionConstraintData&, - const RecursionConstraintData&); + const RecursionConstraintData&, + RecursionSplicer*); template HonkRecursionConstraintsOutput create_recursion_constraints( MegaKernelCircuitBuilder&, GateCounter&, @@ -315,7 +340,8 @@ template HonkRecursionConstraintsOutput create_recursi const RecursionConstraintData&, const RecursionConstraintData&, const RecursionConstraintData&, - const RecursionConstraintData&); + const RecursionConstraintData&, + RecursionSplicer*); template HonkRecursionConstraintsOutput create_recursion_constraints( MegaHidingKernelCircuitBuilder&, GateCounter&, @@ -324,6 +350,7 @@ template HonkRecursionConstraintsOutput create_r const RecursionConstraintData&, const RecursionConstraintData&, const RecursionConstraintData&, - const RecursionConstraintData&); + const RecursionConstraintData&, + RecursionSplicer*); } // namespace acir_format diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.hpp index 77e49f4..31e20a3 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint.hpp @@ -108,6 +108,15 @@ struct RecursionConstraint { // A group of recursion constraints of one proof type, paired with their original ACIR opcode indices. using RecursionConstraintData = std::pair, std::vector>; +class RecursionSplicer; + +/** + * @brief Add one Honk recursion constraint (proof type HONK, HONK_ZK, ROLLUP_HONK or ROOT_ROLLUP_HONK) to an Ultra + * builder. + */ +HonkRecursionConstraintOutput create_ultra_honk_recursion_constraint( + UltraCircuitBuilder& builder, const RecursionConstraint& constraint); + /** * @brief Single entrypoint to process recursion constraints * @@ -134,6 +143,7 @@ using RecursionConstraintData = std::pair, std: * @param avm_recursion_data pair of (AvmRecursionConstraints, AvmRecursionConstraintsOriginalOpcodeIndices) * @param hn_recursion_data pair of (HypernovaRecursionConstraints, HypernovaRecursionConstraintsOriginalOpcodeIndices) * @param chonk_recursion_data pair of (ChonkRecursionConstraints, ChonkRecursionConstraintsOriginalOpcodeIndices) + * @param splicer Scratch builds of the leading Honk recursion constraints, if any were launched (Ultra only) */ template [[nodiscard("pairing points and IPA claim must be accumulated")]] HonkRecursionConstraintsOutput @@ -144,7 +154,8 @@ create_recursion_constraints(Builder& builder, const RecursionConstraintData& honk_recursion_data, const RecursionConstraintData& avm_recursion_data, const RecursionConstraintData& hn_recursion_data, - const RecursionConstraintData& chonk_recursion_data); + const RecursionConstraintData& chonk_recursion_data, + RecursionSplicer* splicer = nullptr); /** * @brief Process HyperNova recursion constraints and complete kernel logic diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.cpp index c9c3e8c..0b8fe8f 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.cpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.cpp @@ -71,7 +71,7 @@ void HonkRecursionConstraintsOutput::update_triple_ipa_opening( } template <> -std::pair>, HonkProof> HonkRecursionConstraintsOutput< +std::pair>, IpaOpeningProofTask<>> HonkRecursionConstraintsOutput< UltraCircuitBuilder>::perform_IPA_accumulation(UltraCircuitBuilder& builder) const { using RecursiveCurve = stdlib::grumpkin; @@ -93,14 +93,16 @@ std::pair>, HonkProof> HonkRe CommitmentKey commitment_key(1 << CONST_ECCVM_LOG_N); if (accumulators.size() == 2) { - return RecursiveIPA::accumulate(commitment_key, std::move(accumulators[0]), std::move(accumulators[1])); + return RecursiveIPA::accumulate_deferred( + commitment_key, std::move(accumulators[0]), std::move(accumulators[1])); } if (accumulators.size() == 1) { - return RecursiveIPA::prove_accumulator_claim(commitment_key, std::move(accumulators[0])); + return RecursiveIPA::prove_accumulator_claim_deferred(commitment_key, std::move(accumulators[0])); } if (accumulators.empty()) { info("Proving with UltraRollupHonk but no IPA claims exist."); - return RecursiveIPA::create_random_valid_ipa_claim_and_proof(builder); + const auto [poly, x] = RecursiveIPA::sample_random_opening(); + return RecursiveIPA::create_valid_ipa_claim_deferred(builder, poly, x); } throw_or_abort("Too many nested IPA accumulators to accumulate"); } @@ -117,7 +119,8 @@ void HonkRecursionConstraintsOutput::perform_full_IPA_verif 2U, "Root rollup must accumulate two IPA proofs."); - auto [ipa_claim, ipa_proof] = perform_IPA_accumulation(builder); + auto [ipa_claim, ipa_proof_task] = perform_IPA_accumulation(builder); + const HonkProof ipa_proof = ipa_proof_task.prove(); // IPA verification VerifierCommitmentKey> verifier_commitment_key( @@ -138,10 +141,10 @@ void HonkRecursionConstraintsOutput::finalize(UltraCircuitB using IO = stdlib::recursion::honk::RollupIO; // We have multiple IPA claims, we need to accumulate them - auto [ipa_claim, ipa_proof] = perform_IPA_accumulation(builder); + auto [ipa_claim, ipa_proof_task] = perform_IPA_accumulation(builder); - // Set proof - builder.ipa_proof = ipa_proof; + // Nothing reads the proof before the circuit is proven, so it is computed in the background meanwhile + builder.set_pending_ipa_proof(std::move(ipa_proof_task).launch()); // Propagate pairing points and ipa claim IO inputs; diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.hpp index 1030c75..f1e736c 100644 --- a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.hpp +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_constraint_output.hpp @@ -6,6 +6,7 @@ #pragma once #include "barretenberg/commitment_schemes/claim.hpp" +#include "barretenberg/commitment_schemes/ipa/ipa.hpp" #include "barretenberg/eccvm/eccvm_verifier.hpp" #include "barretenberg/stdlib/eccvm_verifier/verifier_commitment_key.hpp" #include "barretenberg/stdlib/honk_verifier/ipa_accumulator.hpp" @@ -64,10 +65,11 @@ template struct HonkRecursionConstraintsOutput { private: /** - * @brief Accumulate the IPA claims and proofs held in this output + * @brief Accumulate the IPA claims and proofs held in this output into one claim, returned with the task that + * computes its native opening proof */ [[nodiscard("IPA claim should be accumulated, IPA proof should be propagated")]] std:: - pair>, HonkProof> + pair>, IpaOpeningProofTask<>> perform_IPA_accumulation(Builder& builder) const; /** diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.cpp new file mode 100644 index 0000000..68ba33e --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.cpp @@ -0,0 +1,394 @@ +#include "barretenberg/dsl/acir_format/recursion_splice.hpp" + +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/dsl/acir_format/honk_recursion_constraint.hpp" +#include "barretenberg/dsl/acir_format/mock_verifier_inputs.hpp" +#include "barretenberg/dsl/acir_format/scratch_build.hpp" +#include "barretenberg/ecc/curves/bn254/g1.hpp" +#include "barretenberg/flavor/ultra_flavor.hpp" +#include "barretenberg/stdlib/primitives/builder_binding.hpp" +#include "barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp" + +#include +#include +#include +#include +#include + +namespace acir_format { + +#if BB_SCRATCH_BUILDS_AVAILABLE + +namespace { + +using scratch_build::message_of; +using scratch_build::milliseconds_between; +using scratch_build::MIN_THREADS; +using scratch_build::refusal_reason; +using scratch_build::return_freed_memory; +using scratch_build::ScratchCancellation; +using scratch_build::ScratchThread; + +/** + * @brief Whether a scratch build may start for `constraint` on a builder of `num_variables` variables. + * @details Its inputs are read when it starts, before the serial build would reject a malformed constraint, so each + * must be a variable of the builder. + */ +bool is_eligible(const RecursionConstraint& constraint, const size_t num_variables) +{ + const auto exists = [num_variables](const uint32_t index) { return index < num_variables; }; + return (constraint.proof_type == HONK || constraint.proof_type == ROLLUP_HONK || + constraint.proof_type == ROOT_ROLLUP_HONK) && + constraint.predicate.is_constant && constraint.predicate.value == bb::fr::one() && + std::ranges::all_of(constraint.proof, exists) && std::ranges::all_of(constraint.key, exists) && + std::ranges::all_of(constraint.public_inputs, exists) && exists(constraint.key_hash); +} + +/** + * @brief The draws an eligible constraint makes: the replay of the proof construction it skips, then the offset + * generator of the edge-case multiplication in its KZG batch opening. + * @details A prediction only: a splice is accepted only when the engine stands where the scratch build started, and + * the scratch build reports where it ended. + */ +void predicted_draws(const RecursionConstraint& constraint) +{ + const size_t num_public_inputs = constraint.public_inputs.size(); + if (constraint.proof_type == ROLLUP_HONK || constraint.proof_type == ROOT_ROLLUP_HONK) { + discard_arbitrary_valid_honk_proof_randomness( + num_public_inputs); + } else { + discard_arbitrary_valid_honk_proof_randomness>( + num_public_inputs); + } + [[maybe_unused]] const bb::g1::element offset_generator = bb::g1::element::random_element(); +} + +} // namespace + +struct RecursionSplicer::Scratch { + size_t index; + // The constraint as launched; take() splices only for an equal one. + RecursionConstraint original; + // seed_indices[i] is the real index of scratch input variable i; `constraint` names scratch inputs instead. + std::vector seed_indices; + std::vector seed_values; + RecursionConstraint constraint; + bb::numeric::RNG::Position start; + ScratchCancellation cancellation; + + // Written by the scratch thread, read by the building thread after the join or after reading `finished` true. + std::unique_ptr builder; + std::optional> output; + bb::numeric::RNG::Position reached; + std::exception_ptr error; + Clock::time_point finished_at; + std::atomic finished = false; + + bb::numeric::RNG* engine = nullptr; + ScratchThread thread; + + // Inputs are numbered by distinct real index at first appearance in the order proof, key, public inputs, key + // hash, so two inputs share a scratch variable exactly when they share a real one. + Scratch(const UltraCircuitBuilder& real, const RecursionConstraint& launched, const size_t scratch_index) + : index(scratch_index) + , original(launched) + , constraint(launched) + , cancellation("RecursionSplicer", [scratch_index, num_checks = size_t{ 0 }]() mutable { + // Only the scratch thread counts. + if (RecursionSpliceTestHooks::scratch_recording) { + RecursionSpliceTestHooks::scratch_recording(scratch_index, ++num_checks); + } + }) + { + std::unordered_map seed_of; + const auto seed = [&](uint32_t& index) { + const auto [it, inserted] = seed_of.try_emplace(index, static_cast(seed_indices.size())); + if (inserted) { + seed_indices.push_back(index); + seed_values.push_back(real.get_variable(index)); + } + index = it->second; + }; + for (uint32_t& index : constraint.proof) { + seed(index); + } + for (uint32_t& index : constraint.key) { + seed(index); + } + for (uint32_t& index : constraint.public_inputs) { + seed(index); + } + seed(constraint.key_hash); + } + + /** + * @brief Runs build() on a scratch thread of its own; throws when it cannot start. + */ + void start_thread(bb::numeric::RNG& draw_engine) + { + engine = &draw_engine; + const bool started = thread.start( + [](void* scratch) -> void* { + static_cast(scratch)->build(); + return nullptr; + }, + this); + if (!started) { + throw_or_abort("RecursionSplicer: could not start a scratch thread"); + } + } + + void join() { thread.join(); } + + // Throws nothing: whatever the build throws is kept in `error`. + void build() noexcept + { + try { + // parallel_for's core count and pool are per thread, so at one core this thread's loops run inline + // instead of starting a worker pool of its own. + bb::set_parallel_for_concurrency(1); + const std::unique_ptr scope = engine->draw_from(start); + builder = + std::make_unique(SpliceRecording{ .cancellation = &cancellation }, seed_values); + output = create_ultra_honk_recursion_constraint(*builder, constraint); + reached = scope->reached(); + if (RecursionSpliceTestHooks::after_scratch_build) { + RecursionSpliceTestHooks::after_scratch_build(index); + } + } catch (...) { + error = std::current_exception(); + } + finished_at = Clock::now(); + finished.store(true, std::memory_order_release); + } + + // Called once the scratch thread is joined. Freed memory is returned first, while the builder still lives. + void discard() + { + if (!builder) { + return; + } + return_freed_memory(); + output.reset(); + builder.reset(); + if (RecursionSpliceTestHooks::discarded) { + RecursionSpliceTestHooks::discarded(index); + } + } +}; + +RecursionSplicer::RecursionSplicer(bb::numeric::RNG& engine) + : engine_(engine) +{} + +RecursionSplicer::~RecursionSplicer() +{ + reap(); +} + +void RecursionSplicer::reap() +{ + // Requested of every running build first, so a join waits only until that build's next recording, or its end. + for (const auto& scratch : scratches_) { + if (scratch->thread.running()) { + scratch->cancellation.request(); + } + } + for (const auto& scratch : scratches_) { + scratch->join(); + scratch->discard(); + } +} + +void RecursionSplicer::finish() +{ + reap(); + report(); +} + +std::unique_ptr RecursionSplicer::launch(const UltraCircuitBuilder& builder, + const std::vector& honk_constraints) +{ + const size_t num_variables = builder.get_num_variables(); + if (RecursionSpliceTestHooks::disabled || builder.is_write_vk_mode() || honk_constraints.empty() || + !is_eligible(honk_constraints.front(), num_variables)) { + return nullptr; + } + const size_t num_threads = bb::get_num_cpus(); + if (num_threads < MIN_THREADS) { + return nullptr; + } + std::unique_ptr splicer(new RecursionSplicer(bb::numeric::get_randomness())); + bb::numeric::RNG& engine = splicer->engine_; + try { + // Honk recursion constraints are built first and every later kind is ineligible, so the walk ends in this + // list. Each start position is the previous one moved by the previous constraint's predicted draws. + bb::numeric::RNG::Position position = engine.position(); + for (const RecursionConstraint& constraint : honk_constraints) { + if (splicer->scratches_.size() == num_threads - 1 || !is_eligible(constraint, num_variables)) { + break; + } + auto scratch = std::make_unique(builder, constraint, splicer->scratches_.size()); + scratch->start = position; + position = + engine.after(position, [&constraint](bb::numeric::RNG& /*engine*/) { predicted_draws(constraint); }); + splicer->scratches_.push_back(std::move(scratch)); + } + splicer->launched_at_ = Clock::now(); + for (const auto& scratch : splicer->scratches_) { + scratch->start_thread(engine); + ++splicer->stats_.launched; + } + } catch (...) { + // A launch that fails splices nothing; the destructor joins the threads already started. + return nullptr; + } + if (splicer->scratches_.empty()) { + return nullptr; + } + return splicer; +} + +void RecursionSplicer::refuse(Scratch& scratch, std::string reason) +{ + if (stats_.refused == 0) { + stats_.first_refusal = std::move(reason); + } + ++stats_.refused; + scratch.discard(); +} + +std::optional> RecursionSplicer::take( + const size_t index, const RecursionConstraint& constraint, UltraCircuitBuilder& builder) +{ + if (index >= scratches_.size()) { + return std::nullopt; + } + Scratch& scratch = *scratches_[index]; + if (!(constraint == scratch.original)) { + scratch.cancellation.request(); + scratch.join(); + refuse(scratch, "the constraint changed since the scratch build started"); + return std::nullopt; + } + if (index == 0 && !wait_for_first(scratch)) { + return std::nullopt; + } + scratch.join(); + if (index == 0) { + first_finished_at_ = scratch.finished_at; + } + if (scratch.error) { + const std::string message = message_of(scratch.error); + vinfo("recursion splice: the scratch build of Honk recursion constraint ", index, " threw: ", message); + refuse(scratch, "the scratch build threw: " + message); + return std::nullopt; + } + // Before the splice: the scratch build drew what the serial build would draw only from the position it started at. + if (!engine_.at(scratch.start)) { + refuse(scratch, "the engine moved since the scratch build started"); + return std::nullopt; + } + const SpliceResult result = builder.splice(*scratch.builder, scratch.seed_indices); + if (!result.spliced()) { + refuse(scratch, refusal_reason(result.refusal)); + return std::nullopt; + } + engine_.adopt(scratch.reached); + HonkRecursionConstraintOutput output = std::move(*scratch.output); + stdlib::rebind_to_builder(output, &builder, result.index_map, result.pairing_tag_offset); + BB_ASSERT_DEBUG(stdlib::count_contexts_on(output, scratch.builder.get()) == 0, + "RecursionSplicer: a spliced output still refers to its scratch builder"); + scratch.discard(); + ++stats_.spliced; + return output; +} + +/** + * @brief Whether take(0) waits for scratch build 0; when not, the build is cancelled, its thread left to stop at its + * next recording, and the constraint is built in place. + */ +bool RecursionSplicer::wait_for_first(Scratch& scratch) +{ + first_reached_at_ = Clock::now(); + const bool finished = scratch.finished.load(std::memory_order_acquire); + if (finished) { + first_finished_at_ = scratch.finished_at; + } + const FirstTake policy = RecursionSpliceTestHooks::first_take; + if (policy == FirstTake::Wait || (policy == FirstTake::Auto && finished)) { + return true; + } + scratch.cancellation.request(); + ++stats_.built_in_place; + return false; +} + +std::string RecursionSplicer::summary() const +{ + std::string line = std::to_string(stats_.spliced) + " of " + std::to_string(stats_.launched) + " spliced, " + + std::to_string(stats_.refused) + " refused, " + std::to_string(stats_.built_in_place) + + " built in place"; + std::string detail; + if (first_reached_at_.has_value()) { + detail = + "head start " + std::to_string(milliseconds_between(launched_at_, *first_reached_at_)) + " ms, scratch 0 "; + if (!first_finished_at_.has_value()) { + detail += "not finished"; + } else if (RecursionSpliceTestHooks::first_take == FirstTake::Wait) { + // Negative when the building thread had to wait. + detail += "margin " + std::to_string(milliseconds_between(*first_finished_at_, *first_reached_at_)) + " ms"; + } else { + detail += "finished " + std::to_string(milliseconds_between(*first_finished_at_, *first_reached_at_)) + + " ms earlier"; + } + } + if (stats_.refused > 0) { + detail += (detail.empty() ? "" : "; ") + std::string("first refusal: ") + stats_.first_refusal; + } + return detail.empty() ? line : line + " (" + detail + ")"; +} + +void RecursionSplicer::report() const +{ + vinfo("recursion splice: ", summary()); + if (RecursionSpliceTestHooks::stats != nullptr) { + *RecursionSpliceTestHooks::stats = stats_; + } +} + +#else + +struct RecursionSplicer::Scratch {}; + +RecursionSplicer::RecursionSplicer(bb::numeric::RNG& engine) + : engine_(engine) +{} + +RecursionSplicer::~RecursionSplicer() = default; + +std::unique_ptr RecursionSplicer::launch(const UltraCircuitBuilder& /*builder*/, + const std::vector& /*honk_constraints*/) +{ + return nullptr; +} + +void RecursionSplicer::refuse(Scratch& /*scratch*/, std::string /*reason*/) {} + +std::optional> RecursionSplicer::take( + const size_t /*index*/, const RecursionConstraint& /*constraint*/, UltraCircuitBuilder& /*builder*/) +{ + return std::nullopt; +} + +void RecursionSplicer::finish() {} + +void RecursionSplicer::report() const {} + +#endif + +} // namespace acir_format diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.hpp new file mode 100644 index 0000000..bdfd6d8 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.hpp @@ -0,0 +1,146 @@ +#pragma once + +#include "barretenberg/dsl/acir_format/recursion_constraint.hpp" +#include "barretenberg/dsl/acir_format/recursion_constraint_output.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace acir_format { + +/** + * @brief What one circuit build did with its scratch builds. + */ +struct RecursionSpliceStats { + size_t launched = 0; + size_t spliced = 0; + size_t refused = 0; + // Constraints whose scratch build was cancelled because the building thread reached them first. + size_t built_in_place = 0; + // Why the first refused constraint was built serially; empty when none was refused. + std::string first_refusal; +}; + +/** + * @brief How RecursionSplicer::take treats scratch build 0. + */ +enum class FirstTake : uint8_t { + Auto, // splice it when it has finished, otherwise cancel it and build the constraint in place + Wait, // wait for it and splice it + InPlace, // cancel it and build the constraint in place +}; + +/** + * @brief Test-only switches of the recursion splice, all off by default. + * @details Set them only while no circuit is being built. + */ +struct RecursionSpliceTestHooks { + using ConstraintHook = + std::function; + + // Builds every recursion constraint serially. + static inline bool disabled = false; + // Runs on the building thread just before Honk recursion constraint `index` is spliced or built serially. + static inline ConstraintHook before_constraint; + // Runs on the building thread just after Honk recursion constraint `index` was spliced or built serially. + static inline ConstraintHook after_constraint; + // Runs on a scratch thread when its build of constraint `index` has finished; a throw refuses that build. + static inline std::function after_scratch_build; + // Runs on a scratch thread before each recording of its build of constraint `index`, `count` counting from 1, + // before the cancellation check. + static inline std::function scratch_recording; + // Runs on the building thread once the scratch builder of constraint `index` has been destroyed. + static inline std::function discarded; + static inline FirstTake first_take = FirstTake::Auto; + // Receives the counts of each build that started scratch builds. + static inline RecursionSpliceStats* stats = nullptr; +}; + +/** + * @brief Builds the leading eligible Honk recursion constraints of an Ultra circuit on scratch builders on their own + * threads, and splices each into the real builder when the serial order reaches it. + * @details A constraint is eligible when it verifies a plain, rollup or root rollup Honk proof under a constant-true + * predicate. Whether a constraint is spliced or built serially never changes the circuit: a refused constraint is built + * serially on the unchanged builder and engine. + * + * When the building thread reaches the first constraint before its scratch build has finished, that build is + * cancelled and the constraint is built in place, so which path builds it depends on timing. A cancelled build only + * ever had its own builder and its own draws: it never touches the real builder or the real engine, its draws come + * from its draw scope under an engine with positions and from its thread's own buffer otherwise, and they are dropped + * as a refused build's are. It stops by throwing at its next recording. Once the last Honk recursion constraint is + * built, its thread is joined, never detached, its builder destroyed, and its freed memory returned the same way as + * every other scratch build's. + */ +class RecursionSplicer { + public: + /** + * @brief Start one scratch build per leading eligible constraint of `honk_constraints`, at most one fewer than the + * worker threads; null when none starts. + * @details Call on the building thread after `builder` holds the witness and before any opcode reaches it. Starts + * nothing for a builder without a witness, with fewer than three threads, without native threads, pthreads and + * exceptions, under OpenMP, or when starting fails. A constraint naming a witness index the builder does not have + * is not eligible. The engine is get_randomness() and must stay the same object until the last splice. + */ + static std::unique_ptr launch(const bb::UltraCircuitBuilder& builder, + const std::vector& honk_constraints); + + RecursionSplicer(const RecursionSplicer&) = delete; + RecursionSplicer(RecursionSplicer&&) = delete; + RecursionSplicer& operator=(const RecursionSplicer&) = delete; + RecursionSplicer& operator=(RecursionSplicer&&) = delete; + + /** + * @brief Cancel every scratch build still running, join every scratch thread and destroy every scratch builder, + * returning first, on glibc, the memory freed into malloc arenas to the operating system. + */ + ~RecursionSplicer(); + + /** + * @brief Splice the scratch build of Honk recursion constraint `index`, which is `constraint`, into `builder` and + * return its output bound to `builder`; nullopt when the constraint must be built serially. + * @details Call on the building thread exactly where the serial build of that constraint would start, once per + * index in increasing order. On nullopt, `builder` and the engine are unchanged. A `constraint` other than the one + * launched at `index` is refused once its scratch build is cancelled and joined. Otherwise index 0 is spliced only + * if its build has finished, and is else cancelled and nullopt returned at once; a later index waits for its build. + */ + std::optional> take(size_t index, + const RecursionConstraint& constraint, + bb::UltraCircuitBuilder& builder); + + /** + * @brief Once the last Honk recursion constraint is built: cancel, join and destroy every scratch build still held, + * as the destructor does, then log how many constraints were spliced, refused and built in place, why the first + * refusal happened, and how far scratch build 0 was ahead of the building thread. + */ + void finish(); + + private: + struct Scratch; + using Clock = std::chrono::steady_clock; + + explicit RecursionSplicer(bb::numeric::RNG& engine); + void refuse(Scratch& scratch, std::string reason); + bool wait_for_first(Scratch& scratch); + void reap(); + void report() const; + std::string summary() const; + + // Unread in builds without native threads, where nothing is ever launched. + [[maybe_unused]] bb::numeric::RNG& engine_; + std::vector> scratches_; + RecursionSpliceStats stats_; + Clock::time_point launched_at_; + std::optional first_reached_at_; + // When scratch build 0 finished, if take(0) saw it finish. + std::optional first_finished_at_; +}; + +} // namespace acir_format diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.test.cpp new file mode 100644 index 0000000..f37c2fe --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/recursion_splice.test.cpp @@ -0,0 +1,1002 @@ +#include "barretenberg/dsl/acir_format/recursion_splice.hpp" +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/dsl/acir_format/acir_format.hpp" +#include "barretenberg/dsl/acir_format/gate_counter.hpp" +#include "barretenberg/dsl/acir_format/test_class.hpp" +#include "barretenberg/dsl/acir_format/utils.hpp" +#include "barretenberg/dsl/acir_format/witness_constant.hpp" +#include "barretenberg/flavor/ultra_flavor.hpp" +#include "barretenberg/flavor/ultra_zk_flavor.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/numeric/random/entropy_buffer_observer.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp" +#include "barretenberg/stdlib_circuit_builders/mock_circuits.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp" +#include "barretenberg/ultra_honk/prover_instance.hpp" +#include "barretenberg/ultra_honk/ultra_prover.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__GLIBC__) +#include +#endif + +/** + * A circuit whose Honk recursion constraints are built on scratch builders and spliced must equal the serial build of + * the same program in every builder member, and a refused splice or a first constraint built in place must leave the + * serial result. With the seeded engine the variable values and the engine position must match too; with the default + * engine the two builds draw different offset generators, so values are not compared. + */ + +using namespace acir_format; +using namespace bb; + +namespace { + +using Builder = UltraCircuitBuilder; +using bb::test_utils::CompareValues; +using bb::test_utils::expect_same_builder; +using bb::test_utils::expect_same_builder_state; + +// Mirrors the condition under which production starts scratch builds. +#if !defined(NO_MULTITHREADING) && !defined(__wasm__) && !defined(_WIN32) && !defined(OMP_MULTITHREADING) && \ + defined(__cpp_exceptions) && !defined(BB_NO_EXCEPTIONS) +constexpr bool SCRATCH_BUILDS_AVAILABLE = true; +#else +constexpr bool SCRATCH_BUILDS_AVAILABLE = false; +#endif + +constexpr size_t NUM_INNER_PUBLIC_INPUTS = 2; +// The largest range a small range constraint accepts. +constexpr uint64_t MAX_SMALL_RANGE = (1ULL << 16) - 1; + +// A recursion constraint with a constant-true predicate and the witness vector its indices point into. +struct InnerProof { + RecursionConstraint constraint; + WitnessVector witness; +}; + +template InnerProof prove_inner_circuit(const uint32_t proof_type) +{ + Builder builder; + MockCircuits::add_arithmetic_gates(builder); + for (size_t i = 0; i < NUM_INNER_PUBLIC_INPUTS; ++i) { + builder.add_public_variable(fr::random_element()); + } + IO::add_default(builder); + auto prover_instance = std::make_shared>(builder); + auto verification_key = std::make_shared(prover_instance->get_precomputed()); + UltraProver_ prover(prover_instance, verification_key); + const HonkProof proof = prover.construct_proof(); + + InnerProof inner; + inner.constraint = recursion_data_to_recursion_constraint(inner.witness, + proof, + verification_key->to_field_elements(), + verification_key->hash(), + fr::one(), + builder.num_public_inputs() - IO::PUBLIC_INPUTS_SIZE, + proof_type); + // The predicate witness is appended last; a constant predicate leaves it unused. + BB_ASSERT_EQ(static_cast(inner.constraint.predicate.index), inner.witness.size() - 1); + inner.witness.pop_back(); + inner.constraint.predicate = WitnessOrConstant::from_constant(fr::one()); + return inner; +} + +// One program verifying `proofs` in order, each constraint's indices moved past the witnesses before it. +AcirProgram make_program(const std::vector& proofs) +{ + std::vector constraints; + WitnessVector witness; + for (const InnerProof* inner : proofs) { + RecursionConstraint constraint = inner->constraint; + const auto offset = static_cast(witness.size()); + for (std::vector* indices : { &constraint.key, &constraint.proof, &constraint.public_inputs }) { + for (uint32_t& index : *indices) { + index += offset; + } + } + constraint.key_hash += offset; + witness.insert(witness.end(), inner->witness.begin(), inner->witness.end()); + constraints.push_back(std::move(constraint)); + } + return AcirProgram{ .constraints = constraint_to_acir_format(constraints), .witness = witness }; +} + +std::vector inputs_of(const RecursionConstraint& constraint) +{ + std::vector inputs = constraint.proof; + inputs.insert(inputs.end(), constraint.key.begin(), constraint.key.end()); + inputs.insert(inputs.end(), constraint.public_inputs.begin(), constraint.public_inputs.end()); + inputs.push_back(constraint.key_hash); + return inputs; +} + +// Puts a range tag on a small input of Honk recursion constraint `target`, which refuses its splice. +RecursionSpliceTestHooks::ConstraintHook tag_a_small_input(const size_t target) +{ + return [target](Builder& builder, const RecursionConstraint& constraint, const size_t index) { + if (index != target) { + return; + } + const std::vector inputs = inputs_of(constraint); + const auto small = std::ranges::find_if( + inputs, [&](uint32_t input) { return uint256_t(builder.get_variable(input)) <= MAX_SMALL_RANGE; }); + ASSERT_NE(small, inputs.end()); + builder.create_small_range_constraint(*small, MAX_SMALL_RANGE); + }; +} + +// Clears every hook and restores the first-take policy when a test ends, whatever its outcome. +struct HookReset { + HookReset() = default; + HookReset(const HookReset&) = delete; + HookReset(HookReset&&) = delete; + HookReset& operator=(const HookReset&) = delete; + HookReset& operator=(HookReset&&) = delete; + ~HookReset() + { + RecursionSpliceTestHooks::disabled = false; + RecursionSpliceTestHooks::before_constraint = nullptr; + RecursionSpliceTestHooks::after_constraint = nullptr; + RecursionSpliceTestHooks::after_scratch_build = nullptr; + RecursionSpliceTestHooks::scratch_recording = nullptr; + RecursionSpliceTestHooks::discarded = nullptr; + RecursionSpliceTestHooks::stats = nullptr; + RecursionSpliceTestHooks::first_take = first_take; + } + + const FirstTake first_take = RecursionSpliceTestHooks::first_take; +}; + +struct Build { + Builder builder; + RecursionSpliceStats stats; + // The engine position after each Honk recursion constraint, then after the whole build. + std::vector positions; +}; + +// The hooks of one build. Unless a test says otherwise the first constraint waits for its scratch build, so that a +// spliced first constraint is covered whatever the timing. +struct Hooks { + // Runs in serial and spliced builds. + RecursionSpliceTestHooks::ConstraintHook before_constraint; + // Run in spliced builds only. + RecursionSpliceTestHooks::ConstraintHook spliced_before_constraint; + RecursionSpliceTestHooks::ConstraintHook spliced_after_constraint; + std::function after_scratch_build; + std::function scratch_recording; + std::function discarded; + FirstTake first_take = FirstTake::Wait; +}; + +/** + * @brief Build `program` with or without splicing, from the engine position `start` when the engine has positions. + */ +Build build(const AcirProgram& program, + const ProgramMetadata& metadata, + const bool splice, + const numeric::RNG::Position& start, + const Hooks& hooks = {}) +{ + numeric::RNG& engine = numeric::get_randomness(); + if (!start.empty()) { + engine.adopt(start); + } + Build result; + RecursionSpliceTestHooks::disabled = !splice; + RecursionSpliceTestHooks::before_constraint = + [&](Builder& builder, const RecursionConstraint& constraint, const size_t index) { + if (hooks.before_constraint) { + hooks.before_constraint(builder, constraint, index); + } + if (splice && hooks.spliced_before_constraint) { + hooks.spliced_before_constraint(builder, constraint, index); + } + }; + RecursionSpliceTestHooks::after_constraint = + [&](Builder& builder, const RecursionConstraint& constraint, const size_t index) { + result.positions.push_back(engine.position()); + if (splice && hooks.spliced_after_constraint) { + hooks.spliced_after_constraint(builder, constraint, index); + } + }; + RecursionSpliceTestHooks::after_scratch_build = hooks.after_scratch_build; + RecursionSpliceTestHooks::scratch_recording = hooks.scratch_recording; + RecursionSpliceTestHooks::discarded = hooks.discarded; + RecursionSpliceTestHooks::first_take = hooks.first_take; + RecursionSpliceTestHooks::stats = &result.stats; + AcirProgram copy = program; + result.builder = create_circuit(copy, metadata); + result.positions.push_back(engine.position()); + return result; +} + +// Lets one thread wait, for a bounded time, until another sets it. +class Signal { + public: + void set() + { + { + const std::lock_guard lock(mutex_); + set_ = true; + } + condition_.notify_all(); + } + + [[nodiscard]] bool wait() + { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, std::chrono::minutes(2), [this] { return set_; }); + } + + private: + std::mutex mutex_; + std::condition_variable condition_; + bool set_ = false; +}; + +// Owned by a thread through a thread_local, so its destructor runs when that thread exits. +struct ExitMarker { + ExitMarker() = default; + ExitMarker(const ExitMarker&) = delete; + ExitMarker(ExitMarker&&) = delete; + ExitMarker& operator=(const ExitMarker&) = delete; + ExitMarker& operator=(ExitMarker&&) = delete; + ~ExitMarker() + { + if (exited != nullptr) { + exited->store(true); + } + } + + std::atomic* exited = nullptr; +}; + +class RecursionSpliceTest : public ::testing::Test { + protected: + static void SetUpTestSuite() + { + bb::srs::init_file_crs_factory(bb::srs::bb_crs_path()); + using DefaultIO = stdlib::recursion::honk::DefaultIO; + for (size_t i = 0; i < 3; ++i) { + honk_proofs.push_back(prove_inner_circuit(HONK)); + } + zk_proof = prove_inner_circuit(HONK_ZK); + rollup_proof = prove_inner_circuit(ROLLUP_HONK); + } + + void SetUp() override + { + if (!SCRATCH_BUILDS_AVAILABLE) { + GTEST_SKIP() << "this build starts no scratch builds"; + } + // Three Honk constraints need three scratch threads beside the building thread. + if (bb::get_num_cpus() < 4) { + GTEST_SKIP() << "needs at least four threads"; + } + start = numeric::get_randomness().position(); + } + + bool seeded() const { return !start.empty(); } + CompareValues compare_values() const { return seeded() ? CompareValues::Yes : CompareValues::No; } + + // The builder, and with the seeded engine the engine position after each constraint, match the serial build. + void expect_same_build(const Build& spliced, const Build& serial) const + { + expect_same_builder(spliced.builder, serial.builder, compare_values()); + EXPECT_TRUE(spliced.positions == serial.positions); + EXPECT_EQ(serial.stats.launched, 0); + } + + // Builds `program` serially and spliced from the same engine position and checks they agree. + std::pair build_both(const AcirProgram& program, + const ProgramMetadata& metadata = {}, + const Hooks& hooks = {}) + { + const HookReset reset; + Build serial = build(program, metadata, /*splice=*/false, start, hooks); + Build spliced = build(program, metadata, /*splice=*/true, start, hooks); + expect_same_build(spliced, serial); + return { std::move(serial), std::move(spliced) }; + } + + void expect_spliced(const std::vector& proofs, + const size_t expected_splices, + const ProgramMetadata& metadata = {}) + { + const auto [serial, spliced] = build_both(make_program(proofs), metadata); + EXPECT_EQ(spliced.stats.spliced, expected_splices); + EXPECT_EQ(spliced.stats.refused, 0) << spliced.stats.first_refusal; + EXPECT_EQ(spliced.stats.built_in_place, 0); + } + + // The first constraint is built in place and every later one spliced: the cancelled build moved neither the real + // builder nor the engine, so each later scratch build still starts where the engine stands. + void expect_first_in_place(const std::vector& proofs) + { + const auto [serial, spliced] = build_both(make_program(proofs), {}, Hooks{ .first_take = FirstTake::InPlace }); + EXPECT_EQ(spliced.stats.launched, proofs.size()); + EXPECT_EQ(spliced.stats.built_in_place, 1); + EXPECT_EQ(spliced.stats.spliced, proofs.size() - 1); + EXPECT_EQ(spliced.stats.refused, 0) << spliced.stats.first_refusal; + } + + std::vector three_honk_proofs() const + { + return { &honk_proofs[0], &honk_proofs[1], &honk_proofs[2] }; + } + + static inline std::vector honk_proofs; + static inline std::optional zk_proof; + static inline std::optional rollup_proof; + numeric::RNG::Position start; +}; + +TEST_F(RecursionSpliceTest, OneConstraint) +{ + expect_spliced({ &honk_proofs[0] }, 1); +} + +TEST_F(RecursionSpliceTest, TwoConstraints) +{ + expect_spliced({ &honk_proofs[0], &honk_proofs[1] }, 2); +} + +TEST_F(RecursionSpliceTest, ThreeConstraints) +{ + expect_spliced(three_honk_proofs(), 3); +} + +TEST_F(RecursionSpliceTest, RollupConstraint) +{ + expect_spliced({ &*rollup_proof }, 1, ProgramMetadata{ .has_ipa_claim = true }); +} + +// A root rollup program verifies the IPA opening its two proofs carry after their Honk recursion constraints, which +// makes it a circuit of several million gates; those two constraints alone are cheap enough to build per merge, with +// and without a splicer. +TEST_F(RecursionSpliceTest, RootRollupConstraintsAlone) +{ + const HookReset reset; + RecursionSpliceTestHooks::first_take = FirstTake::Wait; + InnerProof root = *rollup_proof; + root.constraint.proof_type = ROOT_ROLLUP_HONK; + const AcirProgram program = make_program({ &root, &root }); + const AcirFormat& constraints = program.constraints; + const auto build_constraints = [&](const bool splice) { + if (seeded()) { + numeric::get_randomness().adopt(start); + } + Build result; + result.builder = Builder{ program.witness, constraints.public_inputs, /*is_write_vk_mode=*/false }; + RecursionSpliceTestHooks::stats = &result.stats; + RecursionSpliceTestHooks::after_constraint = [&](Builder&, const RecursionConstraint&, size_t) { + result.positions.push_back(numeric::get_randomness().position()); + }; + const std::unique_ptr splicer = + splice ? RecursionSplicer::launch(result.builder, constraints.honk_recursion_constraints) : nullptr; + GateCounter gate_counter{ &result.builder, /*collect_gates_per_opcode=*/false }; + std::vector gates_per_opcode; + (void)create_recursion_constraints( + result.builder, + gate_counter, + gates_per_opcode, + /*ivc_base=*/nullptr, + { constraints.honk_recursion_constraints, constraints.original_opcode_indices.honk_recursion_constraints }, + /*avm_recursion_data=*/{}, + /*hn_recursion_data=*/{}, + /*chonk_recursion_data=*/{}, + splicer.get()); + return result; + }; + const Build serial = build_constraints(/*splice=*/false); + const Build spliced = build_constraints(/*splice=*/true); + expect_same_build(spliced, serial); + EXPECT_EQ(spliced.stats.spliced, 2); + EXPECT_EQ(spliced.stats.refused, 0) << spliced.stats.first_refusal; +} + +TEST_F(RecursionSpliceTest, EligibleAfterIneligibleIsBuiltSerially) +{ + expect_spliced({ &*zk_proof, &honk_proofs[0] }, 0); +} + +TEST_F(RecursionSpliceTest, ScratchThreadsGetAMainThreadSizedStack) +{ +#if !defined(__GLIBC__) + GTEST_SKIP() << "reads the stack size with pthread_getattr_np"; +#else + std::atomic stack_bytes = 0; + const auto [serial, spliced] = + build_both(make_program({ &honk_proofs[0] }), {}, Hooks{ .after_scratch_build = [&](size_t /*index*/) { + pthread_attr_t attributes; + size_t size = 0; + if (pthread_getattr_np(pthread_self(), &attributes) == 0) { + pthread_attr_getstacksize(&attributes, &size); + pthread_attr_destroy(&attributes); + } + stack_bytes.store(size); + } }); + EXPECT_EQ(spliced.stats.spliced, 1); + EXPECT_GE(stack_bytes.load(), size_t{ 8 } << 20); +#endif +} + +// A scratch build reads its inputs when it starts, so a constraint naming a variable the builder lacks gets none. +TEST_F(RecursionSpliceTest, ConstraintWithAnInputOutOfRangeIsNotLaunched) +{ + const HookReset reset; + const InnerProof& inner = honk_proofs[0]; + const Builder builder(inner.witness, {}, /*is_write_vk_mode=*/false); + const auto out_of_range = static_cast(builder.get_num_variables()); + EXPECT_NE(RecursionSplicer::launch(builder, { inner.constraint }), nullptr); + const std::vector> breaks{ + [&](RecursionConstraint& constraint) { constraint.proof.back() = out_of_range; }, + [&](RecursionConstraint& constraint) { constraint.key.back() = out_of_range; }, + [&](RecursionConstraint& constraint) { constraint.public_inputs.back() = out_of_range; }, + [&](RecursionConstraint& constraint) { constraint.key_hash = out_of_range; }, + }; + for (size_t i = 0; i < breaks.size(); ++i) { + RecursionConstraint constraint = inner.constraint; + breaks[i](constraint); + EXPECT_EQ(RecursionSplicer::launch(builder, { constraint }), nullptr) << i; + } +} + +TEST_F(RecursionSpliceTest, RefusesAConstraintOtherThanTheLaunchedOne) +{ + const HookReset reset; + RecursionSpliceTestHooks::first_take = FirstTake::Wait; + RecursionSpliceStats stats; + RecursionSpliceTestHooks::stats = &stats; + const InnerProof& inner = honk_proofs[0]; + Builder builder(inner.witness, {}, /*is_write_vk_mode=*/false); + const std::unique_ptr splicer = RecursionSplicer::launch(builder, { inner.constraint }); + ASSERT_NE(splicer, nullptr); + RecursionConstraint other = inner.constraint; + std::swap(other.proof[0], other.proof[1]); + const Builder before = builder; + EXPECT_FALSE(splicer->take(0, other, builder).has_value()); + expect_same_builder_state(builder, before); + splicer->finish(); + EXPECT_EQ(stats.spliced, 0); + EXPECT_EQ(stats.refused, 1); + EXPECT_EQ(stats.first_refusal, "the constraint changed since the scratch build started"); +} + +// A later constraint other than the launched one is refused too, once its scratch build is cancelled and joined. +TEST_F(RecursionSpliceTest, RefusesALaterConstraintOtherThanTheLaunchedOne) +{ + const HookReset reset; + RecursionSpliceTestHooks::first_take = FirstTake::Wait; + RecursionSpliceStats stats; + RecursionSpliceTestHooks::stats = &stats; + const AcirProgram program = make_program({ &honk_proofs[0], &honk_proofs[1] }); + const std::vector& constraints = program.constraints.honk_recursion_constraints; + Builder builder(program.witness, {}, /*is_write_vk_mode=*/false); + const std::unique_ptr splicer = RecursionSplicer::launch(builder, constraints); + ASSERT_NE(splicer, nullptr); + EXPECT_TRUE(splicer->take(0, constraints[0], builder).has_value()); + RecursionConstraint other = constraints[1]; + std::swap(other.proof[0], other.proof[1]); + const Builder before = builder; + EXPECT_FALSE(splicer->take(1, other, builder).has_value()); + expect_same_builder_state(builder, before); + splicer->finish(); + EXPECT_EQ(stats.spliced, 1); + EXPECT_EQ(stats.refused, 1); + EXPECT_EQ(stats.first_refusal, "the constraint changed since the scratch build started"); +} + +TEST_F(RecursionSpliceTest, LoneConstraintBuiltInPlace) +{ + expect_first_in_place({ &honk_proofs[0] }); +} + +TEST_F(RecursionSpliceTest, TwoConstraintsFirstBuiltInPlace) +{ + expect_first_in_place({ &honk_proofs[0], &honk_proofs[1] }); +} + +TEST_F(RecursionSpliceTest, ThreeConstraintsFirstBuiltInPlace) +{ + expect_first_in_place(three_honk_proofs()); +} + +// The production policy: whichever way timing decides the first constraint, the builder is the serial one. +TEST_F(RecursionSpliceTest, FirstTakeByTiming) +{ + const auto [serial, spliced] = + build_both(make_program(three_honk_proofs()), {}, Hooks{ .first_take = FirstTake::Auto }); + EXPECT_EQ(spliced.stats.spliced + spliced.stats.built_in_place, 3); + EXPECT_LE(spliced.stats.built_in_place, 1); + EXPECT_EQ(spliced.stats.refused, 0) << spliced.stats.first_refusal; +} + +/** + * The first scratch build is cancelled while the building thread builds the constraint in place, at four points: held + * at its first, a middle and its last recording, then released, and after it finished. It stops at that very + * recording, its thread has exited by the time its builder is discarded, which happens before the Honk recursion + * constraints are reported and so before any later kind of constraint is built, and the real builder and engine end as + * in the serial build. + */ +TEST_F(RecursionSpliceTest, CancelsTheFirstScratchBuildAtFourPoints) +{ + const HookReset reset; + const AcirProgram program = make_program({ &honk_proofs[0] }); + std::atomic num_recordings = 0; + { + const Build counted = + build(program, {}, /*splice=*/true, start, Hooks{ .scratch_recording = [&](size_t index, size_t count) { + if (index == 0) { + num_recordings.store(count); + } + } }); + ASSERT_EQ(counted.stats.spliced, 1); + } + const size_t total = num_recordings.load(); + ASSERT_GT(total, 2); + const Build serial = build(program, {}, /*splice=*/false, start); + + // The first, a middle and the last recording, then past the end: the build has finished when cancelled. + for (const size_t cancel_at : { size_t{ 1 }, total / 2, total, total + 1 }) { + SCOPED_TRACE(cancel_at); + const bool after_finish = cancel_at > total; + Signal held; + Signal released; + std::atomic last_recording = 0; + std::atomic finished = false; + std::atomic exited = false; + std::vector discarded; + bool exited_before_discard = false; + bool reported_before_discard = true; + const Hooks hooks{ + .spliced_before_constraint = + [&](Builder&, const RecursionConstraint&, size_t index) { + if (index == 0) { + EXPECT_TRUE(held.wait()); + } + }, + .spliced_after_constraint = + [&](Builder&, const RecursionConstraint&, size_t index) { + if (index == 0) { + released.set(); + } + }, + .after_scratch_build = + [&](size_t index) { + if (index == 0) { + finished.store(true); + if (after_finish) { + held.set(); + } + } + }, + .scratch_recording = + [&](size_t index, size_t count) { + if (index != 0) { + return; + } + thread_local ExitMarker marker; + marker.exited = &exited; + last_recording.store(count); + if (count == cancel_at) { + held.set(); + EXPECT_TRUE(released.wait()); + } + }, + .discarded = + [&](size_t index) { + discarded.push_back(index); + if (index == 0) { + exited_before_discard = exited.load(); + reported_before_discard = RecursionSpliceTestHooks::stats->launched != 0; + } + }, + .first_take = FirstTake::InPlace, + }; + const Build spliced = build(program, {}, /*splice=*/true, start, hooks); + expect_same_build(spliced, serial); + EXPECT_EQ(spliced.stats.built_in_place, 1); + EXPECT_EQ(spliced.stats.spliced, 0); + EXPECT_EQ(spliced.stats.refused, 0) << spliced.stats.first_refusal; + EXPECT_EQ(last_recording.load(), std::min(cancel_at, total)); + EXPECT_EQ(finished.load(), after_finish); + EXPECT_EQ(discarded, std::vector{ 0 }); + EXPECT_TRUE(exited_before_discard); + EXPECT_FALSE(reported_before_discard); + EXPECT_EQ(spliced.stats.launched, 1); + } +} + +/** + * An error on the building thread cancels every scratch build it has not taken before joining it. Builds 1 and 2 are + * held at their first recording until build 0 has been joined and discarded, which the splicer reaches only after + * requesting every cancellation, so on release each throws at that recording. Were a build joined before its + * cancellation was requested, builds 1 and 2 would run on to their end once released. Build 0 is joined first and so + * cannot be held; whether it stops early or finishes depends on timing, and it is not checked. + */ +TEST_F(RecursionSpliceTest, AnErrorOnTheBuildingThreadCancelsTheScratchBuilds) +{ + const HookReset reset; + std::mutex mutex; + std::condition_variable recorded; + size_t num_recording = 0; + std::array, 3> finished{}; + Signal first_discarded; + std::vector discarded; + const Hooks hooks{ + .spliced_before_constraint = + [&](Builder&, const RecursionConstraint&, size_t index) { + if (index != 0) { + return; + } + { + std::unique_lock lock(mutex); + EXPECT_TRUE(recorded.wait_for(lock, std::chrono::minutes(2), [&] { return num_recording == 3; })); + } + throw_or_abort("forced building thread failure"); + }, + .after_scratch_build = [&](size_t index) { finished[index].store(true); }, + .scratch_recording = + [&](size_t index, size_t count) { + if (count != 1) { + return; + } + { + const std::lock_guard lock(mutex); + ++num_recording; + } + recorded.notify_all(); + if (index != 0) { + EXPECT_TRUE(first_discarded.wait()); + } + }, + .discarded = + [&](size_t index) { + discarded.push_back(index); + if (index == 0) { + first_discarded.set(); + } + }, + }; + EXPECT_THROW((void)build(make_program(three_honk_proofs()), {}, /*splice=*/true, start, hooks), std::runtime_error); + EXPECT_FALSE(finished[1].load()); + EXPECT_FALSE(finished[2].load()); + EXPECT_EQ(discarded, (std::vector{ 0, 1, 2 })); +} + +// The forced refusals hit the middle of three constraints; the first is spliced either way. + +TEST_F(RecursionSpliceTest, RefusesWhenTheEngineMoved) +{ + const auto [serial, spliced] = + build_both(make_program(three_honk_proofs()), + {}, + Hooks{ .before_constraint = [](Builder&, const RecursionConstraint&, size_t index) { + if (index == 1) { + [[maybe_unused]] const uint64_t extra_draw = numeric::get_randomness().get_random_uint64(); + } + } }); + if (seeded()) { + // Every later start position was predicted without the extra draw. + EXPECT_EQ(spliced.stats.spliced, 1); + EXPECT_EQ(spliced.stats.refused, 2); + EXPECT_EQ(spliced.stats.first_refusal, "the engine moved since the scratch build started"); + } else { + // An engine without an order has no position to miss. + EXPECT_EQ(spliced.stats.spliced, 3); + EXPECT_EQ(spliced.stats.refused, 0); + } +} + +TEST_F(RecursionSpliceTest, RefusesATaggedInput) +{ + const auto [serial, spliced] = + build_both(make_program(three_honk_proofs()), {}, Hooks{ .before_constraint = tag_a_small_input(1) }); + EXPECT_EQ(spliced.stats.spliced, 2); + EXPECT_EQ(spliced.stats.refused, 1); + EXPECT_EQ(spliced.stats.first_refusal, "an input carries a range tag"); +} + +TEST_F(RecursionSpliceTest, RefusesInputsSharingACycle) +{ + const auto [serial, spliced] = build_both( + make_program(three_honk_proofs()), + {}, + Hooks{ .before_constraint = [](Builder& builder, const RecursionConstraint& constraint, size_t index) { + if (index != 1) { + return; + } + std::unordered_map first_with_value; + for (const uint32_t input : inputs_of(constraint)) { + const auto [it, inserted] = first_with_value.try_emplace(builder.get_variable(input), input); + if (!inserted && it->second != input) { + builder.assert_equal(it->second, input); + return; + } + } + FAIL() << "no two inputs share a value"; + } }); + EXPECT_EQ(spliced.stats.spliced, 2); + EXPECT_EQ(spliced.stats.refused, 1); + EXPECT_EQ(spliced.stats.first_refusal, "inputs share a copy cycle"); +} + +TEST_F(RecursionSpliceTest, RefusesAScratchBuildThatThrew) +{ + const auto [serial, spliced] = + build_both(make_program(three_honk_proofs()), {}, Hooks{ .after_scratch_build = [](size_t index) { + if (index == 1) { + throw_or_abort("forced scratch build failure"); + } + } }); + EXPECT_EQ(spliced.stats.spliced, 2); + EXPECT_EQ(spliced.stats.refused, 1); + EXPECT_EQ(spliced.stats.first_refusal, "the scratch build threw: forced scratch build failure"); +} + +/** + * @brief Records, per thread, each refill of the default engine's entropy buffer and each range a draw consumes. + */ +class BufferLog final : public numeric::EntropyBufferObserver { + public: + struct Fill { + std::thread::id thread; + size_t size; + }; + struct Consume { + std::thread::id thread; + uint64_t fill; + size_t offset; + size_t length; + }; + + BufferLog() = default; + BufferLog(const BufferLog&) = delete; + BufferLog(BufferLog&&) = delete; + BufferLog& operator=(const BufferLog&) = delete; + BufferLog& operator=(BufferLog&&) = delete; + // Draws after a failed test must not reach a destroyed log. + ~BufferLog() override { numeric::set_entropy_buffer_observer(nullptr); } + + void on_fill(const uint64_t fill, const size_t size) override + { + const std::lock_guard lock(mutex); + fills.emplace(fill, Fill{ std::this_thread::get_id(), size }); + } + + void on_consume(const uint64_t fill, const size_t offset, const size_t length) override + { + const std::lock_guard lock(mutex); + consumes.push_back({ std::this_thread::get_id(), fill, offset, length }); + } + + std::mutex mutex; + std::unordered_map fills; + std::vector consumes; +}; + +TEST_F(RecursionSpliceTest, ScratchThreadsDrawOnlyFromTheirOwnBuffers) +{ + if (seeded()) { + GTEST_SKIP() << "the entropy buffer belongs to the default engine"; + } + const HookReset reset; + // The first build is cancelled at its first recording, which follows its draws, while held there. + constexpr size_t CANCELLED = 0; + constexpr size_t REFUSED = 1; + std::mutex mutex; + std::map scratch_threads; + Signal held; + Signal released; + BufferLog log; + numeric::set_entropy_buffer_observer(&log); + const Hooks hooks{ + .spliced_before_constraint = + [&](Builder&, const RecursionConstraint&, size_t index) { + if (index == CANCELLED) { + EXPECT_TRUE(held.wait()); + } + }, + .spliced_after_constraint = + [&](Builder&, const RecursionConstraint&, size_t index) { + if (index == CANCELLED) { + released.set(); + } + }, + .after_scratch_build = + [](size_t index) { + if (index == REFUSED) { + throw_or_abort("forced scratch build failure"); + } + }, + .scratch_recording = + [&](size_t index, size_t count) { + if (count != 1) { + return; + } + { + const std::lock_guard lock(mutex); + scratch_threads.emplace(index, std::this_thread::get_id()); + } + if (index == CANCELLED) { + held.set(); + EXPECT_TRUE(released.wait()); + } + }, + .first_take = FirstTake::InPlace, + }; + const Build spliced = build(make_program(three_honk_proofs()), {}, /*splice=*/true, start, hooks); + numeric::set_entropy_buffer_observer(nullptr); + + EXPECT_EQ(spliced.stats.spliced, 1); + EXPECT_EQ(spliced.stats.refused, 1); + EXPECT_EQ(spliced.stats.built_in_place, 1); + ASSERT_EQ(scratch_threads.size(), 3); + std::unordered_set scratch_ids; + for (const auto& [index, thread] : scratch_threads) { + scratch_ids.insert(thread); + } + + // A scratch thread starts after the observer, so each of its fills is seen and belongs to it. + size_t refused_consumes = 0; + size_t cancelled_consumes = 0; + for (const BufferLog::Consume& consume : log.consumes) { + if (consume.fill == 0) { + EXPECT_FALSE(scratch_ids.contains(consume.thread)); + continue; + } + const auto fill = log.fills.find(consume.fill); + ASSERT_NE(fill, log.fills.end()); + EXPECT_EQ(fill->second.thread, consume.thread); + EXPECT_LE(consume.offset + consume.length, fill->second.size); + if (fill->second.thread == scratch_threads.at(REFUSED)) { + ++refused_consumes; + } + if (fill->second.thread == scratch_threads.at(CANCELLED)) { + ++cancelled_consumes; + } + } + // The refused and the cancelled build drew: their draws are consumed by nothing else, because no other thread + // reads their fills. + EXPECT_GT(refused_consumes, 0); + EXPECT_GT(cancelled_consumes, 0); + + // No two consumed ranges of one buffer overlap; an unobserved fill is told apart by its thread. + std::map, std::vector>> ranges; + for (const BufferLog::Consume& consume : log.consumes) { + const std::thread::id owner = consume.fill == 0 ? consume.thread : std::thread::id{}; + ranges[{ consume.fill, owner }].emplace_back(consume.offset, consume.length); + } + for (auto& [buffer, consumed] : ranges) { + std::ranges::sort(consumed); + for (size_t i = 1; i < consumed.size(); ++i) { + EXPECT_LE(consumed[i - 1].first + consumed[i - 1].second, consumed[i].first); + } + } +} + +/** + * A root rollup program verifies two rollup proofs, then the IPA opening both carry: a circuit of about 6.35M gates, + * too costly to build per merge. The suite name puts these tests among the nightly ones (see + * barretenberg/cpp/bootstrap.sh), and each test builds that circuit as few times as it can. + */ +class HonkRecursionConstraintTestRootSplice : public RecursionSpliceTest { + protected: + static void SetUpTestSuite() + { + bb::srs::init_file_crs_factory(bb::srs::bb_crs_path()); + root_proof = prove_inner_circuit(ROOT_ROLLUP_HONK); + } + + static AcirProgram root_program() { return make_program({ &*root_proof, &*root_proof }); } + + // expect_same_build without its two root-sized copies: `spliced` is finalized in place, and so is `serial` when + // `finalize_serial`, else one copy of it. + void expect_same_root_build(Build& spliced, Build& serial, const bool finalize_serial) const + { + expect_same_builder_state(spliced.builder, serial.builder, compare_values()); + EXPECT_TRUE(spliced.positions == serial.positions); + EXPECT_EQ(serial.stats.launched, 0); + spliced.builder.finalize_circuit(); + if (finalize_serial) { + serial.builder.finalize_circuit(); + expect_same_builder_state(spliced.builder, serial.builder, compare_values()); + } else { + Builder serial_finalized = serial.builder; + serial_finalized.finalize_circuit(); + expect_same_builder_state(spliced.builder, serial_finalized, compare_values()); + } + } + + // Proves `builder` from the engine position `from`, freeing the builder once the prover has copied it. + static HonkProof prove(Builder& builder, const numeric::RNG::Position& from) + { + numeric::get_randomness().adopt(from); + const auto prover_instance = + std::make_shared>(builder, CopiedCircuitData::RELEASE); + builder = Builder{}; + const auto verification_key = + std::make_shared(prover_instance->get_precomputed()); + UltraProver_ prover(prover_instance, verification_key); + return prover.construct_proof(); + } + + // The root rollup verifies its IPA accumulator in full and passes no claim on. + const ProgramMetadata metadata{ .has_ipa_claim = false }; + static inline std::optional root_proof; +}; + +// One serial build, which every spliced build equals in every member, before and after finalization. At most three +// root builders are alive at once: the serial build, the production-policy build and a finalized copy of the former. +TEST_F(HonkRecursionConstraintTestRootSplice, SplicedBuildsMatchTheSerialBuild) +{ + const HookReset reset; + const AcirProgram program = root_program(); + Build serial = build(program, metadata, /*splice=*/false, start); + EXPECT_FALSE(serial.builder.failed()) << serial.builder.err(); + { + // The production policy: the first constraint is spliced only if its scratch build has finished when the + // building thread reaches it. That depends on timing, so the counts are logged rather than checked. + Build by_timing = build(program, metadata, /*splice=*/true, start, Hooks{ .first_take = FirstTake::Auto }); + expect_same_root_build(by_timing, serial, /*finalize_serial=*/false); + EXPECT_EQ(by_timing.stats.refused, 0) << by_timing.stats.first_refusal; + info("root rollup, first take by timing: ", + by_timing.stats.spliced, + " spliced, ", + by_timing.stats.built_in_place, + " built in place"); + } + // The first constraint waits for its scratch build, so both are spliced whatever the timing. The engine positions + // after each constraint, which expect_same_root_build compares too, only bite under the seeded engine: the default + // engine has none. + Build waited = build(program, metadata, /*splice=*/true, start); + expect_same_root_build(waited, serial, /*finalize_serial=*/true); + EXPECT_EQ(waited.stats.spliced, 2); + EXPECT_EQ(waited.stats.refused, 0) << waited.stats.first_refusal; + EXPECT_EQ(waited.stats.built_in_place, 0); + // Under the default engine the two builds draw different offset generators, so their proofs differ. + if (seeded()) { + const HonkProof waited_proof = prove(waited.builder, serial.positions.back()); + const HonkProof serial_proof = prove(serial.builder, serial.positions.back()); + EXPECT_TRUE(waited_proof == serial_proof); + } +} + +// The second root constraint is refused and built in place, on the builder and engine the first splice left. The tag +// that refuses it goes into the serial build too, so this test cannot share the serial build above. +TEST_F(HonkRecursionConstraintTestRootSplice, RefusedConstraintIsBuiltInPlace) +{ + const HookReset reset; + const AcirProgram program = root_program(); + const Hooks hooks{ .before_constraint = tag_a_small_input(1) }; + Build serial = build(program, metadata, /*splice=*/false, start, hooks); + Build spliced = build(program, metadata, /*splice=*/true, start, hooks); + expect_same_root_build(spliced, serial, /*finalize_serial=*/true); + EXPECT_EQ(spliced.stats.spliced, 1); + EXPECT_EQ(spliced.stats.refused, 1); + EXPECT_EQ(spliced.stats.first_refusal, "an input carries a range tag"); +} + +} // namespace diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/scratch_build.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/scratch_build.cpp new file mode 100644 index 0000000..bad4b73 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/scratch_build.cpp @@ -0,0 +1,116 @@ +#include "barretenberg/dsl/acir_format/scratch_build.hpp" + +#if BB_SCRATCH_BUILDS_AVAILABLE + +#include "barretenberg/common/throw_or_abort.hpp" + +#include +#if defined(__GLIBC__) +#include +#endif + +namespace acir_format::scratch_build { + +namespace { + +// 8 MiB, the usual main-thread default; a scratch build needs more stack than some platforms give other threads. +constexpr size_t SCRATCH_STACK_BYTES = size_t{ 8 } << 20; + +} // namespace + +ScratchCancellation::ScratchCancellation(const std::string_view owner, std::function before_check) + : message_(std::string(owner) + ": the scratch build was cancelled") + , before_check_(std::move(before_check)) +{} + +void ScratchCancellation::request() noexcept +{ + requested_.store(true, std::memory_order_relaxed); +} + +void ScratchCancellation::check() +{ + if (before_check_) { + before_check_(); + } + if (requested_.load(std::memory_order_relaxed)) { + throw_or_abort(message_); + } +} + +bool ScratchThread::start(void* (*body)(void*), void* arg) +{ + pthread_attr_t attributes; + if (pthread_attr_init(&attributes) != 0) { + return false; + } + int status = pthread_attr_setstacksize(&attributes, SCRATCH_STACK_BYTES); + if (status == 0) { + status = pthread_create(&thread_, &attributes, body, arg); + } + pthread_attr_destroy(&attributes); + running_ = status == 0; + return running_; +} + +void ScratchThread::join() +{ + if (running_) { + pthread_join(thread_, nullptr); + running_ = false; + } +} + +std::string refusal_reason(const bb::SpliceRefusal refusal) +{ + using bb::SpliceRefusal; + switch (refusal) { + case SpliceRefusal::None: + return "none"; + case SpliceRefusal::BuilderState: + return "builder state"; + case SpliceRefusal::Failed: + return "a builder has failed"; + case SpliceRefusal::PublicInput: + return "the scratch build added a public input"; + case SpliceRefusal::InputValue: + return "an input value changed"; + case SpliceRefusal::InputCycle: + return "inputs share a copy cycle"; + case SpliceRefusal::InputTag: + return "an input carries a range tag"; + case SpliceRefusal::RowForm: + return "a row of a form the splice cannot copy"; + case SpliceRefusal::UnknownForm: + return "state of a form the splice does not translate"; + } + return "unknown"; +} + +void return_freed_memory() +{ +#if defined(__GLIBC__) + malloc_trim(0); +#endif +} + +std::string message_of(const std::exception_ptr& error) +{ + try { + std::rethrow_exception(error); + } catch (const std::exception& exception) { + return exception.what(); + } catch (...) { + return "an exception that is not a std::exception"; + } +} + +int64_t milliseconds_between(const std::chrono::steady_clock::time_point from, + const std::chrono::steady_clock::time_point to) +{ + return static_cast(std::chrono::duration_cast(to - from).count()); +} + +} // namespace acir_format::scratch_build + +#endif diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/scratch_build.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/scratch_build.hpp new file mode 100644 index 0000000..80bde90 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/scratch_build.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include "barretenberg/stdlib_circuit_builders/circuit_splice.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +// Scratch builds need native threads with a parallel_for pool and core count of their own (wasm shares the pool between +// threads, and OpenMP loops ignore the core count), pthreads to size their stacks, and exceptions. +#if !defined(NO_MULTITHREADING) && !defined(__wasm__) && !defined(_WIN32) && !defined(OMP_MULTITHREADING) && \ + defined(__cpp_exceptions) && !defined(BB_NO_EXCEPTIONS) +#define BB_SCRATCH_BUILDS_AVAILABLE 1 +#include +#else +#define BB_SCRATCH_BUILDS_AVAILABLE 0 +#endif + +/** + * What every scratch build of a circuit uses: a builder constructed with SpliceRecording, built on a thread of its own + * and spliced into the real builder by the building thread. + */ +namespace acir_format::scratch_build { + +#if BB_SCRATCH_BUILDS_AVAILABLE + +// Scratch builds start only with at least this many threads, and use at most all but the building thread. +constexpr size_t MIN_THREADS = 3; + +/** + * @brief Stops a scratch build at its next recording once requested from another thread. + */ +class ScratchCancellation final : public bb::SpliceCancellation { + public: + // A cancelled build throws ": the scratch build was cancelled". `before_check`, when set, runs on the + // recording thread before each check. + explicit ScratchCancellation(std::string_view owner, std::function before_check = {}); + + void request() noexcept; + void check() override; + + private: + std::string message_; + std::function before_check_; + std::atomic requested_ = false; +}; + +/** + * @brief A thread with a stack of the usual main-thread size, joined at most once. + */ +class ScratchThread { + public: + // Runs `body(arg)` on a new thread; false when it could not start. + [[nodiscard]] bool start(void* (*body)(void*), void* arg); + // Waits for the thread when it was started and not yet joined. + void join(); + bool running() const { return running_; } + + private: + pthread_t thread_{}; + bool running_ = false; +}; + +std::string refusal_reason(bb::SpliceRefusal refusal); + +/** + * @brief Returns to the system the memory that scratch threads have freed. + * @details Freed blocks stay resident in the malloc arena of the thread that allocated them, which the building thread + * does not allocate from. While a scratch builder lives, that memory lies in free blocks below the builder's own, which + * glibc can return; once the builder is destroyed its arena is a single top block, which glibc trims only in the main + * arena. + */ +void return_freed_memory(); + +// What `error` says, or a fixed text when it holds something other than a std::exception. +std::string message_of(const std::exception_ptr& error); + +int64_t milliseconds_between(std::chrono::steady_clock::time_point from, std::chrono::steady_clock::time_point to); + +#endif + +} // namespace acir_format::scratch_build diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.cpp new file mode 100644 index 0000000..db7e2cb --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.cpp @@ -0,0 +1,389 @@ +#include "barretenberg/dsl/acir_format/sha256_splice.hpp" + +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/dsl/acir_format/scratch_build.hpp" +#include "barretenberg/numeric/random/engine.hpp" + +#include +#include +#include +#include +#include + +namespace acir_format { + +using bb::UltraCircuitBuilder; + +namespace { + +void build_in_place(UltraCircuitBuilder& builder, + const std::vector& run, + const size_t begin, + const size_t end, + const Sha256RunOptions& options, + const std::function& after_in_place) +{ + for (size_t i = begin; i < end; ++i) { + if (options.before_in_place) { + options.before_in_place(builder, i); + } + create_sha256_compression_constraints(builder, run[i]); + after_in_place(i); + } +} + +} // namespace + +size_t Sha256RunSplicer::num_chunks(const size_t num_compressions, + const size_t num_threads, + const Sha256RunOptions& options) +{ + const size_t by_size = num_compressions / std::max(options.min_compressions_per_chunk, 1); + return std::min({ by_size, options.max_chunks, num_threads }); +} + +void build_sha256_compressions(UltraCircuitBuilder& builder, + const std::vector& run, + Sha256RunSplicer* splicer, + const Sha256RunOptions& options, + const std::function& after_in_place) +{ + if (splicer != nullptr) { + splicer->build(builder, run, after_in_place); + return; + } + build_in_place(builder, run, 0, run.size(), options, after_in_place); + if (options.stats != nullptr) { + *options.stats = Sha256RunStats{ .compressions = run.size(), .chunks = 1, .built_in_place = 1 }; + } +} + +#if BB_SCRATCH_BUILDS_AVAILABLE + +namespace { + +using scratch_build::message_of; +using scratch_build::milliseconds_between; +using scratch_build::MIN_THREADS; +using scratch_build::refusal_reason; +using scratch_build::return_freed_memory; +using scratch_build::ScratchCancellation; +using scratch_build::ScratchThread; + +// Chunk `chunk` of `num_chunks` equal contiguous chunks of `num_compressions` starts here. +size_t chunk_begin(const size_t chunk, const size_t num_chunks, const size_t num_compressions) +{ + return chunk * num_compressions / num_chunks; +} + +// Visits every witness index a compression names: inputs, hash values, outputs. +template void for_each_witness(Compression& compression, const Visit& visit) +{ + for (auto& input : compression.inputs) { + if (!input.is_constant) { + visit(input.index); + } + } + for (auto& input : compression.hash_values) { + if (!input.is_constant) { + visit(input.index); + } + } + for (auto& output : compression.result) { + visit(output); + } +} + +bool names_only_variables_below(const std::span compressions, const size_t num_variables) +{ + bool all_below = true; + for (const Sha256Compression& compression : compressions) { + for_each_witness(compression, [&](const uint32_t index) { all_below = all_below && index < num_variables; }); + } + return all_below; +} + +} // namespace + +struct Sha256RunSplicer::Chunk { + size_t index; + // seed_indices[i] is the real index of scratch input variable i; `compressions` name scratch inputs instead. + std::vector seed_indices; + std::vector seed_values; + std::vector compressions; + const Sha256RunOptions* options; + bb::numeric::RNG::Position start; + ScratchCancellation cancellation; + + // Written by the scratch thread, read by the building thread after the join. + std::unique_ptr builder; + bb::numeric::RNG::Position reached; + std::exception_ptr error; + Clock::time_point finished_at; + + bb::numeric::RNG* engine = nullptr; + ScratchThread thread; + + // Inputs are numbered by distinct real index at first appearance, so two inputs share a scratch variable exactly + // when they share a real one. + Chunk(const UltraCircuitBuilder& real, + const std::span launched, + const size_t chunk_index, + const Sha256RunOptions& run_options) + : index(chunk_index) + , compressions(launched.begin(), launched.end()) + , options(&run_options) + , cancellation("Sha256RunSplicer", [&run_options, chunk_index, num_checks = size_t{ 0 }]() mutable { + // Only the scratch thread counts. + if (run_options.scratch_recording) { + run_options.scratch_recording(chunk_index, ++num_checks); + } + }) + { + std::unordered_map seed_of; + for (Sha256Compression& compression : compressions) { + for_each_witness(compression, [&](uint32_t& variable) { + const auto [it, inserted] = seed_of.try_emplace(variable, static_cast(seed_indices.size())); + if (inserted) { + seed_indices.push_back(variable); + seed_values.push_back(real.get_variable(variable)); + } + variable = it->second; + }); + } + } + + static void* run_build(void* chunk) + { + static_cast(chunk)->build(); + return nullptr; + } + + // Throws nothing: whatever the build throws is kept in `error`. + void build() noexcept + { + try { + // parallel_for's core count and pool are per thread, so at one core this thread's loops run inline + // instead of starting a worker pool of its own. + bb::set_parallel_for_concurrency(1); + const std::unique_ptr scope = engine->draw_from(start); + builder = std::make_unique(bb::SpliceRecording{ .cancellation = &cancellation }, + seed_values); + for (const Sha256Compression& compression : compressions) { + create_sha256_compression_constraints(*builder, compression); + } + reached = scope->reached(); + if (options->after_scratch_build) { + options->after_scratch_build(index, *builder); + } + } catch (...) { + error = std::current_exception(); + } + finished_at = Clock::now(); + } + + // Called once the scratch thread is joined. Freed memory is returned first, while the builder still lives. + void discard() + { + if (!builder) { + return; + } + return_freed_memory(); + builder.reset(); + if (options->discarded) { + options->discarded(index); + } + } +}; + +Sha256RunSplicer::Sha256RunSplicer(const std::vector& run, + const size_t num_chunks, + const Sha256RunOptions& options) + : run_(run) + , num_chunks_(num_chunks) + , options_(options) + , chunks_(num_chunks) +{ + stats_.compressions = run.size(); + stats_.chunks = num_chunks; +} + +Sha256RunSplicer::~Sha256RunSplicer() +{ + reap(); +} + +void Sha256RunSplicer::reap() +{ + // Requested of every running build first, so a join waits only until that build's next recording, or its end. + for (const auto& chunk : chunks_) { + if (chunk != nullptr && chunk->thread.running()) { + chunk->cancellation.request(); + } + } + for (const auto& chunk : chunks_) { + if (chunk != nullptr) { + chunk->thread.join(); + chunk->discard(); + } + } +} + +std::unique_ptr Sha256RunSplicer::launch(const UltraCircuitBuilder& builder, + const std::vector& run, + const Sha256RunOptions& options) +{ + const size_t num_threads = bb::get_num_cpus(); + if (builder.is_write_vk_mode() || num_threads < MIN_THREADS) { + return nullptr; + } + const size_t count = num_chunks(run.size(), num_threads, options); + if (count < 2) { + return nullptr; + } + std::unique_ptr splicer(new Sha256RunSplicer(run, count, options)); + bb::numeric::RNG& engine = bb::numeric::get_randomness(); + const bb::numeric::RNG::Position start = engine.position(); + const std::span compressions(run); + const size_t num_variables = builder.get_num_variables(); + try { + for (size_t c = 1; c < count; ++c) { + const size_t begin = chunk_begin(c, count, run.size()); + const auto chunk = compressions.subspan(begin, chunk_begin(c + 1, count, run.size()) - begin); + // Seeds are read here, before the serial build would reject a compression naming a missing variable. + if (names_only_variables_below(chunk, num_variables)) { + splicer->chunks_[c] = std::make_unique(builder, chunk, c, splicer->options_); + splicer->chunks_[c]->start = start; + splicer->chunks_[c]->engine = &engine; + } + } + splicer->launched_at_ = Clock::now(); + for (const auto& chunk : splicer->chunks_) { + if (chunk == nullptr) { + continue; + } + // A launch that fails splices nothing; the destructor joins the threads already started. + if (!chunk->thread.start(&Chunk::run_build, chunk.get())) { + return nullptr; + } + ++splicer->stats_.launched; + } + } catch (...) { + return nullptr; + } + if (splicer->stats_.launched == 0) { + return nullptr; + } + return splicer; +} + +void Sha256RunSplicer::build(UltraCircuitBuilder& builder, + const std::vector& run, + const std::function& after_in_place) +{ + reached_at_ = Clock::now(); + const bool same_run = run == run_; + for (size_t c = 0; c < num_chunks_; ++c) { + if (chunks_[c] == nullptr || !take(*chunks_[c], builder, same_run)) { + build_in_place(builder, + run, + chunk_begin(c, num_chunks_, run.size()), + chunk_begin(c + 1, num_chunks_, run.size()), + options_, + after_in_place); + ++stats_.built_in_place; + } + } + vinfo("sha256 splice: ", summary()); + if (options_.stats != nullptr) { + *options_.stats = stats_; + } +} + +bool Sha256RunSplicer::take(Chunk& chunk, UltraCircuitBuilder& builder, const bool same_run) +{ + if (!same_run) { + chunk.cancellation.request(); + chunk.thread.join(); + refuse(chunk, "the compressions changed since the scratch builds started"); + return false; + } + const Clock::time_point needed_at = Clock::now(); + chunk.thread.join(); + if (!first_taken_.has_value()) { + first_taken_ = chunk.index; + first_needed_at_ = needed_at; + first_finished_at_ = chunk.finished_at; + } + if (chunk.error) { + const std::string message = message_of(chunk.error); + vinfo("sha256 splice: the scratch build of chunk ", chunk.index, " threw: ", message); + refuse(chunk, "the scratch build threw: " + message); + return false; + } + // The serial build would draw from wherever the engine then stands, which the scratch build could not know. + if (!(chunk.reached == chunk.start)) { + refuse(chunk, "the scratch build drew randomness"); + return false; + } + const bb::SpliceResult result = builder.splice(*chunk.builder, chunk.seed_indices); + if (!result.spliced()) { + refuse(chunk, refusal_reason(result.refusal)); + return false; + } + chunk.discard(); + ++stats_.spliced; + return true; +} + +void Sha256RunSplicer::refuse(Chunk& chunk, std::string reason) +{ + if (stats_.refused == 0) { + stats_.first_refusal = std::move(reason); + } + ++stats_.refused; + chunk.discard(); +} + +std::string Sha256RunSplicer::summary() const +{ + std::string line = std::to_string(stats_.compressions) + " compressions in " + std::to_string(stats_.chunks) + + " chunks, " + std::to_string(stats_.spliced) + " of " + std::to_string(stats_.launched) + + " spliced, " + std::to_string(stats_.refused) + " refused, " + + std::to_string(stats_.built_in_place) + " built in place (head start " + + std::to_string(milliseconds_between(launched_at_, reached_at_)) + " ms"; + if (first_taken_.has_value()) { + // Negative when the building thread had to wait. + line += ", chunk " + std::to_string(*first_taken_) + " margin " + + std::to_string(milliseconds_between(first_finished_at_, first_needed_at_)) + " ms"; + } + if (stats_.refused > 0) { + line += "; first refusal: " + stats_.first_refusal; + } + return line + ")"; +} + +#else + +struct Sha256RunSplicer::Chunk {}; + +Sha256RunSplicer::~Sha256RunSplicer() = default; + +std::unique_ptr Sha256RunSplicer::launch(const UltraCircuitBuilder& /*builder*/, + const std::vector& /*run*/, + const Sha256RunOptions& /*options*/) +{ + return nullptr; +} + +void Sha256RunSplicer::build(UltraCircuitBuilder& builder, + const std::vector& run, + const std::function& after_in_place) +{ + build_in_place(builder, run, 0, run.size(), options_, after_in_place); +} + +#endif + +} // namespace acir_format diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.hpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.hpp new file mode 100644 index 0000000..37b05d7 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include "barretenberg/dsl/acir_format/sha256_constraint.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace acir_format { + +/** + * @brief What one circuit build did with its SHA-256 compression constraints. + */ +struct Sha256RunStats { + size_t compressions = 0; + // The chunks the run was cut into; 1 when it was built in place whole. + size_t chunks = 0; + size_t launched = 0; + size_t spliced = 0; + size_t refused = 0; + // Chunks the building thread built: chunk 0, chunks not launched and refused chunks. + size_t built_in_place = 0; + // Why the first refused chunk was built in place; empty when none was refused. + std::string first_refusal; +}; + +/** + * @brief How the SHA-256 compression constraints of an Ultra circuit are cut into chunks built on scratch threads. + * @details Splicing a chunk saves the building thread its in-place build, less its launch, splice and scratch builder's + * destruction. An earlier form splicing into a fresh builder on 64 threads measured 1.7 to 1.9 ms per compression in + * place and about 1 ms per chunk plus 0.6 ms per compression for those three; on a real circuit, 16 chunks took the + * building thread's run of 512 compressions from 886 to 537 ms. The chunk count never changes the circuit. + */ +struct Sha256RunOptions { + // From 8 compressions a chunk's in-place build costs the building thread more than twice what splicing it does. + static constexpr size_t MIN_COMPRESSIONS_PER_CHUNK = 8; + // The most chunks measured: on 512 compressions 16 chunks saved about a fifth more than 4 did. + static constexpr size_t MAX_CHUNKS = 16; + + size_t min_compressions_per_chunk = MIN_COMPRESSIONS_PER_CHUNK; + size_t max_chunks = MAX_CHUNKS; + + // Observers for tests. They are compiled in production and native callers can set them through ProgramMetadata; + // every caller in this repository leaves them empty, and nothing serialized exposes them. + // Runs on the building thread before it builds compression `compression` in place. + std::function before_in_place; + // Runs on a scratch thread when its build of chunk `chunk` has finished; a throw refuses the chunk. + std::function after_scratch_build; + // Runs on the scratch thread at each recording of chunk `chunk`, before its cancellation check; `count` from 1. + std::function scratch_recording; + // Runs on the building thread once the scratch builder of chunk `chunk` has been destroyed. + std::function discarded; + // Receives the counts of the build. + Sha256RunStats* stats = nullptr; +}; + +/** + * @brief Builds the SHA-256 compression constraints of an Ultra circuit in equal contiguous chunks: the building thread + * builds chunk 0 in place, and each later chunk is built on a scratch builder on a thread of its own and spliced into + * the real builder at its turn in list order. + * @details A chunk's scratch build reads only the values of the witnesses its compressions read and write, its seeds, + * and the splice appends to the real builder what building the chunk there would, so the circuit is the serial build's + * whatever the chunk count, the thread count or the timing. A chunk that names a variable the builder lacks is not + * launched; one the splice refuses, or whose scratch build threw or moved a seeded engine's position, is built in place + * at its turn. Every scratch thread is joined, never detached: at its chunk's turn, or after every running build was + * cancelled when the build ends early. Each scratch builder's freed memory is returned before it is destroyed. + */ +class Sha256RunSplicer { + public: + /** + * @brief How many chunks a run of `num_compressions` is cut into on `num_threads` threads; under 2, none. + */ + static size_t num_chunks(size_t num_compressions, size_t num_threads, const Sha256RunOptions& options); + + /** + * @brief Start a scratch build of every chunk of `run` but the first; null when none starts. + * @details Call on the building thread after `builder` holds the witness and before any opcode reaches it. The + * seeds are witnesses, whose values the builder holds from its construction; the splice checks at each chunk's turn + * that they still have them and that no later constraint joined or tagged them. Starts nothing for a builder + * without a witness, with fewer than three threads, without native threads, pthreads and exceptions, or under + * OpenMP. + */ + static std::unique_ptr launch(const bb::UltraCircuitBuilder& builder, + const std::vector& run, + const Sha256RunOptions& options); + + Sha256RunSplicer(const Sha256RunSplicer&) = delete; + Sha256RunSplicer(Sha256RunSplicer&&) = delete; + Sha256RunSplicer& operator=(const Sha256RunSplicer&) = delete; + Sha256RunSplicer& operator=(Sha256RunSplicer&&) = delete; + + /** + * @brief Cancel every scratch build still running, join every scratch thread and destroy every scratch builder. + */ + ~Sha256RunSplicer(); + + /** + * @brief Build `run` on `builder` where the serial build of the compressions would start, then log how many chunks + * were spliced, refused and built in place; `after_in_place(i)` runs once compression i is built in place. + * @details A `run` other than the one launched is built in place whole once every scratch build is cancelled. + */ + void build(bb::UltraCircuitBuilder& builder, + const std::vector& run, + const std::function& after_in_place); + + private: + struct Chunk; + using Clock = std::chrono::steady_clock; + + Sha256RunSplicer(const std::vector& run, size_t num_chunks, const Sha256RunOptions& options); + bool take(Chunk& chunk, bb::UltraCircuitBuilder& builder, bool same_run); + void refuse(Chunk& chunk, std::string reason); + void reap(); + std::string summary() const; + + std::vector run_; + size_t num_chunks_ = 0; + Sha256RunOptions options_; + // Indexed by chunk; null for chunk 0 and for chunks not launched. + std::vector> chunks_; + Sha256RunStats stats_; + Clock::time_point launched_at_; + Clock::time_point reached_at_; + // When the building thread reached the first launched chunk, and when that chunk's scratch build finished. + std::optional first_taken_; + Clock::time_point first_needed_at_; + Clock::time_point first_finished_at_; +}; + +/** + * @brief Build the SHA-256 compression constraints `run` of an Ultra circuit in list order: through `splicer` when it + * is not null, otherwise each in place; `after_in_place(i)` runs once compression i is built in place. + */ +void build_sha256_compressions(bb::UltraCircuitBuilder& builder, + const std::vector& run, + Sha256RunSplicer* splicer, + const Sha256RunOptions& options, + const std::function& after_in_place); + +} // namespace acir_format diff --git a/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.test.cpp b/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.test.cpp new file mode 100644 index 0000000..ccfc75a --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/dsl/acir_format/sha256_splice.test.cpp @@ -0,0 +1,360 @@ +#include "barretenberg/dsl/acir_format/sha256_splice.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/crypto/poseidon2/poseidon2_params.hpp" +#include "barretenberg/crypto/poseidon2/poseidon2_permutation.hpp" +#include "barretenberg/crypto/sha256/sha256.hpp" +#include "barretenberg/dsl/acir_format/acir_format.hpp" +#include "barretenberg/dsl/acir_format/scratch_build.hpp" +#include "barretenberg/dsl/acir_format/test_class.hpp" +#include "barretenberg/dsl/acir_format/witness_constant.hpp" +#include "barretenberg/flavor/ultra_flavor.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp" +#include "barretenberg/ultra_honk/prover_instance.hpp" +#include "barretenberg/ultra_honk/ultra_prover.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * An Ultra circuit whose SHA-256 compression constraints are built in chunks on scratch builders and spliced must equal + * the serial build of the same program in every builder member, and prove to the same bytes, whatever the chunk count + * and whichever chunks are built in place instead. + */ + +using namespace acir_format; +using namespace bb; + +namespace { + +using Builder = UltraCircuitBuilder; +using bb::test_utils::expect_same_builder; +using Poseidon2 = crypto::Poseidon2Permutation; + +constexpr size_t NUM_COMPRESSIONS = 12; + +Sha256RunOptions serial_options() +{ + return { .max_chunks = 1 }; +} + +// Three chunks of four compressions, on three threads or more. +Sha256RunOptions three_chunks() +{ + return { .min_compressions_per_chunk = NUM_COMPRESSIONS / 3, .max_chunks = 3 }; +} + +fr word(const uint32_t value) +{ + return fr(static_cast(value)); +} + +/** + * @brief A 32-bit XOR, then `num_compressions` SHA-256 compressions each taking the previous one's output as its state, + * the first message word of each range-constrained to 32 bits, then a Poseidon2 permutation of the last output's first + * four words. With `small_word`, the second message word of that compression is below 256 and range-constrained to 8 + * bits, which tags it. + */ +AcirProgram make_program(const size_t num_compressions, const std::optional small_word = std::nullopt) +{ + WitnessVector witness; + std::vector opcodes; + const auto add = [&](const fr& value) { + witness.push_back(value); + return static_cast(witness.size() - 1); + }; + const auto append = [&](const auto& constraint) { + const std::vector converted = constraint_to_acir_opcode(constraint); + opcodes.insert(opcodes.end(), converted.begin(), converted.end()); + }; + const auto witness_of = [](const uint32_t index) { return WitnessOrConstant::from_index(index); }; + + constexpr uint32_t LEFT = 0x12345678; + constexpr uint32_t RIGHT = 0x0f0f0f0f; + append(LogicConstraint{ .a = witness_of(add(word(LEFT))), + .b = witness_of(add(word(RIGHT))), + .result = add(word(LEFT ^ RIGHT)), + .num_bits = 32, + .is_xor_gate = true }); + + std::array state = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; + std::array state_witnesses{}; + for (size_t j = 0; j < 8; ++j) { + state_witnesses[j] = add(word(state[j])); + } + for (size_t i = 0; i < num_compressions; ++i) { + std::array block{}; + for (size_t j = 0; j < 16; ++j) { + block[j] = 0x9e3779b9U * static_cast((16 * i) + j + 1); + } + if (small_word == i) { + block[1] = 200; + } + Sha256Compression compression; + for (size_t j = 0; j < 16; ++j) { + compression.inputs[j] = witness_of(add(word(block[j]))); + } + for (size_t j = 0; j < 8; ++j) { + compression.hash_values[j] = witness_of(state_witnesses[j]); + } + state = crypto::sha256_block(state, block); + for (size_t j = 0; j < 8; ++j) { + compression.result[j] = add(word(state[j])); + } + state_witnesses = compression.result; + append(RangeConstraint{ .witness = compression.inputs[0].index, .num_bits = 32 }); + if (small_word == i) { + append(RangeConstraint{ .witness = compression.inputs[1].index, .num_bits = 8 }); + } + append(compression); + } + + Poseidon2::State input{}; + Poseidon2Constraint permutation; + for (size_t j = 0; j < input.size(); ++j) { + input[j] = word(state[j]); + permutation.state.push_back(witness_of(state_witnesses[j])); + } + for (const fr& output : Poseidon2::permutation(input)) { + permutation.result.push_back(add(output)); + } + append(permutation); + return AcirProgram{ .constraints = circuit_serde_to_acir_format(build_acir_circuit(opcodes), /*is_mega=*/false), + .witness = witness }; +} + +struct Build { + Builder builder; + Sha256RunStats stats; +}; + +Build build(const AcirProgram& program, Sha256RunOptions options) +{ + Build result; + options.stats = &result.stats; + AcirProgram copy = program; + result.builder = create_circuit(copy, ProgramMetadata{ .sha256_run = options }); + return result; +} + +HonkProof prove(Builder builder) +{ + auto prover_instance = std::make_shared>(builder); + auto verification_key = std::make_shared(prover_instance->get_precomputed()); + UltraProver_ prover(prover_instance, verification_key); + return prover.construct_proof(); +} + +/** + * @brief Whether the run was built in place whole because no scratch build started, as when a thread quota makes a + * thread fail to start. Counts that need the chunks do not hold then, but the circuit must still be the serial one. + */ +bool built_in_place_whole(const Sha256RunStats& stats) +{ + if (stats.launched != 0) { + return false; + } + EXPECT_EQ(stats.chunks, 1U); + EXPECT_EQ(stats.built_in_place, 1U); + return true; +} + +class Sha256SpliceTest : public ::testing::Test { + protected: + static void SetUpTestSuite() { bb::srs::init_file_crs_factory(bb::srs::bb_crs_path()); } + + void SetUp() override + { + if (!BB_SCRATCH_BUILDS_AVAILABLE) { + GTEST_SKIP() << "this build starts no scratch builds"; + } + if (bb::get_num_cpus() < 3) { + GTEST_SKIP() << "three chunks need three threads"; + } + } +}; + +TEST_F(Sha256SpliceTest, ChunksMatchTheSerialBuildAndItsProof) +{ + const AcirProgram program = make_program(NUM_COMPRESSIONS); + const Build serial = build(program, serial_options()); + const Build spliced = build(program, three_chunks()); + EXPECT_FALSE(serial.builder.failed()) << serial.builder.err(); + EXPECT_EQ(serial.stats.launched, 0); + expect_same_builder(spliced.builder, serial.builder); + EXPECT_EQ(prove(spliced.builder), prove(serial.builder)); + if (built_in_place_whole(spliced.stats)) { + GTEST_SKIP() << "no scratch thread started, so the run was built in place"; + } + EXPECT_EQ(spliced.stats.chunks, 3); + EXPECT_EQ(spliced.stats.spliced, 2); + EXPECT_EQ(spliced.stats.refused, 0) << spliced.stats.first_refusal; +} + +TEST_F(Sha256SpliceTest, ChunkCountDoesNotChangeTheBuilder) +{ + const AcirProgram program = make_program(Sha256RunOptions::MAX_CHUNKS); + const Build serial = build(program, serial_options()); + const size_t most = std::min(Sha256RunOptions::MAX_CHUNKS, bb::get_num_cpus()); + bool any_in_place = false; + for (const size_t num_chunks : { size_t{ 2 }, size_t{ 3 }, most }) { + const Build spliced = build(program, { .min_compressions_per_chunk = 1, .max_chunks = num_chunks }); + expect_same_builder(spliced.builder, serial.builder); + if (built_in_place_whole(spliced.stats)) { + any_in_place = true; + continue; + } + EXPECT_EQ(spliced.stats.chunks, num_chunks); + EXPECT_EQ(spliced.stats.spliced, num_chunks - 1) << spliced.stats.first_refusal; + } + if (any_in_place) { + GTEST_SKIP() << "a run started no scratch thread and was built in place"; + } +} + +TEST_F(Sha256SpliceTest, RefusedAndThrowingMiddleChunksAreBuiltInPlace) +{ + // The 8-bit range constraint tags a message word of compression 5, in the middle chunk. + const AcirProgram program = make_program(NUM_COMPRESSIONS, /*small_word=*/5); + const Build serial = build(program, serial_options()); + + const Build refused = build(program, three_chunks()); + expect_same_builder(refused.builder, serial.builder); + const bool refused_in_place = built_in_place_whole(refused.stats); + if (!refused_in_place) { + EXPECT_EQ(refused.stats.spliced, 1); + EXPECT_EQ(refused.stats.refused, 1); + EXPECT_EQ(refused.stats.built_in_place, 2); + EXPECT_EQ(refused.stats.first_refusal, "an input carries a range tag"); + } + + Sha256RunOptions throwing = three_chunks(); + throwing.after_scratch_build = [](const size_t chunk, Builder& /*scratch*/) { + if (chunk == 1) { + throw_or_abort("forced scratch build failure"); + } + }; + const Build threw = build(program, throwing); + expect_same_builder(threw.builder, serial.builder); + const bool threw_in_place = built_in_place_whole(threw.stats); + if (!threw_in_place) { + EXPECT_EQ(threw.stats.spliced, 1); + EXPECT_EQ(threw.stats.refused, 1); + EXPECT_EQ(threw.stats.built_in_place, 2); + EXPECT_EQ(threw.stats.first_refusal, "the scratch build threw: forced scratch build failure"); + } + if (refused_in_place || threw_in_place) { + GTEST_SKIP() << "a run started no scratch thread and was built in place, so nothing was refused"; + } +} + +TEST_F(Sha256SpliceTest, ShortRunStartsNoScratchThread) +{ + std::atomic recorded = false; + Sha256RunOptions options; + options.scratch_recording = [&](size_t /*chunk*/, size_t /*count*/) { recorded.store(true); }; + // One compression short of two chunks under the production rule. + const Build result = build(make_program((2 * Sha256RunOptions::MIN_COMPRESSIONS_PER_CHUNK) - 1), options); + EXPECT_FALSE(result.builder.failed()) << result.builder.err(); + EXPECT_EQ(result.stats.chunks, 1); + EXPECT_EQ(result.stats.launched, 0); + EXPECT_FALSE(recorded.load()); +} + +/** + * An error on the building thread while chunks are being built cancels every running scratch build before joining it, + * and surfaces as the serial build's error. Chunk 2 is held at its first recording until chunk 1 has been joined and + * discarded, which happens only after every cancellation was requested, so on release it throws at that recording. + * Chunk 1 is joined first and so cannot be held; whether it stops early depends on timing, and it is not checked. + */ +TEST_F(Sha256SpliceTest, AnErrorOnTheBuildingThreadCancelsTheRunningChunks) +{ + const AcirProgram program = make_program(NUM_COMPRESSIONS); + // The checks below need both scratch builds running. A thread quota can keep scratch threads from starting, and + // the run is then built in place with nothing to cancel, which a run without hooks shows first. + if (built_in_place_whole(build(program, three_chunks()).stats)) { + GTEST_SKIP() << "no scratch thread started, so there is nothing to cancel"; + } + std::mutex mutex; + std::condition_variable recorded; + size_t num_recording = 0; + std::array, 3> finished{}; + std::promise first_discarded; + const std::shared_future released = first_discarded.get_future().share(); + std::vector discarded; + + // Throws before the second compression of chunk 0, once both scratch builds have reached a recording if asked to. + const auto fail_in_chunk_0 = [&](const bool wait_for_chunks) { + return [&, wait_for_chunks](Builder& /*builder*/, const size_t compression) { + if (compression != 1) { + return; + } + if (wait_for_chunks) { + std::unique_lock lock(mutex); + EXPECT_TRUE(recorded.wait_for(lock, std::chrono::minutes(2), [&] { return num_recording == 2; })); + } + throw_or_abort("forced building thread failure"); + }; + }; + // Only run where scratch builds start, which needs exceptions; other builds must still compile it. + const auto error_of = [&](const Sha256RunOptions& options) { +#if BB_SCRATCH_BUILDS_AVAILABLE + try { + (void)build(program, options); + } catch (const std::exception& error) { + return std::string(error.what()); + } +#else + (void)build(program, options); +#endif + return std::string(); + }; + + Sha256RunOptions serial = serial_options(); + serial.before_in_place = fail_in_chunk_0(false); + Sha256RunOptions chunked = three_chunks(); + chunked.before_in_place = fail_in_chunk_0(true); + chunked.after_scratch_build = [&](const size_t chunk, Builder& /*scratch*/) { finished[chunk].store(true); }; + chunked.scratch_recording = [&](const size_t chunk, const size_t count) { + if (count != 1) { + return; + } + { + const std::lock_guard lock(mutex); + ++num_recording; + } + recorded.notify_all(); + if (chunk == 2) { + EXPECT_EQ(released.wait_for(std::chrono::minutes(2)), std::future_status::ready); + } + }; + chunked.discarded = [&](const size_t chunk) { + discarded.push_back(chunk); + if (chunk == 1) { + first_discarded.set_value(); + } + }; + + const std::string serial_error = error_of(serial); + EXPECT_EQ(serial_error, "forced building thread failure"); + EXPECT_EQ(error_of(chunked), serial_error); + EXPECT_FALSE(finished[2].load()); + EXPECT_EQ(discarded, (std::vector{ 1, 2 })); +} + +} // namespace diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/field_impl.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/field_impl.hpp index c9283b3..adc97a2 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/field_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/field_impl.hpp @@ -293,6 +293,30 @@ template constexpr field field::to_montgomery_form() const noexc template constexpr field field::from_montgomery_form() const noexcept { +#if defined(__SIZEOF_INT128__) && !defined(__wasm__) + if constexpr (T::modulus_3 != 0 && T::modulus_3 < MODULUS_TOP_LIMB_LARGE_THRESHOLD) { + if (!std::is_constant_evaluated()) { + // REDC(y) with no product to form: y already occupies only four words. Use four fixed + // reduction rounds, avoiding the structural zero products of multiplication by raw one. + uint64_t t0 = data[0], t1 = data[1], t2 = data[2], t3 = data[3]; + auto reduce_word = [&] { + const uint64_t q = t0 * T::r_inv; + uint64_t carry = mac_discard_lo(t0, q, T::modulus_0); + t0 = mac(t1, q, T::modulus_1, carry, carry); + t1 = mac(t2, q, T::modulus_2, carry, carry); + t2 = mac(t3, q, T::modulus_3, carry, carry); + t3 = carry; + }; + reduce_word(); + reduce_word(); + reduce_word(); + reduce_word(); + field result{ t0, t1, t2, t3 }; + result.assert_coarse_form(); + return result; + } + } +#endif constexpr field one_raw{ 1, 0, 0, 0 }; return operator*(one_raw); } @@ -306,6 +330,14 @@ template constexpr void field::self_to_montgomery_form() & noexcept template constexpr void field::self_from_montgomery_form() & noexcept { +#if defined(__SIZEOF_INT128__) && !defined(__wasm__) + if constexpr (T::modulus_3 != 0 && T::modulus_3 < MODULUS_TOP_LIMB_LARGE_THRESHOLD) { + if (!std::is_constant_evaluated()) { + *this = from_montgomery_form(); + return; + } + } +#endif constexpr field one_raw{ 1, 0, 0, 0 }; *this *= one_raw; } diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/prime_field.test.cpp b/barretenberg/cpp/src/barretenberg/ecc/fields/prime_field.test.cpp index 2c5bc79..75aead4 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/prime_field.test.cpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/prime_field.test.cpp @@ -21,6 +21,7 @@ #include "barretenberg/numeric/random/engine.hpp" #include "barretenberg/numeric/uint256/uint256.hpp" #include "barretenberg/serialize/test_helper.hpp" +#include #include using namespace bb; @@ -800,3 +801,84 @@ TYPED_TEST(PrimeFieldTwoFiftyFourTest, ToMontgomeryFormNoReductionNeeded) << "Edge case: Result of to_montgomery_form exceeds [0, 2p) for offset " << offset; } } + +namespace { +template void check_conversion_against_raw_one(const F& input) +{ + const F original_product = input * F{ 1, 0, 0, 0 }; + const F original_reduced = original_product.reduce_once(); + const F product = input.from_montgomery_form(); + const F reduced = input.from_montgomery_form_reduced(); + F self_product = input; + self_product.self_from_montgomery_form(); + F self_reduced = input; + self_reduced.self_from_montgomery_form_reduced(); + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(product.data[limb], original_product.data[limb]); + EXPECT_EQ(reduced.data[limb], original_reduced.data[limb]); + EXPECT_EQ(self_product.data[limb], original_product.data[limb]); + EXPECT_EQ(self_reduced.data[limb], original_reduced.data[limb]); + } +} +} // namespace + +TYPED_TEST(PrimeFieldTest, FromMontgomerySmallValuesAndCoarseRepresentatives) +{ + using F = TypeParam; + constexpr F constant_input(17); + constexpr F constant_result = constant_input.from_montgomery_form_reduced(); + static_assert(constant_result.data[0] == 17 && constant_result.data[1] == 0 && constant_result.data[2] == 0 && + constant_result.data[3] == 0); + const uint64_t top = F::modulus.data[3]; + const uint256_t maximum{ UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX }; + for (const uint64_t value : std::array{ 0, + 1, + 2, + 65535, + 65536, + uint64_t(1) << 32, + (uint64_t(1) << 63) - 1, + uint64_t(1) << 63, + UINT64_MAX, + top - 1, + top, + top + 1, + top + 2 }) { + const F input = F(value).reduce_once(); + check_conversion_against_raw_one(input); + const F reduced = input.from_montgomery_form_reduced(); + EXPECT_EQ(reduced.data[0], value); + EXPECT_EQ(reduced.data[1] | reduced.data[2] | reduced.data[3], 0U); + const uint256_t raw{ input.data[0], input.data[1], input.data[2], input.data[3] }; + if (raw <= maximum - F::modulus) { + const uint256_t coarse = raw + F::modulus; + check_conversion_against_raw_one(F{ coarse.data[0], coarse.data[1], coarse.data[2], coarse.data[3] }); + } + } +} + +TYPED_TEST(PrimeFieldTest, FromMontgomeryArbitraryRawWords) +{ + using F = TypeParam; + const uint256_t maximum{ UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX }; + const uint256_t twice_p = F::modulus + F::modulus; + for (const uint256_t& raw : std::array{ + uint256_t(0), F::modulus - 1, F::modulus, F::modulus + 1, twice_p - 1, twice_p, twice_p + 1, maximum }) { + check_conversion_against_raw_one(F{ raw.data[0], raw.data[1], raw.data[2], raw.data[3] }); + } + for (size_t bit = 0; bit < 256; ++bit) { + const uint256_t raw = uint256_t(1) << bit; + check_conversion_against_raw_one(F{ raw.data[0], raw.data[1], raw.data[2], raw.data[3] }); + } + uint64_t state = 0x9e3779b97f4a7c15ULL; + auto next = [&]() { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + return state; + }; + for (size_t i = 0; i < 4096; ++i) { + const std::array words{ next(), next(), next(), next() }; + check_conversion_against_raw_one(F{ words[0], words[1], words[2], words[3] }); + } +} diff --git a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_push_span.hpp b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_push_span.hpp index 1059b1b..b499d9c 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_push_span.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/fields/vector_field_push_span.hpp @@ -85,17 +85,22 @@ template struct VectorFieldPushSpan { } // The g-th completed VectorField, for SIMD arithmetic over all W of its elements at once. + // Unchecked in release like Polynomial::get: walkers call require_backing() once per walk, and every + // change of count is checked (push, adopt_cursor), so num_full_vectors() never exceeds the backing. [[gnu::always_inline]] Vec& operator[](size_t g) noexcept { - BB_ASSERT(g < vector_fields.size()); + BB_ASSERT_DEBUG(g < vector_fields.size()); return vector_fields[g]; } [[gnu::always_inline]] const Vec& operator[](size_t g) const noexcept { - BB_ASSERT(g < vector_fields.size()); + BB_ASSERT_DEBUG(g < vector_fields.size()); return vector_fields[g]; } + // Release bounds check for a walk that indexes this span at every g < num_full. + void require_backing(size_t num_full) const noexcept { BB_ASSERT_LTE(num_full, vector_fields.size()); } + size_t num_full_vectors() const noexcept { return count / W; } // completed VectorFields size_t tail() const noexcept { return count % W; } // trailing elements, in partial[0..tail()) const Field* tail_data() const noexcept { return partial.data(); } @@ -137,6 +142,7 @@ template struct VectorFieldPushSpan { // this so the result reports the same size() / tail() as its input. void adopt_cursor(const VectorFieldPushSpan& src) noexcept { + require_backing(src.num_full_vectors()); count = src.count; lane = src.lane; } @@ -203,6 +209,7 @@ template struct VectorAffineElementPushSpan { template void for_each_point(Kernel kernel) const { size_t k = 0; + y.require_backing(x.num_full_vectors()); for (size_t g = 0; g < x.num_full_vectors(); ++g) { const auto xs = x[g].to_array(); const auto ys = y[g].to_array(); @@ -260,6 +267,7 @@ template const auto& first = std::get<0>(spans); const size_t num_full = first.num_full_vectors(); const size_t ntail = first.tail(); + (std::get(spans).require_backing(num_full), ...); for (size_t g = 0; g < num_full; ++g) { kernel(std::get(spans)[g]...); } @@ -311,6 +319,7 @@ template { const size_t num_full = in.num_full_vectors(); const size_t ntail = in.tail(); + out.require_backing(num_full); if constexpr (Dir == Direction::Backward) { for (size_t g = num_full; g-- > 0;) { step(bulk_acc, in[g], out[g]); diff --git a/barretenberg/cpp/src/barretenberg/ecc/groups/group.hpp b/barretenberg/cpp/src/barretenberg/ecc/groups/group.hpp index eead342..8fcd3bb 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/groups/group.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/groups/group.hpp @@ -93,9 +93,7 @@ template class group { const size_t num_generators, const size_t starting_index = 0) { - // Safety: domain_separator_bytes is indexed via &domain_separator_bytes[0] below. - // An empty domain separator would be UB and also defeats domain separation. - BB_ASSERT(!domain_separator_bytes.empty(), "derive_generators: domain_separator_bytes must be non-empty"); + const blake3::out_array domain_hash = hash_domain_separator(domain_separator_bytes); // We serialize the generator index into 4 bytes (uint32_t). Ensure we never silently truncate. if (num_generators > 0) { @@ -106,21 +104,9 @@ template class group { } std::vector result; - const auto domain_hash = blake3::blake3s_constexpr(&domain_separator_bytes[0], domain_separator_bytes.size()); - std::vector generator_preimage; - generator_preimage.reserve(64); - std::copy(domain_hash.begin(), domain_hash.end(), std::back_inserter(generator_preimage)); - for (size_t i = 0; i < 32; ++i) { - generator_preimage.emplace_back(0); - } + result.reserve(num_generators); for (size_t i = starting_index; i < starting_index + num_generators; ++i) { - auto generator_index = static_cast(i); - uint32_t mask = 0xff; - generator_preimage[32] = static_cast(generator_index >> 24); - generator_preimage[33] = static_cast((generator_index >> 16) & mask); - generator_preimage[34] = static_cast((generator_index >> 8) & mask); - generator_preimage[35] = static_cast(generator_index & mask); - result.push_back(affine_element::hash_to_curve(generator_preimage)); + result.push_back(derive_generator(domain_hash, static_cast(i))); } return result; } @@ -135,6 +121,33 @@ template class group { } return derive_generators(domain_bytes, num_generators, starting_index); } + + /** + * @brief The BLAKE3 hash of a domain separator, which forms the first half of every generator preimage in + * `derive_generators`. + */ + inline static blake3::out_array hash_domain_separator(const std::vector& domain_separator_bytes) + { + // An empty domain separator defeats domain separation. + BB_ASSERT(!domain_separator_bytes.empty(), "derive_generators: domain_separator_bytes must be non-empty"); + return blake3::blake3s_constexpr(domain_separator_bytes.data(), domain_separator_bytes.size()); + } + + /** + * @brief Generator number `generator_index` of the domain whose separator hashes to `domain_hash`, exactly as + * `derive_generators` computes it. + * @details A pure function of its arguments, so distinct indices may be derived concurrently. + */ + inline static affine_element derive_generator(const blake3::out_array& domain_hash, const uint32_t generator_index) + { + std::vector generator_preimage(64, 0); + std::copy(domain_hash.begin(), domain_hash.end(), generator_preimage.begin()); + generator_preimage[32] = static_cast(generator_index >> 24); + generator_preimage[33] = static_cast((generator_index >> 16) & 0xff); + generator_preimage[34] = static_cast((generator_index >> 8) & 0xff); + generator_preimage[35] = static_cast(generator_index & 0xff); + return affine_element::hash_to_curve(generator_preimage); + } }; } // namespace bb 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 index 3e09654..14ce9b4 100644 --- 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 @@ -5,6 +5,7 @@ #include "barretenberg/numeric/random/engine.hpp" #include "barretenberg/polynomials/polynomial.hpp" #include "scalar_multiplication.hpp" +#include #include using namespace bb; @@ -27,6 +28,29 @@ class ConcurrencyScope { 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 BatchMsmConcurrentChunksTest : public ::testing::Test {}; @@ -34,6 +58,77 @@ template class BatchMsmConcurrentChunksTest : public ::testing::Te using CurveTypes = ::testing::Types; TYPED_TEST_SUITE(BatchMsmConcurrentChunksTest, CurveTypes); +// The chunked path's arena block is capped at 2 GiB, so a pool wide enough that one slice per worker overflows the cap +// runs fewer workers than the pool. 128 members of 2^15 points at pool width 128 take the many-member admission as one +// chunk each; with every fourth scalar non-zero (a different residue per member) every member must still match its +// stand-alone MSM, checked exactly on the first, middle and last members and on all through one random linear +// combination, and get its scalars back. The test allocates an arena block of about 2 GiB. +TYPED_TEST(BatchMsmConcurrentChunksTest, BudgetCappedWorkersMatchStandaloneMsm) +{ +#if defined(__wasm__) || defined(NO_MULTITHREADING) + GTEST_SKIP() << "no concurrent large-member path without threads"; +#else + using Element = typename TypeParam::Element; + using AffineElement = typename TypeParam::AffineElement; + using ScalarField = typename TypeParam::ScalarField; + + constexpr size_t POOL = 128; + constexpr size_t N = scalar_multiplication::MSM_MIN_PTS_PER_THREAD * POOL; + // The dispatch's cap, checked against the smaller of the two GLV variants' slices, so it binds whichever the batch + // uses. + constexpr size_t CHUNK_ARENA_BUDGET = size_t{ 2 } << 30; + const size_t with_glv = scalar_multiplication::compute_arena_bytes_for_msm(N, true, false, 1); + const size_t without_glv = scalar_multiplication::compute_arena_bytes_for_msm(N, false, false, 1); + const size_t slice = with_glv < without_glv ? with_glv : without_glv; + ASSERT_GT(slice, 0U); + ASSERT_LT(CHUNK_ARENA_BUDGET / slice, POOL); + + std::vector points(N); + for (auto& point : points) { + point = AffineElement::random_element(&engine); + } + ConcurrencyScope concurrency(POOL); + std::vector> scalars(POOL, std::vector(N, ScalarField::zero())); + std::vector> spans; + for (size_t k = 0; k < POOL; ++k) { + for (size_t i = k % 4; i < N; i += 4) { + scalars[k][i] = ScalarField::random_element(&engine); + } + spans.emplace_back(0, std::span(scalars[k])); + } + const auto original = scalars; + const auto result = + scalar_multiplication::MSM_fast::batch_multi_scalar_mul(points, spans, /*handle_edge_cases=*/false); + for (size_t k = 0; k < POOL; ++k) { + EXPECT_EQ(scalars[k], original[k]) << "scalars of MSM " << k << " not restored"; + } + for (const size_t k : { size_t{ 0 }, POOL / 2, POOL - 1 }) { + const AffineElement expected = scalar_multiplication::MSM::msm( + points, PolynomialSpan(0, std::span(scalars[k])), true); + EXPECT_EQ(to_buffer(result[k]), to_buffer(expected)) << "MSM " << k; + } + + // Linearity over the shared points: sum_k r_k * MSM(points, s_k) == MSM(points, sum_k r_k * s_k) for non-zero r_k. + std::vector weights(POOL, ScalarField::zero()); + for (auto& weight : weights) { + while (weight.is_zero()) { + weight = ScalarField::random_element(&engine); + } + } + std::vector combined(N, ScalarField::zero()); + Element weighted_results = Element::infinity(); + for (size_t k = 0; k < POOL; ++k) { + for (size_t i = k % 4; i < N; i += 4) { + combined[i] += weights[k] * scalars[k][i]; + } + weighted_results += Element(result[k]) * weights[k]; + } + const AffineElement expected_combination = scalar_multiplication::MSM::msm( + points, PolynomialSpan(0, std::span(combined)), true); + EXPECT_EQ(to_buffer(AffineElement(weighted_results)), to_buffer(expected_combination)); +#endif +} + // 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. @@ -49,16 +144,9 @@ TYPED_TEST(BatchMsmConcurrentChunksTest, MatchesStandaloneMsm) 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); - } - }); + std::vector points; + std::vector pool; + random_points_and_scalars(max_wide, points, pool); 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 } }) { @@ -102,7 +190,8 @@ TYPED_TEST(BatchMsmConcurrentChunksTest, MatchesStandaloneMsm) } const auto original_scalars = batch_scalars; - const auto result = scalar_multiplication::MSM::batch_multi_scalar_mul( + // MSM_fast directly: the MSM facade runs the legacy implementation when BB_MSM_LEGACY is set. + const auto result = scalar_multiplication::MSM_fast::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. @@ -113,3 +202,115 @@ TYPED_TEST(BatchMsmConcurrentChunksTest, MatchesStandaloneMsm) } #endif } + +// A batch of three wide members takes the chunked path only where each member's share of the pool is at least 8/3 +// threads and its 2^16-point chunks fill the pool: at pool width 8 here (10 minimum chunks, raised to 16 unequal +// parts), not at 4 or 12. Every width must give each member's stand-alone MSM byte for byte and restore its scalars. +TYPED_TEST(BatchMsmConcurrentChunksTest, FewWideMembersMatchStandaloneMsm) +{ +#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 sizes = { (3 * CHUNK) + 5, (2 * CHUNK) + 777, (3 * CHUNK) - 3 }; + const size_t max_n = *std::max_element(sizes.begin(), sizes.end()); + std::vector points; + std::vector pool; + random_points_and_scalars(max_n, points, pool); + + for (const size_t pool_width : { size_t{ 4 }, size_t{ 8 }, size_t{ 12 } }) { + ConcurrencyScope concurrency(pool_width); + std::vector> batch_scalars(sizes.size()); + std::vector> spans; + std::vector expected(sizes.size()); + for (size_t k = 0; k < sizes.size(); ++k) { + // The second member is sparse, so the parts of one batch differ in cost as well as in length. + batch_scalars[k].resize(sizes[k]); + for (size_t i = 0; i < sizes[k]; ++i) { + const ScalarField& random = pool[((k * 17) + i) % max_n]; + batch_scalars[k][i] = (k == 1 && i % 3 != 0) ? ScalarField::zero() : random; + } + 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_fast::batch_multi_scalar_mul( + points, spans, /*handle_edge_cases=*/false); + for (size_t k = 0; k < sizes.size(); ++k) { + 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"; + } + } + + // Members of 3, 3 and 2 times 2^16 points at pool width 8 are admitted and cut into exactly eight parts, one per + // 2^16 points. Member 0's chunks sum to equal points (each chunk doubles the points and halves the scalars), + // member 1's middle chunk is all zero, and member 2's two chunks sum to opposite points, so its MSM is the point at + // infinity. The same shape with member 1 reading part of member 0's scalars must not be admitted, and must still + // give every stand-alone MSM and restore the shared scalars. + using Element = typename TypeParam::Element; + ConcurrencyScope concurrency(8); + std::vector chunk_points(3 * CHUNK); + parallel_for_range(CHUNK, [&](size_t start, size_t end) { + for (size_t j = start; j < end; ++j) { + Element p(points[j]); + for (size_t c = 0; c < 3; ++c) { + chunk_points[(c * CHUNK) + j] = AffineElement(p); + p = p.dbl(); + } + } + }); + const ScalarField half = ScalarField(2).invert(); + std::vector> edge(3); + edge[0].resize(3 * CHUNK); + edge[1].resize(3 * CHUNK); + edge[2].resize(2 * CHUNK); + for (size_t j = 0; j < CHUNK; ++j) { + edge[0][j] = pool[j]; + edge[0][CHUNK + j] = pool[j] * half; + edge[0][(2 * CHUNK) + j] = pool[j] * half * half; + edge[1][j] = pool[(j + 7) % max_n]; + edge[1][CHUNK + j] = ScalarField::zero(); + edge[1][(2 * CHUNK) + j] = pool[(j + 11) % max_n]; + edge[2][j] = pool[(j + 13) % max_n]; + edge[2][CHUNK + j] = -(edge[2][j] * half); + } + auto standalone = [&](std::span scalars) { + return scalar_multiplication::MSM::msm( + chunk_points, PolynomialSpan(0, scalars), /*handle_edge_cases=*/true); + }; + { + std::vector> spans; + for (auto& scalars : edge) { + spans.emplace_back(0, std::span(scalars)); + } + const auto original = edge; + const auto result = + scalar_multiplication::MSM_fast::batch_multi_scalar_mul(chunk_points, spans, false); + const AffineElement first_chunk = standalone(std::span(edge[0]).first(CHUNK)); + EXPECT_EQ(to_buffer(result[0]), to_buffer(AffineElement(Element(first_chunk) * ScalarField(3)))); + EXPECT_TRUE(result[2].is_point_at_infinity()); + for (size_t k = 0; k < edge.size(); ++k) { + EXPECT_EQ(to_buffer(result[k]), to_buffer(standalone(edge[k]))) << "edge-case MSM " << k; + EXPECT_EQ(edge[k], original[k]) << "scalars of edge-case MSM " << k << " not restored"; + } + } + { + std::vector> spans; + spans.emplace_back(0, std::span(edge[0])); + spans.emplace_back(0, std::span(edge[0]).subspan(CHUNK)); + spans.emplace_back(0, std::span(edge[1])); + const auto original = edge; + const auto result = + scalar_multiplication::MSM_fast::batch_multi_scalar_mul(chunk_points, spans, false); + EXPECT_EQ(to_buffer(result[0]), to_buffer(standalone(edge[0]))); + EXPECT_EQ(to_buffer(result[1]), to_buffer(standalone(std::span(edge[0]).subspan(CHUNK)))); + EXPECT_EQ(to_buffer(result[2]), to_buffer(standalone(edge[1]))); + EXPECT_EQ(edge, original) << "aliased scalars not restored"; + } +#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 5117268..90d14a0 100644 --- a/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp +++ b/barretenberg/cpp/src/barretenberg/ecc/scalar_multiplication/pippenger_batched.hpp @@ -238,6 +238,11 @@ void pippenger_round_parallel_batched(std::span= CONCURRENT_MIN_POOL_WIDTH: fewer threads make the win too small to justify. + // A batch of a few large members also qualifies when each member's share of the pool, pool_width / members, is at + // least 8/3 threads and its 2^16-point chunks fill the pool. Spreading one member over that many threads costs + // CPU and leaves threads idle in its reductions, which single-threaded chunks avoid; with fewer threads per + // member there is no such cost to remove, and the chunked path's tail makes it a loss. + static constexpr size_t CONCURRENT_CHUNK_POINTS = size_t{ 1 } << 16; #ifdef __wasm__ // wasm keeps large members on the sequential shared-arena dispatch: with single-threaded MSMs the // concurrent path's per-worker live arenas buy nothing over one reused arena. @@ -268,9 +273,15 @@ void pippenger_round_parallel_batched(std::span= CONCURRENT_MIN_POOL_WIDTH && - large_members.size() > CONCURRENT_MIN_MEMBERS && - max_large_n <= total_large_n / pool_width && scalar_spans_disjoint(); + size_t min_chunks = 0; + for (size_t m : large_members) { + min_chunks += (n_input[m] + CONCURRENT_CHUNK_POINTS - 1) / CONCURRENT_CHUNK_POINTS; + } + const bool many_balanced_members = + large_members.size() > CONCURRENT_MIN_MEMBERS && max_large_n <= total_large_n / pool_width; + const bool few_wide_members = (3 * pool_width) >= (8 * large_members.size()) && min_chunks >= pool_width; + const bool large_members_concurrent = pool_width >= CONCURRENT_MIN_POOL_WIDTH && !large_members.empty() && + (many_balanced_members || few_wide_members) && scalar_spans_disjoint(); #endif // A few independent large native MSMs can instead share the CPU budget, @@ -513,9 +524,7 @@ void pippenger_round_parallel_batched(std::span parts(large_members.size()); + size_t total_parts = 0; + for (size_t i = 0; i < large_members.size(); ++i) { + parts[i] = (n_input[large_members[i]] + CONCURRENT_CHUNK_POINTS - 1) / CONCURRENT_CHUNK_POINTS; + total_parts += parts[i]; + } + const size_t whole_rounds = ((total_parts + pool_width - 1) / pool_width) * pool_width; + // Orders members by part size n / parts, compared exactly by cross-multiplication; ties go to the lower index. + const auto smaller_parts = [&](size_t a, size_t b) { + const size_t lhs = n_input[large_members[a]] * parts[b]; + const size_t rhs = n_input[large_members[b]] * parts[a]; + return lhs != rhs ? lhs < rhs : a > b; + }; + std::priority_queue, decltype(smaller_parts)> largest_parts(smaller_parts); + for (size_t i = 0; i < large_members.size(); ++i) { + largest_parts.push(i); + } + for (size_t added = total_parts; added < whole_rounds; ++added) { + const size_t i = largest_parts.top(); + if (n_input[large_members[i]] <= parts[i]) { + break; + } + largest_parts.pop(); + ++parts[i]; + largest_parts.push(i); + } std::vector chunks; - for (size_t m : large_members) { + for (size_t i = 0; i < large_members.size(); ++i) { + const size_t m = large_members[i]; 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 }); + for (size_t k = 0; k < parts[i]; ++k) { + const size_t begin = (n * k) / parts[i]; + chunks.push_back({ m, begin, ((n * (k + 1)) / parts[i]) - begin }); } } std::sort(chunks.begin(), chunks.end(), [](const Chunk& a, const Chunk& b) { @@ -544,10 +583,37 @@ void pippenger_round_parallel_batched(std::span= 2 ? std::max(2, (info_for(chunk.member) * chunk.length) / n) + : info_for(chunk.member); + const bool ext_glv = !external_glv_for(chunk.member, n).empty(); + chunk_arena_bytes = std::max( + chunk_arena_bytes, compute_arena_bytes_for_msm(chunk.length, ext_glv, info, /*max_threads=*/1)); + } + const size_t workers_by_budget = chunk_arena_bytes > 0 + ? std::max(1, CHUNK_ARENA_BUDGET / chunk_arena_bytes) + : std::numeric_limits::max(); std::vector partials(chunks.size()); - const size_t num_workers = std::min(pool_width, chunks.size()); + const size_t num_workers = std::min({ pool_width, chunks.size(), workers_by_budget }); + std::unique_ptr chunk_arena_owner; // NOLINT(cppcoreguidelines-avoid-c-arrays) + if (chunk_arena_bytes > 0) { + chunk_arena_owner = std::make_unique_for_overwrite( + num_workers * chunk_arena_bytes); // NOLINT(cppcoreguidelines-avoid-c-arrays) + } std::atomic next_chunk{ 0 }; - bb::parallel_for(num_workers, [&](size_t) { + bb::parallel_for(num_workers, [&](size_t tid) { + std::span worker_arena; + if (chunk_arena_bytes > 0) { + worker_arena = { chunk_arena_owner.get() + (tid * chunk_arena_bytes), chunk_arena_bytes }; + } while (true) { const size_t c = next_chunk.fetch_add(1, std::memory_order_relaxed); if (c >= chunks.size()) { @@ -564,8 +630,9 @@ void pippenger_round_parallel_batched(std::span 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); + sp, point_arrays[m].subspan(offset), info, glv, worker_arena, /*max_threads=*/1); } + round_parallel_detail::release_arena_slice(worker_arena); }); // out_results starts at infinity; summing in chunk order keeps the result deterministic. for (size_t c = 0; c < chunks.size(); ++c) { 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 23ce0a6..1951004 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 @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #if !defined(__wasm__) && !defined(NO_MULTITHREADING) && SIZE_MAX > UINT32_MAX @@ -287,6 +288,8 @@ template inline void drain_batch(ThreadScratch& s, size_ // pair_dest[k] is the `next_len` value recorded when the k-th pair was queued, which is < the // read cursor at that level — so the write lands on an already-read slot (see tree_reduce_in_place). size_t k = 0; + s.out.x.require_backing(s.out.num_full_vectors()); + s.out.y.require_backing(s.out.num_full_vectors()); for (size_t g = 0; g < s.out.num_full_vectors(); ++g) { const auto xs = s.out.x[g].to_array(); const auto ys = s.out.y[g].to_array(); @@ -3015,59 +3018,55 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan(chunk_bucket_lo[tid]); - const size_t my_hi = chunk_bucket_hi_all[(w * num_threads) + tid]; - size_t bucket_cursor = my_lo; - - for (size_t pos = cs_lo; pos < cs_hi;) { - const size_t end = std::min(pos + SUBCHUNK_ENTRIES_CAP, cs_hi); - reduce_chunk(s, - sched_w, - bucket_start, - pos, - end, - bucket_cursor, - my_hi, - points, - std::span(dedup_state.extra_points)); - const size_t len = s.result_len; - for (size_t k = 0; k < len; ++k) { - const uint32_t d = s.curr_buckets[k]; - const size_t slot = d - my_lo; - if (dst_present[slot]) { - s.overflow_slots[s.overflow_len] = static_cast(slot); - s.overflow_pts[s.overflow_len] = s.curr_pts[k]; - ++s.overflow_len; - } else { - dst_dense[slot] = s.curr_pts[k]; - dst_present[slot] = 1; - } + // Stage 6a: each (schedule slice, window) owns a separate dense output range. + // Scratch belongs to the worker executing that job; no state crosses job boundaries. + // Keep each job's original reduction order and output offsets so Stage 6b is unchanged. + auto bucket_partials_job = [&](size_t tid, size_t w, size_t worker_id) { + auto& s = thread_scratch[worker_id]; + const size_t* chunk_start_w = chunk_start_all.data() + (w * (num_threads + 1)); + const size_t cs_lo = chunk_start_w[tid]; + const size_t cs_hi = chunk_start_w[tid + 1]; + if (cs_lo == cs_hi) { + return; + } + const uint32_t* sched_w = schedule.data() + (w * n); + const size_t* bucket_start = bucket_start_all.data() + (w * (bucket_stride + 1)); + AffineElement* dst_dense = + bucket_partials_dense.data() + bucket_partials_offsets[(tid * windows_in_batch) + w]; + uint8_t* dst_present = + bucket_partials_present.data() + bucket_partials_offsets[(tid * windows_in_batch) + w]; + const size_t* chunk_bucket_lo = chunk_bucket_lo_all.data() + (w * (num_threads + 1)); + const uint32_t my_lo = static_cast(chunk_bucket_lo[tid]); + const size_t my_hi = chunk_bucket_hi_all[(w * num_threads) + tid]; + size_t bucket_cursor = my_lo; + + for (size_t pos = cs_lo; pos < cs_hi;) { + const size_t end = std::min(pos + SUBCHUNK_ENTRIES_CAP, cs_hi); + reduce_chunk(s, + sched_w, + bucket_start, + pos, + end, + bucket_cursor, + my_hi, + points, + std::span(dedup_state.extra_points)); + const size_t len = s.result_len; + for (size_t k = 0; k < len; ++k) { + const uint32_t d = s.curr_buckets[k]; + const size_t slot = d - my_lo; + if (dst_present[slot]) { + s.overflow_slots[s.overflow_len] = static_cast(slot); + s.overflow_pts[s.overflow_len] = s.curr_pts[k]; + ++s.overflow_len; + } else { + dst_dense[slot] = s.curr_pts[k]; + dst_present[slot] = 1; } - pos = end; } - merge_overflow(s, dst_dense); + pos = end; } + merge_overflow(s, dst_dense); }; // Stage 6b (cross-thread bucket reduction): each rebalanced task `tprime` owns a @@ -3207,7 +3206,31 @@ typename Curve::Element pippenger_round_parallel(PolynomialSpan 1 && windows_in_batch > 1) { + // A fixed slice owner can remain busy while peers finish all their windows. + // Claim independent window/slice jobs dynamically, using the same scratch budget. + // Window-major order starts every window with all of its slices available. + std::atomic next_job{ 0 }; + const size_t num_jobs = num_threads * windows_in_batch; + round_parallel_detail::msm_parallel_for(num_threads, [&](size_t worker_id) { + while (true) { + const size_t job = next_job.fetch_add(1, std::memory_order_relaxed); + if (job >= num_jobs) { + break; + } + bucket_partials_job(job % num_threads, job / num_threads, worker_id); + } + }); + } else +#endif + { + round_parallel_detail::msm_parallel_for(num_threads, [&](size_t tid) { + for (size_t w = 0; w < windows_in_batch; ++w) { + bucket_partials_job(tid, w, tid); + } + }); + } } { BB_BENCH_NAME("MSM_fast::Stage6b_reduce_cross_thread"); diff --git a/barretenberg/cpp/src/barretenberg/flavor/prover_polynomials.hpp b/barretenberg/cpp/src/barretenberg/flavor/prover_polynomials.hpp index 2301abe..c890fcb 100644 --- a/barretenberg/cpp/src/barretenberg/flavor/prover_polynomials.hpp +++ b/barretenberg/cpp/src/barretenberg/flavor/prover_polynomials.hpp @@ -8,6 +8,9 @@ #include "barretenberg/common/zip_view.hpp" #include "barretenberg/polynomials/polynomial.hpp" +#include +#include + namespace bb { /** @@ -30,7 +33,7 @@ class ProverPolynomialsBase : public AllEntitiesBase { ProverPolynomialsBase(const ProverPolynomialsBase& o) = delete; ProverPolynomialsBase(ProverPolynomialsBase&& o) noexcept = default; ProverPolynomialsBase& operator=(ProverPolynomialsBase&& o) noexcept = default; - ~ProverPolynomialsBase() = default; + ~ProverPolynomialsBase() { release_pages_of(static_cast(*this).get_all()); } [[nodiscard]] size_t get_polynomial_size() const { return this->q_c().virtual_size(); } [[nodiscard]] AllValuesType get_row(size_t row_idx) const { @@ -80,6 +83,19 @@ class ProverPolynomialsBase : public AllEntitiesBase { polynomial.increase_virtual_size(size_in); } } + + private: + // The shifted polynomials share memory with their unshifted ones; both die here, so such a block still counts as + // held only by this object. + template static void release_pages_of(std::span all) noexcept + { + static_assert(N != std::dynamic_extent); + std::array polys{}; + for (size_t i = 0; i < N; ++i) { + polys[i] = &all[i]; + } + Polynomial::release_pages_before_destruction(polys); + } }; } // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp b/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp index 42f6fa9..8988f40 100644 --- a/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp +++ b/barretenberg/cpp/src/barretenberg/honk/composer/permutation_lib.hpp @@ -16,6 +16,7 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/bb_bench.hpp" #include "barretenberg/common/ref_span.hpp" +#include "barretenberg/common/scratch_array.hpp" #include "barretenberg/common/thread.hpp" #include "barretenberg/flavor/flavor.hpp" #include "barretenberg/polynomials/polynomial.hpp" @@ -47,10 +48,10 @@ using CyclicPermutation = std::vector; * thousands per circuit). */ struct CopyCycles { - std::vector offsets; // size = num_cycles + 1 - std::vector nodes; + ScratchArray offsets; // size = num_cycles + 1 + ScratchArray nodes; - size_t size() const { return offsets.empty() ? 0 : offsets.size() - 1; } + size_t size() const { return offsets.size() == 0 ? 0 : offsets.size() - 1; } std::span operator[](size_t i) const { return { nodes.data() + offsets[i], offsets[i + 1] - offsets[i] }; 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 e86fe25..6effa23 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 @@ -11,6 +11,7 @@ #include "barretenberg/common/mem.hpp" #include "barretenberg/common/ref_array.hpp" #include "barretenberg/common/ref_vector.hpp" +#include "barretenberg/common/release_pages.hpp" #include "barretenberg/common/serialize.hpp" #include "barretenberg/common/throw_or_abort.hpp" #include @@ -201,9 +202,36 @@ template class TileChunks { void reserve(size_t num_tiles) { chunks_.reserve((num_tiles + CHUNK_MASK) >> CHUNK_SHIFT); } + /** + * @brief Grows the store to `num_tiles` tiles, allocating chunks as `emplace_back` would. Chunks are + * zero-initialized when allocated, so the new tiles read as empty until the caller writes them. + */ + void grow_for_overwrite(size_t num_tiles) + { + while (capacity() < num_tiles) { + chunks_.push_back(std::make_unique()); + } + size_ = std::max(size_, num_tiles); + } + size_t size() const { return size_; } size_t capacity() const { return chunks_.size() * CHUNK_TILES; } + /** + * @brief Adds every chunk to `blocks` (a PageBlockList or BatchedPageRelease), so the pages of the tiles can be + * released just before the store is freed. + * @details Chunks under the release floor are skipped by `blocks.add`. + */ + template void add_chunks_to(Blocks& blocks) const noexcept + { + // Tiles fill the chunks in order, so the tiles in use in a chunk are a prefix of it. + for (size_t c = 0; c < chunks_.size(); ++c) { + const size_t first_tile = c * CHUNK_TILES; + const size_t used_tiles = std::min(size_ - std::min(size_, first_tile), CHUNK_TILES); + blocks.add(chunks_[c].get(), sizeof(Chunk), sizeof(Tile) * used_tiles); + } + } + void clear() { chunks_.clear(); @@ -752,6 +780,98 @@ template class ExecutionTraceBlockStorage { */ void reserve(size_t num_rows) { tiles.reserve((num_rows + GATE_TILE_SIZE - 1) >> GATE_TILE_SHIFT); } + /** + * @brief Adds `count` rows, to be filled by copy_translated_rows before the block is read, and returns the index of + * the first. + */ + size_t grow_rows_for_overwrite(size_t count) + { + const size_t first = num_rows_; + const size_t end = first + count; + const size_t num_tiles = (end + GATE_TILE_SIZE - 1) >> GATE_TILE_SHIFT; + if (num_tiles > tiles.size()) { + // New tiles are zero, so slots past the last row read as zero, as they do after appends. + tiles.grow_for_overwrite(num_tiles); + } + for (size_t i = 0; i < count; ++i) { +#ifdef CHECK_CIRCUIT_STACKTRACES + this->stack_traces.populate(); +#endif + this->tracy_gate(); + } + num_rows_ = end; + return first; + } + + /** @brief Per value table (the non-gate selectors', then the gate values'): this block's id of each source id. */ + using ValueIdMaps = std::array, NUM_NON_GATE_SELECTORS + 1>; + + /** + * @brief Interns every value of `source`'s value tables here and returns the id translation copy_translated_rows + * needs. Not thread-safe (it may add values to this block's tables): call it before any concurrent copy. + */ + ValueIdMaps intern_values_of(const ExecutionTraceBlockStorage& source) + { + ValueIdMaps maps; + for (size_t t = 0; t < maps.size(); ++t) { + const Table& from = source.value_tables_[t]; + maps[t].resize(from.size()); + for (uint32_t id = 0; id < from.size(); ++id) { + maps[t][id] = value_tables_[t].intern(from[id]); + } + } + return maps; + } + + /** + * @brief Fills rows [row, row + count), added by grow_rows_for_overwrite, with rows [source_row, source_row + + * count) of `source`, every wire w replaced by wire_map[w] and every selector value id translated by `value_ids` + * (from intern_values_of(source)), so each row holds the same selector values as in `source`. + * @details `source` must own the same gate kinds, so that every copied gate kind is owned here. Calls on disjoint + * row ranges may run concurrently. + */ + void copy_translated_rows(const ExecutionTraceBlockStorage& source, + const size_t source_row, + const size_t row, + const size_t count, + const uint32_t* wire_map, + const ValueIdMaps& value_ids) + { + BB_ASSERT(owns_same_gate_kinds(source), "copy_translated_rows: source owns other gate kinds"); + BB_ASSERT_LTE(source_row + count, source.num_rows_); + BB_ASSERT_LTE(row + count, num_rows_); + size_t i = 0; + while (i < count) { + const size_t from_row = source_row + i; + const size_t to_row = row + i; + const size_t from_slot = from_row & GATE_TILE_MASK; + const size_t to_slot = to_row & GATE_TILE_MASK; + // The longest run of rows that stays inside one tile on both sides. + const size_t len = std::min({ count - i, GATE_TILE_SIZE - from_slot, GATE_TILE_SIZE - to_slot }); + const Tile& from = source.tiles[from_row >> GATE_TILE_SHIFT]; + Tile& to = tiles[to_row >> GATE_TILE_SHIFT]; + for (size_t w = 0; w < NUM_WIRES; ++w) { + const uint32_t* from_wires = from.wires[w].data() + from_slot; + uint32_t* to_wires = to.wires[w].data() + to_slot; + for (size_t k = 0; k < len; ++k) { + to_wires[k] = wire_map[from_wires[k]]; + } + } + for (size_t c = 0; c < NUM_NON_GATE_SELECTORS; ++c) { + const auto field = NON_GATE_SELECTORS[c].tile_field; + const std::vector& ids = value_ids[c]; + for (size_t k = 0; k < len; ++k) { + (to.*field)[to_slot + k] = ids[(from.*field)[from_slot + k]]; + } + } + for (size_t k = 0; k < len; ++k) { + to.gate_value[to_slot + k] = value_ids.back()[from.gate_value[from_slot + k]]; + } + std::copy_n(from.gate_kind.data() + from_slot, len, to.gate_kind.data() + to_slot); + i += len; + } + } + /** * @brief Reference to this block's selector view for `kind`; aborts if the block does not own it. * For cross-block reads, use `read_gate_selector` instead. @@ -822,9 +942,11 @@ template class ExecutionTraceBlockStorage { // Accessor indices follow NON_GATE_SELECTORS table order. SelectorColumn& q_m() { return columns_[0]; }; SelectorColumn& q_c() { return columns_[1]; }; + const SelectorColumn& q_c() const { return columns_[1]; }; SelectorColumn& q_1() { return columns_[2]; }; SelectorColumn& q_2() { return columns_[3]; }; SelectorColumn& q_3() { return columns_[4]; }; + const SelectorColumn& q_3() const { return columns_[4]; }; SelectorColumn& q_4() { return columns_[5]; }; SelectorColumn& q_5() { return columns_[6]; }; @@ -864,6 +986,12 @@ template class ExecutionTraceBlockStorage { } } + bool owns_same_gate_kinds(const ExecutionTraceBlockStorage& other) const + { + return std::ranges::equal( + gate_columns_, other.gate_columns_, [](const auto& a, const auto& b) { return a.kind() == b.kind(); }); + } + Tile& tile_for_append() { if ((num_rows_ & GATE_TILE_MASK) == 0 && (num_rows_ >> GATE_TILE_SHIFT) == tiles.size()) { diff --git a/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.hpp b/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.hpp index ae297e3..ed1d73a 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.hpp +++ b/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.hpp @@ -8,6 +8,7 @@ #include "barretenberg/common/assert.hpp" #include "barretenberg/common/throw_or_abort.hpp" #include +#include #include #include #include @@ -40,6 +41,32 @@ inline std::vector slice_input(const uint256_t& input, const uint64_t return slices; } +/** + * @brief Return `target % base` and replace `target` with `target / base`. + * @details Computes quotient and remainder together: a mask and a shift for a power-of-two base, one native division + * while `target` fits in 64 bits, and one single-limb long division otherwise (which rejects a zero base). + */ +inline uint64_t divmod_in_place(uint256_t& target, const uint64_t base) +{ + if (std::has_single_bit(base)) { + const uint64_t remainder = target.data[0] & (base - 1); + target >>= static_cast(std::countr_zero(base)); + return remainder; + } + if (base != 0 && (target.data[1] | target.data[2] | target.data[3]) == 0) { + const uint64_t value = target.data[0]; + if (value < base) { + target.data[0] = 0; + return value; + } + target.data[0] = value / base; + return value % base; + } + const auto [quotient, remainder] = target.divmod(base); + target = quotient; + return remainder; +} + /** * @brief Decompose a uint256_t using a different base for each digit position (least-significant first). * Throws if the input is too large to be fully represented by the given bases. @@ -55,8 +82,7 @@ inline std::vector slice_input_using_variable_bases(const uint256_t& i if (target >= bases[i] && i == bases.size() - 1) { throw_or_abort(format("Last key slice greater than ", bases[i])); } - slices.push_back((target % bases[i]).data[0]); - target /= bases[i]; + slices.push_back(divmod_in_place(target, bases[i])); } return slices; } @@ -82,14 +108,11 @@ template constexpr std::array constexpr uint256_t map_into_sparse_form(const uint64_t input) { uint256_t out = 0UL; - auto converted = input; constexpr auto base_powers = get_base_powers(); - for (size_t i = 0; i < 32; ++i) { - uint64_t sparse_bit = ((converted >> i) & 1U); - if (sparse_bit) { - out += base_powers[i]; - } + // Visit only the set bits among the low 32, in increasing order. + for (uint64_t remaining = input & 0xffffffffULL; remaining != 0; remaining &= remaining - 1) { + out += base_powers[static_cast(std::countr_zero(remaining))]; } return out; } diff --git a/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.test.cpp b/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.test.cpp new file mode 100644 index 0000000..5e408c5 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/numeric/bitop/sparse_form.test.cpp @@ -0,0 +1,51 @@ +#include "sparse_form.hpp" +#include +#include +#include + +using namespace bb; +using numeric::uint256_t; + +namespace { + +// Tests every one of the low 32 bit positions in turn. +template uint256_t reference_sparse_form(const uint64_t input) +{ + const auto base_powers = numeric::get_base_powers(); + uint256_t out = 0; + for (size_t i = 0; i < 32; ++i) { + if (((input >> i) & 1U) != 0) { + out += base_powers[i]; + } + } + return out; +} + +template void check_sparse_form() +{ + // A local generator: tests in this program rely on the state of the shared debug engine. + std::mt19937_64 engine(base); + // Bits above the low 32 must be ignored. + std::vector inputs{ 0, 1, 0xffffffffULL, ~uint64_t(0), uint64_t(1) << 32 }; + for (size_t i = 0; i < 32; ++i) { + inputs.push_back(uint64_t(1) << i); + } + for (size_t i = 0; i < 64; ++i) { + inputs.push_back(engine()); + } + for (const uint64_t input : inputs) { + EXPECT_EQ(numeric::map_into_sparse_form(input), reference_sparse_form(input)); + } +} + +} // namespace + +TEST(SparseForm, MapIntoSparseFormMatchesBitwiseReference) +{ + static_assert(numeric::map_into_sparse_form<16>(0b101) == uint256_t(16 * 16 + 1)); + check_sparse_form<3>(); + check_sparse_form<9>(); + check_sparse_form<11>(); + check_sparse_form<16>(); + check_sparse_form<28>(); +} diff --git a/barretenberg/cpp/src/barretenberg/numeric/random/engine.cpp b/barretenberg/cpp/src/barretenberg/numeric/random/engine.cpp index 014919a..db0e564 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/random/engine.cpp +++ b/barretenberg/cpp/src/barretenberg/numeric/random/engine.cpp @@ -7,12 +7,14 @@ #include "engine.hpp" #include "barretenberg/common/assert.hpp" #include "barretenberg/common/throw_or_abort.hpp" +#include "entropy_buffer_observer.hpp" #include #include #include #include #include #include +#include #if defined(__APPLE__) #include #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR @@ -60,8 +62,12 @@ struct RandomBufferWrapper { std::unique_ptr buffer; // Offset into the unused part of the buffer ssize_t offset = -1; + // Identity of the current fill as reported to an observer; 0 when the fill was made with none installed + uint64_t fill_id = 0; }; thread_local RandomBufferWrapper random_buffer_wrapper; +std::atomic entropy_buffer_observer{ nullptr }; +std::atomic entropy_buffer_fill_count{ 0 }; /** * @brief Generate an array of random unsigned ints sampled from a CSPRNG * @@ -74,6 +80,7 @@ template std::array random_data; constexpr size_t random_data_buffer_size = sizeof(random_data); + EntropyBufferObserver* const observer = entropy_buffer_observer.load(std::memory_order_acquire); // if the buffer is not initialized or doesn't contain enough bytes, sample randomness // We could preserve the leftover bytes, but it's a bit messy @@ -96,13 +103,28 @@ template std::array std::arrayon_fill(random_buffer_wrapper.fill_id, RANDOM_BUFFER_SIZE); + } } + if (BB_UNLIKELY(observer != nullptr)) { + observer->on_consume( + random_buffer_wrapper.fill_id, static_cast(random_buffer_wrapper.offset), random_data_buffer_size); + } memcpy(&random_data, random_buffer_wrapper.buffer.get() + random_buffer_wrapper.offset, random_data_buffer_size); random_buffer_wrapper.offset += static_cast(random_data_buffer_size); return random_data; } + +class SubstituteStream; +// The substitute stream installed on this thread by a DebugEngine, if any. +thread_local SubstituteStream* active_substitute = nullptr; + +/** + * @brief A private copy of a DebugEngine's generator that the engine reads, on the thread that created it, in place of + * its own generator. + */ +class SubstituteStream final : public RNG::DrawScope { + public: + SubstituteStream(const RNG* issuer, const std::mt19937_64& start) + : owner(issuer) + , generator(start) + { + if (active_substitute != nullptr) { + throw_or_abort("RNG::draw_from: a draw scope is already active on this thread"); + } + active_substitute = this; + } + SubstituteStream(const SubstituteStream&) = delete; + SubstituteStream(SubstituteStream&&) = delete; + SubstituteStream& operator=(const SubstituteStream&) = delete; + SubstituteStream& operator=(SubstituteStream&&) = delete; + ~SubstituteStream() override + { + // Destroying a scope on another thread would leave the creating thread reading freed memory. + BB_ASSERT(active_substitute == this, "RNG::DrawScope destroyed on a thread other than the one that created it"); + active_substitute = nullptr; + } + + [[nodiscard]] RNG::Position reached() const override { return { owner, generator }; } + + const RNG* const owner; + std::mt19937_64 generator; + std::uniform_int_distribution dist{ 0ULL, UINT64_MAX }; +}; } // namespace +EntropyBufferObserver* set_entropy_buffer_observer(EntropyBufferObserver* observer) +{ + return entropy_buffer_observer.exchange(observer, std::memory_order_acq_rel); +} + class RandomEngine : public RNG { public: uint8_t get_random_uint8() override @@ -209,28 +282,87 @@ class DebugEngine : public RNG { : engine(std::mt19937_64(seed)) {} - uint8_t get_random_uint8() override { return static_cast(dist(engine)); } + Position position() const override + { + reject_inside_own_scope("position"); + return { this, engine }; + } + + Position after(const Position& start, const std::function& draws) override + { + auto scope = draw_from(start); + draws(*this); + return scope->reached(); + } + + std::unique_ptr draw_from(const Position& start) override + { + reject_foreign("draw_from", start); + return std::make_unique(this, *start.state); + } + + bool at(const Position& where) const override + { + reject_inside_own_scope("at"); + return where.issuer == this && where.state.has_value() && *where.state == engine; + } + + void adopt(const Position& where) override + { + reject_inside_own_scope("adopt"); + reject_foreign("adopt", where); + engine = *where.state; + } + + private: + // Reads the calling thread's substitute stream when it has one for this engine, so no draw can bypass a scope. + uint64_t draw() + { + SubstituteStream* const substitute = active_substitute; + if (BB_UNLIKELY(substitute != nullptr && substitute->owner == this)) { + return substitute->dist(substitute->generator); + } + return dist(engine); + } + + // Inside its own scope a thread must not touch the shared generator, which another thread may be advancing. + void reject_inside_own_scope(const char* operation) const + { + if (active_substitute != nullptr && active_substitute->owner == this) { + throw_or_abort(std::string("RNG::") + operation + ": called inside a draw scope of this engine"); + } + } + + void reject_foreign(const char* operation, const Position& where) const + { + if (where.empty() || where.issuer != this) { + throw_or_abort(std::string("RNG::") + operation + ": position is empty or issued by another engine"); + } + } + + public: + uint8_t get_random_uint8() override { return static_cast(draw()); } - uint16_t get_random_uint16() override { return static_cast(dist(engine)); } + uint16_t get_random_uint16() override { return static_cast(draw()); } - uint32_t get_random_uint32() override { return static_cast(dist(engine)); } + uint32_t get_random_uint32() override { return static_cast(draw()); } - uint64_t get_random_uint64() override { return dist(engine); } + uint64_t get_random_uint64() override { return draw(); } uint128_t get_random_uint128() override { - uint128_t hi = dist(engine); - uint128_t lo = dist(engine); + uint128_t hi = draw(); + uint128_t lo = draw(); return (hi << 64) | lo; } uint256_t get_random_uint256() override { // Do not inline in constructor call. Evaluation order is important for cross-compiler consistency. - auto a = dist(engine); - auto b = dist(engine); - auto c = dist(engine); - auto d = dist(engine); + auto a = draw(); + auto b = draw(); + auto c = draw(); + auto d = draw(); return { a, b, c, d }; } diff --git a/barretenberg/cpp/src/barretenberg/numeric/random/engine.hpp b/barretenberg/cpp/src/barretenberg/numeric/random/engine.hpp index 2ef64d5..57dd290 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/random/engine.hpp +++ b/barretenberg/cpp/src/barretenberg/numeric/random/engine.hpp @@ -10,12 +10,85 @@ #include "../uintx/uintx.hpp" #include "unistd.h" #include +#include +#include +#include #include namespace bb::numeric { class RNG { public: + /** + * @brief Where an engine's stream of draws stands. + * @details Empty for an engine whose draws have no order to name. A non-empty position is meaningful only to the + * engine object that issued it. + */ + struct Position { + const RNG* issuer = nullptr; + std::optional state; + + [[nodiscard]] bool empty() const { return !state.has_value(); } + bool operator==(const Position& other) const = default; + }; + + /** + * @brief The calling thread's substitute stream, installed by draw_from() for as long as this object lives. + * @details Must be destroyed on the thread that created it. + */ + class DrawScope { + public: + DrawScope() = default; + virtual ~DrawScope() = default; + DrawScope(const DrawScope&) = delete; + DrawScope(DrawScope&&) = delete; + DrawScope& operator=(const DrawScope&) = delete; + DrawScope& operator=(DrawScope&&) = delete; + + /** + * @brief Where the substitute stream stands now; empty when the engine installed none. + */ + [[nodiscard]] virtual Position reached() const { return {}; } + }; + + /** + * @brief Where the stream stands now; empty for an engine without an order. + */ + [[nodiscard]] virtual Position position() const { return {}; } + + /** + * @brief Where the stream would stand after `draws` ran from `start`, leaving this engine where it is. + * @details `draws` may draw through its argument or through any reference to this engine; the values are + * discarded. An engine without an order returns an empty position without calling `draws`. + */ + [[nodiscard]] virtual Position after([[maybe_unused]] const Position& start, + [[maybe_unused]] const std::function& draws) + { + return {}; + } + + /** + * @brief Make every draw the calling thread makes through this engine read a private stream started at `start`, + * for as long as the returned scope lives. + * @details References to this engine taken earlier are covered, and the engine's own stream is never read in the + * meantime. One scope per thread at a time. An engine without an order installs nothing: the thread draws as it + * always does. + */ + [[nodiscard]] virtual std::unique_ptr draw_from([[maybe_unused]] const Position& start) + { + return std::make_unique(); + } + + /** + * @brief Whether the stream stands exactly at `where`; always true for an engine without an order. + */ + [[nodiscard]] virtual bool at([[maybe_unused]] const Position& where) const { return true; } + + /** + * @brief Move the stream to `where`; does nothing for an engine without an order. + */ + virtual void adopt([[maybe_unused]] const Position& where) {} + virtual uint8_t get_random_uint8() = 0; virtual uint16_t get_random_uint16() = 0; diff --git a/barretenberg/cpp/src/barretenberg/numeric/random/engine_position.test.cpp b/barretenberg/cpp/src/barretenberg/numeric/random/engine_position.test.cpp new file mode 100644 index 0000000..393b0a0 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/numeric/random/engine_position.test.cpp @@ -0,0 +1,304 @@ +#include "barretenberg/common/assert.hpp" +#include "barretenberg/ecc/curves/bn254/g1.hpp" +#include "engine.hpp" +#include "entropy_buffer_observer.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace bb; +using numeric::RNG; + +namespace { + +constexpr std::uint_fast64_t SEED = 0x5eed; + +// Draws of every width, recorded as 64-bit words so two runs can be compared. +std::vector mixed_draws(RNG& engine, size_t rounds) +{ + std::vector out; + for (size_t i = 0; i < rounds; i++) { + out.push_back(engine.get_random_uint8()); + out.push_back(engine.get_random_uint16()); + out.push_back(engine.get_random_uint32()); + out.push_back(engine.get_random_uint64()); + const uint128_t wide = engine.get_random_uint128(); + out.push_back(static_cast(wide)); + out.push_back(static_cast(wide >> 64)); + const uint256_t widest = engine.get_random_uint256(); + out.insert(out.end(), widest.data, widest.data + 4); + } + return out; +} + +std::vector group_draws(RNG& engine, size_t count) +{ + std::vector out; + for (size_t i = 0; i < count; i++) { + out.push_back(g1::element::random_element(&engine)); + } + return out; +} + +} // namespace + +TEST(EnginePosition, DebugEngineScopeOnAnotherThreadMatchesSerialStream) +{ + constexpr size_t ROUNDS = 200; + auto& engine = numeric::get_debug_randomness(true, SEED); + const std::vector serial = mixed_draws(engine, ROUNDS); + const uint64_t serial_next = engine.get_random_uint64(); + + numeric::get_debug_randomness(true, SEED); + const RNG::Position start = engine.position(); + ASSERT_FALSE(start.empty()); + + std::vector on_thread; + std::vector through_accessor; + RNG::Position reached; + std::thread([&] { + RNG& captured = numeric::get_debug_randomness(); + auto scope = engine.draw_from(start); + on_thread = mixed_draws(captured, ROUNDS / 2); + through_accessor = mixed_draws(numeric::get_debug_randomness(), ROUNDS - (ROUNDS / 2)); + reached = scope->reached(); + }).join(); + on_thread.insert(on_thread.end(), through_accessor.begin(), through_accessor.end()); + + EXPECT_EQ(on_thread, serial); + EXPECT_TRUE(engine.at(start)); + EXPECT_FALSE(engine.at(reached)); + + std::vector looked_ahead; + EXPECT_EQ(engine.after(start, [&](RNG& r) { looked_ahead = mixed_draws(r, ROUNDS); }), reached); + EXPECT_EQ(looked_ahead, serial); + EXPECT_TRUE(engine.at(start)); + + engine.adopt(reached); + EXPECT_TRUE(engine.at(reached)); + EXPECT_EQ(engine.get_random_uint64(), serial_next); +} + +TEST(EnginePosition, DebugEngineScopeIsPerThread) +{ + constexpr size_t ROUNDS = 50; + auto& engine = numeric::get_debug_randomness(true, SEED); + const std::vector serial = mixed_draws(engine, 2 * ROUNDS); + + numeric::get_debug_randomness(true, SEED); + const RNG::Position start = engine.position(); + std::mutex mutex; + std::condition_variable cv; + int stage = 0; + std::vector on_thread; + std::thread worker([&] { + auto scope = engine.draw_from(start); + on_thread = mixed_draws(engine, ROUNDS); + std::unique_lock lock(mutex); + stage = 1; + cv.notify_all(); + cv.wait(lock, [&] { return stage == 2; }); + const auto rest = mixed_draws(engine, ROUNDS); + on_thread.insert(on_thread.end(), rest.begin(), rest.end()); + }); + std::vector on_main; + { + std::unique_lock lock(mutex); + cv.wait(lock, [&] { return stage == 1; }); + // The worker's scope stays installed while the main thread draws from the shared stream. + on_main = mixed_draws(engine, ROUNDS); + stage = 2; + cv.notify_all(); + } + worker.join(); + + EXPECT_EQ(on_thread, serial); + EXPECT_EQ(on_main, + std::vector(serial.begin(), serial.begin() + static_cast(on_main.size()))); +} + +TEST(EnginePosition, DebugEngineGroupElementsLandOnTheSameEndPosition) +{ + constexpr size_t COUNT = 16; + auto& engine = numeric::get_debug_randomness(true, SEED); + const RNG::Position start = engine.position(); + + std::vector on_thread; + RNG::Position reached; + std::thread([&] { + auto scope = engine.draw_from(start); + on_thread = group_draws(engine, COUNT); + reached = scope->reached(); + }).join(); + + std::vector looked_ahead; + EXPECT_EQ(engine.after(start, [&](RNG& r) { looked_ahead = group_draws(r, COUNT); }), reached); + EXPECT_TRUE(engine.at(start)); + + const std::vector serial = group_draws(engine, COUNT); + EXPECT_TRUE(engine.at(reached)); + for (size_t i = 0; i < COUNT; i++) { + EXPECT_TRUE(on_thread[i] == serial[i]); + EXPECT_TRUE(looked_ahead[i] == serial[i]); + } +} + +TEST(EnginePosition, DebugEngineRejectsMisuse) +{ + auto& engine = numeric::get_debug_randomness(true, SEED); + const RNG::Position empty; + EXPECT_FALSE(engine.at(empty)); + EXPECT_THROW_WITH_MESSAGE(engine.adopt(empty), "position is empty"); + EXPECT_THROW_WITH_MESSAGE((void)engine.draw_from(empty), "position is empty"); + + const RNG::Position start = engine.position(); + auto scope = engine.draw_from(start); + EXPECT_THROW_WITH_MESSAGE((void)engine.draw_from(start), "already active on this thread"); + EXPECT_THROW_WITH_MESSAGE((void)engine.at(start), "inside a draw scope"); +} + +TEST(EnginePosition, DefaultEngineHasNoOrder) +{ + auto& engine = numeric::get_randomness(); + if (!engine.position().empty()) { + GTEST_SKIP() << "get_randomness() returns an ordered engine in this build"; + } + const RNG::Position start = engine.position(); + EXPECT_TRUE(engine.at(start)); + bool called = false; + EXPECT_TRUE(engine.after(start, [&](RNG&) { called = true; }).empty()); + EXPECT_FALSE(called); + { + auto scope = engine.draw_from(start); + EXPECT_NE(engine.get_random_uint256(), engine.get_random_uint256()); + EXPECT_TRUE(scope->reached().empty()); + } + engine.adopt(start); + EXPECT_TRUE(engine.at(start)); + EXPECT_TRUE(engine.position().empty()); +} + +namespace { + +// Records which thread made each fill and the byte ranges each thread consumed, merging contiguous consumption. +class RecordingObserver final : public numeric::EntropyBufferObserver { + public: + struct Consumed { + std::thread::id consumer; + size_t begin; + size_t end; + }; + struct Fill { + std::thread::id filler; + size_t size = 0; + std::vector consumed; + }; + + void on_fill(uint64_t fill, size_t size) override + { + std::lock_guard lock(mutex); + if (!fills.emplace(fill, Fill{ std::this_thread::get_id(), size, {} }).second) { + duplicate_fill_ids++; + } + } + + void on_consume(uint64_t fill, size_t offset, size_t length) override + { + std::lock_guard lock(mutex); + const auto it = fills.find(fill); + if (it == fills.end()) { + unrecorded_fill_consumers.insert(std::this_thread::get_id()); + return; + } + auto& consumed = it->second.consumed; + if (!consumed.empty() && consumed.back().consumer == std::this_thread::get_id() && + consumed.back().end == offset) { + consumed.back().end += length; + } else { + consumed.push_back({ std::this_thread::get_id(), offset, offset + length }); + } + } + + std::mutex mutex; + std::map fills; + std::set unrecorded_fill_consumers; + size_t duplicate_fill_ids = 0; +}; + +} // namespace + +TEST(EnginePosition, DefaultEngineThreadsConsumeOnlyTheirOwnFills) +{ + auto& engine = numeric::get_randomness(); + if (!engine.position().empty()) { + GTEST_SKIP() << "get_randomness() returns an ordered engine in this build"; + } + // A 256-bit draw consumes 32 bytes; about 2.5 MiB per thread makes every thread refill its buffer at least twice. + constexpr size_t BYTES_PER_DRAW = 32; + constexpr size_t DRAWS_PER_THREAD = (5UL << 20) / 2 / BYTES_PER_DRAW; + constexpr size_t ROUNDS = 3; + constexpr size_t THREADS_PER_ROUND = 2; + + RecordingObserver observer; + ASSERT_EQ(numeric::set_entropy_buffer_observer(&observer), nullptr); + std::mutex ids_mutex; + std::set workers; + for (size_t round = 0; round < ROUNDS; round++) { + std::vector threads; + for (size_t t = 0; t < THREADS_PER_ROUND; t++) { + // Half of the threads draw inside a scope, which must change nothing for this engine. + const bool scoped = (t % 2) == 0; + threads.emplace_back([&engine, &ids_mutex, &workers, scoped] { + { + std::lock_guard lock(ids_mutex); + workers.insert(std::this_thread::get_id()); + } + std::unique_ptr scope; + if (scoped) { + scope = engine.draw_from(engine.position()); + } + for (size_t i = 0; i < DRAWS_PER_THREAD; i++) { + static_cast(engine.get_random_uint256()); + } + }); + } + for (auto& thread : threads) { + thread.join(); + } + } + numeric::set_entropy_buffer_observer(nullptr); + + EXPECT_EQ(observer.duplicate_fill_ids, 0U); + for (const auto& worker : workers) { + EXPECT_EQ(observer.unrecorded_fill_consumers.count(worker), 0U); + } + std::map fills_per_worker; + size_t consumed_bytes = 0; + for (auto& [id, fill] : observer.fills) { + if (workers.contains(fill.filler)) { + fills_per_worker[fill.filler]++; + } + auto ranges = fill.consumed; + std::sort(ranges.begin(), ranges.end(), [](const auto& a, const auto& b) { return a.begin < b.begin; }); + for (size_t i = 0; i < ranges.size(); i++) { + EXPECT_EQ(ranges[i].consumer, fill.filler) << "fill " << id << " read by a thread that did not fill it"; + EXPECT_LE(ranges[i].end, fill.size); + if (i + 1 < ranges.size()) { + EXPECT_LE(ranges[i].end, ranges[i + 1].begin) << "fill " << id << " has overlapping reads"; + } + if (workers.contains(ranges[i].consumer)) { + consumed_bytes += ranges[i].end - ranges[i].begin; + } + } + } + EXPECT_EQ(fills_per_worker.size(), workers.size()); + for (const auto& [worker, count] : fills_per_worker) { + EXPECT_GE(count, 2U); + } + EXPECT_EQ(consumed_bytes, ROUNDS * THREADS_PER_ROUND * DRAWS_PER_THREAD * BYTES_PER_DRAW); +} diff --git a/barretenberg/cpp/src/barretenberg/numeric/random/entropy_buffer_observer.hpp b/barretenberg/cpp/src/barretenberg/numeric/random/entropy_buffer_observer.hpp new file mode 100644 index 0000000..9cd63b7 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/numeric/random/entropy_buffer_observer.hpp @@ -0,0 +1,43 @@ +#pragma once +#include +#include + +namespace bb::numeric { + +/** + * @brief Sees each refill of the default engine's per-thread entropy buffer and each byte range a draw consumes from + * it, for tests. + * @details Every callback runs on the thread that made the read or the draw, concurrently with other threads, so an + * implementation must be thread-safe. + */ +class EntropyBufferObserver { + public: + EntropyBufferObserver() = default; + virtual ~EntropyBufferObserver() = default; + EntropyBufferObserver(const EntropyBufferObserver&) = delete; + EntropyBufferObserver(EntropyBufferObserver&&) = delete; + EntropyBufferObserver& operator=(const EntropyBufferObserver&) = delete; + EntropyBufferObserver& operator=(EntropyBufferObserver&&) = delete; + + /** + * @brief The calling thread refilled its buffer from the operating-system source. + * @param fill Identifies this fill of this buffer; unique in the process and never 0. + * @param size Number of bytes the fill holds. + */ + virtual void on_fill(uint64_t fill, size_t size) = 0; + + /** + * @brief The calling thread consumed bytes [offset, offset + length) of `fill`. + * @details `fill` is 0 when the buffer was filled while no observer was installed. + */ + virtual void on_consume(uint64_t fill, size_t offset, size_t length) = 0; +}; + +/** + * @brief Install `observer` for the default engine (nullptr removes it) and return the observer it replaces. + * @details The observer must outlive every draw made while it is installed. With none installed, a draw pays one + * predictable branch. + */ +EntropyBufferObserver* set_entropy_buffer_observer(EntropyBufferObserver* observer); + +} // namespace bb::numeric diff --git a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp index 7fd207c..f53da69 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp +++ b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx.test.cpp @@ -371,6 +371,12 @@ TEST(uintx, Bn254ReciprocalDivisionBoundaries) check(value >> (1024 - 576)); check(value >> (1024 - 544)); check(value >> 512); + check(value >> 516); // Fully exercise the native x < 2^508 path. + check(value >> 520); + const auto narrow_multiple = (value >> 770) * modulus; + check(narrow_multiple - 1); + check(narrow_multiple); + check(narrow_multiple + 1); const auto quotient = value >> 704; const auto multiple = quotient * modulus; 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 88d6915..4cabce8 100644 --- a/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/numeric/uintx/uintx_impl.hpp @@ -254,6 +254,25 @@ template std::pair, uintx> uintx> 252) == uint256_t(0)) { + static const uint256_t reciprocal = + (uintx(1) << 508).divmod_base(uintx(BN254FQMODULUS256)).first.lo.lo; + const auto lower = lo.lo.mul_extended(reciprocal); + const auto upper = lo.hi.mul_extended(reciprocal); + const base_uint middle = base_uint(upper.first, upper.second) + base_uint(lower.second); + uint256_t quotient = (middle >> 252).lo; + const auto product = quotient.mul_extended(BN254FQMODULUS256); + base_uint remainder = lo - base_uint(product.first, product.second); + if (remainder >= base_uint(BN254FQMODULUS256)) { + quotient += 1; + remainder -= base_uint(BN254FQMODULUS256); + } + return { uintx(base_uint(quotient)), uintx(remainder) }; + } +#endif // For x < S = 2^576, mu = floor(S / p) gives an underestimate // q = floor(x * mu / S) of x / p by at most one. Keep the full-width // Barrett path below for larger operands; no caller bounds are assumed. diff --git a/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp b/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp index 38cfd34..c0ec1f8 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/backing_memory.hpp @@ -6,12 +6,16 @@ #pragma once +#include "barretenberg/common/release_pages.hpp" #include "barretenberg/common/throw_or_abort.hpp" #include "unistd.h" +#include +#include #include #include #include #include +#include #include #include #if !defined(__wasm__) && !defined(_WIN32) @@ -145,7 +149,87 @@ template struct BackingMemory { ~BackingMemory() = default; + /** + * @brief Before the listed handles are destroyed together, release the pages of every in-memory block that no + * other handle owns, with one team of threads for all of them (see release_pages_in_parallel). + * @details A block qualifies when its owner count equals the number of distinct listed handles to it, so memory + * shared with an object outside the list is left alone, however often a handle is listed. File-backed memory and + * blocks not allocated by allocate() are never released. The caller guarantees that no other thread can acquire a + * new reference to a listed block during the call; in particular, no weak_ptr to one may exist. The released + * blocks' contents are lost, so this must run immediately before the handles are destroyed. + */ + template + static void release_pages_of_sole_owned(const std::array& handles) noexcept + { + // A handle holds one reference however often it is listed. + std::array unique = handles; + std::sort(unique.begin(), unique.end(), std::less<>{}); + const auto num_unique = static_cast(std::unique(unique.begin(), unique.end()) - unique.begin()); + // A deleter lives in its block's shared control block, so equal deleters mean the same block. + std::array deleters{}; + for (size_t i = 0; i < num_unique; ++i) { + deleters[i] = unique[i]->aligned_deleter(); + } + bb::PageBlockList blocks; + std::array added{}; + size_t num_added = 0; + for (size_t i = 0; i < num_unique; ++i) { + AlignedDeleter* deleter = deleters[i]; + if (deleter == nullptr || deleter->pages_released.load(std::memory_order_relaxed) || + std::find(deleters.data(), deleters.data() + i, deleter) != deleters.data() + i) { + continue; + } + const auto num_listed = std::count(deleters.data() + i, deleters.data() + num_unique, deleter); + if (num_listed == unique[i]->aligned_memory.use_count() && + blocks.add(deleter->allocation, deleter->bytes)) { + added[num_added++] = deleter; + // Dropping a copy acquires the count, so earlier owners' accesses happen before the release. + [[maybe_unused]] const std::shared_ptr copy = unique[i]->aligned_memory; + } + } + if (blocks.release()) { + for (size_t i = 0; i < num_added; ++i) { + added[i]->pages_released.store(true, std::memory_order_relaxed); + } + } + } + private: + // Keeps the block's allocation and size, so that a batch can release the block's pages before its last handle is + // destroyed. An aliasing handle shares this deleter but may point inside the allocation. + struct AlignedDeleter { + Fr* allocation = nullptr; + size_t bytes = 0; + // Relaxed suffices: it only lets the deleter skip a release a batch already made, and orders nothing else. + std::atomic pages_released{ false }; + + AlignedDeleter(Fr* allocated, size_t allocated_bytes) noexcept + : allocation(allocated) + , bytes(allocated_bytes) + {} + // shared_ptr needs a copyable deleter, and std::atomic is not copyable. + AlignedDeleter(const AlignedDeleter& other) noexcept + : allocation(other.allocation) + , bytes(other.bytes) + , pages_released(other.pages_released.load(std::memory_order_relaxed)) + {} + + void operator()(Fr* p) const + { + if (!pages_released.load(std::memory_order_relaxed)) { + // Inside a PolynomialMemoryRelease scope (the AVM prover's), the scope releases the pages of every + // block freed in it with one team of threads, then frees them; otherwise this block's pages go now. + if (bb::PolynomialMemoryRelease::defer_free(p, bytes, [](void* q) { delete[] static_cast(q); })) { + return; + } + bb::release_pages_in_parallel(p, bytes); + } + delete[] p; + } + }; + + AlignedDeleter* aligned_deleter() const { return std::get_deleter(aligned_memory); } + // Use new Fr[] instead of std::make_shared(n) to avoid serial // value-initialization (zeroing). Polynomial's constructor handles // zeroing in parallel where needed. @@ -157,11 +241,7 @@ template struct BackingMemory { return; } Fr* ptr = new Fr[size]; - 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.aligned_memory = std::shared_ptr(ptr, AlignedDeleter{ ptr, size * sizeof(Fr) }); 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 cd7a376..1db7120 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/fold_stride2.hpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace bb { @@ -143,6 +144,28 @@ template std::pair twice_folded_backed_range(const return { src.start_index() / 4, (src.end_index() / 4) + (src.end_index() % 4 != 0 ? 1 : 0) }; } +/** Outputs per work item of `fold_stride4_backed_all`: 2 MiB of bn254 source reads, about a millisecond of work. */ +inline constexpr size_t FOLD_STRIDE4_OUTPUTS_PER_CHUNK = size_t{ 1 } << 14; + +/** + * @brief The outputs k in [k_begin, k_end) of `fold_stride4_backed`, which must lie inside + * `twice_folded_backed_range(src)`; leaves `dst`'s end index alone, so disjoint ranges may run concurrently. + */ +template +void fold_stride4_backed_range(const Polynomial& src, + Polynomial& dst, + size_t k_begin, + size_t k_end, + const Fr& first_challenge, + const Fr& second_challenge) +{ + for (size_t k = k_begin; k < k_end; ++k) { + const Fr even = fold_pair(src[4 * k], src[(4 * k) + 1], first_challenge); + const Fr odd = fold_pair(src[(4 * k) + 2], src[(4 * k) + 3], first_challenge); + dst[ScalarIndex{ k }] = fold_pair(even, odd, second_challenge); + } +} + /** * @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 @@ -160,14 +183,51 @@ void fold_stride4_backed(const Polynomial& 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); - } + fold_stride4_backed_range(src, dst, begin, end, first_challenge, second_challenge); dst.shrink_end_index(end); } +/** + * @brief `fold_stride4_backed(src[j], dst[j], ...)` for every j, scheduled as chunks of at most `outputs_per_chunk` + * outputs so that a few long polynomials do not leave most threads idle. Outputs and end indices are exactly those of + * the per-polynomial calls, whatever the thread count. + * @details `src` and `dst` are indexable ranges of polynomials of equal size (e.g. `get_all()` views); the `dst` + * polynomials must be distinct from each other and from every source. + */ +template +void fold_stride4_backed_all(const Sources& src, + Dests&& dst, + const Fr& first_challenge, + const Fr& second_challenge, + size_t outputs_per_chunk = FOLD_STRIDE4_OUTPUTS_PER_CHUNK) +{ + BB_ASSERT_EQ(src.size(), dst.size()); + BB_ASSERT_GT(outputs_per_chunk, 0UL); + struct Chunk { + size_t poly; + size_t begin; + size_t end; + }; + std::vector chunks; + for (size_t j = 0; j < src.size(); ++j) { + const auto [begin, end] = twice_folded_backed_range(src[j]); + for (size_t k = begin; k < end; k += outputs_per_chunk) { + chunks.push_back({ j, k, std::min(end, k + outputs_per_chunk) }); + } + } + parallel_for(chunks.size(), [&](size_t c) { + const Chunk& chunk = chunks[c]; + fold_stride4_backed_range( + src[chunk.poly], dst[chunk.poly], chunk.begin, chunk.end, first_challenge, second_challenge); + }); + for (size_t j = 0; j < src.size(); ++j) { + const auto [begin, end] = twice_folded_backed_range(src[j]); + if (begin != end) { + dst[j].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. diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp index 4f62bfc..0ed46fe 100644 --- a/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial.hpp @@ -283,6 +283,20 @@ template class Polynomial { */ Polynomial share() const; + /** + * @brief Before the listed polynomials are destroyed together, release the pages of the memory that only they hold, + * with one team of threads (see BackingMemory::release_pages_of_sole_owned). Their contents are lost. + */ + template + static void release_pages_before_destruction(const std::array& polys) noexcept + { + std::array*, N> handles{}; + for (size_t i = 0; i < N; ++i) { + handles[i] = &polys[i]->coefficients_.backing_memory_; + } + BackingMemory::release_pages_of_sole_owned(handles); + } + /** * @brief Check whether or not a polynomial is identically zero * diff --git a/barretenberg/cpp/src/barretenberg/polynomials/polynomial_page_release.test.cpp b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_page_release.test.cpp new file mode 100644 index 0000000..dc4d0ab --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/polynomials/polynomial_page_release.test.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +#include "barretenberg/polynomials/polynomial.hpp" + +// A polynomial listed twice still counts as one owner of its memory, so memory also held outside the list keeps its +// contents while the memory only the list holds is released. +TEST(Polynomial, ReleasePagesLeavesMemoryHeldOutsideTheList) +{ +// Released anonymous pages read back as zeros only on Linux. +#if !defined(__linux__) || defined(NO_MULTITHREADING) + GTEST_SKIP() << "needs Linux and native threads"; +#else + if (slow_low_memory) { + GTEST_SKIP() << "file-backed memory is never released"; + } + using FF = bb::fr; + using Polynomial = bb::Polynomial; + constexpr size_t MIB_ELEMENTS = (size_t{ 1 } << 20) / sizeof(FF); + const FF fill(7); + // `sole` alone reaches the 64 MiB minimum of a release; `held` is at the 32 MiB floor of a block, so it would be + // released too if its owner outside the list were missed. + Polynomial sole(64 * MIB_ELEMENTS, Polynomial::DontZeroMemory::FLAG); + Polynomial held(32 * MIB_ELEMENTS, Polynomial::DontZeroMemory::FLAG); + std::fill(sole.data(), sole.data() + sole.size(), fill); + std::fill(held.data(), held.data() + held.size(), fill); + const Polynomial outside = held.share(); + + Polynomial::release_pages_before_destruction(std::array{ &sole, &held, &held }); + + EXPECT_EQ(sole.get(sole.size() / 2), FF::zero()); + EXPECT_EQ(std::count(outside.data(), outside.data() + outside.size(), fill), + static_cast(outside.size())); +#endif +} diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp index 7d1c410..4a541bd 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_external_relation.hpp @@ -160,6 +160,50 @@ template class Poseidon2ExternalRelationImpl { std::get<3>(evals) += q_pos_by_scaling * (v4 - Accumulator(w_4_shift)); }; +#ifndef __wasm__ + // Native prover batching: transpose the external matrix onto the round's subrelation weights. + struct SubrelationBatchingConstants { + std::array sbox; + std::array shifts; + }; + + static SubrelationBatchingConstants compute_subrelation_batching_constants(const std::array& w) + { + return { { w[0] * FF(5) + w[1] * FF(4) + w[2] + w[3], + w[0] * FF(7) + w[1] * FF(6) + w[2] * FF(3) + w[3], + w[0] + w[1] + w[2] * FF(5) + w[3] * FF(4), + w[0] * FF(3) + w[1] + w[2] * FF(7) + w[3] * FF(6) }, + w }; + } + + template + static void accumulate_with_subrelation_batching(ContainerOverSubrelations& evals, + const AllEntities& in, + const Parameters&, + const FF& scaling_factor, + const SubrelationBatchingConstants& constants) + { + using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; + using Coeff = typename Accumulator::CoefficientAccumulator; + using Id = typename AllEntities::EntityId; + // m*x^5 = (x^2)^2*(m*x): apply the weight to two coefficients, not seven evaluations. + auto weighted_sbox = [](const auto& x, const FF& weight) -> Accumulator { + const Accumulator square(x.sqr()); + return square.sqr() * Accumulator(x * weight); + }; + auto body = weighted_sbox(Coeff(in[Id::w_l]) + Coeff(in[Id::q_l]), constants.sbox[0]); + body += weighted_sbox(Coeff(in[Id::w_r]) + Coeff(in[Id::q_r]), constants.sbox[1]); + body += weighted_sbox(Coeff(in[Id::w_o]) + Coeff(in[Id::q_o]), constants.sbox[2]); + body += weighted_sbox(Coeff(in[Id::w_4]) + Coeff(in[Id::q_4]), constants.sbox[3]); + auto shifts = Coeff(in[Id::w_l_shift]) * constants.shifts[0]; + shifts += Coeff(in[Id::w_r_shift]) * constants.shifts[1]; + shifts += Coeff(in[Id::w_o_shift]) * constants.shifts[2]; + shifts += Coeff(in[Id::w_4_shift]) * constants.shifts[3]; + body -= Accumulator(shifts); + std::get<0>(evals) += Accumulator(Coeff(in[Id::q_poseidon2_external]) * scaling_factor) * body; + } +#endif + }; template using Poseidon2ExternalRelation = Relation>; diff --git a/barretenberg/cpp/src/barretenberg/relations/poseidon2_internal_relation.hpp b/barretenberg/cpp/src/barretenberg/relations/poseidon2_internal_relation.hpp index 6b30fa1..14ec854 100644 --- a/barretenberg/cpp/src/barretenberg/relations/poseidon2_internal_relation.hpp +++ b/barretenberg/cpp/src/barretenberg/relations/poseidon2_internal_relation.hpp @@ -164,6 +164,50 @@ template class Poseidon2InternalRelationImpl { barycentric_term += scaled_u1; std::get<3>(evals) += barycentric_term; }; +#ifndef __wasm__ + // Native prover batching: combine the four linear terms before their common selector product. + struct SubrelationBatchingConstants { + FF sbox; + std::array wires; + std::array shifts; + }; + + static SubrelationBatchingConstants compute_subrelation_batching_constants(const std::array& w) + { + const auto sum = w[0] + w[1] + w[2] + w[3]; + return { w[0] * D1 + w[1] + w[2] + w[3], + { sum + w[1] * D2_minus_1, sum + w[2] * D3_minus_1, sum + w[3] * D4_minus_1 }, + w }; + } + + template + static void accumulate_with_subrelation_batching(ContainerOverSubrelations& evals, + const AllEntities& in, + const Parameters&, + const FF& scaling_factor, + const SubrelationBatchingConstants& constants) + { + using Accumulator = std::tuple_element_t<0, ContainerOverSubrelations>; + using Coeff = typename Accumulator::CoefficientAccumulator; + using Id = typename AllEntities::EntityId; + const auto s1 = Accumulator(Coeff(in[Id::w_l]) + Coeff(in[Id::q_l])); + auto u1 = s1.sqr(); + u1 = u1.sqr(); + u1 *= s1; + const auto q_scaled = Coeff(in[Id::q_poseidon2_internal]) * scaling_factor; + auto linear = Coeff(in[Id::w_r]) * constants.wires[0]; + linear += Coeff(in[Id::w_o]) * constants.wires[1]; + linear += Coeff(in[Id::w_4]) * constants.wires[2]; + linear -= Coeff(in[Id::w_l_shift]) * constants.shifts[0]; + linear -= Coeff(in[Id::w_r_shift]) * constants.shifts[1]; + linear -= Coeff(in[Id::w_o_shift]) * constants.shifts[2]; + linear -= Coeff(in[Id::w_4_shift]) * constants.shifts[3]; + auto body = u1 * Accumulator(q_scaled * constants.sbox); + body += Accumulator(linear * q_scaled); + std::get<0>(evals) += body; + } +#endif + }; // namespace bb template using Poseidon2InternalRelation = Relation>; 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 3f4ab8e..d36810f 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.cpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.cpp @@ -374,8 +374,6 @@ std::vector get_bn254_g1_data(const std::filesystem::path& p 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. @@ -386,7 +384,10 @@ Bn254G1Points load_bn254_g1_points(const std::filesystem::path& path, size_t num delete[] p; }); }; - { + // As get_bn254_g1_data: whole pinned chunks (a verification key is only computed from those), and BB_VERIFY_CRS=1 + // skips the uncompressed cache, which has no pinned hashes. + num_points = round_up_to_chunk_boundary(num_points); + if (std::getenv("BB_VERIFY_CRS") == nullptr) { BB_BENCH_NAME("get_bn254_g1_data"); std::filesystem::create_directories(path); const auto uncompressed_path = path / "bn254_g1.dat"; @@ -402,11 +403,22 @@ Bn254G1Points load_bn254_g1_points(const std::filesystem::path& path, size_t num } #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 }; + auto points = get_bn254_g1_data(path, num_points, allow_download); + const size_t size = points.size(); + return { share_bn254_g1_points(std::move(points)), size }; +} + +std::shared_ptr share_bn254_g1_points(std::vector&& points) +{ + // The vector stays the owner of the points; the deleter owns the vector. + auto* owner = new std::vector(std::move(points)); + return std::shared_ptr(owner->data(), [owner](g1::affine_element* /*unused*/) { + const PageBlock block{ owner->data(), + owner->capacity() * sizeof(g1::affine_element), + owner->size() * sizeof(g1::affine_element) }; + static_cast(release_pages_in_parallel(std::span(&block, 1))); + delete owner; + }); } // Loads the canonical 128-byte serialization of [x]_2 from disk and verifies it against the pinned 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 de69edf..5fdae9f 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.hpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/get_bn254_crs.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace bb { std::vector get_bn254_g1_data(const std::filesystem::path& path, @@ -32,5 +33,11 @@ struct Bn254G1Points { */ Bn254G1Points load_bn254_g1_points(const std::filesystem::path& path, size_t num_points, bool allow_download = true); +/** + * @brief Moves `points` into shared storage without copying them; the storage hands the pages holding the points back + * from several threads before it is freed (see release_pages_in_parallel). + */ +std::shared_ptr share_bn254_g1_points(std::vector&& points); + 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 4f62d59..7abf6f4 100644 --- a/barretenberg/cpp/src/barretenberg/srs/factories/get_grumpkin_crs.cpp +++ b/barretenberg/cpp/src/barretenberg/srs/factories/get_grumpkin_crs.cpp @@ -9,7 +9,9 @@ #include "grumpkin_crs_data.hpp" #include "grumpkin_srs_gen.hpp" #include "pread.hpp" +#include #include +#include #include namespace bb { @@ -67,12 +69,32 @@ std::vector get_grumpkin_g1_data(const std::file // Not hashed here: the CRS constructor checks every point against the pinned chunk hashes, and accepts only // whole chunks. std::vector points(verify_points); + // The bytes are not authenticated yet, so a parse may fail: the first error is rethrown once every worker is + // done, as a serial parse would throw it. + std::exception_ptr parse_error; + std::mutex parse_error_mutex; parallel_for([&](ThreadChunk chunk) { - for (auto i : chunk.range(verify_points)) { - points[i] = - from_buffer(data, i * sizeof(curve::Grumpkin::AffineElement)); +#ifndef BB_NO_EXCEPTIONS + try { +#endif + for (auto i : chunk.range(verify_points)) { + points[i] = + from_buffer(data, i * sizeof(curve::Grumpkin::AffineElement)); + } +#ifndef BB_NO_EXCEPTIONS + } catch (...) { + 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 return points; } diff --git a/barretenberg/cpp/src/barretenberg/srs/factories/grumpkin_crs_load.test.cpp b/barretenberg/cpp/src/barretenberg/srs/factories/grumpkin_crs_load.test.cpp new file mode 100644 index 0000000..9368512 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/srs/factories/grumpkin_crs_load.test.cpp @@ -0,0 +1,161 @@ +#include "barretenberg/api/file_io.hpp" +#include "barretenberg/common/log.hpp" +#include "barretenberg/common/serialize.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/constants.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include "barretenberg/srs/factories/get_grumpkin_crs.hpp" +#include "barretenberg/srs/factories/grumpkin_crs_data.hpp" +#include "barretenberg/srs/factories/grumpkin_srs_gen.hpp" +#include +#include +#include +#include +#include +#include +#include + +using namespace bb; + +namespace { +using Point = curve::Grumpkin::AffineElement; +constexpr size_t CHUNK = srs::GRUMPKIN_G1_CHUNK_SIZE_POINTS; +constexpr const char* FILE_NAME = "grumpkin_g1_v2.flat.dat"; +// parallel_for concurrencies to load at; 0 leaves the setting alone, since without multithreading it cannot be set. +#ifdef NO_MULTITHREADING +constexpr std::array CONCURRENCIES{ 0 }; +#else +constexpr std::array CONCURRENCIES{ 1, 3, 16 }; +#endif + +// The cached-file path as a single serial read of the whole-chunk prefix and a serial parse of it. As in bb v6.1.0, it +// isn't hashed here: the CRS constructor checks the points against the pinned chunk hashes. +std::vector serial_load(const std::filesystem::path& dir, size_t num_points) +{ + const size_t verify_points = ((num_points + CHUNK - 1) / CHUNK) * CHUNK; + const size_t verify_bytes = verify_points * sizeof(Point); + if (get_file_size(dir / FILE_NAME) < verify_bytes) { + throw_or_abort(format("Grumpkin CRS cache needs ", + verify_points, + " points for integrity verification, but generation is not allowed")); + } + const auto data = read_file(dir / FILE_NAME, verify_bytes); + std::vector points(verify_points); + for (size_t i = 0; i < verify_points; ++i) { + points[i] = from_buffer(data, i * sizeof(Point)); + } + return points; +} + +// Without exceptions a failed load aborts, so error paths are only exercised when exceptions are enabled. +std::string error_of(const std::function& load) +{ +#ifdef BB_NO_EXCEPTIONS + load(); + return ""; +#else + try { + load(); + } catch (const std::exception& e) { + return e.what(); + } + return ""; +#endif +} +} // namespace + +// Files of several pinned chunks, built from the canonical generator: the whole file, one whose last chunk is partial, +// and one with a corrupted third chunk. For every request size and parallel_for concurrency the loader must return +// the serial path's points (the whole chunks the request needs), and fail exactly where the serial path fails. +class GrumpkinCrsLoad : public ::testing::Test { + protected: + static void SetUpTestSuite() + { + root = std::filesystem::temp_directory_path() / ("grumpkin-crs-load-" + std::to_string(getpid())); + canonical = srs::generate_grumpkin_srs(srs::GRUMPKIN_G1_NUM_POINTS); + const auto bytes = to_buffer(canonical); + ASSERT_EQ(bytes.size(), srs::GRUMPKIN_G1_SIZE_BYTES); + verify_grumpkin_crs_integrity(bytes); + + const auto write = [&](const char* name, std::span data) { + std::filesystem::create_directories(root / name); + write_file(root / name / FILE_NAME, data); + }; + write("full", bytes); + write("partial", std::span(bytes).first((2 * CHUNK + CHUNK / 2) * sizeof(Point))); + auto corrupt = bytes; + corrupt[(2 * CHUNK + 5) * sizeof(Point)] ^= 1; + write("corrupt", corrupt); + } + static void TearDownTestSuite() { std::filesystem::remove_all(root); } + + static void expect_same(const char* file, size_t num_points) + { + const auto dir = root / file; + const size_t original_concurrency = get_num_cpus(); + const std::string serial_error = error_of([&] { serial_load(dir, num_points); }); + for (const size_t concurrency : CONCURRENCIES) { + if (concurrency != 0) { + set_parallel_for_concurrency(concurrency); + } + const std::string context = std::string(file) + ", num_points " + std::to_string(num_points) + + ", concurrency " + std::to_string(concurrency); + if (!serial_error.empty()) { + EXPECT_EQ(error_of([&] { get_grumpkin_g1_data(dir, num_points, /*allow_download=*/false); }), + serial_error) + << context; + continue; + } + const auto points = get_grumpkin_g1_data(dir, num_points, /*allow_download=*/false); + EXPECT_EQ(points, serial_load(dir, num_points)) << context; + } + if (CONCURRENCIES[0] != 0) { + set_parallel_for_concurrency(original_concurrency); + } + if (serial_error.empty() && std::string(file) != "corrupt") { + const auto serial = serial_load(dir, num_points); + ASSERT_GE(serial.size(), num_points) << file; + EXPECT_TRUE(std::equal(serial.begin(), serial.end(), canonical.begin())) << file; + } + } + + static inline std::filesystem::path root; + static inline std::vector canonical; +}; + +TEST_F(GrumpkinCrsLoad, WholeFileMatchesSerialPath) +{ + for (const size_t n : { size_t{ 1 }, + size_t{ 1 } << CONST_ECCVM_LOG_N, + CHUNK, + CHUNK + 1, + 2 * CHUNK + 7, + 3 * CHUNK, + srs::GRUMPKIN_G1_NUM_POINTS }) { + expect_same("full", n); + } +} + +TEST_F(GrumpkinCrsLoad, PartialLastChunkMatchesSerialPath) +{ +#ifdef BB_NO_EXCEPTIONS + GTEST_SKIP() << "a short cache aborts without exceptions"; +#endif + for (const size_t n : { size_t{ 1 }, CHUNK + 1, 2 * CHUNK, 2 * CHUNK + 1 }) { + expect_same("partial", n); + } + EXPECT_FALSE(error_of([&] { serial_load(root / "partial", 2 * CHUNK + 1); }).empty()); +} + +TEST_F(GrumpkinCrsLoad, CorruptChunkMatchesSerialPath) +{ +#ifdef BB_NO_EXCEPTIONS + GTEST_SKIP() << "a corrupt chunk aborts without exceptions"; +#endif + for (const size_t n : { size_t{ 1 } << CONST_ECCVM_LOG_N, 2 * CHUNK, 2 * CHUNK + 1, srs::GRUMPKIN_G1_NUM_POINTS }) { + expect_same("corrupt", n); + } + // Loading doesn't hash in v6.1.0 (the CRS constructor does): a corrupted cache loads, or fails to parse, exactly as + // the serial path does. +} 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 32e8891..720d63f 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 @@ -6,6 +6,7 @@ #include "barretenberg/ecc/scalar_multiplication/scalar_multiplication.hpp" #include "bn254_crs_data.hpp" #include "crs_integrity.hpp" +#include "get_bn254_crs.hpp" #include #include #include @@ -64,21 +65,16 @@ class MemBn254Crs : public Crs { 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_([&points, &g2_point] { + const size_t num_points = points.size(); + return std::make_shared(share_bn254_g1_points(std::move(points)), num_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()); } diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp index 9b1cac2..bd69b19 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/hash/keccak/keccak.cpp @@ -454,9 +454,16 @@ template void keccak::chi(keccak_state& internal) } for (size_t x = 0; x < 5; ++x) { // Normalize lane outputs and assign to internal.state +#ifndef __wasm__ + const auto [value, msb] = + plookup_read::read_first_and_last_from_table(KECCAK_CHI_OUTPUT, lane_outputs[x]); + internal.state[y * 5 + x] = value; + internal.state_msb[y * 5 + x] = msb; +#else auto accumulators = plookup_read::get_lookup_accumulators(KECCAK_CHI_OUTPUT, lane_outputs[x]); internal.state[y * 5 + x] = accumulators[ColumnIdx::C2][0]; internal.state_msb[y * 5 + x] = accumulators[ColumnIdx::C3][accumulators[ColumnIdx::C3].size() - 1]; +#endif } } } @@ -506,9 +513,15 @@ std::array, keccak::NUM_KECCAK_LANES> keccak: keccak_state internal; internal.context = ctx; for (size_t i = 0; i < state.size(); ++i) { +#ifndef __wasm__ + const auto [value, msb] = plookup_read::read_first_and_last_from_table(KECCAK_FORMAT_INPUT, state[i]); + internal.state[i] = value; + internal.state_msb[i] = msb; +#else const auto accumulators = plookup_read::get_lookup_accumulators(KECCAK_FORMAT_INPUT, state[i]); internal.state[i] = accumulators[ColumnIdx::C2][0]; internal.state_msb[i] = accumulators[ColumnIdx::C3][accumulators[ColumnIdx::C3].size() - 1]; +#endif } compute_twisted_state(internal); keccakf1600(internal); diff --git a/barretenberg/cpp/src/barretenberg/stdlib/hash/sha256/sha256.cpp b/barretenberg/cpp/src/barretenberg/stdlib/hash/sha256/sha256.cpp index cf51fcd..df77370 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/hash/sha256/sha256.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/hash/sha256/sha256.cpp @@ -49,20 +49,14 @@ SHA256::sparse_witness_limbs SHA256::convert_witness(const fie using field_pt = field_t; sparse_witness_limbs result(input); - const auto lookup = plookup_read::get_lookup_accumulators(MultiTableId::SHA256_WITNESS_INPUT, input); - - result.sparse_limbs = std::array{ - lookup[ColumnIdx::C2][0], - lookup[ColumnIdx::C2][1], - lookup[ColumnIdx::C2][2], - lookup[ColumnIdx::C2][3], - }; - result.rotated_limb_corrections = std::array{ - lookup[ColumnIdx::C3][0], - lookup[ColumnIdx::C3][1], - lookup[ColumnIdx::C3][2], - lookup[ColumnIdx::C3][3], - }; + constexpr std::array columns{ ColumnIdx::C2, ColumnIdx::C2, ColumnIdx::C2, ColumnIdx::C2, + ColumnIdx::C3, ColumnIdx::C3, ColumnIdx::C3, ColumnIdx::C3 }; + constexpr std::array rows{ 0, 1, 2, 3, 0, 1, 2, 3 }; + const auto lookup = + plookup_read::read_rows_from_table(MultiTableId::SHA256_WITNESS_INPUT, input, columns, rows); + + result.sparse_limbs = std::array{ lookup[0], lookup[1], lookup[2], lookup[3] }; + result.rotated_limb_corrections = std::array{ lookup[4], lookup[5], lookup[6], lookup[7] }; result.has_sparse_limbs = true; return result; @@ -248,12 +242,14 @@ field_t SHA256::choose_with_sigma1(sparse_value& e, const spar // Separates rotation contributions (0-3) from Choose encoding (0-6) in each base-28 digit constexpr fr SPARSE_MULT = fr(7); - const auto lookup = plookup_read::get_lookup_accumulators(SHA256_CH_INPUT, e.normal); + constexpr std::array columns{ ColumnIdx::C3, ColumnIdx::C2, ColumnIdx::C2 }; + constexpr std::array rows{ 0, 0, 2 }; + const auto lookup = plookup_read::read_rows_from_table(SHA256_CH_INPUT, e.normal, columns, rows); const auto rotation_coefficients = sha256_tables::get_choose_rotation_multipliers(); - field_pt rotation_result = lookup[ColumnIdx::C3][0]; - e.sparse = lookup[ColumnIdx::C2][0]; - field_pt sparse_L2 = lookup[ColumnIdx::C2][2]; + field_pt rotation_result = lookup[0]; + e.sparse = lookup[1]; + field_pt sparse_L2 = lookup[2]; // Compute e + 7*Σ₁(e) in sparse form field_pt xor_result = (rotation_result * SPARSE_MULT) @@ -293,13 +289,15 @@ field_t SHA256::majority_with_sigma0(sparse_value& a, const sp // Separates rotation contributions (0-3) from Majority encoding (0-3) in each base-16 digit constexpr fr SPARSE_MULT = fr(4); - const auto lookup = plookup_read::get_lookup_accumulators(SHA256_MAJ_INPUT, a.normal); + constexpr std::array columns{ ColumnIdx::C3, ColumnIdx::C2, ColumnIdx::C2 }; + constexpr std::array rows{ 0, 0, 1 }; + const auto lookup = plookup_read::read_rows_from_table(SHA256_MAJ_INPUT, a.normal, columns, rows); const auto rotation_coefficients = sha256_tables::get_majority_rotation_multipliers(); // first row of 3rd column gives accumulating sum of "non-trivial" wraps - field_pt rotation_result = lookup[ColumnIdx::C3][0]; - a.sparse = lookup[ColumnIdx::C2][0]; - field_pt sparse_L1_acc = lookup[ColumnIdx::C2][1]; + field_pt rotation_result = lookup[0]; + a.sparse = lookup[1]; + field_pt sparse_L1_acc = lookup[2]; // Compute a + 4*Σ₀(a) in sparse form field_pt xor_result = (rotation_result * SPARSE_MULT) diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp index 26e3b07..02687e3 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.hpp @@ -59,6 +59,20 @@ template class bigfield { os << "{ " << a.element << " <= " << a.maximum_value << " }"; return os; } + /** + * @brief Construct a constant limb from its integer value, which must be below both the native modulus and + * DEFAULT_MAXIMUM_LIMB. + * @details Equal to Limb(field_t(ctx, bb::fr(value))), whose maximum value is the element converted + * back out of Montgomery form, i.e. `value` itself. + */ + static Limb from_constant(Builder* ctx, const uint256_t& value) + { + BB_ASSERT_DEBUG(value <= DEFAULT_MAXIMUM_LIMB); + Limb limb; + limb.element = field_t(ctx, bb::fr(value)); + limb.maximum_value = value; + return limb; + } Limb(const Limb& other) = default; Limb(Limb&& other) noexcept = default; Limb& operator=(const Limb& other) = default; @@ -570,11 +584,24 @@ template class bigfield { bool enable_divisor_nz_check = true); static bigfield sum(const std::vector& terms); + // Caller-owned native witness-evaluation cache. It stores no circuit values + // and accepts a hit only for the same reduced denominator. + class NativeDivisionCache { + friend class bigfield; + uint256_t denominator_{ 0 }; + native inverse_; + bool valid_ = false; + }; + static bigfield internal_div(const std::vector& numerators, const bigfield& denominator, - bool check_for_zero); + bool check_for_zero, + NativeDivisionCache* cache = nullptr); static bigfield div_without_denominator_check(const std::vector& numerators, const bigfield& denominator); + static bigfield div_without_denominator_check(const std::vector& numerators, + const bigfield& denominator, + NativeDivisionCache& cache); bigfield div_without_denominator_check(const bigfield& denominator); static bigfield div_check_denominator_nonzero(const std::vector& numerators, const bigfield& denominator); @@ -672,19 +699,22 @@ template class bigfield { */ static bigfield unreduced_zero() { - // 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(prime_basis_value); - return result; + // A context-free constant fixed by the moduli, so it is built once and copied + static const bigfield unreduced_zero_constant = [] { + const uint512_t multiple_of_modulus = ((get_maximum_unreduced_value() / modulus_u512) + 1) * modulus_u512; + 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(prime_basis_value); + return result; + }(); + return unreduced_zero_constant; } /** @@ -1035,6 +1065,7 @@ template class bigfield { // For testing purposes only friend class bigfield_test_access; + template friend struct BuilderBindingWalk; private: /** diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.test.cpp index 40ca81f..2e64667 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield.test.cpp @@ -17,6 +17,7 @@ #include "barretenberg/transcript/origin_tag.hpp" #include #include +#include #include using namespace bb; @@ -741,6 +742,12 @@ template class stdlib_bigfield : public testing::Test { fq_native expected = (a_native * b_native) + c_native; expected = expected.from_montgomery_form_reduced(); uint512_t result = d_ct.get_value(); + if (a_type == InputType::CONSTANT && b_type == InputType::CONSTANT && + c_type == InputType::WITNESS) { + // This branch delegates to sum(), whose value may be unreduced. + // Only this newly covered branch needs the canonical field oracle. + result = result % uint512_t(fq_native::modulus); + } EXPECT_EQ(result.lo.data[0], expected.data[0]); EXPECT_EQ(result.lo.data[1], expected.data[1]); @@ -1576,6 +1583,45 @@ template class stdlib_bigfield : public testing::Test { EXPECT_EQ(fq_native((selected.get_value() % uint512_t(fq_native::modulus)).lo), b); } + static void test_native_division_cache() + { + Builder cached_builder; + Builder plain_builder; + typename fq_ct::NativeDivisionCache cache; + for (const uint64_t divisor : std::array{ 7, 7, 11, 7 }) { + auto run = [&](Builder& builder, bool use_cache) { + auto a = fq_ct::create_from_u512_as_witness(&builder, uint512_t(17)); + auto b = fq_ct::create_from_u512_as_witness(&builder, uint512_t(3)); + auto denominator = fq_ct::create_from_u512_as_witness(&builder, uint512_t(divisor)); + return use_cache ? fq_ct::div_without_denominator_check({ a, b }, denominator, cache) + : fq_ct::div_without_denominator_check({ a, b }, denominator); + }; + const auto cached = run(cached_builder, true); + const auto plain = run(plain_builder, false); + EXPECT_EQ(cached.get_value(), plain.get_value()); + ASSERT_EQ(cached_builder.get_variables().size(), plain_builder.get_variables().size()); + for (size_t i = 0; i < cached_builder.get_variables().size(); ++i) { + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(cached_builder.get_variables()[i].data[limb], plain_builder.get_variables()[i].data[limb]); + } + } + EXPECT_EQ(cached_builder.blocks, plain_builder.blocks); + EXPECT_EQ(cached_builder.real_variable_index, plain_builder.real_variable_index); + // The public base equality includes private next/previous copy-cycle indices. + EXPECT_EQ(static_cast&>(cached_builder), + static_cast&>(plain_builder)); + } + EXPECT_TRUE(CircuitChecker::check(cached_builder)); + EXPECT_TRUE(CircuitChecker::check(plain_builder)); + + // A zero denominator follows the existing unchecked constant path and + // does not consume a previously cached nonzero inverse. + const fq_ct one(1); + const fq_ct zero(0); + EXPECT_EQ(fq_ct::div_without_denominator_check({ one }, zero, cache).get_value(), + fq_ct::div_without_denominator_check({ one }, zero).get_value()); + } + static void test_division_context() { auto builder = Builder(); @@ -2362,6 +2408,8 @@ TYPED_TEST(stdlib_bigfield, madd) } TYPED_TEST(stdlib_bigfield, madd_with_constants) { + TestFixture::test_madd(InputType::CONSTANT, InputType::CONSTANT, InputType::WITNESS); // c * c + w + TestFixture::test_madd(InputType::CONSTANT, InputType::CONSTANT, InputType::CONSTANT); // c * c + c TestFixture::test_madd(InputType::WITNESS, InputType::WITNESS, InputType::CONSTANT); // w * w + c TestFixture::test_madd(InputType::WITNESS, InputType::CONSTANT, InputType::WITNESS); // w * c + w TestFixture::test_madd(InputType::WITNESS, InputType::CONSTANT, InputType::CONSTANT); // w * c + c @@ -2691,3 +2739,9 @@ TYPED_TEST(stdlib_bigfield, less_than_works) EXPECT_TRUE(CircuitChecker::check(builder)); EXPECT_FALSE(builder.failed()); } + + +TYPED_TEST(stdlib_bigfield, native_division_cache_preserves_witnesses_and_gates) +{ + TestFixture::test_native_division_cache(); +} diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_circuit_identity.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_circuit_identity.test.cpp new file mode 100644 index 0000000..61451e2 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_circuit_identity.test.cpp @@ -0,0 +1,139 @@ +#include "barretenberg/circuit_checker/circuit_checker.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/numeric/uintx/uintx.hpp" +#include "barretenberg/stdlib/primitives/bigfield/bigfield.hpp" +#include "barretenberg/stdlib/primitives/circuit_builders/circuit_builders.hpp" +#include "barretenberg/stdlib/primitives/curves/bn254.hpp" +#include "barretenberg/stdlib/primitives/curves/secp256k1.hpp" +#include "barretenberg/stdlib/primitives/curves/secp256r1.hpp" +#include +#include +#include + +// Pins the native shortcuts of bigfield against straightforward compositions of the public API: every constant, +// witness, gate and copy constraint must be exactly what the plain composition produces. + +using namespace bb; + +namespace { +auto& engine = numeric::get_debug_randomness(); + +template void expect_same_field(const stdlib::field_t& a, const stdlib::field_t& b) +{ + EXPECT_EQ(a.get_context(), b.get_context()); + EXPECT_EQ(a.is_constant(), b.is_constant()); + for (size_t i = 0; i < 4; ++i) { + EXPECT_EQ(a.additive_constant.data[i], b.additive_constant.data[i]); + EXPECT_EQ(a.multiplicative_constant.data[i], b.multiplicative_constant.data[i]); + } + EXPECT_EQ(a.get_origin_tag(), b.get_origin_tag()); +} + +template void expect_same_circuit(const Builder& a, const Builder& b) +{ + ASSERT_EQ(a.get_variables().size(), b.get_variables().size()); + for (size_t i = 0; i < a.get_variables().size(); ++i) { + for (size_t limb = 0; limb < 4; ++limb) { + EXPECT_EQ(a.get_variables()[i].data[limb], b.get_variables()[i].data[limb]); + } + } + EXPECT_EQ(a.blocks, b.blocks); + EXPECT_EQ(a.real_variable_index, b.real_variable_index); + EXPECT_EQ(static_cast&>(a), static_cast&>(b)); + EXPECT_EQ(a.failed(), b.failed()); +} +} // namespace + +template class BigfieldCircuitIdentity : public testing::Test { + public: + using fq_ct = BigField; + using Builder = typename fq_ct::field_ct::Builder; + using field_ct = stdlib::field_t; + using witness_ct = stdlib::witness_t; + using Limb = typename fq_ct::Limb; + static constexpr uint64_t L = fq_ct::NUM_LIMB_BITS; + + static void expect_same_bigfield(const fq_ct& a, const fq_ct& b) + { + EXPECT_EQ(a.get_context(), b.get_context()); + for (size_t i = 0; i < fq_ct::NUM_LIMBS; ++i) { + expect_same_field(a.get_limb(i).element, b.get_limb(i).element); + EXPECT_EQ(a.get_limb(i).maximum_value, b.get_limb(i).maximum_value); + } + expect_same_field(a.get_prime_basis_limb(), b.get_prime_basis_limb()); + } + + // The limbs `bigfield(ctx, value)` is specified to hold: constant limbs of the 68-bit slices of `value`, whose + // maximum values come from the generic Limb constructor. + static void expect_constant_layout(Builder* ctx, const fq_ct& actual, const uint256_t& value) + { + EXPECT_EQ(actual.get_context(), ctx); + for (size_t i = 0; i < fq_ct::NUM_LIMBS; ++i) { + const Limb reference{ field_ct(ctx, fr(value.slice(i * L, (i + 1) * L))) }; + expect_same_field(actual.get_limb(i).element, reference.element); + EXPECT_EQ(actual.get_limb(i).maximum_value, reference.maximum_value); + } + expect_same_field(actual.get_prime_basis_limb(), field_ct(ctx, fr(value))); + } + + static void test_constant_constructors() + { + Builder builder; + for (Builder* ctx : std::array{ nullptr, &builder }) { + expect_constant_layout(ctx, fq_ct(ctx), uint256_t(0)); + // fr(0) is the all-zero representation, which is what the zero constructor writes. + EXPECT_EQ(fr(0).data[0] | fr(0).data[1] | fr(0).data[2] | fr(0).data[3], 0ULL); + + std::vector values{ 0, 1, (uint256_t(1) << L) - 1, uint256_t(1) << L, fq_ct::modulus - 1 }; + for (size_t i = 0; i < 8; ++i) { + values.emplace_back(engine.get_random_uint256() % fq_ct::modulus); + } + for (const auto& value : values) { + expect_constant_layout(ctx, fq_ct(ctx, value), value); + } + } + expect_constant_layout(nullptr, fq_ct::one(), uint256_t(1)); + expect_constant_layout(nullptr, fq_ct::zero(), uint256_t(0)); + EXPECT_EQ(builder.get_num_variables(), Builder().get_num_variables()); + } + + static void test_unreduced_zero() + { + const uint512_t multiple = + ((fq_ct::get_maximum_unreduced_value() / fq_ct::modulus_u512) + 1) * fq_ct::modulus_u512; + const uint64_t msb = multiple.get_msb(); + const std::array slices{ multiple.slice(0, L).lo, + multiple.slice(L, 2 * L).lo, + multiple.slice(2 * L, 3 * L).lo, + multiple.slice(3 * L, msb + 1).lo }; + for (size_t call = 0; call < 2; ++call) { + const fq_ct actual = fq_ct::unreduced_zero(); + EXPECT_EQ(actual.get_context(), nullptr); + for (size_t i = 0; i < fq_ct::NUM_LIMBS; ++i) { + const Limb reference{ field_ct(fr(slices[i])) }; + expect_same_field(actual.get_limb(i).element, reference.element); + EXPECT_EQ(actual.get_limb(i).maximum_value, reference.maximum_value); + } + expect_same_field(actual.get_prime_basis_limb(), + field_ct(uint256_t((multiple % uint512_t(fr::modulus)).lo))); + EXPECT_EQ(actual.get_value(), multiple); + } + } +}; + +using CircuitTypes = testing::Types::BaseField, + typename stdlib::secp256k1::BaseField, + typename stdlib::secp256k1::ScalarField, + typename stdlib::secp256r1::BaseField, + typename stdlib::secp256r1::ScalarField>; +TYPED_TEST_SUITE(BigfieldCircuitIdentity, CircuitTypes); + +TYPED_TEST(BigfieldCircuitIdentity, ConstantConstructors) +{ + TestFixture::test_constant_constructors(); +} + +TYPED_TEST(BigfieldCircuitIdentity, UnreducedZero) +{ + TestFixture::test_unreduced_zero(); +} 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 9bb903e..795eeea 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bigfield/bigfield_impl.hpp @@ -24,22 +24,22 @@ namespace bb::stdlib { template bigfield::bigfield(Builder* parent_context) : context(parent_context) - , binary_basis_limbs{ Limb(field_t(parent_context, bb::fr(0))), - Limb(field_t(parent_context, bb::fr(0))), - Limb(field_t(parent_context, bb::fr(0))), - Limb(field_t(parent_context, bb::fr(0))) } - , prime_basis_limb(context, 0) -{} + , prime_basis_limb(parent_context) +{ + // Default limbs are constant zeros with maximum value 0. bb::fr(0) is the all-zero representation, so this equals + // building each limb from field_t(parent_context, bb::fr(0)) without the Montgomery conversions. + for (auto& limb : binary_basis_limbs) { + limb.element.context = parent_context; + } +} template bigfield::bigfield(Builder* parent_context, const uint256_t& value) : context(parent_context) - , binary_basis_limbs{ Limb(field_t(parent_context, bb::fr(value.slice(0, NUM_LIMB_BITS)))), - Limb(field_t(parent_context, bb::fr(value.slice(NUM_LIMB_BITS, NUM_LIMB_BITS * 2)))), - Limb(field_t(parent_context, - bb::fr(value.slice(NUM_LIMB_BITS * 2, NUM_LIMB_BITS * 3)))), - Limb(field_t(parent_context, - bb::fr(value.slice(NUM_LIMB_BITS * 3, NUM_LIMB_BITS * 4)))) } + , binary_basis_limbs{ Limb::from_constant(parent_context, value.slice(0, NUM_LIMB_BITS)), + Limb::from_constant(parent_context, value.slice(NUM_LIMB_BITS, NUM_LIMB_BITS * 2)), + Limb::from_constant(parent_context, value.slice(NUM_LIMB_BITS * 2, NUM_LIMB_BITS * 3)), + Limb::from_constant(parent_context, value.slice(NUM_LIMB_BITS * 3, NUM_LIMB_BITS * 4)) } , prime_basis_limb(context, value) { BB_ASSERT_LT(value, modulus); @@ -775,7 +775,8 @@ bigfield bigfield::sum(const std::vector& term template bigfield bigfield::internal_div(const std::vector& numerators, const bigfield& denominator, - bool check_for_zero) + bool check_for_zero, + NativeDivisionCache* cache) { BB_ASSERT_LT(numerators.size(), MAXIMUM_SUMMAND_COUNT); if (numerators.empty()) { @@ -813,11 +814,22 @@ bigfield bigfield::internal_div(const std::vector; const NativeField numerator_native(uint256_t((left % modulus).lo.lo)); - inverse_value = uint512_t(uint256_t(numerator_native * NativeField(denominator_reduced).invert())); + NativeField denominator_inverse; + if (cache != nullptr && cache->valid_ && cache->denominator_ == denominator_reduced) { + denominator_inverse = cache->inverse_; + } else { + denominator_inverse = NativeField(denominator_reduced).invert(); + if (cache != nullptr) { + cache->denominator_ = denominator_reduced; + cache->inverse_ = denominator_inverse; + cache->valid_ = true; + } + } + inverse_value = uint512_t(uint256_t(numerator_native * denominator_inverse)); } - const uint1024_t quotient_1024 = - (uint1024_t(inverse_value) * right + unreduced_zero().get_value() - left) / modulus; + static const uint512_t unreduced_zero_value = unreduced_zero().get_value(); + const uint1024_t quotient_1024 = (uint1024_t(inverse_value) * right + unreduced_zero_value - left) / modulus; const uint512_t quotient_value = quotient_1024.lo; bigfield inverse; @@ -847,7 +859,7 @@ bigfield bigfield::internal_div(const std::vector bigfield::div_without_denominator_check(const s return internal_div(numerators, denominator, false); } +template +bigfield bigfield::div_without_denominator_check(const std::vector& numerators, + const bigfield& denominator, + NativeDivisionCache& cache) +{ + return internal_div(numerators, denominator, false, &cache); +} + template bigfield bigfield::div_without_denominator_check(const bigfield& denominator) { @@ -1070,14 +1090,11 @@ bigfield bigfield::madd(const bigfield& to_mul, const st const uint1024_t add_right(add_values); const uint1024_t modulus(target_basis.modulus); - const auto [quotient_1024, remainder_1024] = (left * mul_right + add_right).divmod(modulus); - - const uint512_t quotient_value = quotient_1024.lo; - const uint512_t remainder_value = remainder_1024.lo; - bigfield remainder; bigfield quotient; if (is_constant() && to_mul.is_constant() && add_constant) { + const auto [_, remainder_1024] = (left * mul_right + add_right).divmod(modulus); + const uint512_t remainder_value = remainder_1024.lo; remainder = bigfield(ctx, uint256_t(remainder_value.lo)); return remainder; } else if (is_constant() && to_mul.is_constant()) { @@ -1096,6 +1113,10 @@ bigfield bigfield::madd(const bigfield& to_mul, const st } return (*this).madd(to_mul, to_add); } + // Only compute the quotient and remainder after ruling out paths that do not consume them. + const auto [quotient_1024, remainder_1024] = (left * mul_right + add_right).divmod(modulus); + const uint512_t quotient_value = quotient_1024.lo; + const uint512_t remainder_value = remainder_1024.lo; quotient = create_from_u512_as_witness(ctx, quotient_value, false, num_quotient_bits); remainder = create_from_u512_as_witness(ctx, remainder_value); }; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup.hpp index f2e851d..b0c667d 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup.hpp @@ -468,6 +468,7 @@ template class element { // For testing purposes only friend class element_test_accessor; + template friend struct ::bb::stdlib::BuilderBindingWalk; private: // Private constructor with explicit infinity flag control. diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup_impl.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup_impl.hpp index 74d331b..6eeb7c2 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup_impl.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/biggroup/biggroup_impl.hpp @@ -374,10 +374,27 @@ std::array, 2> element::checked_unconditiona const Fq denominator = other._x - _x; const Fq x2x1 = -(other._x + _x); - const Fq lambda1 = Fq::div_without_denominator_check({ other._y, -_y }, denominator); + auto division_cache = [] { + if constexpr (requires { typename Fq::NativeDivisionCache; }) { + return typename Fq::NativeDivisionCache{}; + } else { + return false; + } + }(); + const auto divide = [&](const std::vector& numerators) { + if constexpr (requires { + typename Fq::NativeDivisionCache; + Fq::div_without_denominator_check(numerators, denominator, division_cache); + }) { + return Fq::div_without_denominator_check(numerators, denominator, division_cache); + } else { + return Fq::div_without_denominator_check(numerators, denominator); + } + }; + const Fq lambda1 = divide({ other._y, -_y }); const Fq x_3 = lambda1.sqradd({ x2x1 }); const Fq y_3 = lambda1.madd(_x - x_3, { -_y }); - const Fq lambda2 = Fq::div_without_denominator_check({ -other._y, -_y }, denominator); + const Fq lambda2 = divide({ -other._y, -_y }); const Fq x_4 = lambda2.sqradd({ x2x1 }); const Fq y_4 = lambda2.madd(_x - x_4, { -_y }); diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bool/bool.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bool/bool.hpp index 25a5fd0..b398cff 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/bool/bool.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/bool/bool.hpp @@ -180,6 +180,7 @@ template class bool_t { template friend class bigfield; template friend class field_t; + template friend struct BuilderBindingWalk; }; template inline std::ostream& operator<<(std::ostream& os, bool_t const& v) diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/builder_binding.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/builder_binding.hpp new file mode 100644 index 0000000..5ece8c8 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/builder_binding.hpp @@ -0,0 +1,202 @@ +#pragma once +#include "barretenberg/common/assert.hpp" +#include "barretenberg/stdlib/primitives/bigfield/bigfield.hpp" +#include "barretenberg/stdlib/primitives/bigfield/goblin_field.hpp" +#include "barretenberg/stdlib/primitives/biggroup/biggroup.hpp" +#include "barretenberg/stdlib/primitives/bool/bool.hpp" +#include "barretenberg/stdlib/primitives/field/field.hpp" +#include "barretenberg/stdlib/primitives/group/cycle_group.hpp" +#include "barretenberg/stdlib/primitives/pairing_points.hpp" +#include "barretenberg/stdlib_circuit_builders/pairing_points_tagging.hpp" +#include +#include +#include +#include +#include + +namespace bb { +template class OpeningPair; +template class OpeningClaim; +} // namespace bb + +namespace bb::stdlib::recursion::honk { +template struct UltraRecursiveVerifierOutput; +} // namespace bb::stdlib::recursion::honk + +namespace bb::stdlib { + +/** + * @brief Visits, in place, every builder pointer, witness index and pairing-point tag index a stdlib value holds. + * @details Reads and writes members directly and calls nothing that can add a gate, a variable or a tag. A `Visitor` + * provides `context(Builder*&)`, `witness(uint32_t&)` and `pairing_tag(uint32_t&)`. Covers `field_t`, `bool_t`, + * `bigfield`, `goblin_field`, both bn254 group element kinds, `cycle_group`, `PairingPoints`, `OpeningPair`, + * `OpeningClaim`, `UltraRecursiveVerifierOutput` and vectors and arrays of these (`Proof` included). + */ +template struct BuilderBindingWalk { + template static void visit(field_t& value, Visitor& visitor) + { + visitor.context(value.context); + visitor.witness(value.witness_index); + } + + template static void visit(bool_t& value, Visitor& visitor) + { + visitor.context(value.context); + visitor.witness(value.witness_index); + } + + template static void visit(bigfield& value, Visitor& visitor) + { + visitor.context(value.context); + for (auto& limb : value.binary_basis_limbs) { + visit(limb.element, visitor); + } + visit(value.prime_basis_limb, visitor); + } + + template static void visit(goblin_field& value, Visitor& visitor) + { + for (auto& limb : value.limbs) { + visit(limb, visitor); + } + } + + template + static void visit(element_default::element& value, Visitor& visitor) + { + visit(value._x, visitor); + visit(value._y, visitor); + visit(value._is_infinity, visitor); + } + + template + static void visit(element_goblin::goblin_element& value, Visitor& visitor) + { + visit(value.x(), visitor); + visit(value.y(), visitor); + } + + template static void visit(cycle_group& value, Visitor& visitor) + { + visitor.context(value.context); + visit(value._x, visitor); + visit(value._y, visitor); + visit(value._is_infinity, visitor); + } + + template + requires std::is_same_v + static void visit(recursion::PairingPoints& value, Visitor& visitor) + { + for (auto& point : value) { + visit(point, visitor); + } + visitor.pairing_tag(value.tag_index); + } + + template static void visit(OpeningPair& value, Visitor& visitor) + { + visit(value.challenge, visitor); + visit(value.evaluation, visitor); + } + + template static void visit(OpeningClaim& value, Visitor& visitor) + { + visit(value.opening_pair, visitor); + visit(value.commitment, visitor); + } + + template + static void visit(recursion::honk::UltraRecursiveVerifierOutput& value, Visitor& visitor) + { + visit(value.points_accumulator, visitor); + visit(value.ipa_claim, visitor); + visit(value.ipa_proof, visitor); + visit(value.kernel_return_data, visitor); + visit(value.ecc_op_tables, visitor); + visit(value.transcript_hash, visitor); + } + + template static void visit(std::vector& values, Visitor& visitor) + { + for (auto& value : values) { + visit(value, visitor); + } + } + + template static void visit(std::array& values, Visitor& visitor) + { + for (auto& value : values) { + visit(value, visitor); + } + } +}; + +/** + * @brief Make `object`, built on a scratch builder, refer to `builder`, where each scratch variable `i` lives at + * `real_index_of[i]`. + * @details Sets every non-null builder pointer, on leaves and on aggregates that keep their own, to `builder`; maps + * every witness index through `real_index_of`, leaving `IS_CONSTANT` alone; adds `pairing_tag_offset` to every + * registered pairing-point tag index. Every other member (constants, cached values, limb bounds, infinity flags, origin + * tags, population flags) keeps its value, and neither builder gains a gate, a variable or a tag. + * @pre Every witness index in `object` is below `real_index_of.size()` and maps to a variable of `builder`. + */ +template +void rebind_to_builder(T& object, + Builder* builder, + const std::vector& real_index_of, + uint32_t pairing_tag_offset) +{ + struct Rebind { + Builder* builder; + const std::vector& real_index_of; + uint32_t pairing_tag_offset; + + void context(Builder*& context) const + { + if (context != nullptr) { + context = builder; + } + } + void witness(uint32_t& index) const + { + if (index == IS_CONSTANT) { + return; + } + BB_ASSERT_LT(index, real_index_of.size(), "rebind_to_builder: witness index outside the index map"); + index = real_index_of[index]; + BB_ASSERT(index != IS_CONSTANT, "rebind_to_builder: a witness maps to the constant sentinel"); + } + void pairing_tag(uint32_t& tag) const + { + if (tag != PairingPointsTagging::UNREGISTERED) { + tag += pairing_tag_offset; + } + } + }; + Rebind rebind{ builder, real_index_of, pairing_tag_offset }; + BuilderBindingWalk::visit(object, rebind); +} + +/** + * @brief Count the builder pointers in `object`, on leaves and aggregates alike, that equal `builder`. + * @details Walks the same members as rebind_to_builder() and reads them only; a nonzero count after rebinding means a + * pointer was left on the scratch builder. + */ +template size_t count_contexts_on(const T& object, const Builder* builder) +{ + struct Count { + const Builder* builder; + size_t count = 0; + + void context(Builder*& context) { count += (context == builder) ? 1 : 0; } + void witness(uint32_t& /*index*/) {} + void pairing_tag(uint32_t& /*tag*/) {} + }; + Count counter{ builder }; + // The walk takes mutable references; this visitor writes nothing. + BuilderBindingWalk::visit(const_cast(object), counter); + return counter.count; +} + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/builder_binding.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/builder_binding.test.cpp new file mode 100644 index 0000000..95e3b2b --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/builder_binding.test.cpp @@ -0,0 +1,403 @@ +#include "barretenberg/stdlib/primitives/builder_binding.hpp" +#include "barretenberg/commitment_schemes/claim.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib/primitives/curves/bn254.hpp" +#include "barretenberg/stdlib/primitives/curves/grumpkin.hpp" +#include "barretenberg/stdlib/proof/proof.hpp" +#include "barretenberg/ultra_honk/ultra_verifier.hpp" +#include + +namespace bb::stdlib { +namespace { + +using Builder = UltraCircuitBuilder; +using field_ct = field_t; +using bool_ct = bool_t; +using witness_ct = witness_t; +using Bn254 = bn254; +using fq_ct = Bn254::BaseField; +using G1 = Bn254::Group; +using cycle_group_ct = cycle_group; +using PairingPointsCt = recursion::PairingPoints; +using OpeningClaimCt = OpeningClaim>; +using VerifierOutput = recursion::honk::UltraRecursiveVerifierOutput; + +// Builder pointers of every member, read through public accessors only so the walk is checked independently. +using Contexts = std::vector; + +void collect_contexts(const field_ct& value, Contexts& out) +{ + out.push_back(value.get_context()); +} + +void collect_contexts(const bool_ct& value, Contexts& out) +{ + out.push_back(value.get_context()); +} + +void collect_contexts(const fq_ct& value, Contexts& out) +{ + out.push_back(value.context); + for (size_t i = 0; i < fq_ct::NUM_LIMBS; i++) { + collect_contexts(value.get_limb(i).element, out); + } + collect_contexts(value.get_prime_basis_limb(), out); +} + +void collect_contexts(const G1& value, Contexts& out) +{ + collect_contexts(value.x(), out); + collect_contexts(value.y(), out); + collect_contexts(value.is_point_at_infinity(), out); +} + +void collect_contexts(const cycle_group_ct& value, Contexts& out) +{ + out.push_back(value.get_context()); + collect_contexts(value.x(), out); + collect_contexts(value.y(), out); + collect_contexts(value.is_point_at_infinity(), out); +} + +void collect_contexts(const PairingPointsCt& value, Contexts& out) +{ + collect_contexts(value.P0(), out); + collect_contexts(value.P1(), out); +} + +void collect_contexts(const OpeningClaimCt& value, Contexts& out) +{ + collect_contexts(value.opening_pair.challenge, out); + collect_contexts(value.opening_pair.evaluation, out); + collect_contexts(value.commitment, out); +} + +template void collect_contexts(const std::vector& values, Contexts& out) +{ + for (const auto& value : values) { + collect_contexts(value, out); + } +} + +template void collect_contexts(const std::array& values, Contexts& out) +{ + for (const auto& value : values) { + collect_contexts(value, out); + } +} + +void collect_contexts(const VerifierOutput& value, Contexts& out) +{ + collect_contexts(value.points_accumulator, out); + collect_contexts(value.ipa_claim, out); + collect_contexts(value.ipa_proof, out); + collect_contexts(value.kernel_return_data, out); + collect_contexts(value.ecc_op_tables, out); + collect_contexts(value.transcript_hash, out); +} + +template Contexts contexts_of(const T& value) +{ + Contexts out; + collect_contexts(value, out); + return out; +} + +// Every pointer that was on `from` is on `to`, and every null pointer stayed null. +void expect_moved(const Contexts& before, const Contexts& after, const Builder* from, const Builder* to) +{ + ASSERT_EQ(before.size(), after.size()); + for (size_t i = 0; i < before.size(); i++) { + if (before[i] == nullptr) { + EXPECT_EQ(after[i], nullptr) << "member " << i; + } else { + EXPECT_EQ(before[i], from) << "member " << i; + EXPECT_EQ(after[i], to) << "member " << i; + } + } +} + +void expect_only_on(const Contexts& contexts, const Builder* builder) +{ + for (const auto* context : contexts) { + EXPECT_TRUE(context == nullptr || context == builder); + } +} + +struct IndexRecorder { + std::vector witnesses; + std::vector tags; + void context(Builder*& /*context*/) {} + void witness(uint32_t& index) { witnesses.push_back(index); } + void pairing_tag(uint32_t& tag) { tags.push_back(tag); } +}; + +template IndexRecorder record_indices(T& object) +{ + IndexRecorder recorder; + BuilderBindingWalk::visit(object, recorder); + return recorder; +} + +// One value of every kind a recursion constraint can return, on one builder. +struct Values { + field_ct witness; + field_ct scaled; + field_ct constant_on_builder; + field_ct constant_without_builder; + bool_ct flag; + bool_ct inverted_flag; + bool_ct constant_flag; + fq_ct big; + fq_ct big_constant; + G1 point; + cycle_group_ct grumpkin_point; + PairingPointsCt pairing_points; + VerifierOutput output; + + template void for_each(F&& f) + { + f(witness); + f(scaled); + f(constant_on_builder); + f(constant_without_builder); + f(flag); + f(inverted_flag); + f(constant_flag); + f(big); + f(big_constant); + f(point); + f(grumpkin_point); + f(pairing_points); + f(output); + } + + // Both pairing-point objects register one tag each. + static constexpr uint32_t NUM_PAIRING_TAGS = 2; + + static Values make(Builder& builder) + { + Values v; + v.witness = field_ct::from_witness(&builder, fr(5)); + v.scaled = v.witness * fr(3) + fr(7); + v.constant_on_builder = field_ct(&builder, fr(9)); + v.constant_without_builder = field_ct(fr(11)); + v.flag = bool_ct(witness_ct(&builder, true)); + v.inverted_flag = !v.flag; + v.constant_flag = bool_ct(&builder, false); + v.big = fq_ct::from_witness(&builder, fq::random_element()); + v.big_constant = fq_ct(&builder, uint256_t(123456789)); + v.point = G1::from_witness(&builder, g1::affine_element::random_element()); + v.grumpkin_point = cycle_group_ct::from_witness(&builder, cycle_group_ct::AffineElement::random_element()); + v.pairing_points = PairingPointsCt(G1::from_witness(&builder, g1::affine_element::random_element()), + G1::from_witness(&builder, g1::affine_element::random_element())); + v.output.points_accumulator = PairingPointsCt(G1::from_witness(&builder, g1::affine_element::random_element()), + G1::from_witness(&builder, g1::affine_element::random_element())); + v.output.ipa_claim = + OpeningClaimCt{ { fq_ct::from_witness(&builder, fq::random_element()), + fq_ct::from_witness(&builder, fq::random_element()) }, + cycle_group_ct::from_witness(&builder, cycle_group_ct::AffineElement::random_element()) }; + v.output.ipa_proof = Proof(builder, HonkProof{ fr(1), fr(2), fr::random_element() }); + return v; + } +}; + +void expect_same_values(const PairingPointsCt& a, const PairingPointsCt& b) +{ + EXPECT_EQ(a.P0().get_value(), b.P0().get_value()); + EXPECT_EQ(a.P1().get_value(), b.P1().get_value()); + EXPECT_EQ(a.is_populated(), b.is_populated()); + EXPECT_EQ(a.is_default(), b.is_default()); +} + +void expect_same_values(const Values& a, const Values& b) +{ + EXPECT_EQ(a.witness.get_value(), b.witness.get_value()); + EXPECT_EQ(a.scaled.get_value(), b.scaled.get_value()); + EXPECT_EQ(a.scaled.additive_constant, b.scaled.additive_constant); + EXPECT_EQ(a.scaled.multiplicative_constant, b.scaled.multiplicative_constant); + EXPECT_EQ(a.witness.get_origin_tag(), b.witness.get_origin_tag()); + EXPECT_EQ(a.constant_on_builder.get_value(), b.constant_on_builder.get_value()); + EXPECT_EQ(a.constant_without_builder.get_value(), b.constant_without_builder.get_value()); + EXPECT_EQ(a.flag.get_value(), b.flag.get_value()); + EXPECT_EQ(a.inverted_flag.get_value(), b.inverted_flag.get_value()); + EXPECT_EQ(a.constant_flag.get_value(), b.constant_flag.get_value()); + EXPECT_EQ(a.big.get_value(), b.big.get_value()); + EXPECT_EQ(a.big_constant.get_value(), b.big_constant.get_value()); + for (size_t i = 0; i < fq_ct::NUM_LIMBS; i++) { + EXPECT_EQ(a.big.get_limb(i).maximum_value, b.big.get_limb(i).maximum_value); + EXPECT_EQ(a.big.get_limb(i).element.get_value(), b.big.get_limb(i).element.get_value()); + } + EXPECT_EQ(a.big.get_prime_basis_limb().get_value(), b.big.get_prime_basis_limb().get_value()); + EXPECT_EQ(a.point.get_value(), b.point.get_value()); + EXPECT_EQ(a.point.is_point_at_infinity().get_value(), b.point.is_point_at_infinity().get_value()); + EXPECT_EQ(a.grumpkin_point.get_value(), b.grumpkin_point.get_value()); + expect_same_values(a.pairing_points, b.pairing_points); + expect_same_values(a.output.points_accumulator, b.output.points_accumulator); + EXPECT_EQ(a.output.ipa_claim.opening_pair.challenge.get_value(), + b.output.ipa_claim.opening_pair.challenge.get_value()); + EXPECT_EQ(a.output.ipa_claim.opening_pair.evaluation.get_value(), + b.output.ipa_claim.opening_pair.evaluation.get_value()); + EXPECT_EQ(a.output.ipa_claim.commitment.get_value(), b.output.ipa_claim.commitment.get_value()); + EXPECT_EQ(a.output.ipa_proof.get_value(), b.output.ipa_proof.get_value()); +} + +struct Counts { + size_t gates; + size_t variables; + bool operator==(const Counts& other) const = default; +}; + +Counts counts(const Builder& builder) +{ + return { builder.num_gates(), builder.get_num_variables() }; +} + +class BuilderBindingTests : public testing::Test { + public: + static void SetUpTestSuite() { bb::srs::init_file_crs_factory(bb::srs::bb_crs_path()); } +}; + +} // namespace + +TEST_F(BuilderBindingTests, RebindsEveryMemberToTheRealBuilder) +{ + constexpr size_t EXTRA_VARIABLES = 7; + constexpr uint32_t TAG_OFFSET = 3; + + Builder scratch; + Values values = Values::make(scratch); + const Values original = values; + + // The real builder holds every scratch variable after variables and pairing-point tags of its own. + Builder real; + for (size_t i = 0; i < EXTRA_VARIABLES; i++) { + real.add_variable(fr::random_element()); + } + for (uint32_t i = 0; i < TAG_OFFSET + Values::NUM_PAIRING_TAGS; i++) { + real.pairing_points_tagging.create_pairing_point_tag(); + } + std::vector real_index_of; + for (uint32_t i = 0; i < scratch.get_num_variables(); i++) { + real_index_of.push_back(real.add_variable(scratch.get_variable(i))); + } + ASSERT_GT(real_index_of.front(), 0U); + + std::vector contexts_before; + std::vector indices_before; + size_t on_scratch_before = 0; + values.for_each([&](auto& member) { + contexts_before.push_back(contexts_of(member)); + indices_before.push_back(record_indices(member)); + on_scratch_before += count_contexts_on(member, &scratch); + }); + EXPECT_GT(on_scratch_before, 0U); + + const Counts scratch_counts = counts(scratch); + const Counts real_counts = counts(real); + values.for_each([&](auto& member) { rebind_to_builder(member, &real, real_index_of, TAG_OFFSET); }); + expect_same_values(original, values); + EXPECT_EQ(counts(scratch), scratch_counts); + EXPECT_EQ(counts(real), real_counts); + + size_t member = 0; + values.for_each([&](auto& value) { + expect_moved(contexts_before[member], contexts_of(value), &scratch, &real); + EXPECT_EQ(count_contexts_on(value, &scratch), 0U) << "member " << member; + + const IndexRecorder after = record_indices(value); + const IndexRecorder& before = indices_before[member]; + ASSERT_EQ(after.witnesses.size(), before.witnesses.size()); + for (size_t i = 0; i < before.witnesses.size(); i++) { + if (before.witnesses[i] == IS_CONSTANT) { + EXPECT_EQ(after.witnesses[i], IS_CONSTANT); + } else { + EXPECT_EQ(after.witnesses[i], real_index_of[before.witnesses[i]]); + EXPECT_EQ(real.get_variable(after.witnesses[i]), scratch.get_variable(before.witnesses[i])); + } + } + ASSERT_EQ(after.tags.size(), before.tags.size()); + for (size_t i = 0; i < before.tags.size(); i++) { + EXPECT_EQ(after.tags[i], before.tags[i] + TAG_OFFSET); + } + member++; + }); + EXPECT_EQ(values.constant_without_builder.get_context(), nullptr); + EXPECT_TRUE(values.constant_on_builder.is_constant()); + EXPECT_EQ(values.constant_on_builder.get_context(), &real); +} + +TEST_F(BuilderBindingTests, ArithmeticOnReboundValuesAllocatesOnTheRealBuilder) +{ + Builder scratch; + Values values = Values::make(scratch); + Builder real; + for (uint32_t i = 0; i < Values::NUM_PAIRING_TAGS; i++) { + real.pairing_points_tagging.create_pairing_point_tag(); + } + std::vector real_index_of; + for (uint32_t i = 0; i < scratch.get_num_variables(); i++) { + real_index_of.push_back(real.add_variable(scratch.get_variable(i))); + } + values.for_each([&](auto& member) { rebind_to_builder(member, &real, real_index_of, 0); }); + + const Counts scratch_counts = counts(scratch); + const Counts real_counts = counts(real); + + const field_ct product = values.witness * values.scaled; + const bool_ct conjunction = values.flag & values.inverted_flag; + const fq_ct big_square = values.big * values.big; + const G1 doubled = values.point.dbl(); + const cycle_group_ct grumpkin_doubled = values.grumpkin_point.dbl(); + PairingPointsCt fresh(G1::from_witness(&real, g1::affine_element::random_element()), + G1::from_witness(&real, g1::affine_element::random_element())); + values.pairing_points.aggregate(fresh); + + EXPECT_EQ(counts(scratch), scratch_counts); + EXPECT_GT(real.num_gates(), real_counts.gates); + EXPECT_GT(real.get_num_variables(), real_counts.variables); + EXPECT_EQ(product.get_value(), fr(5 * (5 * 3 + 7))); + EXPECT_FALSE(conjunction.get_value()); + expect_only_on(contexts_of(product), &real); + expect_only_on(contexts_of(conjunction), &real); + expect_only_on(contexts_of(big_square), &real); + expect_only_on(contexts_of(doubled), &real); + expect_only_on(contexts_of(grumpkin_doubled), &real); + expect_only_on(contexts_of(values.pairing_points), &real); + EXPECT_EQ(count_contexts_on(values.pairing_points, &scratch), 0U); +} + +TEST_F(BuilderBindingTests, RebindsGoblinPointsOnMega) +{ + using MegaG1 = bn254::Group; + using MegaOutput = recursion::honk::UltraRecursiveVerifierOutput; + + MegaCircuitBuilder scratch; + MegaOutput output; + output.kernel_return_data = MegaG1::from_witness(&scratch, g1::affine_element::random_element()); + output.transcript_hash = field_t::from_witness(&scratch, fr::random_element()); + const auto point = output.kernel_return_data.get_value(); + const auto hash = output.transcript_hash.get_value(); + + MegaCircuitBuilder real; + real.add_variable(fr::random_element()); + std::vector real_index_of; + for (uint32_t i = 0; i < scratch.get_num_variables(); i++) { + real_index_of.push_back(real.add_variable(scratch.get_variable(i))); + } + EXPECT_GT(count_contexts_on(output, &scratch), 0U); + rebind_to_builder(output, &real, real_index_of, 0); + + EXPECT_EQ(count_contexts_on(output, &scratch), 0U); + for (const auto& limb : output.kernel_return_data.x().limbs) { + EXPECT_EQ(limb.get_context(), &real); + } + for (const auto& limb : output.kernel_return_data.y().limbs) { + EXPECT_EQ(limb.get_context(), &real); + } + EXPECT_EQ(output.transcript_hash.get_context(), &real); + EXPECT_EQ(output.kernel_return_data.get_value(), point); + EXPECT_EQ(output.transcript_hash.get_value(), hash); +} + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp index 8d6326f..bbbef9b 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/field/field.hpp @@ -42,6 +42,10 @@ template T* validate_context(const Container& e return result; } +// Visits the builder pointers and witness indices of stdlib values in place (builder_binding.hpp); befriended by every +// value type that holds one. +template struct BuilderBindingWalk; + template class bool_t; template class field_t { public: @@ -58,6 +62,7 @@ template class field_t { template friend class bool_t; template friend class bigfield; template friend void mark_witness_as_used(const field_t& field); + template friend struct BuilderBindingWalk; mutable Builder* context = nullptr; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.cpp index 75ddb1d..d8239bf 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.cpp @@ -12,6 +12,7 @@ #include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" #include "./cycle_group.hpp" +#include "./straus_native_hints.hpp" #include "barretenberg/numeric/general/general.hpp" #include "barretenberg/stdlib/primitives/circuit_builders/circuit_builders_fwd.hpp" #include "barretenberg/stdlib/primitives/plookup/plookup.hpp" @@ -794,6 +795,13 @@ typename cycle_group::batch_mul_internal_output cycle_group::_ native_straus_tables.emplace_back(std::move(table)); } + // Every round adds the same offset generators, so the offset generator accumulator adds their sum once per + // round. + Element offset_generator_sum = Group::point_at_infinity; + for (size_t j = 0; j < num_points; ++j) { + offset_generator_sum += offset_generators[j + 1]; + } + // Perform the Straus algorithm natively to generate the witness values (hints) for all intermediate points Element accumulator = offset_generators[0]; for (size_t i = 0; i < num_rounds; ++i) { @@ -811,10 +819,10 @@ typename cycle_group::batch_mul_internal_output cycle_group::_ const Element point = native_straus_tables[j][slice_value]; accumulator += point; - // Populate hint and update offset generator accumulator + // Populate hint operation_transcript.push_back(accumulator); - offset_generator_accumulator += Element(offset_generators[j + 1]); } + offset_generator_accumulator += offset_generator_sum; } } @@ -1049,40 +1057,34 @@ typename cycle_group::batch_mul_internal_output cycle_group::_ point_tables.emplace_back(context, std::move(precomputed_tables[i])); } - // Compute all intermediate points natively for use as hints in the in-circuit Straus algorithm. - // Using projective coordinates + batch normalize to avoid per-operation modular inversions. - // The per-point lookup tables (point_tables) already hold the precomputed affine entries; we reuse - // them directly rather than rebuilding projective copies. - std::vector operation_transcript; - Element offset_generator_accumulator = offset_generators[0]; - { - // Perform Straus algorithm natively - Element accumulator = offset_generators[0]; - for (size_t i = 0; i < num_rounds; ++i) { - if (i != 0) { - for (size_t j = 0; j < table_bits; ++j) { - accumulator = accumulator.dbl(); - operation_transcript.push_back(accumulator); - offset_generator_accumulator = offset_generator_accumulator.dbl(); - } - } - for (size_t j = 0; j < num_points; ++j) { - auto slice_value = static_cast(scalar_slices[j].slices_native[num_rounds - i - 1]); - const Element point(point_tables[j].get_native_table()[slice_value]); - accumulator += point; - operation_transcript.push_back(accumulator); - offset_generator_accumulator += Element(offset_generators[j + 1]); - } - } - } - - // Batch-normalize all hint points - Element::batch_normalize(operation_transcript.data(), operation_transcript.size()); - std::vector operation_hints; - operation_hints.reserve(operation_transcript.size()); - for (const Element& element : operation_transcript) { - operation_hints.emplace_back(element.x, element.y); + // Compute all intermediate points natively for use as hints in the in-circuit Straus algorithm, in projective + // coordinates to avoid per-operation inversions. The accumulator adds the tables' affine entries with mixed + // additions. + std::vector native_tables(num_points); + std::vector native_slices(num_points); + for (size_t j = 0; j < num_points; ++j) { + native_tables[j] = point_tables[j].get_native_table().data(); + native_slices[j] = scalar_slices[j].slices_native.data(); } + StrausNativeHints native_hints = compute_straus_hints({ .offset_generators = offset_generators, + .tables = native_tables, + .slices = native_slices, + .num_rounds = num_rounds, + .table_bits = table_bits }); + Element* operation_transcript = native_hints.operation_transcript.get(); + + // Normalize the hint points in chunks, one batched inversion per chunk. Affine coordinates are unique, so the + // hint values do not depend on where the chunks start. + std::vector operation_hints(native_hints.transcript_size); + parallel_for_heuristic( + native_hints.transcript_size, + [&](size_t start, size_t end, size_t /*chunk_index*/) { + Element::batch_normalize(operation_transcript + start, end - start); + for (size_t k = start; k < end; ++k) { + operation_hints[k] = AffineElement(operation_transcript[k].x, operation_transcript[k].y); + } + }, + /*heuristic_cost=*/7 * thread_heuristics::FF_MULTIPLICATION_COST); // Execute Straus algorithm in-circuit using plookup reads and precomputed hints AffineElement* hint_ptr = operation_hints.data(); @@ -1105,7 +1107,7 @@ typename cycle_group::batch_mul_internal_output cycle_group::_ } accumulator.set_origin_tag(OriginTag::constant()); - return { accumulator, AffineElement(offset_generator_accumulator) }; + return { accumulator, AffineElement(native_hints.offset_generator_accumulator) }; } /** diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.hpp index f7f4869..22338b5 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group.hpp @@ -228,6 +228,7 @@ template class cycle_group { // Allow straus_lookup_table and straus_plookup_table to access the private constructor for efficiency friend class ::bb::stdlib::straus_lookup_table; friend class ::bb::stdlib::straus_plookup_table; + template friend struct ::bb::stdlib::BuilderBindingWalk; // Private constructor that allows explicit control over infinity flag. // Use public constructors or factory methods instead - they auto-detect infinity from coordinates. diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_fixed_batch_mul_hints.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_fixed_batch_mul_hints.test.cpp new file mode 100644 index 0000000..a0b17f8 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_fixed_batch_mul_hints.test.cpp @@ -0,0 +1,76 @@ +#include "barretenberg/circuit_checker/circuit_checker.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/stdlib/primitives/group/cycle_group.hpp" + +#include +#include +#include +#include + +namespace bb::stdlib { +namespace { + +using Builder = UltraCircuitBuilder; +using cycle_group_ct = cycle_group; +using cycle_scalar_ct = cycle_group_ct::cycle_scalar; +using AffineElement = cycle_group_ct::AffineElement; +using ScalarField = cycle_scalar_ct::ScalarField; + +std::vector fixed_batch_mul_witness(const std::vector& points, + const std::vector& scalars) +{ + Builder builder; + std::vector constant_points; + std::vector witness_scalars; + for (size_t i = 0; i < points.size(); ++i) { + constant_points.emplace_back(points[i]); + witness_scalars.push_back(cycle_scalar_ct::from_witness(&builder, scalars[i])); + } + cycle_group_ct::fixed_batch_mul(constant_points, witness_scalars, /*table_bits=*/8); + EXPECT_TRUE(CircuitChecker::check(builder)); + return builder.get_variables(); +} + +} // namespace + +// The native hints are normalized in chunks whose boundaries follow the thread count, which must not change any +// witness value. +TEST(CycleGroupFixedBatchMulHints, WitnessDoesNotDependOnThreadCount) +{ + constexpr size_t num_points = 256; + const auto points = bb::grumpkin::g1::derive_generators("cycle_group_fixed_batch_mul_hints_test", num_points); + auto& engine = numeric::get_debug_randomness(); + std::vector scalars(num_points); + for (auto& scalar : scalars) { + scalar = ScalarField::random_element(&engine); + } + + const auto reference = fixed_batch_mul_witness(points, scalars); +#ifdef NO_MULTITHREADING + // The thread count cannot be changed in a build without threads: check that the witness is reproducible. + constexpr std::array concurrencies{ 1 }; +#else + const size_t original_concurrency = get_num_cpus(); + constexpr std::array concurrencies{ 1, 5 }; +#endif + for (const size_t concurrency : concurrencies) { +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(concurrency); +#endif + const auto witness = fixed_batch_mul_witness(points, scalars); + + EXPECT_EQ(witness.size(), reference.size()); + size_t num_mismatches = 0; + for (size_t i = 0; i < std::min(witness.size(), reference.size()); ++i) { + num_mismatches += static_cast(witness[i] != reference[i]); + } + EXPECT_EQ(num_mismatches, 0U) << "concurrency " << concurrency; + } +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(original_concurrency); +#endif +} + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators.hpp index be2771a..486a91c 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators.hpp @@ -1,8 +1,12 @@ #pragma once +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/thread.hpp" #include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" +#include #include +#include #include #include #include @@ -16,7 +20,8 @@ namespace bb::stdlib { * * Generator `i` depends only on the domain separator and `i`, so every request returns the same prefix. Derivation * costs ~65us per generator, so blocks are memoized; they are append-only and retained, which keeps a span valid - * after another thread has grown the store. + * after another thread has grown the store. A new block copies the generators already held and derives only the new + * indices, in parallel. */ template class cycle_group_offset_generators { public: @@ -30,7 +35,9 @@ template class cycle_group_offset_generators { */ static const cycle_group_offset_generators& default_generators() { - static const cycle_group_offset_generators instance; + // Never destroyed: freeing the memoized generators at exit only delays the exit. + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) + static const cycle_group_offset_generators& instance = *new cycle_group_offset_generators(); return instance; } @@ -46,7 +53,9 @@ template class cycle_group_offset_generators { while (block_size < num_generators) { block_size *= 2; } - blocks.push_back(std::make_unique(Group::derive_generators(DOMAIN_SEPARATOR, block_size, 0))); + const std::span held = + blocks.empty() ? std::span{} : std::span(*blocks.back()); + blocks.push_back(std::make_unique(derive_block(held, block_size))); } return { blocks.back()->data(), num_generators }; @@ -58,6 +67,27 @@ template class cycle_group_offset_generators { // Doubling keeps a circuit built from many differently sized MSMs to a handful of derivations. static constexpr size_t MIN_BLOCK_SIZE = 32; + /** + * @brief The first `block_size` generators, given the first `held.size()` of them. + */ + static Block derive_block(const std::span held, const size_t block_size) + { + BB_ASSERT(block_size - 1 <= static_cast(UINT32_MAX), + "cycle_group_offset_generators: generator index exceeds uint32 range"); + Block block(block_size); + std::copy(held.begin(), held.end(), block.begin()); + + const std::vector domain_separator_bytes(DOMAIN_SEPARATOR.begin(), DOMAIN_SEPARATOR.end()); + const auto domain_hash = Group::hash_domain_separator(domain_separator_bytes); + const size_t num_held = held.size(); + // Each index is a pure function written to its own slot, so the block does not depend on scheduling. + parallel_for(block_size - num_held, [&](size_t i) { + const size_t index = num_held + i; + block[index] = Group::derive_generator(domain_hash, static_cast(index)); + }); + return block; + } + mutable std::mutex mutex; mutable std::vector> blocks; }; diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators_growth.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators_growth.test.cpp new file mode 100644 index 0000000..1046c7f --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/cycle_group_offset_generators_growth.test.cpp @@ -0,0 +1,33 @@ +#include "cycle_group_offset_generators.hpp" + +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" + +#include + +namespace bb::stdlib { + +using OffsetGenerators = cycle_group_offset_generators; + +// A grown block reuses the generators already held and derives the rest separately; both parts must match a single +// serial derivation. +TEST(CycleGroupOffsetGeneratorsGrowth, GrownBlockMatchesSerialDerivation) +{ + constexpr size_t num_generators = 100; + const auto expected = + grumpkin::g1::derive_generators(OffsetGenerators::DOMAIN_SEPARATOR, num_generators, /*starting_index=*/0); + + const OffsetGenerators generators; + // The first request derives a small block, so the second one grows the store from it. + const auto held = generators.get(3); + const auto grown = generators.get(num_generators); + + ASSERT_EQ(grown.size(), num_generators); + for (size_t i = 0; i < held.size(); ++i) { + EXPECT_EQ(held[i], expected[i]); + } + for (size_t i = 0; i < num_generators; ++i) { + EXPECT_EQ(grown[i], expected[i]); + } +} + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.cpp new file mode 100644 index 0000000..6d0fd9f --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.cpp @@ -0,0 +1,158 @@ +#include "barretenberg/stdlib/primitives/group/straus_native_hints.hpp" + +#include "barretenberg/common/thread.hpp" +#include "barretenberg/numeric/general/general.hpp" + +#include +#include + +namespace bb::stdlib { +namespace { + +using Group = bb::grumpkin::g1; +using Element = Group::element; +using AffineElement = Group::affine_element; + +// Fixed so that the chunks, and with them every intermediate value, do not depend on the thread count. +constexpr size_t POINTS_PER_CHUNK = 1024; + +const AffineElement& table_read(const StrausTableReads& reads, const size_t round, const size_t point) +{ + return reads.tables[point][static_cast(reads.slices[point][reads.num_rounds - 1 - round])]; +} + +StrausNativeHints allocate_hints(const StrausTableReads& reads) +{ + StrausNativeHints hints; + hints.transcript_size = (reads.num_rounds * reads.tables.size()) + ((reads.num_rounds - 1) * reads.table_bits); + hints.operation_transcript = std::make_unique_for_overwrite(hints.transcript_size); + // Overwritten by the caller, but a return that is not elided copies it. + hints.offset_generator_accumulator = Group::point_at_infinity; + return hints; +} + +} // namespace + +bool straus_hints_use_threads(const size_t num_reads) +{ + return num_reads >= STRAUS_HINTS_MIN_PARALLEL_READS && get_num_cpus() >= STRAUS_HINTS_MIN_THREADS; +} + +StrausNativeHints compute_straus_hints(const StrausTableReads& reads) +{ + return straus_hints_use_threads(reads.num_rounds * reads.tables.size()) ? compute_straus_hints_parallel(reads) + : compute_straus_hints_serial(reads); +} + +StrausNativeHints compute_straus_hints_serial(const StrausTableReads& reads) +{ + const size_t num_points = reads.tables.size(); + StrausNativeHints hints = allocate_hints(reads); + Element* transcript = hints.operation_transcript.get(); + size_t num_operations = 0; + + // Every round adds the same offset generators, so the offset generator accumulator adds their sum once per round. + Element offset_generator_sum = Group::point_at_infinity; + for (size_t j = 0; j < num_points; ++j) { + offset_generator_sum += reads.offset_generators[j + 1]; + } + + Element accumulator = reads.offset_generators[0]; + Element offset_generator_accumulator = reads.offset_generators[0]; + for (size_t i = 0; i < reads.num_rounds; ++i) { + if (i != 0) { + for (size_t j = 0; j < reads.table_bits; ++j) { + accumulator = accumulator.dbl(); + transcript[num_operations++] = accumulator; + offset_generator_accumulator = offset_generator_accumulator.dbl(); + } + } + for (size_t j = 0; j < num_points; ++j) { + accumulator += table_read(reads, i, j); + transcript[num_operations++] = accumulator; + } + offset_generator_accumulator += offset_generator_sum; + } + hints.offset_generator_accumulator = offset_generator_accumulator; + return hints; +} + +StrausNativeHints compute_straus_hints_parallel(const StrausTableReads& reads) +{ + const size_t num_points = reads.tables.size(); + const size_t num_rounds = reads.num_rounds; + const size_t table_bits = reads.table_bits; + const size_t chunks_per_round = numeric::ceil_div(num_points, POINTS_PER_CHUNK); + const size_t num_chunks = num_rounds * chunks_per_round; + // Round i's additions start at entry i * (num_points + table_bits), right after its doublings. + const auto first_addition = [&](const size_t round) { return round * (num_points + table_bits); }; + const auto first_point = [&](const size_t chunk) { return (chunk % chunks_per_round) * POINTS_PER_CHUNK; }; + const auto end_point = [&](const size_t chunk) { + return std::min(first_point(chunk) + POINTS_PER_CHUNK, num_points); + }; + + std::vector offset_generator_sums(chunks_per_round); + parallel_for(chunks_per_round, [&](const size_t chunk) { + Element sum = Group::point_at_infinity; + for (size_t j = first_point(chunk); j < end_point(chunk); ++j) { + sum += reads.offset_generators[j + 1]; + } + offset_generator_sums[chunk] = sum; + }); + std::vector chunk_sums(num_chunks); + parallel_for(num_chunks, [&](const size_t chunk) { + const size_t round = chunk / chunks_per_round; + Element sum = Group::point_at_infinity; + for (size_t j = first_point(chunk); j < end_point(chunk); ++j) { + sum += table_read(reads, round, j); + } + chunk_sums[chunk] = sum; + }); + + StrausNativeHints hints = allocate_hints(reads); + Element* transcript = hints.operation_transcript.get(); + Element offset_generator_sum = Group::point_at_infinity; + for (const Element& sum : offset_generator_sums) { + offset_generator_sum += sum; + } + std::vector chunk_starts(num_chunks); + bool any_infinity = false; + Element accumulator = reads.offset_generators[0]; + Element offset_generator_accumulator = reads.offset_generators[0]; + for (size_t i = 0; i < num_rounds; ++i) { + if (i != 0) { + for (size_t j = 0; j < table_bits; ++j) { + accumulator = accumulator.dbl(); + transcript[first_addition(i) - table_bits + j] = accumulator; + any_infinity |= accumulator.is_point_at_infinity(); + offset_generator_accumulator = offset_generator_accumulator.dbl(); + } + } + for (size_t k = 0; k < chunks_per_round; ++k) { + chunk_starts[(i * chunks_per_round) + k] = accumulator; + accumulator += chunk_sums[(i * chunks_per_round) + k]; + } + offset_generator_accumulator += offset_generator_sum; + } + hints.offset_generator_accumulator = offset_generator_accumulator; + + std::vector chunk_has_infinity(num_chunks, 0); + parallel_for(num_chunks, [&](const size_t chunk) { + const size_t round = chunk / chunks_per_round; + Element* round_additions = transcript + first_addition(round); + Element value = chunk_starts[chunk]; + bool has_infinity = false; + for (size_t j = first_point(chunk); j < end_point(chunk); ++j) { + value += table_read(reads, round, j); + round_additions[j] = value; + has_infinity |= value.is_point_at_infinity(); + } + chunk_has_infinity[chunk] = static_cast(has_infinity); + }); + if (any_infinity || std::ranges::any_of(chunk_has_infinity, [](const uint8_t flag) { return flag != 0; })) { + return compute_straus_hints_serial(reads); + } + return hints; +} + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.hpp new file mode 100644 index 0000000..cacfa82 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" + +#include +#include +#include +#include + +namespace bb::stdlib { + +/** + * @brief The native table reads of the Straus loop of a fixed-base batch multiplication. + * @details Round i of num_rounds reads, for each point j in order, tables[j][slices[j][num_rounds - 1 - i]]: tables[j] + * holds the 2^table_bits entries of point j and slices[j] the num_rounds slices of its scalar, least significant first. + * offset_generators[0] starts the accumulator, and offset_generators[j + 1] is the offset in every entry of tables[j]. + */ +struct StrausTableReads { + std::span offset_generators; + std::span tables; + std::span slices; + size_t num_rounds = 0; + size_t table_bits = 0; +}; + +/** + * @brief The native values the in-circuit Straus loop takes as hints. + * @details operation_transcript[k] is the accumulator after the k-th operation of the loop: in each round after the + * first, table_bits doublings, then one addition per point. offset_generator_accumulator is the sum of the offset + * generator terms the final accumulator carries. + */ +struct StrausNativeHints { + std::unique_ptr operation_transcript; + size_t transcript_size = 0; + bb::grumpkin::g1::element offset_generator_accumulator; +}; + +/** + * Below this many table reads, or with fewer threads than STRAUS_HINTS_MIN_THREADS, the hints are computed serially. + * The threaded computation adds every table entry twice, so it needs about four threads to halve the time, and the + * serial chain of 2^16 reads is short against a circuit of that size; the bound also keeps every multiplication but + * the largest on the serial code. + */ +inline constexpr size_t STRAUS_HINTS_MIN_PARALLEL_READS = size_t{ 1 } << 16; +inline constexpr size_t STRAUS_HINTS_MIN_THREADS = 4; + +/** Whether compute_straus_hints uses several threads for num_reads table reads at the current thread count. */ +bool straus_hints_use_threads(size_t num_reads); + +/** The hints, computed serially or on several threads by straus_hints_use_threads; the values do not depend on it. */ +StrausNativeHints compute_straus_hints(const StrausTableReads& reads); + +/** The hints, computed one operation after the other. */ +StrausNativeHints compute_straus_hints_serial(const StrausTableReads& reads); + +/** + * @brief The hints, computed on several threads. + * @details Each round's reads are cut into chunks of a fixed number of points. The chunk sums are computed in parallel, + * the accumulator before each chunk follows serially from them and the doublings, and each chunk then fills its + * entries in parallel. Group addition is associative and every formula used is complete on Grumpkin (infinity, equal + * and opposite points), so every entry is the serial entry's group element, and its affine coordinates, which are + * what becomes a hint, are unique. A point at infinity has no unique coordinates and its hint carries its raw + * projective ones, so if any entry is at infinity the serial computation is returned instead. + */ +StrausNativeHints compute_straus_hints_parallel(const StrausTableReads& reads); + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.test.cpp new file mode 100644 index 0000000..f33dde4 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/group/straus_native_hints.test.cpp @@ -0,0 +1,316 @@ +#include "barretenberg/stdlib/primitives/group/straus_native_hints.hpp" +#include "barretenberg/circuit_checker/circuit_checker.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/numeric/general/general.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "barretenberg/stdlib/primitives/group/cycle_group.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp" + +#include +#include +#include +#include +#include + +namespace bb::stdlib { +namespace { + +using Builder = UltraCircuitBuilder; +using cycle_group_ct = cycle_group; +using cycle_scalar_ct = cycle_group_ct::cycle_scalar; +using Group = bb::grumpkin::g1; +using Element = Group::element; +using AffineElement = Group::affine_element; + +constexpr size_t NUM_ROUNDS = 32; +constexpr size_t TABLE_BITS = 2; +constexpr size_t TABLE_SIZE = size_t{ 1 } << TABLE_BITS; +// The parallel code cuts each round into chunks of 1024 points; these cases end in a partial chunk. +constexpr size_t SMALL_NUM_POINTS = 5; +constexpr size_t LARGE_NUM_POINTS = 2053; +static_assert(SMALL_NUM_POINTS * NUM_ROUNDS < STRAUS_HINTS_MIN_PARALLEL_READS); +static_assert(LARGE_NUM_POINTS * NUM_ROUNDS >= STRAUS_HINTS_MIN_PARALLEL_READS); + +// Points share a few tables; the computation does not care which table a pointer names. +struct Reads { + std::vector offset_generators; + std::vector> distinct_tables; + std::vector> scalar_slices; + std::vector tables; + std::vector slices; + + void point_to_tables(const std::vector& table_of_point) + { + for (size_t j = 0; j < table_of_point.size(); ++j) { + tables.push_back(distinct_tables[table_of_point[j]].data()); + slices.push_back(scalar_slices[j].data()); + } + } + StrausTableReads reads() const + { + return { .offset_generators = offset_generators, + .tables = tables, + .slices = slices, + .num_rounds = NUM_ROUNDS, + .table_bits = TABLE_BITS }; + } +}; + +std::vector> random_slices(const size_t num_points) +{ + auto& engine = numeric::get_debug_randomness(); + std::vector> slices(num_points, std::vector(NUM_ROUNDS)); + for (auto& point_slices : slices) { + for (auto& slice : point_slices) { + slice = engine.get_random_uint64() % TABLE_SIZE; + } + } + return slices; +} + +// Tables as the plookup batch multiplication builds them: offset generator + k * base point. +Reads random_reads(const size_t num_points) +{ + constexpr size_t num_tables = 4; + const auto offset_generators = cycle_group_ct::OffsetGenerators::default_generators().get(num_points + 1); + const auto bases = Group::derive_generators("straus_native_hints_test", num_tables); + Reads reads{ .offset_generators = { offset_generators.begin(), offset_generators.end() }, + .distinct_tables = std::vector>(num_tables), + .scalar_slices = random_slices(num_points) }; + for (size_t t = 0; t < num_tables; ++t) { + Element entry = offset_generators[t + 1]; + for (auto& table_entry : reads.distinct_tables[t]) { + table_entry = AffineElement(entry); + entry += bases[t]; + } + } + std::vector table_of_point(num_points); + for (size_t j = 0; j < num_points; ++j) { + table_of_point[j] = j % num_tables; + } + reads.point_to_tables(table_of_point); + return reads; +} + +/** + * The serial code's edge cases, from an accumulator starting at P: adding P doubles it and adding a table entry at + * infinity keeps it; with `cancel`, adding -P twice takes it to infinity, a transcript entry at infinity, from which + * adding P restarts it. In the last round, at the start of the second chunk P then -P cancels inside a chunk sum and + * Q + Q doubles there, and the third chunk, which ends the round, sums to infinity through a table entry at infinity. + */ +Reads edge_reads(const size_t num_points, const bool cancel) +{ + const auto points = Group::derive_generators("straus_native_hints_edge_test", 2); + const AffineElement& p = points[0]; + const AffineElement& q = points[1]; + constexpr uint64_t P = 0; + constexpr uint64_t INFINITY_ENTRY = 1; + constexpr uint64_t MINUS_P = 2; + constexpr uint64_t Q = 3; + Reads reads{ .offset_generators = std::vector(num_points + 1, q), + .distinct_tables = { { p, Group::affine_point_at_infinity, -p, q } }, + .scalar_slices = random_slices(num_points) }; + reads.offset_generators[0] = p; + // Round 0 reads each point's most significant slice. + const std::vector first_round = { P, INFINITY_ENTRY, MINUS_P, cancel ? MINUS_P : Q, P }; + for (size_t j = 0; j < first_round.size(); ++j) { + reads.scalar_slices[j][NUM_ROUNDS - 1] = first_round[j]; + } + if (num_points == LARGE_NUM_POINTS) { + const std::array chunk_start = { P, MINUS_P, Q, Q }; + for (size_t j = 0; j < chunk_start.size(); ++j) { + reads.scalar_slices[1024 + j][0] = chunk_start[j]; + } + const std::array last_chunk = { P, MINUS_P, INFINITY_ENTRY, P, MINUS_P }; + for (size_t j = 0; j < last_chunk.size(); ++j) { + reads.scalar_slices[2048 + j][0] = last_chunk[j]; + } + } + reads.point_to_tables(std::vector(num_points, 0)); + return reads; +} + +/** + * Round 0 reaches infinity in its third chunk, which the threaded code replays from an accumulator rebuilt from the + * first two chunks' sums: every point reads a table entry at infinity, which keeps the accumulator at P, except the + * one before last, which reads -P. The entry at infinity carries a nonzero raw y, so the serial accumulator ends the + * round with that y, which round 1's doublings keep, while the threaded code rebuilds the round's end from its last + * chunk's sum, -P, and gets infinity in its own encoding. Only the serial fallback makes those doubling hints agree. + */ +Reads later_chunk_infinity_reads() +{ + const auto points = Group::derive_generators("straus_native_hints_edge_test", 2); + const AffineElement& p = points[0]; + const AffineElement& q = points[1]; + AffineElement infinity = Group::affine_point_at_infinity; + infinity.y = bb::grumpkin::fq(7); + constexpr uint64_t INFINITY_ENTRY = 1; + constexpr uint64_t MINUS_P = 2; + Reads reads{ .offset_generators = std::vector(LARGE_NUM_POINTS + 1, q), + .distinct_tables = { { p, infinity, -p, q } }, + .scalar_slices = random_slices(LARGE_NUM_POINTS) }; + reads.offset_generators[0] = p; + for (size_t j = 0; j < LARGE_NUM_POINTS; ++j) { + reads.scalar_slices[j][NUM_ROUNDS - 1] = j == LARGE_NUM_POINTS - 2 ? MINUS_P : INFINITY_ENTRY; + } + reads.point_to_tables(std::vector(LARGE_NUM_POINTS, 0)); + return reads; +} + +// The affine hints the batch multiplication makes of a transcript, including the raw coordinates of infinity. +std::vector affine_hints(const StrausNativeHints& hints) +{ + std::vector transcript(hints.operation_transcript.get(), + hints.operation_transcript.get() + hints.transcript_size); + Element::batch_normalize(transcript.data(), transcript.size()); + std::vector affine(transcript.size()); + for (size_t k = 0; k < transcript.size(); ++k) { + affine[k] = AffineElement(transcript[k].x, transcript[k].y); + } + return affine; +} + +bool same_hint(const AffineElement& actual, const AffineElement& expected) +{ + if (actual.is_point_at_infinity() || expected.is_point_at_infinity()) { + return std::ranges::equal(actual.x.data, expected.x.data) && std::ranges::equal(actual.y.data, expected.y.data); + } + return actual == expected; +} + +void expect_same_hints(const StrausNativeHints& actual, const StrausNativeHints& expected, const std::string& label) +{ + const auto actual_hints = affine_hints(actual); + const auto expected_hints = affine_hints(expected); + ASSERT_EQ(actual_hints.size(), expected_hints.size()) << label; + size_t num_mismatches = 0; + for (size_t k = 0; k < actual_hints.size(); ++k) { + num_mismatches += static_cast(!same_hint(actual_hints[k], expected_hints[k])); + } + EXPECT_EQ(num_mismatches, 0U) << label; + EXPECT_EQ(AffineElement(actual.offset_generator_accumulator), AffineElement(expected.offset_generator_accumulator)) + << label; +} + +Builder build_batch_mul(const std::vector& points, const std::vector& scalars) +{ + Builder builder; + std::vector constant_points; + std::vector witness_scalars; + for (size_t i = 0; i < points.size(); ++i) { + constant_points.emplace_back(points[i]); + witness_scalars.push_back(cycle_scalar_ct::from_witness(&builder, scalars[i])); + } + cycle_group_ct::fixed_batch_mul(constant_points, witness_scalars, /*table_bits=*/4); + return builder; +} + +#if !defined(NO_MULTITHREADING) && !defined(OMP_MULTITHREADING) +/** + * @brief Gives the calling thread's parallel_for a fresh pool of `width` threads, itself included, and on destruction + * restores the width it found, again with a fresh pool. + * @details The pool is made by the first parallel_for after a reset, at the width of that moment; a width change alone + * leaves an existing pool as it is. + */ +class FreshParallelForPool { + public: + explicit FreshParallelForPool(const size_t width) + : original_width_(get_num_cpus()) + { + reset(width); + } + FreshParallelForPool(const FreshParallelForPool&) = delete; + FreshParallelForPool(FreshParallelForPool&&) = delete; + FreshParallelForPool& operator=(const FreshParallelForPool&) = delete; + FreshParallelForPool& operator=(FreshParallelForPool&&) = delete; + ~FreshParallelForPool() { reset(original_width_); } + + private: + static void reset(const size_t width) + { + set_parallel_for_concurrency(width); + parallel_for_stop_workers(); + } + + size_t original_width_; +}; +#endif + +} // namespace + +TEST(StrausNativeHints, ThreadedHintsEqualTheSerialOnes) +{ + struct Case { + std::string label; + Reads reads; + bool has_infinity_entry; + }; + std::vector cases; + cases.reserve(7); + cases.push_back({ "random, small", random_reads(SMALL_NUM_POINTS), false }); + cases.push_back({ "random, large", random_reads(LARGE_NUM_POINTS), false }); + for (const size_t num_points : { SMALL_NUM_POINTS, LARGE_NUM_POINTS }) { + for (const bool cancel : { false, true }) { + cases.push_back({ (cancel ? "edges with a transcript entry at infinity, " : "edges, ") + + std::string(num_points == SMALL_NUM_POINTS ? "small" : "large"), + edge_reads(num_points, cancel), + cancel }); + } + } + cases.push_back({ "a round ending at infinity in a later chunk", later_chunk_infinity_reads(), true }); + for (const Case& test_case : cases) { + const StrausTableReads reads = test_case.reads.reads(); + const StrausNativeHints serial = compute_straus_hints_serial(reads); + const auto serial_hints = affine_hints(serial); + EXPECT_EQ( + std::ranges::any_of(serial_hints, [](const AffineElement& hint) { return hint.is_point_at_infinity(); }), + test_case.has_infinity_entry) + << test_case.label; + expect_same_hints(compute_straus_hints_parallel(reads), serial, test_case.label + ", threaded"); + expect_same_hints(compute_straus_hints(reads), serial, test_case.label + ", dispatched"); + } +} + +// A pool of one thread computes the hints serially and larger pools in parallel; the circuits must be the same. +TEST(StrausNativeHints, LargeBatchMulCircuitDoesNotDependOnThreadCount) +{ + constexpr size_t table_bits = 4; + constexpr size_t num_points = 1025; + constexpr size_t num_reads = numeric::ceil_div(cycle_scalar_ct::NUM_BITS, table_bits) * num_points; + static_assert(num_reads >= STRAUS_HINTS_MIN_PARALLEL_READS); + const auto points = Group::derive_generators("straus_native_hints_circuit_test", num_points); + auto& engine = numeric::get_debug_randomness(); + std::vector scalars(num_points); + for (auto& scalar : scalars) { + scalar = bb::grumpkin::fr::random_element(&engine); + } + // A zero scalar reads every table's first entry, its offset generator. + scalars[5] = 0; + +#if defined(NO_MULTITHREADING) || defined(OMP_MULTITHREADING) + const Builder reference = build_batch_mul(points, scalars); + EXPECT_TRUE(CircuitChecker::check(reference)); + GTEST_SKIP() << "builds without threads or with OpenMP have no parallel_for pool whose width the test can set"; +#else + // After each build the pool it ran on is still the calling thread's, so its worker count shows the build's width. + const size_t original_width = get_num_cpus(); + const Builder reference = [&] { + const FreshParallelForPool pool(1); + EXPECT_FALSE(straus_hints_use_threads(num_reads)); + Builder built = build_batch_mul(points, scalars); + EXPECT_EQ(parallel_for_num_workers(), 0U); + return built; + }(); + EXPECT_TRUE(CircuitChecker::check(reference)); + for (const size_t width : { size_t{ 4 }, std::max(original_width, 16) }) { + SCOPED_TRACE("width " + std::to_string(width)); + const FreshParallelForPool pool(width); + EXPECT_TRUE(straus_hints_use_threads(num_reads)); + const Builder builder = build_batch_mul(points, scalars); + EXPECT_EQ(parallel_for_num_workers(), width - 1); + test_utils::expect_same_builder(builder, reference); + } +#endif +} + +} // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.cpp index b032353..143b098 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.cpp @@ -8,6 +8,7 @@ #include "barretenberg/stdlib/primitives/circuit_builders/circuit_builders.hpp" #include "barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.hpp" #include "barretenberg/stdlib_circuit_builders/plookup_tables/types.hpp" +#include namespace bb::stdlib { @@ -15,6 +16,60 @@ using plookup::ColumnIdx; using plookup::MultiTableId; using namespace bb; +namespace { +// Selects the last row of a column in read_selected_lookup_rows. +constexpr size_t LAST_LOOKUP_ROW = std::numeric_limits::max(); + +// The builders still generate every lookup witness and gate. Only the returned field_t wrappers +// are selected: constructing or tagging a wrapper does not modify its builder or witness value. +template +std::array, N> read_selected_lookup_rows(const MultiTableId id, + const field_t& key_a, + const field_t& key_b, + const bool is_2_to_1_lookup, + const std::array& columns, + const std::array& rows) +{ + Builder* ctx = key_a.get_context() ? key_a.get_context() : key_b.get_context(); + const auto lookup_data = + plookup::get_lookup_accumulators(id, key_a.get_value(), key_b.get_value(), is_2_to_1_lookup); + const auto row = [&](size_t i) { + const size_t num_rows = lookup_data[columns[i]].size(); + BB_ASSERT_DEBUG(rows[i] == LAST_LOOKUP_ROW || rows[i] < num_rows); + return rows[i] == LAST_LOOKUP_ROW ? num_rows - 1 : rows[i]; + }; + std::array, N> result; + if (key_a.is_constant() && (key_b.is_constant() || !is_2_to_1_lookup)) { + for (size_t i = 0; i < N; ++i) { + result[i] = field_t(ctx, lookup_data[columns[i]][row(i)]); + } + return result; + } + + // Keep the normalization and constant-witness operations in the same order as the full API. + uint32_t lhs_index = key_a.get_witness_index(); + uint32_t rhs_index = key_b.get_witness_index(); + if (key_a.is_constant()) { + lhs_index = ctx->put_constant_variable(key_a.get_value()); + } + if (key_b.is_constant() && is_2_to_1_lookup) { + rhs_index = ctx->put_constant_variable(key_b.get_value()); + } + auto key_b_witness = std::make_optional(rhs_index); + if (rhs_index == stdlib::IS_CONSTANT) { + key_b_witness = std::nullopt; + } + const auto accumulator_witnesses = + ctx->create_gates_from_plookup_accumulators(id, lookup_data, lhs_index, key_b_witness); + const auto merged_tag = OriginTag(key_a.get_origin_tag(), key_b.get_origin_tag()); + for (size_t i = 0; i < N; ++i) { + result[i] = field_t::from_witness_index(ctx, accumulator_witnesses[columns[i]][row(i)]); + result[i].set_origin_tag(merged_tag); + } + return result; +} +} // namespace + template plookup::ReadData> plookup_read::get_lookup_accumulators(const MultiTableId id, const field_t& key_a, @@ -74,9 +129,14 @@ template std::pair, field_t> plookup_read::read_pair_from_table(const MultiTableId id, const field_t& key) { +#ifndef __wasm__ + auto result = read_selected_lookup_rows(id, key, 0, false, { ColumnIdx::C2, ColumnIdx::C3 }, { 0, 0 }); + return { std::move(result[0]), std::move(result[1]) }; +#else const auto lookup = get_lookup_accumulators(id, key); return { lookup[ColumnIdx::C2][0], lookup[ColumnIdx::C3][0] }; +#endif } template @@ -84,20 +144,86 @@ field_t plookup_read::read_from_2_to_1_table(const MultiTableI const field_t& key_a, const field_t& key_b) { +#ifndef __wasm__ + auto result = read_selected_lookup_rows(id, key_a, key_b, true, { ColumnIdx::C3 }, { 0 }); + return std::move(result[0]); +#else const auto lookup = get_lookup_accumulators(id, key_a, key_b, /*is_2_to_1_lookup=*/true); return lookup[ColumnIdx::C3][0]; +#endif } template field_t plookup_read::read_from_1_to_2_table(const MultiTableId id, const field_t& key_a) { +#ifndef __wasm__ + auto result = read_selected_lookup_rows(id, key_a, 0, false, { ColumnIdx::C2 }, { 0 }); + return std::move(result[0]); +#else const auto lookup = get_lookup_accumulators(id, key_a); return lookup[ColumnIdx::C2][0]; +#endif +} + +#ifndef __wasm__ +// Return the reconstructed second column and the final third-column slice, without materializing +// the other circuit-field wrappers. The underlying lookup queries, witnesses and gates are unchanged. +template +std::pair, field_t> plookup_read::read_first_and_last_from_table( + const MultiTableId id, const field_t& key) +{ + auto result = read_selected_lookup_rows( + id, key, 0, false, { ColumnIdx::C2, ColumnIdx::C3 }, { 0, LAST_LOOKUP_ROW }); + return { std::move(result[0]), std::move(result[1]) }; +} +#endif + +template +template +std::array, N> plookup_read::read_rows_from_table(const MultiTableId id, + const field_t& key, + const std::array& columns, + const std::array& rows) +{ + return read_selected_lookup_rows(id, key, 0, false, columns, rows); } template class plookup_read; // Plookup-backed: only the arithmetizations that keep the lookup gate. INSTANTIATE_CLASS_FOR_EACH_MEGA_BUILDER_WITH_LOOKUP(plookup_read) + +// read_rows_from_table for the row counts SHA-256 uses, on every builder SHA-256 is instantiated for (v6.0.0 adds +// MegaAppCircuitBuilder through the macro above). +template std::array, 3> plookup_read::read_rows_from_table<3>( + MultiTableId, + const field_t&, + const std::array&, + const std::array&); +template std::array, 8> plookup_read::read_rows_from_table<8>( + MultiTableId, + const field_t&, + const std::array&, + const std::array&); +template std::array, 3> plookup_read::read_rows_from_table<3>( + MultiTableId, + const field_t&, + const std::array&, + const std::array&); +template std::array, 8> plookup_read::read_rows_from_table<8>( + MultiTableId, + const field_t&, + const std::array&, + const std::array&); +template std::array, 3> plookup_read::read_rows_from_table<3>( + MultiTableId, + const field_t&, + const std::array&, + const std::array&); +template std::array, 8> plookup_read::read_rows_from_table<8>( + MultiTableId, + const field_t&, + const std::array&, + const std::array&); } // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.hpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.hpp index b596167..d450484 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.hpp @@ -33,6 +33,11 @@ template class plookup_read { public: static std::pair read_pair_from_table(const plookup::MultiTableId id, const field_pt& key); +#ifndef __wasm__ + // Select C2[0] and C3[last]; all lookup witnesses and constraints are still generated. + static std::pair read_first_and_last_from_table(const plookup::MultiTableId id, + const field_pt& key); +#endif static field_pt read_from_2_to_1_table(const plookup::MultiTableId id, const field_pt& key_a, @@ -43,5 +48,16 @@ template class plookup_read { const field_pt& key_a, const field_pt& key_b = 0, const bool is_2_to_1_lookup = false); + + /** + * @brief Return lookup[columns[i]][rows[i]] for each i, where lookup = get_lookup_accumulators(id, key). + * @details Creates the same witnesses and gates as get_lookup_accumulators(id, key) but constructs only the + * selected result wrappers. Instantiated for N = 3 and N = 8. + */ + template + static std::array read_rows_from_table(const plookup::MultiTableId id, + const field_pt& key, + const std::array& columns, + const std::array& rows); }; } // namespace bb::stdlib diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.test.cpp index ee9b3cd..6e08804 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.test.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup.test.cpp @@ -1,4 +1,5 @@ #include "plookup.hpp" +#include "barretenberg/serialize/msgpack_impl.hpp" #include "barretenberg/circuit_checker/circuit_checker.hpp" #include "barretenberg/numeric/bitop/rotate.hpp" #include "barretenberg/numeric/bitop/sparse_form.hpp" @@ -632,3 +633,58 @@ TEST(PlookupTests, Sha256InputMultiTablesMatchBasicTableSizes) } } } +#ifndef __wasm__ +TEST(PlookupTests, SelectedNativeResultsMatchFullProjection) +{ + // Each API runs on an independent equal builder, so witness indices and gate state can be compared. + for (size_t api = 0; api < 4; ++api) { + for (size_t mask = 0; mask < (api == 0 ? 4U : 2U); ++mask) { + Builder full_builder; + Builder selected_builder; + const auto make_key = [](Builder& builder, const fr& value, bool witness) { + field_ct key = witness ? field_ct(witness_ct(&builder, value)) : field_ct(&builder, value); + // Exercise normalization of a nontrivial affine witness expression. + return witness ? key * fr(3) + fr(7) : key; + }; + const auto full_a = make_key(full_builder, fr(12345), (mask & 1U) != 0); + const auto selected_a = make_key(selected_builder, fr(12345), (mask & 1U) != 0); + const auto full_b = make_key(full_builder, fr(6789), (mask & 2U) != 0); + const auto selected_b = make_key(selected_builder, fr(6789), (mask & 2U) != 0); + const auto table = api == 0 ? MultiTableId::UINT32_XOR : MultiTableId::KECCAK_FORMAT_INPUT; + const auto full = api == 0 ? plookup_read::get_lookup_accumulators(table, full_a, full_b, true) + : plookup_read::get_lookup_accumulators(table, full_a); + const auto compare = [&](const field_ct& expected, const field_ct& actual) { + EXPECT_EQ(expected.get_value(), actual.get_value()); + EXPECT_TRUE(field_ct::witness_indices_match(expected, actual)); + EXPECT_EQ(expected.is_constant(), actual.is_constant()); + EXPECT_TRUE(expected.is_normalized()); + EXPECT_TRUE(actual.is_normalized()); + EXPECT_EQ(expected.get_origin_tag(), actual.get_origin_tag()); + EXPECT_EQ(actual.get_context(), &selected_builder); + }; + if (api == 0) { + compare(full[ColumnIdx::C3][0], plookup_read::read_from_2_to_1_table(table, selected_a, selected_b)); + } else if (api == 1) { + compare(full[ColumnIdx::C2][0], plookup_read::read_from_1_to_2_table(table, selected_a)); + } else if (api == 2) { + const auto pair = plookup_read::read_pair_from_table(table, selected_a); + compare(full[ColumnIdx::C2][0], pair.first); + compare(full[ColumnIdx::C3][0], pair.second); + } else { + const auto pair = plookup_read::read_first_and_last_from_table(table, selected_a); + compare(full[ColumnIdx::C2][0], pair.first); + compare(full[ColumnIdx::C3].back(), pair.second); + } + EXPECT_EQ(full_builder.get_variables(), selected_builder.get_variables()); + EXPECT_EQ(full_builder.num_gates(), selected_builder.num_gates()); + // The schema records circuit variables, selectors, wires and lookup data. + const auto full_circuit = full_builder.export_circuit(); + const auto selected_circuit = selected_builder.export_circuit(); + EXPECT_EQ(std::string(full_circuit.data(), full_circuit.size()), + std::string(selected_circuit.data(), selected_circuit.size())); + EXPECT_TRUE(CircuitChecker::check(full_builder)); + EXPECT_TRUE(CircuitChecker::check(selected_builder)); + } + } +} +#endif diff --git a/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup_rows.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup_rows.test.cpp new file mode 100644 index 0000000..88bf1ed --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib/primitives/plookup/plookup_rows.test.cpp @@ -0,0 +1,69 @@ +#include "barretenberg/serialize/msgpack_impl.hpp" + +#include "barretenberg/circuit_checker/circuit_checker.hpp" +#include "barretenberg/stdlib/primitives/circuit_builders/circuit_builders.hpp" +#include "plookup.hpp" +#include + +using namespace bb; +using namespace bb::plookup; + +namespace { +using Builder = UltraCircuitBuilder; +using field_ct = stdlib::field_t; +using witness_ct = stdlib::witness_t; +using plookup_read = stdlib::plookup_read; + +// Runs the full read and the selected-row read on two equal builders and requires equal circuits and results. +template +void check_rows_match_full_read(const MultiTableId id, + const std::array& columns, + const std::array& rows) +{ + for (const bool witness_key : { true, false }) { + const auto make_key = [&](Builder& builder) { + const fr value(0x12345678); + // A nontrivial affine witness expression exercises key normalization; 3 * value + 7 < 2^32. + return witness_key ? field_ct(witness_ct(&builder, value)) * fr(3) + fr(7) : field_ct(&builder, value); + }; + Builder full_builder; + Builder rows_builder; + const auto full = plookup_read::get_lookup_accumulators(id, make_key(full_builder)); + const auto selected = plookup_read::read_rows_from_table(id, make_key(rows_builder), columns, rows); + + for (size_t i = 0; i < N; ++i) { + const field_ct& expected = full[columns[i]][rows[i]]; + EXPECT_EQ(expected.get_value(), selected[i].get_value()); + EXPECT_EQ(expected.is_constant(), selected[i].is_constant()); + EXPECT_TRUE(field_ct::witness_indices_match(expected, selected[i])); + EXPECT_EQ(selected[i].get_context(), &rows_builder); + } + EXPECT_EQ(full_builder.get_variables(), rows_builder.get_variables()); + EXPECT_EQ(full_builder.num_gates(), rows_builder.num_gates()); + // The exported circuit records variables, selectors, wires and lookup tables. + const auto full_circuit = full_builder.export_circuit(); + const auto rows_circuit = rows_builder.export_circuit(); + EXPECT_EQ(std::string(full_circuit.data(), full_circuit.size()), + std::string(rows_circuit.data(), rows_circuit.size())); + EXPECT_TRUE(CircuitChecker::check(rows_builder)); + } +} +} // namespace + +TEST(PlookupRows, MatchFullReadForSha256InputTables) +{ + check_rows_match_full_read<3>( + MultiTableId::SHA256_CH_INPUT, { ColumnIdx::C3, ColumnIdx::C2, ColumnIdx::C2 }, { 0, 0, 2 }); + check_rows_match_full_read<3>( + MultiTableId::SHA256_MAJ_INPUT, { ColumnIdx::C3, ColumnIdx::C2, ColumnIdx::C2 }, { 0, 0, 1 }); + check_rows_match_full_read<8>(MultiTableId::SHA256_WITNESS_INPUT, + { ColumnIdx::C1, + ColumnIdx::C2, + ColumnIdx::C3, + ColumnIdx::C1, + ColumnIdx::C2, + ColumnIdx::C3, + ColumnIdx::C2, + ColumnIdx::C3 }, + { 3, 0, 1, 0, 3, 2, 2, 3 }); +} diff --git a/barretenberg/cpp/src/barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp b/barretenberg/cpp/src/barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp index c6e986a..d363453 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp @@ -406,15 +406,26 @@ class RollupIO { * */ static void add_default(Builder& builder) + { + const auto [ipa_polynomial, ipa_challenge] = IPA>::sample_random_opening(); + add_default(builder, ipa_polynomial, ipa_challenge); + }; + + /** + * @brief Add default public inputs, with the IPA claim opening ipa_polynomial at ipa_challenge + * @details Lets a caller draw the opening (IPA::sample_random_opening) separately from building the circuit. + */ + static void add_default(Builder& builder, const bb::Polynomial& ipa_polynomial, const bb::fq& ipa_challenge) { RollupIO inputs; inputs.pairing_inputs = PairingInputs::construct_default(); - auto [stdlib_opening_claim, ipa_proof] = - IPA>::create_random_valid_ipa_claim_and_proof(builder); + auto [stdlib_opening_claim, ipa_proof_task] = + IPA>::create_valid_ipa_claim_deferred(builder, ipa_polynomial, ipa_challenge); + auto ipa_proof = std::move(ipa_proof_task).launch(); inputs.ipa_claim = stdlib_opening_claim; inputs.set_public(); - builder.ipa_proof = ipa_proof; + builder.set_pending_ipa_proof(std::move(ipa_proof)); }; }; } // namespace bb::stdlib::recursion::honk diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/bounded_range_sort.hpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/bounded_range_sort.hpp new file mode 100644 index 0000000..a6588a5 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/bounded_range_sort.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include "barretenberg/common/thread.hpp" + +#include +#include +#include +#include + +namespace bb::range_sort { +/** + * Contiguous chunks of [0, size); chunk c is [begin(c), begin(c + 1)). `run` processes them in parallel when there are + * several. A chunk must write only outputs it owns or positions fixed before the run, so that results do not depend on + * the number of chunks. + */ +class Chunks { + public: + // At most one chunk per CPU, each of at least `min_chunk_size` elements unless there is a single chunk. + static Chunks of_min_size(size_t size, size_t min_chunk_size) + { + return Chunks(size, std::min(size / std::max(min_chunk_size, 1), get_num_cpus())); + } + + // `count` chunks (at least one), some of them empty when `count` exceeds `size`. + static Chunks with_count(size_t size, size_t count) { return Chunks(size, count); } + + size_t count() const { return count_; } + size_t begin(size_t chunk) const + { + return static_cast(static_cast(size_) * static_cast(chunk) / count_); + } + + // Calls body(chunk, begin, end) for every chunk. + template void run(const Body& body) const + { + if (count_ == 1) { + body(size_t{ 0 }, size_t{ 0 }, size_); + return; + } + parallel_for(count_, [&](size_t chunk) { body(chunk, begin(chunk), begin(chunk + 1)); }); + } + + private: + Chunks(size_t size, size_t count) + : size_(size) + , count_(std::max(count, 1)) + {} + + size_t size_; + size_t count_; +}; + +/** + * Sort a large primitive range-value list using its small declared alphabet. + * Return false without changing values when the general sort should handle it. + * Counts use size_t: the number of equal values need not fit in uint32_t. + */ +inline bool try_counting_sort(std::vector& values, uint64_t maximum) +{ + constexpr size_t MAX_ALPHABET = 1U << 16; + constexpr size_t MIN_VALUES = 256; + // Each chunk counts into its own alphabet-sized counters; with at least four values per counter, the counters of + // several chunks take at most half the memory of `values`. + constexpr size_t MIN_CHUNK_VALUES = 1U << 16; + constexpr size_t MIN_VALUES_PER_COUNTER = 4; + if (maximum >= MAX_ALPHABET || values.size() < MIN_VALUES) { + return false; + } + const size_t alphabet = static_cast(maximum) + 1; + if (values.size() < alphabet) { + return false; + } + // Avoid allocating counters for an already sorted valid list. + if (std::is_sorted(values.begin(), values.end())) { + return values.back() <= maximum; + } + const auto chunks = + Chunks::of_min_size(values.size(), std::max(MIN_CHUNK_VALUES, MIN_VALUES_PER_COUNTER * alphabet)); + std::vector counts(chunks.count() * alphabet, 0); + std::vector chunk_out_of_range(chunks.count(), 0); + chunks.run([&](size_t chunk, size_t begin, size_t end) { + size_t* chunk_counts = counts.data() + (chunk * alphabet); + for (size_t i = begin; i < end; ++i) { + if (values[i] > maximum) { + chunk_out_of_range[chunk] = 1; + return; + } + ++chunk_counts[values[i]]; + } + }); + if (std::ranges::any_of(chunk_out_of_range, [](uint8_t out_of_range) { return out_of_range != 0; })) { + return false; // No output writes have occurred: preserve the original invalid-input path. + } + for (size_t chunk = 1; chunk < chunks.count(); ++chunk) { + const size_t* chunk_counts = counts.data() + (chunk * alphabet); + for (size_t value = 0; value < alphabet; ++value) { + counts[value] += chunk_counts[value]; + } + } + size_t position = 0; + for (size_t value = 0; value < alphabet; ++value) { + std::fill_n(values.data() + position, counts[value], static_cast(value)); + position += counts[value]; + } + return true; +} +} // namespace bb::range_sort diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_builder_base.hpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_builder_base.hpp index 10d2f24..a5b72ac 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_builder_base.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_builder_base.hpp @@ -5,7 +5,9 @@ // ===================== #pragma once +#include "barretenberg/common/address_space_reserve.hpp" #include "barretenberg/common/assert.hpp" +#include "barretenberg/common/release_pages.hpp" #include "barretenberg/ecc/curves/bn254/bn254.hpp" #include "barretenberg/ecc/curves/bn254/fr.hpp" #include "barretenberg/ecc/curves/grumpkin/grumpkin.hpp" @@ -13,11 +15,15 @@ #include "barretenberg/public_input_component/public_component_key.hpp" #include "barretenberg/serialize/msgpack.hpp" #include "pairing_points_tagging.hpp" +#include #include #include +#include +#include #include #include +#include namespace bb { static constexpr uint32_t DEFAULT_TAG = 0; @@ -70,6 +76,56 @@ template class CircuitBuilderBase { */ uint32_t get_first_variable_in_class(uint32_t index) const; + /** + * @brief Append `count` variables, each its own real variable carrying `tag`. + * @details Leaves the state of `count` calls of CircuitBuilderBase::add_variable, each followed by setting the tag + * of the new variable to `tag`, where the i-th call adds the value `write_values` assigns to `values[i]`. The + * per-variable vectors also end with the capacities those calls would give them. `write_values(values)` is called + * once with the value slots of the new variables, zero-initialized, and must assign each of them. The virtual + * add_variable is not called. + * @return The index of the first new variable; the others follow it consecutively. + */ + template + uint32_t add_tagged_variables(const size_t count, const uint32_t tag, const WriteValues& write_values) + { + const size_t first = variables.size(); + const size_t new_size = first + count; + reserve_as_appends(variables, new_size); + reserve_as_appends(real_variable_index, new_size); + reserve_as_appends(next_var_index, new_size); + reserve_as_appends(prev_var_index, new_size); + reserve_as_appends(real_variable_tags, new_size); + variables.resize(new_size); + write_values(std::span(variables).subspan(first)); + real_variable_index.resize(new_size); + std::iota(real_variable_index.begin() + static_cast(first), + real_variable_index.end(), + static_cast(first)); + next_var_index.resize(new_size, REAL_VARIABLE); + prev_var_index.resize(new_size, FIRST_VARIABLE_IN_CLASS); + real_variable_tags.resize(new_size, tag); + return static_cast(first); + } + + /** + * @brief Give `vec` the capacity that appending one element at a time up to `size` elements would give it. + * @details Appends double a full vector's capacity (one element for an empty one), saturating at max_size(), under + * libc++ and libstdc++, and `reserve` allocates exactly the requested capacity. A `size` above max_size() makes + * `reserve` throw std::length_error, as the append reaching it would. + */ + template static void reserve_as_appends(std::vector& vec, const size_t size) + { + size_t capacity = vec.capacity(); + if (capacity >= size) { + return; + } + const size_t max_size = vec.max_size(); + while (capacity < size && capacity < max_size) { + capacity = capacity == 0 ? 1 : (capacity > max_size / 2 ? max_size : 2 * capacity); + } + vec.reserve(std::max(capacity, size)); + } + /** * @brief Check whether each variable index points to a witness value in the variables array * @details Any variable whose index does not point to witness value is deemed invalid. This implicitly checks @@ -139,6 +195,33 @@ template class CircuitBuilderBase { bool operator==(const CircuitBuilderBase& other) const = default; + /** + * @brief Whether this builder equals `other` in every member but the variable values, of which only the number + * is compared. + */ + bool equal_except_values(const CircuitBuilderBase& other) const + { + const auto members = [](const CircuitBuilderBase& builder) { + return std::tie(builder._public_inputs, + builder._public_inputs_finalized, + builder.next_var_index, + builder.prev_var_index, + builder._zero_idx, + builder._num_gates, + builder._tau, + builder._current_tag, + builder.real_variable_index, + builder.real_variable_tags, + builder.circuit_finalized, + builder._failed, + builder._err, + builder._is_write_vk_mode, + builder.variable_names, + builder.pairing_points_tagging); + }; + return variables.size() == other.variables.size() && members(*this) == members(other); + } + virtual size_t get_num_finalized_gates() const; virtual size_t get_num_variables() const; @@ -211,6 +294,8 @@ template class CircuitBuilderBase { const std::vector& public_inputs() const { return _public_inputs; }; + bool public_inputs_finalized() const { return _public_inputs_finalized; } + /** * @brief Set the _public_inputs_finalized to true to prevent any new public inputs from being added * @details This is used, for example, for special internal public inputs (like pairing inputs) which we want to @@ -245,6 +330,43 @@ template class CircuitBuilderBase { real_variable_tags.reserve(capacity); } + // Entries reserved per per-variable vector where address space may be reserved: 2^25 x 48 bytes = 1.5 GiB for the + // five with a 32-byte FF. Chosen for address space, not derived from any circuit or input; beyond it the vectors + // grow as std::vector does. + static constexpr size_t VARIABLES_ADDRESS_SPACE_ENTRIES = size_t{ 1 } << 25; + + /** + * @brief Reserve the per-variable vectors for VARIABLES_ADDRESS_SPACE_ENTRIES variables when + * address_space_reservation_allowed() and all five reservations succeed, else for `fallback` as reserve_variables. + */ + void reserve_variables_address_space(size_t fallback) + { + _variables_reservation.value = VariablesReservation::NotAttempted; + if (fallback < VARIABLES_ADDRESS_SPACE_ENTRIES && address_space_reservation_allowed()) { + if (try_reserve_address_space(VARIABLES_ADDRESS_SPACE_ENTRIES, + variables, + real_variable_index, + next_var_index, + prev_var_index, + real_variable_tags)) { + _variables_reservation.value = VariablesReservation::Reserved; + return; + } + _variables_reservation.value = VariablesReservation::Refused; + } + reserve_variables(fallback); + } + + /** + * @brief What the last reserve_variables_address_space call did, which the Ultra ACIR and seed constructors make + * first; not the vectors' current capacity, which free_variables, for one, releases without changing this. + * @details NotAttempted: reservation is not allowed, or the fallback already reaches the reservation (also for a + * builder that never made the call). Refused: try_reserve_address_space returned false, because the allocator + * refused or a vector already had capacity, and the call went on to reserve the fallback. Reserved: otherwise. + */ + enum class VariablesReservation : uint8_t { NotAttempted, Refused, Reserved }; + VariablesReservation variables_reservation() const { return _variables_reservation.value; } + // Disallow add_variable for non-FF types to prevent implicit conversions (specifically, using indices rather // than values) template uint32_t add_variable(const OT& in) = delete; @@ -285,9 +407,33 @@ template class CircuitBuilderBase { // True if we are writing a vk; used to disable certain warnings bool _is_write_vk_mode = false; + // Not part of a builder's identity: builders holding the same circuit are equal whatever their reservation did. + struct VariablesReservationRecord { + VariablesReservation value = VariablesReservation::NotAttempted; + bool operator==(const VariablesReservationRecord& /*other*/) const { return true; } + }; + VariablesReservationRecord _variables_reservation; + protected: std::unordered_map variable_names; + /** + * @brief Adds the storage of the witness values and the copy-constraint bookkeeping to `blocks`, so their pages can + * be released just before they are freed. Each vector qualifies by its capacity, but only its elements are + * released. + */ + template void add_variable_storage_to(Blocks& blocks) noexcept + { + const auto add = [&blocks](std::vector& vec) noexcept { + blocks.add(vec.data(), vec.capacity() * sizeof(T), vec.size() * sizeof(T)); + }; + add(variables); + add(next_var_index); + add(prev_var_index); + add(real_variable_index); + add(real_variable_tags); + } + public: /** * @brief Assign a name to a variable (equivalence class) diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_splice.hpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_splice.hpp new file mode 100644 index 0000000..8dd1b01 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/circuit_splice.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include + +namespace bb { + +/** + * @brief Lets another thread abandon a build on a recording builder: the builder calls check() before each recording. + */ +class SpliceCancellation { + public: + SpliceCancellation() = default; + SpliceCancellation(const SpliceCancellation&) = delete; + SpliceCancellation(SpliceCancellation&&) = delete; + SpliceCancellation& operator=(const SpliceCancellation&) = delete; + SpliceCancellation& operator=(SpliceCancellation&&) = delete; + virtual ~SpliceCancellation() = default; + + /** + * @brief Runs on the recording thread before each recording; a throw abandons the build, whose builder must then + * only be destroyed. + */ + virtual void check() = 0; +}; + +/** + * @brief Selects the builder constructor whose builder records what UltraCircuitBuilder_::splice must replay of it. + */ +struct SpliceRecording { + // Checked before each recording when set; it must outlive the builder. + SpliceCancellation* cancellation = nullptr; +}; + +/** + * @brief What a builder constructed with SpliceRecording records of its own construction: the changes to copy cycles + * and tags in order, and where each new constant and range list put the rows a splice may drop. + */ +struct SpliceLog { + struct Event { + enum class Kind : uint8_t { + AssertEqual, // assert_equal(a, b) + Tag, // the class of variable a takes tag b + }; + Kind kind; + uint32_t a; + uint32_t b; + }; + // A constant created on a cache miss, with the position of its fixing row and of its used-witness entry. + struct Constant { + uint32_t variable; + size_t arithmetic_row; + size_t used_witness; + }; + // A range list: its first `staircase_size` entries are its staircase, whose rows start at `arithmetic_row`. + struct RangeList { + uint64_t target_range; + uint32_t range_tag; + uint32_t staircase_size; + size_t arithmetic_row; + }; + + // The state the builder had when recording started: seeds, then the zero constant and its fixing row. + uint32_t num_seeds = 0; + uint32_t num_prefix_variables = 0; + size_t num_prefix_arithmetic_rows = 0; + size_t num_prefix_gates = 0; + size_t num_prefix_used_witnesses = 0; + + std::vector events; + std::vector constants; + std::vector range_lists; + // A table was registered with register_basic_lookup_table: splice recreates a table from its id, which only fixes + // the contents of a table get_table created. + bool registered_table = false; + + SpliceCancellation* cancellation = nullptr; +}; + +/** + * @brief Why UltraCircuitBuilder_::splice left the target builder unchanged. + */ +enum class SpliceRefusal : uint8_t { + None, + BuilderState, // source not recording or seed count mismatch, target recording, a builder finalized or in write-VK + // mode + Failed, // a builder has failed + PublicInput, // the source added a public input or finalized its public inputs + InputValue, // a seed's value differs from the value of its target variable + InputCycle, // two input variables share a copy cycle, or an input index is the index of another shared variable + InputTag, // an input variable, or a shared constant a source tag reaches, carries a tag in the target + RowForm, // a row the splice cannot copy: elliptic (creation may edit an earlier row) + UnknownForm, // state the splice does not translate (a registered lookup table, a table numbered other than by its + // position, IPA proof, names, unrecorded tags, tag permutation entries or constants) +}; + +/** + * @brief The outcome of UltraCircuitBuilder_::splice. + */ +struct SpliceResult { + SpliceRefusal refusal = SpliceRefusal::None; + // When spliced: the index in the target of every source variable, indexed by source index. + std::vector index_map; + // When spliced: added to a source pairing-point tag index, gives its index in the target. + uint32_t pairing_tag_offset = 0; + + bool spliced() const { return refusal == SpliceRefusal::None; } +}; + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/pairing_points_tagging.hpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/pairing_points_tagging.hpp index 6371350..9f003ff 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/pairing_points_tagging.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/pairing_points_tagging.hpp @@ -121,6 +121,31 @@ class PairingPointsTagging { */ uint32_t get_tag(uint32_t tag_index) const { return pairing_points_tags_.at(tag_index); } + size_t num_tags() const { return pairing_points_tags_.size(); } + + /** + * @brief Append the tags of `other` as if its tag operations had run here after this object's own, each tag shifted + * by the number of tags here before the call. + * @return The shift, which maps a tag index of `other` to its index here. + */ + uint32_t append_shifted(const PairingPointsTagging& other) + { + BB_ASSERT(!other.has_public_pairing_points_, "Cannot append pairing points that have been set to public."); + BB_ASSERT(!has_public_pairing_points_ || other.pairing_points_tags_.empty(), + "Cannot create pairing points after pairing points have been set to public."); + // A tag is the index of its class representative, and every tag ever created holds one entry. + BB_ASSERT_EQ(static_cast(next_pairing_point_tag_), pairing_points_tags_.size()); + BB_ASSERT_EQ(static_cast(other.next_pairing_point_tag_), other.pairing_points_tags_.size()); + const uint32_t shift = next_pairing_point_tag_; + pairing_points_tags_.reserve(pairing_points_tags_.size() + other.pairing_points_tags_.size()); + for (const uint32_t tag : other.pairing_points_tags_) { + pairing_points_tags_.push_back(tag + shift); + } + next_pairing_point_tag_ += other.next_pairing_point_tag_; + has_pairing_points_ = has_pairing_points_ || other.has_pairing_points_; + return shift; + } + /** * @brief Require publication of the final accumulator, or defaults when there are no obligations. */ diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/lookup_slicing.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/lookup_slicing.test.cpp new file mode 100644 index 0000000..37bbf0c --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/lookup_slicing.test.cpp @@ -0,0 +1,89 @@ +#include "barretenberg/numeric/bitop/sparse_form.hpp" +#include "barretenberg/numeric/random/engine.hpp" +#include "plookup_tables.hpp" +#include + +namespace bb::plookup { +namespace { + +using numeric::uint256_t; + +// Each digit as a remainder followed by a separate quotient division. +std::vector reference_slices(uint256_t target, const std::vector& bases) +{ + std::vector slices; + for (const uint64_t base : bases) { + slices.push_back((target % base).data[0]); + target /= base; + } + return slices; +} + +// The largest input the bases represent (their product minus one), saturated at 2^256 - 1. +uint256_t max_sliceable_input(const std::vector& bases) +{ + const uint256_t all_ones = ~uint256_t(0); + uint256_t product = 1; + for (const uint64_t base : bases) { + if (product > all_ones / base) { + return all_ones; + } + product *= base; + } + return product - 1; +} + +void check_slicing(const std::vector& bases) +{ + auto& engine = numeric::get_debug_randomness(); + const uint256_t all_ones = ~uint256_t(0); + const uint256_t max_input = max_sliceable_input(bases); + + std::vector inputs{ 0, 1, max_input, max_input >> 1 }; + for (size_t i = 0; i < 64; ++i) { + // Vary the bit length so that one-limb and multi-limb dividends both occur. + uint256_t input = engine.get_random_uint256() >> (engine.get_random_uint64() & 255); + if (max_input != all_ones) { + input = input % (max_input + 1); + } + inputs.push_back(input); + } + for (const auto& input : inputs) { + EXPECT_EQ(numeric::slice_input_using_variable_bases(input, bases), reference_slices(input, bases)); + } + if (max_input != all_ones) { + EXPECT_THROW(numeric::slice_input_using_variable_bases(max_input + 1, bases), std::runtime_error); + } +} + +} // namespace + +TEST(LookupSlicing, MatchesReferenceForEveryMultiTable) +{ + for (size_t id = 0; id < static_cast(MultiTableId::NUM_MULTI_TABLES); ++id) { + const auto& bases = get_multitable(static_cast(id)).slice_sizes; + if (bases.empty()) { + continue; + } + SCOPED_TRACE("MultiTable id=" + std::to_string(id)); + check_slicing(bases); + } +} + +TEST(LookupSlicing, MatchesReferenceForEdgeBases) +{ + constexpr uint64_t max_u64 = ~uint64_t(0); + constexpr uint64_t top_bit = uint64_t(1) << 63; + const std::vector> base_lists{ + { 1, 3, 1 }, + { 784, 784, 784, 784 }, + { top_bit, top_bit, top_bit, top_bit, top_bit }, + { max_u64, max_u64, max_u64, max_u64, 5 }, + { top_bit + 1, 3, 7, top_bit + 1 }, + }; + for (const auto& bases : base_lists) { + check_slicing(bases); + } +} + +} // namespace bb::plookup diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.cpp index 562fcd5..6788d42 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.cpp @@ -186,27 +186,25 @@ ReadData get_lookup_accumulators(const MultiTableId id, const auto key_a_slices = numeric::slice_input_using_variable_bases(key_a, multi_table.slice_sizes); const auto key_b_slices = numeric::slice_input_using_variable_bases(key_b, multi_table.slice_sizes); - std::vector column_1_raw_values; - std::vector column_2_raw_values; - std::vector column_3_raw_values; + // Each column holds the raw slice values until they are accumulated in place below. + lookup[C1].resize(num_lookups); + lookup[C2].resize(num_lookups); + lookup[C3].resize(num_lookups); + lookup.lookup_entries.reserve(num_lookups); for (size_t i = 0; i < num_lookups; ++i) { // compute the value(s) corresponding to the key(s) using the i-th basic table query function const auto values = multi_table.get_table_values[i]({ key_a_slices[i], key_b_slices[i] }); // store all query data in raw columns and key entry - column_1_raw_values.emplace_back(key_a_slices[i]); - column_2_raw_values.emplace_back(is_2_to_1_lookup ? key_b_slices[i] : values[0]); - column_3_raw_values.emplace_back(is_2_to_1_lookup ? values[0] : values[1]); + lookup[C1][i] = fr(key_a_slices[i]); + lookup[C2][i] = is_2_to_1_lookup ? key_b_slices[i] : values[0]; + lookup[C3][i] = is_2_to_1_lookup ? values[0] : values[1]; // Store the lookup entries for use in constructing the sorted table/lookup polynomials later on const BasicTable::LookupEntry lookup_entry{ { key_a_slices[i], key_b_slices[i] }, values }; lookup.lookup_entries.emplace_back(lookup_entry); } - lookup[C1].resize(num_lookups); - lookup[C2].resize(num_lookups); - lookup[C3].resize(num_lookups); - /** * A multi-table consists of multiple basic tables (say L = 6). * @@ -246,14 +244,10 @@ ReadData get_lookup_accumulators(const MultiTableId id, * For more details: see ./README.md * */ - lookup[C1][num_lookups - 1] = column_1_raw_values[num_lookups - 1]; - lookup[C2][num_lookups - 1] = column_2_raw_values[num_lookups - 1]; - lookup[C3][num_lookups - 1] = column_3_raw_values[num_lookups - 1]; - for (size_t i = num_lookups - 1; i > 0; --i) { - lookup[C1][i - 1] = column_1_raw_values[i - 1] + lookup[C1][i] * multi_table.column_1_step_sizes[i]; - lookup[C2][i - 1] = column_2_raw_values[i - 1] + lookup[C2][i] * multi_table.column_2_step_sizes[i]; - lookup[C3][i - 1] = column_3_raw_values[i - 1] + lookup[C3][i] * multi_table.column_3_step_sizes[i]; + lookup[C1][i - 1] = lookup[C1][i - 1] + lookup[C1][i] * multi_table.column_1_step_sizes[i]; + lookup[C2][i - 1] = lookup[C2][i - 1] + lookup[C2][i] * multi_table.column_2_step_sizes[i]; + lookup[C3][i - 1] = lookup[C3][i - 1] + lookup[C3][i] * multi_table.column_3_step_sizes[i]; } return lookup; } diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp index 8a17672..fba518d 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.cpp @@ -19,16 +19,38 @@ #include "barretenberg/honk/execution_trace/generated/mega_execution_trace_generated.hpp" #include "barretenberg/honk/execution_trace/generated/mega_kernel_execution_trace_generated.hpp" #include "barretenberg/honk/execution_trace/generated/mega_zk_execution_trace_generated.hpp" +#include "bounded_range_sort.hpp" #include "rom_ram_logic.hpp" +#include #include "barretenberg/crypto/sha256/sha256.hpp" #include "barretenberg/serialize/msgpack_impl.hpp" +#include #include +#include +#include #include #include namespace bb { +namespace { +// A small integer as a compile-time field element. Writing the integer where a field element is expected converts it +// to Montgomery form, a field multiplication, every time the line runs. +template constexpr FF fe_constant = FF(value); + +// The sorted values of a range list are written to their new variables in chunks of at least this many values: a +// value is a 32-byte copy, so smaller chunks would not repay a parallel dispatch. +constexpr size_t SORTED_VALUES_MIN_CHUNK = size_t{ 1 } << 15; +// The entries of a range list are resolved to real variables, and the values read, in chunks of at least this many +// entries: each entry is a scattered read, so a chunk of this size outweighs a parallel dispatch. +constexpr size_t RANGE_LIST_MIN_CHUNK = size_t{ 1 } << 13; +// A range list is deduplicated through a bitmap over all variables when the bitmap has at most this many 64-bit words +// per list entry, as scanning a word costs far less than an entry's share of a comparison sort; sparser lists are +// sorted. Both give the same sorted set of real indices. +constexpr size_t BITMAP_MAX_WORDS_PER_LIST_ENTRY = 16; +} // namespace + template void UltraCircuitBuilder_::finalize_circuit() { /** @@ -119,7 +141,7 @@ template void UltraCircuitBuilder_::cr .a_scaling = in.a_scaling, .b_scaling = in.b_scaling, .c_scaling = in.c_scaling, - .d_scaling = 0, + .d_scaling = fe_constant, .const_scaling = in.const_scaling }); } @@ -139,15 +161,15 @@ void UltraCircuitBuilder_::create_big_mul_add_gate(const mul_qua // If include_next_gate_w_4 is true then we set q_arith = 2. In this case, the linear term in the ArithmeticRelation // is scaled by a factor of 2. We compensate here by scaling the quadratic term by 2 to achieve the constraint: // 2 * [q_m * w_1 * w_2 + \sum_{i=1..4} q_i * w_i + q_c + w_4_shift] = 0 - const FF mul_scaling = include_next_gate_w_4 ? in.mul_scaling * FF(2) : in.mul_scaling; + const FF mul_scaling = include_next_gate_w_4 ? in.mul_scaling * fe_constant : in.mul_scaling; blocks.arithmetic.template append_gate({ .wires = { in.a, in.b, in.c, in.d }, - .q_m = mul_scaling, - .q_c = in.const_scaling, - .q_1 = in.a_scaling, - .q_2 = in.b_scaling, - .q_3 = in.c_scaling, - .q_4 = in.d_scaling, - .gate_value = include_next_gate_w_4 ? 2 : 1 }); + .q_m = mul_scaling, + .q_c = in.const_scaling, + .q_1 = in.a_scaling, + .q_2 = in.b_scaling, + .q_3 = in.c_scaling, + .q_4 = in.d_scaling, + .gate_value = include_next_gate_w_4 ? fe_constant : fe_constant }); this->increment_num_gates(); } @@ -165,12 +187,12 @@ void UltraCircuitBuilder_::create_big_add_gate(const add_quad_assert_valid_variables({ in.a, in.b, in.c, in.d }); blocks.arithmetic.template append_gate({ .wires = { in.a, in.b, in.c, in.d }, - .q_c = in.const_scaling, - .q_1 = in.a_scaling, - .q_2 = in.b_scaling, - .q_3 = in.c_scaling, - .q_4 = in.d_scaling, - .gate_value = include_next_gate_w_4 ? 2 : 1 }); + .q_c = in.const_scaling, + .q_1 = in.a_scaling, + .q_2 = in.b_scaling, + .q_3 = in.c_scaling, + .q_4 = in.d_scaling, + .gate_value = include_next_gate_w_4 ? fe_constant : fe_constant }); this->increment_num_gates(); } @@ -206,8 +228,8 @@ void UltraCircuitBuilder_::create_bilinear_batched_eq_gate(const row.q_2 = in.q_r; row.q_3 = in.q_o; row.q_4 = in.q_4; - row.q_5 = in.mode == BilinearBatchedEqMode::Bilinear ? in.q_5 : FF(0); - row.gate_value = in.mode == BilinearBatchedEqMode::Bilinear ? 1 : 2; + row.q_5 = in.mode == BilinearBatchedEqMode::Bilinear ? in.q_5 : fe_constant; + row.gate_value = in.mode == BilinearBatchedEqMode::Bilinear ? fe_constant : fe_constant; block_for_row.template append_gate(row); } this->increment_num_gates(); @@ -223,11 +245,10 @@ void UltraCircuitBuilder_::create_bool_gate(const uint32_t varia { this->assert_valid_variables({ variable_index }); - blocks.arithmetic.template append_gate( - { .wires = { variable_index, variable_index, this->zero_idx(), this->zero_idx() }, - .q_m = 1, - .q_1 = -1, - .gate_value = 1 }); + blocks.arithmetic.template append_gate({ .wires = { variable_index, variable_index, this->zero_idx(), this->zero_idx() }, + .q_m = fe_constant, + .q_1 = fe_constant, + .gate_value = fe_constant }); this->increment_num_gates(); } @@ -243,12 +264,12 @@ void UltraCircuitBuilder_::create_arithmetic_gate(const arithmet this->assert_valid_variables({ in.a, in.b, in.c }); blocks.arithmetic.template append_gate({ .wires = { in.a, in.b, in.c, this->zero_idx() }, - .q_m = in.q_m, - .q_c = in.q_c, - .q_1 = in.q_l, - .q_2 = in.q_r, - .q_3 = in.q_o, - .gate_value = 1 }); + .q_m = in.q_m, + .q_c = in.q_c, + .q_1 = in.q_l, + .q_2 = in.q_r, + .q_3 = in.q_o, + .gate_value = fe_constant }); this->increment_num_gates(); } @@ -278,7 +299,7 @@ void UltraCircuitBuilder_::create_ecc_add_gate(const ecc_add_gat // Convert bool to field element for the relation: +1 for addition, -1 for subtraction // The elliptic curve relation assumes q_sign² = 1 (see elliptic_relation.hpp) - const FF q_sign = in.is_addition ? FF(1) : FF(-1); + const FF q_sign = in.is_addition ? fe_constant : fe_constant; // Determine whether we can fuse this addition operation into the previous gate in the block bool can_fuse_into_previous_gate = @@ -287,15 +308,16 @@ void UltraCircuitBuilder_::create_ecc_add_gate(const ecc_add_gat block.w_o()[block.size() - 1] == in.y1; /* output y coord of previous gate is input of this one */ if (can_fuse_into_previous_gate) { - block.q_1().set(block.size() - 1, q_sign); // set q_sign of previous gate - block.gate_selector_for(GateKind::Elliptic).set(block.size() - 1, 1); // set q_ecc of previous gate to 1 + // set q_sign and q_ecc = 1 on the previous gate + block.q_1().set(block.size() - 1, q_sign); + block.gate_selector_for(GateKind::Elliptic).set(block.size() - 1, fe_constant); } else { { auto& block_for_row = block; GateRowT row{}; row.wires = { this->zero_idx(), in.x1, in.y1, this->zero_idx() }; row.q_1 = q_sign; - row.gate_value = 1; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } this->increment_num_gates(); @@ -336,15 +358,16 @@ void UltraCircuitBuilder_::create_ecc_dbl_gate(const ecc_dbl_gat // If possible, update the previous gate to be the first gate in the pair, otherwise create a new gate if (can_fuse_into_previous_gate) { - block.gate_selector_for(GateKind::Elliptic).set(block.size() - 1, 1); // set q_ecc of previous gate to 1 - block.q_m().set(block.size() - 1, 1); // set q_m (q_is_double) of previous gate to 1 + // set q_ecc = 1 and q_m (q_is_double) = 1 on the previous gate + block.gate_selector_for(GateKind::Elliptic).set(block.size() - 1, fe_constant); + block.q_m().set(block.size() - 1, fe_constant); } else { { auto& block_for_row = block; GateRowT row{}; row.wires = { this->zero_idx(), in.x1, in.y1, this->zero_idx() }; - row.q_m = 1; - row.gate_value = 1; + row.q_m = fe_constant; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } this->increment_num_gates(); @@ -367,11 +390,10 @@ void UltraCircuitBuilder_::fix_witness(const uint32_t witness_in // Mark as intentionally single-gate for boomerang detection update_used_witnesses(witness_index); - blocks.arithmetic.template append_gate( - { .wires = { witness_index, this->zero_idx(), this->zero_idx(), this->zero_idx() }, - .q_c = -witness_value, - .q_1 = 1, - .gate_value = 1 }); + blocks.arithmetic.template append_gate({ .wires = { witness_index, this->zero_idx(), this->zero_idx(), this->zero_idx() }, + .q_c = -witness_value, + .q_1 = fe_constant, + .gate_value = fe_constant }); this->increment_num_gates(); } @@ -382,6 +404,11 @@ uint32_t UltraCircuitBuilder_::put_constant_variable(const FF& v return constant_variable_indices.at(variable); } else { uint32_t variable_index = this->add_variable(variable); + if (splice_log_.has_value()) [[unlikely]] { + recording_log().constants.push_back({ .variable = variable_index, + .arithmetic_row = blocks.arithmetic.size(), + .used_witness = used_witnesses.size() }); + } fix_witness(variable_index, variable); constant_variable_indices.insert({ variable, variable_index }); return variable_index; @@ -414,6 +441,9 @@ plookup::BasicTable& UltraCircuitBuilder_::get_table(const plook template plookup::BasicTable* UltraCircuitBuilder_::register_basic_lookup_table(plookup::BasicTable&& table) { + if (splice_log_.has_value()) [[unlikely]] { + recording_log().registered_table = true; + } // Indices start at 1; see get_table() for the reason. table.table_index = lookup_tables.size() + 1; BB_ASSERT_GT(table.table_index, 0U, "Table index must be greater than 0"); @@ -434,6 +464,29 @@ void UltraCircuitBuilder_::create_lookup_gate(const uint32_t key const FF column_2_step_size, const FF column_3_step_size) requires(ExecutionTrace::has_gate_kind(GateKind::Lookup)) +{ + append_lookup_gate(key_idx, + val1_idx, + val2_idx, + table, + entry, + FF(table.table_index), + column_1_step_size, + column_2_step_size, + column_3_step_size); +} + +template +void UltraCircuitBuilder_::append_lookup_gate(const uint32_t key_idx, + const uint32_t val1_idx, + const uint32_t val2_idx, + plookup::BasicTable& table, + const plookup::BasicTable::LookupEntry& entry, + const FF& table_index_selector, + const FF& column_1_step_size, + const FF& column_2_step_size, + const FF& column_3_step_size) + requires(ExecutionTrace::has_gate_kind(GateKind::Lookup)) { this->assert_valid_variables({ key_idx, val1_idx, val2_idx }); @@ -443,11 +496,11 @@ void UltraCircuitBuilder_::create_lookup_gate(const uint32_t key auto& block_for_row = blocks.lookup; GateRowT row{}; row.wires = { key_idx, val1_idx, val2_idx, this->zero_idx() }; - row.gate_value = 1; + row.gate_value = fe_constant; row.q_m = column_2_step_size; row.q_c = column_3_step_size; row.q_2 = column_1_step_size; - row.q_3 = FF(table.table_index); + row.q_3 = table_index_selector; block_for_row.template append_gate(row); } this->increment_num_gates(); @@ -493,13 +546,22 @@ plookup::ReadData UltraCircuitBuilder_::create_gates_f const auto& multi_table = plookup::get_multitable(id); const size_t num_lookups = read_values[ColumnIdx::C1].size(); plookup::ReadData read_data; + read_data[ColumnIdx::C1].reserve(num_lookups); + read_data[ColumnIdx::C2].reserve(num_lookups); + read_data[ColumnIdx::C3].reserve(num_lookups); + // Consecutive basic lookups often share a table: resolve it and its q_3 selector once per run of equal ids. + plookup::BasicTable* table = nullptr; + FF table_index_selector; for (size_t i = 0; i < num_lookups; ++i) { const bool is_first_lookup = (i == 0); const bool is_last_lookup = (i == num_lookups - 1); - // Get basic lookup table; construct and add to builder.lookup_tables if not already present - plookup::BasicTable& table = get_table(multi_table.basic_table_ids[i]); + if (table == nullptr || table->id != multi_table.basic_table_ids[i]) { + // Get basic lookup table; construct and add to builder.lookup_tables if not already present + table = &get_table(multi_table.basic_table_ids[i]); + table_index_selector = FF(table->table_index); + } // Create witness variables: first lookup reuses user's input indices, subsequent create new variables const auto first_idx = is_first_lookup ? key_a_index : this->add_variable(read_values[ColumnIdx::C1][i]); @@ -513,12 +575,19 @@ plookup::ReadData UltraCircuitBuilder_::create_gates_f read_data[ColumnIdx::C3].push_back(third_idx); // Step size coefficients: zero for last lookup (no next accumulator), negative step sizes otherwise - const FF col1_step = is_last_lookup ? FF(0) : -multi_table.column_1_step_sizes[i + 1]; - const FF col2_step = is_last_lookup ? FF(0) : -multi_table.column_2_step_sizes[i + 1]; - const FF col3_step = is_last_lookup ? FF(0) : -multi_table.column_3_step_sizes[i + 1]; - - create_lookup_gate( - first_idx, second_idx, third_idx, table, read_values.lookup_entries[i], col1_step, col2_step, col3_step); + const FF col1_step = is_last_lookup ? fe_constant : -multi_table.column_1_step_sizes[i + 1]; + const FF col2_step = is_last_lookup ? fe_constant : -multi_table.column_2_step_sizes[i + 1]; + const FF col3_step = is_last_lookup ? fe_constant : -multi_table.column_3_step_sizes[i + 1]; + + append_lookup_gate(first_idx, + second_idx, + third_idx, + *table, + read_values.lookup_entries[i], + table_index_selector, + col1_step, + col2_step, + col3_step); } return read_data; } @@ -554,6 +623,12 @@ typename UltraCircuitBuilder_::RangeList UltraCircuitBuilder_(result.variable_indices.size()), + .arithmetic_row = blocks.arithmetic.size() }); + } // Need this because these variables will not appear in the witness otherwise create_unconstrained_gates(result.variable_indices); @@ -569,7 +644,7 @@ std::vector UltraCircuitBuilder_::create_limbed_range_ BB_ASSERT_GT(num_bits, 0U); BB_ASSERT_GTE(MAX_NUM_BITS_RANGE_CONSTRAINT, num_bits); - uint256_t val = (uint256_t)(this->get_variable(variable_index)); + const uint256_t val = (uint256_t)(this->get_variable(variable_index)); // If the value is out of range, set the CircuitBuilder error to the given msg. if (val.get_msb() >= num_bits && !this->failed()) { @@ -579,32 +654,42 @@ std::vector UltraCircuitBuilder_::create_limbed_range_ // compute limb structure const uint64_t sublimb_mask = (1ULL << target_range_bitnum) - 1; - std::vector sublimbs; - std::vector sublimb_indices; - const bool has_remainder_bits = (num_bits % target_range_bitnum != 0); const uint64_t num_limbs = (num_bits / target_range_bitnum) + has_remainder_bits; const uint64_t last_limb_size = num_bits - ((num_bits / target_range_bitnum) * target_range_bitnum); const uint64_t last_limb_range = ((uint64_t)1 << last_limb_size) - 1; - // extract limbs from the value - uint256_t accumulator = val; - for (size_t i = 0; i < num_limbs; ++i) { - sublimbs.push_back(accumulator.data[0] & sublimb_mask); - accumulator = accumulator >> target_range_bitnum; - } + // Limb j holds bits [j * target_range_bitnum, (j + 1) * target_range_bitnum) of the value; the full sublimb mask + // also applies to the remainder limb, whose smaller range is enforced by its range constraint. + const auto limb_value = [&](const uint64_t j) { + const uint64_t shift = j * target_range_bitnum; + const uint64_t word = shift / 64; + const uint64_t offset = shift % 64; + if (word >= 4) { + return uint64_t{ 0 }; + } + uint64_t bits = val.data[word] >> offset; + if (offset != 0 && word + 1 < 4) { + bits |= val.data[word + 1] << (64 - offset); + } + return bits & sublimb_mask; + }; + // set the correct range constraint on each limb. note that when there are remainder bits, the last limb must be // constrained to a smaller range. - const size_t num_full_limbs = has_remainder_bits ? sublimbs.size() - 1 : sublimbs.size(); - for (size_t i = 0; i < num_full_limbs; ++i) { - const auto limb_idx = this->add_variable(bb::fr(sublimbs[i])); - sublimb_indices.emplace_back(limb_idx); - create_small_range_constraint(limb_idx, sublimb_mask); - } - if (has_remainder_bits) { - const auto limb_idx = this->add_variable(bb::fr(sublimbs.back())); + std::vector sublimb_indices; + sublimb_indices.reserve(static_cast(num_limbs)); + RangeList* list = nullptr; + for (uint64_t j = 0; j < num_limbs; ++j) { + const uint64_t sublimb = limb_value(j); + const bool is_remainder_limb = has_remainder_bits && (j == num_limbs - 1); + const auto limb_idx = this->add_variable(bb::fr(sublimb)); sublimb_indices.emplace_back(limb_idx); - create_small_range_constraint(limb_idx, last_limb_range); + register_new_variable_range_constraint(limb_idx, + is_remainder_limb ? last_limb_range : sublimb_mask, + sublimb, + list, + "create_small_range_constraint"); } // Prove that the limbs reconstruct the original value by processing limbs in groups of 3. @@ -616,7 +701,21 @@ std::vector UltraCircuitBuilder_::create_limbed_range_ // `leftovers` is the number of real limbs in the final triple (1, 2, or 3). const uint64_t leftovers = (num_limbs % 3) == 0 ? 3 : (num_limbs % 3); - accumulator = val; + // The gate scalings FF(uint256_t(1) << shift) for the limb positions of the default limb size, so that the common + // case does not convert them to Montgomery form on every call (see fe_constant). + static constexpr size_t MAX_DEFAULT_LIMBS = + (MAX_NUM_BITS_RANGE_CONSTRAINT + DEFAULT_PLOOKUP_RANGE_BITNUM - 1) / DEFAULT_PLOOKUP_RANGE_BITNUM; + static constexpr size_t NUM_DEFAULT_SCALINGS = 3 * ((MAX_DEFAULT_LIMBS + 2) / 3); + static constexpr std::array DEFAULT_SCALINGS = [] { + std::array scalings{}; + for (size_t k = 0; k < NUM_DEFAULT_SCALINGS; ++k) { + scalings[k] = FF(uint256_t(1) << (DEFAULT_PLOOKUP_RANGE_BITNUM * k)); + } + return scalings; + }(); + const bool use_default_scalings = + (target_range_bitnum == DEFAULT_PLOOKUP_RANGE_BITNUM) && (3 * num_limb_triples <= NUM_DEFAULT_SCALINGS); + uint32_t accumulator_idx = variable_index; // loop goes from `i = 0` to `num_limb_triples`, but some special case must be taken for the last triple (`i == // num_limb_triples - 1`), hence some conditional logic. @@ -629,12 +728,6 @@ std::vector UltraCircuitBuilder_::create_limbed_range_ !(i == (num_limb_triples - 1) && (leftovers < 3)), }; - // The witness values of the 3 limbs in this triple (0 for padding positions). - const uint64_t round_sublimbs[3]{ - real_limbs[0] ? sublimbs[3 * i] : 0, - real_limbs[1] ? sublimbs[3 * i + 1] : 0, - real_limbs[2] ? sublimbs[3 * i + 2] : 0, - }; // The witnesss indices of the current 3 limbs (zero_idx for padding positions). const uint32_t new_limbs[3]{ real_limbs[0] ? sublimb_indices[3 * i] : this->zero_idx(), @@ -647,16 +740,14 @@ std::vector UltraCircuitBuilder_::create_limbed_range_ target_range_bitnum * (3 * i + 1), target_range_bitnum * (3 * i + 2), }; - // Compute the new accumulator after subtracting this triple's contribution. - // After the final iteration, accumulator should be 0. - uint256_t new_accumulator = accumulator - (uint256_t(round_sublimbs[0]) << shifts[0]) - - (uint256_t(round_sublimbs[1]) << shifts[1]) - - (uint256_t(round_sublimbs[2]) << shifts[2]); + const auto scaling = [&](const size_t k) { + return use_default_scalings ? DEFAULT_SCALINGS[(3 * i) + k] : FF(uint256_t(1) << shifts[k]); + }; // This `big_add_gate` has differing behavior depending on whether or not `i == num_limb_triples - 1`. // If `i != num_limb_triples - 1`, then the constraint will be limb[0]*2^shift[0] + limb[1]*2^shift[1] + // limb[2]*2^shift[2] - acc = new_accumulator (the last argument to `create_big_add_gate` is `true`, means the - // sum is w_4-shift, which will be the witness corresponding to what is currently `new_accumulator`.). + // sum is w_4-shift, which will be the witness corresponding to the new accumulator.). // If `i == num_limb_triples - 1`, then the last argument to `create_big_add_gate` is false, so the constraint // is limb[0]*2^shift[0] + limb[1]*2^shift[1] + limb[2]*2^shift[2] - acc = 0. // @@ -669,16 +760,17 @@ std::vector UltraCircuitBuilder_::create_limbed_range_ new_limbs[1], new_limbs[2], accumulator_idx, - uint256_t(1) << shifts[0], - uint256_t(1) << shifts[1], - uint256_t(1) << shifts[2], - -1, - 0, + scaling(0), + scaling(1), + scaling(2), + fe_constant, + fe_constant, }, (i != num_limb_triples - 1)); if (i != num_limb_triples - 1) { - accumulator_idx = this->add_variable(fr(new_accumulator)); - accumulator = new_accumulator; + // The accumulator after subtracting limbs 0..3i+2 is the value with those limbs' bits cleared. + const uint64_t consumed_bits = target_range_bitnum * (3 * i + 3); + accumulator_idx = this->add_variable(fr((val >> consumed_bits) << consumed_bits)); } } return sublimb_indices; @@ -689,19 +781,33 @@ void UltraCircuitBuilder_::create_small_range_constraint(const u const uint64_t target_range, std::string_view msg) { - // make sure `target_range` is not too big. + register_small_range_constraint(variable_index, target_range, RangeWitnessValue{}, msg); +} + +template +template +void UltraCircuitBuilder_::register_small_range_constraint(const uint32_t variable_index, + const uint64_t target_range, + ValueSource value_source, + std::string_view msg) +{ + // Keep the original public check in this body so its field temporaries do not span another helper call. BB_ASSERT_GTE(MAX_SMALL_RANGE_CONSTRAINT_VAL, target_range); - const bool is_out_of_range = (uint256_t(this->get_variable(variable_index)).data[0] > target_range); + const bool is_out_of_range = [&] { + if constexpr (std::is_same_v) { + return uint256_t(this->get_variable(variable_index)).data[0] > target_range; + } else { + static_assert(std::is_same_v); + return value_source > target_range; + } + }(); if (is_out_of_range && !this->failed()) { this->failure(std::string(msg)); } - if (range_lists.count(target_range) == 0) { - range_lists.insert({ target_range, create_range_list(target_range) }); - } + auto& list = get_or_create_range_list(target_range); // The tag of `variable_index` is `DEFAULT_TAG` if it has never been range-constrained and a non-trivial value // otherwise. const auto existing_tag = this->real_variable_tags[this->real_variable_index[variable_index]]; - auto& list = range_lists[target_range]; // If the variable's tag matches the target range list's tag, do nothing; the variable has _already_ been // constrained to this exact range (i.e., `create_new_range_constraint(variable_index, target_range)` has already @@ -749,7 +855,49 @@ void UltraCircuitBuilder_::create_small_range_constraint(const u BB_ASSERT(found_tag); } +template +typename UltraCircuitBuilder_::RangeList& UltraCircuitBuilder_< + ExecutionTrace>::get_or_create_range_list(const uint64_t target_range) +{ + auto list_it = range_lists.find(target_range); + if (list_it == range_lists.end()) { + list_it = range_lists.emplace(target_range, create_range_list(target_range)).first; + } + return list_it->second; +} + +template +void UltraCircuitBuilder_::register_new_variable_range_constraint(const uint32_t variable_index, + const uint64_t target_range, + const uint64_t value, + RangeList*& list, + std::string_view msg) +{ + BB_ASSERT_GTE(MAX_SMALL_RANGE_CONSTRAINT_VAL, target_range); + if (value > target_range && !this->failed()) { + this->failure(std::string(msg)); + } + // std::map does not relocate its elements, so the cached list stays valid while other lists are inserted. + if (list == nullptr || list->target_range != target_range) { + list = &get_or_create_range_list(target_range); + } + BB_ASSERT_DEBUG(this->real_variable_index[variable_index] == variable_index); + BB_ASSERT_DEBUG(this->real_variable_tags[variable_index] == DEFAULT_TAG); + if (splice_log_.has_value()) [[unlikely]] { + recording_log().events.push_back({ SpliceLog::Event::Kind::Tag, variable_index, list->range_tag }); + } + this->real_variable_tags[variable_index] = list->range_tag; + list->variable_indices.emplace_back(variable_index); +} + template void UltraCircuitBuilder_::process_range_list(RangeList& list) +{ + VariableBitmap real_variables; + process_range_list(list, real_variables); +} + +template +void UltraCircuitBuilder_::process_range_list(RangeList& list, VariableBitmap& real_variables) { this->assert_valid_variables(list.variable_indices); @@ -757,58 +905,181 @@ template void UltraCircuitBuilder_::pr // replace witness-index in variable_indices with the corresponding real-variable-index i.e., if a copy constraint // has been applied on a variable after it was range constrained, this makes sure the indices in list point to the - // updated index in the range list so the set equivalence does not fail - for (uint32_t& x : list.variable_indices) { - x = this->real_variable_index[x]; - } - // Sort `variable_indices` and remove duplicate witness indices to prevent the sorted list set size being wrong! - std::sort(list.variable_indices.begin(), list.variable_indices.end()); - auto back_iterator = std::unique(list.variable_indices.begin(), list.variable_indices.end()); - list.variable_indices.erase(back_iterator, list.variable_indices.end()); - - // Extract the values of each (real) variable into a list to be sorted (in the sense of the range/plookup-style - // argument). + // updated index in the range list so the set equivalence does not fail. The real indices are sorted and + // deduplicated, to prevent the sorted list set size being wrong, and the value of each (real) variable is extracted + // into a list to be sorted (in the sense of the range/plookup-style argument). + std::vector& variable_indices = list.variable_indices; + const size_t list_size = variable_indices.size(); + const auto list_chunks = range_sort::Chunks::of_min_size(list_size, RANGE_LIST_MIN_CHUNK); + const uint256_t target_range(list.target_range); std::vector sorted_list; - sorted_list.reserve(list.variable_indices.size()); - for (const auto variable_index : list.variable_indices) { - // note that `field_element` is < 32 bits as the corresponding witness has a non-trivial range-constraint. - const auto& field_element = this->get_variable(variable_index); - const uint32_t shrinked_value = static_cast(field_element); - sorted_list.emplace_back(shrinked_value); + std::vector chunk_values_in_range; + // Writes the value of a real variable to sorted_list[position]; returns whether it lies in the range. + const auto extract_value = [&](const size_t position, const uint32_t variable_index) { + // note that the value is < 32 bits as the corresponding witness has a non-trivial range-constraint. Convert + // once, then validate the full value. + const auto native_value = static_cast(this->get_variable(variable_index)); + sorted_list[position] = static_cast(native_value.data[0]); + return native_value <= target_range; + }; + + const size_t num_variables = this->get_num_variables(); + const size_t num_words = (num_variables + 63) / 64; + if (num_words > BITMAP_MAX_WORDS_PER_LIST_ENTRY * list_size) { + list_chunks.run([&](size_t /*chunk*/, const size_t begin, const size_t end) { + for (size_t i = begin; i < end; ++i) { + variable_indices[i] = this->real_variable_index[variable_indices[i]]; + } + }); + std::sort(variable_indices.begin(), variable_indices.end()); + auto back_iterator = std::unique(variable_indices.begin(), variable_indices.end()); + variable_indices.erase(back_iterator, variable_indices.end()); + + sorted_list.resize(variable_indices.size()); + const auto value_chunks = range_sort::Chunks::of_min_size(variable_indices.size(), RANGE_LIST_MIN_CHUNK); + chunk_values_in_range.assign(value_chunks.count(), 1); + value_chunks.run([&](const size_t chunk, const size_t begin, const size_t end) { + bool in_range = true; + for (size_t i = begin; i < end; ++i) { + const bool value_in_range = extract_value(i, variable_indices[i]); + in_range = in_range && value_in_range; + } + chunk_values_in_range[chunk] = static_cast(in_range); + }); + } else { + // Mark the real indices in the bitmap, then read the set bits back in increasing order: the sorted, + // deduplicated real indices. + if (real_variables.size() < num_words) { + VariableBitmap(num_words).swap(real_variables); + } + std::vector chunk_lowest(list_chunks.count(), std::numeric_limits::max()); + std::vector chunk_highest(list_chunks.count(), 0); + list_chunks.run([&](const size_t chunk, const size_t begin, const size_t end) { + uint32_t lowest = std::numeric_limits::max(); + uint32_t highest = 0; + // Bits of consecutive entries in the same word are set with one atomic operation. + size_t word = 0; + uint64_t bits = 0; + for (size_t i = begin; i < end; ++i) { + const uint32_t real_index = this->real_variable_index[variable_indices[i]]; + BB_ASSERT_DEBUG(real_index < num_variables); + lowest = std::min(lowest, real_index); + highest = std::max(highest, real_index); + if ((real_index >> 6) != word) { + if (bits != 0) { + real_variables[word].fetch_or(bits, std::memory_order_relaxed); + } + word = real_index >> 6; + bits = 0; + } + bits |= uint64_t{ 1 } << (real_index & 63); + } + if (bits != 0) { + real_variables[word].fetch_or(bits, std::memory_order_relaxed); + } + chunk_lowest[chunk] = lowest; + chunk_highest[chunk] = highest; + }); + const size_t first_word = *std::ranges::min_element(chunk_lowest) >> 6; + const size_t num_list_words = (*std::ranges::max_element(chunk_highest) >> 6) + 1 - first_word; + const auto word_chunks = range_sort::Chunks::with_count(num_list_words, list_chunks.count()); + // chunk_offsets[c] is the position in the deduplicated list of the first real index in word chunk c. + std::vector chunk_offsets(word_chunks.count() + 1, 0); + word_chunks.run([&](const size_t chunk, const size_t begin, const size_t end) { + size_t count = 0; + for (size_t w = first_word + begin; w < first_word + end; ++w) { + count += static_cast(std::popcount(real_variables[w].load(std::memory_order_relaxed))); + } + chunk_offsets[chunk + 1] = count; + }); + std::partial_sum(chunk_offsets.begin(), chunk_offsets.end(), chunk_offsets.begin()); + const size_t num_real_variables = chunk_offsets.back(); + + sorted_list.resize(num_real_variables); + chunk_values_in_range.assign(word_chunks.count(), 1); + word_chunks.run([&](const size_t chunk, const size_t begin, const size_t end) { + size_t position = chunk_offsets[chunk]; + bool in_range = true; + for (size_t w = first_word + begin; w < first_word + end; ++w) { + uint64_t bits = real_variables[w].load(std::memory_order_relaxed); + real_variables[w].store(0, std::memory_order_relaxed); + while (bits != 0) { + const auto real_index = + static_cast((w << 6) + static_cast(std::countr_zero(bits))); + bits &= bits - 1; + variable_indices[position] = real_index; + const bool value_in_range = extract_value(position, real_index); + in_range = in_range && value_in_range; + ++position; + } + } + chunk_values_in_range[chunk] = static_cast(in_range); + }); + variable_indices.resize(num_real_variables); } + const bool values_in_range = + std::ranges::all_of(chunk_values_in_range, [](const uint8_t in_range) { return in_range != 0; }); + if (!values_in_range || !range_sort::try_counting_sort(sorted_list, list.target_range)) { #ifdef NO_PAR_ALGOS - std::sort(sorted_list.begin(), sorted_list.end()); + std::sort(sorted_list.begin(), sorted_list.end()); #else - std::sort(std::execution::par_unseq, sorted_list.begin(), sorted_list.end()); + std::sort(std::execution::par_unseq, sorted_list.begin(), sorted_list.end()); #endif + } // list must be padded to a multipe of 4 and larger than 4 (gate_width) constexpr size_t gate_width = NUM_WIRES; - size_t padding = (gate_width - (list.variable_indices.size() % gate_width)) % gate_width; - - std::vector indices; - indices.reserve(padding + sorted_list.size()); - - if (list.variable_indices.size() <= gate_width) { + const size_t num_values = sorted_list.size(); + size_t padding = (gate_width - (num_values % gate_width)) % gate_width; + if (num_values <= gate_width) { padding += gate_width; } - for (size_t i = 0; i < padding; ++i) { - indices.emplace_back(this->zero_idx()); - } - // tag the elements in the sorted_list to apply the multiset-equality check implicit in range-constraints. - for (const auto sorted_value : sorted_list) { - const uint32_t index = this->add_variable(fr(sorted_value)); - assign_tag(index, list.tau_tag); - indices.emplace_back(index); - } + // tag the elements in the sorted_list to apply the multiset-equality check implicit in range-constraints: one new + // variable per sorted value, in order, each its own real variable carrying the tau tag. Equal values are adjacent + // in the sorted list, so each run within a chunk converts its value to a field element once. + const uint32_t first_sorted_index = + this->add_tagged_variables(num_values, list.tau_tag, [&](const std::span values) { + range_sort::Chunks::of_min_size(num_values, SORTED_VALUES_MIN_CHUNK) + .run([&](size_t /*chunk*/, const size_t begin, const size_t end) { + if (begin == end) { + return; + } + uint32_t run_value = sorted_list[begin]; + FF run_element(run_value); + for (size_t i = begin; i < end; ++i) { + if (sorted_list[i] != run_value) { + run_value = sorted_list[i]; + run_element = FF(run_value); + } + values[i] = run_element; + } + }); + }); + std::vector indices(padding + num_values); + std::fill_n(indices.begin(), padding, this->zero_idx()); + std::iota(indices.begin() + static_cast(padding), indices.end(), first_sorted_index); // constrain the _sorted_ list: starts at 0, ends at `target_range`, consecutive differences in {0, 1, 2, 3}. create_sort_constraint_with_edges(indices, 0, list.target_range); } template void UltraCircuitBuilder_::process_range_lists() { + VariableBitmap real_variables; for (auto& i : range_lists) { - process_range_list(i.second); + process_range_list(i.second, real_variables); + } +} + +template +void UltraCircuitBuilder_::append_delta_range_rows(const std::vector& variable_indices) +{ + // The rows differ only in their wires. + GateRowT row{}; + row.gate_value = fe_constant; + for (size_t i = 0; i < variable_indices.size(); i += NUM_WIRES) { + this->increment_num_gates(); + row.wires = { variable_indices[i], variable_indices[i + 1], variable_indices[i + 2], variable_indices[i + 3] }; + blocks.delta_range.template append_gate(row); } } @@ -819,19 +1090,7 @@ void UltraCircuitBuilder_::enforce_small_deltas(const std::vecto BB_ASSERT_EQ(variable_indices.size() % gate_width, 0U); this->assert_valid_variables(variable_indices); - for (size_t i = 0; i < variable_indices.size(); i += gate_width) { - - this->increment_num_gates(); - { - auto& block_for_row = blocks.delta_range; - GateRowT row{}; - row.wires = { - variable_indices[i], variable_indices[i + 1], variable_indices[i + 2], variable_indices[i + 3] - }; - row.gate_value = 1; - block_for_row.template append_gate(row); - } - } + append_delta_range_rows(variable_indices); // dummy gate needed because of widget's check of next row create_unconstrained_gate(blocks.delta_range, variable_indices[variable_indices.size() - 1], @@ -878,19 +1137,7 @@ void UltraCircuitBuilder_::create_sort_constraint_with_edges( // enforce delta range relation for all rows (there are `variabe_indices.size() / gate_width`). note that there are // at least two rows. - for (size_t i = 0; i < variable_indices.size(); i += gate_width) { - - this->increment_num_gates(); - { - auto& block_for_row = block; - GateRowT row{}; - row.wires = { - variable_indices[i], variable_indices[i + 1], variable_indices[i + 2], variable_indices[i + 3] - }; - row.gate_value = 1; - block_for_row.template append_gate(row); - } - } + append_delta_range_rows(variable_indices); // the delta_range constraint has to have access to w_1-shift (it checks that w_1-shift - w_4 is in {0, 1, 2, 3}). // Therefore, we repeat the last element in an unconstrained gate. @@ -931,15 +1178,15 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_ : fe_constant; switch (type) { case MEMORY_SELECTORS::ROM_CONSISTENCY_CHECK: { // Memory read gate used with the sorted list of memory reads. // Apply sorted memory read checks with the following additional check: // 1. Assert that if index field across two gates does not change, the value field does not change. // Used for ROM reads and RAM reads across write/read boundaries - row.q_1 = 1; - row.q_2 = 1; + row.q_1 = fe_constant; + row.q_2 = fe_constant; break; } case MEMORY_SELECTORS::RAM_CONSISTENCY_CHECK: { @@ -948,22 +1195,22 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_; break; } case MEMORY_SELECTORS::RAM_TIMESTAMP_CHECK: { // For two adjacent RAM entries that share the same index, validate the timestamp value is monotonically // increasing - row.q_1 = 1; - row.q_4 = 1; + row.q_1 = fe_constant; + row.q_4 = fe_constant; break; } case MEMORY_SELECTORS::ROM_READ: { // Memory read gate for reading memory cells. Also used for the _initialization_ of ROM memory cells. // Validates record witness computation (r = read_write_flag + index * \eta + timestamp * \eta^2 + value * // \eta^3) - row.q_1 = 1; - row.q_m = 1; // validate record witness is correctly computed + row.q_1 = fe_constant; + row.q_m = fe_constant; // validate record witness is correctly computed // read/write flag stored in q_c break; } @@ -971,8 +1218,8 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_; + row.q_m = fe_constant; // validate record witness is correctly computed // read/write flag stored in q_c break; } @@ -980,9 +1227,9 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_; + row.q_m = fe_constant; // validate record witness is correctly computed + row.q_c = fe_constant; // read/write flag stored in q_c break; } case MEMORY_SELECTORS::ROM_LOGUP_TABLE: { @@ -990,7 +1237,7 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_; break; } case MEMORY_SELECTORS::ROM_LOGUP_READ: { @@ -998,7 +1245,7 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_; break; } default: { @@ -1037,31 +1284,31 @@ typename UltraCircuitBuilder_::GateRowT UltraCircuitBuilder_ : fe_constant; switch (type) { case NNF_SELECTORS::LIMB_ACCUMULATE_1: { - row.q_3 = 1; - row.q_4 = 1; + row.q_3 = fe_constant; + row.q_4 = fe_constant; break; } case NNF_SELECTORS::LIMB_ACCUMULATE_2: { - row.q_3 = 1; - row.q_m = 1; + row.q_3 = fe_constant; + row.q_m = fe_constant; break; } case NNF_SELECTORS::NON_NATIVE_FIELD_1: { - row.q_2 = 1; - row.q_3 = 1; + row.q_2 = fe_constant; + row.q_3 = fe_constant; break; } case NNF_SELECTORS::NON_NATIVE_FIELD_2: { - row.q_2 = 1; - row.q_4 = 1; + row.q_2 = fe_constant; + row.q_4 = fe_constant; break; } case NNF_SELECTORS::NON_NATIVE_FIELD_3: { - row.q_2 = 1; - row.q_m = 1; + row.q_2 = fe_constant; + row.q_m = fe_constant; break; } default: { @@ -1095,32 +1342,38 @@ void UltraCircuitBuilder_::range_constrain_two_limbs(const uint3 BB_ASSERT_LTE(hi_limb_bits, 14U * 5U); // If the value is larger than the range, we log the error in builder - const bool is_lo_out_of_range = (uint256_t(this->get_variable(lo_idx)) >= (uint256_t(1) << lo_limb_bits)); + const uint256_t lo_limb(this->get_variable(lo_idx)); + const bool is_lo_out_of_range = (lo_limb >= (uint256_t(1) << lo_limb_bits)); if (is_lo_out_of_range && !this->failed()) { this->failure(std::string(msg) + ": lo limb."); } - const bool is_hi_out_of_range = (uint256_t(this->get_variable(hi_idx)) >= (uint256_t(1) << hi_limb_bits)); + const uint256_t hi_limb(this->get_variable(hi_idx)); + const bool is_hi_out_of_range = (hi_limb >= (uint256_t(1) << hi_limb_bits)); if (is_hi_out_of_range && !this->failed()) { this->failure(std::string(msg) + ": hi limb."); } + // The five 14-bit sublimbs (bits [14k, 14k + 14)) of the low 70 bits of a limb. We can use the constant 2^14 - 1 + // mask here: if a sublimb value exceeds its expected range, the witness fails the range check below. + const auto get_sublimb_values = [](const uint256_t& limb) { + constexpr uint64_t MAX_SUBLIMB_MASK = (1ULL << 14) - 1; + const uint64_t low = limb.data[0]; + const uint64_t high = limb.data[1]; + return std::array{ low & MAX_SUBLIMB_MASK, + (low >> 14) & MAX_SUBLIMB_MASK, + (low >> 28) & MAX_SUBLIMB_MASK, + (low >> 42) & MAX_SUBLIMB_MASK, + ((low >> 56) | (high << 8)) & MAX_SUBLIMB_MASK }; + }; + // Sometimes we try to use limbs that are too large. It's easier to catch this issue here - const auto get_sublimbs = [&](const uint32_t& limb_idx, const std::array& sublimb_masks) { - const uint256_t limb = this->get_variable(limb_idx); - // we can use constant 2^14 - 1 mask here. If the sublimb value exceeds the expected value then witness will - // fail the range check below - // We also use zero_idx to substitute variables that should be zero - constexpr uint256_t MAX_SUBLIMB_MASK = (uint256_t(1) << 14) - 1; + // We also use zero_idx to substitute variables that should be zero + const auto get_sublimbs = [&](const std::array& sublimb_values, + const std::array& sublimb_masks) { std::array sublimb_indices; - sublimb_indices[0] = sublimb_masks[0] != 0 ? this->add_variable(fr(limb & MAX_SUBLIMB_MASK)) : this->zero_idx(); - sublimb_indices[1] = - sublimb_masks[1] != 0 ? this->add_variable(fr((limb >> 14) & MAX_SUBLIMB_MASK)) : this->zero_idx(); - sublimb_indices[2] = - sublimb_masks[2] != 0 ? this->add_variable(fr((limb >> 28) & MAX_SUBLIMB_MASK)) : this->zero_idx(); - sublimb_indices[3] = - sublimb_masks[3] != 0 ? this->add_variable(fr((limb >> 42) & MAX_SUBLIMB_MASK)) : this->zero_idx(); - sublimb_indices[4] = - sublimb_masks[4] != 0 ? this->add_variable(fr((limb >> 56) & MAX_SUBLIMB_MASK)) : this->zero_idx(); + for (size_t i = 0; i < 5; ++i) { + sublimb_indices[i] = sublimb_masks[i] != 0 ? this->add_variable(fr(sublimb_values[i])) : this->zero_idx(); + } return sublimb_indices; }; @@ -1140,8 +1393,10 @@ void UltraCircuitBuilder_::range_constrain_two_limbs(const uint3 const auto lo_masks = get_limb_masks(lo_limb_bits); const auto hi_masks = get_limb_masks(hi_limb_bits); - const std::array lo_sublimbs = get_sublimbs(lo_idx, lo_masks); - const std::array hi_sublimbs = get_sublimbs(hi_idx, hi_masks); + const std::array lo_values = get_sublimb_values(lo_limb); + const std::array hi_values = get_sublimb_values(hi_limb); + const std::array lo_sublimbs = get_sublimbs(lo_values, lo_masks); + const std::array hi_sublimbs = get_sublimbs(hi_values, hi_masks); { auto row = nnf_selectors_row(NNF_SELECTORS::LIMB_ACCUMULATE_1); @@ -1160,14 +1415,15 @@ void UltraCircuitBuilder_::range_constrain_two_limbs(const uint3 } this->increment_num_gates(3); + RangeList* list = nullptr; for (size_t i = 0; i < 5; i++) { if (lo_masks[i] != 0) { - create_small_range_constraint( - lo_sublimbs[i], lo_masks[i], "ultra_circuit_builder: sublimb of low too large"); + register_new_variable_range_constraint( + lo_sublimbs[i], lo_masks[i], lo_values[i], list, "ultra_circuit_builder: sublimb of low too large"); } if (hi_masks[i] != 0) { - create_small_range_constraint( - hi_sublimbs[i], hi_masks[i], "ultra_circuit_builder: sublimb of hi too large"); + register_new_variable_range_constraint( + hi_sublimbs[i], hi_masks[i], hi_values[i], list, "ultra_circuit_builder: sublimb of hi too large"); } } }; @@ -1213,6 +1469,8 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ constexpr FF LIMB_SHIFT = uint256_t(1) << DEFAULT_NON_NATIVE_FIELD_LIMB_BITS; constexpr FF LIMB_RSHIFT = FF(1) / FF(uint256_t(1) << DEFAULT_NON_NATIVE_FIELD_LIMB_BITS); constexpr FF LIMB_RSHIFT_2 = FF(1) / FF(uint256_t(1) << (2 * DEFAULT_NON_NATIVE_FIELD_LIMB_BITS)); + constexpr FF MINUS_LIMB_SHIFT = -LIMB_SHIFT; + constexpr FF MINUS_LIMB_SHIFT_SQR = -LIMB_SHIFT.sqr(); // lo_0 = (a0·b0 - r0) + (a1·b0 + a0·b1)·2^L FF lo_0 = (a0 * b0 - r0) + (a1 * b0 + a0 * b1) * LIMB_SHIFT; @@ -1246,9 +1504,9 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ lo_1_idx, input.neg_modulus[0] + input.neg_modulus[1] * LIMB_SHIFT, input.neg_modulus[0] * LIMB_SHIFT, - -LIMB_SHIFT, - -LIMB_SHIFT.sqr(), - 0 }, + MINUS_LIMB_SHIFT, + MINUS_LIMB_SHIFT_SQR, + fe_constant }, /*include_next_gate_w_4*/ true); // Gate 2: unconstrained gate to provide lo_0 via w_4_shift for gate 1 create_unconstrained_gate(blocks.arithmetic, this->zero_idx(), this->zero_idx(), this->zero_idx(), lo_0_idx); @@ -1335,9 +1593,9 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ hi_1_idx, -input.neg_modulus[1] * LIMB_SHIFT - input.neg_modulus[0], -input.neg_modulus[0] * LIMB_SHIFT, - -1, - -1, - 0, + fe_constant, + fe_constant, + fe_constant, }, /*include_next_gate_w_4*/ true); @@ -1351,11 +1609,11 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ input.q[0], input.q[1], hi_2_idx, - -1, + fe_constant, input.neg_modulus[3] * LIMB_RSHIFT + input.neg_modulus[2] * LIMB_RSHIFT_2, input.neg_modulus[2] * LIMB_RSHIFT + input.neg_modulus[1] * LIMB_RSHIFT_2, LIMB_RSHIFT_2, - 0, + fe_constant, }); return std::array{ lo_1_idx, hi_3_idx }; @@ -1539,7 +1797,7 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ // When q_arith == 3, w_4_shift is scaled by 2 (see ArithmeticRelation for details). Therefore, for consistency we // also scale each linear term by this factor of 2 so that the constraint is effectively: // (q_l * w_1) + (q_r * w_2) + (q_o * w_3) + (q_4 * w_4) + q_c + w_4_shift = 0 - const FF linear_term_scale_factor = 2; + constexpr FF linear_term_scale_factor = fe_constant; { auto& block_for_row = block; GateRowT row{}; @@ -1548,7 +1806,7 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst0 * linear_term_scale_factor; row.q_2 = -x_mulconst0 * linear_term_scale_factor; row.q_3 = -y_mulconst0 * linear_term_scale_factor; - row.gate_value = 3; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1559,7 +1817,7 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst1; row.q_2 = -x_mulconst1; row.q_3 = -y_mulconst1; - row.gate_value = 2; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1570,8 +1828,8 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst2; row.q_1 = -x_mulconst2; row.q_2 = -y_mulconst2; - row.q_3 = 1; - row.gate_value = 1; + row.q_3 = fe_constant; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1582,8 +1840,8 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst3; row.q_1 = -x_mulconst3; row.q_2 = -y_mulconst3; - row.q_3 = 1; - row.gate_value = 1; + row.q_3 = fe_constant; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1673,7 +1931,7 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ // When q_arith == 3, w_4_shift is scaled by 2 (see ArithmeticRelation for details). Therefore, for consistency we // also scale each linear term by this factor of 2 so that the constraint is effectively: // (q_l * w_1) + (q_r * w_2) + (q_o * w_3) + (q_4 * w_4) + q_c + w_4_shift = 0 - const FF linear_term_scale_factor = 2; + constexpr FF linear_term_scale_factor = fe_constant; { auto& block_for_row = block; GateRowT row{}; @@ -1682,7 +1940,7 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst0 * linear_term_scale_factor; row.q_2 = -x_mulconst0 * linear_term_scale_factor; row.q_3 = y_mulconst0 * linear_term_scale_factor; - row.gate_value = 3; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1693,7 +1951,7 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst1; row.q_2 = -x_mulconst1; row.q_3 = y_mulconst1; - row.gate_value = 2; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1704,8 +1962,8 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst2; row.q_1 = -x_mulconst2; row.q_2 = y_mulconst2; - row.q_3 = 1; - row.gate_value = 1; + row.q_3 = fe_constant; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1716,8 +1974,8 @@ std::array UltraCircuitBuilder_::evaluate_non_nativ row.q_c = -addconst3; row.q_1 = -x_mulconst3; row.q_2 = y_mulconst3; - row.q_3 = 1; - row.gate_value = 1; + row.q_3 = fe_constant; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } @@ -1870,13 +2128,12 @@ void UltraCircuitBuilder_::create_poseidon2_external_gate(const poseidon2_ex { if constexpr (requires { this->blocks.poseidon2_external; }) { auto& block = this->blocks.poseidon2_external; - block.template append_gate( - { .wires = { in.a, in.b, in.c, in.d }, - .q_1 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][0], - .q_2 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][1], - .q_3 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][2], - .q_4 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][3], - .gate_value = 1 }); + block.template append_gate({ .wires = { in.a, in.b, in.c, in.d }, + .q_1 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][0], + .q_2 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][1], + .q_3 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][2], + .q_4 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][3], + .gate_value = fe_constant }); this->increment_num_gates(); } else { throw_or_abort("create_poseidon2_external_gate base is Ultra-only (Mega overrides into its poseidon2 block)"); @@ -1897,7 +2154,7 @@ void UltraCircuitBuilder_::create_poseidon2_internal_gate(const poseidon2_in GateRowT row{}; row.wires = { in.a, in.b, in.c, in.d }; row.q_1 = crypto::Poseidon2Bn254ScalarFieldParams::round_constants[in.round_idx][0]; - row.gate_value = 1; + row.gate_value = fe_constant; block_for_row.template append_gate(row); } this->increment_num_gates(); @@ -2072,6 +2329,64 @@ template void UltraCircuitBuilder_::fr std::unordered_set().swap(finalize_witnesses); } +template void UltraCircuitBuilder_::release_storage_pages() noexcept +{ + if (splice_log_.has_value()) { + release_recording_storage_pages(); + return; + } + // Holds far more blocks than a circuit has at or above the release floor; blocks past it are just freed as usual. + constexpr size_t MAX_RELEASED_BLOCKS = 128; + PageBlockList released; + for (const auto& block : blocks.get()) { + block.tiles.add_chunks_to(released); + } + this->add_variable_storage_to(released); + released.release(); +} + +template void UltraCircuitBuilder_::release_recording_storage_pages() noexcept +{ + constexpr size_t BATCH_BLOCKS = 128; + BatchedPageRelease released( + PageReleaseFloors{ .min_block_bytes = RECORDING_RELEASE_MIN_BLOCK_BYTES, .min_total_bytes = 0 }); + // Only elements that own nothing: zeroing a vector of vectors would leak the inner ones. + const auto add = [&released](std::vector& vec) noexcept { + static_assert(std::is_trivially_destructible_v); + released.add(vec.data(), vec.capacity() * sizeof(T), vec.size() * sizeof(T)); + }; + for (const auto& block : blocks.get()) { + block.tiles.add_chunks_to(released); + } + this->add_variable_storage_to(released); + for (auto& [target_range, list] : range_lists) { + add(list.variable_indices); + } + for (auto& array : rom_ram_logic.rom_arrays) { + add(array.state); + add(array.records); + } + for (auto& array : rom_ram_logic.ram_arrays) { + add(array.state); + add(array.records); + } + for (auto& table : lookup_tables) { + add(table.column_1); + add(table.column_2); + add(table.column_3); + add(table.lookup_gate_rows); + } + add(memory_read_records); + add(memory_write_records); + add(rom_logup_records); + add(cached_partial_non_native_field_multiplications); + add(used_witnesses); + add(splice_log_->events); + add(splice_log_->constants); + add(splice_log_->range_lists); + released.release(); +} + template class UltraCircuitBuilder_; template class UltraCircuitBuilder_; template class UltraCircuitBuilder_; diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp index 6140c1e..aa0e29c 100644 --- a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp @@ -6,14 +6,18 @@ #pragma once #include "barretenberg/common/assert.hpp" +#include "barretenberg/common/deferred_value.hpp" #include "barretenberg/honk/execution_trace/generated/ultra_execution_trace_generated.hpp" #include "barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.hpp" #include "barretenberg/stdlib_circuit_builders/plookup_tables/types.hpp" #include "circuit_builder_base.hpp" +#include "circuit_splice.hpp" #include "rom_ram_logic.hpp" +#include #include #include +#include #include #include "barretenberg/serialize/msgpack.hpp" @@ -201,9 +205,51 @@ class UltraCircuitBuilder_ : public CircuitBuilderBase + void register_small_range_constraint(uint32_t variable_index, + uint64_t target_range, + ValueSource value_source, + std::string_view msg); + + // The range list of `target_range`, created if it does not exist yet. + RangeList& get_or_create_range_list(uint64_t target_range); + + // register_small_range_constraint for a variable the caller has just created and not yet tagged or + // copy-constrained, with its value: such a variable is its own real variable and carries DEFAULT_TAG, so it joins + // the list without the tag checks. `list` caches the list of the caller's previous registration. + void register_new_variable_range_constraint( + uint32_t variable_index, uint64_t target_range, uint64_t value, RangeList*& list, std::string_view msg); + + // create_lookup_gate with its q_3 selector, FF(table.table_index), supplied by the caller. + void append_lookup_gate(uint32_t key_idx, + uint32_t val1_idx, + uint32_t val2_idx, + plookup::BasicTable& table, + const plookup::BasicTable::LookupEntry& entry, + const FF& table_index_selector, + const FF& column_1_step_size, + const FF& column_2_step_size, + const FF& column_3_step_size) + requires(ExecutionTrace::has_gate_kind(GateKind::Lookup)); + // The set of lookup tables used by the circuit, plus the gate data for the lookups from each table std::deque lookup_tables; + // Set only on a builder constructed with SpliceRecording. + std::optional splice_log_; + + // The log of a recording builder, once its cancellation, if any, has let the recording go on. + SpliceLog& recording_log() + { + if (splice_log_->cancellation != nullptr) { + splice_log_->cancellation->check(); + } + return *splice_log_; + } + public: // Storage for wires and selectors for all gate types ExecutionTrace blocks; @@ -226,6 +272,22 @@ class UltraCircuitBuilder_ : public CircuitBuilderBase cached_partial_non_native_field_multiplications; std::vector ipa_proof; + // An IPA proof still being computed, held instead of ipa_proof until resolve_ipa_proof(). + DeferredValue> pending_ipa_proof; + + /** + * @brief Hand over an IPA proof that is still being computed; it replaces any proof set before. + */ + void set_pending_ipa_proof(DeferredValue> proof) + { + ipa_proof.clear(); + pending_ipa_proof = std::move(proof); + } + + /** + * @brief The IPA proof, after waiting for a pending one. Rethrows what computing a pending proof threw. + */ + const std::vector& resolve_ipa_proof() { return resolve_into(ipa_proof, pending_ipa_proof); } void populate_public_inputs_block(); @@ -274,10 +336,17 @@ class UltraCircuitBuilder_ : public CircuitBuilderBasereserve_variables( - std::max(witness_values.size() * VARIABLES_PER_ACIR_WITNESS_HINT, MIN_VARIABLES_RESERVE)); + const size_t hint = std::max(witness_values.size() * VARIABLES_PER_ACIR_WITNESS_HINT, MIN_VARIABLES_RESERVE); + // Mega circuits are built many in turn by one process. Hint-sized buffers may reuse warm heap blocks, where a + // reservation is a fresh mapping each time and its capacity qualifies all five arrays for the page release. + if constexpr (ExecutionTrace::IS_MEGA_ARITHMETIZATION) { + this->reserve_variables(hint); + } else { + this->reserve_variables_address_space(hint); + } for (const auto value : witness_values) { this->add_variable(value); } @@ -292,14 +361,63 @@ class UltraCircuitBuilder_ : public CircuitBuilderBasecheck()` when it is set. + */ + UltraCircuitBuilder_(SpliceRecording recording, std::span seed_values) + requires(!ExecutionTrace::IS_MEGA_ARITHMETIZATION) + : CircuitBuilderBase(false) + { + this->reserve_variables_address_space(seed_values.size() + 1); + for (const FF& value : seed_values) { + this->add_variable(value); + } + this->set_zero_idx(put_constant_variable(FF::zero())); + this->set_tau_at_index(DEFAULT_TAG, DEFAULT_TAG); + // splice treats every row after the zero constant's fixing row as recorded. + BB_ASSERT_EQ(blocks.get_total_content_size(), blocks.arithmetic.size()); + SpliceLog log; + log.num_seeds = static_cast(seed_values.size()); + log.num_prefix_variables = static_cast(this->get_num_variables()); + log.num_prefix_arithmetic_rows = blocks.arithmetic.size(); + log.num_prefix_gates = this->num_gates(); + log.num_prefix_used_witnesses = used_witnesses.size(); + log.cancellation = recording.cancellation; + splice_log_.emplace(std::move(log)); + } + UltraCircuitBuilder_(const UltraCircuitBuilder_& other) = default; UltraCircuitBuilder_(UltraCircuitBuilder_&& other) = default; UltraCircuitBuilder_& operator=(const UltraCircuitBuilder_& other) = default; UltraCircuitBuilder_& operator=(UltraCircuitBuilder_&& other) = default; - ~UltraCircuitBuilder_() override = default; + ~UltraCircuitBuilder_() override { release_storage_pages(); } void finalize_circuit(); + bool is_recording() const { return splice_log_.has_value(); } + + /** + * @brief Append the circuit built on `source` after its seeds, leaving this builder exactly as building that + * circuit here, on the variables `seed_indices`, would have left it. + * @details `source` was constructed with SpliceRecording on the values of the variables `seed_indices` of this + * builder, in that order, and the circuit was then built on it. Every precondition is checked before anything + * changes: neither builder has failed, is finalized or is in write-VK mode, and this one is not recording; each + * seed still has its source value; no two inputs share a copy cycle and none carries a tag, the inputs being the + * seeds and the zero and cached constants that a source tag reaches; the source added no public input, elliptic + * row, IPA proof or variable name, registered no lookup table with register_basic_lookup_table, did not finalize + * its public inputs, and its tag permutation holds only DEFAULT_TAG's entry and its range lists'. When one fails + * this builder is unchanged. Each source table becomes the table get_table gives for its id here, and its read + * records follow that table's. + * @return The refusal, or, when spliced, the index here of every source variable and the shift of the source's + * pairing-point tags, with which values built on `source` are rebound to this builder. + */ + SpliceResult splice(const UltraCircuitBuilder_& source, std::span seed_indices) + requires(!ExecutionTrace::IS_MEGA_ARITHMETIZATION); + void create_add_gate(const add_triple_& in); void create_big_mul_add_gate(const mul_quad_& in, const bool use_next_gate_w_4 = false); void create_big_add_gate(const add_quad_& in, const bool use_next_gate_w_4 = false); @@ -422,6 +540,14 @@ class UltraCircuitBuilder_ : public CircuitBuilderBase::assert_equal(a_idx, b_idx, msg); + } + void assert_equal_constant(const uint32_t a_idx, const FF& b, std::string const& msg = "assert equal constant") { if (this->get_variable(a_idx) != b && !this->failed()) { @@ -539,6 +665,9 @@ class UltraCircuitBuilder_ : public CircuitBuilderBasereal_variable_tags[this->real_variable_index[variable_index]], DEFAULT_TAG); + if (splice_log_.has_value()) [[unlikely]] { + recording_log().events.push_back({ SpliceLog::Event::Kind::Tag, variable_index, tag }); + } this->real_variable_tags[this->real_variable_index[variable_index]] = tag; } /** @@ -581,6 +710,31 @@ class UltraCircuitBuilder_ : public CircuitBuilderBase>; + // process_range_list with a bitmap that is kept, all clear, for the next list. + void process_range_list(RangeList& list, VariableBitmap& real_variables); + // One delta-range row per `NUM_WIRES` consecutive entries of `variable_indices`. + void append_delta_range_rows(const std::vector& variable_indices); + + public: /** * Custom Gate Selectors **/ diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_address_space.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_address_space.test.cpp new file mode 100644 index 0000000..c6120f1 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_address_space.test.cpp @@ -0,0 +1,111 @@ +#include "barretenberg/common/address_space_reserve.hpp" +#include "barretenberg/stdlib_circuit_builders/mega_circuit_builder.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include +#include +#include +#include +#include +#include + +namespace bb { +namespace { + +using Builder = UltraCircuitBuilder; +using Reservation = Builder::VariablesReservation; + +// The capacities of the per-variable vectors a test can reach (next_var_index and prev_var_index are private). +template std::array capacities(const B& builder) +{ + return { builder.get_variables().capacity(), + builder.real_variable_index.capacity(), + builder.real_variable_tags.capacity() }; +} + +// Checks what the constructor reserved: an attempt exactly when this process allows one, and the reservation or else +// at least `hint` entries in each reachable per-variable vector. +void check_reservation(const Builder& builder, size_t hint) +{ + const Reservation state = builder.variables_reservation(); + EXPECT_EQ(state != Reservation::NotAttempted, address_space_reservation_allowed()); + for (const size_t capacity : capacities(builder)) { + if (state == Reservation::Reserved) { + EXPECT_GE(capacity, Builder::VARIABLES_ADDRESS_SPACE_ENTRIES); + } else { + EXPECT_GE(capacity, hint); + EXPECT_LT(capacity, Builder::VARIABLES_ADDRESS_SPACE_ENTRIES); + } + } +} + +// Adds variables until `builder` holds `num_variables`, then checks that the variables `values` were given at +// construction still hold them and, where the builder holds the reservation, that the storage never moved. +template void grow_and_check(B& builder, const std::vector& values, size_t num_variables) +{ + const bool reserved = builder.variables_reservation() == Reservation::Reserved; + const fr* const storage = builder.get_variables().data(); + while (builder.get_num_variables() < num_variables) { + builder.add_variable(fr(builder.get_num_variables())); + } + for (size_t i = 0; i < values.size(); ++i) { + EXPECT_EQ(builder.get_variable(static_cast(i)), values[i]); + } + if (reserved) { + EXPECT_EQ(builder.get_variables().data(), storage); + } +} + +// 1000 witnesses, whose hint is max(4 * 1000, 65536) variables. +std::vector acir_witness() +{ + std::vector witness(1000); + for (size_t i = 0; i < witness.size(); ++i) { + witness[i] = fr(7 * i + 1); + } + return witness; +} + +TEST(UltraCircuitBuilderAddressSpace, AcirBuilderGrowsPastItsHint) +{ + const std::vector witness = acir_witness(); + Builder builder(witness, /*public_inputs=*/std::vector{}, /*is_write_vk_mode=*/false); + check_reservation(builder, 65536); + grow_and_check(builder, witness, (size_t{ 1 } << 17) + 1); +} + +// A Mega circuit from ACIR keeps the witness-count hint whatever this process allows. +TEST(UltraCircuitBuilderAddressSpace, MegaAcirBuilderKeepsItsHint) +{ + const std::vector witness = acir_witness(); + MegaCircuitBuilder builder( + std::make_shared(), witness, /*public_inputs=*/std::vector{}, /*is_write_vk_mode=*/false); + EXPECT_EQ(builder.variables_reservation(), Reservation::NotAttempted); + for (const size_t capacity : capacities(builder)) { + EXPECT_GE(capacity, 65536U); + EXPECT_LT(capacity, Builder::VARIABLES_ADDRESS_SPACE_ENTRIES); + } + grow_and_check(builder, witness, (size_t{ 1 } << 17) + 1); +} + +// The reservation state is not part of a builder's identity: the call changes only `b`'s capacity and state. +TEST(UltraCircuitBuilderAddressSpace, ReservationStateIsNotCompared) +{ + const Builder a; + Builder b; + b.reserve_variables_address_space(1); + EXPECT_EQ(a.variables_reservation() != b.variables_reservation(), address_space_reservation_allowed()); + EXPECT_TRUE(static_cast&>(a) == static_cast&>(b)); +} + +TEST(UltraCircuitBuilderAddressSpace, SeedBuilderGrowsPastItsHint) +{ + const std::vector seeds{ fr(3), fr(5), fr(7) }; + Builder builder(SpliceRecording{}, seeds); + // The hint for three seeds is four variables. + check_reservation(builder, 4); + grow_and_check(builder, seeds, 4096); +} + +} // namespace +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_splice.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_splice.cpp new file mode 100644 index 0000000..7fb4ca5 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_splice.cpp @@ -0,0 +1,528 @@ +#include "ultra_circuit_builder.hpp" + +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/thread.hpp" +#include "barretenberg/numeric/uint256/uint256.hpp" +#include "bounded_range_sort.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace bb { + +namespace { + +// Each row-copy task covers at least this many rows, ending on a tile boundary so that tasks share no tile. +constexpr size_t MIN_ROWS_PER_TASK = size_t{ 1 } << 12; +// The values of new variables are copied in chunks of at least this many: a chunk outweighs a parallel dispatch. +constexpr size_t MIN_VARIABLES_PER_CHUNK = size_t{ 1 } << 15; + +// Consecutive source positions copied to consecutive destination positions. +struct Run { + size_t source; + size_t destination; + size_t count; +}; + +// The runs of [begin, end) outside the half-open intervals `dropped`, numbered consecutively from destination 0. +std::vector runs_outside(const size_t begin, const size_t end, std::vector> dropped) +{ + std::ranges::sort(dropped); + std::vector runs; + size_t next = begin; + size_t destination = 0; + for (const auto& [lo, hi] : dropped) { + if (lo > next) { + runs.push_back({ .source = next, .destination = destination, .count = lo - next }); + destination += lo - next; + } + next = std::max(next, hi); + } + if (end > next) { + runs.push_back({ .source = next, .destination = destination, .count = end - next }); + } + return runs; +} + +size_t total_count(const std::vector& runs) +{ + return runs.empty() ? 0 : runs.back().destination + runs.back().count; +} + +// Calls body(source, destination, count) for the parts of `runs` covering destinations [begin, end), in order. +template +void for_each_run_part(const std::vector& runs, const size_t begin, const size_t end, const Body& body) +{ + if (begin >= end) { + return; + } + // The first run starts at destination 0, so the run holding `begin` precedes the first run starting after it. + auto it = std::ranges::upper_bound(runs, begin, {}, &Run::destination); + for (--it; it != runs.end() && it->destination < end; ++it) { + const size_t lo = std::max(begin, it->destination); + const size_t hi = std::min(end, it->destination + it->count); + body(it->source + (lo - it->destination), lo, hi - lo); + } +} + +bool has_bit(const std::vector& bits, const uint32_t index) +{ + return ((bits[index >> 6] >> (index & 63)) & 1) != 0; +} + +} // namespace + +template +SpliceResult UltraCircuitBuilder_::splice(const UltraCircuitBuilder_& source, + const std::span seed_indices) + requires(!ExecutionTrace::IS_MEGA_ARITHMETIZATION) +{ + const auto refuse = [](const SpliceRefusal refusal) { return SpliceResult{ .refusal = refusal }; }; + + if (!source.splice_log_.has_value() || source.splice_log_->num_seeds != seed_indices.size() || + splice_log_.has_value() || this->circuit_finalized || source.circuit_finalized || this->is_write_vk_mode() || + source.is_write_vk_mode()) { + return refuse(SpliceRefusal::BuilderState); + } + const SpliceLog& log = *source.splice_log_; + if (this->failed() || source.failed()) { + return refuse(SpliceRefusal::Failed); + } + if (!source.public_inputs().empty() || source.blocks.pub_inputs.size() != 0 || source.public_inputs_finalized()) { + return refuse(SpliceRefusal::PublicInput); + } + if (source.blocks.elliptic.size() != 0) { + return refuse(SpliceRefusal::RowForm); + } + const PairingPointsTagging& source_tagging = source.pairing_points_tagging; + if (log.registered_table || !source.ipa_proof.empty() || source.pending_ipa_proof.valid() || + !source.variable_names.empty() || source_tagging.has_public_pairing_points() || + (source_tagging.num_tags() != 0 && this->pairing_points_tagging.has_public_pairing_points())) { + return refuse(SpliceRefusal::UnknownForm); + } + // Each source table, which get_table created, becomes the table get_table gives for its id here: the first table + // of that id, or a new one, created in the order the source first read its tables and so numbered as building the + // source's rows here would number it. The source numbered each table by its position, which a row's q_3 holds. + const std::deque& source_tables = source.lookup_tables; + std::vector table_targets(source_tables.size(), nullptr); + std::vector table_numbers(source_tables.size()); + size_t num_new_tables = 0; + for (size_t p = 0; p < source_tables.size(); ++p) { + if (source_tables[p].table_index != p + 1) { + return refuse(SpliceRefusal::UnknownForm); + } + const auto it = std::ranges::find(lookup_tables, source_tables[p].id, &plookup::BasicTable::id); + if (it != lookup_tables.end()) { + table_targets[p] = &*it; + table_numbers[p] = FF(it->table_index); + } else { + table_numbers[p] = FF(lookup_tables.size() + ++num_new_tables); + } + } + const auto source_table_position = [](const FF& q_3) { return static_cast(uint256_t(q_3).data[0] - 1); }; + const ExecutionTraceBlockStorage& source_lookup = source.blocks.lookup; + FF last_table_number = FF::zero(); + for (size_t row = 0; row < source_lookup.size(); ++row) { + const FF q_3 = source_lookup.q_3()[row]; + if (q_3 != last_table_number) { + const uint256_t number(q_3); + if (number == 0 || number > source_tables.size()) { + return refuse(SpliceRefusal::UnknownForm); + } + last_table_number = q_3; + } + } + // Every source tag belongs to a recorded range list, and every source constant but zero was recorded. The tag + // permutation fixes DEFAULT_TAG and swaps the two tags of each recorded range list, and holds nothing else. + const std::unordered_map& source_tau = source.tau(); + const auto tau_maps = [&source_tau](const uint32_t from, const uint32_t to) { + const auto it = source_tau.find(from); + return it != source_tau.end() && it->second == to; + }; + if (source.get_current_tag() != 2 * log.range_lists.size() || source.range_lists.size() != log.range_lists.size() || + source.constant_variable_indices.size() != log.constants.size() + 1 || + source_tau.size() != 1 + (2 * log.range_lists.size()) || !tau_maps(DEFAULT_TAG, DEFAULT_TAG)) { + return refuse(SpliceRefusal::UnknownForm); + } + std::vector source_lists(log.range_lists.size()); + for (size_t l = 0; l < log.range_lists.size(); ++l) { + const auto& recorded = log.range_lists[l]; + const auto it = source.range_lists.find(recorded.target_range); + if (it == source.range_lists.end() || it->second.range_tag != recorded.range_tag || + it->second.tau_tag != recorded.range_tag + 1 || + it->second.variable_indices.size() < recorded.staircase_size || + !tau_maps(recorded.range_tag, recorded.range_tag + 1) || + !tau_maps(recorded.range_tag + 1, recorded.range_tag)) { + return refuse(SpliceRefusal::UnknownForm); + } + source_lists[l] = &it->second; + } + + const size_t num_seeds = seed_indices.size(); + const std::vector& source_values = source.get_variables(); + // The real variable here of each input, which must be untagged and in a copy cycle of its own. + std::vector input_classes; + input_classes.reserve(num_seeds + 1); + for (size_t i = 0; i < num_seeds; ++i) { + const uint32_t index = seed_indices[i]; + BB_ASSERT_LT(index, this->get_num_variables(), "splice: seed index out of range"); + if (source_values[i] != this->get_variable(index)) { + return refuse(SpliceRefusal::InputValue); + } + const uint32_t real_index = this->real_variable_index[index]; + if (this->real_variable_tags[real_index] != DEFAULT_TAG) { + return refuse(SpliceRefusal::InputTag); + } + input_classes.push_back(real_index); + } + std::vector sorted_seeds(seed_indices.begin(), seed_indices.end()); + std::ranges::sort(sorted_seeds); + // The source compares variable indices, so no seed may coincide with another variable the source shares. + const auto is_seed = [&](const uint32_t index) { return std::ranges::binary_search(sorted_seeds, index); }; + + const size_t num_source_variables = source.get_num_variables(); + std::vector index_map(num_source_variables); + std::ranges::copy(seed_indices, index_map.begin()); + index_map[source.zero_idx()] = this->zero_idx(); + // Source variables that are this builder's: the zero, then constants cached here. + std::vector shared_variables{ source.zero_idx() }; + + // A source constant whose value is cached here is the cached variable, without its fixing row or used-witness + // entry. + std::vector> dropped_variables; + std::vector> dropped_rows; + std::vector dropped_used_witnesses; + std::vector constant_cached(log.constants.size(), 0); + for (size_t c = 0; c < log.constants.size(); ++c) { + const auto& constant = log.constants[c]; + const auto it = constant_variable_indices.find(source_values[constant.variable]); + if (it == constant_variable_indices.end()) { + continue; + } + constant_cached[c] = 1; + index_map[constant.variable] = it->second; + shared_variables.push_back(constant.variable); + dropped_variables.emplace_back(constant.variable, constant.variable + 1); + dropped_rows.emplace_back(constant.arithmetic_row, constant.arithmetic_row + 1); + dropped_used_witnesses.push_back(constant.used_witness); + } + for (const uint32_t shared : shared_variables) { + if (is_seed(index_map[shared])) { + return refuse(SpliceRefusal::InputCycle); + } + } + + // A source range list whose range has a list here is that list: its staircase is this list's staircase, without + // its rows. + std::vector target_lists(log.range_lists.size(), nullptr); + for (size_t l = 0; l < log.range_lists.size(); ++l) { + const auto& recorded = log.range_lists[l]; + const auto it = range_lists.find(recorded.target_range); + if (it == range_lists.end()) { + continue; + } + const std::vector& target_staircase = it->second.variable_indices; + const std::vector& source_staircase = source_lists[l]->variable_indices; + const size_t staircase_size = recorded.staircase_size; + if (target_staircase.size() < staircase_size) { + return refuse(SpliceRefusal::UnknownForm); + } + const size_t first = source_staircase[0]; + for (size_t q = 0; q < staircase_size; ++q) { + if (source_staircase[q] != first + q) { + return refuse(SpliceRefusal::UnknownForm); + } + if (is_seed(target_staircase[q])) { + return refuse(SpliceRefusal::InputCycle); + } + index_map[first + q] = target_staircase[q]; + } + target_lists[l] = &it->second; + dropped_variables.emplace_back(first, first + staircase_size); + dropped_rows.emplace_back(recorded.arithmetic_row, + recorded.arithmetic_row + ((staircase_size + NUM_WIRES - 1) / NUM_WIRES)); + } + + // A shared variable in a source class that a tag reaches decides range constraints, which read the class tag: it + // has to be untagged here and in a copy cycle of its own among the inputs, as it is in the source. + std::vector tagged_classes((num_source_variables + 63) / 64, 0); + for (const auto& event : log.events) { + if (event.kind == SpliceLog::Event::Kind::Tag) { + const uint32_t source_class = source.real_variable_index[event.a]; + tagged_classes[source_class >> 6] |= uint64_t{ 1 } << (source_class & 63); + } + } + for (const uint32_t shared : shared_variables) { + if (!has_bit(tagged_classes, source.real_variable_index[shared])) { + continue; + } + const uint32_t real_index = this->real_variable_index[index_map[shared]]; + if (this->real_variable_tags[real_index] != DEFAULT_TAG) { + return refuse(SpliceRefusal::InputTag); + } + input_classes.push_back(real_index); + } + std::ranges::sort(input_classes); + if (std::ranges::adjacent_find(input_classes) != input_classes.end()) { + return refuse(SpliceRefusal::InputCycle); + } + + // Every precondition holds: from here on the builder changes. + + // The tags of a source list are its list's here, or a fresh pair, allocated in the order the lists were created. + std::vector tag_map(source.get_current_tag() + 1, DEFAULT_TAG); + for (size_t l = 0; l < log.range_lists.size(); ++l) { + const uint32_t range_tag = log.range_lists[l].range_tag; + if (target_lists[l] != nullptr) { + tag_map[range_tag] = target_lists[l]->range_tag; + tag_map[range_tag + 1] = target_lists[l]->tau_tag; + } else { + const uint32_t new_range_tag = get_new_tag(); + const uint32_t new_tau_tag = get_new_tag(); + set_tau_transposition(new_range_tag, new_tau_tag); + tag_map[range_tag] = new_range_tag; + tag_map[range_tag + 1] = new_tau_tag; + } + } + + // The kept source variables, in source order, become new variables here. + const std::vector variable_runs = + runs_outside(log.num_prefix_variables, num_source_variables, std::move(dropped_variables)); + const size_t num_new_variables = total_count(variable_runs); + const size_t first_new_variable = this->get_num_variables(); + this->add_tagged_variables(num_new_variables, DEFAULT_TAG, [&](const std::span values) { + range_sort::Chunks::of_min_size(num_new_variables, MIN_VARIABLES_PER_CHUNK) + .run([&](size_t /*chunk*/, const size_t begin, const size_t end) { + for_each_run_part( + variable_runs, begin, end, [&](const size_t from, const size_t to, const size_t count) { + std::copy_n(source_values.data() + from, count, values.data() + to); + std::iota(index_map.data() + from, + index_map.data() + from + count, + static_cast(first_new_variable + to)); + }); + }); + }); + + // The kept source rows of each block are appended to it, wires through the index map, copied by tasks over + // contiguous row ranges of all blocks. + struct BlockCopy { + ExecutionTraceBlockStorage* target; + const ExecutionTraceBlockStorage* source; + std::vector runs; + size_t first_row; + // The target's id of each of the source's selector value ids (blocks dedup their selector values). + typename ExecutionTraceBlockStorage::ValueIdMaps value_ids; + }; + const size_t memory_offset = blocks.memory.size(); + const size_t lookup_offset = blocks.lookup.size(); + const size_t rom_offset = rom_ram_logic.rom_arrays.size(); + auto target_blocks = blocks.get(); + auto source_blocks = source.blocks.get(); + std::vector copies; + size_t num_rows = 0; + size_t num_dropped_rows = 0; + for (size_t b = 0; b < target_blocks.size(); ++b) { + const ExecutionTraceBlockStorage& from = source_blocks[b]; + const bool is_arithmetic = &from == &source.blocks.arithmetic; + const size_t begin = is_arithmetic ? log.num_prefix_arithmetic_rows : 0; + std::vector runs = runs_outside( + begin, from.size(), is_arithmetic ? std::move(dropped_rows) : std::vector>{}); + const size_t count = total_count(runs); + num_dropped_rows += from.size() - begin - count; + if (count == 0) { + continue; + } + num_rows += count; + copies.push_back({ .target = &target_blocks[b], .source = &from, .runs = std::move(runs), .first_row = 0 }); + } + const size_t rows_per_task = std::max(MIN_ROWS_PER_TASK, (num_rows + get_num_cpus() - 1) / get_num_cpus()); + struct Task { + size_t copy; + size_t begin; + size_t end; + }; + std::vector tasks; + for (size_t c = 0; c < copies.size(); ++c) { + BlockCopy& copy = copies[c]; + const size_t count = total_count(copy.runs); + copy.first_row = copy.target->grow_rows_for_overwrite(count); + // Serial: interning may add values to the target's tables, which the concurrent copies below only read. + copy.value_ids = copy.target->intern_values_of(*copy.source); + for (size_t begin = 0; begin < count;) { + const size_t aligned_end = (copy.first_row + begin + rows_per_task + GATE_TILE_MASK) & ~GATE_TILE_MASK; + const size_t end = std::min(count, aligned_end - copy.first_row); + tasks.push_back({ .copy = c, .begin = begin, .end = end }); + begin = end; + } + } + const auto run_task = [&](const size_t t) { + const Task& task = tasks[t]; + const BlockCopy& copy = copies[task.copy]; + for_each_run_part(copy.runs, task.begin, task.end, [&](const size_t from, const size_t to, const size_t count) { + copy.target->copy_translated_rows( + *copy.source, from, copy.first_row + to, count, index_map.data(), copy.value_ids); + }); + }; + if (tasks.size() == 1) { + run_task(0); + } else if (!tasks.empty()) { + parallel_for(tasks.size(), run_task); + } + this->increment_num_gates(source.num_gates() - log.num_prefix_gates - num_dropped_rows); + // A ROM-LogUp row carries its array id in q_c; source arrays follow the arrays here. + if (rom_offset != 0) { + for (const uint32_t gate : source.rom_logup_records) { + const uint64_t rom_id = uint256_t(source.blocks.memory.q_c()[gate]).data[0]; + blocks.memory.q_c().set(memory_offset + gate, FF(rom_id + rom_offset)); + } + } + + // A source table's read records follow those of its table here; a new table is the source's, renumbered. + for (size_t p = 0; p < source_tables.size(); ++p) { + const plookup::BasicTable& from = source_tables[p]; + if (table_targets[p] == nullptr) { + lookup_tables.push_back(from); + lookup_tables.back().table_index = lookup_tables.size(); + } else { + // Tables of one id have the same rows, so the source's rows are rows of the target table too. + std::vector& records = table_targets[p]->lookup_gate_rows; + records.insert(records.end(), from.lookup_gate_rows.begin(), from.lookup_gate_rows.end()); + } + } + // A lookup row carries its table's number in q_3; consecutive rows mostly read one table. + if (!source_tables.empty()) { + FF last_source = FF::zero(); + FF last_target = FF::zero(); + for (size_t row = lookup_offset; row < blocks.lookup.size(); ++row) { + // A copy: a selector reference is only valid until the next set on the block. + const FF q_3 = blocks.lookup.q_3()[row]; + if (q_3 != last_source) { + last_source = q_3; + last_target = table_numbers[source_table_position(q_3)]; + } + blocks.lookup.q_3().set(row, last_target); + } + } + + for (size_t l = 0; l < log.range_lists.size(); ++l) { + const std::vector& from = source_lists[l]->variable_indices; + if (target_lists[l] != nullptr) { + std::vector& to = target_lists[l]->variable_indices; + const size_t staircase_size = log.range_lists[l].staircase_size; + for (size_t q = staircase_size; q < from.size(); ++q) { + to.push_back(index_map[from[q]]); + } + } else { + const uint32_t range_tag = log.range_lists[l].range_tag; + RangeList list{ .target_range = log.range_lists[l].target_range, + .range_tag = tag_map[range_tag], + .tau_tag = tag_map[range_tag + 1], + .variable_indices = {} }; + list.variable_indices.reserve(from.size()); + for (const uint32_t variable : from) { + list.variable_indices.push_back(index_map[variable]); + } + range_lists.emplace(list.target_range, std::move(list)); + } + } + + // Copy cycles and tags, replayed in source order. A tag write equals assign_tag's: the inputs it can reach are + // untagged here. + const std::string assert_equal_message = "assert_equal"; + for (const auto& event : log.events) { + if (event.kind == SpliceLog::Event::Kind::AssertEqual) { + CircuitBuilderBase::assert_equal(index_map[event.a], index_map[event.b], assert_equal_message); + } else { + this->real_variable_tags[this->real_variable_index[index_map[event.a]]] = tag_map[event.b]; + } + } + + for (size_t c = 0; c < log.constants.size(); ++c) { + if (constant_cached[c] == 0) { + const uint32_t variable = log.constants[c].variable; + constant_variable_indices.emplace(source_values[variable], index_map[variable]); + } + } + + cached_partial_non_native_field_multiplications.reserve( + cached_partial_non_native_field_multiplications.size() + + source.cached_partial_non_native_field_multiplications.size()); + for (auto entry : source.cached_partial_non_native_field_multiplications) { + for (size_t limb = 0; limb < 4; ++limb) { + entry.a[limb] = index_map[entry.a[limb]]; + entry.b[limb] = index_map[entry.b[limb]]; + } + entry.lo_0 = index_map[entry.lo_0]; + entry.hi_0 = index_map[entry.hi_0]; + entry.hi_1 = index_map[entry.hi_1]; + cached_partial_non_native_field_multiplications.push_back(entry); + } + + const auto map_cell = [&](const uint32_t cell) { + return cell == UNINITIALIZED_MEMORY_RECORD ? cell : index_map[cell]; + }; + for (RomTranscript array : source.rom_ram_logic.rom_arrays) { + for (auto& cell : array.state) { + cell = { map_cell(cell[0]), map_cell(cell[1]) }; + } + for (auto& record : array.records) { + record.index_witness = index_map[record.index_witness]; + record.value_column1_witness = index_map[record.value_column1_witness]; + record.value_column2_witness = index_map[record.value_column2_witness]; + record.record_witness = index_map[record.record_witness]; + record.gate_index += memory_offset; + } + rom_ram_logic.rom_arrays.push_back(std::move(array)); + } + for (RamTranscript array : source.rom_ram_logic.ram_arrays) { + for (auto& cell : array.state) { + cell = map_cell(cell); + } + for (auto& record : array.records) { + record.index_witness = index_map[record.index_witness]; + record.timestamp_witness = index_map[record.timestamp_witness]; + record.value_witness = index_map[record.value_witness]; + record.record_witness = index_map[record.record_witness]; + record.gate_index += memory_offset; + } + rom_ram_logic.ram_arrays.push_back(std::move(array)); + } + const auto append_gates = [&](const std::vector& from, std::vector& to) { + for (const uint32_t gate : from) { + to.push_back(static_cast(gate + memory_offset)); + } + }; + append_gates(source.memory_read_records, memory_read_records); + append_gates(source.memory_write_records, memory_write_records); + append_gates(source.rom_logup_records, rom_logup_records); + + const uint32_t pairing_tag_offset = this->pairing_points_tagging.append_shifted(source_tagging); + + // Constants were recorded in creation order, so their used-witness positions ascend. + size_t next_dropped = 0; + for (size_t k = log.num_prefix_used_witnesses; k < source.used_witnesses.size(); ++k) { + if (next_dropped < dropped_used_witnesses.size() && dropped_used_witnesses[next_dropped] == k) { + ++next_dropped; + continue; + } + used_witnesses.push_back(index_map[source.used_witnesses[k]]); + } + for (const uint32_t variable : source.finalize_witnesses) { + finalize_witnesses.insert(index_map[variable]); + } + + SpliceResult result; + result.index_map = std::move(index_map); + result.pairing_tag_offset = pairing_tag_offset; + return result; +} + +template SpliceResult UltraCircuitBuilder_::splice( + const UltraCircuitBuilder_& source, std::span seed_indices); + +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_splice.test.cpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_splice.test.cpp new file mode 100644 index 0000000..54f9089 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_splice.test.cpp @@ -0,0 +1,429 @@ +#include "barretenberg/common/assert.hpp" +#include "barretenberg/common/throw_or_abort.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp" + +#include +#include +#include +#include +#include +#include + +/** + * A circuit built on a recording builder seeded with the values of some variables of a target builder, then spliced + * into the target, must leave the target exactly as building the same circuit on the target itself does; a refused + * splice must leave the target unchanged. + */ + +namespace bb { +namespace { + +using Builder = UltraCircuitBuilder; + +using test_utils::expect_same_builder; +using test_utils::expect_same_builder_state; + +// Variables a circuit returns, as indices in the builder it ran on, and the pairing-point tags it created. +struct Outputs { + std::vector variables; + std::vector pairing_tags; +}; + +using Circuit = std::function&)>; + +// A new variable that appears in a wire, as a range constraint requires. +uint32_t add_witness(Builder& builder, const fr& value) +{ + const uint32_t index = builder.add_variable(value); + builder.create_unconstrained_gate( + builder.blocks.arithmetic, index, builder.zero_idx(), builder.zero_idx(), builder.zero_idx()); + return index; +} + +// A target builder that already holds constants, range lists, ROM and RAM arrays, cached multiplications and +// pairing-point tags that the circuits below meet again. +struct Target { + Builder builder; + // Input variables: inputs[0] and inputs[3] have equal values. + std::vector inputs; + + Target() + { + for (const uint64_t value : { 5ULL, 1000ULL, 77ULL, 5ULL, 123456ULL, 9ULL }) { + inputs.push_back(builder.add_variable(fr(value))); + } + builder.put_constant_variable(fr(3)); + builder.put_constant_variable(fr(7)); + const uint32_t small = add_witness(builder, fr(200)); + builder.create_small_range_constraint(small, 255); + const uint32_t wide = builder.add_variable(fr(40000)); + builder.create_limbed_range_constraint(wide, 20); + const size_t rom = builder.create_ROM_array(2); + builder.set_ROM_element(rom, 0, small); + builder.set_ROM_element(rom, 1, wide); + const size_t ram = builder.create_RAM_array(1); + builder.init_RAM_element(ram, 0, small); + builder.queue_partial_non_native_field_multiplication( + { .a = { small, wide, small, wide }, .b = { wide, wide, small, small } }); + builder.pairing_points_tagging.create_pairing_point_tag(); + } +}; + +// Constants cached in the target and new ones, existing and new range lists, ROM, RAM, non-native multiplication, +// assert_equal on seeds, and enough arithmetic rows for more than one copy task. Expects six inputs, the fourth equal +// to the first. +Outputs mixed_circuit(Builder& builder, const std::vector& in) +{ + const uint32_t zero = builder.zero_idx(); + const uint32_t three = builder.put_constant_variable(fr(3)); + const uint32_t eleven = builder.put_constant_variable(fr(11)); + BB_ASSERT_EQ(builder.put_constant_variable(fr(11)), eleven); + + const fr x_value = builder.get_variable(in[0]) * builder.get_variable(in[1]) + fr(3); + const uint32_t x = builder.add_variable(x_value); + builder.create_big_mul_add_gate({ .a = in[0], + .b = in[1], + .c = x, + .d = three, + .mul_scaling = 1, + .a_scaling = 0, + .b_scaling = 0, + .c_scaling = -1, + .d_scaling = 1, + .const_scaling = 0 }); + const uint32_t y = builder.add_variable(x_value + fr(11)); + builder.create_add_gate( + { .a = x, .b = eleven, .c = y, .a_scaling = 1, .b_scaling = 1, .c_scaling = -1, .const_scaling = 0 }); + // The fifth input is the second again. + builder.create_add_gate( + { .a = in[1], .b = in[4], .c = zero, .a_scaling = 1, .b_scaling = -1, .c_scaling = 0, .const_scaling = 0 }); + + // Lists of ranges 255, 63 and 2^14 - 1 exist in the target; 1023 and 4095 do not. + builder.create_small_range_constraint(add_witness(builder, fr(200)), 255); + builder.create_small_range_constraint(in[2], 1023); + builder.create_limbed_range_constraint(in[1], 20); + const uint32_t lo = add_witness(builder, fr(uint256_t(1) << 60)); + const uint32_t hi = add_witness(builder, fr(12345)); + builder.range_constrain_two_limbs(lo, hi); + + const size_t rom = builder.create_ROM_array(3); + builder.set_ROM_element(rom, 0, in[0]); + builder.set_ROM_element(rom, 1, x); + builder.set_ROM_element(rom, 2, eleven); + const uint32_t one = builder.add_variable(fr(1)); + const uint32_t rom_read = builder.read_ROM_array(rom, one); + + const size_t ram = builder.create_RAM_array(2); + builder.init_RAM_element(ram, 0, in[0]); + builder.init_RAM_element(ram, 1, in[2]); + builder.write_RAM_array(ram, one, x); + const uint32_t ram_read = builder.read_RAM_array(ram, one); + + const auto [nnf_lo, nnf_hi] = builder.queue_partial_non_native_field_multiplication( + { .a = { in[0], in[1], x, three }, .b = { y, in[2], three, in[5] } }); + + builder.assert_equal(in[0], in[3]); + builder.assert_equal_constant(in[0], builder.get_variable(in[0])); + const uint32_t copy = add_witness(builder, builder.get_variable(in[2])); + builder.assert_equal(copy, in[2]); + builder.create_small_range_constraint(copy, 1023); + builder.update_used_witnesses(x); + + fr accumulator = builder.get_variable(y); + uint32_t previous = y; + for (size_t i = 0; i < 5000; ++i) { + accumulator += builder.get_variable(in[5]); + const uint32_t next = builder.add_variable(accumulator); + builder.create_add_gate({ .a = previous, + .b = in[5], + .c = next, + .a_scaling = 1, + .b_scaling = 1, + .c_scaling = -1, + .const_scaling = 0 }); + previous = next; + } + + auto& tagging = builder.pairing_points_tagging; + const uint32_t first_tag = tagging.create_pairing_point_tag(); + const uint32_t second_tag = tagging.create_pairing_point_tag(); + const std::array aggregated{ first_tag, second_tag }; + const uint32_t result_tag = tagging.aggregate_pairing_point_tags(aggregated); + + return { .variables = { x, y, rom_read, ram_read, nnf_lo, nnf_hi, copy, previous, eleven }, + .pairing_tags = { first_tag, second_tag, result_tag } }; +} + +// Meets the constant 11 and the range 1023 again, and tags the cached constant 11. Expects two inputs. +Outputs follow_up_circuit(Builder& builder, const std::vector& in) +{ + const uint32_t eleven = builder.put_constant_variable(fr(11)); + const uint32_t thirteen = builder.put_constant_variable(fr(13)); + builder.create_small_range_constraint(eleven, 1023); + const uint32_t sum = add_witness(builder, builder.get_variable(in[0]) + builder.get_variable(in[1])); + builder.create_add_gate( + { .a = in[0], .b = in[1], .c = sum, .a_scaling = 1, .b_scaling = 1, .c_scaling = -1, .const_scaling = 0 }); + builder.create_small_range_constraint(add_witness(builder, fr(1000)), 1023); + builder.create_dyadic_range_constraint(add_witness(builder, fr(100)), 7, "follow up"); + builder.assert_equal(sum, add_witness(builder, builder.get_variable(sum))); + return { .variables = { eleven, thirteen, sum }, .pairing_tags = {} }; +} + +// The seeds of `inputs`, one per distinct index in order of first appearance, and each input's seed position. +struct Seeds { + std::vector indices; + std::vector values; + std::vector positions; + + Seeds(const Builder& builder, const std::vector& inputs) + { + for (const uint32_t input : inputs) { + const auto it = std::ranges::find(indices, input); + positions.push_back(static_cast(it - indices.begin())); + if (it == indices.end()) { + indices.push_back(input); + values.push_back(builder.get_variable(input)); + } + } + } +}; + +// Builds `circuit` on `serial` and, through a recording builder, splices it into `target`; checks the outputs map. +SpliceResult build_both_ways(Builder& serial, + Builder& target, + const std::vector& inputs, + const Circuit& circuit) +{ + const Outputs serial_outputs = circuit(serial, inputs); + const Seeds seeds(target, inputs); + Builder recording(SpliceRecording{}, seeds.values); + const Outputs recorded_outputs = circuit(recording, seeds.positions); + SpliceResult result = target.splice(recording, seeds.indices); + if (result.spliced()) { + EXPECT_EQ(result.index_map.size(), recording.get_num_variables()); + for (size_t i = 0; i < serial_outputs.variables.size(); ++i) { + EXPECT_EQ(result.index_map[recorded_outputs.variables[i]], serial_outputs.variables[i]); + } + for (size_t i = 0; i < serial_outputs.pairing_tags.size(); ++i) { + EXPECT_EQ(recorded_outputs.pairing_tags[i] + result.pairing_tag_offset, serial_outputs.pairing_tags[i]); + } + } + return result; +} + +TEST(UltraCircuitBuilderSplice, MatchesSerialBuild) +{ + Target target; + Builder serial = target.builder; + const std::vector inputs{ + target.inputs[0], target.inputs[1], target.inputs[2], target.inputs[3], target.inputs[1], target.inputs[5], + }; + const SpliceResult result = build_both_ways(serial, target.builder, inputs, mixed_circuit); + ASSERT_EQ(result.refusal, SpliceRefusal::None); + expect_same_builder(target.builder, serial); +} + +TEST(UltraCircuitBuilderSplice, TwoSplicesInARow) +{ + Target target; + Builder serial = target.builder; + const std::vector first_inputs{ + target.inputs[0], target.inputs[1], target.inputs[2], target.inputs[3], target.inputs[1], target.inputs[5], + }; + ASSERT_EQ(build_both_ways(serial, target.builder, first_inputs, mixed_circuit).refusal, SpliceRefusal::None); + const std::vector second_inputs{ target.inputs[4], target.inputs[5] }; + ASSERT_EQ(build_both_ways(serial, target.builder, second_inputs, follow_up_circuit).refusal, SpliceRefusal::None); + expect_same_builder(target.builder, serial); +} + +// Records `circuit` on the seeds of `inputs` with the given seed values, applies `before_splice` to a fresh target and +// the recording, then checks that the splice is refused for `expected` and changes nothing. Every Target has the same +// variable indices, so `inputs` may come from any of them. +void expect_refusal(const std::vector& inputs, + const Circuit& circuit, + const std::function& before_splice, + const SpliceRefusal expected, + const std::vector& seed_values = {}) +{ + Target target; + const Seeds seeds(target.builder, inputs); + Builder recording(SpliceRecording{}, seed_values.empty() ? seeds.values : seed_values); + circuit(recording, seeds.positions); + before_splice(target.builder, recording); + const Builder before = target.builder; + const SpliceResult result = target.builder.splice(recording, seeds.indices); + EXPECT_EQ(result.refusal, expected); + EXPECT_TRUE(result.index_map.empty()); + expect_same_builder_state(target.builder, before); +} + +const auto no_change = [](Builder& /*target*/, Builder& /*recording*/) {}; + +TEST(UltraCircuitBuilderSplice, RefusesTaggedSeed) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal( + inputs, + follow_up_circuit, + [seed = target.inputs[5]](Builder& builder, Builder& /*recording*/) { + builder.create_small_range_constraint(seed, 15); + }, + SpliceRefusal::InputTag); +} + +TEST(UltraCircuitBuilderSplice, RefusesSeedsSharingACycle) +{ + Target target; + const std::vector inputs{ target.inputs[0], target.inputs[3] }; + expect_refusal( + inputs, + follow_up_circuit, + [&](Builder& builder, Builder& /*recording*/) { builder.assert_equal(target.inputs[0], target.inputs[3]); }, + SpliceRefusal::InputCycle); +} + +TEST(UltraCircuitBuilderSplice, RefusesChangedSeedValue) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal(inputs, follow_up_circuit, no_change, SpliceRefusal::InputValue, { fr(123456), fr(10) }); +} + +TEST(UltraCircuitBuilderSplice, RefusesFailedBuilder) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal( + inputs, + follow_up_circuit, + [](Builder& builder, Builder& /*recording*/) { builder.failure("target failed"); }, + SpliceRefusal::Failed); + expect_refusal( + inputs, + follow_up_circuit, + [](Builder& /*target*/, Builder& recording) { + recording.create_small_range_constraint(add_witness(recording, fr(300)), 255); + }, + SpliceRefusal::Failed); +} + +TEST(UltraCircuitBuilderSplice, RefusesAddedPublicInput) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal( + inputs, + follow_up_circuit, + [](Builder& /*target*/, Builder& recording) { recording.add_public_variable(fr(42)); }, + SpliceRefusal::PublicInput); +} + +TEST(UltraCircuitBuilderSplice, RefusesFinalizedPublicInputs) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal( + inputs, + follow_up_circuit, + [](Builder& /*target*/, Builder& recording) { recording.finalize_public_inputs(); }, + SpliceRefusal::PublicInput); +} + +TEST(UltraCircuitBuilderSplice, RefusesUnrecordedTagPermutationEntry) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal( + inputs, + follow_up_circuit, + [](Builder& /*target*/, Builder& recording) { + // A tag past the current one, so no other count changes. + const uint32_t tag = recording.get_current_tag() + 1; + recording.set_tau_at_index(tag, tag); + }, + SpliceRefusal::UnknownForm); +} + +TEST(UltraCircuitBuilderSplice, RefusesEllipticRow) +{ + Target target; + const std::vector inputs{ target.inputs[4], target.inputs[5] }; + expect_refusal( + inputs, + follow_up_circuit, + [](Builder& /*target*/, Builder& recording) { + const uint32_t x3 = recording.add_variable(fr(1)); + const uint32_t y3 = recording.add_variable(fr(2)); + recording.create_ecc_dbl_gate({ .x1 = 0, .y1 = 1, .x3 = x3, .y3 = y3 }); + }, + SpliceRefusal::RowForm); +} + +TEST(UltraCircuitBuilderSplice, RecordingBuilderReleasesBlocksUnderTheDefaultFloors) +{ +// Released anonymous pages read back as zeros only on Linux. +#if !defined(__linux__) || defined(NO_MULTITHREADING) + GTEST_SKIP() << "needs Linux and native threads"; +#else + // About 27 MiB of gate tiles and 4 MiB of values: every block is under the 32 MiB floor, and the total is under the + // 64 MiB minimum, of a builder that does not record. + constexpr size_t NUM_WITNESSES = 100'000; + // A tile in the middle of the largest tile chunk, and a variable in the middle of every per-variable array. + constexpr size_t PROBE_TILE = 10'000; + constexpr uint32_t PROBE_VARIABLE = NUM_WITNESSES / 2; + const auto fill = [](Builder& builder) { + for (size_t i = 0; i < NUM_WITNESSES; ++i) { + add_witness(builder, fr(i + 1)); + } + }; + const auto probes_released = [](const Builder& builder) { + return builder.get_variables()[PROBE_VARIABLE] == fr(0) && builder.real_variable_index[PROBE_VARIABLE] == 0 && + builder.blocks.arithmetic.tiles[PROBE_TILE].wires[0][0] == 0; + }; + + Builder plain; + fill(plain); + ASSERT_FALSE(probes_released(plain)); + plain.release_storage_pages(); + EXPECT_FALSE(probes_released(plain)); + + Builder recording(SpliceRecording{}, std::vector{ fr(5) }); + fill(recording); + ASSERT_FALSE(probes_released(recording)); + recording.release_storage_pages(); + EXPECT_TRUE(probes_released(recording)); +#endif +} + +// Counts the checks of a recording builder and throws from them once requested. +class CountingCancellation final : public SpliceCancellation { + public: + void check() override + { + ++checks; + if (requested) { + throw_or_abort("cancelled"); + } + } + + size_t checks = 0; + bool requested = false; +}; + +TEST(UltraCircuitBuilderSplice, RecordingChecksItsCancellationBeforeEachRecording) +{ + CountingCancellation cancellation; + Builder recording(SpliceRecording{ .cancellation = &cancellation }, std::vector{ fr(5), fr(5), fr(7) }); + recording.assert_equal(0, 1); + EXPECT_EQ(cancellation.checks, 1); + // A gate records nothing. + recording.create_add_gate({ 0, 1, 2, fr(1), fr(1), fr(-1), fr(-3) }); + EXPECT_EQ(cancellation.checks, 1); + cancellation.requested = true; + EXPECT_THROW_OR_ABORT(recording.assert_equal(0, 2), "cancelled"); +} + +} // namespace +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp new file mode 100644 index 0000000..e8aabaa --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" + +#include +#include + +namespace bb::test_utils { + +enum class CompareValues : bool { No, Yes }; + +/** + * @brief Expect two Ultra builders to be equal in every member. + * @details With CompareValues::No, only the variable values are skipped, for builds whose draws differ. + */ +inline void expect_same_builder_state(const UltraCircuitBuilder& actual, + const UltraCircuitBuilder& expected, + const CompareValues values = CompareValues::Yes) +{ + const auto& actual_base = static_cast&>(actual); + const auto& expected_base = static_cast&>(expected); + if (values == CompareValues::Yes) { + EXPECT_TRUE(actual_base == expected_base); + EXPECT_TRUE(actual.get_variables() == expected.get_variables()); + } else { + EXPECT_TRUE(actual_base.equal_except_values(expected_base)); + } + EXPECT_EQ(actual.real_variable_index, expected.real_variable_index); + EXPECT_EQ(actual.real_variable_tags, expected.real_variable_tags); + EXPECT_EQ(actual.num_gates(), expected.num_gates()); + EXPECT_EQ(actual.failed(), expected.failed()); + EXPECT_EQ(actual.err(), expected.err()); + EXPECT_TRUE(actual.range_lists == expected.range_lists); + EXPECT_TRUE(actual.blocks == expected.blocks); + EXPECT_EQ(actual.memory_read_records, expected.memory_read_records); + EXPECT_EQ(actual.memory_write_records, expected.memory_write_records); + EXPECT_EQ(actual.rom_logup_records, expected.rom_logup_records); + EXPECT_TRUE(actual.constant_variable_indices == expected.constant_variable_indices); + EXPECT_TRUE(actual.rom_ram_logic == expected.rom_ram_logic); + EXPECT_TRUE(actual.get_lookup_tables() == expected.get_lookup_tables()); + // The entries' own equality ignores their outputs. + const auto& actual_nnf = actual.cached_partial_non_native_field_multiplications; + const auto& expected_nnf = expected.cached_partial_non_native_field_multiplications; + ASSERT_EQ(actual_nnf.size(), expected_nnf.size()); + for (size_t i = 0; i < actual_nnf.size(); ++i) { + EXPECT_EQ(actual_nnf[i].a, expected_nnf[i].a); + EXPECT_EQ(actual_nnf[i].b, expected_nnf[i].b); + EXPECT_EQ(actual_nnf[i].lo_0, expected_nnf[i].lo_0); + EXPECT_EQ(actual_nnf[i].hi_0, expected_nnf[i].hi_0); + EXPECT_EQ(actual_nnf[i].hi_1, expected_nnf[i].hi_1); + } + EXPECT_TRUE(actual.ipa_proof == expected.ipa_proof); + EXPECT_EQ(actual.pending_ipa_proof.valid(), expected.pending_ipa_proof.valid()); + EXPECT_EQ(actual.get_used_witnesses(), expected.get_used_witnesses()); + EXPECT_EQ(actual.get_finalize_witnesses(), expected.get_finalize_witnesses()); + EXPECT_EQ(actual.is_recording(), expected.is_recording()); +} + +/** + * @brief Expect two Ultra builders to be equal as they are and, on copies, after finalizing both. + */ +inline void expect_same_builder(const UltraCircuitBuilder& actual, + const UltraCircuitBuilder& expected, + const CompareValues values = CompareValues::Yes) +{ + expect_same_builder_state(actual, expected, values); + UltraCircuitBuilder actual_finalized = actual; + UltraCircuitBuilder expected_finalized = expected; + actual_finalized.finalize_circuit(); + expected_finalized.finalize_circuit(); + expect_same_builder_state(actual_finalized, expected_finalized, values); +} + +} // namespace bb::test_utils diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/first_two_rounds_chunked.test.cpp b/barretenberg/cpp/src/barretenberg/sumcheck/first_two_rounds_chunked.test.cpp new file mode 100644 index 0000000..f4250a6 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/sumcheck/first_two_rounds_chunked.test.cpp @@ -0,0 +1,91 @@ +#include "barretenberg/flavor/ultra_flavor.hpp" +#include "barretenberg/sumcheck/sumcheck.hpp" + +#include +#include +#include +#include + +using namespace bb; + +// The chunked two-round fold against the per-polynomial fold on a complete table (every polynomial backed, shifted +// views included, extents that do and do not divide the chunk) at 1, 4 and 16 threads, each on a fresh pool. The +// reference shares the arithmetic kernel, so this is a scheduling reference: it checks chunk coverage, boundaries and +// end indices. Destinations are poisoned first, so an output no chunk writes cannot match by leftover memory. +TEST(SumcheckFirstTwoRounds, ChunkedMatchesPerPolynomial) +{ + using Flavor = UltraFlavor; + using FF = typename Flavor::FF; + using Polynomial = typename Flavor::Polynomial; + using PartiallyEvaluated = typename Flavor::PartiallyEvaluatedMultivariates; + constexpr size_t multivariate_d = 8; + constexpr size_t multivariate_n = size_t{ 1 } << multivariate_d; + constexpr std::array starts{ 1, 2, 5, 9 }; + constexpr std::array ends{ 256, 243, 130, 13, 66 }; + + typename Flavor::ProverPolynomials full; + size_t i = 0; + for (auto& poly : full.get_unshifted()) { + const size_t start = starts[i % starts.size()]; + const size_t end = ends[i % ends.size()]; + poly = Polynomial(end - start, multivariate_n, start); + for (size_t row = start; row < end; ++row) { + poly.at(row) = FF::random_element(); + } + ++i; + } + full.set_shifted(); + + const FF u0 = FF::random_element(); + const FF u1 = FF::random_element(); + const FF poison = FF::random_element(); + PartiallyEvaluated expected(full, multivariate_n, /*num_folds=*/2); + for (auto [src, dst] : zip_view(full.get_all(), expected.get_all())) { + fold_stride4_backed(src, dst, u0, u1); + } + auto count_mismatches = [&](PartiallyEvaluated& folded) { + size_t mismatches = 0; + for (auto [got, want] : zip_view(folded.get_all(), expected.get_all())) { + EXPECT_EQ(got.start_index(), want.start_index()); + EXPECT_EQ(got.end_index(), want.end_index()); + for (size_t k = want.start_index(); k < want.end_index(); ++k) { + mismatches += got[k] == want[k] ? 0 : 1; + } + } + return mismatches; + }; + +#ifdef NO_MULTITHREADING + const std::vector thread_counts{ 1 }; +#else + const std::vector thread_counts{ 1, 4, 16 }; + const size_t saved_concurrency = get_num_cpus(); +#endif + for (const size_t outputs_per_chunk : { size_t{ 16 }, FOLD_STRIDE4_OUTPUTS_PER_CHUNK }) { + for (const size_t threads : thread_counts) { +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(threads); + parallel_for_stop_workers(); +#endif + PartiallyEvaluated folded(full, multivariate_n, /*num_folds=*/2); + for (auto& poly : folded.get_all()) { + for (size_t k = poly.start_index(); k < poly.end_index(); ++k) { + poly.at(k) = poison; + } + } + fold_stride4_backed_all(full.get_all(), folded.get_all(), u0, u1, outputs_per_chunk); + EXPECT_EQ(count_mismatches(folded), 0UL) + << threads << " threads, " << outputs_per_chunk << " outputs per chunk"; + } + } +#ifndef NO_MULTITHREADING + set_parallel_for_concurrency(saved_concurrency); + parallel_for_stop_workers(); +#endif + + auto transcript = Flavor::Transcript::test_prover_init_empty(); + SumcheckProver sumcheck( + multivariate_n, full, transcript, FF(1), std::vector(multivariate_d, FF(1)), {}, multivariate_d); + auto folded = sumcheck.partially_evaluate_first_two_rounds(full, u0, u1); + EXPECT_EQ(count_mismatches(folded), 0UL); +} diff --git a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp index c26b1e7..dea560e 100644 --- a/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp +++ b/barretenberg/cpp/src/barretenberg/sumcheck/sumcheck.hpp @@ -751,19 +751,21 @@ template class SumcheckProver { * @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. + * @param outputs_per_chunk Work-item size of `bb::fold_stride4_backed_all`; the result does not depend on it. */ - PartiallyEvaluatedMultivariates partially_evaluate_first_two_rounds(ProverPolynomials& full_polynomials, - const FF& first_challenge, - const FF& second_challenge) + PartiallyEvaluatedMultivariates partially_evaluate_first_two_rounds( + ProverPolynomials& full_polynomials, + const FF& first_challenge, + const FF& second_challenge, + size_t outputs_per_chunk = FOLD_STRIDE4_OUTPUTS_PER_CHUNK) { 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); - }); + fold_stride4_backed_all(full_polynomials.get_all(), + partially_evaluated_polynomials.get_all(), + first_challenge, + second_challenge, + outputs_per_chunk); return partially_evaluated_polynomials; } diff --git a/barretenberg/cpp/src/barretenberg/trace_to_polynomials/trace_to_polynomials.cpp b/barretenberg/cpp/src/barretenberg/trace_to_polynomials/trace_to_polynomials.cpp index 54b485b..03c409a 100644 --- a/barretenberg/cpp/src/barretenberg/trace_to_polynomials/trace_to_polynomials.cpp +++ b/barretenberg/cpp/src/barretenberg/trace_to_polynomials/trace_to_polynomials.cpp @@ -6,6 +6,8 @@ #include "trace_to_polynomials.hpp" #include "barretenberg/common/assert.hpp" +#include "barretenberg/common/release_pages.hpp" +#include "barretenberg/common/scratch_array.hpp" #include "barretenberg/common/thread.hpp" #include "barretenberg/constants.hpp" #include "barretenberg/ext/starknet/flavor/ultra_starknet_flavor.hpp" @@ -19,6 +21,7 @@ #include "barretenberg/flavor/ultra_keccak_flavor.hpp" #include "barretenberg/flavor/ultra_keccak_zk_flavor.hpp" #include "barretenberg/flavor/ultra_zk_flavor.hpp" +#include #include namespace bb { @@ -72,23 +75,39 @@ CopyCycles TraceToPolynomials::populate_wires_and_selectors_and_compute_ // selector, sourced from the unique block that owns the matching `GateKind`. { BB_BENCH_NAME("populate_selectors"); + // One task per row chunk of a (block, selector) pair: the blocks differ greatly in size, and with one task + // per pair the few pairs of the largest blocks would run alone after every other task has finished. + constexpr uint32_t SELECTOR_ROWS_PER_TASK = 1 << 15; struct SelectorTask { Selector* source; size_t target_poly_idx; uint32_t trace_offset; - uint32_t block_size; + uint32_t row_begin; + uint32_t row_end; }; const auto& polynomials_ref = polynomials; const size_t num_non_gate = polynomials_ref.get_non_gate_selectors().size(); std::vector selector_tasks; + const auto add_selector_tasks = [&](Selector* source, + size_t target_poly_idx, + uint32_t trace_offset, + uint32_t block_size) { + for (uint32_t row_begin = 0; row_begin < block_size; row_begin += SELECTOR_ROWS_PER_TASK) { + selector_tasks.emplace_back(SelectorTask{ source, + target_poly_idx, + trace_offset, + row_begin, + std::min(row_begin + SELECTOR_ROWS_PER_TASK, block_size) }); + } + }; for (auto& block : blocks_array) { const uint32_t offset = block.trace_offset(); const uint32_t block_size = static_cast(block.size()); auto non_gate = Flavor::Generated::get_block_non_gate_selectors(block); for (size_t i = 0; i < non_gate.size(); ++i) { - selector_tasks.emplace_back(SelectorTask{ &non_gate[i], i, offset, block_size }); + add_selector_tasks(&non_gate[i], i, offset, block_size); } } @@ -96,10 +115,10 @@ CopyCycles TraceToPolynomials::populate_wires_and_selectors_and_compute_ constexpr auto& gate_kinds = Flavor::Generated::GATE_KINDS; for (size_t i = 0; i < gate_kinds.size(); ++i) { auto& block = gate_blocks[i]; - selector_tasks.emplace_back(SelectorTask{ &block.gate_selector_for(gate_kinds[i]), - num_non_gate + i, - block.trace_offset(), - static_cast(block.size()) }); + add_selector_tasks(&block.gate_selector_for(gate_kinds[i]), + num_non_gate + i, + block.trace_offset(), + static_cast(block.size())); } parallel_for(selector_tasks.size(), [&](size_t task_idx) { @@ -109,8 +128,8 @@ CopyCycles TraceToPolynomials::populate_wires_and_selectors_and_compute_ // Bulk-copy the range that lands inside the polynomial's backing store (tile-wise, no // per-element virtual call); rows clamped off by the store bounds would previously have // been dropped by set_if_valid_index and must be zero. - const size_t dst_begin = std::max(task.trace_offset, poly.start_index()); - const size_t dst_end = std::min(task.trace_offset + task.block_size, poly.end_index()); + const size_t dst_begin = std::max(task.trace_offset + task.row_begin, poly.start_index()); + const size_t dst_end = std::min(task.trace_offset + task.row_end, poly.end_index()); if (dst_begin < dst_end) { source.copy_into(&poly.at(dst_begin), dst_begin - task.trace_offset, dst_end - dst_begin); } @@ -124,8 +143,8 @@ CopyCycles TraceToPolynomials::populate_wires_and_selectors_and_compute_ for (size_t block_idx = 0; block_idx < num_blocks; ++block_idx) { cell_offsets[block_idx + 1] = cell_offsets[block_idx] + blocks_array[block_idx].size() * NUM_WIRES; } - // The real variable index of every wire cell. - std::vector cell_real_var_idx(cell_offsets[num_blocks]); + // The real variable index of every wire cell; phase 2 writes every cell. + ScratchArray cell_real_var_idx(cell_offsets[num_blocks]); // Phase 2: populate the wires and record each cell's real variable index, in parallel over row chunks of all // blocks (the blocks differ greatly in size). With CopiedCircuitData::RELEASE, the task that finishes a block's @@ -172,51 +191,78 @@ CopyCycles TraceToPolynomials::populate_wires_and_selectors_and_compute_ } if (copied_circuit_data == CopiedCircuitData::RELEASE && chunks_left[task.block_idx].fetch_sub(1, std::memory_order_acq_rel) == 1) { + if constexpr (IsUltraHonk) { + // Freeing a large tile chunk unmaps its pages serially on this worker; hand them back from several + // threads first, as the builder's destructor does. A store has far fewer than 64 chunks. + PageBlockList<64> released; + block.tiles.add_chunks_to(released); + released.release(); + } block.free_data(); } }); } - // Phases 2.5 and 2.6 split the variables into one contiguous range per thread. Each thread scans all cells in - // order and handles only its own variables, so every copy cycle is counted and filled by one thread, in cell order. + // Phases 2.5 and 2.6 split the variables into one contiguous range per scan task. Each task scans all cells in + // order and handles only its own variables, so every copy cycle is counted and filled by one task, in cell order. + // Every task reads every cell in each phase, so beyond a few tasks more of them only add memory traffic. + constexpr size_t MAX_COPY_CYCLE_SCAN_TASKS = 16; + const size_t num_scan_tasks = std::clamp(get_num_cpus(), 1, MAX_COPY_CYCLE_SCAN_TASKS); + const auto scan_task_vars = [&](size_t task_idx) { + return ThreadChunk{ .thread_index = task_idx, .total_threads = num_scan_tasks }.range(num_cycles); + }; + // task_node_begin[t] is the first node of task t's variables in the CSR node array. + std::vector task_node_begin(num_scan_tasks + 1, 0); { BB_BENCH_NAME("counting copy_cycles"); - // Count copy-cycle sizes per real variable, then take the exclusive prefix sum to get the CSR offsets; a - // single flat node array replaces one heap-allocated vector per variable. - copy_cycles.offsets.assign(num_cycles + 1, 0); - parallel_for([&](const ThreadChunk& chunk) { - const auto vars = chunk.range(num_cycles); + // Count copy-cycle sizes per real variable; phase 2.6 turns them into CSR offsets. A single flat node array + // replaces one heap-allocated vector per variable. + copy_cycles.offsets = ScratchArray(num_cycles + 1); + parallel_for(num_scan_tasks, [&](size_t task_idx) { + const auto vars = scan_task_vars(task_idx); if (vars.empty()) { return; } const uint32_t var_begin = static_cast(vars.front()); const uint32_t num_vars = static_cast(vars.size()); - for (const uint32_t real_var_idx : cell_real_var_idx) { + uint32_t* counts = ©_cycles.offsets[var_begin]; + std::fill_n(counts, num_vars, 0U); + for (const uint32_t real_var_idx : cell_real_var_idx.span()) { if (real_var_idx - var_begin < num_vars) { - ++copy_cycles.offsets[real_var_idx]; + ++counts[real_var_idx - var_begin]; } } + uint32_t task_nodes = 0; + for (uint32_t i = 0; i < num_vars; ++i) { + task_nodes += counts[i]; + } + task_node_begin[task_idx + 1] = task_nodes; }); - uint32_t running = 0; - for (size_t i = 0; i < num_cycles; ++i) { - const uint32_t count = copy_cycles.offsets[i]; - copy_cycles.offsets[i] = running; - running += count; + for (size_t task_idx = 0; task_idx < num_scan_tasks; ++task_idx) { + task_node_begin[task_idx + 1] += task_node_begin[task_idx]; } - copy_cycles.offsets[num_cycles] = running; - copy_cycles.nodes.resize(running); + copy_cycles.offsets[num_cycles] = task_node_begin[num_scan_tasks]; + copy_cycles.nodes = ScratchArray(task_node_begin[num_scan_tasks]); } { BB_BENCH_NAME("fill_copy_cycles"); - std::vector cursors(copy_cycles.offsets.begin(), copy_cycles.offsets.end() - 1); - parallel_for([&](const ThreadChunk& chunk) { - const auto vars = chunk.range(num_cycles); + ScratchArray cursors(num_cycles); + parallel_for(num_scan_tasks, [&](size_t task_idx) { + const auto vars = scan_task_vars(task_idx); if (vars.empty()) { return; } const uint32_t var_begin = static_cast(vars.front()); const uint32_t num_vars = static_cast(vars.size()); + // Exclusive prefix sum of this task's counts, starting at the task's first node. + uint32_t running = task_node_begin[task_idx]; + for (uint32_t var = var_begin; var < var_begin + num_vars; ++var) { + const uint32_t count = copy_cycles.offsets[var]; + copy_cycles.offsets[var] = running; + cursors[var] = running; + running += count; + } for (size_t block_idx = 0; block_idx < num_blocks; ++block_idx) { const uint32_t offset = blocks_array[block_idx].trace_offset(); const uint32_t block_size = static_cast(blocks_array[block_idx].size()); diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/deferred_ipa_proof.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/deferred_ipa_proof.test.cpp new file mode 100644 index 0000000..b58d54c --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/deferred_ipa_proof.test.cpp @@ -0,0 +1,34 @@ +#include "barretenberg/commitment_schemes/ipa/ipa.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" +#include "barretenberg/ultra_honk/prover_instance.hpp" + +#include + +using namespace bb; + +// RollupIO::add_default computes the IPA proof in the background; through the builder, and through a prover instance +// built before it was resolved, it equals the proof that create_valid_ipa_claim_and_proof computes inline. +TEST(DeferredIpaProof, EqualsSynchronousProof) +{ + using RecursiveIPA = IPA>; + srs::init_file_crs_factory(srs::bb_crs_path()); + const auto [polynomial, challenge] = RecursiveIPA::sample_random_opening(); + + UltraCircuitBuilder synchronous_builder; + const HonkProof expected = + RecursiveIPA::create_valid_ipa_claim_and_proof(synchronous_builder, polynomial, challenge).second; + + UltraCircuitBuilder builder; + stdlib::recursion::honk::RollupIO::add_default(builder, polynomial, challenge); + EXPECT_TRUE(builder.pending_ipa_proof.valid()); + + ProverInstance_ prover_instance(builder); + EXPECT_TRUE(prover_instance.has_ipa_proof()); + EXPECT_EQ(prover_instance.resolve_ipa_proof(), expected); + + EXPECT_EQ(builder.resolve_ipa_proof(), expected); + EXPECT_EQ(builder.resolve_ipa_proof(), expected); + EXPECT_FALSE(builder.pending_ipa_proof.valid()); +} diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.cpp index 45867b6..6a91765 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.cpp @@ -118,8 +118,9 @@ ProverInstance_::ProverInstance_(Circuit& circuit, CopiedCircuitData cop public_inputs.emplace_back(polynomials.w_r()[idx]); } - // Copy IPA proof if present + // Copy IPA proof if present; one still being computed stays pending until the proof is exported ipa_proof = circuit.ipa_proof; + pending_ipa_proof = circuit.pending_ipa_proof; if (std::getenv("BB_POLY_STATS")) { analyze_prover_polynomials(polynomials); diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.hpp b/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.hpp index e5d939a..d05f588 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.hpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/prover_instance.hpp @@ -6,6 +6,7 @@ #pragma once #include "barretenberg/common/assert.hpp" +#include "barretenberg/common/deferred_value.hpp" #include "barretenberg/ext/starknet/flavor/ultra_starknet_flavor.hpp" #include "barretenberg/ext/starknet/flavor/ultra_starknet_zk_flavor.hpp" #include "barretenberg/flavor/flavor.hpp" @@ -51,6 +52,8 @@ template class ProverInstance_ { std::vector gate_challenges; HonkProof ipa_proof; // utilized for rollup proofs (IO::HasIPA) + // An IPA proof still being computed, held instead of ipa_proof until resolve_ipa_proof(). + DeferredValue pending_ipa_proof; std::vector memory_read_records; std::vector memory_write_records; @@ -71,6 +74,13 @@ template class ProverInstance_ { return final_active_wire_idx; } + bool has_ipa_proof() const { return !ipa_proof.empty() || pending_ipa_proof.valid(); } + + /** + * @brief The IPA proof, after waiting for a pending one. Rethrows what computing a pending proof threw. + */ + const HonkProof& resolve_ipa_proof() { return resolve_into(ipa_proof, pending_ipa_proof); } + Flavor::PrecomputedData get_precomputed() { return typename Flavor::PrecomputedData{ polynomials.get_precomputed(), metadata }; diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/splice_lookup.test.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/splice_lookup.test.cpp new file mode 100644 index 0000000..5f1bb85 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/splice_lookup.test.cpp @@ -0,0 +1,264 @@ +#include "barretenberg/honk/proof_system/types/proof.hpp" +#include "barretenberg/special_public_inputs/special_public_inputs.hpp" +#include "barretenberg/srs/global_crs.hpp" +#include "barretenberg/stdlib/special_public_inputs/special_public_inputs.hpp" +#include "barretenberg/stdlib_circuit_builders/circuit_splice.hpp" +#include "barretenberg/stdlib_circuit_builders/plookup_tables/plookup_tables.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder.hpp" +#include "barretenberg/stdlib_circuit_builders/ultra_circuit_builder_test_utils.hpp" +#include "barretenberg/ultra_honk/prover_instance.hpp" +#include "barretenberg/ultra_honk/ultra_prover.hpp" +#include "barretenberg/ultra_honk/ultra_verifier.hpp" + +#include +#include +#include +#include +#include +#include +#include + +/** + * Lookup gadgets built in chunks on recording builders and spliced in order into a target must leave the target, and + * its proof, exactly as building them on the target itself does, tables and their read records included; a refused + * splice must leave the target unchanged. + */ + +namespace bb { +namespace { + +using Builder = UltraCircuitBuilder; +using Flavor = UltraFlavor; +using plookup::ColumnIdx; +using plookup::MultiTableId; +using test_utils::expect_same_builder; +using test_utils::expect_same_builder_state; + +constexpr uint64_t CACHED_CONSTANT = 3; +constexpr size_t NUM_MESSAGES = 12; +constexpr size_t NUM_CHUNKS = 3; + +// A new variable that appears in a wire, as a range constraint requires. +uint32_t add_witness(Builder& builder, const fr& value) +{ + const uint32_t index = builder.add_variable(value); + builder.create_unconstrained_gate( + builder.blocks.arithmetic, index, builder.zero_idx(), builder.zero_idx(), builder.zero_idx()); + return index; +} + +// The result of a multi-table lookup on `key_a`, and on `key_b` for a two-key table. +uint32_t lookup(Builder& builder, const MultiTableId id, const uint32_t key_a, const std::optional key_b) +{ + const fr b_value = key_b.has_value() ? builder.get_variable(*key_b) : fr(0); + const auto accumulators = + plookup::get_lookup_accumulators(id, builder.get_variable(key_a), b_value, key_b.has_value()); + return builder.create_gates_from_plookup_accumulators(id, accumulators, key_a, key_b)[ColumnIdx::C3][0]; +} + +// One step in the style of a SHA-256 round: a 32-bit XOR of `chain` and `message`, the majority-function input form of +// the result, then a 32-bit AND of the result and `message`, which is returned and also offset by a cached constant. +uint32_t lookup_gadget(Builder& builder, const uint32_t chain, const uint32_t message) +{ + const uint32_t mixed = lookup(builder, MultiTableId::UINT32_XOR, chain, message); + lookup(builder, MultiTableId::SHA256_MAJ_INPUT, mixed, std::nullopt); + const uint32_t result = lookup(builder, MultiTableId::UINT32_AND, mixed, message); + const uint32_t constant = builder.put_constant_variable(fr(CACHED_CONSTANT)); + const uint32_t offset = builder.add_variable(builder.get_variable(result) + fr(CACHED_CONSTANT)); + builder.create_add_gate({ .a = result, + .b = constant, + .c = offset, + .a_scaling = 1, + .b_scaling = 1, + .c_scaling = -1, + .const_scaling = 0 }); + return result; +} + +uint32_t run_gadgets(Builder& builder, uint32_t chain, const std::span messages) +{ + for (const uint32_t message : messages) { + chain = lookup_gadget(builder, chain, message); + } + return chain; +} + +// A target that already holds an AND table pair, so the tables the gadgets create here are numbered after it while a +// recording numbers them from 1; a range list with a tagged variable; and the constant the gadgets cache. +struct Target { + Builder builder; + uint32_t chain; + // Messages 2i and 2i + 1 have equal values. + std::vector messages; + uint32_t tagged; + + explicit Target(const size_t num_messages) + { + const uint32_t left = builder.add_variable(fr(0x12345678)); + const uint32_t right = builder.add_variable(fr(0x0f0f0f0f)); + lookup(builder, MultiTableId::UINT32_AND, left, right); + builder.put_constant_variable(fr(CACHED_CONSTANT)); + tagged = add_witness(builder, fr(200)); + builder.create_small_range_constraint(tagged, 255); + chain = builder.add_variable(fr(0x6a09e667)); + for (size_t i = 0; i < num_messages; ++i) { + const uint32_t value = 0x9e3779b9U * static_cast((i / 2) + 1); + messages.push_back(builder.add_variable(fr(static_cast(value)))); + } + } +}; + +// A recording builder seeded with `chain` and `messages` of `target`, the gadgets built on it, and the result there. +struct Recording { + std::vector seeds; + Builder builder; + uint32_t result; + + Recording(const Builder& target, const uint32_t chain, const std::span messages) + : seeds(seeds_of(chain, messages)) + , builder(SpliceRecording{}, values_of(target, seeds)) + { + std::vector positions(messages.size()); + std::iota(positions.begin(), positions.end(), uint32_t{ 1 }); + result = run_gadgets(builder, 0, positions); + } + + static std::vector seeds_of(const uint32_t chain, const std::span messages) + { + std::vector seeds{ chain }; + seeds.insert(seeds.end(), messages.begin(), messages.end()); + return seeds; + } + + static std::vector values_of(const Builder& target, const std::vector& seeds) + { + std::vector values; + for (const uint32_t seed : seeds) { + values.push_back(target.get_variable(seed)); + } + return values; + } +}; + +// Builds the gadgets on `messages` from `chain` on `serial`, and in `num_chunks` equal chunks on recording builders +// spliced in order into `target`; checks that each chunk is spliced and that the results agree, and returns the result. +uint32_t build_both_ways(Builder& serial, + Builder& target, + const uint32_t chain, + const std::span messages, + const size_t num_chunks) +{ + const uint32_t serial_result = run_gadgets(serial, chain, messages); + const size_t chunk_size = messages.size() / num_chunks; + uint32_t target_chain = chain; + for (size_t c = 0; c < num_chunks; ++c) { + const Recording recording(target, target_chain, messages.subspan(c * chunk_size, chunk_size)); + const SpliceResult result = target.splice(recording.builder, recording.seeds); + EXPECT_EQ(result.refusal, SpliceRefusal::None); + if (!result.spliced()) { + return serial_result; + } + target_chain = result.index_map[recording.result]; + } + EXPECT_EQ(target_chain, serial_result); + return serial_result; +} + +// A later gate reads the result and a later variable joins its copy cycle, as the next constraint would. +void use_result(Builder& builder, const uint32_t result, const uint32_t tagged) +{ + builder.assert_equal(add_witness(builder, builder.get_variable(result)), result); + const uint32_t sum = builder.add_variable(builder.get_variable(result) + builder.get_variable(tagged)); + builder.create_add_gate( + { .a = result, .b = tagged, .c = sum, .a_scaling = 1, .b_scaling = 1, .c_scaling = -1, .const_scaling = 0 }); +} + +HonkProof prove_and_verify(Builder builder) +{ + stdlib::recursion::honk::DefaultIO::add_default(builder); + auto instance = std::make_shared>(builder); + auto vk = std::make_shared(instance->get_precomputed()); + UltraProver_ prover(instance, vk); + auto proof = prover.construct_proof(); + UltraVerifier_ verifier(std::make_shared(vk)); + EXPECT_TRUE(verifier.verify_proof(proof).result); + return proof; +} + +class SpliceLookup : public ::testing::Test { + protected: + static void SetUpTestSuite() { bb::srs::init_file_crs_factory(bb::srs::bb_crs_path()); } +}; + +TEST_F(SpliceLookup, ChunksMatchTheSerialBuildAndItsProof) +{ + Target target(NUM_MESSAGES); + Builder serial = target.builder; + const uint32_t result = build_both_ways(serial, target.builder, target.chain, target.messages, NUM_CHUNKS); + use_result(serial, result, target.tagged); + use_result(target.builder, result, target.tagged); + expect_same_builder(target.builder, serial); + EXPECT_EQ(prove_and_verify(target.builder), prove_and_verify(serial)); +} + +TEST_F(SpliceLookup, SecondRunSplicedOntoTheResult) +{ + Target target(2 * NUM_MESSAGES); + Builder serial = target.builder; + const std::span messages(target.messages); + const uint32_t first = + build_both_ways(serial, target.builder, target.chain, messages.first(NUM_MESSAGES), NUM_CHUNKS); + use_result(serial, first, target.tagged); + use_result(target.builder, first, target.tagged); + const uint32_t second = build_both_ways(serial, target.builder, first, messages.subspan(NUM_MESSAGES), NUM_CHUNKS); + use_result(serial, second, target.tagged); + use_result(target.builder, second, target.tagged); + expect_same_builder(target.builder, serial); +} + +// Records the gadgets on the first two messages, applies `before_splice` to the target and the recording, then checks +// that the splice is refused for `expected` and changes nothing. +void expect_refusal(const std::function& before_splice, + const SpliceRefusal expected) +{ + Target target(2); + Recording recording(target.builder, target.chain, target.messages); + ASSERT_NE(recording.builder.blocks.lookup.size(), 0U); + before_splice(target, recording.builder); + const Builder before = target.builder; + const SpliceResult result = target.builder.splice(recording.builder, recording.seeds); + EXPECT_EQ(result.refusal, expected); + EXPECT_TRUE(result.index_map.empty()); + expect_same_builder_state(target.builder, before); +} + +TEST_F(SpliceLookup, RefusalsBesideLookupRowsLeaveTheTargetUnchanged) +{ + // An elliptic row: its creation may edit an earlier row. + expect_refusal( + [](Target& /*target*/, Builder& recording) { + const uint32_t x3 = recording.add_variable(fr(1)); + const uint32_t y3 = recording.add_variable(fr(2)); + recording.create_ecc_dbl_gate({ .x1 = 0, .y1 = 1, .x3 = x3, .y3 = y3 }); + }, + SpliceRefusal::RowForm); + // A table numbered other than by its registry position, which the rows' table numbers rely on. + expect_refusal([](Target& /*target*/, Builder& recording) { recording.get_lookup_tables()[1].table_index = 9; }, + SpliceRefusal::UnknownForm); + // A registered table, whose contents its id does not fix. + expect_refusal( + [](Target& /*target*/, Builder& recording) { + plookup::BasicTable table{}; + table.id = plookup::BasicTableId::STRAUS_EC_POINT; + recording.register_basic_lookup_table(std::move(table)); + }, + SpliceRefusal::UnknownForm); + // Two seeds of equal value joined in one copy cycle here after the recording. + const auto join_seeds = [](Target& target, Builder& /*recording*/) { + target.builder.assert_equal(target.messages[0], target.messages[1]); + }; + expect_refusal(join_seeds, SpliceRefusal::InputCycle); +} + +} // namespace +} // namespace bb diff --git a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp index 12b1f65..5844704 100644 --- a/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp +++ b/barretenberg/cpp/src/barretenberg/ultra_honk/ultra_prover.cpp @@ -29,7 +29,7 @@ UltraProver_::UltraProver_(std::shared_ptr prover_instan * * **Prover Level (this function):** * [public_inputs | honk_proof | ipa_proof] - * - Appends IPA proof if prover_instance->ipa_proof is non-empty + * - Appends the prover instance's IPA proof if it has one, waiting for it if it is still being computed * - SYMMETRIC with UltraVerifier_::split_rollup_proof() which extracts the IPA portion * * **API Level (bbapi):** @@ -43,9 +43,10 @@ template typename UltraProver_::Proof UltraProver_export_proof(); // Append IPA proof if present - if (!prover_instance->ipa_proof.empty()) { - BB_ASSERT_EQ(prover_instance->ipa_proof.size(), static_cast(IPA_PROOF_LENGTH)); - proof.insert(proof.end(), prover_instance->ipa_proof.begin(), prover_instance->ipa_proof.end()); + const HonkProof& ipa_proof = prover_instance->resolve_ipa_proof(); + if (!ipa_proof.empty()) { + BB_ASSERT_EQ(ipa_proof.size(), static_cast(IPA_PROOF_LENGTH)); + proof.insert(proof.end(), ipa_proof.begin(), ipa_proof.end()); } return proof;