Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions barretenberg/cpp/src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,13 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "GNU")
endif()

# We enable -O1 level optimsations, even when compiling debug wasm, otherwise we get "local count too large" at runtime.
# Release wasm is built with -O3 and the loop vectorizer off: the vectorizer turns field-arithmetic loops into i64x2
# multiplies that V8 lowers to slow sequences (scalar Fr mul 50 ns -> 72 ns), while the rest of -O3 (inlining,
# unrolling) proves ~8% faster than -Oz end to end. The cost is a larger artifact (gzipped ~3.9 MB -> ~5.6 MB);
# configure with -DWASM_RELEASE_OPT=-Oz to prioritise size instead.
# Release wasm is built with -O2 and the loop vectorizer off: the vectorizer turns field-arithmetic loops into i64x2
# multiplies that V8 lowers to slow sequences, while -O2 proves faster than -Oz and keeps V8's code memory within the
# proving RAM budget (-O3 did not). Configure WASM_RELEASE_OPT explicitly to experiment with other release flags.
if(WASM)
set(CMAKE_CXX_FLAGS_DEBUG "-O1 -g")
set(CMAKE_C_FLAGS_DEBUG "-O1 -g")
set(WASM_RELEASE_OPT "-O3 -fno-vectorize" CACHE STRING "Optimisation flags for release WASM builds")
set(WASM_RELEASE_OPT "-O2 -fno-vectorize" CACHE STRING "Optimisation flags for release WASM builds")
set(CMAKE_CXX_FLAGS_RELEASE "${WASM_RELEASE_OPT} -DNDEBUG")
set(CMAKE_C_FLAGS_RELEASE "${WASM_RELEASE_OPT} -DNDEBUG")
add_link_options(-Wl,--export-memory,--import-memory,--stack-first,-z,stack-size=1048576,--max-memory=4294967296)
Expand Down
117 changes: 72 additions & 45 deletions barretenberg/cpp/src/barretenberg/common/assert.hpp

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,15 @@ constexpr size_t CACHE_LINE_SIZE = 64;
// How long an idle thread busy-waits for the next job (workers) or for the job to finish (caller) before blocking on a
// condition variable. Provers issue thousands of short parallel_for calls back to back (sumcheck rounds, MSM stages,
// per-polynomial loops); waking a blocked thread costs tens of microseconds, which is comparable to the work itself.
#ifdef __wasm__
// On WASM the spin is bounded by a poll count, not the clock: steady_clock::now() is a call out to the host's WASI
// clock_time_get, which bb.js answers in whole milliseconds, so a 100 us deadline would last until the next tick.
constexpr size_t SPIN_POLLS = size_t{ 1 } << 19;
#else
constexpr auto SPIN_DURATION = std::chrono::microseconds(100);
// The clock is only read once every SPIN_CLOCK_INTERVAL spins.
constexpr size_t SPIN_CLOCK_INTERVAL = 64;
#endif

inline void cpu_relax()
{
Expand All @@ -51,11 +57,20 @@ inline void cpu_relax()
}

/**
* @brief Busy-waits until `done()` holds or SPIN_DURATION elapses.
* @brief Busy-waits until `done()` holds or the spin bound (SPIN_POLLS, or SPIN_DURATION off WASM) is reached.
* @return true if `done()` holds.
*/
template <typename Done> bool spin_until(const Done& done)
{
#ifdef __wasm__
for (size_t polls = 0; polls < SPIN_POLLS; ++polls) {
if (done()) {
return true;
}
cpu_relax();
}
return done();
#else
auto deadline = std::chrono::steady_clock::now() + SPIN_DURATION;
for (size_t spins = 1;; ++spins) {
if (done()) {
Expand All @@ -66,6 +81,7 @@ template <typename Done> bool spin_until(const Done& done)
}
cpu_relax();
}
#endif
}

/**
Expand Down
25 changes: 19 additions & 6 deletions barretenberg/cpp/src/barretenberg/ecc/fields/vector_field.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
// in the product phase, NOT 81. Combined with 9 Yuval reductions × 9
// madConst = 81, total is 66+81 = 147. Schoolbook would have been 81+81 =
// 162. The gist: "it's ~25% of the total runtime."
// sqr() keeps the split but squares each part, doubling the off-diagonal
// terms: 39 muls in the product phase (see vector_field_wasm.cpp).
//
// 2. Op-by-op interleaving.
// Scalar statement, then equivalent quad statement, then next scalar, etc.
Expand Down Expand Up @@ -103,12 +105,12 @@ template <class Params> inline constexpr std::array<uint64_t, 9> compute_tnm_was
return tnm;
}

// Marker trait: specialized to true for each Params whose VectorField has a
// SIMD operator* body (an explicit specialization defined in
// Marker trait: specialized to true for each Params whose VectorField has
// SIMD operator* and sqr bodies (explicit specializations defined in
// vector_field_wasm.cpp). vectorized_for / vectorized_for_if read this to
// decide whether to take the bulk path. Add a new specialization (below)
// when adding the corresponding operator* body so the gate and the body
// stay in lockstep.
// when adding the corresponding operator* and sqr bodies so the gate and the
// bodies stay in lockstep.
template <class Params> struct has_simd_mont_mul : std::false_type {};
template <class Params> inline constexpr bool has_simd_mont_mul_v = has_simd_mont_mul<Params>::value;

Expand Down Expand Up @@ -192,8 +194,17 @@ template <class Params> struct alignas(32) VectorField {
static VectorField zero() noexcept { return broadcast(Field::zero()); }
static VectorField one() noexcept { return broadcast(Field::one()); }

#if BB_VECTOR_FIELD_SIMD
// Under WASM SIMD, sqr has explicit specializations for Bn254FrParams and Bn254FqParams next to operator*
// (see vector_field_wasm.cpp), with the same link-time contract. Their output limbs equal (*this) * (*this).
VectorField sqr() const noexcept;
// Square entry point for the packed affine addition.
VectorField sqr_for_affine() const noexcept { return sqr(); }
void self_sqr() noexcept { *this = sqr(); }
#else
VectorField sqr() const noexcept { return (*this) * (*this); }
void self_sqr() noexcept { *this = (*this) * (*this); }
#endif
VectorField operator-() const noexcept { return zero() - *this; }
// Per-lane scalar invert. Slow path -- for static-init constants and rare relation use. For batched
// inversions of independent values use the K=5 batch-inversion pattern in ecc/groups/element_impl.hpp.
Expand Down Expand Up @@ -291,18 +302,20 @@ template <class Params> struct alignas(32) VectorField {
base[idx[2] - offset],
base[idx[3] - offset],
base[idx[4] - offset] };
return VectorField(tmp);
return VectorField(tmp.data());
}

// Counterpart to `gather` for sources that aren't a flat `Field*` -- e.g. a polynomial's `operator[]`,
// which handles virtual-zero and start-index translation. lane L is set to value_at(L).
// The lanes are staged contiguously, so they pack through the transpose constructor rather than the per-lane
// scalar pack of the std::array constructor (the limbs are identical).
template <typename Fn> static VectorField from_lanes(const Fn& value_at) noexcept
{
std::array<Field, SIZE> lanes;
for (size_t lane = 0; lane < SIZE; ++lane) {
lanes[lane] = value_at(lane);
}
return VectorField(lanes);
return VectorField(lanes.data());
}

// SLOW PATH — see gather. Writes base[idx[L] - offset] = this->get(L) for L in 0..4.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Body of VectorField<Params>::sqr under WASM SIMD: the squaring counterpart of
// vector_field_mont_mul_body.inl.hpp, included inside per-Params explicit
// specializations in vector_field_wasm.cpp in the same way.
//
// BB_VF_KARATSUBA_SQR_STAGES_1_4 yields the same pl*, ph*, pc* columns as the
// multiply kernel does for identical operands, except that pc8 (= pl8) is not
// formed and pc7 is only available as pm7 = pc7 - pl7. Stage 5 below is the
// multiply's combine with those two substitutions, so temp_0..temp_16 and the
// stage 6..10 output match (*this) * (*this) limb for limb.
//
// Including this file inside `{ ... }` of a `VectorField<Foo>::sqr`
// specialization is the supported use; do not include it at namespace scope.
VectorField result;

BB_VF_LOAD_SQR_LIMBS(*this);
BB_VF_KARATSUBA_SQR_STAGES_1_4();

// ============================================================
// Stage 5: Combine into temp_0..temp_16 (see the multiply body), with
// temp[12] = pm7 + ph[2] (pm7 = pc[7] - pl[7])
// temp[13] = ph[3] (pc[8] - pl[8] = 0)
// ============================================================
uint64_t temp_0 = pl0;
v128_t tlo_0 = pl0_lo;
v128_t thi_0 = pl0_hi;
uint64_t temp_1 = pl1;
v128_t tlo_1 = pl1_lo;
v128_t thi_1 = pl1_hi;
uint64_t temp_2 = pl2;
v128_t tlo_2 = pl2_lo;
v128_t thi_2 = pl2_hi;
uint64_t temp_3 = pl3;
v128_t tlo_3 = pl3_lo;
v128_t thi_3 = pl3_hi;
uint64_t temp_4 = pl4;
v128_t tlo_4 = pl4_lo;
v128_t thi_4 = pl4_hi;

uint64_t temp_5 = pl5 + (pc0 - pl0 - ph0);
v128_t tlo_5 = wasm_i64x2_add(pl5_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc0_lo, pl0_lo), ph0_lo));
v128_t thi_5 = wasm_i64x2_add(pl5_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc0_hi, pl0_hi), ph0_hi));
uint64_t temp_6 = pl6 + (pc1 - pl1 - ph1);
v128_t tlo_6 = wasm_i64x2_add(pl6_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc1_lo, pl1_lo), ph1_lo));
v128_t thi_6 = wasm_i64x2_add(pl6_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc1_hi, pl1_hi), ph1_hi));
uint64_t temp_7 = pl7 + (pc2 - pl2 - ph2);
v128_t tlo_7 = wasm_i64x2_add(pl7_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc2_lo, pl2_lo), ph2_lo));
v128_t thi_7 = wasm_i64x2_add(pl7_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc2_hi, pl2_hi), ph2_hi));
uint64_t temp_8 = pl8 + (pc3 - pl3 - ph3);
v128_t tlo_8 = wasm_i64x2_add(pl8_lo, wasm_i64x2_sub(wasm_i64x2_sub(pc3_lo, pl3_lo), ph3_lo));
v128_t thi_8 = wasm_i64x2_add(pl8_hi, wasm_i64x2_sub(wasm_i64x2_sub(pc3_hi, pl3_hi), ph3_hi));

uint64_t temp_9 = pc4 - pl4 - ph4;
v128_t tlo_9 = wasm_i64x2_sub(wasm_i64x2_sub(pc4_lo, pl4_lo), ph4_lo);
v128_t thi_9 = wasm_i64x2_sub(wasm_i64x2_sub(pc4_hi, pl4_hi), ph4_hi);

uint64_t temp_10 = (pc5 - pl5 - ph5) + ph0;
v128_t tlo_10 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc5_lo, pl5_lo), ph5_lo), ph0_lo);
v128_t thi_10 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc5_hi, pl5_hi), ph5_hi), ph0_hi);
uint64_t temp_11 = (pc6 - pl6 - ph6) + ph1;
v128_t tlo_11 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc6_lo, pl6_lo), ph6_lo), ph1_lo);
v128_t thi_11 = wasm_i64x2_add(wasm_i64x2_sub(wasm_i64x2_sub(pc6_hi, pl6_hi), ph6_hi), ph1_hi);
uint64_t temp_12 = pm7 + ph2;
v128_t tlo_12 = wasm_i64x2_add(pm7_lo, ph2_lo);
v128_t thi_12 = wasm_i64x2_add(pm7_hi, ph2_hi);
uint64_t temp_13 = ph3;
v128_t tlo_13 = ph3_lo;
v128_t thi_13 = ph3_hi;

uint64_t temp_14 = ph4;
v128_t tlo_14 = ph4_lo;
v128_t thi_14 = ph4_hi;
uint64_t temp_15 = ph5;
v128_t tlo_15 = ph5_lo;
v128_t thi_15 = ph5_hi;
uint64_t temp_16 = ph6;
v128_t tlo_16 = ph6_lo;
v128_t thi_16 = ph6_hi;

// Stages 6..10: unchanged from the multiply.
BB_VF_RUN_STAGES_6_THROUGH_10();
return result;
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include "barretenberg/ecc/fields/vector_field.hpp"

#include "barretenberg/ecc/curves/bn254/fq.hpp"
#include "barretenberg/ecc/curves/bn254/fr.hpp"

#include <array>
#include <cstring>
#include <gtest/gtest.h>
#include <vector>

namespace {

// sqr / self_sqr / sqr_for_affine run a dedicated squaring kernel under WASM SIMD; it must return the exact
// limbs of v * v, not just the same residue, on coarse [0, 2p) lanes and boundary values alike.
template <class VecT> void expect_sqr_limbs_match_self_mul()
{
using F = typename VecT::Field;
const F neg_one = -F::one();
const auto two_p_minus_one = F::modulus + F::modulus - bb::numeric::uint256_t(1);
const F raw_p(F::modulus.data[0], F::modulus.data[1], F::modulus.data[2], F::modulus.data[3]);
const F raw_two_p_minus_one(
two_p_minus_one.data[0], two_p_minus_one.data[1], two_p_minus_one.data[2], two_p_minus_one.data[3]);

std::vector<VecT> inputs{ VecT(std::array<F, 5>{ F::zero(), F::one(), neg_one, raw_p, raw_two_p_minus_one }),
VecT(std::array<F, 5>{ raw_two_p_minus_one, raw_p, neg_one, F::one(), F::zero() }) };
for (int trial = 0; trial < 256; ++trial) {
std::array<F, 5> a;
std::array<F, 5> b;
for (size_t i = 0; i < 5; ++i) {
a[i] = F::random_element();
b[i] = F::random_element();
}
inputs.push_back(VecT(a) + VecT(b));
}

const auto expect_same_limbs = [](const std::array<F, 5>& expected, const std::array<F, 5>& got) {
for (size_t i = 0; i < 5; ++i) {
EXPECT_EQ(std::memcmp(expected[i].data, got[i].data, sizeof(expected[i].data)), 0) << "lane " << i;
}
};
for (const VecT& v : inputs) {
const auto expected = (v * v).to_array();
expect_same_limbs(expected, v.sqr().to_array());
VecT self = v;
self.self_sqr();
expect_same_limbs(expected, self.to_array());
if constexpr (bb::vector_field_simd_enabled) {
expect_same_limbs(expected, v.sqr_for_affine().to_array());
}
}
}

} // namespace

TEST(VectorFieldTest, SqrLimbsMatchSelfMul)
{
expect_sqr_limbs_match_self_mul<bb::VectorField<bb::Bn254FrParams>>();
}

TEST(VectorFieldFqTest, SqrLimbsMatchSelfMul)
{
expect_sqr_limbs_match_self_mul<bb::VectorField<bb::Bn254FqParams>>();
}
Loading
Loading