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

feat: generic circuit struct #123

Closed
Show file tree
Hide file tree
Changes from 1 commit
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
20 changes: 10 additions & 10 deletions crates/mpz-circuits-generic/src/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ use thiserror::Error;
/// The built output is ensured to be a directed acyclic graph (DAG).
///
/// The gates are topologically sorted.
#[derive(Debug)]
#[derive(Debug, Default)]
pub struct CircuitBuilder<T>
where
T: Component,
{
/// Circuit gates
gates: Vec<T>,
/// For each input, map the gate index that provides it.
input_map: HashMap<usize, usize>,
input_map: HashMap<u32, usize>,
}

impl<T> CircuitBuilder<T>
Expand All @@ -39,16 +39,16 @@ where

/// Adds a gate to the builder.
pub fn add_gate(&mut self, gate: T) -> &mut Self {
for &input in gate.get_inputs().iter() {
self.input_map.insert(input, self.gates.len());
for input in gate.get_inputs() {
self.input_map.insert(input.id, self.gates.len());
}

self.gates.push(gate);
self
}

/// Builds the circuit.
pub fn build(&mut self) -> Result<Circuit<T>, CircuitError> {
pub fn build(&mut self) -> Result<Circuit<T>, CircuitBuilderError> {
self.sort_gates()?;

Ok(Circuit::new(take(&mut self.gates)))
Expand All @@ -62,7 +62,7 @@ where
/// This requires that the gates form a directed acyclic graph (DAG).
///
/// The sorting is done using Kahn's Algorithm.
fn sort_gates(&mut self) -> Result<(), CircuitError> {
fn sort_gates(&mut self) -> Result<(), CircuitBuilderError> {
// In-degree: the number of gates that provide input to each gate
// This represents how many other gates need to be processed before this gate
let mut in_degree = vec![0; self.gates.len()];
Expand All @@ -72,8 +72,8 @@ where

// Populate lists
for (i, gate) in self.gates.iter().enumerate() {
for &output in gate.get_outputs().iter() {
let output = self.input_map.get(&output);
for output in gate.get_outputs() {
let output = self.input_map.get(&output.id);

if let Some(&gate_index) = output {
adjacency_list[i].push(gate_index);
Expand Down Expand Up @@ -109,7 +109,7 @@ where

// If some node is left unprocessed, there is a cycle
if sorted_indices.len() != self.gates.len() {
return Err(CircuitError::CycleDetected);
return Err(CircuitBuilderError::CycleDetected);
}

// Sort the gates
Expand Down Expand Up @@ -152,7 +152,7 @@ impl<T> Circuit<T> {

/// Circuit errors.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CircuitError {
pub enum CircuitBuilderError {
#[error("Cycle detected")]
CycleDetected,
}
7 changes: 5 additions & 2 deletions crates/mpz-circuits-generic/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
pub mod circuit;
pub mod model;
mod circuit;
mod model;

pub use circuit::{Circuit, CircuitBuilder, CircuitBuilderError};
pub use model::{Component, Node};
23 changes: 18 additions & 5 deletions crates/mpz-circuits-generic/src/model.rs
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we add a Node newtype, as we currently have in mpz-circuits. Gives us better typing. Perhaps we should also switch it from usize to u32 so the circuit isn't needlessly twice the size on 64 bit archs.

Copy link
Member Author

Choose a reason for hiding this comment

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

  • I think that adding a Node type is not strictly necessary so I wouldn't implement it in the model. Don't see how much of an improvement this extra typing could provide on our level, perhaps implementers could add this layer themselves.
  • The input or output is intended to be a position on a linear memory array so it will be usize in the end, on 64-bit architectures you'll have to complete the address to access an index.

But both are good suggestions, I could be missing something!

Copy link
Collaborator

Choose a reason for hiding this comment

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

Don't see how much of an improvement this extra typing could provide on our level

It's all about the public API: What do you want to commit to? Using usize commits to that underlying representation, whereas a Node(u32) type allows us to constrain the data type and the traits which a node implements. For example why would a node implement Add? usize does. Do we want to allow it to be mutated? How might that affect certain invariants we have elsewhere? This is less an issue for private types, but this is explicitly part of the crates pub api.

The input or output is intended to be a position on a linear memory array so it will be usize in the end

Yes it will be used to index into linear memory, but a Vec<u32> is half the size of a Vec<u64>, and hence a Vec<Gate> will be half the size if Node is backed by a u32 instead of u64 on 64-bit archs.

Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,24 @@
//!
//! This module contains the main traits and structures used to represent the circuits.

/// A `Component` trait that represents a block with inputs and outputs.
/// A `Component` defines a block with inputs and outputs.
pub trait Component {
/// Returns the input node indices.
fn get_inputs(&self) -> Vec<usize>;
/// Returns an iterator over the input node indices.
fn get_inputs(&self) -> impl Iterator<Item = &Node<u32>>;

/// Returns the output node indices.
fn get_outputs(&self) -> Vec<usize>;
/// Returns an iterator over the output node indices.
fn get_outputs(&self) -> impl Iterator<Item = &Node<u32>>;
}

/// A circuit node, holds a generic type identifier.
#[derive(Debug, Eq, PartialEq)]
pub struct Node<T> {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why is this generic?

pub(crate) id: T,
}

impl<T> Node<T> {
/// Creates a new node with the given identifier.
pub fn new(id: T) -> Self {
Self { id }
}
}
Loading