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

More efficient Matrix data structure #45

Open
wants to merge 6 commits into
base: brakedown
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions bench-templates/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ pub fn bench_pcs_method<
let pp = PCS::setup(num_vars, Some(num_vars), rng).unwrap();
let (ck, vk) = PCS::trim(&pp, num_vars, num_vars, None).unwrap();

// Modify to alter sample size and/or significance level
group.significance_level(0.1).sample_size(10);

group.bench_with_input(
BenchmarkId::from_parameter(num_vars),
&num_vars,
Expand Down
2 changes: 1 addition & 1 deletion poly-commit/benches/brakedown_ml_times.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ fn rand_point_brakedown_ml<F: PrimeField>(num_vars: usize, rng: &mut ChaCha20Rng
}

const MIN_NUM_VARS: usize = 12;
const MAX_NUM_VARS: usize = 22;
const MAX_NUM_VARS: usize = 22; // 30

bench!(
Brakedown<Fr>,
Expand Down
6 changes: 3 additions & 3 deletions poly-commit/src/linear_codes/data_structures.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::utils::SprsMat;
use crate::{utils::Matrix, PCCommitment, PCCommitmentState};
use crate::{utils::ColumnMajorMatrix, utils::RowMajorMatrix, PCCommitment, PCCommitmentState};
use ark_crypto_primitives::{
crh::CRHScheme,
merkle_tree::{Config, LeafParam, Path, TwoToOneParam},
Expand Down Expand Up @@ -95,8 +95,8 @@ where
F: PrimeField,
H: CRHScheme,
{
pub(crate) mat: Matrix<F>,
pub(crate) ext_mat: Matrix<F>,
pub(crate) mat: RowMajorMatrix<F>,
pub(crate) ext_mat: ColumnMajorMatrix<F>,
pub(crate) leaves: Vec<H::Output>,
}

Expand Down
21 changes: 12 additions & 9 deletions poly-commit/src/linear_codes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::utils::{inner_product, Matrix};
use crate::utils::{inner_product, ColumnMajorMatrix, RowMajorMatrix};
use crate::{
to_bytes, Error, LabeledCommitment, LabeledPolynomial, PCCommitterKey, PCUniversalParams,
PCVerifierKey, PolynomialCommitment,
Expand All @@ -19,7 +19,7 @@ use ark_std::string::ToString;
use ark_std::vec::Vec;

#[cfg(feature = "parallel")]
use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};

mod utils;

Expand Down Expand Up @@ -111,7 +111,10 @@ where
/// Arrange the coefficients of the polynomial into a matrix,
/// and apply encoding to each row.
/// Returns the tuple (original_matrix, encoded_matrix).
fn compute_matrices(polynomial: &P, param: &Self::LinCodePCParams) -> (Matrix<F>, Matrix<F>) {
fn compute_matrices(
polynomial: &P,
param: &Self::LinCodePCParams,
) -> (RowMajorMatrix<F>, ColumnMajorMatrix<F>) {
let mut coeffs = Self::poly_to_vec(polynomial);

// 1. Computing the matrix dimensions.
Expand All @@ -120,11 +123,11 @@ where
// padding the coefficient vector with zeroes
coeffs.resize(n_rows * n_cols, F::zero());

let mat = Matrix::new_from_flat(n_rows, n_cols, &coeffs);
let mat = RowMajorMatrix::new_from_flat(n_rows, n_cols, &coeffs);

// 2. Apply encoding row-wise
let rows = mat.rows();
let ext_mat = Matrix::new_from_rows(
let ext_mat = ColumnMajorMatrix::new_from_rows(
cfg_iter!(rows)
.map(|r| Self::encode(r, param).unwrap())
.collect(),
Expand Down Expand Up @@ -252,9 +255,9 @@ where

// 2. Create the Merkle tree from the hashes of each column.
let ext_mat_cols = ext_mat.cols();
let leaves: Vec<H::Output> = cfg_into_iter!(ext_mat_cols)
let leaves: Vec<H::Output> = cfg_iter!(ext_mat_cols)
.map(|col| {
H::evaluate(ck.col_hash_params(), col)
H::evaluate(ck.col_hash_params(), col.borrow())
.map_err(|_| Error::HashingError)
.unwrap()
})
Expand Down Expand Up @@ -522,8 +525,8 @@ fn generate_proof<F, C, S>(
sec_param: usize,
distance: (usize, usize),
b: &[F],
mat: &Matrix<F>,
ext_mat: &Matrix<F>,
mat: &RowMajorMatrix<F>,
ext_mat: &ColumnMajorMatrix<F>,
col_tree: &MerkleTree<C>,
sponge: &mut S,
) -> Result<LinCodePCProofSingle<F, C>, Error>
Expand Down
122 changes: 80 additions & 42 deletions poly-commit/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

use ark_ff::Field;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::vec::Vec;

Check failure on line 12 in poly-commit/src/utils.rs

View workflow job for this annotation

GitHub Actions / Test (nightly)

the item `Vec` is imported redundantly

/// Takes as input a struct, and converts them to a series of bytes. All traits
/// that implement `CanonicalSerialize` can be automatically converted to bytes
Expand Down Expand Up @@ -47,14 +47,22 @@

#[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)]
#[derivative(Default(bound = ""), Clone(bound = ""), Debug(bound = ""))]
pub struct Matrix<F: Field> {
pub struct RowMajorMatrix<F: Field> {
pub(crate) n: usize,
pub(crate) m: usize,
entries: Vec<Vec<F>>,
rows: Vec<Vec<F>>,
}

impl<F: Field> Matrix<F> {
/// Returns a Matrix of dimensions n x m given a list of n * m field elements.
#[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)]
#[derivative(Default(bound = ""), Clone(bound = ""), Debug(bound = ""))]
pub struct ColumnMajorMatrix<F: Field> {
pub(crate) n: usize,
pub(crate) m: usize,
cols: Vec<Vec<F>>,
}

impl<F: Field> RowMajorMatrix<F> {
/// Returns a RowMajorMatrix of dimensions n x m given a list of n * m field elements.
/// The list should be ordered row-first, i.e. [a11, ..., a1m, a21, ..., a2m, ...].
///
/// # Panics
Expand All @@ -70,21 +78,37 @@
);

// TODO more efficient to run linearly?
let entries: Vec<Vec<F>> = (0..n)
let rows: Vec<Vec<F>> = (0..n)
.map(|row| (0..m).map(|col| entry_list[m * row + col]).collect())
.collect();

Self { n, m, entries }
Self { n, m, rows }
}

/// Returns self as a list of rows
pub(crate) fn rows(&self) -> &Vec<Vec<F>> {
&self.rows
}

/// Returns the entry in position (i, j). **Indexing starts at 0 in both coordinates**,
/// i.e. the first element is in position (0, 0) and the last one in (n - 1, j - 1),
/// where n and m are the number of rows and columns, respectively.
///
/// Index bound checks are waived for efficiency and behaviour under invalid indexing is undefined
#[cfg(test)]
pub(crate) fn entry(&self, i: usize, j: usize) -> F {
self.rows[i][j]
Comment on lines +98 to +100

Choose a reason for hiding this comment

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

this doesn't seem to be used

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, it is not used in Hyrax and in Ligero, it is only for testing. We can remove it.

}

/// Returns a Matrix given a list of its rows, each in turn represented as a list of field elements.
/// Returns a RowMajorMatrix given a list of its rows, each in turn represented as a list of field elements.
///
/// # Panics
/// Panics if the sub-lists do not all have the same length.
pub(crate) fn new_from_rows(row_list: Vec<Vec<F>>) -> Self {
let m = row_list[0].len();
#[cfg(test)]
pub(crate) fn new_from_rows(row_major: Vec<Vec<F>>) -> Self {

Choose a reason for hiding this comment

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

This is only used in testing now

Choose a reason for hiding this comment

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

can be removed / refactor tests

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 that RowMajorMatrix is used in Hyrax and Ligero too. We need this method for them. So I would say let's keep it.

let m = row_major[0].len();

for row in row_list.iter().skip(1) {
for row in row_major.iter().skip(1) {
assert_eq!(
row.len(),
m,
Expand All @@ -93,34 +117,12 @@
}

Self {
n: row_list.len(),
n: row_major.len(),
m,
entries: row_list,
rows: row_major,
}
}

/// Returns the entry in position (i, j). **Indexing starts at 0 in both coordinates**,
/// i.e. the first element is in position (0, 0) and the last one in (n - 1, j - 1),
/// where n and m are the number of rows and columns, respectively.
///
/// Index bound checks are waived for efficiency and behaviour under invalid indexing is undefined
#[cfg(test)]
pub(crate) fn entry(&self, i: usize, j: usize) -> F {
self.entries[i][j]
}

/// Returns self as a list of rows
pub(crate) fn rows(&self) -> Vec<Vec<F>> {
self.entries.clone()
}

/// Returns self as a list of columns
pub(crate) fn cols(&self) -> Vec<Vec<F>> {
(0..self.m)
.map(|col| (0..self.n).map(|row| self.entries[row][col]).collect())
.collect()
}

/// Returns the product v * self, where v is interpreted as a row vector. In other words,
/// it returns a linear combination of the rows of self with coefficients given by v.
///
Expand All @@ -139,14 +141,50 @@
inner_product(
v,
&(0..self.n)
.map(|row| self.entries[row][col])
.map(|row| self.rows[row][col])
.collect::<Vec<F>>(),
)
})
.collect()
}
}

impl<F: Field> ColumnMajorMatrix<F> {
/// Returns a ColumnMajorMatrix given a list of its rows, each in turn represented as a list of field elements.
///
/// # Panics
/// Panics if the sub-lists do not all have the same length.
pub(crate) fn new_from_rows(row_major: Vec<Vec<F>>) -> Self {
let m = row_major[0].len();

for row in row_major.iter().skip(1) {
assert_eq!(
row.len(),
m,
"Invalid matrix construction: not all rows have the same length"
);
}
let cols = (0..m)
.map(|col| {
(0..row_major.len())
.map(|row| row_major[row][col])
.collect()
})
.collect();

Self {
n: row_major.len(),
m,
cols,
}
}

/// Returns self as a list of columns
pub(crate) fn cols(&self) -> &Vec<Vec<F>> {
&self.cols
}
}

#[inline]
pub(crate) fn inner_product<F: Field>(v1: &[F], v2: &[F]) -> F {
ark_std::cfg_iter!(v1)
Expand Down Expand Up @@ -207,22 +245,22 @@
#[test]
fn test_matrix_constructor_flat() {
let entries: Vec<Fr> = to_field(vec![10, 100, 4, 67, 44, 50]);
let mat = Matrix::new_from_flat(2, 3, &entries);
let mat = RowMajorMatrix::new_from_flat(2, 3, &entries);
assert_eq!(mat.entry(1, 2), Fr::from(50));
}

#[test]
fn test_matrix_constructor_flat_square() {
let entries: Vec<Fr> = to_field(vec![10, 100, 4, 67]);
let mat = Matrix::new_from_flat(2, 2, &entries);
let mat = RowMajorMatrix::new_from_flat(2, 2, &entries);
assert_eq!(mat.entry(1, 1), Fr::from(67));
}

#[test]
#[should_panic(expected = "dimensions are 2 x 3 but entry vector has 5 entries")]
fn test_matrix_constructor_flat_panic() {
let entries: Vec<Fr> = to_field(vec![10, 100, 4, 67, 44]);
Matrix::new_from_flat(2, 3, &entries);
RowMajorMatrix::new_from_flat(2, 3, &entries);
}

#[test]
Expand All @@ -232,7 +270,7 @@
to_field(vec![23, 1, 0]),
to_field(vec![55, 58, 9]),
];
let mat = Matrix::new_from_rows(rows);
let mat = RowMajorMatrix::new_from_rows(rows);
assert_eq!(mat.entry(2, 0), Fr::from(55));
}

Expand All @@ -244,7 +282,7 @@
to_field(vec![23, 1, 0]),
to_field(vec![55, 58]),
];
Matrix::new_from_rows(rows);
ColumnMajorMatrix::new_from_rows(rows);
}

#[test]
Expand All @@ -255,7 +293,7 @@
to_field(vec![17, 89]),
];

let mat = Matrix::new_from_rows(rows);
let mat = ColumnMajorMatrix::new_from_rows(rows);

assert_eq!(mat.cols()[1], to_field(vec![76, 92, 89]));
}
Expand All @@ -268,7 +306,7 @@
to_field(vec![55, 58, 9]),
];

let mat = Matrix::new_from_rows(rows);
let mat = RowMajorMatrix::new_from_rows(rows);
let v: Vec<Fr> = to_field(vec![12, 41, 55]);
// by giving the result in the integers and then converting to Fr
// we ensure the test will still pass even if Fr changes
Expand Down
Loading