Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Perf] Introduce MulAssign for LinearCombination #1

Draft
wants to merge 3 commits into
base: mainnet-staging
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions circuit/algorithms/src/poseidon/hash_many.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,16 +163,15 @@ impl<E: Environment, const RATE: usize> Poseidon<E, RATE> {

/// Apply the Maximally Distance Separating (MDS) matrix in-place.
#[inline]
fn apply_mds(&self, state: &mut [Field<E>]) {
let mut new_state = Vec::with_capacity(state.len());
fn apply_mds(&self, state: &mut [Field<E>], new_state: &mut Vec<Field<E>>) {
for i in 0..state.len() {
let mut accumulator = Field::zero();
for (j, element) in state.iter().enumerate() {
accumulator += element * &self.mds[i][j];
}
new_state.push(accumulator);
}
state.clone_from_slice(&new_state);
state.swap_with_slice(new_state);
}

/// Apply the permutation for all rounds in-place.
Expand All @@ -183,11 +182,13 @@ impl<E: Environment, const RATE: usize> Poseidon<E, RATE> {
let partial_round_range = full_rounds_over_2..(full_rounds_over_2 + self.partial_rounds);

// Iterate through all rounds to permute.
let mut new_state = Vec::with_capacity(state.len());
for i in 0..(self.partial_rounds + self.full_rounds) {
let is_full_round = !partial_round_range.contains(&i);
self.apply_ark(state, i);
self.apply_s_box(state, is_full_round);
self.apply_mds(state);
self.apply_mds(state, &mut new_state);
new_state.clear();
}
}
}
Expand Down
16 changes: 15 additions & 1 deletion circuit/environment/src/helpers/linear_combination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use snarkvm_fields::PrimeField;

use core::{
fmt,
ops::{Add, AddAssign, Mul, Neg, Sub},
ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub},
};

// Before high level program operations are converted into constraints, they are first tracked as linear combinations.
Expand Down Expand Up @@ -463,6 +463,20 @@ impl<F: PrimeField> Mul<&F> for &LinearCombination<F> {
}
}

impl<F: PrimeField> MulAssign<&F> for LinearCombination<F> {
fn mul_assign(&mut self, coefficient: &F) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: this new implementation is virtually identical to the preexisting Mul<&F> for LinearCombination that is currently being used after first going through Mul<&F> for &LinearCombination

self.constant *= coefficient;
self.terms = std::mem::take(&mut self.terms)
.into_iter()
.filter_map(|(v, current_coefficient)| {
let res = current_coefficient * coefficient;
(!res.is_zero()).then_some((v, res))
})
.collect();
self.value *= coefficient;
}
}

impl<F: PrimeField> fmt::Debug for LinearCombination<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let mut output = format!("Constant({})", self.constant);
Expand Down
8 changes: 8 additions & 0 deletions circuit/types/field/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ description = "Field circuit for a decentralized virtual machine"
license = "Apache-2.0"
edition = "2021"

[[bench]]
name = "mul"
path = "benches/mul.rs"
harness = false

[dependencies.console]
package = "snarkvm-console-types-field"
path = "../../../console/types/field"
Expand All @@ -20,6 +25,9 @@ version = "=0.16.19"
path = "../boolean"
version = "=0.16.19"

[dev-dependencies.criterion]
version = "0.5"

[features]
default = [ "enable_console" ]
enable_console = [ "console" ]
41 changes: 41 additions & 0 deletions circuit/types/field/benches/mul.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate criterion;

use snarkvm_circuit_environment::*;
use snarkvm_circuit_types_field::Field;

use criterion::Criterion;

fn bench_mul(c: &mut Criterion) {
c.bench_function("Field::mul_assign", move |b| {
let one = Field::<Circuit>::one();
let two = one.clone() + &one;
let mut base = two.clone();

b.iter(|| {
base *= &two;
})
});
}

criterion_group! {
name = mul;
config = Criterion::default();
targets = bench_mul
}

criterion_main!(mul);
2 changes: 1 addition & 1 deletion circuit/types/field/src/mul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl<E: Environment> MulAssign<Field<E>> for Field<E> {
impl<E: Environment> MulAssign<&Field<E>> for Field<E> {
fn mul_assign(&mut self, other: &Field<E>) {
match (self.is_constant(), other.is_constant()) {
(true, true) | (false, true) => *self = (&self.linear_combination * *other.eject_value()).into(),
(true, true) | (false, true) => self.linear_combination *= &*other.eject_value(),
(true, false) => *self = (&other.linear_combination * *self.eject_value()).into(),
(false, false) => {
let product = witness!(|self, other| self * other);
Expand Down