Skip to content

Commit

Permalink
Fix order of ints and floats parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
quackzar committed Sep 18, 2024
1 parent cee6c37 commit e1da08a
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 48 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ thiserror = "1.0.50"
tokio = { version = "1.32.0", features = ["full"] }
tokio-util = { version = "0.7.9", features = ["io", "net", "io-util", "codec", "full"] }
tracing = { version = "0.1.40", features = ["max_level_debug"]}
tracing-serde = "0.1.3"

[dev-dependencies]
tracing-subscriber = "0.3.18"
Expand Down
11 changes: 11 additions & 0 deletions pycare/Cargo.lock

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

5 changes: 0 additions & 5 deletions pycare/examples/vm1.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import logging
from caring import Expr, Engine, preproc

FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(format=FORMAT)
logging.getLogger().setLevel(logging.INFO)

preproc(12, 10, "./context1.bin", "./context2.bin")

engine = Engine(
Expand Down
37 changes: 16 additions & 21 deletions pycare/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,19 @@ impl Expr {
/// Construct a new share expression
#[staticmethod]
fn share(num: &Bound<'_, PyAny>) -> PyResult<Self> {
let res = if let Ok(num) = num.extract::<f64>() {
println!("sharing as float");
let num = vm::Number::Float(num);
vm::Expr::share(num)
} else if let Ok(num) = num.extract::<u64>() {
println!("sharing as int");
// TODO: Consider signedness
// TODO: Consider signed integers
let res = if let Ok(num) = num.extract::<u64>() {
let num = vm::Number::Integer(num);
vm::Expr::share(num)
} else if let Ok(num) = num.extract::<Vec<f64>>() {
println!("sharing as float");
let num: Vec<_> = num.into_iter().map(vm::Number::Float).collect();
vm::Expr::share_vec(num)
} else if let Ok(num) = num.extract::<f64>() {
let num = vm::Number::Float(num);
vm::Expr::share(num)
} else if let Ok(num) = num.extract::<Vec<u64>>() {
println!("sharing as int");
// TODO: Consider signedness
let num: Vec<_> = num.into_iter().map(vm::Number::Integer).collect();
vm::Expr::share_vec(num)
} else if let Ok(num) = num.extract::<Vec<f64>>() {
let num: Vec<_> = num.into_iter().map(vm::Number::Float).collect();
vm::Expr::share_vec(num)
} else {
return Err(PyTypeError::new_err("num is not a number"));
};
Expand All @@ -43,20 +38,20 @@ impl Expr {

#[staticmethod]
fn symmetric_share(num: &Bound<'_, PyAny>, id: Id, size: usize) -> PyResult<Vec<Expr>> {
let res = if let Ok(num) = num.extract::<f64>() {
let num = vm::Number::Float(num);
vm::Expr::symmetric_share(num)
} else if let Ok(num) = num.extract::<u64>() {
// TODO: Consider signedness
// TODO: Consider signed integers
let res = if let Ok(num) = num.extract::<u64>() {
let num = vm::Number::Integer(num);
vm::Expr::symmetric_share(num)
} else if let Ok(num) = num.extract::<Vec<f64>>() {
let num: Vec<_> = num.into_iter().map(vm::Number::Float).collect();
vm::Expr::symmetric_share_vec(num)
} else if let Ok(num) = num.extract::<f64>() {
let num = vm::Number::Float(num);
vm::Expr::symmetric_share(num)
} else if let Ok(num) = num.extract::<Vec<u64>>() {
// TODO: Consider signedness
let num: Vec<_> = num.into_iter().map(vm::Number::Integer).collect();
vm::Expr::symmetric_share_vec(num)
} else if let Ok(num) = num.extract::<Vec<f64>>() {
let num: Vec<_> = num.into_iter().map(vm::Number::Float).collect();
vm::Expr::symmetric_share_vec(num)
} else {
return Err(PyTypeError::new_err("num is not a number"));
};
Expand Down
49 changes: 28 additions & 21 deletions src/vm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{collections::BTreeMap, error::Error, fmt::Display};
use ff::{Field, PrimeField};
use itertools::{Either, Itertools};
use rand::RngCore;
use serde::{de::DeserializeOwned, Serialize};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use thiserror::Error;

use crate::{
Expand All @@ -16,10 +16,10 @@ use crate::{
schemes::{interactive::InteractiveSharedMany, spdz},
};

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Value<F> {
Single(F),
Vector(Vector<F>),
Vectorized(Vector<F>),
}

impl<F> Value<F> {
Expand All @@ -32,22 +32,22 @@ impl<F> Value<F> {

pub fn unwrap_vector(self) -> Vector<F> {
match self {
Value::Vector(v) => v,
Value::Vectorized(v) => v,
_ => panic!("Was single and not a vector!"),
}
}

pub fn map<U>(self, func: impl Fn(F) -> U) -> Value<U> {
match self {
Value::Single(a) => Value::Single(func(a)),
Value::Vector(a) => Value::Vector(a.into_iter().map(func).collect()),
Value::Vectorized(a) => Value::Vectorized(a.into_iter().map(func).collect()),
}
}

pub fn to_vec(self) -> Vec<F> {
match self {
Value::Single(s) => vec![s],
Value::Vector(v) => v.into(),
Value::Vectorized(v) => v.into(),
}
}
}
Expand All @@ -59,7 +59,7 @@ impl<F> From<F> for Value<F> {
}
impl<F> From<Vector<F>> for Value<F> {
fn from(value: Vector<F>) -> Self {
Value::Vector(value)
Value::Vectorized(value)
}
}

Expand All @@ -70,7 +70,7 @@ impl<F> Value<F> {
{
match self {
Value::Single(v) => Value::Single(v.into()),
Value::Vector(v) => Value::Vector(v.into_iter().map(|v| v.into()).collect()),
Value::Vectorized(v) => Value::Vectorized(v.into_iter().map(|v| v.into()).collect()),
}
}

Expand All @@ -80,18 +80,18 @@ impl<F> Value<F> {
{
match self {
Value::Single(v) => Ok(Value::Single(v.try_into()?)),
Value::Vector(v) => {
Value::Vectorized(v) => {
let bs: Vector<B> = v.into_iter().map(|v| v.try_into()).try_collect()?;
Ok(Value::Vector(bs))
Ok(Value::Vectorized(bs))
}
}
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConstRef(u16);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Instruction {
Share(ConstRef),
SymShare(ConstRef),
Expand Down Expand Up @@ -174,7 +174,7 @@ impl<F> Script<F> {
stack.push(1usize);
shared += 1;
}
Value::Vector(v) => {
Value::Vectorized(v) => {
stack.push(v.len());
shared += v.len();
}
Expand All @@ -184,7 +184,7 @@ impl<F> Script<F> {
stack.append(&mut vec![1usize; parties]);
shared += parties;
}
Value::Vector(v) => {
Value::Vectorized(v) => {
shared += v.len() * parties;
stack.append(&mut vec![v.len(); parties])
}
Expand All @@ -193,7 +193,7 @@ impl<F> Script<F> {
stack.pop();
match self.get_constant(*addr) {
Value::Single(_) => stack.push(1usize),
Value::Vector(v) => stack.push(v.len()),
Value::Vectorized(v) => stack.push(v.len()),
}
}
Instruction::Recv(_) => {
Expand Down Expand Up @@ -419,9 +419,12 @@ where
tracing::info!(
"Starting execution of {n} instructions with {m} contants as player {i} with {f} fuel"
);
for (i, c) in constants.iter().enumerate() {
tracing::debug!("Constant[{i}]: {c:?}");
}

for (i, opcode) in script.instructions.iter().enumerate() {
tracing::trace!("Executing opcode: {opcode:?}");
tracing::trace!("Executing opcode: {opcode}");
self.step(&mut stack, &mut results, constants, opcode)
.await
.map_err(|e| ExecutionError {
Expand All @@ -430,6 +433,10 @@ where
})?;
}

for (i, c) in results.iter().enumerate() {
tracing::debug!("Results[{i}]: {c:?}");
}

// TODO: Handle multiple outputs
results.pop().ok_or_else(|| {
let reason = Box::new(RuntimeError::<S::Error>::NoResult()).into();
Expand Down Expand Up @@ -468,7 +475,7 @@ where
let share = S::share(ctx, *f, &mut rng, &mut coms).await?;
stack.push_single(share)
}
Value::Vector(fs) => {
Value::Vectorized(fs) => {
let share = S::share_many(ctx, fs, &mut rng, &mut coms).await?;
stack.push_vector(share)
}
Expand All @@ -482,7 +489,7 @@ where
let shares = shares.into_iter().map(|s| SharedValue::Single(s));
stack.stack.extend(shares) // dirty hack
}
Value::Vector(f) => {
Value::Vectorized(f) => {
let shares = S::symmetric_share_many(ctx, f, &mut rng, &mut coms).await?;
let shares = shares.into_iter().map(|s| SharedValue::Vector(s));
stack.stack.extend(shares) // dirty hack
Expand All @@ -505,7 +512,7 @@ where
}
SharedValue::Vector(share) => {
let f = S::recombine_many(ctx, share, &mut coms).await?;
results.push(Value::Vector(f));
results.push(Value::Vectorized(f));
}
};
}
Expand All @@ -531,11 +538,11 @@ where
let con = get_constant(addr);
match (stack.pop(), con) {
(SharedValue::Single(a), Value::Single(con)) => stack.push_single(a * *con),
(SharedValue::Vector(_a), Value::Vector(_con)) => {
(SharedValue::Vector(_a), Value::Vectorized(_con)) => {
todo!("vector mult")
//stack.push_vector(a * &constant)
}
(SharedValue::Single(_), Value::Vector(_)) => todo!(),
(SharedValue::Single(_), Value::Vectorized(_)) => todo!(),
(SharedValue::Vector(_), Value::Single(_)) => todo!(),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/vm/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<F> Exp<F> {
// This is slighty cursed.
pub fn symmetric_share_vec(secret: impl Into<Vector<F>>) -> ExpList<F> {
ExpList {
constant: Value::Vector(secret.into()),
constant: Value::Vectorized(secret.into()),
}
}

Expand Down
11 changes: 11 additions & 0 deletions wecare/Cargo.lock

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

0 comments on commit e1da08a

Please sign in to comment.