file_path
stringlengths 7
180
| content
stringlengths 0
811k
| repo
stringclasses 11
values |
---|---|---|
src/pfsys/evm/aggregation_kzg.rs | #[cfg(not(target_arch = "wasm32"))]
use crate::graph::CircuitSize;
use crate::pfsys::{Snark, SnarkWitness};
#[cfg(not(target_arch = "wasm32"))]
use colored_json::ToColoredJson;
use halo2_proofs::circuit::AssignedCell;
use halo2_proofs::plonk::{self};
use halo2_proofs::{
circuit::{Layouter, SimpleFloorPlanner, Value},
plonk::{Circuit, ConstraintSystem},
};
use halo2_wrong_ecc::{
integer::rns::Rns,
maingate::{
MainGate, MainGateConfig, MainGateInstructions, RangeChip, RangeConfig, RangeInstructions,
RegionCtx,
},
EccConfig,
};
use halo2curves::bn256::{Bn256, Fq, Fr, G1Affine};
use halo2curves::ff::PrimeField;
use itertools::Itertools;
#[cfg(not(target_arch = "wasm32"))]
use log::debug;
use log::trace;
use rand::rngs::OsRng;
use snark_verifier::loader::native::NativeLoader;
use snark_verifier::loader::EcPointLoader;
use snark_verifier::{
loader,
pcs::{
kzg::{
Bdfg21, KzgAccumulator, KzgAs, KzgSuccinctVerifyingKey, LimbsEncoding,
LimbsEncodingInstructions,
},
AccumulationScheme, AccumulationSchemeProver,
},
system,
util::arithmetic::fe_to_limbs,
verifier::{self, SnarkVerifier},
};
use std::rc::Rc;
use thiserror::Error;
const LIMBS: usize = 4;
const BITS: usize = 68;
type As = KzgAs<Bn256, Bdfg21>;
/// Type for aggregator verification
type PlonkSuccinctVerifier = verifier::plonk::PlonkSuccinctVerifier<As, LimbsEncoding<LIMBS, BITS>>;
const T: usize = 5;
const RATE: usize = 4;
const R_F: usize = 8;
const R_P: usize = 60;
type Svk = KzgSuccinctVerifyingKey<G1Affine>;
type BaseFieldEccChip = halo2_wrong_ecc::BaseFieldEccChip<G1Affine, LIMBS, BITS>;
/// The loader type used in the transcript definition
type Halo2Loader<'a> = loader::halo2::Halo2Loader<'a, G1Affine, BaseFieldEccChip>;
/// Application snark transcript
pub type PoseidonTranscript<L, S> =
system::halo2::transcript::halo2::PoseidonTranscript<G1Affine, L, S, T, RATE, R_F, R_P>;
#[derive(Error, Debug)]
/// Errors related to proof aggregation
pub enum AggregationError {
/// A KZG proof could not be verified
#[error("failed to verify KZG proof")]
KZGProofVerification,
/// proof read errors
#[error("Failed to read proof")]
ProofRead,
/// proof verification errors
#[error("Failed to verify proof")]
ProofVerify,
/// proof creation errors
#[error("Failed to create proof")]
ProofCreate,
}
type AggregationResult<'a> = (
// accumulator
KzgAccumulator<G1Affine, Rc<Halo2Loader<'a>>>,
// the set of assigned cells
Vec<Vec<AssignedCell<Fr, Fr>>>,
);
type LoadedProof<'a> = verifier::plonk::PlonkProof<
G1Affine,
Rc<
loader::halo2::Halo2Loader<
'a,
G1Affine,
halo2_wrong_ecc::BaseFieldEccChip<G1Affine, 4, 68>,
>,
>,
KzgAs<Bn256, Bdfg21>,
>;
/// Aggregate one or more application snarks of the same shape into a KzgAccumulator
pub fn aggregate<'a>(
svk: &Svk,
loader: &Rc<Halo2Loader<'a>>,
snarks: &[SnarkWitness<Fr, G1Affine>],
as_proof: Value<&'_ [u8]>,
split_proofs: bool,
) -> Result<AggregationResult<'a>, plonk::Error> {
let assign_instances = |instances: &[Vec<Value<Fr>>]| {
instances
.iter()
.map(|instances| {
instances
.iter()
.map(|instance| loader.assign_scalar(*instance))
.collect_vec()
})
.collect_vec()
};
let mut accumulators = vec![];
let mut snark_instances = vec![];
let mut proofs: Vec<LoadedProof<'_>> = vec![];
for snark in snarks.iter() {
let protocol = snark.protocol.as_ref().unwrap().loaded(loader);
let instances = assign_instances(&snark.instances);
// get assigned cells
snark_instances.extend(instances.iter().map(|instance| {
instance
.iter()
.map(|v| v.clone().into_assigned())
.collect_vec()
}));
// loader.ctx().constrain_equal(cell_0, cell_1)
let mut transcript = PoseidonTranscript::<Rc<Halo2Loader>, _>::new(loader, snark.proof());
let proof = PlonkSuccinctVerifier::read_proof(svk, &protocol, &instances, &mut transcript)
.map_err(|_| plonk::Error::Synthesis)?;
if split_proofs {
let previous_proof = proofs.last();
let split_commit = match snark.clone().split {
Some(split) => split,
None => {
log::error!("Failed to split KZG commit for sequential proofs");
return Err(plonk::Error::Synthesis);
}
};
if let Some(previous_proof) = previous_proof {
// output of previous proof
let output = &previous_proof.witnesses[split_commit.start..split_commit.end];
// input of current proof
let split_commit_len = split_commit.end - split_commit.start;
let input = &proof.witnesses[..split_commit_len];
// these points were already assigned previously when loading the transcript so this is safe
// and equivalent to a copy constraint and an equality constraint
for (output, input) in output.iter().zip(input.iter()) {
loader
.ec_point_assert_eq("assert commits match", output, input)
.map_err(|e| {
log::error!(
"Failed to match KZG commits for sequential proofs: {:?}",
e
);
plonk::Error::Synthesis
})?;
}
}
proofs.push(proof.clone());
}
let mut accum = PlonkSuccinctVerifier::verify(svk, &protocol, &instances, &proof)
.map_err(|_| plonk::Error::Synthesis)?;
accumulators.append(&mut accum);
}
let accumulator = {
let mut transcript = PoseidonTranscript::<Rc<Halo2Loader>, _>::new(loader, as_proof);
let proof = As::read_proof(&Default::default(), &accumulators, &mut transcript).unwrap();
As::verify(&Default::default(), &accumulators, &proof).map_err(|_| plonk::Error::Synthesis)
}?;
Ok((accumulator, snark_instances))
}
/// The Halo2 Config for the aggregation circuit
#[derive(Clone, Debug)]
pub struct AggregationConfig {
main_gate_config: MainGateConfig,
range_config: RangeConfig,
}
impl AggregationConfig {
/// Configure the aggregation circuit
pub fn configure<F: PrimeField>(
meta: &mut ConstraintSystem<F>,
composition_bits: Vec<usize>,
overflow_bits: Vec<usize>,
) -> Self {
let main_gate_config = MainGate::<F>::configure(meta);
let range_config =
RangeChip::<F>::configure(meta, &main_gate_config, composition_bits, overflow_bits);
#[cfg(not(target_arch = "wasm32"))]
{
let circuit_size = CircuitSize::from_cs(meta, 23);
// not wasm
debug!(
"circuit size: \n {}",
circuit_size
.as_json()
.unwrap()
.to_colored_json_auto()
.unwrap()
);
}
AggregationConfig {
main_gate_config,
range_config,
}
}
/// Create a MainGate from the aggregation approach
pub fn main_gate(&self) -> MainGate<Fr> {
MainGate::new(self.main_gate_config.clone())
}
/// Create a range chip to decompose and range check inputs
pub fn range_chip(&self) -> RangeChip<Fr> {
RangeChip::new(self.range_config.clone())
}
/// Create an ecc chip for ec ops
pub fn ecc_chip(&self) -> BaseFieldEccChip {
BaseFieldEccChip::new(EccConfig::new(
self.range_config.clone(),
self.main_gate_config.clone(),
))
}
}
/// Aggregation Circuit with a SuccinctVerifyingKey, application snark witnesses (each with a proof and instance variables), and the instance variables and the resulting aggregation circuit proof.
#[derive(Clone, Debug)]
pub struct AggregationCircuit {
svk: Svk,
snarks: Vec<SnarkWitness<Fr, G1Affine>>,
instances: Vec<Fr>,
as_proof: Value<Vec<u8>>,
split_proof: bool,
}
impl AggregationCircuit {
/// Create a new Aggregation Circuit with a SuccinctVerifyingKey, application snark witnesses (each with a proof and instance variables), and the instance variables and the resulting aggregation circuit proof.
pub fn new(
svk: &KzgSuccinctVerifyingKey<G1Affine>,
snarks: impl IntoIterator<Item = Snark<Fr, G1Affine>>,
split_proof: bool,
) -> Result<Self, AggregationError> {
let snarks = snarks.into_iter().collect_vec();
let mut accumulators = vec![];
for snark in snarks.iter() {
trace!("Aggregating with snark instances {:?}", snark.instances);
let mut transcript = PoseidonTranscript::<NativeLoader, _>::new(snark.proof.as_slice());
let proof = PlonkSuccinctVerifier::read_proof(
svk,
snark.protocol.as_ref().unwrap(),
&snark.instances,
&mut transcript,
)
.map_err(|e| {
log::error!("{:?}", e);
AggregationError::ProofRead
})?;
let mut accum = PlonkSuccinctVerifier::verify(
svk,
snark.protocol.as_ref().unwrap(),
&snark.instances,
&proof,
)
.map_err(|_| AggregationError::ProofVerify)?;
accumulators.append(&mut accum);
}
trace!("Accumulator");
let (accumulator, as_proof) = {
let mut transcript = PoseidonTranscript::<NativeLoader, _>::new(Vec::new());
let accumulator =
As::create_proof(&Default::default(), &accumulators, &mut transcript, OsRng)
.map_err(|_| AggregationError::ProofCreate)?;
(accumulator, transcript.finalize())
};
trace!("KzgAccumulator");
let KzgAccumulator { lhs, rhs } = accumulator;
let instances = [lhs.x, lhs.y, rhs.x, rhs.y]
.map(fe_to_limbs::<_, _, LIMBS, BITS>)
.concat();
Ok(Self {
svk: *svk,
snarks: snarks.into_iter().map_into().collect(),
instances,
as_proof: Value::known(as_proof),
split_proof,
})
}
///
pub fn num_limbs() -> usize {
LIMBS
}
///
pub fn num_bits() -> usize {
BITS
}
/// Accumulator indices used in generating verifier.
pub fn accumulator_indices() -> Vec<(usize, usize)> {
(0..4 * LIMBS).map(|idx| (0, idx)).collect()
}
/// Number of instance variables for the aggregation circuit, used in generating verifier.
pub fn num_instance(orginal_circuit_instances: usize) -> Vec<usize> {
let accumulation_instances = 4 * LIMBS;
vec![accumulation_instances + orginal_circuit_instances]
}
/// Instance variables for the aggregation circuit, fed to verifier.
pub fn instances(&self) -> Vec<Fr> {
// also get snark instances here
let mut snark_instances: Vec<Vec<Vec<Value<Fr>>>> = self
.snarks
.iter()
.map(|snark| snark.instances.clone())
.collect_vec();
// reduce from Vec<Vec<Vec<Value<Fr>>>> to Vec<Vec<Value<Fr>>>
let mut instances: Vec<Fr> = self.instances.clone();
for snark_instance in snark_instances.iter_mut() {
for instance in snark_instance.iter_mut() {
let mut felt_evals = vec![];
for value in instance.iter_mut() {
value.map(|v| felt_evals.push(v));
}
instances.extend(felt_evals);
}
}
instances
}
fn as_proof(&self) -> Value<&[u8]> {
self.as_proof.as_ref().map(Vec::as_slice)
}
}
impl Circuit<Fr> for AggregationCircuit {
type Config = AggregationConfig;
type FloorPlanner = SimpleFloorPlanner;
type Params = ();
fn without_witnesses(&self) -> Self {
Self {
svk: self.svk,
snarks: self
.snarks
.iter()
.map(SnarkWitness::without_witnesses)
.collect(),
instances: Vec::new(),
as_proof: Value::unknown(),
split_proof: self.split_proof,
}
}
fn configure(meta: &mut ConstraintSystem<Fr>) -> Self::Config {
AggregationConfig::configure(
meta,
vec![BITS / LIMBS],
Rns::<Fq, Fr, LIMBS, BITS>::construct().overflow_lengths(),
)
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<Fr>,
) -> Result<(), plonk::Error> {
let main_gate = config.main_gate();
let range_chip = config.range_chip();
range_chip.load_table(&mut layouter)?;
let (accumulator_limbs, snark_instances) = layouter.assign_region(
|| "",
|region| {
let ctx = RegionCtx::new(region, 0);
let ecc_chip = config.ecc_chip();
let loader = Halo2Loader::new(ecc_chip, ctx);
let (accumulator, snark_instances) = aggregate(
&self.svk,
&loader,
&self.snarks,
self.as_proof(),
self.split_proof,
)?;
let accumulator_limbs = [accumulator.lhs, accumulator.rhs]
.iter()
.map(|ec_point| {
loader
.ecc_chip()
.assign_ec_point_to_limbs(&mut loader.ctx_mut(), ec_point.assigned())
})
.collect::<Result<Vec<_>, plonk::Error>>()?
.into_iter()
.flatten();
Ok((accumulator_limbs, snark_instances))
},
)?;
let mut instance_offset = 0;
for limb in accumulator_limbs {
main_gate.expose_public(layouter.namespace(|| ""), limb, instance_offset)?;
instance_offset += 1;
}
for instance in snark_instances.into_iter() {
for elem in instance.into_iter() {
main_gate.expose_public(layouter.namespace(|| ""), elem, instance_offset)?;
instance_offset += 1;
}
}
Ok(())
}
}
| https://github.com/zkonduit/ezkl |
src/pfsys/evm/mod.rs | use thiserror::Error;
/// Aggregate proof generation for EVM using KZG
pub mod aggregation_kzg;
#[derive(Error, Debug)]
/// Errors related to evm verification
pub enum EvmVerificationError {
/// If the Solidity verifier worked but returned false
#[error("Solidity verifier found the proof invalid")]
InvalidProof,
/// If the Solidity verifier threw and error (e.g. OutOfGas)
#[error("Execution of Solidity code failed")]
SolidityExecution,
/// EVM execution errors
#[error("EVM execution of raw code failed")]
RawExecution,
/// EVM verify errors
#[error("evm verification reverted")]
Reverted,
/// EVM verify errors
#[error("evm deployment failed")]
Deploy,
/// Invalid Visibilit
#[error("Invalid visibility")]
InvalidVisibility,
}
| https://github.com/zkonduit/ezkl |
src/pfsys/mod.rs | /// EVM related proving and verification
pub mod evm;
/// SRS generation, processing, verification and downloading
pub mod srs;
use crate::circuit::CheckMode;
use crate::graph::GraphWitness;
use crate::pfsys::evm::aggregation_kzg::PoseidonTranscript;
use crate::{Commitments, EZKL_BUF_CAPACITY, EZKL_KEY_FORMAT};
use clap::ValueEnum;
use halo2_proofs::circuit::Value;
use halo2_proofs::plonk::{
create_proof, keygen_pk, keygen_vk_custom, verify_proof, Circuit, ProvingKey, VerifyingKey,
};
use halo2_proofs::poly::commitment::{CommitmentScheme, Params, ParamsProver, Prover, Verifier};
use halo2_proofs::poly::ipa::commitment::IPACommitmentScheme;
use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;
use halo2_proofs::poly::VerificationStrategy;
use halo2_proofs::transcript::{EncodedChallenge, TranscriptReadBuffer, TranscriptWriterBuffer};
use halo2curves::ff::{FromUniformBytes, PrimeField, WithSmallOrderMulGroup};
use halo2curves::serde::SerdeObject;
use halo2curves::CurveAffine;
use instant::Instant;
use log::{debug, info, trace};
#[cfg(not(feature = "det-prove"))]
use rand::rngs::OsRng;
#[cfg(feature = "det-prove")]
use rand::rngs::StdRng;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use snark_verifier::loader::native::NativeLoader;
use snark_verifier::system::halo2::transcript::evm::EvmTranscript;
use snark_verifier::verifier::plonk::PlonkProtocol;
use std::error::Error;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Cursor, Write};
use std::ops::Deref;
use std::path::PathBuf;
use thiserror::Error as thisError;
use tosubcommand::ToFlags;
use halo2curves::bn256::{Bn256, Fr, G1Affine};
fn serde_format_from_str(s: &str) -> halo2_proofs::SerdeFormat {
match s {
"processed" => halo2_proofs::SerdeFormat::Processed,
"raw-bytes-unchecked" => halo2_proofs::SerdeFormat::RawBytesUnchecked,
"raw-bytes" => halo2_proofs::SerdeFormat::RawBytes,
_ => panic!("invalid serde format"),
}
}
#[allow(missing_docs)]
#[derive(
ValueEnum, Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize, Serialize, PartialOrd,
)]
pub enum ProofType {
#[default]
Single,
ForAggr,
}
impl std::fmt::Display for ProofType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
ProofType::Single => "single",
ProofType::ForAggr => "for-aggr",
}
)
}
}
impl ToFlags for ProofType {
fn to_flags(&self) -> Vec<String> {
vec![format!("{}", self)]
}
}
impl From<ProofType> for TranscriptType {
fn from(val: ProofType) -> Self {
match val {
ProofType::Single => TranscriptType::EVM,
ProofType::ForAggr => TranscriptType::Poseidon,
}
}
}
impl From<ProofType> for StrategyType {
fn from(val: ProofType) -> Self {
match val {
ProofType::Single => StrategyType::Single,
ProofType::ForAggr => StrategyType::Accum,
}
}
}
#[cfg(feature = "python-bindings")]
impl ToPyObject for ProofType {
fn to_object(&self, py: Python) -> PyObject {
match self {
ProofType::Single => "Single".to_object(py),
ProofType::ForAggr => "ForAggr".to_object(py),
}
}
}
#[cfg(feature = "python-bindings")]
/// Obtains StrategyType from PyObject (Required for StrategyType to be compatible with Python)
impl<'source> pyo3::FromPyObject<'source> for ProofType {
fn extract(ob: &'source pyo3::PyAny) -> pyo3::PyResult<Self> {
let trystr = <pyo3::types::PyString as pyo3::PyTryFrom>::try_from(ob)?;
let strval = trystr.to_string();
match strval.to_lowercase().as_str() {
"single" => Ok(ProofType::Single),
"for-aggr" => Ok(ProofType::ForAggr),
_ => Err(pyo3::exceptions::PyValueError::new_err(
"Invalid value for ProofType",
)),
}
}
}
#[allow(missing_docs)]
#[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum StrategyType {
Single,
Accum,
}
impl std::fmt::Display for StrategyType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value()
.expect("no values are skipped")
.get_name()
.fmt(f)
}
}
#[cfg(feature = "python-bindings")]
/// Converts StrategyType into a PyObject (Required for StrategyType to be compatible with Python)
impl pyo3::IntoPy<PyObject> for StrategyType {
fn into_py(self, py: Python) -> PyObject {
match self {
StrategyType::Single => "single".to_object(py),
StrategyType::Accum => "accum".to_object(py),
}
}
}
#[cfg(feature = "python-bindings")]
/// Obtains StrategyType from PyObject (Required for StrategyType to be compatible with Python)
impl<'source> pyo3::FromPyObject<'source> for StrategyType {
fn extract(ob: &'source pyo3::PyAny) -> pyo3::PyResult<Self> {
let trystr = <pyo3::types::PyString as pyo3::PyTryFrom>::try_from(ob)?;
let strval = trystr.to_string();
match strval.to_lowercase().as_str() {
"single" => Ok(StrategyType::Single),
"accum" => Ok(StrategyType::Accum),
_ => Err(pyo3::exceptions::PyValueError::new_err(
"Invalid value for StrategyType",
)),
}
}
}
#[derive(thisError, Debug)]
/// Errors related to pfsys
pub enum PfSysError {
/// Packing exponent is too large
#[error("largest packing exponent exceeds max. try reducing the scale")]
PackingExponent,
}
#[allow(missing_docs)]
#[derive(
ValueEnum, Default, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, PartialOrd,
)]
pub enum TranscriptType {
Poseidon,
#[default]
EVM,
}
impl std::fmt::Display for TranscriptType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
TranscriptType::Poseidon => "poseidon",
TranscriptType::EVM => "evm",
}
)
}
}
impl ToFlags for TranscriptType {
fn to_flags(&self) -> Vec<String> {
vec![format!("{}", self)]
}
}
#[cfg(feature = "python-bindings")]
impl ToPyObject for TranscriptType {
fn to_object(&self, py: Python) -> PyObject {
match self {
TranscriptType::Poseidon => "Poseidon".to_object(py),
TranscriptType::EVM => "EVM".to_object(py),
}
}
}
#[cfg(feature = "python-bindings")]
///
pub fn g1affine_to_pydict(g1affine_dict: &PyDict, g1affine: &G1Affine) {
let g1affine_x = field_to_string(&g1affine.x);
let g1affine_y = field_to_string(&g1affine.y);
g1affine_dict.set_item("x", g1affine_x).unwrap();
g1affine_dict.set_item("y", g1affine_y).unwrap();
}
#[cfg(feature = "python-bindings")]
use halo2curves::bn256::G1;
#[cfg(feature = "python-bindings")]
///
pub fn g1_to_pydict(g1_dict: &PyDict, g1: &G1) {
let g1_x = field_to_string(&g1.x);
let g1_y = field_to_string(&g1.y);
let g1_z = field_to_string(&g1.z);
g1_dict.set_item("x", g1_x).unwrap();
g1_dict.set_item("y", g1_y).unwrap();
g1_dict.set_item("z", g1_z).unwrap();
}
/// converts fp into a little endian Hex string
pub fn field_to_string<F: PrimeField + SerdeObject + Serialize>(fp: &F) -> String {
let repr = serde_json::to_string(&fp).unwrap();
let b: String = serde_json::from_str(&repr).unwrap();
b
}
/// converts a little endian Hex string into a field element
pub fn string_to_field<F: PrimeField + SerdeObject + Serialize + DeserializeOwned>(
b: &String,
) -> F {
let repr = serde_json::to_string(&b).unwrap();
let fp: F = serde_json::from_str(&repr).unwrap();
fp
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
/// Contains the instances of the circuit in human readable form
pub struct PrettyElements {
/// the inputs as rescaled floats -- represented as a String for maximum compatibility with Python and JS
pub rescaled_inputs: Vec<Vec<String>>,
/// the inputs as felts but 0x strings -- represented as a String for maximum compatibility with Python and JS
pub inputs: Vec<Vec<String>>,
/// the processed inputs (eg. hash of the inputs) -- stays as a felt represented as a 0x string for maximum compatibility with Python and JS
pub processed_inputs: Vec<Vec<String>>,
/// the processed params (eg. hash of the params) -- stays as a felt represented as a 0x string for maximum compatibility with Python and JS
pub processed_params: Vec<Vec<String>>,
/// the processed outputs (eg. hash of the outputs) -- stays as a felt represented as a 0x string for maximum compatibility with Python and JS
pub processed_outputs: Vec<Vec<String>>,
/// the outputs as rescaled floats (if any) -- represented as a String for maximum compatibility with Python and JS
pub rescaled_outputs: Vec<Vec<String>>,
/// the outputs as felts but 0x strings (if any) -- represented as a String for maximum compatibility with Python and JS
pub outputs: Vec<Vec<String>>,
}
/// An application snark with proof and instance variables ready for aggregation (raw field element)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Snark<F: PrimeField + SerdeObject, C: CurveAffine>
where
C::Scalar: Serialize + DeserializeOwned,
C::ScalarExt: Serialize + DeserializeOwned,
{
/// the protocol
pub protocol: Option<PlonkProtocol<C>>,
/// public instances of the snark
pub instances: Vec<Vec<F>>,
/// the proof
pub proof: Vec<u8>,
/// hex encoded proof
pub hex_proof: Option<String>,
/// transcript type
pub transcript_type: TranscriptType,
/// the split proof
pub split: Option<ProofSplitCommit>,
/// the proof instances as rescaled floats
pub pretty_public_inputs: Option<PrettyElements>,
/// timestamp
pub timestamp: Option<u128>,
/// commitment
pub commitment: Option<Commitments>,
}
#[cfg(feature = "python-bindings")]
use pyo3::{types::PyDict, PyObject, Python, ToPyObject};
#[cfg(feature = "python-bindings")]
impl<F: PrimeField + SerdeObject + Serialize, C: CurveAffine + Serialize> ToPyObject for Snark<F, C>
where
C::Scalar: Serialize + DeserializeOwned,
C::ScalarExt: Serialize + DeserializeOwned,
{
fn to_object(&self, py: Python) -> PyObject {
let dict = PyDict::new(py);
let field_elems: Vec<Vec<String>> = self
.instances
.iter()
.map(|x| x.iter().map(|fp| field_to_string(fp)).collect())
.collect::<Vec<_>>();
dict.set_item("instances", field_elems).unwrap();
let hex_proof = hex::encode(&self.proof);
dict.set_item("proof", format!("0x{}", hex_proof)).unwrap();
dict.set_item("transcript_type", self.transcript_type)
.unwrap();
dict.to_object(py)
}
}
impl<
F: PrimeField + SerdeObject + Serialize + FromUniformBytes<64> + DeserializeOwned,
C: CurveAffine + Serialize + DeserializeOwned,
> Snark<F, C>
where
C::Scalar: Serialize + DeserializeOwned,
C::ScalarExt: Serialize + DeserializeOwned,
{
/// Create a new application snark from proof and instance variables ready for aggregation
pub fn new(
protocol: Option<PlonkProtocol<C>>,
instances: Vec<Vec<F>>,
proof: Vec<u8>,
hex_proof: Option<String>,
transcript_type: TranscriptType,
split: Option<ProofSplitCommit>,
pretty_public_inputs: Option<PrettyElements>,
commitment: Option<Commitments>,
) -> Self {
Self {
protocol,
instances,
proof,
hex_proof,
transcript_type,
split,
pretty_public_inputs,
// unix timestamp
timestamp: Some(
instant::SystemTime::now()
.duration_since(instant::SystemTime::UNIX_EPOCH)
.unwrap()
.as_millis(),
),
commitment,
}
}
/// create hex proof from proof
pub fn create_hex_proof(&mut self) {
let hex_proof = hex::encode(&self.proof);
self.hex_proof = Some(format!("0x{}", hex_proof));
}
/// Saves the Proof to a specified `proof_path`.
pub fn save(&self, proof_path: &PathBuf) -> Result<(), Box<dyn Error>> {
let file = std::fs::File::create(proof_path)?;
let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, file);
serde_json::to_writer(&mut writer, &self)?;
Ok(())
}
/// Load a json serialized proof from the provided path.
pub fn load<Scheme: CommitmentScheme<Curve = C, Scalar = F>>(
proof_path: &PathBuf,
) -> Result<Self, Box<dyn Error>>
where
<C as CurveAffine>::ScalarExt: FromUniformBytes<64>,
{
trace!("reading proof");
let file = std::fs::File::open(proof_path)?;
let reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, file);
let proof: Self = serde_json::from_reader(reader)?;
Ok(proof)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// A proof split commit
pub struct ProofSplitCommit {
/// The start index of the output in the witness
start: usize,
/// The end index of the output in the witness
end: usize,
}
impl From<GraphWitness> for Option<ProofSplitCommit> {
fn from(witness: GraphWitness) -> Self {
let mut elem_offset = 0;
if let Some(input) = witness.processed_inputs {
if let Some(polycommit) = input.polycommit {
// flatten and count number of elements
let num_elements = polycommit
.iter()
.map(|polycommit| polycommit.len())
.sum::<usize>();
elem_offset += num_elements;
}
}
if let Some(params) = witness.processed_params {
if let Some(polycommit) = params.polycommit {
// flatten and count number of elements
let num_elements = polycommit
.iter()
.map(|polycommit| polycommit.len())
.sum::<usize>();
elem_offset += num_elements;
}
}
if let Some(output) = witness.processed_outputs {
if let Some(polycommit) = output.polycommit {
// flatten and count number of elements
let num_elements = polycommit
.iter()
.map(|polycommit| polycommit.len())
.sum::<usize>();
Some(ProofSplitCommit {
start: elem_offset,
end: elem_offset + num_elements,
})
} else {
None
}
} else {
None
}
}
}
/// An application snark with proof and instance variables ready for aggregation (wrapped field element)
#[derive(Clone, Debug)]
pub struct SnarkWitness<F: PrimeField, C: CurveAffine> {
protocol: Option<PlonkProtocol<C>>,
instances: Vec<Vec<Value<F>>>,
proof: Value<Vec<u8>>,
split: Option<ProofSplitCommit>,
}
impl<F: PrimeField, C: CurveAffine> SnarkWitness<F, C> {
fn without_witnesses(&self) -> Self {
SnarkWitness {
protocol: self.protocol.clone(),
instances: self
.instances
.iter()
.map(|instances| vec![Value::unknown(); instances.len()])
.collect(),
proof: Value::unknown(),
split: self.split.clone(),
}
}
fn proof(&self) -> Value<&[u8]> {
self.proof.as_ref().map(Vec::as_slice)
}
}
impl<F: PrimeField + SerdeObject, C: CurveAffine> From<Snark<F, C>> for SnarkWitness<F, C>
where
C::Scalar: Serialize + DeserializeOwned,
C::ScalarExt: Serialize + DeserializeOwned,
{
fn from(snark: Snark<F, C>) -> Self {
Self {
protocol: snark.protocol,
instances: snark
.instances
.into_iter()
.map(|instances| instances.into_iter().map(Value::known).collect())
.collect(),
proof: Value::known(snark.proof),
split: snark.split,
}
}
}
/// Creates a [VerifyingKey] and [ProvingKey] for a [crate::graph::GraphCircuit] (`circuit`) with specific [CommitmentScheme] parameters (`params`).
pub fn create_keys<Scheme: CommitmentScheme, C: Circuit<Scheme::Scalar>>(
circuit: &C,
params: &'_ Scheme::ParamsProver,
disable_selector_compression: bool,
) -> Result<ProvingKey<Scheme::Curve>, halo2_proofs::plonk::Error>
where
C: Circuit<Scheme::Scalar>,
<Scheme as CommitmentScheme>::Scalar: FromUniformBytes<64>,
{
// Real proof
let empty_circuit = <C as Circuit<Scheme::Scalar>>::without_witnesses(circuit);
// Initialize verifying key
let now = Instant::now();
trace!("preparing VK");
let vk = keygen_vk_custom(params, &empty_circuit, !disable_selector_compression)?;
let elapsed = now.elapsed();
info!("VK took {}.{}", elapsed.as_secs(), elapsed.subsec_millis());
// Initialize the proving key
let now = Instant::now();
let pk = keygen_pk(params, vk, &empty_circuit)?;
let elapsed = now.elapsed();
info!("PK took {}.{}", elapsed.as_secs(), elapsed.subsec_millis());
Ok(pk)
}
/// a wrapper around halo2's create_proof
#[allow(clippy::too_many_arguments)]
pub fn create_proof_circuit<
'params,
Scheme: CommitmentScheme,
C: Circuit<Scheme::Scalar>,
P: Prover<'params, Scheme>,
V: Verifier<'params, Scheme>,
Strategy: VerificationStrategy<'params, Scheme, V>,
E: EncodedChallenge<Scheme::Curve>,
TW: TranscriptWriterBuffer<Vec<u8>, Scheme::Curve, E>,
TR: TranscriptReadBuffer<Cursor<Vec<u8>>, Scheme::Curve, E>,
>(
circuit: C,
instances: Vec<Vec<Scheme::Scalar>>,
params: &'params Scheme::ParamsProver,
pk: &ProvingKey<Scheme::Curve>,
check_mode: CheckMode,
commitment: Commitments,
transcript_type: TranscriptType,
split: Option<ProofSplitCommit>,
protocol: Option<PlonkProtocol<Scheme::Curve>>,
) -> Result<Snark<Scheme::Scalar, Scheme::Curve>, Box<dyn Error>>
where
Scheme::ParamsVerifier: 'params,
Scheme::Scalar: Serialize
+ DeserializeOwned
+ SerdeObject
+ PrimeField
+ FromUniformBytes<64>
+ WithSmallOrderMulGroup<3>,
Scheme::Curve: Serialize + DeserializeOwned,
{
let strategy = Strategy::new(params.verifier_params());
let mut transcript = TranscriptWriterBuffer::<_, Scheme::Curve, _>::init(vec![]);
#[cfg(feature = "det-prove")]
let mut rng = <StdRng as rand::SeedableRng>::from_seed([0u8; 32]);
#[cfg(not(feature = "det-prove"))]
let mut rng = OsRng;
let pi_inner = instances
.iter()
.map(|e| e.deref())
.collect::<Vec<&[Scheme::Scalar]>>();
let pi_inner: &[&[&[Scheme::Scalar]]] = &[&pi_inner];
trace!("instances {:?}", instances);
trace!(
"pk num instance column: {:?}",
pk.get_vk().cs().num_instance_columns()
);
info!("proof started...");
// not wasm32 unknown
let now = Instant::now();
create_proof::<Scheme, P, _, _, TW, _>(
params,
pk,
&[circuit],
pi_inner,
&mut rng,
&mut transcript,
)?;
let proof = transcript.finalize();
let hex_proof = format!("0x{}", hex::encode(&proof));
let checkable_pf = Snark::new(
protocol,
instances,
proof,
Some(hex_proof),
transcript_type,
split,
None,
Some(commitment),
);
// sanity check that the generated proof is valid
if check_mode == CheckMode::SAFE {
debug!("verifying generated proof");
let verifier_params = params.verifier_params();
verify_proof_circuit::<V, Scheme, Strategy, E, TR>(
&checkable_pf,
verifier_params,
pk.get_vk(),
strategy,
verifier_params.n(),
)?;
}
let elapsed = now.elapsed();
info!(
"proof took {}.{}",
elapsed.as_secs(),
elapsed.subsec_millis()
);
Ok(checkable_pf)
}
/// Swaps the proof commitments to a new set in the proof
pub fn swap_proof_commitments<
Scheme: CommitmentScheme,
E: EncodedChallenge<Scheme::Curve>,
TW: TranscriptWriterBuffer<Vec<u8>, Scheme::Curve, E>,
>(
snark: &Snark<Scheme::Scalar, Scheme::Curve>,
commitments: &[Scheme::Curve],
) -> Result<Snark<Scheme::Scalar, Scheme::Curve>, Box<dyn Error>>
where
Scheme::Scalar: SerdeObject
+ PrimeField
+ FromUniformBytes<64>
+ WithSmallOrderMulGroup<3>
+ Ord
+ Serialize
+ DeserializeOwned,
Scheme::Curve: Serialize + DeserializeOwned,
{
let mut transcript_new: TW = TranscriptWriterBuffer::<_, Scheme::Curve, _>::init(vec![]);
// polycommit commitments are the first set of points in the proof, this we'll always be the first set of advice
for commit in commitments {
transcript_new
.write_point(*commit)
.map_err(|_| "failed to write point")?;
}
let proof_first_bytes = transcript_new.finalize();
let mut snark_new = snark.clone();
// swap the proof bytes for the new ones
snark_new.proof[..proof_first_bytes.len()].copy_from_slice(&proof_first_bytes);
snark_new.create_hex_proof();
Ok(snark_new)
}
/// Swap the proof commitments to a new set in the proof for KZG
pub fn swap_proof_commitments_polycommit(
snark: &Snark<Fr, G1Affine>,
commitments: &[G1Affine],
) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> {
let proof = match snark.commitment {
Some(Commitments::KZG) => match snark.transcript_type {
TranscriptType::EVM => swap_proof_commitments::<
KZGCommitmentScheme<Bn256>,
_,
EvmTranscript<G1Affine, _, _, _>,
>(snark, commitments)?,
TranscriptType::Poseidon => swap_proof_commitments::<
KZGCommitmentScheme<Bn256>,
_,
PoseidonTranscript<NativeLoader, _>,
>(snark, commitments)?,
},
Some(Commitments::IPA) => match snark.transcript_type {
TranscriptType::EVM => swap_proof_commitments::<
IPACommitmentScheme<G1Affine>,
_,
EvmTranscript<G1Affine, _, _, _>,
>(snark, commitments)?,
TranscriptType::Poseidon => swap_proof_commitments::<
IPACommitmentScheme<G1Affine>,
_,
PoseidonTranscript<NativeLoader, _>,
>(snark, commitments)?,
},
None => {
return Err("commitment scheme not found".into());
}
};
Ok(proof)
}
/// A wrapper around halo2's verify_proof
pub fn verify_proof_circuit<
'params,
V: Verifier<'params, Scheme>,
Scheme: CommitmentScheme,
Strategy: VerificationStrategy<'params, Scheme, V>,
E: EncodedChallenge<Scheme::Curve>,
TR: TranscriptReadBuffer<Cursor<Vec<u8>>, Scheme::Curve, E>,
>(
snark: &Snark<Scheme::Scalar, Scheme::Curve>,
params: &'params Scheme::ParamsVerifier,
vk: &VerifyingKey<Scheme::Curve>,
strategy: Strategy,
orig_n: u64,
) -> Result<Strategy::Output, halo2_proofs::plonk::Error>
where
Scheme::Scalar: SerdeObject
+ PrimeField
+ FromUniformBytes<64>
+ WithSmallOrderMulGroup<3>
+ Serialize
+ DeserializeOwned,
Scheme::Curve: Serialize + DeserializeOwned,
{
let pi_inner = snark
.instances
.iter()
.map(|e| e.deref())
.collect::<Vec<&[Scheme::Scalar]>>();
let instances: &[&[&[Scheme::Scalar]]] = &[&pi_inner];
trace!("instances {:?}", instances);
let mut transcript = TranscriptReadBuffer::init(Cursor::new(snark.proof.clone()));
verify_proof::<Scheme, V, _, TR, _>(params, vk, strategy, instances, &mut transcript, orig_n)
}
/// Loads a [VerifyingKey] at `path`.
pub fn load_vk<Scheme: CommitmentScheme, C: Circuit<Scheme::Scalar>>(
path: PathBuf,
params: <C as Circuit<Scheme::Scalar>>::Params,
) -> Result<VerifyingKey<Scheme::Curve>, Box<dyn Error>>
where
C: Circuit<Scheme::Scalar>,
Scheme::Curve: SerdeObject + CurveAffine,
Scheme::Scalar: PrimeField + SerdeObject + FromUniformBytes<64>,
{
info!("loading verification key from {:?}", path);
let f =
File::open(path.clone()).map_err(|_| format!("failed to load vk at {}", path.display()))?;
let mut reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, f);
let vk = VerifyingKey::<Scheme::Curve>::read::<_, C>(
&mut reader,
serde_format_from_str(&EZKL_KEY_FORMAT),
params,
)?;
info!("done loading verification key ✅");
Ok(vk)
}
/// Loads a [ProvingKey] at `path`.
pub fn load_pk<Scheme: CommitmentScheme, C: Circuit<Scheme::Scalar>>(
path: PathBuf,
params: <C as Circuit<Scheme::Scalar>>::Params,
) -> Result<ProvingKey<Scheme::Curve>, Box<dyn Error>>
where
C: Circuit<Scheme::Scalar>,
Scheme::Curve: SerdeObject + CurveAffine,
Scheme::Scalar: PrimeField + SerdeObject + FromUniformBytes<64>,
{
info!("loading proving key from {:?}", path);
let f =
File::open(path.clone()).map_err(|_| format!("failed to load pk at {}", path.display()))?;
let mut reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, f);
let pk = ProvingKey::<Scheme::Curve>::read::<_, C>(
&mut reader,
serde_format_from_str(&EZKL_KEY_FORMAT),
params,
)?;
info!("done loading proving key ✅");
Ok(pk)
}
/// Saves a [ProvingKey] to `path`.
pub fn save_pk<C: SerdeObject + CurveAffine>(
path: &PathBuf,
pk: &ProvingKey<C>,
) -> Result<(), io::Error>
where
C::ScalarExt: FromUniformBytes<64> + SerdeObject,
{
info!("saving proving key 💾");
let f = File::create(path)?;
let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);
pk.write(&mut writer, serde_format_from_str(&EZKL_KEY_FORMAT))?;
writer.flush()?;
info!("done saving proving key ✅");
Ok(())
}
/// Saves a [VerifyingKey] to `path`.
pub fn save_vk<C: CurveAffine + SerdeObject>(
path: &PathBuf,
vk: &VerifyingKey<C>,
) -> Result<(), io::Error>
where
C::ScalarExt: FromUniformBytes<64> + SerdeObject,
{
info!("saving verification key 💾");
let f = File::create(path)?;
let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);
vk.write(&mut writer, serde_format_from_str(&EZKL_KEY_FORMAT))?;
writer.flush()?;
info!("done saving verification key ✅");
Ok(())
}
/// Saves [CommitmentScheme] parameters to `path`.
pub fn save_params<Scheme: CommitmentScheme>(
path: &PathBuf,
params: &'_ Scheme::ParamsVerifier,
) -> Result<(), io::Error> {
info!("saving parameters 💾");
let f = File::create(path)?;
let mut writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f);
params.write(&mut writer)?;
writer.flush()?;
Ok(())
}
////////////////////////
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;
use halo2curves::bn256::{Bn256, Fr, G1Affine};
use tempfile::Builder;
#[tokio::test]
async fn test_can_load_saved_srs() {
let tmp_dir = Builder::new().prefix("example").tempdir().unwrap();
let fname = tmp_dir.path().join("polycommit.params");
let srs = srs::gen_srs::<KZGCommitmentScheme<Bn256>>(1);
let res = save_params::<KZGCommitmentScheme<Bn256>>(&fname, &srs);
assert!(res.is_ok());
let res = srs::load_srs_prover::<KZGCommitmentScheme<Bn256>>(fname);
assert!(res.is_ok())
}
#[test]
fn test_snark_serialization_roundtrip() {
let snark = Snark::<Fr, G1Affine> {
proof: vec![1, 2, 3, 4, 5, 6, 7, 8],
instances: vec![vec![Fr::from(1)], vec![Fr::from(2)]],
transcript_type: TranscriptType::EVM,
protocol: None,
hex_proof: None,
split: None,
pretty_public_inputs: None,
timestamp: None,
commitment: None,
};
snark
.save(&"test_snark_serialization_roundtrip.json".into())
.unwrap();
let snark2 = Snark::<Fr, G1Affine>::load::<KZGCommitmentScheme<Bn256>>(
&"test_snark_serialization_roundtrip.json".into(),
)
.unwrap();
assert_eq!(snark.instances, snark2.instances);
assert_eq!(snark.proof, snark2.proof);
assert_eq!(snark.transcript_type, snark2.transcript_type);
}
}
| https://github.com/zkonduit/ezkl |
src/pfsys/srs.rs | use halo2_proofs::poly::commitment::CommitmentScheme;
use halo2_proofs::poly::commitment::Params;
use halo2_proofs::poly::commitment::ParamsProver;
use log::info;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
/// for now we use the urls of the powers of tau ceremony from <https://github.com/han0110/halo2-kzg-srs>
pub const PUBLIC_SRS_URL: &str =
"https://trusted-setup-halo2kzg.s3.eu-central-1.amazonaws.com/perpetual-powers-of-tau-raw-";
/// Helper function for generating SRS. Only use for testing
pub fn gen_srs<Scheme: CommitmentScheme>(k: u32) -> Scheme::ParamsProver {
Scheme::ParamsProver::new(k)
}
/// Loads the [CommitmentScheme::ParamsVerifier] at `path`.
pub fn load_srs_verifier<Scheme: CommitmentScheme>(
path: PathBuf,
) -> Result<Scheme::ParamsVerifier, Box<dyn Error>> {
info!("loading srs from {:?}", path);
let f = File::open(path.clone())
.map_err(|_| format!("failed to load srs at {}", path.display()))?;
let mut reader = BufReader::new(f);
Params::<'_, Scheme::Curve>::read(&mut reader).map_err(Box::<dyn Error>::from)
}
/// Loads the [CommitmentScheme::ParamsVerifier] at `path`.
pub fn load_srs_prover<Scheme: CommitmentScheme>(
path: PathBuf,
) -> Result<Scheme::ParamsProver, Box<dyn Error>> {
info!("loading srs from {:?}", path);
let f = File::open(path.clone())
.map_err(|_| format!("failed to load srs at {}", path.display()))?;
let mut reader = BufReader::new(f);
Params::<'_, Scheme::Curve>::read(&mut reader).map_err(Box::<dyn Error>::from)
}
| https://github.com/zkonduit/ezkl |
src/python.rs | use crate::circuit::modules::polycommit::PolyCommitChip;
use crate::circuit::modules::poseidon::{
spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH},
PoseidonChip,
};
use crate::circuit::modules::Module;
use crate::circuit::{CheckMode, Tolerance};
use crate::commands::*;
use crate::fieldutils::{felt_to_i128, i128_to_felt};
use crate::graph::modules::POSEIDON_LEN_GRAPH;
use crate::graph::TestDataSource;
use crate::graph::{
quantize_float, scale_to_multiplier, GraphCircuit, GraphSettings, Model, Visibility,
};
use crate::pfsys::evm::aggregation_kzg::AggregationCircuit;
use crate::pfsys::{
load_pk, load_vk, save_params, save_vk, srs::gen_srs as ezkl_gen_srs, srs::load_srs_prover,
ProofType, TranscriptType,
};
use crate::Commitments;
use crate::RunArgs;
use halo2_proofs::poly::ipa::commitment::IPACommitmentScheme;
use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;
use halo2curves::bn256::{Bn256, Fq, Fr, G1Affine, G1};
use pyo3::exceptions::{PyIOError, PyRuntimeError};
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use pyo3_log;
use snark_verifier::util::arithmetic::PrimeField;
use std::str::FromStr;
use std::{fs::File, path::PathBuf};
use tokio::runtime::Runtime;
type PyFelt = String;
/// pyclass representing an enum
#[pyclass]
#[derive(Debug, Clone)]
enum PyTestDataSource {
/// The data is loaded from a file
File,
/// The data is loaded from the chain
OnChain,
}
impl From<PyTestDataSource> for TestDataSource {
fn from(py_test_data_source: PyTestDataSource) -> Self {
match py_test_data_source {
PyTestDataSource::File => TestDataSource::File,
PyTestDataSource::OnChain => TestDataSource::OnChain,
}
}
}
/// pyclass containing the struct used for G1, this is mostly a helper class
#[pyclass]
#[derive(Debug, Clone)]
struct PyG1 {
#[pyo3(get, set)]
/// Field Element representing x
x: PyFelt,
#[pyo3(get, set)]
/// Field Element representing y
y: PyFelt,
/// Field Element representing y
#[pyo3(get, set)]
z: PyFelt,
}
impl From<G1> for PyG1 {
fn from(g1: G1) -> Self {
PyG1 {
x: crate::pfsys::field_to_string::<Fq>(&g1.x),
y: crate::pfsys::field_to_string::<Fq>(&g1.y),
z: crate::pfsys::field_to_string::<Fq>(&g1.z),
}
}
}
impl From<PyG1> for G1 {
fn from(val: PyG1) -> Self {
G1 {
x: crate::pfsys::string_to_field::<Fq>(&val.x),
y: crate::pfsys::string_to_field::<Fq>(&val.y),
z: crate::pfsys::string_to_field::<Fq>(&val.z),
}
}
}
impl pyo3::ToPyObject for PyG1 {
fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject {
let g1_dict = pyo3::types::PyDict::new(py);
g1_dict.set_item("x", self.x.to_object(py)).unwrap();
g1_dict.set_item("y", self.y.to_object(py)).unwrap();
g1_dict.set_item("z", self.z.to_object(py)).unwrap();
g1_dict.into()
}
}
/// pyclass containing the struct used for G1
#[pyclass]
#[derive(Debug, Clone)]
pub struct PyG1Affine {
#[pyo3(get, set)]
///
pub x: PyFelt,
#[pyo3(get, set)]
///
pub y: PyFelt,
}
impl From<G1Affine> for PyG1Affine {
fn from(g1: G1Affine) -> Self {
PyG1Affine {
x: crate::pfsys::field_to_string::<Fq>(&g1.x),
y: crate::pfsys::field_to_string::<Fq>(&g1.y),
}
}
}
impl From<PyG1Affine> for G1Affine {
fn from(val: PyG1Affine) -> Self {
G1Affine {
x: crate::pfsys::string_to_field::<Fq>(&val.x),
y: crate::pfsys::string_to_field::<Fq>(&val.y),
}
}
}
impl pyo3::ToPyObject for PyG1Affine {
fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject {
let g1_dict = pyo3::types::PyDict::new(py);
g1_dict.set_item("x", self.x.to_object(py)).unwrap();
g1_dict.set_item("y", self.y.to_object(py)).unwrap();
g1_dict.into()
}
}
/// Python class containing the struct used for run_args
///
/// Returns
/// -------
/// PyRunArgs
///
#[pyclass]
#[derive(Clone)]
struct PyRunArgs {
#[pyo3(get, set)]
/// float: The tolerance for error on model outputs
pub tolerance: f32,
#[pyo3(get, set)]
/// int: The denominator in the fixed point representation used when quantizing inputs
pub input_scale: crate::Scale,
#[pyo3(get, set)]
/// int: The denominator in the fixed point representation used when quantizing parameters
pub param_scale: crate::Scale,
#[pyo3(get, set)]
/// int: If the scale is ever > scale_rebase_multiplier * input_scale then the scale is rebased to input_scale (this a more advanced parameter, use with caution)
pub scale_rebase_multiplier: u32,
#[pyo3(get, set)]
/// list[int]: The min and max elements in the lookup table input column
pub lookup_range: crate::circuit::table::Range,
#[pyo3(get, set)]
/// int: The log_2 number of rows
pub logrows: u32,
#[pyo3(get, set)]
/// int: The number of inner columns used for the lookup table
pub num_inner_cols: usize,
#[pyo3(get, set)]
/// string: accepts `public`, `private`, `fixed`, `hashed/public`, `hashed/private`, `polycommit`
pub input_visibility: Visibility,
#[pyo3(get, set)]
/// string: accepts `public`, `private`, `fixed`, `hashed/public`, `hashed/private`, `polycommit`
pub output_visibility: Visibility,
#[pyo3(get, set)]
/// string: accepts `public`, `private`, `fixed`, `hashed/public`, `hashed/private`, `polycommit`
pub param_visibility: Visibility,
#[pyo3(get, set)]
/// list[tuple[str, int]]: Hand-written parser for graph variables, eg. batch_size=1
pub variables: Vec<(String, usize)>,
#[pyo3(get, set)]
/// bool: Rebase the scale using lookup table for division instead of using a range check
pub div_rebasing: bool,
#[pyo3(get, set)]
/// bool: Should constants with 0.0 fraction be rebased to scale 0
pub rebase_frac_zero_constants: bool,
#[pyo3(get, set)]
/// str: check mode, accepts `safe`, `unsafe`
pub check_mode: CheckMode,
#[pyo3(get, set)]
/// str: commitment type, accepts `kzg`, `ipa`
pub commitment: PyCommitments,
}
/// default instantiation of PyRunArgs
#[pymethods]
impl PyRunArgs {
#[new]
fn new() -> Self {
RunArgs::default().into()
}
}
/// Conversion between PyRunArgs and RunArgs
impl From<PyRunArgs> for RunArgs {
fn from(py_run_args: PyRunArgs) -> Self {
RunArgs {
tolerance: Tolerance::from(py_run_args.tolerance),
input_scale: py_run_args.input_scale,
param_scale: py_run_args.param_scale,
num_inner_cols: py_run_args.num_inner_cols,
scale_rebase_multiplier: py_run_args.scale_rebase_multiplier,
lookup_range: py_run_args.lookup_range,
logrows: py_run_args.logrows,
input_visibility: py_run_args.input_visibility,
output_visibility: py_run_args.output_visibility,
param_visibility: py_run_args.param_visibility,
variables: py_run_args.variables,
div_rebasing: py_run_args.div_rebasing,
rebase_frac_zero_constants: py_run_args.rebase_frac_zero_constants,
check_mode: py_run_args.check_mode,
commitment: Some(py_run_args.commitment.into()),
}
}
}
impl Into<PyRunArgs> for RunArgs {
fn into(self) -> PyRunArgs {
PyRunArgs {
tolerance: self.tolerance.val,
input_scale: self.input_scale,
param_scale: self.param_scale,
num_inner_cols: self.num_inner_cols,
scale_rebase_multiplier: self.scale_rebase_multiplier,
lookup_range: self.lookup_range,
logrows: self.logrows,
input_visibility: self.input_visibility,
output_visibility: self.output_visibility,
param_visibility: self.param_visibility,
variables: self.variables,
div_rebasing: self.div_rebasing,
rebase_frac_zero_constants: self.rebase_frac_zero_constants,
check_mode: self.check_mode,
commitment: self.commitment.into(),
}
}
}
#[pyclass]
#[derive(Debug, Clone)]
/// pyclass representing an enum, denoting the type of commitment
pub enum PyCommitments {
/// KZG commitment
KZG,
/// IPA commitment
IPA,
}
impl From<Option<Commitments>> for PyCommitments {
fn from(commitment: Option<Commitments>) -> Self {
match commitment {
Some(Commitments::KZG) => PyCommitments::KZG,
Some(Commitments::IPA) => PyCommitments::IPA,
None => PyCommitments::KZG,
}
}
}
impl From<PyCommitments> for Commitments {
fn from(py_commitments: PyCommitments) -> Self {
match py_commitments {
PyCommitments::KZG => Commitments::KZG,
PyCommitments::IPA => Commitments::IPA,
}
}
}
impl Into<PyCommitments> for Commitments {
fn into(self) -> PyCommitments {
match self {
Commitments::KZG => PyCommitments::KZG,
Commitments::IPA => PyCommitments::IPA,
}
}
}
impl FromStr for PyCommitments {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"kzg" => Ok(PyCommitments::KZG),
"ipa" => Ok(PyCommitments::IPA),
_ => Err("Invalid value for Commitments".to_string()),
}
}
}
/// Converts a field element hex string to big endian
///
/// Arguments
/// -------
/// felt: str
/// The field element represented as a string
///
///
/// Returns
/// -------
/// str
/// field element represented as a string
///
#[pyfunction(signature = (
felt,
))]
fn felt_to_big_endian(felt: PyFelt) -> PyResult<String> {
let felt = crate::pfsys::string_to_field::<Fr>(&felt);
Ok(format!("{:?}", felt))
}
/// Converts a field element hex string to an integer
///
/// Arguments
/// -------
/// felt: str
/// The field element represented as a string
///
/// Returns
/// -------
/// int
///
#[pyfunction(signature = (
felt,
))]
fn felt_to_int(felt: PyFelt) -> PyResult<i128> {
let felt = crate::pfsys::string_to_field::<Fr>(&felt);
let int_rep = felt_to_i128(felt);
Ok(int_rep)
}
/// Converts a field element hex string to a floating point number
///
/// Arguments
/// -------
/// felt: str
/// The field element represented as a string
///
/// scale: float
/// The scaling factor used to convert the field element into a floating point representation
///
/// Returns
/// -------
/// float
///
#[pyfunction(signature = (
felt,
scale
))]
fn felt_to_float(felt: PyFelt, scale: crate::Scale) -> PyResult<f64> {
let felt = crate::pfsys::string_to_field::<Fr>(&felt);
let int_rep = felt_to_i128(felt);
let multiplier = scale_to_multiplier(scale);
let float_rep = int_rep as f64 / multiplier;
Ok(float_rep)
}
/// Converts a floating point element to a field element hex string
///
/// Arguments
/// -------
/// input: float
/// The field element represented as a string
///
/// scale: float
/// The scaling factor used to quantize the float into a field element
///
/// Returns
/// -------
/// str
/// The field element represented as a string
///
#[pyfunction(signature = (
input,
scale
))]
fn float_to_felt(input: f64, scale: crate::Scale) -> PyResult<PyFelt> {
let int_rep = quantize_float(&input, 0.0, scale)
.map_err(|_| PyIOError::new_err("Failed to quantize input"))?;
let felt = i128_to_felt(int_rep);
Ok(crate::pfsys::field_to_string::<Fr>(&felt))
}
/// Converts a buffer to vector of field elements
///
/// Arguments
/// -------
/// buffer: list[int]
/// List of integers representing a buffer
///
/// Returns
/// -------
/// list[str]
/// List of field elements represented as strings
///
#[pyfunction(signature = (
buffer
))]
fn buffer_to_felts(buffer: Vec<u8>) -> PyResult<Vec<String>> {
fn u8_array_to_u128_le(arr: [u8; 16]) -> u128 {
let mut n: u128 = 0;
for &b in arr.iter().rev() {
n <<= 8;
n |= b as u128;
}
n
}
let buffer = &buffer[..];
// Divide the buffer into chunks of 64 bytes
let chunks = buffer.chunks_exact(16);
// Get the remainder
let remainder = chunks.remainder();
// Add 0s to the remainder to make it 64 bytes
let mut remainder = remainder.to_vec();
// Collect chunks into a Vec<[u8; 16]>.
let chunks: Result<Vec<[u8; 16]>, PyErr> = chunks
.map(|slice| {
let array: [u8; 16] = slice
.try_into()
.map_err(|_| PyIOError::new_err("Failed to slice input buffer"))?;
Ok(array)
})
.collect();
let mut chunks = chunks?;
if !remainder.is_empty() {
remainder.resize(16, 0);
// Convert the Vec<u8> to [u8; 16]
let remainder_array: [u8; 16] = remainder
.try_into()
.map_err(|_| PyIOError::new_err("Failed to slice remainder"))?;
// append the remainder to the chunks
chunks.push(remainder_array);
}
// Convert each chunk to a field element
let field_elements: Vec<Fr> = chunks
.iter()
.map(|x| PrimeField::from_u128(u8_array_to_u128_le(*x)))
.collect();
let field_elements: Vec<String> = field_elements
.iter()
.map(|x| crate::pfsys::field_to_string::<Fr>(x))
.collect();
Ok(field_elements)
}
/// Generate a poseidon hash.
///
/// Arguments
/// -------
/// message: list[str]
/// List of field elements represnted as strings
///
/// Returns
/// -------
/// list[str]
/// List of field elements represented as strings
///
#[pyfunction(signature = (
message,
))]
fn poseidon_hash(message: Vec<PyFelt>) -> PyResult<Vec<PyFelt>> {
let message: Vec<Fr> = message
.iter()
.map(crate::pfsys::string_to_field::<Fr>)
.collect::<Vec<_>>();
let output =
PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>::run(
message.clone(),
)
.map_err(|_| PyIOError::new_err("Failed to run poseidon"))?;
let hash = output[0]
.iter()
.map(crate::pfsys::field_to_string::<Fr>)
.collect::<Vec<_>>();
Ok(hash)
}
/// Generate a kzg commitment.
///
/// Arguments
/// -------
/// message: list[str]
/// List of field elements represnted as strings
///
/// vk_path: str
/// Path to the verification key
///
/// settings_path: str
/// Path to the settings file
///
/// srs_path: str
/// Path to the Structure Reference String (SRS) file
///
/// Returns
/// -------
/// list[PyG1Affine]
///
#[pyfunction(signature = (
message,
vk_path=PathBuf::from(DEFAULT_VK),
settings_path=PathBuf::from(DEFAULT_SETTINGS),
srs_path=None
))]
fn kzg_commit(
message: Vec<PyFelt>,
vk_path: PathBuf,
settings_path: PathBuf,
srs_path: Option<PathBuf>,
) -> PyResult<Vec<PyG1Affine>> {
let message: Vec<Fr> = message
.iter()
.map(crate::pfsys::string_to_field::<Fr>)
.collect::<Vec<_>>();
let settings = GraphSettings::load(&settings_path)
.map_err(|_| PyIOError::new_err("Failed to load circuit settings"))?;
let srs_path =
crate::execute::get_srs_path(settings.run_args.logrows, srs_path, Commitments::KZG);
let srs = load_srs_prover::<KZGCommitmentScheme<Bn256>>(srs_path)
.map_err(|_| PyIOError::new_err("Failed to load srs"))?;
let vk = load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(vk_path, settings)
.map_err(|_| PyIOError::new_err("Failed to load vk"))?;
let output = PolyCommitChip::commit::<KZGCommitmentScheme<Bn256>>(
message,
(vk.cs().blinding_factors() + 1) as u32,
&srs,
);
Ok(output.iter().map(|x| (*x).into()).collect::<Vec<_>>())
}
/// Generate an ipa commitment.
///
/// Arguments
/// -------
/// message: list[str]
/// List of field elements represnted as strings
///
/// vk_path: str
/// Path to the verification key
///
/// settings_path: str
/// Path to the settings file
///
/// srs_path: str
/// Path to the Structure Reference String (SRS) file
///
/// Returns
/// -------
/// list[PyG1Affine]
///
#[pyfunction(signature = (
message,
vk_path=PathBuf::from(DEFAULT_VK),
settings_path=PathBuf::from(DEFAULT_SETTINGS),
srs_path=None
))]
fn ipa_commit(
message: Vec<PyFelt>,
vk_path: PathBuf,
settings_path: PathBuf,
srs_path: Option<PathBuf>,
) -> PyResult<Vec<PyG1Affine>> {
let message: Vec<Fr> = message
.iter()
.map(crate::pfsys::string_to_field::<Fr>)
.collect::<Vec<_>>();
let settings = GraphSettings::load(&settings_path)
.map_err(|_| PyIOError::new_err("Failed to load circuit settings"))?;
let srs_path =
crate::execute::get_srs_path(settings.run_args.logrows, srs_path, Commitments::KZG);
let srs = load_srs_prover::<IPACommitmentScheme<G1Affine>>(srs_path)
.map_err(|_| PyIOError::new_err("Failed to load srs"))?;
let vk = load_vk::<IPACommitmentScheme<G1Affine>, GraphCircuit>(vk_path, settings)
.map_err(|_| PyIOError::new_err("Failed to load vk"))?;
let output = PolyCommitChip::commit::<IPACommitmentScheme<G1Affine>>(
message,
(vk.cs().blinding_factors() + 1) as u32,
&srs,
);
Ok(output.iter().map(|x| (*x).into()).collect::<Vec<_>>())
}
/// Swap the commitments in a proof
///
/// Arguments
/// -------
/// proof_path: str
/// Path to the proof file
///
/// witness_path: str
/// Path to the witness file
///
#[pyfunction(signature = (
proof_path=PathBuf::from(DEFAULT_PROOF),
witness_path=PathBuf::from(DEFAULT_WITNESS),
))]
fn swap_proof_commitments(proof_path: PathBuf, witness_path: PathBuf) -> PyResult<()> {
crate::execute::swap_proof_commitments_cmd(proof_path, witness_path)
.map_err(|_| PyIOError::new_err("Failed to swap commitments"))?;
Ok(())
}
/// Generates a vk from a pk for a model circuit and saves it to a file
///
/// Arguments
/// -------
/// path_to_pk: str
/// Path to the proving key
///
/// circuit_settings_path: str
/// Path to the witness file
///
/// vk_output_path: str
/// Path to create the vk file
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
path_to_pk=PathBuf::from(DEFAULT_PK),
circuit_settings_path=PathBuf::from(DEFAULT_SETTINGS),
vk_output_path=PathBuf::from(DEFAULT_VK),
))]
fn gen_vk_from_pk_single(
path_to_pk: PathBuf,
circuit_settings_path: PathBuf,
vk_output_path: PathBuf,
) -> PyResult<bool> {
let settings = GraphSettings::load(&circuit_settings_path)
.map_err(|_| PyIOError::new_err("Failed to load circuit settings"))?;
let pk = load_pk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(path_to_pk, settings)
.map_err(|_| PyIOError::new_err("Failed to load pk"))?;
let vk = pk.get_vk();
// now save
save_vk::<G1Affine>(&vk_output_path, vk)
.map_err(|_| PyIOError::new_err("Failed to save vk"))?;
Ok(true)
}
/// Generates a vk from a pk for an aggregate circuit and saves it to a file
///
/// Arguments
/// -------
/// path_to_pk: str
/// Path to the proving key
///
/// vk_output_path: str
/// Path to create the vk file
///
/// Returns
/// -------
/// bool
#[pyfunction(signature = (
path_to_pk=PathBuf::from(DEFAULT_PK_AGGREGATED),
vk_output_path=PathBuf::from(DEFAULT_VK_AGGREGATED),
))]
fn gen_vk_from_pk_aggr(path_to_pk: PathBuf, vk_output_path: PathBuf) -> PyResult<bool> {
let pk = load_pk::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(path_to_pk, ())
.map_err(|_| PyIOError::new_err("Failed to load pk"))?;
let vk = pk.get_vk();
// now save
save_vk::<G1Affine>(&vk_output_path, vk)
.map_err(|_| PyIOError::new_err("Failed to save vk"))?;
Ok(true)
}
/// Displays the table as a string in python
///
/// Arguments
/// ---------
/// model: str
/// Path to the onnx file
///
/// Returns
/// ---------
/// str
/// Table of the nodes in the onnx file
///
#[pyfunction(signature = (
model = PathBuf::from(DEFAULT_MODEL),
py_run_args = None
))]
fn table(model: PathBuf, py_run_args: Option<PyRunArgs>) -> PyResult<String> {
let run_args: RunArgs = py_run_args.unwrap_or_else(PyRunArgs::new).into();
let mut reader = File::open(model).map_err(|_| PyIOError::new_err("Failed to open model"))?;
let result = Model::new(&mut reader, &run_args);
match result {
Ok(m) => Ok(m.table_nodes()),
Err(_) => Err(PyIOError::new_err("Failed to import model")),
}
}
/// Generates the Structured Reference String (SRS), use this only for testing purposes
///
/// Arguments
/// ---------
/// srs_path: str
/// Path to the create the SRS file
///
/// logrows: int
/// The number of logrows for the SRS file
///
#[pyfunction(signature = (
srs_path,
logrows,
))]
fn gen_srs(srs_path: PathBuf, logrows: usize) -> PyResult<()> {
let params = ezkl_gen_srs::<KZGCommitmentScheme<Bn256>>(logrows as u32);
save_params::<KZGCommitmentScheme<Bn256>>(&srs_path, ¶ms)?;
Ok(())
}
/// Gets a public srs
///
/// Arguments
/// ---------
/// settings_path: str
/// Path to the settings file
///
/// logrows: int
/// The number of logrows for the SRS file
///
/// srs_path: str
/// Path to the create the SRS file
///
/// commitment: str
/// Specify the commitment used ("kzg", "ipa")
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
settings_path=PathBuf::from(DEFAULT_SETTINGS),
logrows=None,
srs_path=None,
commitment=None,
))]
fn get_srs(
settings_path: Option<PathBuf>,
logrows: Option<u32>,
srs_path: Option<PathBuf>,
commitment: Option<PyCommitments>,
) -> PyResult<bool> {
let commitment: Option<Commitments> = match commitment {
Some(c) => Some(c.into()),
None => None,
};
Runtime::new()
.unwrap()
.block_on(crate::execute::get_srs_cmd(
srs_path,
settings_path,
logrows,
commitment,
))
.map_err(|e| {
let err_str = format!("Failed to get srs: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Generates the circuit settings
///
/// Arguments
/// ---------
/// model: str
/// Path to the onnx file
///
/// output: str
/// Path to create the settings file
///
/// py_run_args: PyRunArgs
/// PyRunArgs object to initialize the settings
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
model=PathBuf::from(DEFAULT_MODEL),
output=PathBuf::from(DEFAULT_SETTINGS),
py_run_args = None,
))]
fn gen_settings(
model: PathBuf,
output: PathBuf,
py_run_args: Option<PyRunArgs>,
) -> Result<bool, PyErr> {
let run_args: RunArgs = py_run_args.unwrap_or_else(PyRunArgs::new).into();
crate::execute::gen_circuit_settings(model, output, run_args).map_err(|e| {
let err_str = format!("Failed to generate settings: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Calibrates the circuit settings
///
/// Arguments
/// ---------
/// data: str
/// Path to the calibration data
///
/// model: str
/// Path to the onnx file
///
/// settings: str
/// Path to the settings file
///
/// lookup_safety_margin: int
/// the lookup safety margin to use for calibration. if the max lookup is 2^k, then the max lookup will be 2^k * lookup_safety_margin. larger = safer but slower
///
/// scales: list[int]
/// Optional scales to specifically try for calibration
///
/// scale_rebase_multiplier: list[int]
/// Optional scale rebase multipliers to specifically try for calibration. This is the multiplier at which we divide to return to the input scale.
///
/// max_logrows: int
/// Optional max logrows to use for calibration
///
/// only_range_check_rebase: bool
/// Check ranges when rebasing
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
data = PathBuf::from(DEFAULT_CALIBRATION_FILE),
model = PathBuf::from(DEFAULT_MODEL),
settings = PathBuf::from(DEFAULT_SETTINGS),
target = CalibrationTarget::default(), // default is "resources
lookup_safety_margin = DEFAULT_LOOKUP_SAFETY_MARGIN.parse().unwrap(),
scales = None,
scale_rebase_multiplier = DEFAULT_SCALE_REBASE_MULTIPLIERS.split(",").map(|x| x.parse().unwrap()).collect(),
max_logrows = None,
only_range_check_rebase = DEFAULT_ONLY_RANGE_CHECK_REBASE.parse().unwrap(),
))]
fn calibrate_settings(
data: PathBuf,
model: PathBuf,
settings: PathBuf,
target: CalibrationTarget,
lookup_safety_margin: i128,
scales: Option<Vec<crate::Scale>>,
scale_rebase_multiplier: Vec<u32>,
max_logrows: Option<u32>,
only_range_check_rebase: bool,
) -> Result<bool, PyErr> {
crate::execute::calibrate(
model,
data,
settings,
target,
lookup_safety_margin,
scales,
scale_rebase_multiplier,
only_range_check_rebase,
max_logrows,
)
.map_err(|e| {
let err_str = format!("Failed to calibrate settings: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Runs the forward pass operation to generate a witness
///
/// Arguments
/// ---------
/// data: str
/// Path to the data file
///
/// model: str
/// Path to the compiled model file
///
/// output: str
/// Path to create the witness file
///
/// vk_path: str
/// Path to the verification key
///
/// srs_path: str
/// Path to the SRS file
///
/// Returns
/// -------
/// dict
/// Python object containing the witness values
///
#[pyfunction(signature = (
data=PathBuf::from(DEFAULT_DATA),
model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),
output=PathBuf::from(DEFAULT_WITNESS),
vk_path=None,
srs_path=None,
))]
fn gen_witness(
data: PathBuf,
model: PathBuf,
output: Option<PathBuf>,
vk_path: Option<PathBuf>,
srs_path: Option<PathBuf>,
) -> PyResult<PyObject> {
let output =
crate::execute::gen_witness(model, data, output, vk_path, srs_path).map_err(|e| {
let err_str = format!("Failed to run generate witness: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Python::with_gil(|py| Ok(output.to_object(py)))
}
/// Mocks the prover
///
/// Arguments
/// ---------
/// witness: str
/// Path to the witness file
///
/// model: str
/// Path to the compiled model file
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
witness=PathBuf::from(DEFAULT_WITNESS),
model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),
))]
fn mock(witness: PathBuf, model: PathBuf) -> PyResult<bool> {
crate::execute::mock(model, witness).map_err(|e| {
let err_str = format!("Failed to run mock: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Mocks the aggregate prover
///
/// Arguments
/// ---------
/// aggregation_snarks: list[str]
/// List of paths to the relevant proof files
///
/// logrows: int
/// Number of logrows to use for the aggregation circuit
///
/// split_proofs: bool
/// Indicates whether the accumulated are segments of a larger proof
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
aggregation_snarks=vec![PathBuf::from(DEFAULT_PROOF)],
logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),
split_proofs = false,
))]
fn mock_aggregate(
aggregation_snarks: Vec<PathBuf>,
logrows: u32,
split_proofs: bool,
) -> PyResult<bool> {
crate::execute::mock_aggregate(aggregation_snarks, logrows, split_proofs).map_err(|e| {
let err_str = format!("Failed to run mock: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Runs the setup process
///
/// Arguments
/// ---------
/// model: str
/// Path to the compiled model file
///
/// vk_path: str
/// Path to create the verification key file
///
/// pk_path: str
/// Path to create the proving key file
///
/// srs_path: str
/// Path to the SRS file
///
/// witness_path: str
/// Path to the witness file
///
/// disable_selector_compression: bool
/// Whether to compress the selectors or not
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),
vk_path=PathBuf::from(DEFAULT_VK),
pk_path=PathBuf::from(DEFAULT_PK),
srs_path=None,
witness_path = None,
disable_selector_compression=DEFAULT_DISABLE_SELECTOR_COMPRESSION.parse().unwrap(),
))]
fn setup(
model: PathBuf,
vk_path: PathBuf,
pk_path: PathBuf,
srs_path: Option<PathBuf>,
witness_path: Option<PathBuf>,
disable_selector_compression: bool,
) -> Result<bool, PyErr> {
crate::execute::setup(
model,
srs_path,
vk_path,
pk_path,
witness_path,
disable_selector_compression,
)
.map_err(|e| {
let err_str = format!("Failed to run setup: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Runs the prover on a set of inputs
///
/// Arguments
/// ---------
/// witness: str
/// Path to the witness file
///
/// model: str
/// Path to the compiled model file
///
/// pk_path: str
/// Path to the proving key file
///
/// proof_path: str
/// Path to create the proof file
///
/// proof_type: str
/// Accepts `single`, `for-aggr`
///
/// srs_path: str
/// Path to the SRS file
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
witness=PathBuf::from(DEFAULT_WITNESS),
model=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),
pk_path=PathBuf::from(DEFAULT_PK),
proof_path=None,
proof_type=ProofType::default(),
srs_path=None,
))]
fn prove(
witness: PathBuf,
model: PathBuf,
pk_path: PathBuf,
proof_path: Option<PathBuf>,
proof_type: ProofType,
srs_path: Option<PathBuf>,
) -> PyResult<PyObject> {
let snark = crate::execute::prove(
witness,
model,
pk_path,
proof_path,
srs_path,
proof_type,
CheckMode::UNSAFE,
)
.map_err(|e| {
let err_str = format!("Failed to run prove: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Python::with_gil(|py| Ok(snark.to_object(py)))
}
/// Verifies a given proof
///
/// Arguments
/// ---------
/// proof_path: str
/// Path to create the proof file
///
/// settings_path: str
/// Path to the settings file
///
/// vk_path: str
/// Path to the verification key file
///
/// srs_path: str
/// Path to the SRS file
///
/// non_reduced_srs: bool
/// Whether to reduce the number of SRS logrows to the number of instances rather than the number of logrows used for proofs (only works if the srs were generated in the same ceremony)
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
proof_path=PathBuf::from(DEFAULT_PROOF),
settings_path=PathBuf::from(DEFAULT_SETTINGS),
vk_path=PathBuf::from(DEFAULT_VK),
srs_path=None,
reduced_srs=DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION.parse::<bool>().unwrap(),
))]
fn verify(
proof_path: PathBuf,
settings_path: PathBuf,
vk_path: PathBuf,
srs_path: Option<PathBuf>,
reduced_srs: bool,
) -> Result<bool, PyErr> {
crate::execute::verify(proof_path, settings_path, vk_path, srs_path, reduced_srs).map_err(
|e| {
let err_str = format!("Failed to run verify: {}", e);
PyRuntimeError::new_err(err_str)
},
)?;
Ok(true)
}
/// Runs the setup process for an aggregate setup
///
/// Arguments
/// ---------
/// sample_snarks: list[str]
/// List of paths to the various proofs
///
/// vk_path: str
/// Path to create the aggregated VK
///
/// pk_path: str
/// Path to create the aggregated PK
///
/// logrows: int
/// Number of logrows to use
///
/// split_proofs: bool
/// Whether the accumulated are segments of a larger proof
///
/// srs_path: str
/// Path to the SRS file
///
/// disable_selector_compression: bool
/// Whether to compress selectors
///
/// commitment: str
/// Accepts `kzg`, `ipa`
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
sample_snarks=vec![PathBuf::from(DEFAULT_PROOF)],
vk_path=PathBuf::from(DEFAULT_VK_AGGREGATED),
pk_path=PathBuf::from(DEFAULT_PK_AGGREGATED),
logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),
split_proofs = false,
srs_path = None,
disable_selector_compression=DEFAULT_DISABLE_SELECTOR_COMPRESSION.parse().unwrap(),
commitment=DEFAULT_COMMITMENT.parse().unwrap(),
))]
fn setup_aggregate(
sample_snarks: Vec<PathBuf>,
vk_path: PathBuf,
pk_path: PathBuf,
logrows: u32,
split_proofs: bool,
srs_path: Option<PathBuf>,
disable_selector_compression: bool,
commitment: PyCommitments,
) -> Result<bool, PyErr> {
crate::execute::setup_aggregate(
sample_snarks,
vk_path,
pk_path,
srs_path,
logrows,
split_proofs,
disable_selector_compression,
commitment.into(),
)
.map_err(|e| {
let err_str = format!("Failed to setup aggregate: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Compiles the circuit for use in other steps
///
/// Arguments
/// ---------
/// model: str
/// Path to the onnx model file
///
/// compiled_circuit: str
/// Path to output the compiled circuit
///
/// settings_path: str
/// Path to the settings files
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
model=PathBuf::from(DEFAULT_MODEL),
compiled_circuit=PathBuf::from(DEFAULT_COMPILED_CIRCUIT),
settings_path=PathBuf::from(DEFAULT_SETTINGS),
))]
fn compile_circuit(
model: PathBuf,
compiled_circuit: PathBuf,
settings_path: PathBuf,
) -> Result<bool, PyErr> {
crate::execute::compile_circuit(model, compiled_circuit, settings_path).map_err(|e| {
let err_str = format!("Failed to setup aggregate: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Creates an aggregated proof
///
/// Arguments
/// ---------
/// aggregation_snarks: list[str]
/// List of paths to the various proofs
///
/// proof_path: str
/// Path to output the aggregated proof
///
/// vk_path: str
/// Path to the VK file
///
/// transcript:
/// Proof transcript type to be used. `evm` used by default. `poseidon` is also supported
///
/// logrows:
/// Logrows used for aggregation circuit
///
/// check_mode: str
/// Run sanity checks during calculations. Accepts `safe` or `unsafe`
///
/// split-proofs: bool
/// Whether the accumulated proofs are segments of a larger circuit
///
/// srs_path: str
/// Path to the SRS used
///
/// commitment: str
/// Accepts "kzg" or "ipa"
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
aggregation_snarks=vec![PathBuf::from(DEFAULT_PROOF)],
proof_path=PathBuf::from(DEFAULT_PROOF_AGGREGATED),
vk_path=PathBuf::from(DEFAULT_VK_AGGREGATED),
transcript=TranscriptType::default(),
logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),
check_mode=CheckMode::UNSAFE,
split_proofs = false,
srs_path=None,
commitment=DEFAULT_COMMITMENT.parse().unwrap(),
))]
fn aggregate(
aggregation_snarks: Vec<PathBuf>,
proof_path: PathBuf,
vk_path: PathBuf,
transcript: TranscriptType,
logrows: u32,
check_mode: CheckMode,
split_proofs: bool,
srs_path: Option<PathBuf>,
commitment: PyCommitments,
) -> Result<bool, PyErr> {
// the K used for the aggregation circuit
crate::execute::aggregate(
proof_path,
aggregation_snarks,
vk_path,
srs_path,
transcript,
logrows,
check_mode,
split_proofs,
commitment.into(),
)
.map_err(|e| {
let err_str = format!("Failed to run aggregate: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Verifies and aggregate proof
///
/// Arguments
/// ---------
/// proof_path: str
/// The path to the proof file
///
/// vk_path: str
/// The path to the verification key file
///
/// logrows: int
/// logrows used for aggregation circuit
///
/// commitment: str
/// Accepts "kzg" or "ipa"
///
/// reduced_srs: bool
/// Whether to reduce the number of SRS logrows to the number of instances rather than the number of logrows used for proofs (only works if the srs were generated in the same ceremony)
///
/// srs_path: str
/// The path to the SRS file
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
proof_path=PathBuf::from(DEFAULT_PROOF_AGGREGATED),
vk_path=PathBuf::from(DEFAULT_VK),
logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),
commitment=DEFAULT_COMMITMENT.parse().unwrap(),
reduced_srs=DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION.parse().unwrap(),
srs_path=None,
))]
fn verify_aggr(
proof_path: PathBuf,
vk_path: PathBuf,
logrows: u32,
commitment: PyCommitments,
reduced_srs: bool,
srs_path: Option<PathBuf>,
) -> Result<bool, PyErr> {
crate::execute::verify_aggr(
proof_path,
vk_path,
srs_path,
logrows,
reduced_srs,
commitment.into(),
)
.map_err(|e| {
let err_str = format!("Failed to run verify_aggr: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Creates an EVM compatible verifier, you will need solc installed in your environment to run this
///
/// Arguments
/// ---------
/// vk_path: str
/// The path to the verification key file
///
/// settings_path: str
/// The path to the settings file
///
/// sol_code_path: str
/// The path to the create the solidity verifier
///
/// abi_path: str
/// The path to create the ABI for the solidity verifier
///
/// srs_path: str
/// The path to the SRS file
///
/// render_vk_separately: bool
/// Whether the verifier key should be rendered as a separate contract. We recommend disabling selector compression if this is enabled. To save the verifier key as a separate contract, set this to true and then call the create-evm-vk command
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
vk_path=PathBuf::from(DEFAULT_VK),
settings_path=PathBuf::from(DEFAULT_SETTINGS),
sol_code_path=PathBuf::from(DEFAULT_SOL_CODE),
abi_path=PathBuf::from(DEFAULT_VERIFIER_ABI),
srs_path=None,
render_vk_seperately = DEFAULT_RENDER_VK_SEPERATELY.parse().unwrap(),
))]
fn create_evm_verifier(
vk_path: PathBuf,
settings_path: PathBuf,
sol_code_path: PathBuf,
abi_path: PathBuf,
srs_path: Option<PathBuf>,
render_vk_seperately: bool,
) -> Result<bool, PyErr> {
crate::execute::create_evm_verifier(
vk_path,
srs_path,
settings_path,
sol_code_path,
abi_path,
render_vk_seperately,
)
.map_err(|e| {
let err_str = format!("Failed to run create_evm_verifier: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Creates an EVM compatible data attestation verifier, you will need solc installed in your environment to run this
///
/// Arguments
/// ---------
/// input_data: str
/// The path to the .json data file, which should contain the necessary calldata and account addresses needed to read from all the on-chain view functions that return the data that the network ingests as inputs
///
/// settings_path: str
/// The path to the settings file
///
/// sol_code_path: str
/// The path to the create the solidity verifier
///
/// abi_path: str
/// The path to create the ABI for the solidity verifier
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
input_data=PathBuf::from(DEFAULT_DATA),
settings_path=PathBuf::from(DEFAULT_SETTINGS),
sol_code_path=PathBuf::from(DEFAULT_SOL_CODE_DA),
abi_path=PathBuf::from(DEFAULT_VERIFIER_DA_ABI),
))]
fn create_evm_data_attestation(
input_data: PathBuf,
settings_path: PathBuf,
sol_code_path: PathBuf,
abi_path: PathBuf,
) -> Result<bool, PyErr> {
crate::execute::create_evm_data_attestation(settings_path, sol_code_path, abi_path, input_data)
.map_err(|e| {
let err_str = format!("Failed to run create_evm_data_attestation: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Setup test evm witness
///
/// Arguments
/// ---------
/// data_path: str
/// The path to the .json data file, which should include both the network input (possibly private) and the network output (public input to the proof)
///
/// compiled_circuit_path: str
/// The path to the compiled model file (generated using the compile-circuit command)
///
/// test_data: str
/// For testing purposes only. The optional path to the .json data file that will be generated that contains the OnChain data storage information derived from the file information in the data .json file. Should include both the network input (possibly private) and the network output (public input to the proof)
///
/// input_sources: str
/// Where the input data comes from
///
/// output_source: str
/// Where the output data comes from
///
/// rpc_url: str
/// RPC URL for an EVM compatible node, if None, uses Anvil as a local RPC node
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
data_path,
compiled_circuit_path,
test_data,
input_source,
output_source,
rpc_url=None,
))]
fn setup_test_evm_witness(
data_path: PathBuf,
compiled_circuit_path: PathBuf,
test_data: PathBuf,
input_source: PyTestDataSource,
output_source: PyTestDataSource,
rpc_url: Option<String>,
) -> Result<bool, PyErr> {
Runtime::new()
.unwrap()
.block_on(crate::execute::setup_test_evm_witness(
data_path,
compiled_circuit_path,
test_data,
rpc_url,
input_source.into(),
output_source.into(),
))
.map_err(|e| {
let err_str = format!("Failed to run setup_test_evm_witness: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// deploys the solidity verifier
#[pyfunction(signature = (
addr_path,
sol_code_path=PathBuf::from(DEFAULT_SOL_CODE),
rpc_url=None,
optimizer_runs=DEFAULT_OPTIMIZER_RUNS.parse().unwrap(),
private_key=None,
))]
fn deploy_evm(
addr_path: PathBuf,
sol_code_path: PathBuf,
rpc_url: Option<String>,
optimizer_runs: usize,
private_key: Option<String>,
) -> Result<bool, PyErr> {
Runtime::new()
.unwrap()
.block_on(crate::execute::deploy_evm(
sol_code_path,
rpc_url,
addr_path,
optimizer_runs,
private_key,
"Halo2Verifier",
))
.map_err(|e| {
let err_str = format!("Failed to run deploy_evm: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// deploys the solidity vk verifier
#[pyfunction(signature = (
addr_path,
sol_code_path=PathBuf::from(DEFAULT_VK_SOL),
rpc_url=None,
optimizer_runs=DEFAULT_OPTIMIZER_RUNS.parse().unwrap(),
private_key=None,
))]
fn deploy_vk_evm(
addr_path: PathBuf,
sol_code_path: PathBuf,
rpc_url: Option<String>,
optimizer_runs: usize,
private_key: Option<String>,
) -> Result<bool, PyErr> {
Runtime::new()
.unwrap()
.block_on(crate::execute::deploy_evm(
sol_code_path,
rpc_url,
addr_path,
optimizer_runs,
private_key,
"Halo2VerifyingKey",
))
.map_err(|e| {
let err_str = format!("Failed to run deploy_evm: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// deploys the solidity da verifier
#[pyfunction(signature = (
addr_path,
input_data,
settings_path=PathBuf::from(DEFAULT_SETTINGS),
sol_code_path=PathBuf::from(DEFAULT_SOL_CODE_DA),
rpc_url=None,
optimizer_runs=DEFAULT_OPTIMIZER_RUNS.parse().unwrap(),
private_key=None
))]
fn deploy_da_evm(
addr_path: PathBuf,
input_data: PathBuf,
settings_path: PathBuf,
sol_code_path: PathBuf,
rpc_url: Option<String>,
optimizer_runs: usize,
private_key: Option<String>,
) -> Result<bool, PyErr> {
Runtime::new()
.unwrap()
.block_on(crate::execute::deploy_da_evm(
input_data,
settings_path,
sol_code_path,
rpc_url,
addr_path,
optimizer_runs,
private_key,
))
.map_err(|e| {
let err_str = format!("Failed to run deploy_da_evm: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// verifies an evm compatible proof, you will need solc installed in your environment to run this
///
/// Arguments
/// ---------
/// addr_verifier: str
/// The path to verifier contract's address
///
/// proof_path: str
/// The path to the proof file (generated using the prove command)
///
/// rpc_url: str
/// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state
///
/// addr_da: str
/// does the verifier use data attestation ?
///
/// addr_vk: str
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
addr_verifier,
proof_path=PathBuf::from(DEFAULT_PROOF),
rpc_url=None,
addr_da = None,
addr_vk = None,
))]
fn verify_evm(
addr_verifier: &str,
proof_path: PathBuf,
rpc_url: Option<String>,
addr_da: Option<&str>,
addr_vk: Option<&str>,
) -> Result<bool, PyErr> {
let addr_verifier = H160Flag::from(addr_verifier);
let addr_da = if let Some(addr_da) = addr_da {
let addr_da = H160Flag::from(addr_da);
Some(addr_da)
} else {
None
};
let addr_vk = if let Some(addr_vk) = addr_vk {
let addr_vk = H160Flag::from(addr_vk);
Some(addr_vk)
} else {
None
};
Runtime::new()
.unwrap()
.block_on(crate::execute::verify_evm(
proof_path,
addr_verifier,
rpc_url,
addr_da,
addr_vk,
))
.map_err(|e| {
let err_str = format!("Failed to run verify_evm: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
/// Creates an evm compatible aggregate verifier, you will need solc installed in your environment to run this
///
/// Arguments
/// ---------
/// aggregation_settings: str
/// path to the settings file
///
/// vk_path: str
/// The path to load the desired verification key file
///
/// sol_code_path: str
/// The path to the Solidity code
///
/// abi_path: str
/// The path to output the Solidity verifier ABI
///
/// logrows: int
/// Number of logrows used during aggregated setup
///
/// srs_path: str
/// The path to the SRS file
///
/// render_vk_separately: bool
/// Whether the verifier key should be rendered as a separate contract. We recommend disabling selector compression if this is enabled. To save the verifier key as a separate contract, set this to true and then call the create-evm-vk command
///
/// Returns
/// -------
/// bool
///
#[pyfunction(signature = (
aggregation_settings=vec![PathBuf::from(DEFAULT_PROOF)],
vk_path=PathBuf::from(DEFAULT_VK_AGGREGATED),
sol_code_path=PathBuf::from(DEFAULT_SOL_CODE),
abi_path=PathBuf::from(DEFAULT_VERIFIER_ABI),
logrows=DEFAULT_AGGREGATED_LOGROWS.parse().unwrap(),
srs_path=None,
render_vk_seperately = DEFAULT_RENDER_VK_SEPERATELY.parse().unwrap(),
))]
fn create_evm_verifier_aggr(
aggregation_settings: Vec<PathBuf>,
vk_path: PathBuf,
sol_code_path: PathBuf,
abi_path: PathBuf,
logrows: u32,
srs_path: Option<PathBuf>,
render_vk_seperately: bool,
) -> Result<bool, PyErr> {
crate::execute::create_evm_aggregate_verifier(
vk_path,
srs_path,
sol_code_path,
abi_path,
aggregation_settings,
logrows,
render_vk_seperately,
)
.map_err(|e| {
let err_str = format!("Failed to run create_evm_verifier_aggr: {}", e);
PyRuntimeError::new_err(err_str)
})?;
Ok(true)
}
// Python Module
#[pymodule]
fn ezkl(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
m.add_class::<PyRunArgs>()?;
m.add_class::<PyG1Affine>()?;
m.add_class::<PyG1>()?;
m.add_class::<PyTestDataSource>()?;
m.add_class::<PyCommitments>()?;
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add_function(wrap_pyfunction!(felt_to_big_endian, m)?)?;
m.add_function(wrap_pyfunction!(felt_to_int, m)?)?;
m.add_function(wrap_pyfunction!(felt_to_float, m)?)?;
m.add_function(wrap_pyfunction!(kzg_commit, m)?)?;
m.add_function(wrap_pyfunction!(ipa_commit, m)?)?;
m.add_function(wrap_pyfunction!(swap_proof_commitments, m)?)?;
m.add_function(wrap_pyfunction!(poseidon_hash, m)?)?;
m.add_function(wrap_pyfunction!(float_to_felt, m)?)?;
m.add_function(wrap_pyfunction!(buffer_to_felts, m)?)?;
m.add_function(wrap_pyfunction!(gen_vk_from_pk_aggr, m)?)?;
m.add_function(wrap_pyfunction!(gen_vk_from_pk_single, m)?)?;
m.add_function(wrap_pyfunction!(table, m)?)?;
m.add_function(wrap_pyfunction!(mock, m)?)?;
m.add_function(wrap_pyfunction!(setup, m)?)?;
m.add_function(wrap_pyfunction!(prove, m)?)?;
m.add_function(wrap_pyfunction!(verify, m)?)?;
m.add_function(wrap_pyfunction!(gen_srs, m)?)?;
m.add_function(wrap_pyfunction!(get_srs, m)?)?;
m.add_function(wrap_pyfunction!(gen_witness, m)?)?;
m.add_function(wrap_pyfunction!(gen_settings, m)?)?;
m.add_function(wrap_pyfunction!(calibrate_settings, m)?)?;
m.add_function(wrap_pyfunction!(aggregate, m)?)?;
m.add_function(wrap_pyfunction!(mock_aggregate, m)?)?;
m.add_function(wrap_pyfunction!(setup_aggregate, m)?)?;
m.add_function(wrap_pyfunction!(compile_circuit, m)?)?;
m.add_function(wrap_pyfunction!(verify_aggr, m)?)?;
m.add_function(wrap_pyfunction!(create_evm_verifier, m)?)?;
m.add_function(wrap_pyfunction!(deploy_evm, m)?)?;
m.add_function(wrap_pyfunction!(deploy_vk_evm, m)?)?;
m.add_function(wrap_pyfunction!(deploy_da_evm, m)?)?;
m.add_function(wrap_pyfunction!(verify_evm, m)?)?;
m.add_function(wrap_pyfunction!(setup_test_evm_witness, m)?)?;
m.add_function(wrap_pyfunction!(create_evm_verifier_aggr, m)?)?;
m.add_function(wrap_pyfunction!(create_evm_data_attestation, m)?)?;
Ok(())
}
| https://github.com/zkonduit/ezkl |
src/srs_sha.rs | use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
/// SRS SHA256 hashes
pub static ref PUBLIC_SRS_SHA256_HASHES: HashMap<u32, &'static str> = HashMap::from_iter([
(
1,
"cafb2aa72c200ddc4e28aacabb8066e829207e2484b8d17059a566232f8a297b",
),
(
2,
"8194ec51da5d332d2e17283ade34920644774452c2fadf33742e8c739e275d8e",
),
(
3,
"0729e815bce2ac4dfad7819982c6479c3b22c32b71f64dca05e8fdd90e8535ef",
),
(
4,
"2c0785da20217fcafd3b12cc363a95eb2529037cc8a9bddf8fb15025cbc8cdc9",
),
(
5,
"5b950e3b76e7a9923d69f6d6585ce6b5f9458e5ec57a71c9de5005d32d544692",
),
(
6,
"85030b2924111fc60acaf4fb8a7bad89531fbe0271aeab0c21e545f71eee273d",
),
(
7,
"e65f95150519fe01c2bedf8f832f5249822ef84c9c017307419e10374ff9eeb1",
),
(
8,
"446092fd1d6030e5bb2f2a8368267d5ed0fbdb6a766f6c5e4a4841827ad3106f",
),
(
9,
"493d088951882ad81af11e08c791a38a37c0ffff14578cf2c7fb9b7bca654d8b",
),
(
10,
"9705d450e5dfd06adb673705f7bc34418ec86339203198beceb2ae7f1ffefedb",
),
(
11,
"257fa566ed9bc0767d3e63e92b5e966829fa3347d320a32055dc31ee7d33f8a4",
),
(
12,
"28b151069f41abc121baa6d2eaa8f9e4c4d8326ddbefee2bd9c0776b80ac6fad",
),
(
13,
"d5d94bb25bdc024f649213593027d861042ee807cafd94b49b54f1663f8f267d",
),
(
14,
"c09129f064c08ecb07ea3689a2247dcc177de6837e7d2f5f946e30453abbccef",
),
(
15,
"90807800a1c3b248a452e1732c45ee5099f38b737356f5542c0584ec9c3ebb45",
),
(
16,
"2a1a494630e71bc026dd5c0eab4c1b9a5dbc656228c1f0d48f5dbd3909b161d3",
),
(
17,
"41509f380362a8d14401c5ae92073154922fe23e45459ce6f696f58607655db7",
),
(
18,
"d0148475717a2ba269784a178cb0ab617bc77f16c58d4a3cbdfe785b591c7034",
),
(
19,
"d1a1655b4366a766d1578beb257849a92bf91cb1358c1a2c37ab180c5d3a204d",
),
(
20,
"54ef75911da76d7a6b7ea341998aaf66cb06c679c53e0a88a4fe070dd3add963",
),
(
21,
"486e044cf98704e07f41137d2b89698dc03d1fbf34d13b60902fea19a6013b4b",
),
(
22,
"1ee9b4396db3e4e2516ac5016626ab6ba967f091d5d23afbdb7df122a0bb9d0c",
),
(
23,
"748e48b9b6d06f9c82d26bf551d0af43ee2e801e4be56d7ccb20312e267fd1d6",
),
(
24,
"f94fa4afa2f5147680f907d4dd96a8826206c26bd3328cd379feaed614b234de",
),
(
25,
"dec49a69893fbcd66cd06296b2d936a6aceb431c130b2e52675fe4274b504f57",
),
(
26,
"b198a51d48b88181508d8e4ea9dea39db285e4585663b29b7e4ded0c22a94875",
),
]);
}
| https://github.com/zkonduit/ezkl |
src/tensor/mod.rs | /// Implementations of common operations on tensors.
pub mod ops;
/// A wrapper around a tensor of circuit variables / advices.
pub mod val;
/// A wrapper around a tensor of Halo2 Value types.
pub mod var;
use halo2curves::ff::PrimeField;
use maybe_rayon::{
prelude::{
IndexedParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator,
ParallelIterator,
},
slice::ParallelSliceMut,
};
use serde::{Deserialize, Serialize};
pub use val::*;
pub use var::*;
use crate::{
circuit::utils,
fieldutils::{felt_to_i32, i128_to_felt, i32_to_felt},
graph::Visibility,
};
use halo2_proofs::{
arithmetic::Field,
circuit::{AssignedCell, Region, Value},
plonk::{Advice, Assigned, Column, ConstraintSystem, Expression, Fixed, VirtualCells},
poly::Rotation,
};
use itertools::Itertools;
use std::error::Error;
use std::fmt::Debug;
use std::iter::Iterator;
use std::ops::{Add, Deref, DerefMut, Div, Mul, Neg, Range, Sub};
use std::{cmp::max, ops::Rem};
use thiserror::Error;
/// A wrapper for tensor related errors.
#[derive(Debug, Error)]
pub enum TensorError {
/// Shape mismatch in a operation
#[error("dimension mismatch in tensor op: {0}")]
DimMismatch(String),
/// Shape when instantiating
#[error("dimensionality error when manipulating a tensor: {0}")]
DimError(String),
/// wrong method was called on a tensor-like struct
#[error("wrong method called")]
WrongMethod,
/// Significant bit truncation when instantiating
#[error("Significant bit truncation when instantiating, try lowering the scale")]
SigBitTruncationError,
/// Failed to convert to field element tensor
#[error("Failed to convert to field element tensor")]
FeltError,
/// Table lookup error
#[error("Table lookup error")]
TableLookupError,
/// Unsupported operation
#[error("Unsupported operation on a tensor type")]
Unsupported,
/// Overflow
#[error("Unsigned integer overflow or underflow error in op: {0}")]
Overflow(String),
}
/// The (inner) type of tensor elements.
pub trait TensorType: Clone + Debug + 'static {
/// Returns the zero value.
fn zero() -> Option<Self> {
None
}
/// Returns the unit value.
fn one() -> Option<Self> {
None
}
/// Max operator for ordering values.
fn tmax(&self, _: &Self) -> Option<Self> {
None
}
}
macro_rules! tensor_type {
($rust_type:ty, $tensor_type:ident, $zero:expr, $one:expr) => {
impl TensorType for $rust_type {
fn zero() -> Option<Self> {
Some($zero)
}
fn one() -> Option<Self> {
Some($one)
}
fn tmax(&self, other: &Self) -> Option<Self> {
Some(max(*self, *other))
}
}
};
}
impl TensorType for f32 {
fn zero() -> Option<Self> {
Some(0.0)
}
// f32 doesnt impl Ord so we cant just use max like we can for i32, usize.
// A comparison between f32s needs to handle NAN values.
fn tmax(&self, other: &Self) -> Option<Self> {
match (self.is_nan(), other.is_nan()) {
(true, true) => Some(f32::NAN),
(true, false) => Some(*other),
(false, true) => Some(*self),
(false, false) => {
if self >= other {
Some(*self)
} else {
Some(*other)
}
}
}
}
}
impl TensorType for f64 {
fn zero() -> Option<Self> {
Some(0.0)
}
// f32 doesnt impl Ord so we cant just use max like we can for i32, usize.
// A comparison between f32s needs to handle NAN values.
fn tmax(&self, other: &Self) -> Option<Self> {
match (self.is_nan(), other.is_nan()) {
(true, true) => Some(f64::NAN),
(true, false) => Some(*other),
(false, true) => Some(*self),
(false, false) => {
if self >= other {
Some(*self)
} else {
Some(*other)
}
}
}
}
}
tensor_type!(bool, Bool, false, true);
tensor_type!(i128, Int128, 0, 1);
tensor_type!(i32, Int32, 0, 1);
tensor_type!(usize, USize, 0, 1);
tensor_type!((), Empty, (), ());
tensor_type!(utils::F32, F32, utils::F32(0.0), utils::F32(1.0));
impl<T: TensorType> TensorType for Tensor<T> {
fn zero() -> Option<Self> {
Some(Tensor::new(Some(&[T::zero().unwrap()]), &[1]).unwrap())
}
fn one() -> Option<Self> {
Some(Tensor::new(Some(&[T::one().unwrap()]), &[1]).unwrap())
}
}
impl<T: TensorType> TensorType for Value<T> {
fn zero() -> Option<Self> {
Some(Value::known(T::zero().unwrap()))
}
fn one() -> Option<Self> {
Some(Value::known(T::one().unwrap()))
}
fn tmax(&self, other: &Self) -> Option<Self> {
Some(
(self.clone())
.zip(other.clone())
.map(|(a, b)| a.tmax(&b).unwrap()),
)
}
}
impl<F: PrimeField + PartialOrd> TensorType for Assigned<F>
where
F: Field,
{
fn zero() -> Option<Self> {
Some(F::ZERO.into())
}
fn one() -> Option<Self> {
Some(F::ONE.into())
}
fn tmax(&self, other: &Self) -> Option<Self> {
if self.evaluate() >= other.evaluate() {
Some(*self)
} else {
Some(*other)
}
}
}
impl<F: PrimeField> TensorType for Expression<F>
where
F: Field,
{
fn zero() -> Option<Self> {
Some(Expression::Constant(F::ZERO))
}
fn one() -> Option<Self> {
Some(Expression::Constant(F::ONE))
}
fn tmax(&self, _: &Self) -> Option<Self> {
todo!()
}
}
impl TensorType for Column<Advice> {}
impl TensorType for Column<Fixed> {}
impl<F: PrimeField + PartialOrd> TensorType for AssignedCell<Assigned<F>, F> {
fn tmax(&self, other: &Self) -> Option<Self> {
let mut output: Option<Self> = None;
self.value_field().zip(other.value_field()).map(|(a, b)| {
if a.evaluate() >= b.evaluate() {
output = Some(self.clone());
} else {
output = Some(other.clone());
}
});
output
}
}
impl<F: PrimeField + PartialOrd> TensorType for AssignedCell<F, F> {
fn tmax(&self, other: &Self) -> Option<Self> {
let mut output: Option<Self> = None;
self.value().zip(other.value()).map(|(a, b)| {
if a >= b {
output = Some(self.clone());
} else {
output = Some(other.clone());
}
});
output
}
}
// specific types
impl TensorType for halo2curves::pasta::Fp {
fn zero() -> Option<Self> {
Some(halo2curves::pasta::Fp::zero())
}
fn one() -> Option<Self> {
Some(halo2curves::pasta::Fp::one())
}
fn tmax(&self, other: &Self) -> Option<Self> {
Some((*self).max(*other))
}
}
impl TensorType for halo2curves::bn256::Fr {
fn zero() -> Option<Self> {
Some(halo2curves::bn256::Fr::zero())
}
fn one() -> Option<Self> {
Some(halo2curves::bn256::Fr::one())
}
fn tmax(&self, other: &Self) -> Option<Self> {
Some((*self).max(*other))
}
}
/// A generic multi-dimensional array representation of a Tensor.
/// The `inner` attribute contains a vector of values whereas `dims` corresponds to the dimensionality of the array
/// and as such determines how we index, query for values, or slice a Tensor.
#[derive(Clone, Debug, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Tensor<T: TensorType> {
inner: Vec<T>,
dims: Vec<usize>,
scale: Option<crate::Scale>,
visibility: Option<Visibility>,
}
impl<T: TensorType> IntoIterator for Tensor<T> {
type Item = T;
type IntoIter = ::std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter()
}
}
impl<T: TensorType> Deref for Tensor<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
self.inner.deref()
}
}
impl<T: TensorType> DerefMut for Tensor<T> {
#[inline]
fn deref_mut(&mut self) -> &mut [T] {
self.inner.deref_mut()
}
}
impl<T: PartialEq + TensorType> PartialEq for Tensor<T> {
fn eq(&self, other: &Tensor<T>) -> bool {
self.dims == other.dims && self.deref() == other.deref()
}
}
impl<I: Iterator> From<I> for Tensor<I::Item>
where
I::Item: TensorType + Clone,
Vec<I::Item>: FromIterator<I::Item>,
{
fn from(value: I) -> Tensor<I::Item> {
let data: Vec<I::Item> = value.collect::<Vec<I::Item>>();
Tensor::new(Some(&data), &[data.len()]).unwrap()
}
}
impl<T> FromIterator<T> for Tensor<T>
where
T: TensorType + Clone,
Vec<T>: FromIterator<T>,
{
fn from_iter<I: IntoIterator<Item = T>>(value: I) -> Tensor<T> {
let data: Vec<I::Item> = value.into_iter().collect::<Vec<I::Item>>();
Tensor::new(Some(&data), &[data.len()]).unwrap()
}
}
impl<F: PrimeField + Clone + TensorType + PartialOrd> From<Tensor<AssignedCell<Assigned<F>, F>>>
for Tensor<i32>
{
fn from(value: Tensor<AssignedCell<Assigned<F>, F>>) -> Tensor<i32> {
let mut output = Vec::new();
value.map(|x| {
x.evaluate().value().map(|y| {
let e = felt_to_i32(*y);
output.push(e);
e
})
});
Tensor::new(Some(&output), value.dims()).unwrap()
}
}
impl<F: PrimeField + Clone + TensorType + PartialOrd> From<Tensor<AssignedCell<F, F>>>
for Tensor<i32>
{
fn from(value: Tensor<AssignedCell<F, F>>) -> Tensor<i32> {
let mut output = Vec::new();
value.map(|x| {
let mut i = 0;
x.value().map(|y| {
let e = felt_to_i32(*y);
output.push(e);
i += 1;
});
if i == 0 {
output.push(0);
}
});
Tensor::new(Some(&output), value.dims()).unwrap()
}
}
impl<F: PrimeField + Clone + TensorType + PartialOrd> From<Tensor<AssignedCell<Assigned<F>, F>>>
for Tensor<Value<F>>
{
fn from(value: Tensor<AssignedCell<Assigned<F>, F>>) -> Tensor<Value<F>> {
let mut output = Vec::new();
for x in value.iter() {
output.push(x.value_field().evaluate());
}
Tensor::new(Some(&output), value.dims()).unwrap()
}
}
impl<F: PrimeField + TensorType + Clone + PartialOrd> From<Tensor<Value<F>>> for Tensor<i32> {
fn from(t: Tensor<Value<F>>) -> Tensor<i32> {
let mut output = Vec::new();
t.map(|x| {
let mut i = 0;
x.map(|y| {
let e = felt_to_i32(y);
output.push(e);
i += 1;
});
if i == 0 {
output.push(0);
}
});
Tensor::new(Some(&output), t.dims()).unwrap()
}
}
impl<F: PrimeField + TensorType + Clone + PartialOrd> From<Tensor<Value<F>>>
for Tensor<Value<Assigned<F>>>
{
fn from(t: Tensor<Value<F>>) -> Tensor<Value<Assigned<F>>> {
let mut ta: Tensor<Value<Assigned<F>>> = Tensor::from((0..t.len()).map(|i| t[i].into()));
// safe to unwrap as we know the dims are correct
ta.reshape(t.dims()).unwrap();
ta
}
}
impl<F: PrimeField + TensorType + Clone> From<Tensor<i32>> for Tensor<Value<F>> {
fn from(t: Tensor<i32>) -> Tensor<Value<F>> {
let mut ta: Tensor<Value<F>> =
Tensor::from((0..t.len()).map(|i| Value::known(i32_to_felt::<F>(t[i]))));
// safe to unwrap as we know the dims are correct
ta.reshape(t.dims()).unwrap();
ta
}
}
impl<F: PrimeField + TensorType + Clone> From<Tensor<i128>> for Tensor<Value<F>> {
fn from(t: Tensor<i128>) -> Tensor<Value<F>> {
let mut ta: Tensor<Value<F>> =
Tensor::from((0..t.len()).map(|i| Value::known(i128_to_felt::<F>(t[i]))));
// safe to unwrap as we know the dims are correct
ta.reshape(t.dims()).unwrap();
ta
}
}
impl<T: Clone + TensorType + std::marker::Send + std::marker::Sync>
maybe_rayon::iter::FromParallelIterator<T> for Tensor<T>
{
fn from_par_iter<I>(par_iter: I) -> Self
where
I: maybe_rayon::iter::IntoParallelIterator<Item = T>,
{
let inner: Vec<T> = par_iter.into_par_iter().collect();
Tensor::new(Some(&inner), &[inner.len()]).unwrap()
}
}
impl<T: Clone + TensorType + std::marker::Send + std::marker::Sync>
maybe_rayon::iter::IntoParallelIterator for Tensor<T>
{
type Iter = maybe_rayon::vec::IntoIter<T>;
type Item = T;
fn into_par_iter(self) -> Self::Iter {
self.inner.into_par_iter()
}
}
impl<'data, T: Clone + TensorType + std::marker::Send + std::marker::Sync>
maybe_rayon::iter::IntoParallelRefMutIterator<'data> for Tensor<T>
{
type Iter = maybe_rayon::slice::IterMut<'data, T>;
type Item = &'data mut T;
fn par_iter_mut(&'data mut self) -> Self::Iter {
self.inner.par_iter_mut()
}
}
impl<T: Clone + TensorType> Tensor<T> {
/// Sets (copies) the tensor values to the provided ones.
pub fn new(values: Option<&[T]>, dims: &[usize]) -> Result<Self, TensorError> {
let total_dims: usize = if !dims.is_empty() {
dims.iter().product()
} else if values.is_some() {
1
} else {
0
};
match values {
Some(v) => {
if total_dims != v.len() {
return Err(TensorError::DimError(format!(
"Cannot create tensor of length {} with dims {:?}",
v.len(),
dims
)));
}
Ok(Tensor {
inner: Vec::from(v),
dims: Vec::from(dims),
scale: None,
visibility: None,
})
}
None => Ok(Tensor {
inner: vec![T::zero().unwrap(); total_dims],
dims: Vec::from(dims),
scale: None,
visibility: None,
}),
}
}
/// set the tensor's (optional) scale parameter
pub fn set_scale(&mut self, scale: crate::Scale) {
self.scale = Some(scale)
}
/// set the tensor's (optional) visibility parameter
pub fn set_visibility(&mut self, visibility: &Visibility) {
self.visibility = Some(visibility.clone())
}
/// getter for scale
pub fn scale(&self) -> Option<crate::Scale> {
self.scale
}
/// getter for visibility
pub fn visibility(&self) -> Option<Visibility> {
self.visibility.clone()
}
/// Returns the number of elements in the tensor.
pub fn len(&self) -> usize {
self.dims().iter().product::<usize>()
}
/// Checks if the number of elements in tensor is 0.
pub fn is_empty(&self) -> bool {
self.inner.len() == 0
}
/// Checks if the number of elements in tensor is 1 but with an empty dimension (this is for onnx compatibility).
pub fn is_singleton(&self) -> bool {
self.dims().is_empty() && self.len() == 1
}
/// Set one single value on the tensor.
///
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(None, &[3, 3, 3]).unwrap();
///
/// a.set(&[0, 0, 1], 10);
/// assert_eq!(a[0 + 0 + 1], 10);
///
/// a.set(&[2, 2, 0], 9);
/// assert_eq!(a[2*9 + 2*3 + 0], 9);
/// ```
pub fn set(&mut self, indices: &[usize], value: T) {
let index = self.get_index(indices);
self[index] = value;
}
/// Get a single value from the Tensor.
///
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(None, &[2, 3, 5]).unwrap();
///
/// a[1*15 + 1*5 + 1] = 5;
/// assert_eq!(a.get(&[1, 1, 1]), 5);
/// ```
pub fn get(&self, indices: &[usize]) -> T {
let index = self.get_index(indices);
self[index].clone()
}
/// Get a mutable array index from rows / columns indices.
///
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(None, &[2, 3, 5]).unwrap();
///
/// a[1*15 + 1*5 + 1] = 5;
/// assert_eq!(a.get(&[1, 1, 1]), 5);
/// ```
pub fn get_mut(&mut self, indices: &[usize]) -> &mut T {
assert_eq!(self.dims.len(), indices.len());
let mut index = 0;
let mut d = 1;
for i in (0..indices.len()).rev() {
assert!(self.dims[i] > indices[i]);
index += indices[i] * d;
d *= self.dims[i];
}
&mut self[index]
}
/// Pad to a length that is divisible by n
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(Some(&[1,2,3,4,5,6]), &[2, 3]).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 0, 0]), &[8]).unwrap();
/// assert_eq!(a.pad_to_zero_rem(4, 0).unwrap(), expected);
///
/// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 0, 0, 0]), &[9]).unwrap();
/// assert_eq!(a.pad_to_zero_rem(9, 0).unwrap(), expected);
/// ```
pub fn pad_to_zero_rem(&self, n: usize, pad: T) -> Result<Tensor<T>, TensorError> {
let mut inner = self.inner.clone();
let remainder = self.len() % n;
if remainder != 0 {
inner.resize(self.len() + n - remainder, pad);
}
Tensor::new(Some(&inner), &[inner.len()])
}
/// Get a single value from the Tensor.
///
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(None, &[2, 3, 5]).unwrap();
///
/// let flat_index = 1*15 + 1*5 + 1;
/// a[1*15 + 1*5 + 1] = 5;
/// assert_eq!(a.get_flat_index(flat_index), 5);
/// ```
pub fn get_flat_index(&self, index: usize) -> T {
self[index].clone()
}
/// Display a tensor
pub fn show(&self) -> String {
if self.len() > 12 {
let start = self[..12].to_vec();
// print the two split by ... in the middle
format!(
"[{} ...]",
start.iter().map(|x| format!("{:?}", x)).join(", "),
)
} else {
format!("[{:?}]", self.iter().map(|x| format!("{:?}", x)).join(", "))
}
}
/// Get a slice from the Tensor.
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3]).unwrap();
/// let mut b = Tensor::<i32>::new(Some(&[1, 2]), &[2]).unwrap();
///
/// assert_eq!(a.get_slice(&[0..2]).unwrap(), b);
/// ```
pub fn get_slice(&self, indices: &[Range<usize>]) -> Result<Tensor<T>, TensorError>
where
T: Send + Sync,
{
if indices.is_empty() {
return Ok(self.clone());
}
if self.dims.len() < indices.len() {
return Err(TensorError::DimError(format!(
"The dimensionality of the slice {:?} is greater than the tensor's {:?}",
indices, self.dims
)));
} else if indices.iter().map(|x| x.end - x.start).collect::<Vec<_>>() == self.dims {
// else if slice is the same as dims, return self
return Ok(self.clone());
}
// if indices weren't specified we fill them in as required
let mut full_indices = indices.to_vec();
for i in 0..(self.dims.len() - indices.len()) {
full_indices.push(0..self.dims()[indices.len() + i])
}
let cartesian_coord: Vec<Vec<usize>> = full_indices
.iter()
.cloned()
.multi_cartesian_product()
.collect();
let res: Vec<T> = cartesian_coord
.par_iter()
.map(|e| {
let index = self.get_index(e);
self[index].clone()
})
.collect();
let dims: Vec<usize> = full_indices.iter().map(|e| e.end - e.start).collect();
Tensor::new(Some(&res), &dims)
}
/// Set a slice of the Tensor.
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[2, 3]).unwrap();
/// let b = Tensor::<i32>::new(Some(&[1, 2, 3, 1, 2, 3]), &[2, 3]).unwrap();
/// a.set_slice(&[1..2], &Tensor::<i32>::new(Some(&[1, 2, 3]), &[1, 3]).unwrap()).unwrap();
/// assert_eq!(a, b);
/// ```
pub fn set_slice(
&mut self,
indices: &[Range<usize>],
value: &Tensor<T>,
) -> Result<(), TensorError>
where
T: Send + Sync,
{
if indices.is_empty() {
return Ok(());
}
if self.dims.len() < indices.len() {
return Err(TensorError::DimError(format!(
"The dimensionality of the slice {:?} is greater than the tensor's {:?}",
indices, self.dims
)));
}
// if indices weren't specified we fill them in as required
let mut full_indices = indices.to_vec();
let omitted_dims = (indices.len()..self.dims.len())
.map(|i| self.dims[i])
.collect::<Vec<_>>();
for dim in &omitted_dims {
full_indices.push(0..*dim);
}
let full_dims = full_indices
.iter()
.map(|x| x.end - x.start)
.collect::<Vec<_>>();
// now broadcast the value to the full dims
let value = value.expand(&full_dims)?;
let cartesian_coord: Vec<Vec<usize>> = full_indices
.iter()
.cloned()
.multi_cartesian_product()
.collect();
let _ = cartesian_coord
.iter()
.enumerate()
.map(|(i, e)| {
self.set(e, value[i].clone());
})
.collect::<Vec<_>>();
Ok(())
}
/// Get the array index from rows / columns indices.
///
/// ```
/// use ezkl::tensor::Tensor;
/// let a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();
///
/// assert_eq!(a.get_index(&[2, 2, 2]), 26);
/// assert_eq!(a.get_index(&[1, 2, 2]), 17);
/// assert_eq!(a.get_index(&[1, 2, 0]), 15);
/// assert_eq!(a.get_index(&[1, 0, 1]), 10);
/// ```
pub fn get_index(&self, indices: &[usize]) -> usize {
assert_eq!(self.dims.len(), indices.len());
let mut index = 0;
let mut d = 1;
for i in (0..indices.len()).rev() {
assert!(self.dims[i] > indices[i]);
index += indices[i] * d;
d *= self.dims[i];
}
index
}
/// Duplicates every nth element
///
/// ```
/// use ezkl::tensor::Tensor;
/// let a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[6]).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 3, 4, 5, 5, 6]), &[8]).unwrap();
/// assert_eq!(a.duplicate_every_n(3, 1, 0).unwrap(), expected);
/// assert_eq!(a.duplicate_every_n(7, 1, 0).unwrap(), a);
///
/// let expected = Tensor::<i32>::new(Some(&[1, 1, 2, 3, 3, 4, 5, 5, 6]), &[9]).unwrap();
/// assert_eq!(a.duplicate_every_n(3, 1, 2).unwrap(), expected);
///
/// ```
pub fn duplicate_every_n(
&self,
n: usize,
num_repeats: usize,
initial_offset: usize,
) -> Result<Tensor<T>, TensorError> {
let mut inner: Vec<T> = vec![];
let mut offset = initial_offset;
for (i, elem) in self.inner.clone().into_iter().enumerate() {
if (i + offset + 1) % n == 0 {
inner.extend(vec![elem; 1 + num_repeats]);
offset += num_repeats;
} else {
inner.push(elem.clone());
}
}
Tensor::new(Some(&inner), &[inner.len()])
}
/// Removes every nth element
///
/// ```
/// use ezkl::tensor::Tensor;
/// let a = Tensor::<i32>::new(Some(&[1, 2, 3, 3, 4, 5, 6, 6]), &[8]).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 3, 5, 6, 6]), &[7]).unwrap();
/// assert_eq!(a.remove_every_n(4, 1, 0).unwrap(), expected);
///
///
pub fn remove_every_n(
&self,
n: usize,
num_repeats: usize,
initial_offset: usize,
) -> Result<Tensor<T>, TensorError> {
let mut inner: Vec<T> = vec![];
let mut indices_to_remove = std::collections::HashSet::new();
for i in 0..self.inner.len() {
if (i + initial_offset + 1) % n == 0 {
for j in 1..(1 + num_repeats) {
indices_to_remove.insert(i + j);
}
}
}
let old_inner = self.inner.clone();
for (i, elem) in old_inner.into_iter().enumerate() {
if !indices_to_remove.contains(&i) {
inner.push(elem.clone());
}
}
Tensor::new(Some(&inner), &[inner.len()])
}
/// Remove indices
/// WARN: assumes indices are in ascending order for speed
/// ```
/// use ezkl::tensor::Tensor;
/// let a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[6]).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[1, 2, 3, 6]), &[4]).unwrap();
/// let mut indices = vec![3, 4];
/// assert_eq!(a.remove_indices(&mut indices, true).unwrap(), expected);
///
///
/// let a = Tensor::<i32>::new(Some(&[52, -245, 153, 13, -4, -56, -163, 249, -128, -172, 396, 143, 2, -96, 504, -44, -158, -393, 61, 95, 191, 74, 64, -219, 553, 104, 235, 222, 44, -216, 63, -251, 40, -140, 112, -355, 60, 123, 26, -116, -89, -200, -109, 168, 135, -34, -99, -54, 5, -81, 322, 87, 4, -139, 420, 92, -295, -12, 262, -1, 26, -48, 231, 1, -335, 244, 188, -4, 5, -362, 57, -198, -184, -117, 40, 305, 49, 30, -59, -26, -37, 96]), &[82]).unwrap();
/// let b = Tensor::<i32>::new(Some(&[52, -245, 153, 13, -4, -56, -163, 249, -128, -172, 396, 143, 2, -96, 504, -44, -158, -393, 61, 95, 191, 74, 64, -219, 553, 104, 235, 222, 44, -216, 63, -251, 40, -140, 112, -355, 60, 123, 26, -116, -89, -200, -109, 168, 135, -34, -99, -54, 5, -81, 322, 87, 4, -139, 420, 92, -295, -12, 262, -1, 26, -48, 231, -335, 244, 188, 5, -362, 57, -198, -184, -117, 40, 305, 49, 30, -59, -26, -37, 96]), &[80]).unwrap();
/// let mut indices = vec![63, 67];
/// assert_eq!(a.remove_indices(&mut indices, true).unwrap(), b);
/// ```
pub fn remove_indices(
&self,
indices: &mut [usize],
is_sorted: bool,
) -> Result<Tensor<T>, TensorError> {
let mut inner: Vec<T> = self.inner.clone();
// time it
if !is_sorted {
indices.par_sort_unstable();
}
// remove indices
for elem in indices.iter().rev() {
inner.remove(*elem);
}
Tensor::new(Some(&inner), &[inner.len()])
}
/// Returns the tensor's dimensions.
pub fn dims(&self) -> &[usize] {
&self.dims
}
///Reshape the tensor
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();
/// a.reshape(&[9, 3]);
/// assert_eq!(a.dims(), &[9, 3]);
/// ```
pub fn reshape(&mut self, new_dims: &[usize]) -> Result<(), TensorError> {
// in onnx parlance this corresponds to converting a tensor to a single element
if new_dims.is_empty() {
if !(self.len() == 1 || self.is_empty()) {
return Err(TensorError::DimError(
"Cannot reshape to empty tensor".to_string(),
));
}
self.dims = vec![];
} else {
let product = if new_dims != [0] {
new_dims.iter().product::<usize>()
} else {
0
};
if self.len() != product {
return Err(TensorError::DimError(format!(
"Cannot reshape tensor of length {} to {:?}",
self.len(),
new_dims
)));
}
self.dims = Vec::from(new_dims);
}
Ok(())
}
/// Move axis of the tensor
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();
/// let b = a.move_axis(0, 2).unwrap();
/// assert_eq!(b.dims(), &[3, 3, 3]);
///
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 1, 2]).unwrap();
/// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6]), &[1, 2, 3]).unwrap();
/// let b = a.move_axis(0, 2).unwrap();
/// assert_eq!(b, expected);
///
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();
/// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();
/// let b = a.move_axis(1, 2).unwrap();
/// assert_eq!(b, expected);
///
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();
/// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();
/// let b = a.move_axis(2, 1).unwrap();
/// assert_eq!(b, expected);
/// ```
pub fn move_axis(&mut self, source: usize, destination: usize) -> Result<Self, TensorError> {
assert!(source < self.dims.len());
assert!(destination < self.dims.len());
let mut new_dims = self.dims.clone();
new_dims.remove(source);
new_dims.insert(destination, self.dims[source]);
// now reconfigure the elements appropriately in the new array
// eg. if we have a 3x3x3 array and we want to move the 0th axis to the 2nd position
// we need to move the elements at 0, 1, 2, 3, 4, 5, 6, 7, 8 to 0, 3, 6, 1, 4, 7, 2, 5, 8
// so we need to move the elements at 0, 1, 2 to 0, 3, 6
// and the elements at 3, 4, 5 to 1, 4, 7
// and the elements at 6, 7, 8 to 2, 5, 8
let cartesian_coords = new_dims
.iter()
.map(|d| 0..*d)
.multi_cartesian_product()
.collect::<Vec<Vec<usize>>>();
let mut output = Tensor::new(None, &new_dims)?;
for coord in cartesian_coords {
let mut old_coord = vec![0; self.dims.len()];
// now fetch the old index
for (i, c) in coord.iter().enumerate() {
if i == destination {
old_coord[source] = *c;
} else if i == source && source < destination {
old_coord[source + 1] = *c;
} else if i == source && source > destination {
old_coord[source - 1] = *c;
} else if (i < source && source < destination)
|| (i < destination && source > destination)
|| (i > source && source > destination)
|| (i > destination && source < destination)
{
old_coord[i] = *c;
} else if i > source && source < destination {
old_coord[i + 1] = *c;
} else if i > destination && source > destination {
old_coord[i - 1] = *c;
} else {
return Err(TensorError::DimError(
"Unknown condition for moving the axis".to_string(),
));
}
}
let value = self.get(&old_coord);
output.set(&coord, value);
}
Ok(output)
}
/// Swap axes of the tensor
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();
/// let b = a.swap_axes(0, 2).unwrap();
/// assert_eq!(b.dims(), &[3, 3, 3]);
///
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 1, 2]).unwrap();
/// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6]), &[2, 1, 3]).unwrap();
/// let b = a.swap_axes(0, 2).unwrap();
/// assert_eq!(b, expected);
///
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();
/// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();
/// let b = a.swap_axes(1, 2).unwrap();
/// assert_eq!(b, expected);
///
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 3, 2]).unwrap();
/// let mut expected = Tensor::<i32>::new(Some(&[1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12]), &[2, 2, 3]).unwrap();
/// let b = a.swap_axes(2, 1).unwrap();
/// assert_eq!(b, expected);
/// ```
pub fn swap_axes(&mut self, source: usize, destination: usize) -> Result<Self, TensorError> {
assert!(source < self.dims.len());
assert!(destination < self.dims.len());
let mut new_dims = self.dims.clone();
new_dims[source] = self.dims[destination];
new_dims[destination] = self.dims[source];
// now reconfigure the elements appropriately in the new array
// eg. if we have a 3x3x3 array and we want to move the 0th axis to the 2nd position
// we need to move the elements at 0, 1, 2, 3, 4, 5, 6, 7, 8 to 0, 3, 6, 1, 4, 7, 2, 5, 8
// so we need to move the elements at 0, 1, 2 to 0, 3, 6
// and the elements at 3, 4, 5 to 1, 4, 7
// and the elements at 6, 7, 8 to 2, 5, 8
let cartesian_coords = new_dims
.iter()
.map(|d| 0..*d)
.multi_cartesian_product()
.collect::<Vec<Vec<usize>>>();
let mut output = Tensor::new(None, &new_dims)?;
for coord in cartesian_coords {
let mut old_coord = vec![0; self.dims.len()];
// now fetch the old index
for (i, c) in coord.iter().enumerate() {
if i == destination {
old_coord[source] = *c;
} else if i == source {
old_coord[destination] = *c;
} else {
old_coord[i] = *c;
}
}
output.set(&coord, self.get(&old_coord));
}
Ok(output)
}
/// Broadcasts the tensor to a given shape
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3, 1]).unwrap();
///
/// let mut expected = Tensor::<i32>::new(Some(&[1, 1, 1, 2, 2, 2, 3, 3, 3]), &[3, 3]).unwrap();
/// assert_eq!(a.expand(&[3, 3]).unwrap(), expected);
///
/// ```
pub fn expand(&self, shape: &[usize]) -> Result<Self, TensorError> {
if self.dims().len() > shape.len() {
return Err(TensorError::DimError(format!(
"Cannot expand {:?} to the smaller shape {:?}",
self.dims(),
shape
)));
}
if shape == self.dims() {
return Ok(self.clone());
}
for d in self.dims() {
if !(shape.contains(d) || *d == 1) {
return Err(TensorError::DimError(format!(
"The current dimension {} must be contained in the new shape {:?} or be 1",
d, shape
)));
}
}
let cartesian_coords = shape
.iter()
.map(|d| 0..*d)
.multi_cartesian_product()
.collect::<Vec<Vec<usize>>>();
let mut output = Tensor::new(None, shape)?;
for coord in cartesian_coords {
let mut new_coord = Vec::with_capacity(self.dims().len());
for (i, c) in coord.iter().enumerate() {
if i < self.dims().len() && self.dims()[i] == 1 {
new_coord.push(0);
} else if i >= self.dims().len() {
// do nothing at this point does not exist in the original tensor
} else {
new_coord.push(*c);
}
}
output.set(&coord, self.get(&new_coord));
}
Ok(output)
}
///Flatten the tensor shape
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<f32>::new(None, &[3, 3, 3]).unwrap();
/// a.flatten();
/// assert_eq!(a.dims(), &[27]);
/// ```
pub fn flatten(&mut self) {
if !self.dims().is_empty() && (self.dims() != [0]) {
self.dims = Vec::from([self.dims.iter().product::<usize>()]);
}
}
/// Maps a function to tensors
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();
/// let mut c = a.map(|x| i32::pow(x,2));
/// assert_eq!(c, Tensor::from([1, 16].into_iter()))
/// ```
pub fn map<F: FnMut(T) -> G, G: TensorType>(&self, mut f: F) -> Tensor<G> {
let mut t = Tensor::from(self.inner.iter().map(|e| f(e.clone())));
// safe to unwrap as we know the dims are correct
t.reshape(self.dims()).unwrap();
t
}
/// Maps a function to tensors and enumerates
/// ```
/// use ezkl::tensor::{Tensor, TensorError};
/// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();
/// let mut c = a.enum_map::<_,_,TensorError>(|i, x| Ok(i32::pow(x + i as i32, 2))).unwrap();
/// assert_eq!(c, Tensor::from([1, 25].into_iter()));
/// ```
pub fn enum_map<F: FnMut(usize, T) -> Result<G, E>, G: TensorType, E: Error>(
&self,
mut f: F,
) -> Result<Tensor<G>, E> {
let vec: Result<Vec<G>, E> = self
.inner
.iter()
.enumerate()
.map(|(i, e)| f(i, e.clone()))
.collect();
let mut t: Tensor<G> = Tensor::from(vec?.iter().cloned());
// safe to unwrap as we know the dims are correct
t.reshape(self.dims()).unwrap();
Ok(t)
}
/// Maps a function to tensors and enumerates in parallel
/// ```
/// use ezkl::tensor::{Tensor, TensorError};
/// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();
/// let mut c = a.par_enum_map::<_,_,TensorError>(|i, x| Ok(i32::pow(x + i as i32, 2))).unwrap();
/// assert_eq!(c, Tensor::from([1, 25].into_iter()));
/// ```
pub fn par_enum_map<
F: Fn(usize, T) -> Result<G, E> + std::marker::Send + std::marker::Sync,
G: TensorType + std::marker::Send + std::marker::Sync,
E: Error + std::marker::Send + std::marker::Sync,
>(
&self,
f: F,
) -> Result<Tensor<G>, E>
where
T: std::marker::Send + std::marker::Sync,
{
let vec: Result<Vec<G>, E> = self
.inner
.par_iter()
.enumerate()
.map(move |(i, e)| f(i, e.clone()))
.collect();
let mut t: Tensor<G> = Tensor::from(vec?.iter().cloned());
// safe to unwrap as we know the dims are correct
t.reshape(self.dims()).unwrap();
Ok(t)
}
/// Maps a function to tensors and enumerates in parallel
/// ```
/// use ezkl::tensor::{Tensor, TensorError};
/// let mut a = Tensor::<i32>::new(Some(&[1, 4]), &[2]).unwrap();
/// let mut c = a.par_enum_map::<_,_,TensorError>(|i, x| Ok(i32::pow(x + i as i32, 2))).unwrap();
/// assert_eq!(c, Tensor::from([1, 25].into_iter()));
/// ```
pub fn par_enum_map_mut_filtered<
F: Fn(usize) -> Result<T, E> + std::marker::Send + std::marker::Sync,
E: Error + std::marker::Send + std::marker::Sync,
>(
&mut self,
filter_indices: &std::collections::HashSet<&usize>,
f: F,
) -> Result<(), E>
where
T: std::marker::Send + std::marker::Sync,
{
self.inner
.par_iter_mut()
.enumerate()
.filter(|(i, _)| filter_indices.contains(i))
.for_each(move |(i, e)| *e = f(i).unwrap());
Ok(())
}
}
impl<T: Clone + TensorType> Tensor<Tensor<T>> {
/// Flattens a tensor of tensors
/// ```
/// use ezkl::tensor::Tensor;
/// let mut a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[2, 3]).unwrap();
/// let mut b = Tensor::<i32>::new(Some(&[1, 4]), &[2, 1]).unwrap();
/// let mut c = Tensor::new(Some(&[a,b]), &[2]).unwrap();
/// let mut d = c.combine().unwrap();
/// assert_eq!(d.dims(), &[8]);
/// ```
pub fn combine(&self) -> Result<Tensor<T>, TensorError> {
let mut dims = 0;
let mut inner = Vec::new();
for t in self.inner.clone().into_iter() {
dims += t.len();
inner.extend(t.inner);
}
Tensor::new(Some(&inner), &[dims])
}
}
impl<T: TensorType + Add<Output = T> + std::marker::Send + std::marker::Sync> Add for Tensor<T> {
type Output = Result<Tensor<T>, TensorError>;
/// Adds tensors.
/// # Arguments
///
/// * `self` - Tensor
/// * `rhs` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Add;
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2, 3, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.add(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[4, 4, 4, 2, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 1D casting
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2]),
/// &[1]).unwrap();
/// let result = x.add(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[4, 3, 4, 3, 3, 3]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
///
/// // Now test 2D casting
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2, 3]),
/// &[2]).unwrap();
/// let result = x.add(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[4, 3, 4, 4, 4, 4]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
fn add(self, rhs: Self) -> Self::Output {
let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();
let mut lhs = self.expand(&broadcasted_shape).unwrap();
let rhs = rhs.expand(&broadcasted_shape).unwrap();
lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {
*o = o.clone() + r;
});
Ok(lhs)
}
}
impl<T: TensorType + Neg<Output = T> + std::marker::Send + std::marker::Sync> Neg for Tensor<T> {
type Output = Tensor<T>;
/// Negates a tensor.
/// # Arguments
/// * `self` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Neg;
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.neg();
/// let expected = Tensor::<i32>::new(Some(&[-2, -1, -2, -1, -1, -1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
fn neg(self) -> Self {
let mut output = self;
output.par_iter_mut().for_each(|x| {
*x = x.clone().neg();
});
output
}
}
impl<T: TensorType + Sub<Output = T> + std::marker::Send + std::marker::Sync> Sub for Tensor<T> {
type Output = Result<Tensor<T>, TensorError>;
/// Subtracts tensors.
/// # Arguments
///
/// * `self` - Tensor
/// * `rhs` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Sub;
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2, 3, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.sub(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[0, -2, 0, 0, 0, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 1D sub
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2]),
/// &[1],
/// ).unwrap();
/// let result = x.sub(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[0, -1, 0, -1, -1, -1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 2D sub
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2, 3]),
/// &[2],
/// ).unwrap();
/// let result = x.sub(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[0, -1, 0, -2, -2, -2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
fn sub(self, rhs: Self) -> Self::Output {
let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();
let mut lhs = self.expand(&broadcasted_shape).unwrap();
let rhs = rhs.expand(&broadcasted_shape).unwrap();
lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {
*o = o.clone() - r;
});
Ok(lhs)
}
}
impl<T: TensorType + Mul<Output = T> + std::marker::Send + std::marker::Sync> Mul for Tensor<T> {
type Output = Result<Tensor<T>, TensorError>;
/// Elementwise multiplies tensors.
/// # Arguments
///
/// * `self` - Tensor
/// * `rhs` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Mul;
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2, 3, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.mul(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[4, 3, 4, 1, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 1D mult
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2]),
/// &[1]).unwrap();
/// let result = x.mul(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[4, 2, 4, 2, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 2D mult
/// let x = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i32>::new(
/// Some(&[2, 2]),
/// &[2]).unwrap();
/// let result = x.mul(k).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[4, 2, 4, 2, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
fn mul(self, rhs: Self) -> Self::Output {
let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();
let mut lhs = self.expand(&broadcasted_shape).unwrap();
let rhs = rhs.expand(&broadcasted_shape).unwrap();
lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {
*o = o.clone() * r;
});
Ok(lhs)
}
}
impl<T: TensorType + Mul<Output = T> + std::marker::Send + std::marker::Sync> Tensor<T> {
/// Elementwise raise a tensor to the nth power.
/// # Arguments
///
/// * `self` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Mul;
/// let x = Tensor::<i32>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.pow(3).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[8, 3375, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn pow(&self, mut exp: u32) -> Result<Self, TensorError> {
// calculate value of output
let mut base = self.clone();
let mut acc = base.map(|_| T::one().unwrap());
while exp > 1 {
if (exp & 1) == 1 {
acc = acc.mul(base.clone())?;
}
exp /= 2;
base = base.clone().mul(base)?;
}
// since exp!=0, finally the exp must be 1.
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
acc.mul(base)
}
}
impl<T: TensorType + Div<Output = T> + std::marker::Send + std::marker::Sync> Div for Tensor<T> {
type Output = Result<Tensor<T>, TensorError>;
/// Elementwise divide a tensor with another tensor.
/// # Arguments
///
/// * `self` - Tensor
/// * `rhs` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Div;
/// let x = Tensor::<i32>::new(
/// Some(&[4, 1, 4, 1, 1, 4]),
/// &[2, 3],
/// ).unwrap();
/// let y = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.div(y).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[2, 1, 2, 1, 1, 4]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // test 1D casting
/// let x = Tensor::<i32>::new(
/// Some(&[4, 1, 4, 1, 1, 4]),
/// &[2, 3],
/// ).unwrap();
/// let y = Tensor::<i32>::new(
/// Some(&[2]),
/// &[1],
/// ).unwrap();
/// let result = x.div(y).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[2, 0, 2, 0, 0, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
fn div(self, rhs: Self) -> Self::Output {
let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();
let mut lhs = self.expand(&broadcasted_shape).unwrap();
let rhs = rhs.expand(&broadcasted_shape).unwrap();
lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {
*o = o.clone() / r;
});
Ok(lhs)
}
}
// implement remainder
impl<T: TensorType + Rem<Output = T> + std::marker::Send + std::marker::Sync> Rem for Tensor<T> {
type Output = Result<Tensor<T>, TensorError>;
/// Elementwise remainder of a tensor with another tensor.
/// # Arguments
/// * `self` - Tensor
/// * `rhs` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use std::ops::Rem;
/// let x = Tensor::<i32>::new(
/// Some(&[4, 1, 4, 1, 1, 4]),
/// &[2, 3],
/// ).unwrap();
/// let y = Tensor::<i32>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = x.rem(y).unwrap();
/// let expected = Tensor::<i32>::new(Some(&[0, 0, 0, 0, 0, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
fn rem(self, rhs: Self) -> Self::Output {
let broadcasted_shape = get_broadcasted_shape(self.dims(), rhs.dims()).unwrap();
let mut lhs = self.expand(&broadcasted_shape).unwrap();
let rhs = rhs.expand(&broadcasted_shape).unwrap();
lhs.par_iter_mut().zip(rhs).for_each(|(o, r)| {
*o = o.clone() % r;
});
Ok(lhs)
}
}
/// Returns the broadcasted shape of two tensors
/// ```
/// use ezkl::tensor::get_broadcasted_shape;
/// let a = vec![2, 3];
/// let b = vec![2, 3];
/// let c = get_broadcasted_shape(&a, &b).unwrap();
/// assert_eq!(c, vec![2, 3]);
///
/// let a = vec![2, 3];
/// let b = vec![3];
/// let c = get_broadcasted_shape(&a, &b).unwrap();
/// assert_eq!(c, vec![2, 3]);
///
/// let a = vec![2, 3];
/// let b = vec![2, 1];
/// let c = get_broadcasted_shape(&a, &b).unwrap();
/// assert_eq!(c, vec![2, 3]);
///
/// let a = vec![2, 3];
/// let b = vec![1, 3];
/// let c = get_broadcasted_shape(&a, &b).unwrap();
/// assert_eq!(c, vec![2, 3]);
///
/// let a = vec![2, 3];
/// let b = vec![1, 1];
/// let c = get_broadcasted_shape(&a, &b).unwrap();
/// assert_eq!(c, vec![2, 3]);
///
/// ```
pub fn get_broadcasted_shape(
shape_a: &[usize],
shape_b: &[usize],
) -> Result<Vec<usize>, Box<dyn Error>> {
let num_dims_a = shape_a.len();
let num_dims_b = shape_b.len();
match (num_dims_a, num_dims_b) {
(a, b) if a == b => {
let mut broadcasted_shape = Vec::with_capacity(num_dims_a);
for (dim_a, dim_b) in shape_a.iter().zip(shape_b.iter()) {
let max_dim = dim_a.max(dim_b);
broadcasted_shape.push(*max_dim);
}
Ok(broadcasted_shape)
}
(a, b) if a < b => Ok(shape_b.to_vec()),
(a, b) if a > b => Ok(shape_a.to_vec()),
_ => Err(Box::new(TensorError::DimError(
"Unknown condition for broadcasting".to_string(),
))),
}
}
////////////////////////
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tensor() {
let data: Vec<f32> = vec![-1.0f32, 0.0, 1.0, 2.5];
let tensor = Tensor::<f32>::new(Some(&data), &[2, 2]).unwrap();
assert_eq!(&tensor[..], &data[..]);
}
#[test]
fn tensor_clone() {
let x = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3]).unwrap();
assert_eq!(x, x.clone());
}
#[test]
fn tensor_eq() {
let a = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3]).unwrap();
let mut b = Tensor::<i32>::new(Some(&[1, 2, 3]), &[3, 1]).unwrap();
b.reshape(&[3]).unwrap();
let c = Tensor::<i32>::new(Some(&[1, 2, 4]), &[3]).unwrap();
let d = Tensor::<i32>::new(Some(&[1, 2, 4]), &[3, 1]).unwrap();
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, d);
}
#[test]
fn tensor_slice() {
let a = Tensor::<i32>::new(Some(&[1, 2, 3, 4, 5, 6]), &[2, 3]).unwrap();
let b = Tensor::<i32>::new(Some(&[1, 4]), &[2, 1]).unwrap();
assert_eq!(a.get_slice(&[0..2, 0..1]).unwrap(), b);
}
}
| https://github.com/zkonduit/ezkl |
src/tensor/ops.rs | use super::TensorError;
use crate::tensor::{Tensor, TensorType};
use itertools::Itertools;
use maybe_rayon::{iter::ParallelIterator, prelude::IntoParallelRefIterator};
pub use std::ops::{Add, Mul, Neg, Sub};
/// Trilu operation.
/// # Arguments
/// * `a` - Tensor
/// * `k` - i32
/// * `upper` - Boolean
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::trilu;
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[1, 3, 2],
/// ).unwrap();
/// let result = trilu(&a, 1, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 2, 0, 0, 0, 0]), &[1, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 1, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[1, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 0, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 0, 4, 0, 0]), &[1, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 0, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 3, 4, 5, 6]), &[1, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, -1, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 0, 6]), &[1, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, -1, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 3, 0, 5, 6]), &[1, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[1, 2, 3],
/// ).unwrap();
/// let result = trilu(&a, 1, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 2, 3, 0, 0, 6]), &[1, 2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 1, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 0, 4, 5, 6]), &[1, 2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 0, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 0, 5, 6]), &[1, 2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 0, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 0, 4, 5, 0]), &[1, 2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, -1, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[1, 2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, -1, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 4, 0, 0]), &[1, 2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9]),
/// &[1, 3, 3],
/// ).unwrap();
/// let result = trilu(&a, 1, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 2, 3, 0, 0, 6, 0, 0, 0]), &[1, 3, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 1, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 0, 4, 5, 6, 7, 8, 9]), &[1, 3, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 0, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 0, 5, 6, 0, 0, 9]), &[1, 3, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, 0, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 0, 4, 5, 0, 7, 8, 9]), &[1, 3, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, -1, true).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 0, 8, 9]), &[1, 3, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = trilu(&a, -1, false).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 4, 0, 0, 7, 8, 0]), &[1, 3, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn trilu<T: TensorType + std::marker::Send + std::marker::Sync>(
a: &Tensor<T>,
k: i32,
upper: bool,
) -> Result<Tensor<T>, TensorError> {
let mut output = a.clone();
// Given a 2-D matrix or batches of 2-D matrices, returns the upper or lower triangular part of the tensor(s).
// The attribute “upper” determines whether the upper or lower part is retained.
// If set to true, the upper triangular matrix is retained. Lower triangular matrix is retained otherwise.
// Default value for the “upper” attribute is true. Trilu takes one input tensor of shape [*, N, M], where * is zero or more batch dimensions.
// The upper triangular part consists of the elements on and above the given diagonal (k).
// The lower triangular part consists of elements on and below the diagonal. All other elements in the matrix are set to zero.
let batch_dims = &a.dims()[0..a.dims().len() - 2];
let batch_cartiesian = batch_dims.iter().map(|d| 0..*d).multi_cartesian_product();
for b in batch_cartiesian {
for i in 0..a.dims()[1] {
for j in 0..a.dims()[2] {
let mut coord = b.clone();
coord.push(i);
coord.push(j);
// If k = 0, the triangular part on and above/below the main diagonal is retained.
if upper {
// If upper is set to true, a positive k retains the upper triangular matrix excluding the main diagonal and (k-1) diagonals above it.
if (j as i32) < (i as i32) + k {
output.set(&coord, T::zero().ok_or(TensorError::Unsupported)?);
}
} else {
// If upper is set to false, a positive k retains the lower triangular matrix including the main diagonal and k diagonals above it.
if (j as i32) > (i as i32) + k {
output.set(&coord, T::zero().ok_or(TensorError::Unsupported)?);
}
}
}
}
}
Ok(output)
}
/// Resize using nearest neighbour interpolation.
/// # Arguments
/// * `a` - Tensor
/// * `scales` - Vector of scales
/// # Examples
/// ```
///
///
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[2, 3],
/// ).unwrap();
/// let result = resize(&a, &[1, 2]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]), &[2, 6]).unwrap();
/// assert_eq!(result, expected);
///
///
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[2, 3],
/// ).unwrap();
/// let result = resize(&a, &[2, 2]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 4, 4, 5, 5, 6, 6]), &[4, 6]).unwrap();
/// assert_eq!(result, expected);
///
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::resize;
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4]),
/// &[2, 2],
/// ).unwrap();
/// let result = resize(&a, &[2, 2]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4]), &[4, 4]).unwrap();
/// assert_eq!(result, expected);
///
///
/// let a = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[3, 2],
/// ).unwrap();
/// let result = resize(&a, &[2, 3]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 5, 5, 5, 6, 6, 6]), &[6, 6]).unwrap();
/// assert_eq!(result, expected);
///
///
/// ```
pub fn resize<T: TensorType + Send + Sync>(
a: &Tensor<T>,
scales: &[usize],
) -> Result<Tensor<T>, TensorError> {
let mut new_shape = vec![];
for (s, d) in scales.iter().zip(a.dims()) {
new_shape.push(s * d);
}
let mut output = Tensor::new(None, &new_shape)?;
let cartesian_coord: Vec<Vec<usize>> = new_shape
.iter()
.map(|d| (0..*d))
.multi_cartesian_product()
.collect();
// resize using nearest neighbour interpolation
// (i.e. just copy the value of the nearest neighbour to pad the tensor)
output = output.par_enum_map(|i, _| {
let mut coord = vec![];
for (j, (c, _d)) in cartesian_coord[i].iter().zip(new_shape.iter()).enumerate() {
let scale = scales[j];
let fragment = c / scale;
coord.push(fragment);
}
Ok::<_, TensorError>(a.get(&coord))
})?;
Ok(output)
}
/// Adds multiple tensors.
/// # Arguments
///
/// * `t` - Vector of tensors
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::add;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i128>::new(
/// Some(&[2, 3, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = add(&[x, k]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[4, 4, 4, 2, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 1D casting
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i128>::new(
/// Some(&[2]),
/// &[1]).unwrap();
/// let result = add(&[x, k]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[4, 3, 4, 3, 3, 3]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn add<T: TensorType + Add<Output = T> + std::marker::Send + std::marker::Sync>(
t: &[Tensor<T>],
) -> Result<Tensor<T>, TensorError> {
// calculate value of output
let mut output: Tensor<T> = t[0].clone();
for e in t[1..].iter() {
output = output.add(e.clone())?;
}
Ok(output)
}
/// Subtracts multiple tensors.
/// # Arguments
///
/// * `a` - Tensor
/// * `b` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::sub;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i128>::new(
/// Some(&[2, 3, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = sub(&[x, k]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, -2, 0, 0, 0, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 1D sub
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i128>::new(
/// Some(&[2]),
/// &[1],
/// ).unwrap();
/// let result = sub(&[x, k]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, -1, 0, -1, -1, -1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn sub<T: TensorType + Sub<Output = T> + std::marker::Send + std::marker::Sync>(
t: &[Tensor<T>],
) -> Result<Tensor<T>, TensorError> {
// calculate value of output
let mut output: Tensor<T> = t[0].clone();
for e in t[1..].iter() {
output = (output - e.clone())?;
}
Ok(output)
}
/// Elementwise multiplies multiple tensors.
/// # Arguments
///
/// * `t` - Tensors
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::mult;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i128>::new(
/// Some(&[2, 3, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = mult(&[x, k]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[4, 3, 4, 1, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// // Now test 1D mult
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = Tensor::<i128>::new(
/// Some(&[2]),
/// &[1]).unwrap();
/// let result = mult(&[x, k]).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[4, 2, 4, 2, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn mult<T: TensorType + Mul<Output = T> + std::marker::Send + std::marker::Sync>(
t: &[Tensor<T>],
) -> Result<Tensor<T>, TensorError> {
// calculate value of output
let mut output: Tensor<T> = t[0].clone();
for e in t[1..].iter() {
output = (output * e.clone())?;
}
Ok(output)
}
/// Downsamples a tensor along a dimension.
/// # Arguments
/// * `input` - Tensor
/// * `dim` - Dimension to downsample along
/// * `stride` - Stride to downsample by
/// * `modulo` - Modulo to downsample by
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::downsample;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[2, 3],
/// ).unwrap();
/// let result = downsample(&x, 0, 1, 1).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[4, 5, 6]), &[1, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = downsample(&x, 1, 2, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 3, 4, 6]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = downsample(&x, 1, 2, 1).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 5]), &[2, 1]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = downsample(&x, 1, 2, 2).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[3, 6]), &[2, 1]).unwrap();
/// assert_eq!(result, expected);
pub fn downsample<T: TensorType + Send + Sync>(
input: &Tensor<T>,
dim: usize,
stride: usize,
modulo: usize,
) -> Result<Tensor<T>, TensorError> {
let mut output_shape = input.dims().to_vec();
// now downsample along axis dim offset by modulo, rounding up (+1 if remaidner is non-zero)
let remainder = (input.dims()[dim] - modulo) % stride;
let div = (input.dims()[dim] - modulo) / stride;
output_shape[dim] = div + (remainder > 0) as usize;
let mut output = Tensor::<T>::new(None, &output_shape)?;
if modulo > input.dims()[dim] {
return Err(TensorError::DimMismatch("downsample".to_string()));
}
// now downsample along axis dim offset by modulo
let indices = (0..output_shape.len())
.map(|i| {
if i == dim {
let mut index = vec![0; output_shape[i]];
for (i, idx) in index.iter_mut().enumerate() {
*idx = i * stride + modulo;
}
index
} else {
(0..output_shape[i]).collect_vec()
}
})
.multi_cartesian_product()
.collect::<Vec<_>>();
output = output.par_enum_map(|i, _: T| {
let coord = indices[i].clone();
Ok(input.get(&coord))
})?;
Ok(output)
}
/// Gathers a tensor along a dimension.
/// # Arguments
/// * `input` - Tensor
/// * `dim` - Dimension to gather along
/// * `index` - Tensor of indices to gather
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::gather;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[2, 3],
/// ).unwrap();
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1]),
/// &[2],
/// ).unwrap();
/// let result = gather(&x, &index, 1).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 4, 5]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn gather<T: TensorType + Send + Sync>(
input: &Tensor<T>,
index: &Tensor<usize>,
dim: usize,
) -> Result<Tensor<T>, TensorError> {
let mut index_clone = index.clone();
index_clone.flatten();
if index_clone.is_singleton() {
index_clone.reshape(&[1])?;
}
// Calculate the output tensor size
let mut output_size = input.dims().to_vec();
output_size[dim] = index_clone.dims()[0];
// Allocate memory for the output tensor
let mut output = Tensor::new(None, &output_size)?;
let cartesian_coord = output_size
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
output = output.par_enum_map(|i, _: T| {
let coord = cartesian_coord[i].clone();
let index_val = index_clone.get(&[coord[dim]]);
let new_coord = coord
.iter()
.enumerate()
.map(|(i, x)| if i == dim { index_val } else { *x })
.collect::<Vec<_>>();
Ok(input.get(&new_coord))
})?;
// Reshape the output tensor
if index.is_singleton() {
output_size.remove(dim);
}
output.reshape(&output_size)?;
Ok(output)
}
/// Scatters a tensor along a dimension.
/// # Arguments
/// * `input` - Tensor
/// * `dim` - Dimension to scatter along
/// * `index` - Tensor of indices to scatter
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::scatter;
/// let x = Tensor::<f64>::new(
/// Some(&[1.0, 2.0, 3.0, 4.0]),
/// &[2, 2],
/// ).unwrap();
/// let src = Tensor::<f64>::new(
/// Some(&[5.0, 6.0, 7.0, 8.0]),
/// &[2, 2],
/// ).unwrap();
/// let index = Tensor::<usize>::new(
/// Some(&[0, 0, 1, 0]),
/// &[2, 2],
/// ).unwrap();
/// let result = scatter(&x, &index, &src, 0).unwrap();
/// let expected = Tensor::<f64>::new(Some(&[5.0, 8.0, 7.0, 4.0]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn scatter<T: TensorType + Send + Sync>(
input: &Tensor<T>,
index: &Tensor<usize>,
src: &Tensor<T>,
dim: usize,
) -> Result<Tensor<T>, TensorError> {
// Writes all values from the tensor src into self at the indices specified in the index tensor.
// For each value in src, its output index is specified by its index in src for dimension != dim and by the corresponding value in index for dimension = dim.
assert_eq!(index.dims(), src.dims());
// Calculate the output tensor size
let src_size = src.dims().to_vec();
// For a 3-D tensor, self is updated as:
// self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0
// self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1
// self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2
let mut output = input.clone();
let cartesian_coord = src_size
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
cartesian_coord.iter().for_each(|coord| {
let mut new_coord = coord.clone();
let index_val = index.get(coord);
new_coord[dim] = index_val;
let val = src.get(coord);
output.set(&new_coord, val);
});
Ok(output)
}
/// Gathers a tensor along a dimension.
/// # Arguments
/// * `input` - Tensor
/// * `dim` - Dimension to gather along
/// * `index` - Tensor of indices to gather
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::gather_elements;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4]),
/// &[2, 2],
/// ).unwrap();
/// let index = Tensor::<usize>::new(
/// Some(&[0, 0, 1, 0]),
/// &[2, 2],
/// ).unwrap();
/// let result = gather_elements(&x, &index, 1).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 4, 3]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn gather_elements<T: TensorType + Send + Sync>(
input: &Tensor<T>,
index: &Tensor<usize>,
dim: usize,
) -> Result<Tensor<T>, TensorError> {
// Calculate the output tensor size
let output_size = index.dims().to_vec();
// same rank
assert_eq!(input.dims().len(), index.dims().len());
// Allocate memory for the output tensor
let mut output = Tensor::new(None, &output_size)?;
let cartesian_coord = output_size
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
output = output.par_enum_map(|i, _: T| {
let coord = cartesian_coord[i].clone();
let index_val = index.get(&coord);
let mut new_coord = coord.clone();
new_coord[dim] = index_val;
let val = input.get(&new_coord);
Ok(val)
})?;
// Reshape the output tensor
output.reshape(&output_size)?;
Ok(output)
}
/// Gather ND.
/// # Arguments
/// * `input` - Tensor
/// * `index` - Tensor of indices to gather
/// * `batch_dims` - Number of batch dimensions
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::gather_nd;
/// let x = Tensor::<i128>::new(
/// Some(&[0, 1, 2, 3]),
/// &[2, 2],
/// ).unwrap();
/// let index = Tensor::<usize>::new(
/// Some(&[0, 0, 1, 1]),
/// &[2, 2],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 3]), &[2]).unwrap();
/// assert_eq!(result, expected);
///
/// let index = Tensor::<usize>::new(
/// Some(&[1, 0]),
/// &[2, 1],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 3, 0, 1]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let x = Tensor::<i128>::new(
/// Some(&[0, 1, 2, 3, 4, 5, 6, 7]),
/// &[2, 2, 2],
/// ).unwrap();
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1, 1, 0]),
/// &[2, 2],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1, 1, 0]),
/// &[2, 1, 2],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 1, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let index = Tensor::<usize>::new(
/// Some(&[1, 0]),
/// &[2, 1],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 1).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1]),
/// &[2, 2, 3],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 3, 4, 5]), &[2, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1, 0, 0, 1, 1, 1, 0]),
/// &[2, 2, 2],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 3, 0, 1, 6, 7, 4, 5]), &[2, 2, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1, 0, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = gather_nd(&x, &index, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 7]), &[2]).unwrap();
/// assert_eq!(result, expected);
///
pub fn gather_nd<T: TensorType + Send + Sync>(
input: &Tensor<T>,
index: &Tensor<usize>,
batch_dims: usize,
) -> Result<Tensor<T>, TensorError> {
// Calculate the output tensor size
let index_dims = index.dims().to_vec();
let input_dims = input.dims().to_vec();
let last_value = index_dims
.last()
.ok_or(TensorError::DimMismatch("gather_nd".to_string()))?;
if last_value > &(input_dims.len() - batch_dims) {
return Err(TensorError::DimMismatch("gather_nd".to_string()));
}
let output_size =
// If indices_shape[-1] == r-b, since the rank of indices is q,
// indices can be thought of as N (q-b-1)-dimensional tensors containing 1-D tensors of dimension r-b,
// where N is an integer equals to the product of 1 and all the elements in the batch dimensions of the indices_shape.
// Let us think of each such r-b ranked tensor as indices_slice.
// Each scalar value corresponding to data[0:b-1,indices_slice] is filled into
// the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor
// if indices_shape[-1] < r-b, since the rank of indices is q, indices can be thought of as N (q-b-1)-dimensional tensor containing 1-D tensors of dimension < r-b.
// Let us think of each such tensors as indices_slice.
// Each tensor slice corresponding to data[0:b-1, indices_slice , :] is filled into the corresponding location of the (q-b-1)-dimensional tensor to form the output tensor
{
let output_rank = input_dims.len() + index_dims.len() - 1 - batch_dims - last_value;
let mut dims = index_dims[..index_dims.len() - 1].to_vec();
let input_offset = batch_dims + last_value;
dims.extend(input_dims[input_offset..input_dims.len()].to_vec());
assert_eq!(output_rank, dims.len());
dims
};
// cartesian coord over batch dims
let mut batch_cartesian_coord = input_dims[0..batch_dims]
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
if batch_cartesian_coord.is_empty() {
batch_cartesian_coord.push(vec![]);
}
let outputs = batch_cartesian_coord
.par_iter()
.map(|batch_coord| {
let batch_slice = batch_coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();
let mut index_slice = index.get_slice(&batch_slice)?;
index_slice.reshape(&index.dims()[batch_dims..])?;
let mut input_slice = input.get_slice(&batch_slice)?;
input_slice.reshape(&input.dims()[batch_dims..])?;
let mut inner_cartesian_coord = index_slice.dims()[0..index_slice.dims().len() - 1]
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
if inner_cartesian_coord.is_empty() {
inner_cartesian_coord.push(vec![]);
}
let output = inner_cartesian_coord
.iter()
.map(|coord| {
let slice = coord
.iter()
.map(|x| *x..*x + 1)
.chain(batch_coord.iter().map(|x| *x..*x + 1))
.collect::<Vec<_>>();
let index_slice = index_slice
.get_slice(&slice)
.unwrap()
.iter()
.map(|x| *x..*x + 1)
.collect::<Vec<_>>();
input_slice.get_slice(&index_slice).unwrap()
})
.collect::<Tensor<_>>();
output.combine()
})
.collect::<Result<Vec<_>, _>>()?;
let mut outputs = outputs.into_iter().flatten().collect::<Tensor<_>>();
outputs.reshape(&output_size)?;
Ok(outputs)
}
/// Scatter ND.
/// This operator is the inverse of GatherND.
/// # Arguments
/// * `input` - Tensor
/// * `index` - Tensor of indices to scatter
/// * `src` - Tensor of src
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::scatter_nd;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6, 7, 8]),
/// &[8],
/// ).unwrap();
///
/// let index = Tensor::<usize>::new(
/// Some(&[4, 3, 1, 7]),
/// &[4, 1],
/// ).unwrap();
/// let src = Tensor::<i128>::new(
/// Some(&[9, 10, 11, 12]),
/// &[4],
/// ).unwrap();
/// let result = scatter_nd(&x, &index, &src).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 11, 3, 10, 9, 6, 7, 12]), &[8]).unwrap();
/// assert_eq!(result, expected);
///
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1,
/// 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1,
/// 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8,
/// 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8]),
/// &[4, 4, 4],
/// ).unwrap();
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 2]),
/// &[2, 1],
/// ).unwrap();
///
/// let src = Tensor::<i128>::new(
/// Some(&[5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
/// 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,
/// ]),
/// &[2, 4, 4],
/// ).unwrap();
///
/// let result = scatter_nd(&x, &index, &src).unwrap();
///
/// let expected = Tensor::<i128>::new(
/// Some(&[5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
/// 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1,
/// 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,
/// 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8]),
/// &[4, 4, 4],
/// ).unwrap();
/// assert_eq!(result, expected);
///
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6, 7, 8]),
/// &[2, 4],
/// ).unwrap();
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1]),
/// &[2, 1],
/// ).unwrap();
/// let src = Tensor::<i128>::new(
/// Some(&[9, 10]),
/// &[2],
/// ).unwrap();
/// let result = scatter_nd(&x, &index, &src).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[9, 9, 9, 9, 10, 10, 10, 10]), &[2, 4]).unwrap();
/// assert_eq!(result, expected);
///
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6, 7, 8]),
/// &[2, 4],
/// ).unwrap();
///
/// let index = Tensor::<usize>::new(
/// Some(&[0, 1]),
/// &[1, 1, 2],
/// ).unwrap();
/// let src = Tensor::<i128>::new(
/// Some(&[9]),
/// &[1, 1],
/// ).unwrap();
/// let result = scatter_nd(&x, &index, &src).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 9, 3, 4, 5, 6, 7, 8]), &[2, 4]).unwrap();
/// assert_eq!(result, expected);
/// ````
///
pub fn scatter_nd<T: TensorType + Send + Sync>(
input: &Tensor<T>,
index: &Tensor<usize>,
src: &Tensor<T>,
) -> Result<Tensor<T>, TensorError> {
// Calculate the output tensor size
let index_dims = index.dims().to_vec();
let input_dims = input.dims().to_vec();
let last_value = index_dims
.last()
.ok_or(TensorError::DimMismatch("scatter_nd".to_string()))?;
if last_value > &input_dims.len() {
return Err(TensorError::DimMismatch("scatter_nd".to_string()));
}
let mut output = input.clone();
let cartesian_coord = index_dims[0..index_dims.len() - 1]
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
cartesian_coord
.iter()
.map(|coord| {
let slice = coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();
let index_val = index.get_slice(&slice)?;
let index_slice = index_val.iter().map(|x| *x..*x + 1).collect::<Vec<_>>();
let src_val = src.get_slice(&slice)?;
output.set_slice(&index_slice, &src_val)?;
Ok(())
})
.collect::<Result<Vec<_>, _>>()?;
Ok(output)
}
/// Abs a tensor.
/// # Arguments
/// * `a` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::abs;
/// let x = Tensor::<i128>::new(
/// Some(&[-2, 15, 2, -1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = abs(&x).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 15, 2, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn abs<T: TensorType + Add<Output = T> + std::cmp::Ord + Neg<Output = T>>(
a: &Tensor<T>,
) -> Result<Tensor<T>, TensorError> {
// calculate value of output
let mut output: Tensor<T> = a.clone();
output.iter_mut().for_each(|a_i| {
if *a_i < T::zero().unwrap() {
*a_i = -a_i.clone();
}
});
Ok(output)
}
/// Intercalates values into a tensor along a given axis.
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::intercalate_values;
///
/// let tensor = Tensor::<i128>::new(Some(&[1, 2, 3, 4]), &[2, 2]).unwrap();
/// let result = intercalate_values(&tensor, 0, 2, 1).unwrap();
///
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 2, 3, 0, 4]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// let result = intercalate_values(&expected, 0, 2, 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 2, 0, 0, 0, 3, 0, 4]), &[3, 3]).unwrap();
///
/// assert_eq!(result, expected);
///
/// ```
pub fn intercalate_values<T: TensorType>(
tensor: &Tensor<T>,
value: T,
stride: usize,
axis: usize,
) -> Result<Tensor<T>, TensorError> {
if stride == 1 {
return Ok(tensor.clone());
}
let mut output_dims = tensor.dims().to_vec();
output_dims[axis] = output_dims[axis] * stride - 1;
let mut output: Tensor<T> = Tensor::new(None, &output_dims)?;
let cartesian_coord = output
.dims()
.iter()
.map(|d| (0..*d))
.multi_cartesian_product()
.collect::<Vec<_>>();
let mut tensor_slice_iter = tensor.iter();
output.iter_mut().enumerate().for_each(|(i, o)| {
let coord = &cartesian_coord[i];
if coord[axis] % stride == 0 {
*o = tensor_slice_iter.next().unwrap().clone();
} else {
*o = value.clone();
}
});
Ok(output)
}
/// One hot encodes a tensor along a given axis.
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::one_hot;
/// let tensor = Tensor::<i128>::new(Some(&[1, 2, 3, 4]), &[2, 2]).unwrap();
/// let result = one_hot(&tensor, 5, 2).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 0, 0,
/// 0, 0, 1, 0, 0,
/// 0, 0, 0, 1, 0,
/// 0, 0, 0, 0, 1]), &[2, 2, 5]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn one_hot(
tensor: &Tensor<i128>,
num_classes: usize,
axis: usize,
) -> Result<Tensor<i128>, TensorError> {
let mut output_dims = tensor.dims().to_vec();
output_dims.insert(axis, num_classes);
let mut output: Tensor<i128> = Tensor::new(None, &output_dims)?;
let cartesian_coord = output
.dims()
.iter()
.map(|d| (0..*d))
.multi_cartesian_product()
.collect::<Vec<_>>();
output
.iter_mut()
.enumerate()
.map(|(i, o)| {
let coord = &cartesian_coord[i];
let coord_axis = coord[axis];
let mut coord_without_axis = coord.clone();
coord_without_axis.remove(axis);
let elem = tensor.get(&coord_without_axis) as usize;
if elem > num_classes {
return Err(TensorError::DimMismatch(format!(
"Expected element to be less than num_classes, but got {}",
elem
)));
};
if coord_axis == elem {
*o = 1;
} else {
*o = 0;
}
Ok(())
})
.collect::<Result<Vec<()>, TensorError>>()?;
Ok(output)
}
/// Pads a ND tensor of shape `B x C x H x D1 x D2 x ...` along all dimensions.
/// # Arguments
///
/// * `image` - Tensor.
/// * `padding` - Tuple of padding values in x and y directions.
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::pad;
///
/// let x = Tensor::<i128>::new(
/// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]),
/// &[1, 1, 3, 3],
/// ).unwrap();
/// let result = pad::<i128>(&x, vec![(0, 0), (0, 0), (1, 1), (1, 1)], 0).unwrap();
/// let expected = Tensor::<i128>::new(
/// Some(&[0, 0, 0, 0, 0, 0, 5, 2, 3, 0, 0, 0, 4, -1, 0, 0, 3, 1, 6, 0, 0, 0, 0, 0, 0]),
/// &[1, 1, 5, 5],
/// ).unwrap();
/// assert_eq!(result, expected);
///
/// let result = pad::<i128>(&x, vec![(1, 1), (1, 1)], 2).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn pad<T: TensorType>(
image: &Tensor<T>,
padding: Vec<(usize, usize)>,
offset: usize,
) -> Result<Tensor<T>, TensorError> {
let padded_dims = image.dims()[offset..]
.iter()
.enumerate()
.map(|(i, d)| d + padding[i].0 + padding[i].1)
.collect::<Vec<_>>();
let mut output_dims = image.dims()[..offset].to_vec();
output_dims.extend(padded_dims);
let mut output = Tensor::<T>::new(None, &output_dims).unwrap();
let cartesian_coord = image
.dims()
.iter()
.map(|d| (0..*d))
.multi_cartesian_product()
.collect::<Vec<_>>();
for coord in cartesian_coord {
let rest = &coord[offset..];
let mut padded_res = coord[..offset].to_vec();
padded_res.extend(rest.iter().zip(padding.iter()).map(|(c, p)| c + p.0));
let image_val = image.get(&coord);
output.set(&padded_res, image_val);
}
output.reshape(&output_dims)?;
Ok(output)
}
/// Concatenates a list of tensors along a specified axis.
/// # Arguments
/// * `inputs` - A slice of tensors to concatenate.
/// * `axis` - The axis along which to concatenate the tensors.
///
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::concat;
/// // tested against pytorch outputs for reference :)
///
/// // 1D example
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3]), &[3]).unwrap();
/// let y = Tensor::<i128>::new(Some(&[4, 5, 6]), &[3]).unwrap();
/// let result = concat(&[&x, &y], 0).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[6]).unwrap();
/// assert_eq!(result, expected);
///
/// // 2D example
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 2]).unwrap();
/// let y = Tensor::<i128>::new(Some(&[7, 8, 9]), &[3, 1]).unwrap();
/// let result = concat(&[&x, &y], 1).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 7, 3, 4, 8, 5, 6, 9]), &[3, 3]).unwrap();
/// assert_eq!(result, expected);
///
/// /// 4D example
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), &[2, 2, 2, 2]).unwrap();
/// let y = Tensor::<i128>::new(Some(&[17, 18, 19, 20, 21, 22, 23, 14]), &[2, 2, 1, 2]).unwrap();
/// let result = concat(&[&x, &y], 2).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 17, 18, 5, 6, 7, 8, 19, 20, 9, 10, 11, 12, 21, 22, 13, 14, 15, 16, 23, 14]), &[2, 2, 3, 2]).unwrap();
/// assert_eq!(result, expected);
///
///
/// // 5D example
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), &[8, 1, 1, 1, 2]).unwrap();
/// let y = Tensor::<i128>::new(Some(&[17, 18, 19, 20, 21, 22, 23, 14]), &[4, 1, 1, 1, 2]).unwrap();
/// let result = concat(&[&x, &y], 0).unwrap();
///
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 14]), &[12, 1, 1, 1, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// ```
///
/// # Errors
/// Returns a TensorError if the tensors in `inputs` have incompatible dimensions for concatenation along the specified `axis`.
pub fn concat<T: TensorType + Send + Sync>(
inputs: &[&Tensor<T>],
axis: usize,
) -> Result<Tensor<T>, TensorError> {
if inputs.len() == 1 {
return Ok(inputs[0].clone());
}
// Calculate the output tensor size
let mut output_size = inputs[0].dims().to_vec();
output_size[axis] = inputs.iter().map(|x| x.dims()[axis]).sum();
// Allocate memory for the output tensor
let mut output = Tensor::new(None, &output_size)?;
let cartesian_coord = output_size
.iter()
.map(|x| 0..*x)
.multi_cartesian_product()
.collect::<Vec<_>>();
let get_input_index = |index_along_axis: usize| -> (usize, usize) {
let mut current_idx = 0;
let mut input_idx = 0;
let mut input_coord_at_idx = 0;
for (i, elem) in inputs.iter().enumerate() {
current_idx += elem.dims()[axis];
if index_along_axis < current_idx {
input_idx = i;
// subtract the current
input_coord_at_idx = index_along_axis - (current_idx - elem.dims()[axis]);
break;
}
}
(input_idx, input_coord_at_idx)
};
output = output.par_enum_map(|i, _: T| {
let coord = cartesian_coord[i].clone();
let mut index = 0;
let mut input_index = 0;
let mut input_coord = coord.clone();
for (j, x) in coord.iter().enumerate() {
if j == axis {
(input_index, input_coord[j]) = get_input_index(*x);
break;
}
index += x;
}
Ok(inputs[input_index].get(&input_coord))
})?;
// Reshape the output tensor
output.reshape(&output_size)?;
Ok(output)
}
/// Slices a tensor from start to end along a given axis
///
/// /// # Examples
/// ```
/// // tested against pytorch output
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::slice;
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 2]).unwrap();
/// let result = slice(&x, &0, &1, &2).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[3, 4]), &[1, 2]).unwrap();
/// assert_eq!(result, expected);
///
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6]), &[3, 2]).unwrap();
/// let result = slice(&x, &1, &1, &2).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 4, 6]), &[3, 1]).unwrap();
/// assert_eq!(result, expected);
///
/// let x = Tensor::<i128>::new(Some(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), &[2, 2, 3]).unwrap();
/// let result = slice(&x, &2, &1, &2).unwrap();
/// let expected = Tensor::<i128>::new(Some(&[2, 5, 8, 11]), &[2, 2, 1]).unwrap();
/// assert_eq!(result, expected);
/// ```
///
pub fn slice<T: TensorType + Send + Sync>(
t: &Tensor<T>,
axis: &usize,
start: &usize,
end: &usize,
) -> Result<Tensor<T>, TensorError> {
let mut slice = vec![];
for (i, d) in t.dims().iter().enumerate() {
if i != *axis {
slice.push(0..*d)
} else {
slice.push(*start..*end)
}
}
t.get_slice(&slice)
}
// ---------------------------------------------------------------------------------------------------------
// -- nonlinear Functions ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
/// Activation functions
pub mod nonlinearities {
use super::*;
/// Ceiling operator.
/// # Arguments
/// * `a` - Tensor
/// * `scale` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
///
/// use ezkl::tensor::ops::nonlinearities::ceil;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[3, 2],
/// ).unwrap();
/// let result = ceil(&x, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[2, 2, 4, 4, 6, 6]), &[3, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn ceil(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale;
let rounded = kix.ceil() * scale;
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Floor operator.
/// # Arguments
/// * `a` - Tensor
/// * `scale` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::floor;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[3, 2],
/// ).unwrap();
/// let result = floor(&x, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[0, 2, 2, 4, 4, 6]), &[3, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn floor(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale;
let rounded = kix.floor() * scale;
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Round operator.
/// # Arguments
/// * `a` - Tensor
/// * `scale` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::round;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[3, 2],
/// ).unwrap();
/// let result = round(&x, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[2, 2, 4, 4, 6, 6]), &[3, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn round(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale;
let rounded = kix.round() * scale;
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Round half to even operator.
/// # Arguments
/// * `a` - Tensor
/// * `scale` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::round_half_to_even;
/// let x = Tensor::<i128>::new(
/// Some(&[1, 2, 3, 4, 5, 6]),
/// &[3, 2],
/// ).unwrap();
/// let result = round_half_to_even(&x, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[0, 2, 4, 4, 4, 6]), &[3, 2]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn round_half_to_even(a: &Tensor<i128>, scale: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale;
let rounded = kix.round_ties_even() * scale;
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Raises to a floating point power.
/// # Arguments
/// * `a` - Tensor
/// * `power` - Floating point power
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::pow;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = pow(&x, 1.0, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 225, 4, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn pow(a: &Tensor<i128>, scale_input: f64, power: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let kix = scale_input * (kix).powf(power);
let rounded = kix.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Applies Kronecker delta to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::kronecker_delta;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = kronecker_delta(&x);
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 0, 0, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn kronecker_delta<T: TensorType + std::cmp::PartialEq + Send + Sync>(
a: &Tensor<T>,
) -> Tensor<T> {
a.par_enum_map(|_, a_i| {
if a_i == T::zero().unwrap() {
Ok::<_, TensorError>(T::one().unwrap())
} else {
Ok::<_, TensorError>(T::zero().unwrap())
}
})
.unwrap()
}
/// Elementwise applies sigmoid to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::sigmoid;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = sigmoid(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 1, 1, 1]), &[2, 3]).unwrap();
///
/// assert_eq!(result, expected);
/// let x = Tensor::<i128>::new(
/// Some(&[65536]),
/// &[1],
/// ).unwrap();
/// let result = sigmoid(&x, 65536.0);
/// let expected = Tensor::<i128>::new(Some(&[47911]), &[1]).unwrap();
/// assert_eq!(result, expected);
///
/// /// assert_eq!(result, expected);
/// let x = Tensor::<i128>::new(
/// Some(&[256]),
/// &[1],
/// ).unwrap();
/// let result = sigmoid(&x, 256.0);
/// let expected = Tensor::<i128>::new(Some(&[187]), &[1]).unwrap();
///
/// ```
pub fn sigmoid(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input / (1.0 + (-kix).exp());
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies hardswish to a tensor of integers.
/// Hardswish is defined as:
// Hardswish(x)={0if x≤−3,xif x≥+3,x⋅(x+3)/6otherwise
// Hardswish(x)=⎩
// ⎨
// ⎧0xx⋅(x+3)/6if x≤−3,if x≥+3,otherwise
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::hardswish;
/// let x = Tensor::<i128>::new(
/// Some(&[-12, -3, 2, 1, 1, 15]),
/// &[2, 3],
/// ).unwrap();
/// let result = hardswish(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 2, 1, 1, 15]), &[2, 3]).unwrap();
///
/// assert_eq!(result, expected);
///
/// ```
pub fn hardswish(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let res = if kix <= -3.0 {
0.0
} else if kix >= 3.0 {
kix
} else {
kix * (kix + 3.0) / 6.0
};
let rounded = (res * scale_input).round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies exponential to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::exp;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = exp(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[7, 3269017, 7, 3, 3, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
///
/// let x = Tensor::<i128>::new(
/// Some(&[37, 12, 41]),
/// &[3],
/// ).unwrap();
/// let result = exp(&x, 512.0);
///
/// let expected = Tensor::<i128>::new(Some(&[550, 524, 555]), &[3]).unwrap();
///
/// assert_eq!(result, expected);
/// ```
pub fn exp(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.exp();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies exponential to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::ln;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 3000]),
/// &[2, 3],
/// ).unwrap();
/// let result = ln(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[1, 3, 1, 0, 0, 8]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
///
///
/// let x = Tensor::<i128>::new(
/// Some(&[37, 12, 41]),
/// &[3],
/// ).unwrap();
/// let result = ln(&x, 512.0);
///
/// let expected = Tensor::<i128>::new(Some(&[-1345, -1922, -1293]), &[3]).unwrap();
///
/// assert_eq!(result, expected);
/// ```
pub fn ln(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.ln();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies sign to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::sign;
/// let x = Tensor::<i128>::new(
/// Some(&[-2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = sign(&x);
/// let expected = Tensor::<i128>::new(Some(&[-1, 1, 1, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn sign(a: &Tensor<i128>) -> Tensor<i128> {
a.par_enum_map(|_, a_i| Ok::<_, TensorError>(a_i.signum()))
.unwrap()
}
/// Elementwise applies square root to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::sqrt;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = sqrt(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[2, 5, 3, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn sqrt(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.sqrt();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies reciprocal square root to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::rsqrt;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let result = rsqrt(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 0, 1, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn rsqrt(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input / (kix.sqrt() + f64::EPSILON);
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies cosine to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::cos;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = cos(&x, 2.0);
/// let expected = Tensor::<i128>::new(Some(& [-1, 2, -1, 2, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn cos(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.cos();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies arccosine to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::acos;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = acos(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 0, 0, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn acos(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.acos();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies cosh to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::cosh;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = cosh(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[27, 36002449669, 1490, 2, 2, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn cosh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.cosh();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies arccosineh to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::acosh;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = acosh(&x, 1.0);
/// let expected = Tensor::<i128>::new(Some(& [2, 4, 3, 0, 0, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn acosh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.acosh();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies sine to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::sin;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = sin(&x, 128.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn sin(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.sin();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies arcsine to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::asin;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = asin(&x, 128.0);
/// let expected = Tensor::<i128>::new(Some(& [4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn asin(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.asin();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies sineh to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::sinh;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = sinh(&x, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[7, 268337, 55, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn sinh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.sinh();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies arcsineh to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::asinh;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = asinh(&x, 128.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn asinh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.asinh();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies tan activation to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::tan;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = tan(&x, 64.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 26, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn tan(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.tan();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies arctan activation to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::atan;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = atan(&x, 128.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn atan(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.atan();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies tanh activation to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::tanh;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = tanh(&x, 128.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 25, 8, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn tanh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.tanh();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies arctanh activation to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::atanh;
/// let x = Tensor::<i128>::new(
/// Some(&[4, 25, 8, 2, 2, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = atanh(&x, 32.0);
/// let expected = Tensor::<i128>::new(Some(&[4, 34, 8, 2, 2, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn atanh(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * kix.atanh();
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Applies error function (erf) on a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale_input` - Single value
/// * `scale_output` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::erffunc;
/// let x = Tensor::<i128>::new(
/// Some(&[5, 28, 9, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = erffunc(&x, 128.0);
/// let expected = Tensor::<i128>::new(Some(&[6, 31, 10, 1, 1, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn erffunc(a: &Tensor<i128>, scale_input: f64) -> Tensor<i128> {
const NCOEF: usize = 28;
const COF: [f64; 28] = [
-1.3026537197817094,
6.419_697_923_564_902e-1,
1.9476473204185836e-2,
-9.561_514_786_808_63e-3,
-9.46595344482036e-4,
3.66839497852761e-4,
4.2523324806907e-5,
-2.0278578112534e-5,
-1.624290004647e-6,
1.303655835580e-6,
1.5626441722e-8,
-8.5238095915e-8,
6.529054439e-9,
5.059343495e-9,
-9.91364156e-10,
-2.27365122e-10,
9.6467911e-11,
2.394038e-12,
-6.886027e-12,
8.94487e-13,
3.13092e-13,
-1.12708e-13,
3.81e-16,
7.106e-15,
-1.523e-15,
-9.4e-17,
1.21e-16,
-2.8e-17,
];
/// Chebyshev coefficients
fn erfccheb(z: f64) -> f64 {
let mut d = 0f64;
let mut dd = 0f64;
assert!(z >= 0f64, "erfccheb requires nonnegative argument");
let t = 2f64 / (2f64 + z);
let ty = 4f64 * t - 2f64;
for j in (1..NCOEF - 1).rev() {
let tmp = d;
d = ty * d - dd + COF[j];
dd = tmp;
}
t * (-z.powi(2) + 0.5 * (COF[0] + ty * d) - dd).exp()
}
pub fn erf(x: f64) -> f64 {
if x >= 0f64 {
1.0 - erfccheb(x)
} else {
erfccheb(-x) - 1f64
}
}
a.par_enum_map(|_, a_i| {
let kix = (a_i as f64) / scale_input;
let fout = scale_input * erf(kix);
let rounded = fout.round();
Ok::<_, TensorError>(rounded as i128)
})
.unwrap()
}
/// Elementwise applies leaky relu to a tensor of integers.
/// # Arguments
///
/// * `a` - Tensor
/// * `scale` - Single value
/// * `slope` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::leakyrelu;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, -5]),
/// &[2, 3],
/// ).unwrap();
/// let result = leakyrelu(&x, 0.1);
/// let expected = Tensor::<i128>::new(Some(&[2, 15, 2, 1, 1, -1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn leakyrelu(a: &Tensor<i128>, slope: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let rounded = if a_i < 0 {
let d_inv_x = (slope) * (a_i as f64);
d_inv_x.round() as i128
} else {
let d_inv_x = a_i as f64;
d_inv_x.round() as i128
};
Ok::<_, TensorError>(rounded)
})
.unwrap()
}
/// Elementwise applies max to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `b` - scalar
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::max;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, -5]),
/// &[2, 3],
/// ).unwrap();
/// let result = max(&x, 1.0, 1.0);
/// let expected = Tensor::<i128>::new(Some(&[2, 15, 2, 1, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn max(a: &Tensor<i128>, scale_input: f64, threshold: f64) -> Tensor<i128> {
// calculate value of output
a.par_enum_map(|_, a_i| {
let d_inv_x = (a_i as f64) / scale_input;
let rounded = if d_inv_x <= threshold {
(threshold * scale_input).round() as i128
} else {
(d_inv_x * scale_input).round() as i128
};
Ok::<_, TensorError>(rounded)
})
.unwrap()
}
/// Elementwise applies min to a tensor of integers.
/// # Arguments
/// * `a` - Tensor
/// * `b` - scalar
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::min;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, -5]),
/// &[2, 3],
/// ).unwrap();
/// let result = min(&x, 1.0, 2.0);
/// let expected = Tensor::<i128>::new(Some(&[2, 2, 2, 1, 1, -5]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn min(a: &Tensor<i128>, scale_input: f64, threshold: f64) -> Tensor<i128> {
// calculate value of output
a.par_enum_map(|_, a_i| {
let d_inv_x = (a_i as f64) / scale_input;
let rounded = if d_inv_x >= threshold {
(threshold * scale_input).round() as i128
} else {
(d_inv_x * scale_input).round() as i128
};
Ok::<_, TensorError>(rounded)
})
.unwrap()
}
/// Elementwise divides a tensor with a const integer element.
/// # Arguments
///
/// * `a` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::const_div;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 7, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = 2.0;
/// let result = const_div(&x, k);
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 4, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn const_div(a: &Tensor<i128>, denom: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let d_inv_x = (a_i as f64) / (denom);
Ok::<_, TensorError>(d_inv_x.round() as i128)
})
.unwrap()
}
/// Elementwise inverse.
/// # Arguments
///
/// * `a` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::recip;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 7, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = 2_f64;
/// let result = recip(&x, 1.0, k);
/// let expected = Tensor::<i128>::new(Some(&[1, 2, 1, 0, 2, 2]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn recip(a: &Tensor<i128>, input_scale: f64, out_scale: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| {
let rescaled = (a_i as f64) / input_scale;
let denom = (1_f64) / (rescaled + f64::EPSILON);
let d_inv_x = out_scale * denom;
Ok::<_, TensorError>(d_inv_x.round() as i128)
})
.unwrap()
}
/// Elementwise inverse.
/// # Arguments
/// * `out_scale` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::zero_recip;
/// let k = 2_f64;
/// let result = zero_recip(1.0);
/// let expected = Tensor::<i128>::new(Some(&[4503599627370496]), &[1]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn zero_recip(out_scale: f64) -> Tensor<i128> {
let a = Tensor::<i128>::new(Some(&[0]), &[1]).unwrap();
a.par_enum_map(|_, a_i| {
let rescaled = a_i as f64;
let denom = (1_f64) / (rescaled + f64::EPSILON);
let d_inv_x = out_scale * denom;
Ok::<_, TensorError>(d_inv_x.round() as i128)
})
.unwrap()
}
/// Elementwise greater than
/// # Arguments
///
/// * `a` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::greater_than;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 7, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = 2.0;
/// let result = greater_than(&x, k);
/// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 1, 0, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn greater_than(a: &Tensor<i128>, b: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) > 0_f64)))
.unwrap()
}
/// Elementwise greater than
/// # Arguments
///
/// * `a` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::greater_than_equal;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 7, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = 2.0;
/// let result = greater_than_equal(&x, k);
/// let expected = Tensor::<i128>::new(Some(&[1, 0, 1, 1, 0, 0]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn greater_than_equal(a: &Tensor<i128>, b: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) >= 0_f64)))
.unwrap()
}
/// Elementwise less than
/// # Arguments
/// * `a` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::less_than;
///
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 7, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = 2.0;
///
/// let result = less_than(&x, k);
/// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 0, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn less_than(a: &Tensor<i128>, b: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) < 0_f64)))
.unwrap()
}
/// Elementwise less than
/// # Arguments
/// * `a` - Tensor
/// * `b` - Single value
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::nonlinearities::less_than_equal;
///
/// let x = Tensor::<i128>::new(
/// Some(&[2, 1, 2, 7, 1, 1]),
/// &[2, 3],
/// ).unwrap();
/// let k = 2.0;
///
/// let result = less_than_equal(&x, k);
/// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 0, 1, 1]), &[2, 3]).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn less_than_equal(a: &Tensor<i128>, b: f64) -> Tensor<i128> {
a.par_enum_map(|_, a_i| Ok::<_, TensorError>(i128::from((a_i as f64 - b) <= 0_f64)))
.unwrap()
}
}
/// Ops that return the transcript i.e intermediate calcs of an op
pub mod accumulated {
use super::*;
/// Dot product of two tensors.
/// # Arguments
///
/// * `inputs` - Vector of tensors of length 2.
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::accumulated::dot;
///
/// let x = Tensor::<i128>::new(
/// Some(&[5, 2]),
/// &[2],
/// ).unwrap();
/// let y = Tensor::<i128>::new(
/// Some(&[5, 5]),
/// &[2],
/// ).unwrap();
/// let expected = Tensor::<i128>::new(
/// Some(&[25, 35]),
/// &[2],
/// ).unwrap();
/// assert_eq!(dot(&[x, y], 1).unwrap(), expected);
/// ```
pub fn dot<T: TensorType + Mul<Output = T> + Add<Output = T>>(
inputs: &[Tensor<T>; 2],
chunk_size: usize,
) -> Result<Tensor<T>, TensorError> {
if inputs[0].clone().len() != inputs[1].clone().len() {
return Err(TensorError::DimMismatch("dot".to_string()));
}
let (a, b): (Tensor<T>, Tensor<T>) = (inputs[0].clone(), inputs[1].clone());
let transcript: Tensor<T> = a
.iter()
.zip(b)
.chunks(chunk_size)
.into_iter()
.scan(T::zero().unwrap(), |acc, chunk| {
let k = chunk.fold(T::zero().unwrap(), |acc, (a_i, b_i)| {
acc.clone() + a_i.clone() * b_i.clone()
});
*acc = acc.clone() + k.clone();
Some(acc.clone())
})
.collect();
Ok(transcript)
}
/// Sums a tensor.
/// # Arguments
///
/// * `a` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::accumulated::sum;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = sum(&x, 1).unwrap();
/// let expected = Tensor::<i128>::new(
/// Some(&[2, 17, 19, 20, 21, 21]),
/// &[6],
/// ).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn sum<T: TensorType + Mul<Output = T> + Add<Output = T>>(
a: &Tensor<T>,
chunk_size: usize,
) -> Result<Tensor<T>, TensorError> {
let transcript: Tensor<T> = a
.iter()
.chunks(chunk_size)
.into_iter()
.scan(T::zero().unwrap(), |acc, chunk| {
let k = chunk.fold(T::zero().unwrap(), |acc, a_i| acc.clone() + a_i.clone());
*acc = acc.clone() + k.clone();
Some(acc.clone())
})
.collect();
Ok(transcript)
}
/// Prod of a tensor.
/// # Arguments
///
/// * `a` - Tensor
/// # Examples
/// ```
/// use ezkl::tensor::Tensor;
/// use ezkl::tensor::ops::accumulated::prod;
/// let x = Tensor::<i128>::new(
/// Some(&[2, 15, 2, 1, 1, 0]),
/// &[2, 3],
/// ).unwrap();
/// let result = prod(&x, 1).unwrap();
/// let expected = Tensor::<i128>::new(
/// Some(&[2, 30, 60, 60, 60, 0]),
/// &[6],
/// ).unwrap();
/// assert_eq!(result, expected);
/// ```
pub fn prod<T: TensorType + Mul<Output = T> + Add<Output = T>>(
a: &Tensor<T>,
chunk_size: usize,
) -> Result<Tensor<T>, TensorError> {
let transcript: Tensor<T> = a
.iter()
.chunks(chunk_size)
.into_iter()
.scan(T::one().unwrap(), |acc, chunk| {
let k = chunk.fold(T::one().unwrap(), |acc, a_i| acc.clone() * a_i.clone());
*acc = acc.clone() * k.clone();
Some(acc.clone())
})
.collect();
Ok(transcript)
}
}
| https://github.com/zkonduit/ezkl |
src/tensor/val.rs | use core::{iter::FilterMap, slice::Iter};
use crate::circuit::region::ConstantsMap;
use super::{
ops::{intercalate_values, pad, resize},
*,
};
use halo2_proofs::{arithmetic::Field, circuit::Cell, plonk::Instance};
pub(crate) fn create_constant_tensor<
F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd,
>(
val: F,
len: usize,
) -> ValTensor<F> {
let mut constant = Tensor::from(vec![ValType::Constant(val); len].into_iter());
constant.set_visibility(&crate::graph::Visibility::Fixed);
ValTensor::from(constant)
}
pub(crate) fn create_unit_tensor<
F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd,
>(
len: usize,
) -> ValTensor<F> {
let mut unit = Tensor::from(vec![ValType::Constant(F::ONE); len].into_iter());
unit.set_visibility(&crate::graph::Visibility::Fixed);
ValTensor::from(unit)
}
pub(crate) fn create_zero_tensor<
F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd,
>(
len: usize,
) -> ValTensor<F> {
let mut zero = Tensor::from(vec![ValType::Constant(F::ZERO); len].into_iter());
zero.set_visibility(&crate::graph::Visibility::Fixed);
ValTensor::from(zero)
}
#[derive(Debug, Clone)]
/// A [ValType] is a wrapper around Halo2 value(s).
pub enum ValType<F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd> {
/// value
Value(Value<F>),
/// assigned value
AssignedValue(Value<Assigned<F>>),
/// previously assigned value
PrevAssigned(AssignedCell<F, F>),
/// constant
Constant(F),
/// assigned constant
AssignedConstant(AssignedCell<F, F>, F),
}
impl<F: PrimeField + TensorType + std::marker::Send + std::marker::Sync + PartialOrd> ValType<F> {
/// Returns the inner cell of the [ValType].
pub fn cell(&self) -> Option<Cell> {
match self {
ValType::PrevAssigned(cell) => Some(cell.cell()),
ValType::AssignedConstant(cell, _) => Some(cell.cell()),
_ => None,
}
}
/// Returns the assigned cell of the [ValType].
pub fn assigned_cell(&self) -> Option<AssignedCell<F, F>> {
match self {
ValType::PrevAssigned(cell) => Some(cell.clone()),
ValType::AssignedConstant(cell, _) => Some(cell.clone()),
_ => None,
}
}
/// Returns true if the value is previously assigned.
pub fn is_prev_assigned(&self) -> bool {
matches!(
self,
ValType::PrevAssigned(_) | ValType::AssignedConstant(..)
)
}
/// Returns true if the value is constant.
pub fn is_constant(&self) -> bool {
matches!(self, ValType::Constant(_) | ValType::AssignedConstant(..))
}
/// get felt eval
pub fn get_felt_eval(&self) -> Option<F> {
let mut res = None;
match self {
ValType::Value(v) => {
v.map(|f| {
res = Some(f);
});
}
ValType::AssignedValue(v) => {
v.map(|f| {
res = Some(f.evaluate());
});
}
ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {
v.value_field().map(|f| {
res = Some(f.evaluate());
});
}
ValType::Constant(v) => {
res = Some(*v);
}
}
res
}
/// get_prev_assigned
pub fn get_prev_assigned(&self) -> Option<AssignedCell<F, F>> {
match self {
ValType::PrevAssigned(v) => Some(v.clone()),
ValType::AssignedConstant(v, _) => Some(v.clone()),
_ => None,
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<ValType<F>> for i32 {
fn from(val: ValType<F>) -> Self {
match val {
ValType::Value(v) => {
let mut output = 0_i32;
let mut i = 0;
v.map(|y| {
let e = felt_to_i32(y);
output = e;
i += 1;
});
output
}
ValType::AssignedValue(v) => {
let mut output = 0_i32;
let mut i = 0;
v.evaluate().map(|y| {
let e = felt_to_i32(y);
output = e;
i += 1;
});
output
}
ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {
let mut output = 0_i32;
let mut i = 0;
v.value().map(|y| {
let e = felt_to_i32(*y);
output = e;
i += 1;
});
output
}
ValType::Constant(v) => felt_to_i32(v),
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<F> for ValType<F> {
fn from(t: F) -> ValType<F> {
ValType::Constant(t)
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Value<F>> for ValType<F> {
fn from(t: Value<F>) -> ValType<F> {
ValType::Value(t)
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Value<Assigned<F>>> for ValType<F> {
fn from(t: Value<Assigned<F>>) -> ValType<F> {
ValType::AssignedValue(t)
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<AssignedCell<F, F>> for ValType<F> {
fn from(t: AssignedCell<F, F>) -> ValType<F> {
ValType::PrevAssigned(t)
}
}
impl<F: PrimeField + TensorType + PartialOrd> TensorType for ValType<F>
where
F: Field,
{
fn zero() -> Option<Self> {
Some(ValType::Constant(<F as Field>::ZERO))
}
fn one() -> Option<Self> {
Some(ValType::Constant(<F as Field>::ONE))
}
}
/// A [ValTensor] is a wrapper around a [Tensor] of [ValType].
/// or a column of an [Instance].
/// This is the type used for all intermediate values in a circuit.
/// It is also the type used for the inputs and outputs of a circuit.
#[derive(Debug, Clone)]
pub enum ValTensor<F: PrimeField + TensorType + PartialOrd> {
/// A tensor of [Value], each containing a field element
Value {
/// Underlying [Tensor].
inner: Tensor<ValType<F>>,
/// Vector of dimensions of the tensor.
dims: Vec<usize>,
///
scale: crate::Scale,
},
/// A tensor backed by an [Instance] column
Instance {
/// [Instance]
inner: Column<Instance>,
/// Vector of dimensions of the tensor.
dims: Vec<Vec<usize>>,
/// Current instance num
idx: usize,
///
initial_offset: usize,
///
scale: crate::Scale,
},
}
impl<F: PrimeField + TensorType + PartialOrd> TensorType for ValTensor<F> {
fn zero() -> Option<Self> {
Some(ValTensor::Value {
inner: Tensor::zero()?,
dims: vec![],
scale: 0,
})
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Tensor<ValType<F>>> for ValTensor<F> {
fn from(t: Tensor<ValType<F>>) -> ValTensor<F> {
ValTensor::Value {
inner: t.map(|x| x),
dims: t.dims().to_vec(),
scale: 1,
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Vec<ValType<F>>> for ValTensor<F> {
fn from(t: Vec<ValType<F>>) -> ValTensor<F> {
ValTensor::Value {
inner: t.clone().into_iter().into(),
dims: vec![t.len()],
scale: 1,
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> TryFrom<Tensor<F>> for ValTensor<F> {
type Error = Box<dyn Error>;
fn try_from(t: Tensor<F>) -> Result<ValTensor<F>, Box<dyn Error>> {
let visibility = t.visibility.clone();
let dims = t.dims().to_vec();
let inner = t.into_iter().map(|x| {
if let Some(vis) = &visibility {
match vis {
Visibility::Fixed => Ok(ValType::Constant(x)),
_ => {
Ok(Value::known(x).into())
}
}
}
else {
Err("visibility should be set to convert a tensor of field elements to a ValTensor.".into())
}
}).collect::<Result<Vec<_>, Box<dyn Error>>>()?;
let mut inner: Tensor<ValType<F>> = inner.into_iter().into();
inner.reshape(&dims)?;
Ok(ValTensor::Value {
inner,
dims,
scale: 1,
})
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Tensor<Value<F>>> for ValTensor<F> {
fn from(t: Tensor<Value<F>>) -> ValTensor<F> {
ValTensor::Value {
inner: t.map(|x| x.into()),
dims: t.dims().to_vec(),
scale: 1,
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Tensor<Value<Assigned<F>>>> for ValTensor<F> {
fn from(t: Tensor<Value<Assigned<F>>>) -> ValTensor<F> {
ValTensor::Value {
inner: t.map(|x| x.into()),
dims: t.dims().to_vec(),
scale: 1,
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> From<Tensor<AssignedCell<F, F>>> for ValTensor<F> {
fn from(t: Tensor<AssignedCell<F, F>>) -> ValTensor<F> {
ValTensor::Value {
inner: t.map(|x| x.into()),
dims: t.dims().to_vec(),
scale: 1,
}
}
}
impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> ValTensor<F> {
/// Allocate a new [ValTensor::Value] from the given [Tensor] of [i128].
pub fn from_i128_tensor(t: Tensor<i128>) -> ValTensor<F> {
let inner = t.map(|x| ValType::Value(Value::known(i128_to_felt(x))));
inner.into()
}
/// Allocate a new [ValTensor::Instance] from the ConstraintSystem with the given tensor `dims`, optionally enabling `equality`.
pub fn new_instance(
cs: &mut ConstraintSystem<F>,
dims: Vec<Vec<usize>>,
scale: crate::Scale,
) -> Self {
let col = cs.instance_column();
cs.enable_equality(col);
ValTensor::Instance {
inner: col,
dims,
initial_offset: 0,
idx: 0,
scale,
}
}
/// Allocate a new [ValTensor::Instance] from the ConstraintSystem with the given tensor `dims`, optionally enabling `equality`.
pub fn new_instance_from_col(
dims: Vec<Vec<usize>>,
scale: crate::Scale,
col: Column<Instance>,
) -> Self {
ValTensor::Instance {
inner: col,
dims,
idx: 0,
initial_offset: 0,
scale,
}
}
///
pub fn get_total_instance_len(&self) -> usize {
match self {
ValTensor::Instance { dims, .. } => dims
.iter()
.map(|x| {
if !x.is_empty() {
x.iter().product::<usize>()
} else {
0
}
})
.sum(),
_ => 0,
}
}
///
pub fn is_instance(&self) -> bool {
matches!(self, ValTensor::Instance { .. })
}
/// reverse order of elements whilst preserving the shape
pub fn reverse(&mut self) -> Result<(), Box<dyn Error>> {
match self {
ValTensor::Value { inner: v, .. } => {
v.reverse();
}
ValTensor::Instance { .. } => {
return Err(Box::new(TensorError::WrongMethod));
}
};
Ok(())
}
///
pub fn set_initial_instance_offset(&mut self, offset: usize) {
if let ValTensor::Instance { initial_offset, .. } = self {
*initial_offset = offset;
}
}
///
pub fn increment_idx(&mut self) {
if let ValTensor::Instance { idx, .. } = self {
*idx += 1;
}
}
///
pub fn set_idx(&mut self, val: usize) {
if let ValTensor::Instance { idx, .. } = self {
*idx = val;
}
}
///
pub fn get_idx(&self) -> usize {
match self {
ValTensor::Instance { idx, .. } => *idx,
_ => 0,
}
}
///
pub fn any_unknowns(&self) -> Result<bool, Box<dyn Error>> {
match self {
ValTensor::Instance { .. } => Ok(true),
_ => Ok(self.get_inner()?.iter().any(|&x| {
let mut is_empty = true;
x.map(|_| is_empty = false);
is_empty
})),
}
}
/// Returns true if all the [ValTensor]'s [Value]s are assigned.
pub fn all_prev_assigned(&self) -> bool {
match self {
ValTensor::Value { inner, .. } => inner.iter().all(|x| x.is_prev_assigned()),
ValTensor::Instance { .. } => false,
}
}
/// Set the [ValTensor]'s scale.
pub fn set_scale(&mut self, scale: crate::Scale) {
match self {
ValTensor::Value { scale: s, .. } => *s = scale,
ValTensor::Instance { scale: s, .. } => *s = scale,
}
}
/// Returns the [ValTensor]'s scale.
pub fn scale(&self) -> crate::Scale {
match self {
ValTensor::Value { scale, .. } => *scale,
ValTensor::Instance { scale, .. } => *scale,
}
}
/// Returns the number of constants in the [ValTensor].
pub fn create_constants_map_iterator(
&self,
) -> FilterMap<Iter<'_, ValType<F>>, fn(&ValType<F>) -> Option<(F, ValType<F>)>> {
match self {
ValTensor::Value { inner, .. } => inner.iter().filter_map(|x| {
if let ValType::Constant(v) = x {
Some((*v, x.clone()))
} else {
None
}
}),
ValTensor::Instance { .. } => {
unreachable!("Instance tensors do not have constants")
}
}
}
/// Returns the number of constants in the [ValTensor].
pub fn create_constants_map(&self) -> ConstantsMap<F> {
match self {
ValTensor::Value { inner, .. } => inner
.par_iter()
.filter_map(|x| {
if let ValType::Constant(v) = x {
Some((*v, x.clone()))
} else {
None
}
})
.collect(),
ValTensor::Instance { .. } => ConstantsMap::new(),
}
}
/// Fetch the underlying [Tensor] of field elements.
pub fn get_felt_evals(&self) -> Result<Tensor<F>, Box<dyn Error>> {
let mut felt_evals: Vec<F> = vec![];
match self {
ValTensor::Value {
inner: v, dims: _, ..
} => {
// we have to push to an externally created vector or else vaf.map() returns an evaluation wrapped in Value<> (which we don't want)
let _ = v.map(|vaf| {
if let Some(f) = vaf.get_felt_eval() {
felt_evals.push(f);
}
});
}
_ => return Err(Box::new(TensorError::WrongMethod)),
};
let mut res: Tensor<F> = felt_evals.into_iter().into();
res.reshape(self.dims())?;
Ok(res)
}
/// Calls is_singleton on the inner tensor.
pub fn is_singleton(&self) -> bool {
match self {
ValTensor::Value { inner, .. } => inner.is_singleton(),
ValTensor::Instance { .. } => false,
}
}
/// Calls `int_evals` on the inner tensor.
pub fn get_int_evals(&self) -> Result<Tensor<i128>, Box<dyn Error>> {
// finally convert to vector of integers
let mut integer_evals: Vec<i128> = vec![];
match self {
ValTensor::Value {
inner: v, dims: _, ..
} => {
// we have to push to an externally created vector or else vaf.map() returns an evaluation wrapped in Value<> (which we don't want)
let _ = v.map(|vaf| match vaf {
ValType::Value(v) => v.map(|f| {
integer_evals.push(crate::fieldutils::felt_to_i128(f));
}),
ValType::AssignedValue(v) => v.map(|f| {
integer_evals.push(crate::fieldutils::felt_to_i128(f.evaluate()));
}),
ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {
v.value_field().map(|f| {
integer_evals.push(crate::fieldutils::felt_to_i128(f.evaluate()));
})
}
ValType::Constant(v) => {
integer_evals.push(crate::fieldutils::felt_to_i128(v));
Value::unknown()
}
});
}
_ => return Err(Box::new(TensorError::WrongMethod)),
};
let mut tensor: Tensor<i128> = integer_evals.into_iter().into();
match tensor.reshape(self.dims()) {
_ => {}
};
Ok(tensor)
}
/// Calls `pad_to_zero_rem` on the inner tensor.
pub fn pad_to_zero_rem(&mut self, n: usize, pad: ValType<F>) -> Result<(), Box<dyn Error>> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = v.pad_to_zero_rem(n, pad)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(Box::new(TensorError::WrongMethod));
}
};
Ok(())
}
/// Calls `get_slice` on the inner tensor.
pub fn get_slice(&self, indices: &[Range<usize>]) -> Result<ValTensor<F>, Box<dyn Error>> {
if indices.iter().map(|x| x.end - x.start).collect::<Vec<_>>() == self.dims() {
return Ok(self.clone());
}
let slice = match self {
ValTensor::Value {
inner: v,
dims: _,
scale,
} => {
let inner = v.get_slice(indices)?;
let dims = inner.dims().to_vec();
ValTensor::Value {
inner,
dims,
scale: *scale,
}
}
_ => return Err(Box::new(TensorError::WrongMethod)),
};
Ok(slice)
}
/// Calls `get_single_elem` on the inner tensor.
pub fn get_single_elem(&self, index: usize) -> Result<ValTensor<F>, Box<dyn Error>> {
let slice = match self {
ValTensor::Value {
inner: v,
dims: _,
scale,
} => {
let inner = Tensor::from(vec![v.get_flat_index(index)].into_iter());
ValTensor::Value {
inner,
dims: vec![1],
scale: *scale,
}
}
_ => return Err(Box::new(TensorError::WrongMethod)),
};
Ok(slice)
}
/// Fetches the inner tensor as a `Tensor<ValType<F>`
pub fn get_inner_tensor(&self) -> Result<&Tensor<ValType<F>>, TensorError> {
Ok(match self {
ValTensor::Value { inner: v, .. } => v,
ValTensor::Instance { .. } => return Err(TensorError::WrongMethod),
})
}
/// Fetches the inner tensor as a `Tensor<ValType<F>`
pub fn get_inner_tensor_mut(&mut self) -> Result<&mut Tensor<ValType<F>>, TensorError> {
Ok(match self {
ValTensor::Value { inner: v, .. } => v,
ValTensor::Instance { .. } => return Err(TensorError::WrongMethod),
})
}
/// Fetches the inner tensor as a `Tensor<Value<F>>`
pub fn get_inner(&self) -> Result<Tensor<Value<F>>, TensorError> {
Ok(match self {
ValTensor::Value { inner: v, .. } => v.map(|x| match x {
ValType::Value(v) => v,
ValType::AssignedValue(v) => v.evaluate(),
ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {
v.value_field().evaluate()
}
ValType::Constant(v) => Value::known(v),
}),
ValTensor::Instance { .. } => return Err(TensorError::WrongMethod),
})
}
/// Calls `expand` on the inner tensor.
pub fn expand(&mut self, dims: &[usize]) -> Result<(), Box<dyn Error>> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = v.expand(dims)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(Box::new(TensorError::WrongMethod));
}
};
Ok(())
}
/// Calls `move_axis` on the inner tensor.
pub fn move_axis(&mut self, source: usize, destination: usize) -> Result<(), Box<dyn Error>> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = v.move_axis(source, destination)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(Box::new(TensorError::WrongMethod));
}
};
Ok(())
}
/// Sets the [ValTensor]'s shape.
pub fn reshape(&mut self, new_dims: &[usize]) -> Result<(), Box<dyn Error>> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
v.reshape(new_dims)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { dims: d, idx, .. } => {
if d[*idx].iter().product::<usize>() != new_dims.iter().product::<usize>() {
return Err(Box::new(TensorError::DimError(format!(
"Cannot reshape {:?} to {:?} as they have number of elements",
d[*idx], new_dims
))));
}
d[*idx] = new_dims.to_vec();
}
};
Ok(())
}
/// Sets the [ValTensor]'s shape.
pub fn slice(
&mut self,
axis: &usize,
start: &usize,
end: &usize,
) -> Result<(), Box<dyn Error>> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = crate::tensor::ops::slice(v, axis, start, end)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(Box::new(TensorError::WrongMethod));
}
};
Ok(())
}
/// Calls `flatten` on the inner [Tensor].
pub fn flatten(&mut self) {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
v.flatten();
*d = v.dims().to_vec();
}
ValTensor::Instance { dims: d, idx, .. } => {
d[*idx] = vec![d[*idx].iter().product()];
}
}
}
/// Calls `duplicate_every_n` on the inner [Tensor].
pub fn duplicate_every_n(
&mut self,
n: usize,
num_repeats: usize,
initial_offset: usize,
) -> Result<(), TensorError> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = v.duplicate_every_n(n, num_repeats, initial_offset)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(TensorError::WrongMethod);
}
}
Ok(())
}
/// gets constants
pub fn get_const_zero_indices(&self) -> Result<Vec<usize>, TensorError> {
match self {
ValTensor::Value { inner: v, .. } => {
let mut indices = vec![];
for (i, e) in v.iter().enumerate() {
if let ValType::Constant(r) = e {
if *r == F::ZERO {
indices.push(i);
}
} else if let ValType::AssignedConstant(_, r) = e {
if *r == F::ZERO {
indices.push(i);
}
}
}
Ok(indices)
}
ValTensor::Instance { .. } => Ok(vec![]),
}
}
/// gets constants
pub fn get_const_indices(&self) -> Result<Vec<usize>, TensorError> {
match self {
ValTensor::Value { inner: v, .. } => {
let mut indices = vec![];
for (i, e) in v.iter().enumerate() {
if let ValType::Constant(_) = e {
indices.push(i);
} else if let ValType::AssignedConstant(_, _) = e {
indices.push(i);
}
}
Ok(indices)
}
ValTensor::Instance { .. } => Ok(vec![]),
}
}
/// calls `remove_indices` on the inner [Tensor].
pub fn remove_indices(
&mut self,
indices: &mut [usize],
is_sorted: bool,
) -> Result<(), TensorError> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
// this is very slow how can we speed this up ?
*v = v.remove_indices(indices, is_sorted)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
if indices.is_empty() {
return Ok(());
} else {
return Err(TensorError::WrongMethod);
}
}
}
Ok(())
}
/// Calls `duplicate_every_n` on the inner [Tensor].
pub fn remove_every_n(
&mut self,
n: usize,
num_repeats: usize,
initial_offset: usize,
) -> Result<(), TensorError> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = v.remove_every_n(n, num_repeats, initial_offset)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(TensorError::WrongMethod);
}
}
Ok(())
}
/// Calls `intercalate_values` on the inner [Tensor].
pub fn intercalate_values(
&mut self,
value: ValType<F>,
stride: usize,
axis: usize,
) -> Result<(), TensorError> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = intercalate_values(v, value, stride, axis)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(TensorError::WrongMethod);
}
}
Ok(())
}
/// Calls `resize` on the inner [Tensor].
pub fn resize(&mut self, scales: &[usize]) -> Result<(), TensorError> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = resize(v, scales)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(TensorError::WrongMethod);
}
};
Ok(())
}
/// Calls `pad_spatial_dims` on the inner [Tensor].
pub fn pad(&mut self, padding: Vec<(usize, usize)>, offset: usize) -> Result<(), TensorError> {
match self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = pad(v, padding, offset)?;
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(TensorError::WrongMethod);
}
}
Ok(())
}
/// Calls `len` on the inner [Tensor].
pub fn len(&self) -> usize {
match self {
ValTensor::Value { dims, .. } => {
if !dims.is_empty() && (dims != &[0]) {
dims.iter().product::<usize>()
} else {
0
}
}
ValTensor::Instance { dims, idx, .. } => {
let dims = dims[*idx].clone();
if !dims.is_empty() && (dims != [0]) {
dims.iter().product::<usize>()
} else {
0
}
}
}
}
///
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Calls `concats` on the inner [Tensor].
pub fn concat(&self, other: Self) -> Result<Self, TensorError> {
let res = match (self, other) {
(ValTensor::Value { inner: v1, .. }, ValTensor::Value { inner: v2, .. }) => {
ValTensor::from(Tensor::new(Some(&[v1.clone(), v2]), &[2])?.combine()?)
}
_ => {
return Err(TensorError::WrongMethod);
}
};
Ok(res)
}
/// Calls `concats` on the inner [Tensor].
pub fn concat_axis(&self, other: Self, axis: &usize) -> Result<Self, TensorError> {
let res = match (self, other) {
(ValTensor::Value { inner: v1, .. }, ValTensor::Value { inner: v2, .. }) => {
let v = crate::tensor::ops::concat(&[v1, &v2], *axis)?;
ValTensor::from(v)
}
_ => {
return Err(TensorError::WrongMethod);
}
};
Ok(res)
}
/// Returns the `dims` attribute of the [ValTensor].
pub fn dims(&self) -> &[usize] {
match self {
ValTensor::Value { dims: d, .. } => d,
ValTensor::Instance { dims: d, idx, .. } => &d[*idx],
}
}
/// A [String] representation of the [ValTensor] for display, for example in showing intermediate values in a computational graph.
pub fn show(&self) -> String {
match self.clone() {
ValTensor::Value {
inner: v, dims: _, ..
} => {
let r: Tensor<i32> = v.map(|x| x.into());
if r.len() > 10 {
let start = r[..5].to_vec();
let end = r[r.len() - 5..].to_vec();
// print the two split by ... in the middle
format!(
"[{} ... {}]",
start.iter().map(|x| format!("{}", x)).join(", "),
end.iter().map(|x| format!("{}", x)).join(", ")
)
} else {
format!("{:?}", r)
}
}
_ => "ValTensor not PrevAssigned".into(),
}
}
}
impl<F: PrimeField + TensorType + PartialOrd> ValTensor<F> {
/// inverts the inner values
pub fn inverse(&self) -> Result<ValTensor<F>, Box<dyn Error>> {
let mut cloned_self = self.clone();
match &mut cloned_self {
ValTensor::Value {
inner: v, dims: d, ..
} => {
*v = v.map(|x| match x {
ValType::AssignedValue(v) => ValType::AssignedValue(v.invert()),
ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => {
ValType::AssignedValue(v.value_field().invert())
}
ValType::Value(v) => ValType::Value(v.map(|x| x.invert().unwrap_or(F::ZERO))),
ValType::Constant(v) => ValType::Constant(v.invert().unwrap_or(F::ZERO)),
});
*d = v.dims().to_vec();
}
ValTensor::Instance { .. } => {
return Err(Box::new(TensorError::WrongMethod));
}
};
Ok(cloned_self)
}
}
| https://github.com/zkonduit/ezkl |
src/tensor/var.rs | use std::collections::HashSet;
use log::{debug, error, warn};
use crate::circuit::{region::ConstantsMap, CheckMode};
use super::*;
/// A wrapper around Halo2's `Column<Fixed>` or `Column<Advice>`.
/// Typically assign [ValTensor]s to [VarTensor]s when laying out a circuit.
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub enum VarTensor {
/// A VarTensor for holding Advice values, which are assigned at proving time.
Advice {
/// Vec of Advice columns, we have [[xx][xx][xx]...] where each inner vec is xx columns
inner: Vec<Vec<Column<Advice>>>,
///
num_inner_cols: usize,
/// Number of rows available to be used in each column of the storage
col_size: usize,
},
/// Dummy var
Dummy {
///
num_inner_cols: usize,
/// Number of rows available to be used in each column of the storage
col_size: usize,
},
/// Empty var
#[default]
Empty,
}
impl VarTensor {
///
pub fn is_advice(&self) -> bool {
matches!(self, VarTensor::Advice { .. })
}
///
pub fn max_rows<F: PrimeField>(cs: &ConstraintSystem<F>, logrows: usize) -> usize {
let base = 2u32;
base.pow(logrows as u32) as usize - cs.blinding_factors() - 1
}
/// Create a new VarTensor::Advice that is unblinded
/// Arguments
/// * `cs` - The constraint system
/// * `logrows` - log2 number of rows in the matrix, including any system and blinding rows.
/// * `capacity` - The number of advice cells to allocate
pub fn new_unblinded_advice<F: PrimeField>(
cs: &mut ConstraintSystem<F>,
logrows: usize,
num_inner_cols: usize,
capacity: usize,
) -> Self {
let max_rows = Self::max_rows(cs, logrows) * num_inner_cols;
let mut modulo = (capacity / max_rows) + 1;
// we add a buffer for duplicated rows (we get at most 1 duplicated row per column)
modulo = ((capacity + modulo) / max_rows) + 1;
let mut advices = vec![];
if modulo > 1 {
warn!(
"using column duplication for {} unblinded advice blocks",
modulo - 1
);
}
for _ in 0..modulo {
let mut inner = vec![];
for _ in 0..num_inner_cols {
let col = cs.unblinded_advice_column();
cs.enable_equality(col);
inner.push(col);
}
advices.push(inner);
}
VarTensor::Advice {
inner: advices,
num_inner_cols,
col_size: max_rows,
}
}
/// Create a new VarTensor::Advice
/// Arguments
/// * `cs` - The constraint system
/// * `logrows` - log2 number of rows in the matrix, including any system and blinding rows.
/// * `capacity` - The number of advice cells to allocate
pub fn new_advice<F: PrimeField>(
cs: &mut ConstraintSystem<F>,
logrows: usize,
num_inner_cols: usize,
capacity: usize,
) -> Self {
let max_rows = Self::max_rows(cs, logrows);
let max_assignments = Self::max_rows(cs, logrows) * num_inner_cols;
let mut modulo = (capacity / max_assignments) + 1;
// we add a buffer for duplicated rows (we get at most 1 duplicated row per column)
modulo = ((capacity + modulo) / max_assignments) + 1;
let mut advices = vec![];
if modulo > 1 {
debug!("using column duplication for {} advice blocks", modulo - 1);
}
for _ in 0..modulo {
let mut inner = vec![];
for _ in 0..num_inner_cols {
let col = cs.advice_column();
cs.enable_equality(col);
inner.push(col);
}
advices.push(inner);
}
VarTensor::Advice {
inner: advices,
num_inner_cols,
col_size: max_rows,
}
}
/// Initializes fixed columns to support the VarTensor::Advice
/// Arguments
/// * `cs` - The constraint system
/// * `logrows` - log2 number of rows in the matrix, including any system and blinding rows.
/// * `capacity` - The number of advice cells to allocate
pub fn constant_cols<F: PrimeField>(
cs: &mut ConstraintSystem<F>,
logrows: usize,
num_constants: usize,
module_requires_fixed: bool,
) -> usize {
if num_constants == 0 && !module_requires_fixed {
return 0;
} else if num_constants == 0 && module_requires_fixed {
let col = cs.fixed_column();
cs.enable_constant(col);
return 1;
}
let max_rows = Self::max_rows(cs, logrows);
let mut modulo = num_constants / max_rows + 1;
// we add a buffer for duplicated rows (we get at most 1 duplicated row per column)
modulo = (num_constants + modulo) / max_rows + 1;
if modulo > 1 {
debug!("using column duplication for {} fixed columns", modulo - 1);
}
for _ in 0..modulo {
let col = cs.fixed_column();
cs.enable_constant(col);
}
modulo
}
/// Create a new VarTensor::Dummy
pub fn dummy(logrows: usize, num_inner_cols: usize) -> Self {
let base = 2u32;
let max_rows = base.pow(logrows as u32) as usize - 6;
VarTensor::Dummy {
col_size: max_rows,
num_inner_cols,
}
}
/// Gets the dims of the object the VarTensor represents
pub fn num_blocks(&self) -> usize {
match self {
VarTensor::Advice { inner, .. } => inner.len(),
_ => 0,
}
}
/// Num inner cols
pub fn num_inner_cols(&self) -> usize {
match self {
VarTensor::Advice { num_inner_cols, .. } | VarTensor::Dummy { num_inner_cols, .. } => {
*num_inner_cols
}
_ => 0,
}
}
/// Total number of columns
pub fn num_cols(&self) -> usize {
match self {
VarTensor::Advice { inner, .. } => inner[0].len() * inner.len(),
_ => 0,
}
}
/// Gets the size of each column
pub fn col_size(&self) -> usize {
match self {
VarTensor::Advice { col_size, .. } | VarTensor::Dummy { col_size, .. } => *col_size,
_ => 0,
}
}
/// Gets the size of each column
pub fn block_size(&self) -> usize {
match self {
VarTensor::Advice {
num_inner_cols,
col_size,
..
}
| VarTensor::Dummy {
col_size,
num_inner_cols,
..
} => *col_size * num_inner_cols,
_ => 0,
}
}
/// Take a linear coordinate and output the (column, row) position in the storage block.
pub fn cartesian_coord(&self, linear_coord: usize) -> (usize, usize, usize) {
// x indexes over blocks of size num_inner_cols
let x = linear_coord / self.block_size();
// y indexes over the cols inside a block
let y = linear_coord % self.num_inner_cols();
// z indexes over the rows inside a col
let z = (linear_coord - x * self.block_size()) / self.num_inner_cols();
(x, y, z)
}
}
impl VarTensor {
/// Retrieve the value of a specific cell in the tensor.
pub fn query_rng<F: PrimeField>(
&self,
meta: &mut VirtualCells<'_, F>,
x: usize,
y: usize,
z: i32,
rng: usize,
) -> Result<Tensor<Expression<F>>, halo2_proofs::plonk::Error> {
match &self {
// when advice we have 1 col per row
VarTensor::Advice { inner: advices, .. } => {
let c = Tensor::from(
// this should fail if dims is empty, should be impossible
(0..rng).map(|i| meta.query_advice(advices[x][y], Rotation(z + i as i32))),
);
Ok(c)
}
_ => {
error!("VarTensor was not initialized");
Err(halo2_proofs::plonk::Error::Synthesis)
}
}
}
/// Retrieve the value of a specific block at an offset in the tensor.
pub fn query_whole_block<F: PrimeField>(
&self,
meta: &mut VirtualCells<'_, F>,
x: usize,
z: i32,
rng: usize,
) -> Result<Tensor<Expression<F>>, halo2_proofs::plonk::Error> {
match &self {
// when advice we have 1 col per row
VarTensor::Advice { inner: advices, .. } => {
let c = Tensor::from({
// this should fail if dims is empty, should be impossible
let cartesian = (0..rng).cartesian_product(0..self.num_inner_cols());
cartesian.map(|(i, y)| meta.query_advice(advices[x][y], Rotation(z + i as i32)))
});
Ok(c)
}
_ => {
error!("VarTensor was not initialized");
Err(halo2_proofs::plonk::Error::Synthesis)
}
}
}
/// Assigns a constant value to a specific cell in the tensor.
pub fn assign_constant<F: PrimeField + TensorType + PartialOrd>(
&self,
region: &mut Region<F>,
offset: usize,
coord: usize,
constant: F,
) -> Result<AssignedCell<F, F>, halo2_proofs::plonk::Error> {
let (x, y, z) = self.cartesian_coord(offset + coord);
match &self {
VarTensor::Advice { inner: advices, .. } => {
region.assign_advice_from_constant(|| "constant", advices[x][y], z, constant)
}
_ => {
error!("VarTensor was not initialized");
Err(halo2_proofs::plonk::Error::Synthesis)
}
}
}
/// Assigns [ValTensor] to the columns of the inner tensor.
pub fn assign_with_omissions<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(
&self,
region: &mut Region<F>,
offset: usize,
values: &ValTensor<F>,
omissions: &HashSet<&usize>,
constants: &mut ConstantsMap<F>,
) -> Result<ValTensor<F>, halo2_proofs::plonk::Error> {
let mut assigned_coord = 0;
let mut res: ValTensor<F> = match values {
ValTensor::Instance { .. } => {
unimplemented!("cannot assign instance to advice columns with omissions")
}
ValTensor::Value { inner: v, .. } => Ok::<ValTensor<F>, halo2_proofs::plonk::Error>(
v.enum_map(|coord, k| {
if omissions.contains(&coord) {
return Ok::<_, halo2_proofs::plonk::Error>(k);
}
let cell =
self.assign_value(region, offset, k.clone(), assigned_coord, constants)?;
assigned_coord += 1;
Ok::<_, halo2_proofs::plonk::Error>(cell)
})?
.into(),
),
}?;
res.set_scale(values.scale());
Ok(res)
}
/// Assigns [ValTensor] to the columns of the inner tensor.
pub fn assign<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(
&self,
region: &mut Region<F>,
offset: usize,
values: &ValTensor<F>,
constants: &mut ConstantsMap<F>,
) -> Result<ValTensor<F>, halo2_proofs::plonk::Error> {
let mut res: ValTensor<F> = match values {
ValTensor::Instance {
inner: instance,
dims,
idx,
initial_offset,
..
} => match &self {
VarTensor::Advice { inner: v, .. } => {
let total_offset: usize = initial_offset
+ dims[..*idx]
.iter()
.map(|x| x.iter().product::<usize>())
.sum::<usize>();
let dims = &dims[*idx];
// this should never ever fail
let t: Tensor<i32> = Tensor::new(None, dims).unwrap();
Ok(t.enum_map(|coord, _| {
let (x, y, z) = self.cartesian_coord(offset + coord);
region.assign_advice_from_instance(
|| "pub input anchor",
*instance,
coord + total_offset,
v[x][y],
z,
)
})?
.into())
}
_ => {
error!("Instance is only supported for advice columns");
Err(halo2_proofs::plonk::Error::Synthesis)
}
},
ValTensor::Value { inner: v, .. } => Ok(v
.enum_map(|coord, k| {
self.assign_value(region, offset, k.clone(), coord, constants)
})?
.into()),
}?;
res.set_scale(values.scale());
Ok(res)
}
/// Assigns specific values (`ValTensor`) to the columns of the inner tensor but allows for column wrapping for accumulated operations.
/// Duplication occurs by copying the last cell of the column to the first cell next column and creating a copy constraint between the two.
pub fn dummy_assign_with_duplication<
F: PrimeField + TensorType + PartialOrd + std::hash::Hash,
>(
&self,
row: usize,
offset: usize,
values: &ValTensor<F>,
single_inner_col: bool,
constants: &mut ConstantsMap<F>,
) -> Result<(ValTensor<F>, usize), halo2_proofs::plonk::Error> {
match values {
ValTensor::Instance { .. } => unimplemented!("duplication is not supported on instance columns. increase K if you require more rows."),
ValTensor::Value { inner: v, dims , ..} => {
let duplication_freq = if single_inner_col {
self.col_size()
} else {
self.block_size()
};
let num_repeats = if single_inner_col {
1
} else {
self.num_inner_cols()
};
let duplication_offset = if single_inner_col {
row
} else {
offset
};
// duplicates every nth element to adjust for column overflow
let mut res: ValTensor<F> = v.duplicate_every_n(duplication_freq, num_repeats, duplication_offset).unwrap().into();
let constants_map = res.create_constants_map();
constants.extend(constants_map);
let total_used_len = res.len();
res.remove_every_n(duplication_freq, num_repeats, duplication_offset).unwrap();
res.reshape(dims).unwrap();
res.set_scale(values.scale());
Ok((res, total_used_len))
}
}
}
/// Assigns specific values (`ValTensor`) to the columns of the inner tensor but allows for column wrapping for accumulated operations.
/// Duplication occurs by copying the last cell of the column to the first cell next column and creating a copy constraint between the two.
pub fn assign_with_duplication<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(
&self,
region: &mut Region<F>,
row: usize,
offset: usize,
values: &ValTensor<F>,
check_mode: &CheckMode,
single_inner_col: bool,
constants: &mut ConstantsMap<F>,
) -> Result<(ValTensor<F>, usize), halo2_proofs::plonk::Error> {
let mut prev_cell = None;
match values {
ValTensor::Instance { .. } => unimplemented!("duplication is not supported on instance columns. increase K if you require more rows."),
ValTensor::Value { inner: v, dims , ..} => {
let duplication_freq = if single_inner_col {
self.col_size()
} else {
self.block_size()
};
let num_repeats = if single_inner_col {
1
} else {
self.num_inner_cols()
};
let duplication_offset = if single_inner_col {
row
} else {
offset
};
// duplicates every nth element to adjust for column overflow
let v = v.duplicate_every_n(duplication_freq, num_repeats, duplication_offset).unwrap();
let mut res: ValTensor<F> = {
v.enum_map(|coord, k| {
let step = if !single_inner_col {
1
} else {
self.num_inner_cols()
};
let (x, y, z) = self.cartesian_coord(offset + coord * step);
if matches!(check_mode, CheckMode::SAFE) && coord > 0 && z == 0 && y == 0 {
// assert that duplication occurred correctly
assert_eq!(Into::<i32>::into(k.clone()), Into::<i32>::into(v[coord - 1].clone()));
};
let cell = self.assign_value(region, offset, k.clone(), coord * step, constants)?;
if single_inner_col {
if z == 0 {
// if we are at the end of the column, we need to copy the cell to the next column
prev_cell = Some(cell.clone());
} else if coord > 0 && z == 0 && single_inner_col {
if let Some(prev_cell) = prev_cell.as_ref() {
let cell = cell.cell().ok_or({
error!("Error getting cell: {:?}", (x,y));
halo2_proofs::plonk::Error::Synthesis})?;
let prev_cell = prev_cell.cell().ok_or({
error!("Error getting cell: {:?}", (x,y));
halo2_proofs::plonk::Error::Synthesis})?;
region.constrain_equal(prev_cell,cell)?;
} else {
error!("Error copy-constraining previous value: {:?}", (x,y));
return Err(halo2_proofs::plonk::Error::Synthesis);
}
}}
Ok(cell)
})?.into()};
let total_used_len = res.len();
res.remove_every_n(duplication_freq, num_repeats, duplication_offset).unwrap();
res.reshape(dims).unwrap();
res.set_scale(values.scale());
if matches!(check_mode, CheckMode::SAFE) {
// during key generation this will be 0 so we use this as a flag to check
// TODO: this isn't very safe and would be better to get the phase directly
let is_assigned = !Into::<Tensor<i32>>::into(res.clone().get_inner().unwrap())
.iter()
.all(|&x| x == 0);
if is_assigned {
assert_eq!(
Into::<Tensor<i32>>::into(values.get_inner().unwrap()),
Into::<Tensor<i32>>::into(res.get_inner().unwrap())
)};
}
Ok((res, total_used_len))
}
}
}
fn assign_value<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>(
&self,
region: &mut Region<F>,
offset: usize,
k: ValType<F>,
coord: usize,
constants: &mut ConstantsMap<F>,
) -> Result<ValType<F>, halo2_proofs::plonk::Error> {
let (x, y, z) = self.cartesian_coord(offset + coord);
let res = match k {
ValType::Value(v) => match &self {
VarTensor::Advice { inner: advices, .. } => {
ValType::PrevAssigned(region.assign_advice(|| "k", advices[x][y], z, || v)?)
}
_ => unimplemented!(),
},
ValType::PrevAssigned(v) => match &self {
VarTensor::Advice { inner: advices, .. } => {
ValType::PrevAssigned(v.copy_advice(|| "k", region, advices[x][y], z)?)
}
_ => unimplemented!(),
},
ValType::AssignedConstant(v, val) => match &self {
VarTensor::Advice { inner: advices, .. } => {
ValType::AssignedConstant(v.copy_advice(|| "k", region, advices[x][y], z)?, val)
}
_ => unimplemented!(),
},
ValType::AssignedValue(v) => match &self {
VarTensor::Advice { inner: advices, .. } => ValType::PrevAssigned(
region
.assign_advice(|| "k", advices[x][y], z, || v)?
.evaluate(),
),
_ => unimplemented!(),
},
ValType::Constant(v) => {
if let std::collections::hash_map::Entry::Vacant(e) = constants.entry(v) {
let value = ValType::AssignedConstant(
self.assign_constant(region, offset, coord, v)?,
v,
);
e.insert(value.clone());
value
} else {
let cell = constants.get(&v).unwrap();
self.assign_value(region, offset, cell.clone(), coord, constants)?
}
}
};
Ok(res)
}
}
| https://github.com/zkonduit/ezkl |
src/wasm.rs | use crate::circuit::modules::polycommit::PolyCommitChip;
use crate::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH};
use crate::circuit::modules::poseidon::PoseidonChip;
use crate::circuit::modules::Module;
use crate::fieldutils::felt_to_i128;
use crate::fieldutils::i128_to_felt;
use crate::graph::modules::POSEIDON_LEN_GRAPH;
use crate::graph::quantize_float;
use crate::graph::scale_to_multiplier;
use crate::graph::{GraphCircuit, GraphSettings};
use crate::pfsys::create_proof_circuit;
use crate::pfsys::evm::aggregation_kzg::AggregationCircuit;
use crate::pfsys::evm::aggregation_kzg::PoseidonTranscript;
use crate::pfsys::verify_proof_circuit;
use crate::pfsys::TranscriptType;
use crate::tensor::TensorType;
use crate::CheckMode;
use crate::Commitments;
use console_error_panic_hook;
use halo2_proofs::plonk::*;
use halo2_proofs::poly::commitment::{CommitmentScheme, ParamsProver};
use halo2_proofs::poly::ipa::multiopen::{ProverIPA, VerifierIPA};
use halo2_proofs::poly::ipa::{
commitment::{IPACommitmentScheme, ParamsIPA},
strategy::SingleStrategy as IPASingleStrategy,
};
use halo2_proofs::poly::kzg::multiopen::ProverSHPLONK;
use halo2_proofs::poly::kzg::multiopen::VerifierSHPLONK;
use halo2_proofs::poly::kzg::{
commitment::{KZGCommitmentScheme, ParamsKZG},
strategy::SingleStrategy as KZGSingleStrategy,
};
use halo2_proofs::poly::VerificationStrategy;
use halo2_solidity_verifier::encode_calldata;
use halo2curves::bn256::{Bn256, Fr, G1Affine};
use halo2curves::ff::{FromUniformBytes, PrimeField};
use snark_verifier::loader::native::NativeLoader;
use snark_verifier::system::halo2::transcript::evm::EvmTranscript;
use std::str::FromStr;
use wasm_bindgen::prelude::*;
use wasm_bindgen_console_logger::DEFAULT_LOGGER;
#[cfg(feature = "web")]
pub use wasm_bindgen_rayon::init_thread_pool;
#[wasm_bindgen]
/// Initialize logger for wasm
pub fn init_logger() {
log::set_logger(&DEFAULT_LOGGER).unwrap();
}
#[wasm_bindgen]
/// Initialize panic hook for wasm
pub fn init_panic_hook() {
console_error_panic_hook::set_once();
}
/// Wrapper around the halo2 encode call data method
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn encodeVerifierCalldata(
proof: wasm_bindgen::Clamped<Vec<u8>>,
vk_address: Option<Vec<u8>>,
) -> Result<Vec<u8>, JsError> {
let snark: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize proof: {}", e)))?;
let vk_address: Option<[u8; 20]> = if let Some(vk_address) = vk_address {
let array: [u8; 20] = serde_json::from_slice(&vk_address[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize vk address: {}", e)))?;
Some(array)
} else {
None
};
let flattened_instances = snark.instances.into_iter().flatten();
let encoded = encode_calldata(
vk_address,
&snark.proof,
&flattened_instances.collect::<Vec<_>>(),
);
Ok(encoded)
}
/// Converts a hex string to a byte array
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn feltToBigEndian(array: wasm_bindgen::Clamped<Vec<u8>>) -> Result<String, JsError> {
let felt: Fr = serde_json::from_slice(&array[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize field element: {}", e)))?;
Ok(format!("{:?}", felt))
}
/// Converts a felt to a little endian string
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn feltToLittleEndian(array: wasm_bindgen::Clamped<Vec<u8>>) -> Result<String, JsError> {
let felt: Fr = serde_json::from_slice(&array[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize field element: {}", e)))?;
let repr = serde_json::to_string(&felt).unwrap();
let b: String = serde_json::from_str(&repr).unwrap();
Ok(b)
}
/// Converts a hex string to a byte array
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn feltToInt(
array: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {
let felt: Fr = serde_json::from_slice(&array[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize field element: {}", e)))?;
Ok(wasm_bindgen::Clamped(
serde_json::to_vec(&felt_to_i128(felt))
.map_err(|e| JsError::new(&format!("Failed to serialize integer: {}", e)))?,
))
}
/// Converts felts to a floating point element
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn feltToFloat(
array: wasm_bindgen::Clamped<Vec<u8>>,
scale: crate::Scale,
) -> Result<f64, JsError> {
let felt: Fr = serde_json::from_slice(&array[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize field element: {}", e)))?;
let int_rep = felt_to_i128(felt);
let multiplier = scale_to_multiplier(scale);
Ok(int_rep as f64 / multiplier)
}
/// Converts a floating point number to a hex string representing a fixed point field element
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn floatToFelt(
input: f64,
scale: crate::Scale,
) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {
let int_rep =
quantize_float(&input, 0.0, scale).map_err(|e| JsError::new(&format!("{}", e)))?;
let felt = i128_to_felt(int_rep);
let vec = crate::pfsys::field_to_string::<halo2curves::bn256::Fr>(&felt);
Ok(wasm_bindgen::Clamped(serde_json::to_vec(&vec).map_err(
|e| JsError::new(&format!("Failed to serialize a float to felt{}", e)),
)?))
}
/// Generate a kzg commitment.
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn kzgCommit(
message: wasm_bindgen::Clamped<Vec<u8>>,
vk: wasm_bindgen::Clamped<Vec<u8>>,
settings: wasm_bindgen::Clamped<Vec<u8>>,
params_ser: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {
let message: Vec<Fr> = serde_json::from_slice(&message[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize message: {}", e)))?;
let mut reader = std::io::BufReader::new(¶ms_ser[..]);
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
let mut reader = std::io::BufReader::new(&vk[..]);
let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize settings: {}", e)))?;
let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
circuit_settings,
)
.map_err(|e| JsError::new(&format!("Failed to deserialize vk: {}", e)))?;
let output = PolyCommitChip::commit::<KZGCommitmentScheme<Bn256>>(
message,
(vk.cs().blinding_factors() + 1) as u32,
¶ms,
);
Ok(wasm_bindgen::Clamped(
serde_json::to_vec(&output).map_err(|e| JsError::new(&format!("{}", e)))?,
))
}
/// Converts a buffer to vector of 4 u64s representing a fixed point field element
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn bufferToVecOfFelt(
buffer: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {
// Convert the buffer to a slice
let buffer: &[u8] = &buffer;
// Divide the buffer into chunks of 64 bytes
let chunks = buffer.chunks_exact(16);
// Get the remainder
let remainder = chunks.remainder();
// Add 0s to the remainder to make it 64 bytes
let mut remainder = remainder.to_vec();
// Collect chunks into a Vec<[u8; 16]>.
let chunks: Result<Vec<[u8; 16]>, JsError> = chunks
.map(|slice| {
let array: [u8; 16] = slice
.try_into()
.map_err(|_| JsError::new("failed to slice input chunks"))?;
Ok(array)
})
.collect();
let mut chunks = chunks?;
if remainder.len() != 0 {
remainder.resize(16, 0);
// Convert the Vec<u8> to [u8; 16]
let remainder_array: [u8; 16] = remainder
.try_into()
.map_err(|_| JsError::new("failed to slice remainder"))?;
// append the remainder to the chunks
chunks.push(remainder_array);
}
// Convert each chunk to a field element
let field_elements: Vec<Fr> = chunks
.iter()
.map(|x| PrimeField::from_u128(u8_array_to_u128_le(*x)))
.collect();
Ok(wasm_bindgen::Clamped(
serde_json::to_vec(&field_elements)
.map_err(|e| JsError::new(&format!("Failed to serialize field elements: {}", e)))?,
))
}
/// Generate a poseidon hash in browser. Input message
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn poseidonHash(
message: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<wasm_bindgen::Clamped<Vec<u8>>, JsError> {
let message: Vec<Fr> = serde_json::from_slice(&message[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize message: {}", e)))?;
let output =
PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>::run(
message.clone(),
)
.map_err(|e| JsError::new(&format!("{}", e)))?;
Ok(wasm_bindgen::Clamped(serde_json::to_vec(&output).map_err(
|e| JsError::new(&format!("Failed to serialize poseidon hash output: {}", e)),
)?))
}
/// Generate a witness file from input.json, compiled model and a settings.json file.
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn genWitness(
compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,
input: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<Vec<u8>, JsError> {
let mut circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize compiled model: {}", e)))?;
let input: crate::graph::input::GraphData = serde_json::from_slice(&input[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize input: {}", e)))?;
let mut input = circuit
.load_graph_input(&input)
.map_err(|e| JsError::new(&format!("{}", e)))?;
let witness = circuit
.forward::<KZGCommitmentScheme<Bn256>>(&mut input, None, None, false)
.map_err(|e| JsError::new(&format!("{}", e)))?;
serde_json::to_vec(&witness)
.map_err(|e| JsError::new(&format!("Failed to serialize witness: {}", e)))
}
/// Generate verifying key in browser
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn genVk(
compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,
params_ser: wasm_bindgen::Clamped<Vec<u8>>,
compress_selectors: bool,
) -> Result<Vec<u8>, JsError> {
// Read in kzg params
let mut reader = std::io::BufReader::new(¶ms_ser[..]);
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
// Read in compiled circuit
let circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize compiled model: {}", e)))?;
// Create verifying key
let vk = create_vk_wasm::<KZGCommitmentScheme<Bn256>, Fr, GraphCircuit>(
&circuit,
¶ms,
compress_selectors,
)
.map_err(Box::<dyn std::error::Error>::from)
.map_err(|e| JsError::new(&format!("Failed to create verifying key: {}", e)))?;
let mut serialized_vk = Vec::new();
vk.write(&mut serialized_vk, halo2_proofs::SerdeFormat::RawBytes)
.map_err(|e| JsError::new(&format!("Failed to serialize vk: {}", e)))?;
Ok(serialized_vk)
}
/// Generate proving key in browser
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn genPk(
vk: wasm_bindgen::Clamped<Vec<u8>>,
compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,
params_ser: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<Vec<u8>, JsError> {
// Read in kzg params
let mut reader = std::io::BufReader::new(¶ms_ser[..]);
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
// Read in compiled circuit
let circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize compiled model: {}", e)))?;
// Read in verifying key
let mut reader = std::io::BufReader::new(&vk[..]);
let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
circuit.settings().clone(),
)
.map_err(|e| JsError::new(&format!("Failed to deserialize verifying key: {}", e)))?;
// Create proving key
let pk = create_pk_wasm::<KZGCommitmentScheme<Bn256>, Fr, GraphCircuit>(vk, &circuit, ¶ms)
.map_err(Box::<dyn std::error::Error>::from)
.map_err(|e| JsError::new(&format!("Failed to create proving key: {}", e)))?;
let mut serialized_pk = Vec::new();
pk.write(&mut serialized_pk, halo2_proofs::SerdeFormat::RawBytes)
.map_err(|e| JsError::new(&format!("Failed to serialize pk: {}", e)))?;
Ok(serialized_pk)
}
/// Verify proof in browser using wasm
#[wasm_bindgen]
pub fn verify(
proof_js: wasm_bindgen::Clamped<Vec<u8>>,
vk: wasm_bindgen::Clamped<Vec<u8>>,
settings: wasm_bindgen::Clamped<Vec<u8>>,
srs: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<bool, JsError> {
let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize settings: {}", e)))?;
let proof: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof_js[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize proof: {}", e)))?;
let mut reader = std::io::BufReader::new(&vk[..]);
let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
circuit_settings.clone(),
)
.map_err(|e| JsError::new(&format!("Failed to deserialize vk: {}", e)))?;
let orig_n = 1 << circuit_settings.run_args.logrows;
let commitment = circuit_settings.run_args.commitment.into();
let mut reader = std::io::BufReader::new(&srs[..]);
let result = match commitment {
Commitments::KZG => {
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
let strategy = KZGSingleStrategy::new(params.verifier_params());
match proof.transcript_type {
TranscriptType::EVM => verify_proof_circuit::<
VerifierSHPLONK<'_, Bn256>,
KZGCommitmentScheme<Bn256>,
KZGSingleStrategy<_>,
_,
EvmTranscript<G1Affine, _, _, _>,
>(&proof, ¶ms, &vk, strategy, orig_n),
TranscriptType::Poseidon => {
verify_proof_circuit::<
VerifierSHPLONK<'_, Bn256>,
KZGCommitmentScheme<Bn256>,
KZGSingleStrategy<_>,
_,
PoseidonTranscript<NativeLoader, _>,
>(&proof, ¶ms, &vk, strategy, orig_n)
}
}
}
Commitments::IPA => {
let params: ParamsIPA<_> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
let strategy = IPASingleStrategy::new(params.verifier_params());
match proof.transcript_type {
TranscriptType::EVM => verify_proof_circuit::<
VerifierIPA<_>,
IPACommitmentScheme<G1Affine>,
IPASingleStrategy<_>,
_,
EvmTranscript<G1Affine, _, _, _>,
>(&proof, ¶ms, &vk, strategy, orig_n),
TranscriptType::Poseidon => {
verify_proof_circuit::<
VerifierIPA<_>,
IPACommitmentScheme<G1Affine>,
IPASingleStrategy<_>,
_,
PoseidonTranscript<NativeLoader, _>,
>(&proof, ¶ms, &vk, strategy, orig_n)
}
}
}
};
match result {
Ok(_) => Ok(true),
Err(e) => Err(JsError::new(&format!("{}", e))),
}
}
#[wasm_bindgen]
#[allow(non_snake_case)]
/// Verify aggregate proof in browser using wasm
pub fn verifyAggr(
proof_js: wasm_bindgen::Clamped<Vec<u8>>,
vk: wasm_bindgen::Clamped<Vec<u8>>,
logrows: u64,
srs: wasm_bindgen::Clamped<Vec<u8>>,
commitment: &str,
) -> Result<bool, JsError> {
let proof: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof_js[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize proof: {}", e)))?;
let mut reader = std::io::BufReader::new(&vk[..]);
let vk = VerifyingKey::<G1Affine>::read::<_, AggregationCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
(),
)
.map_err(|e| JsError::new(&format!("Failed to deserialize vk: {}", e)))?;
let commit = Commitments::from_str(commitment).map_err(|e| JsError::new(&format!("{}", e)))?;
let orig_n = 1 << logrows;
let mut reader = std::io::BufReader::new(&srs[..]);
let result = match commit {
Commitments::KZG => {
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
let strategy = KZGSingleStrategy::new(params.verifier_params());
match proof.transcript_type {
TranscriptType::EVM => verify_proof_circuit::<
VerifierSHPLONK<'_, Bn256>,
KZGCommitmentScheme<Bn256>,
KZGSingleStrategy<_>,
_,
EvmTranscript<G1Affine, _, _, _>,
>(&proof, ¶ms, &vk, strategy, orig_n),
TranscriptType::Poseidon => {
verify_proof_circuit::<
VerifierSHPLONK<'_, Bn256>,
KZGCommitmentScheme<Bn256>,
KZGSingleStrategy<_>,
_,
PoseidonTranscript<NativeLoader, _>,
>(&proof, ¶ms, &vk, strategy, orig_n)
}
}
}
Commitments::IPA => {
let params: ParamsIPA<_> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
let strategy = IPASingleStrategy::new(params.verifier_params());
match proof.transcript_type {
TranscriptType::EVM => verify_proof_circuit::<
VerifierIPA<_>,
IPACommitmentScheme<G1Affine>,
IPASingleStrategy<_>,
_,
EvmTranscript<G1Affine, _, _, _>,
>(&proof, ¶ms, &vk, strategy, orig_n),
TranscriptType::Poseidon => {
verify_proof_circuit::<
VerifierIPA<_>,
IPACommitmentScheme<G1Affine>,
IPASingleStrategy<_>,
_,
PoseidonTranscript<NativeLoader, _>,
>(&proof, ¶ms, &vk, strategy, orig_n)
}
}
}
};
match result {
Ok(_) => Ok(true),
Err(e) => Err(JsError::new(&format!("{}", e))),
}
}
/// Prove in browser using wasm
#[wasm_bindgen]
pub fn prove(
witness: wasm_bindgen::Clamped<Vec<u8>>,
pk: wasm_bindgen::Clamped<Vec<u8>>,
compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,
srs: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<Vec<u8>, JsError> {
#[cfg(feature = "det-prove")]
log::set_max_level(log::LevelFilter::Debug);
#[cfg(not(feature = "det-prove"))]
log::set_max_level(log::LevelFilter::Info);
// read in circuit
let mut circuit: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize circuit: {}", e)))?;
// read in model input
let data: crate::graph::GraphWitness = serde_json::from_slice(&witness[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize witness: {}", e)))?;
// read in proving key
let mut reader = std::io::BufReader::new(&pk[..]);
let pk = ProvingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
circuit.settings().clone(),
)
.map_err(|e| JsError::new(&format!("Failed to deserialize proving key: {}", e)))?;
// prep public inputs
circuit
.load_graph_witness(&data)
.map_err(|e| JsError::new(&format!("{}", e)))?;
let public_inputs = circuit
.prepare_public_inputs(&data)
.map_err(|e| JsError::new(&format!("{}", e)))?;
let proof_split_commits: Option<crate::pfsys::ProofSplitCommit> = data.into();
// read in kzg params
let mut reader = std::io::BufReader::new(&srs[..]);
let commitment = circuit.settings().run_args.commitment.into();
// creates and verifies the proof
let proof = match commitment {
Commitments::KZG => {
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize srs: {}", e)))?;
create_proof_circuit::<
KZGCommitmentScheme<Bn256>,
_,
ProverSHPLONK<_>,
VerifierSHPLONK<_>,
KZGSingleStrategy<_>,
_,
EvmTranscript<_, _, _, _>,
EvmTranscript<_, _, _, _>,
>(
circuit,
vec![public_inputs],
¶ms,
&pk,
CheckMode::UNSAFE,
crate::Commitments::KZG,
TranscriptType::EVM,
proof_split_commits,
None,
)
}
Commitments::IPA => {
let params: ParamsIPA<_> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize srs: {}", e)))?;
create_proof_circuit::<
IPACommitmentScheme<G1Affine>,
_,
ProverIPA<_>,
VerifierIPA<_>,
IPASingleStrategy<_>,
_,
EvmTranscript<_, _, _, _>,
EvmTranscript<_, _, _, _>,
>(
circuit,
vec![public_inputs],
¶ms,
&pk,
CheckMode::UNSAFE,
crate::Commitments::IPA,
TranscriptType::EVM,
proof_split_commits,
None,
)
}
}
.map_err(|e| JsError::new(&format!("{}", e)))?;
Ok(serde_json::to_string(&proof)
.map_err(|e| JsError::new(&format!("{}", e)))?
.into_bytes())
}
// VALIDATION FUNCTIONS
/// Witness file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn witnessValidation(witness: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {
let _: crate::graph::GraphWitness = serde_json::from_slice(&witness[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize witness: {}", e)))?;
Ok(true)
}
/// Compiled circuit validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn compiledCircuitValidation(
compiled_circuit: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<bool, JsError> {
let _: crate::graph::GraphCircuit = bincode::deserialize(&compiled_circuit[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize compiled circuit: {}", e)))?;
Ok(true)
}
/// Input file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn inputValidation(input: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {
let _: crate::graph::input::GraphData = serde_json::from_slice(&input[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize input: {}", e)))?;
Ok(true)
}
/// Proof file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn proofValidation(proof: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {
let _: crate::pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&proof[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize proof: {}", e)))?;
Ok(true)
}
/// Vk file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn vkValidation(
vk: wasm_bindgen::Clamped<Vec<u8>>,
settings: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<bool, JsError> {
let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize settings: {}", e)))?;
let mut reader = std::io::BufReader::new(&vk[..]);
let _ = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
circuit_settings,
)
.map_err(|e| JsError::new(&format!("Failed to deserialize vk: {}", e)))?;
Ok(true)
}
/// Pk file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn pkValidation(
pk: wasm_bindgen::Clamped<Vec<u8>>,
settings: wasm_bindgen::Clamped<Vec<u8>>,
) -> Result<bool, JsError> {
let circuit_settings: GraphSettings = serde_json::from_slice(&settings[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize settings: {}", e)))?;
let mut reader = std::io::BufReader::new(&pk[..]);
let _ = ProvingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
circuit_settings,
)
.map_err(|e| JsError::new(&format!("Failed to deserialize proving key: {}", e)))?;
Ok(true)
}
/// Settings file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn settingsValidation(settings: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {
let _: GraphSettings = serde_json::from_slice(&settings[..])
.map_err(|e| JsError::new(&format!("Failed to deserialize settings: {}", e)))?;
Ok(true)
}
/// Srs file validation
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn srsValidation(srs: wasm_bindgen::Clamped<Vec<u8>>) -> Result<bool, JsError> {
let mut reader = std::io::BufReader::new(&srs[..]);
let _: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader)
.map_err(|e| JsError::new(&format!("Failed to deserialize params: {}", e)))?;
Ok(true)
}
// HELPER FUNCTIONS
/// Creates a [ProvingKey] for a [GraphCircuit] (`circuit`) with specific [CommitmentScheme] parameters (`params`) for the WASM target
#[cfg(target_arch = "wasm32")]
pub fn create_vk_wasm<Scheme: CommitmentScheme, F: PrimeField + TensorType, C: Circuit<F>>(
circuit: &C,
params: &'_ Scheme::ParamsProver,
compress_selectors: bool,
) -> Result<VerifyingKey<Scheme::Curve>, halo2_proofs::plonk::Error>
where
C: Circuit<Scheme::Scalar>,
<Scheme as CommitmentScheme>::Scalar: FromUniformBytes<64>,
{
// Real proof
let empty_circuit = <C as Circuit<F>>::without_witnesses(circuit);
// Initialize the verifying key
let vk = keygen_vk_custom(params, &empty_circuit, compress_selectors)?;
Ok(vk)
}
/// Creates a [ProvingKey] from a [VerifyingKey] for a [GraphCircuit] (`circuit`) with specific [CommitmentScheme] parameters (`params`) for the WASM target
#[cfg(target_arch = "wasm32")]
pub fn create_pk_wasm<Scheme: CommitmentScheme, F: PrimeField + TensorType, C: Circuit<F>>(
vk: VerifyingKey<Scheme::Curve>,
circuit: &C,
params: &'_ Scheme::ParamsProver,
) -> Result<ProvingKey<Scheme::Curve>, halo2_proofs::plonk::Error>
where
C: Circuit<Scheme::Scalar>,
<Scheme as CommitmentScheme>::Scalar: FromUniformBytes<64>,
{
// Real proof
let empty_circuit = <C as Circuit<F>>::without_witnesses(circuit);
// Initialize the proving key
let pk = keygen_pk(params, vk, &empty_circuit)?;
Ok(pk)
}
///
pub fn u8_array_to_u128_le(arr: [u8; 16]) -> u128 {
let mut n: u128 = 0;
for &b in arr.iter().rev() {
n <<= 8;
n |= b as u128;
}
n
}
| https://github.com/zkonduit/ezkl |
tests/integration_tests.rs | #[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod native_tests {
use ezkl::circuit::Tolerance;
use ezkl::fieldutils::{felt_to_i128, i128_to_felt};
// use ezkl::circuit::table::RESERVED_BLINDING_ROWS_PAD;
use ezkl::graph::input::{FileSource, FileSourceInner, GraphData};
use ezkl::graph::{DataSource, GraphSettings, GraphWitness};
use ezkl::Commitments;
use lazy_static::lazy_static;
use rand::Rng;
use std::env::var;
use std::io::{Read, Write};
use std::process::{Child, Command};
use std::sync::Once;
static COMPILE: Once = Once::new();
#[allow(dead_code)]
static COMPILE_WASM: Once = Once::new();
static ENV_SETUP: Once = Once::new();
//Sure to run this once
#[derive(Debug)]
#[allow(dead_code)]
enum Hardfork {
London,
ArrowGlacier,
GrayGlacier,
Paris,
Shanghai,
Latest,
}
lazy_static! {
static ref CARGO_TARGET_DIR: String =
var("CARGO_TARGET_DIR").unwrap_or_else(|_| "./target".to_string());
static ref ANVIL_URL: String = "http://localhost:3030".to_string();
static ref LIMITLESS_ANVIL_URL: String = "http://localhost:8545".to_string();
static ref ANVIL_DEFAULT_PRIVATE_KEY: String =
"ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80".to_string();
}
fn start_anvil(limitless: bool, hardfork: Hardfork) -> Child {
let mut args = vec!["-p"];
if limitless {
args.push("8545");
args.push("--code-size-limit=41943040");
args.push("--disable-block-gas-limit");
} else {
args.push("3030");
}
match hardfork {
Hardfork::Paris => args.push("--hardfork=paris"),
Hardfork::London => args.push("--hardfork=london"),
Hardfork::Latest => {}
Hardfork::Shanghai => args.push("--hardfork=shanghai"),
Hardfork::ArrowGlacier => args.push("--hardfork=arrowGlacier"),
Hardfork::GrayGlacier => args.push("--hardfork=grayGlacier"),
}
let child = Command::new("anvil")
.args(args)
.spawn()
.expect("failed to start anvil process");
std::thread::sleep(std::time::Duration::from_secs(3));
child
}
fn init_binary() {
COMPILE.call_once(|| {
println!("using cargo target dir: {}", *CARGO_TARGET_DIR);
build_ezkl();
});
}
///
#[allow(dead_code)]
pub fn init_wasm() {
COMPILE_WASM.call_once(|| {
build_wasm_ezkl();
});
}
fn setup_py_env() {
ENV_SETUP.call_once(|| {
// supposes that you have a virtualenv called .env and have run the following
// equivalent of python -m venv .env
// source .env/bin/activate
// pip install -r requirements.txt
// maturin develop --release --features python-bindings
// now install torch, pandas, numpy, seaborn, jupyter
let status = Command::new("pip")
.args(["install", "numpy", "onnxruntime", "onnx"])
.stdout(std::process::Stdio::null())
.status()
.expect("failed to execute process");
assert!(status.success());
});
}
fn download_srs(logrows: u32, commitment: Commitments) {
// if does not exist, download it
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"get-srs",
"--logrows",
&format!("{}", logrows),
"--commitment",
&commitment.to_string(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
fn init_params(settings_path: std::path::PathBuf) {
println!("using settings path: {}", settings_path.to_str().unwrap());
// read in settings json
let settings =
std::fs::read_to_string(settings_path).expect("failed to read settings file");
// read in to GraphSettings object
let settings: GraphSettings = serde_json::from_str(&settings).unwrap();
let logrows = settings.run_args.logrows;
download_srs(logrows, settings.run_args.commitment.into());
}
fn mv_test_(test_dir: &str, test: &str) {
let path: std::path::PathBuf = format!("{}/{}", test_dir, test).into();
if !path.exists() {
let status = Command::new("cp")
.args([
"-R",
&format!("./examples/onnx/{}", test),
&format!("{}/{}", test_dir, test),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
}
fn mk_data_batches_(test_dir: &str, test: &str, output_dir: &str, num_batches: usize) {
let path: std::path::PathBuf = format!("{}/{}", test_dir, test).into();
if !path.exists() {
panic!("test_dir does not exist")
} else {
// copy the directory
let status = Command::new("cp")
.args([
"-R",
&format!("{}/{}", test_dir, test),
&format!("{}/{}", test_dir, output_dir),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let data = GraphData::from_path(format!("{}/{}/input.json", test_dir, test).into())
.expect("failed to load input data");
let input_data = match data.input_data {
DataSource::File(data) => data,
_ => panic!("Only File data sources support batching"),
};
let duplicated_input_data: FileSource = input_data
.iter()
.map(|data| (0..num_batches).flat_map(|_| data.clone()).collect())
.collect();
let duplicated_data = GraphData::new(DataSource::File(duplicated_input_data));
let res =
duplicated_data.save(format!("{}/{}/input.json", test_dir, output_dir).into());
assert!(res.is_ok());
}
}
const PF_FAILURE: &str = "examples/test_failure_proof.json";
const PF_FAILURE_AGGR: &str = "examples/test_failure_aggr_proof.json";
const LARGE_TESTS: [&str; 5] = [
"self_attention",
"nanoGPT",
"multihead_attention",
"mobilenet",
"mnist_gan",
];
const ACCURACY_CAL_TESTS: [&str; 6] = [
"accuracy",
"1l_mlp",
"4l_relu_conv_fc",
"1l_elu",
"1l_prelu",
"1l_tiny_div",
];
const TESTS: [&str; 92] = [
"1l_mlp", //0
"1l_slice",
"1l_concat",
"1l_flatten",
// "1l_average",
"1l_div",
"1l_pad", // 5
"1l_reshape",
"1l_eltwise_div",
"1l_sigmoid",
"1l_sqrt",
"1l_softmax", //10
// "1l_instance_norm",
"1l_batch_norm",
"1l_prelu",
"1l_leakyrelu",
"1l_gelu_noappx",
// "1l_gelu_tanh_appx",
"1l_relu", //15
"1l_downsample",
"1l_tanh",
"2l_relu_sigmoid_small",
"2l_relu_fc",
"2l_relu_small", //20
"2l_relu_sigmoid",
"1l_conv",
"2l_sigmoid_small",
"2l_relu_sigmoid_conv",
"3l_relu_conv_fc", //25
"4l_relu_conv_fc",
"1l_erf",
"1l_var",
"1l_elu",
"min", //30
"max",
"1l_max_pool",
"1l_conv_transpose",
"1l_upsample",
"1l_identity", //35
"idolmodel",
"trig",
"prelu_gmm",
"lstm",
"rnn", //40
"quantize_dequantize",
"1l_where",
"boolean",
"boolean_identity",
"decision_tree", // 45
"random_forest",
"gradient_boosted_trees",
"1l_topk",
"xgboost",
"lightgbm", //50
"hummingbird_decision_tree",
"oh_decision_tree",
"linear_svc",
"gather_elements",
"less", //55
"xgboost_reg",
"1l_powf",
"scatter_elements",
"1l_linear",
"linear_regression", //60
"sklearn_mlp",
"1l_mean",
"rounding_ops",
// "mean_as_constrain",
"arange",
"layernorm", //65
"bitwise_ops",
"blackman_window",
"softsign", //68
"softplus",
"selu", //70
"hard_sigmoid",
"log_softmax",
"eye",
"ltsf",
"remainder", //75
"bitshift",
"gather_nd",
"scatter_nd",
"celu",
"gru", // 80
"hard_swish", // 81
"hard_max",
"tril", // 83
"triu", // 84
"logsumexp", // 85
"clip",
"mish",
"reducel1",
"reducel2", // 89
"1l_lppool",
"lstm_large", // 91
];
const WASM_TESTS: [&str; 46] = [
"1l_mlp",
"1l_slice",
"1l_concat",
"1l_flatten",
// "1l_average",
"1l_div",
"1l_pad",
"1l_reshape",
"1l_eltwise_div",
"1l_sigmoid",
"1l_sqrt",
"1l_softmax",
// "1l_instance_norm",
"1l_batch_norm",
"1l_prelu",
"1l_leakyrelu",
"1l_gelu_noappx",
// "1l_gelu_tanh_appx",
"1l_relu",
"1l_downsample",
"1l_tanh",
"2l_relu_sigmoid_small",
"2l_relu_fc",
"2l_relu_small",
"2l_relu_sigmoid",
"1l_conv",
"2l_sigmoid_small",
"2l_relu_sigmoid_conv",
"3l_relu_conv_fc",
"4l_relu_conv_fc",
"1l_erf",
"1l_var",
"1l_elu",
"min",
"max",
"1l_max_pool",
"1l_conv_transpose",
"1l_upsample",
"1l_identity",
// "idolmodel",
"trig",
"prelu_gmm",
"lstm",
"rnn",
"quantize_dequantize",
"1l_where",
"boolean",
"boolean_identity",
"gradient_boosted_trees",
"1l_topk",
// "xgboost",
// "lightgbm",
// "hummingbird_decision_tree",
];
#[cfg(not(feature = "icicle"))]
const TESTS_AGGR: [&str; 21] = [
"1l_mlp",
"1l_flatten",
"1l_average",
"1l_reshape",
"1l_div",
"1l_pad",
"1l_sigmoid",
"1l_gelu_noappx",
"1l_sqrt",
"1l_prelu",
"1l_var",
"1l_leakyrelu",
"1l_relu",
"1l_tanh",
"2l_relu_fc",
"2l_relu_sigmoid_small",
"2l_relu_small",
"1l_conv",
"min",
"max",
"1l_max_pool",
];
#[cfg(feature = "icicle")]
const TESTS_AGGR: [&str; 3] = ["1l_mlp", "1l_flatten", "1l_average"];
const TESTS_EVM: [&str; 23] = [
"1l_mlp",
"1l_flatten",
"1l_average",
"1l_reshape",
"1l_sigmoid",
"1l_div",
"1l_sqrt",
"1l_prelu",
"1l_var",
"1l_leakyrelu",
"1l_gelu_noappx",
"1l_relu",
"1l_tanh",
"2l_relu_sigmoid_small",
"2l_relu_small",
"min",
"max",
"1l_max_pool",
"idolmodel",
"1l_identity",
"lstm",
"rnn",
"quantize_dequantize",
];
const TESTS_EVM_AGGR: [&str; 18] = [
"1l_mlp",
"1l_reshape",
"1l_sigmoid",
"1l_div",
"1l_sqrt",
"1l_prelu",
"1l_var",
"1l_leakyrelu",
"1l_gelu_noappx",
"1l_relu",
"1l_tanh",
"2l_relu_sigmoid_small",
"2l_relu_small",
"2l_relu_fc",
"min",
"max",
"idolmodel",
"1l_identity",
];
const EXAMPLES: [&str; 2] = ["mlp_4d_einsum", "conv2d_mnist"];
macro_rules! test_func_aggr {
() => {
#[cfg(test)]
mod tests_aggr {
use seq_macro::seq;
use crate::native_tests::TESTS_AGGR;
use test_case::test_case;
use crate::native_tests::aggr_prove_and_verify;
use crate::native_tests::kzg_aggr_mock_prove_and_verify;
use tempdir::TempDir;
use ezkl::Commitments;
#[cfg(not(feature="icicle"))]
seq!(N in 0..=20 {
#(#[test_case(TESTS_AGGR[N])])*
fn kzg_aggr_mock_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
kzg_aggr_mock_prove_and_verify(path, test.to_string());
test_dir.close().unwrap();
}
#(#[test_case(TESTS_AGGR[N])])*
fn kzg_aggr_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
aggr_prove_and_verify(path, test.to_string(), "private", "private", "public", Commitments::KZG);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_AGGR[N])])*
fn ipa_aggr_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
aggr_prove_and_verify(path, test.to_string(), "private", "private", "public", Commitments::IPA);
test_dir.close().unwrap();
}
});
#[cfg(feature="icicle")]
seq!(N in 0..=2 {
#(#[test_case(TESTS_AGGR[N])])*
fn aggr_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(test_dir.path().to_str().unwrap(), test);
aggr_prove_and_verify(path, test.to_string(), "private", "private", "public", Commitments::KZG);
test_dir.close().unwrap();
}
});
}
};
}
macro_rules! test_func {
() => {
#[cfg(test)]
mod tests {
use seq_macro::seq;
use crate::native_tests::TESTS;
use crate::native_tests::WASM_TESTS;
use crate::native_tests::ACCURACY_CAL_TESTS;
use crate::native_tests::LARGE_TESTS;
use test_case::test_case;
use crate::native_tests::mock;
use crate::native_tests::accuracy_measurement;
use crate::native_tests::prove_and_verify;
use crate::native_tests::run_js_tests;
use crate::native_tests::render_circuit;
use crate::native_tests::model_serialization_different_binaries;
use rand::Rng;
use tempdir::TempDir;
use ezkl::Commitments;
#[test]
fn model_serialization_different_binaries_() {
let test = "1l_mlp";
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap();
crate::native_tests::mv_test_(path, test);
// percent tolerance test
model_serialization_different_binaries(path, test.to_string());
test_dir.close().unwrap();
}
seq!(N in 0..=5 {
#(#[test_case(ACCURACY_CAL_TESTS[N])])*
fn mock_accuracy_cal_tests(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "public", "fixed", "public", 1, "accuracy", None, 0.0);
test_dir.close().unwrap();
}
});
seq!(N in 0..=91 {
#(#[test_case(TESTS[N])])*
#[ignore]
fn render_circuit_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
render_circuit(path, test.to_string());
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn accuracy_measurement_div_rebase_(test: &str) {
crate::native_tests::init_binary();
crate::native_tests::setup_py_env();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
accuracy_measurement(path, test.to_string(), "private", "private", "public", 1, "accuracy", 2.6, true);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn accuracy_measurement_public_outputs_(test: &str) {
crate::native_tests::init_binary();
crate::native_tests::setup_py_env();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
accuracy_measurement(path, test.to_string(), "private", "private", "public", 1, "accuracy", 2.6, false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn accuracy_measurement_fixed_params_(test: &str) {
crate::native_tests::init_binary();
crate::native_tests::setup_py_env();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
accuracy_measurement(path, test.to_string(), "private", "fixed", "private", 1, "accuracy", 2.6 , false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn accuracy_measurement_public_inputs_(test: &str) {
crate::native_tests::init_binary();
crate::native_tests::setup_py_env();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
accuracy_measurement(path, test.to_string(), "public", "private", "private", 1, "accuracy", 2.6, false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn resources_accuracy_measurement_public_outputs_(test: &str) {
crate::native_tests::init_binary();
crate::native_tests::setup_py_env();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
accuracy_measurement(path, test.to_string(), "private", "private", "public", 1, "resources", 3.1, false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_public_outputs_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "private", "private", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_tolerance_public_outputs_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
// gen random number between 0.0 and 1.0
let tolerance = rand::thread_rng().gen_range(0.0..1.0) * 100.0;
mock(path, test.to_string(), "private", "private", "public", 1, "resources", None, tolerance);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_large_batch_public_outputs_(test: &str) {
// currently variable output rank is not supported in ONNX
if test != "gather_nd" && test != "lstm_large" {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let large_batch_dir = &format!("large_batches_{}", test);
crate::native_tests::mk_data_batches_(path, test, &large_batch_dir, 10);
mock(path, large_batch_dir.to_string(), "private", "private", "public", 10, "resources", None, 0.0);
test_dir.close().unwrap();
}
}
#(#[test_case(TESTS[N])])*
fn mock_public_inputs_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "public", "private", "private", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_fixed_inputs_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "fixed", "private", "private", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_fixed_outputs_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "private", "private", "fixed", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_fixed_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "private", "fixed", "private", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_input_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "hashed", "private", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_kzg_input_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "polycommit", "private", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "private", "hashed", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_kzg_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "private", "polycommit", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_output_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "public", "private", "hashed", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_kzg_output_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "public", "private", "polycommit", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_output_fixed_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "public", "fixed", "hashed", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_output_kzg_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "public", "polycommit", "hashed", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_kzg_all_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "polycommit", "polycommit", "polycommit", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_input_output_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "hashed", "private", "hashed", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_input_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
// needs an extra row for the large model
mock(path, test.to_string(),"hashed", "hashed", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn mock_hashed_all_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
// needs an extra row for the large model
mock(path, test.to_string(),"hashed", "hashed", "hashed", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_single_col(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_triple_col(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 3, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_quadruple_col(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 4, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_octuple_col(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 8, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_tight_lookup_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 1, None, false, "single", Commitments::KZG, 1);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn ipa_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 1, None, false, "single", Commitments::IPA, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_public_input_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "public", "private", "public", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_fixed_params_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "fixed", "public", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_hashed_output(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "hashed", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn kzg_prove_and_verify_kzg_output(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "polycommit", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(TESTS[N])])*
fn ipa_prove_and_verify_ipa_output(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "polycommit", 1, None, false, "single", Commitments::IPA, 2);
test_dir.close().unwrap();
}
});
seq!(N in 0..=45 {
#(#[test_case(WASM_TESTS[N])])*
fn kzg_prove_and_verify_with_overflow_(test: &str) {
crate::native_tests::init_binary();
// crate::native_tests::init_wasm();
let test_dir = TempDir::new(test).unwrap();
env_logger::init();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "private", "public", 1, None, true, "single", Commitments::KZG, 2);
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testWasm", false);
// test_dir.close().unwrap();
}
#(#[test_case(WASM_TESTS[N])])*
fn kzg_prove_and_verify_with_overflow_hashed_inputs_(test: &str) {
crate::native_tests::init_binary();
// crate::native_tests::init_wasm();
let test_dir = TempDir::new(test).unwrap();
env_logger::init();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "hashed", "private", "public", 1, None, true, "single", Commitments::KZG, 2);
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testWasm", false);
// test_dir.close().unwrap();
}
#(#[test_case(WASM_TESTS[N])])*
fn kzg_prove_and_verify_with_overflow_fixed_params_(test: &str) {
crate::native_tests::init_binary();
// crate::native_tests::init_wasm();
let test_dir = TempDir::new(test).unwrap();
env_logger::init();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "safe", "private", "fixed", "public", 1, None, true, "single", Commitments::KZG, 2);
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testWasm", false);
test_dir.close().unwrap();
}
});
seq!(N in 0..=4 {
#(#[test_case(LARGE_TESTS[N])])*
#[ignore]
fn large_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
prove_and_verify(path, test.to_string(), "unsafe", "private", "fixed", "public", 1, None, false, "single", Commitments::KZG, 2);
test_dir.close().unwrap();
}
#(#[test_case(LARGE_TESTS[N])])*
#[ignore]
fn large_mock_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
mock(path, test.to_string(), "private", "fixed", "public", 1, "resources", None, 0.0);
test_dir.close().unwrap();
}
});
}
};
}
macro_rules! test_func_evm {
() => {
#[cfg(test)]
mod tests_evm {
use seq_macro::seq;
use crate::native_tests::TESTS_EVM;
use crate::native_tests::TESTS_EVM_AGGR;
use test_case::test_case;
use crate::native_tests::kzg_evm_prove_and_verify;
use crate::native_tests::kzg_evm_prove_and_verify_render_seperately;
use crate::native_tests::kzg_evm_on_chain_input_prove_and_verify;
use crate::native_tests::kzg_evm_aggr_prove_and_verify;
use tempdir::TempDir;
use crate::native_tests::Hardfork;
use crate::native_tests::run_js_tests;
/// Currently only on chain inputs that return a non-negative value are supported.
const TESTS_ON_CHAIN_INPUT: [&str; 17] = [
"1l_mlp",
"1l_average",
"1l_reshape",
"1l_sigmoid",
"1l_div",
"1l_sqrt",
"1l_prelu",
"1l_var",
"1l_leakyrelu",
"1l_gelu_noappx",
"1l_relu",
"1l_tanh",
"2l_relu_sigmoid_small",
"2l_relu_small",
"2l_relu_fc",
"min",
"max"
];
seq!(N in 0..=16 {
#(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::Latest))])*
#(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::Paris))])*
#(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::London))])*
#(#[test_case((TESTS_ON_CHAIN_INPUT[N],Hardfork::Shanghai))])*
fn kzg_evm_on_chain_input_prove_and_verify_(test: (&str,Hardfork)) {
let (test,hardfork) = test;
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(true, hardfork);
kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), "on-chain", "file", "public", "private");
// test_dir.close().unwrap();
}
#(#[test_case(TESTS_ON_CHAIN_INPUT[N])])*
fn kzg_evm_on_chain_output_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(true, Hardfork::Latest);
kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), "file", "on-chain", "private", "public");
// test_dir.close().unwrap();
}
#(#[test_case(TESTS_ON_CHAIN_INPUT[N])])*
fn kzg_evm_on_chain_input_output_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(true, Hardfork::Latest);
kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), "on-chain", "on-chain", "public", "public");
test_dir.close().unwrap();
}
#(#[test_case(TESTS_ON_CHAIN_INPUT[N])])*
fn kzg_evm_on_chain_input_output_hashed_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(true, Hardfork::Latest);
kzg_evm_on_chain_input_prove_and_verify(path, test.to_string(), "on-chain", "on-chain", "hashed", "hashed");
test_dir.close().unwrap();
}
});
seq!(N in 0..=17 {
// these take a particularly long time to run
#(#[test_case(TESTS_EVM_AGGR[N])])*
#[ignore]
fn kzg_evm_aggr_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_aggr_prove_and_verify(path, test.to_string(), "private", "private", "public");
test_dir.close().unwrap();
}
});
seq!(N in 0..=22 {
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "private", "private", "public");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_prove_and_verify_render_seperately_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify_render_seperately(2, path, test.to_string(), "private", "private", "public");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", true);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_hashed_input_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let mut _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "hashed", "private", "private");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case((TESTS_EVM[N], Hardfork::Latest))])*
#(#[test_case((TESTS_EVM[N], Hardfork::Paris))])*
#(#[test_case((TESTS_EVM[N], Hardfork::London))])*
#(#[test_case((TESTS_EVM[N], Hardfork::Shanghai))])*
fn kzg_evm_kzg_input_prove_and_verify_(test: (&str, Hardfork)) {
let (test,hardfork) = test;
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let mut _anvil_child = crate::native_tests::start_anvil(false, hardfork);
kzg_evm_prove_and_verify(2, path, test.to_string(), "polycommit", "private", "public");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_hashed_params_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "private", "hashed", "public");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_hashed_output_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "private", "private", "hashed");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_kzg_params_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "private", "polycommit", "public");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_kzg_output_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "private", "private", "polycommit");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
#(#[test_case(TESTS_EVM[N])])*
fn kzg_evm_kzg_all_prove_and_verify_(test: &str) {
crate::native_tests::init_binary();
let test_dir = TempDir::new(test).unwrap();
let path = test_dir.path().to_str().unwrap(); crate::native_tests::mv_test_(path, test);
let _anvil_child = crate::native_tests::start_anvil(false, Hardfork::Latest);
kzg_evm_prove_and_verify(2, path, test.to_string(), "polycommit", "polycommit", "polycommit");
#[cfg(not(feature = "icicle"))]
run_js_tests(path, test.to_string(), "testBrowserEvmVerify", false);
test_dir.close().unwrap();
}
});
}
};
}
macro_rules! test_func_examples {
() => {
#[cfg(test)]
mod tests_examples {
use seq_macro::seq;
use crate::native_tests::EXAMPLES;
use test_case::test_case;
use crate::native_tests::run_example as run;
seq!(N in 0..=1 {
#(#[test_case(EXAMPLES[N])])*
fn example_(test: &str) {
run(test.to_string());
}
});
}
};
}
test_func!();
test_func_aggr!();
test_func_evm!();
test_func_examples!();
fn model_serialization_different_binaries(test_dir: &str, example_name: String) {
let status = Command::new("cargo")
.args([
"run",
"--bin",
"ezkl",
"--",
"gen-settings",
"-M",
format!("{}/{}/network.onnx", test_dir, example_name).as_str(),
&format!(
"--settings-path={}/{}/settings.json",
test_dir, example_name
),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new("cargo")
.args([
"run",
"--bin",
"ezkl",
"--",
"compile-circuit",
"-M",
format!("{}/{}/network.onnx", test_dir, example_name).as_str(),
"--compiled-circuit",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
&format!(
"--settings-path={}/{}/settings.json",
test_dir, example_name
),
])
.status()
.expect("failed to execute process");
assert!(status.success());
// now alter binary slightly
// create new temp cargo.toml with a different version
// cpy old cargo.toml to cargo.toml.bak
let status = Command::new("cp")
.args(["Cargo.toml", "Cargo.toml.bak"])
.status()
.expect("failed to execute process");
assert!(status.success());
let mut cargo_toml = std::fs::File::open("Cargo.toml").unwrap();
let mut cargo_toml_contents = String::new();
cargo_toml.read_to_string(&mut cargo_toml_contents).unwrap();
let mut cargo_toml_contents = cargo_toml_contents.split('\n').collect::<Vec<_>>();
// draw a random version number from 0.0.0 to 0.100.100
let mut rng = rand::thread_rng();
let version = &format!(
"version = \"0.{}.{}-test\"",
rng.gen_range(0..100),
rng.gen_range(0..100)
);
let cargo_toml_contents = cargo_toml_contents
.iter_mut()
.map(|line| {
if line.starts_with("version") {
*line = version;
}
*line
})
.collect::<Vec<_>>();
let mut cargo_toml = std::fs::File::create("Cargo.toml").unwrap();
cargo_toml
.write_all(cargo_toml_contents.join("\n").as_bytes())
.unwrap();
let status = Command::new("cargo")
.args([
"run",
"--bin",
"ezkl",
"--",
"gen-witness",
"-D",
&format!("{}/{}/input.json", test_dir, example_name),
"-M",
&format!("{}/{}/network.compiled", test_dir, example_name),
"-O",
&format!("{}/{}/witness.json", test_dir, example_name),
])
.status()
.expect("failed to execute process");
assert!(status.success());
// now delete cargo.toml and move cargo.toml.bak to cargo.toml
let status = Command::new("rm")
.args(["Cargo.toml"])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new("mv")
.args(["Cargo.toml.bak", "Cargo.toml"])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// Mock prove (fast, but does not cover some potential issues)
fn run_example(example_name: String) {
let status = Command::new("cargo")
.args(["run", "--release", "--example", example_name.as_str()])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// Mock prove (fast, but does not cover some potential issues)
#[allow(clippy::too_many_arguments)]
fn mock(
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
batch_size: usize,
cal_target: &str,
scales_to_use: Option<Vec<u32>>,
tolerance: f32,
) {
let mut tolerance = tolerance;
gen_circuit_settings_and_witness(
test_dir,
example_name.clone(),
input_visibility,
param_visibility,
output_visibility,
batch_size,
cal_target,
scales_to_use,
2,
false,
&mut tolerance,
Commitments::KZG,
2,
);
if tolerance > 0.0 {
// load witness and shift the output by a small amount that is less than tolerance percent
let witness = GraphWitness::from_path(
format!("{}/{}/witness.json", test_dir, example_name).into(),
)
.unwrap();
let witness = witness.clone();
let outputs = witness.outputs.clone();
// get values as i128
let output_perturbed_safe: Vec<Vec<halo2curves::bn256::Fr>> = outputs
.iter()
.map(|sv| {
sv.iter()
.map(|v| {
// randomly perturb by a small amount less than tolerance
let perturbation = if v == &halo2curves::bn256::Fr::zero() {
halo2curves::bn256::Fr::zero()
} else {
i128_to_felt(
(felt_to_i128(*v) as f32
* (rand::thread_rng().gen_range(-0.01..0.01) * tolerance))
as i128,
)
};
*v + perturbation
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
// get values as i128
let output_perturbed_bad: Vec<Vec<halo2curves::bn256::Fr>> = outputs
.iter()
.map(|sv| {
sv.iter()
.map(|v| {
// randomly perturb by a small amount less than tolerance
let perturbation = if v == &halo2curves::bn256::Fr::zero() {
halo2curves::bn256::Fr::from(2)
} else {
i128_to_felt(
(felt_to_i128(*v) as f32
* (rand::thread_rng().gen_range(0.02..0.1) * tolerance))
as i128,
)
};
*v + perturbation
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let good_witness = GraphWitness {
outputs: output_perturbed_safe,
..witness.clone()
};
// save
good_witness
.save(format!("{}/{}/witness_ok.json", test_dir, example_name).into())
.unwrap();
let bad_witness = GraphWitness {
outputs: output_perturbed_bad,
..witness.clone()
};
// save
bad_witness
.save(format!("{}/{}/witness_bad.json", test_dir, example_name).into())
.unwrap();
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"mock",
"-W",
format!("{}/{}/witness.json", test_dir, example_name).as_str(),
"-M",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"mock",
"-W",
format!("{}/{}/witness_ok.json", test_dir, example_name).as_str(),
"-M",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"mock",
"-W",
format!("{}/{}/witness_bad.json", test_dir, example_name).as_str(),
"-M",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
])
.status()
.expect("failed to execute process");
assert!(!status.success());
} else {
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"mock",
"-W",
format!("{}/{}/witness.json", test_dir, example_name).as_str(),
"-M",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
}
#[allow(clippy::too_many_arguments)]
fn gen_circuit_settings_and_witness(
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
batch_size: usize,
cal_target: &str,
scales_to_use: Option<Vec<u32>>,
num_inner_columns: usize,
div_rebasing: bool,
tolerance: &mut f32,
commitment: Commitments,
lookup_safety_margin: usize,
) {
let mut args = vec![
"gen-settings".to_string(),
"-M".to_string(),
format!("{}/{}/network.onnx", test_dir, example_name),
format!(
"--settings-path={}/{}/settings.json",
test_dir, example_name
),
format!("--variables=batch_size->{}", batch_size),
format!("--input-visibility={}", input_visibility),
format!("--param-visibility={}", param_visibility),
format!("--output-visibility={}", output_visibility),
format!("--num-inner-cols={}", num_inner_columns),
format!("--tolerance={}", tolerance),
format!("--commitment={}", commitment),
];
if div_rebasing {
args.push("--div-rebasing".to_string());
};
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(args)
.stdout(std::process::Stdio::null())
.status()
.expect("failed to execute process");
assert!(status.success());
let mut calibrate_args = vec![
"calibrate-settings".to_string(),
"--data".to_string(),
format!("{}/{}/input.json", test_dir, example_name),
"-M".to_string(),
format!("{}/{}/network.onnx", test_dir, example_name),
format!(
"--settings-path={}/{}/settings.json",
test_dir, example_name
),
format!("--target={}", cal_target),
format!("--lookup-safety-margin={}", lookup_safety_margin),
];
if let Some(scales) = scales_to_use {
let scales = scales
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>()
.join(",");
calibrate_args.push("--scales".to_string());
calibrate_args.push(scales);
}
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(calibrate_args)
.status()
.expect("failed to execute process");
assert!(status.success());
let mut settings =
GraphSettings::load(&format!("{}/{}/settings.json", test_dir, example_name).into())
.unwrap();
let any_output_scales_smol = settings.model_output_scales.iter().any(|s| *s <= 0);
if any_output_scales_smol {
// set the tolerance to 0.0
settings.run_args.tolerance = Tolerance {
val: 0.0,
scale: 0.0.into(),
};
settings
.save(&format!("{}/{}/settings.json", test_dir, example_name).into())
.unwrap();
*tolerance = 0.0;
}
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"compile-circuit",
"-M",
format!("{}/{}/network.onnx", test_dir, example_name).as_str(),
"--compiled-circuit",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
&format!(
"--settings-path={}/{}/settings.json",
test_dir, example_name
),
])
.stdout(std::process::Stdio::null())
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"gen-witness",
"-D",
&format!("{}/{}/input.json", test_dir, example_name),
"-M",
&format!("{}/{}/network.compiled", test_dir, example_name),
"-O",
&format!("{}/{}/witness.json", test_dir, example_name),
])
.stdout(std::process::Stdio::null())
.status()
.expect("failed to execute process");
assert!(status.success());
}
// Mock prove (fast, but does not cover some potential issues)
#[allow(clippy::too_many_arguments)]
fn accuracy_measurement(
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
batch_size: usize,
cal_target: &str,
target_perc: f32,
div_rebasing: bool,
) {
gen_circuit_settings_and_witness(
test_dir,
example_name.clone(),
input_visibility,
param_visibility,
output_visibility,
batch_size,
cal_target,
None,
2,
div_rebasing,
&mut 0.0,
Commitments::KZG,
2,
);
println!(
" ------------ running accuracy measurement for {}",
example_name
);
// run python ./output_comparison.py in the test dir
let status = Command::new("python")
.args([
"tests/output_comparison.py",
&format!("{}/{}/network.onnx", test_dir, example_name),
&format!("{}/{}/input.json", test_dir, example_name),
&format!("{}/{}/witness.json", test_dir, example_name),
&format!("{}/{}/settings.json", test_dir, example_name),
&format!("{}", target_perc),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// Mock prove (fast, but does not cover some potential issues)
fn render_circuit(test_dir: &str, example_name: String) {
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"render-circuit",
"-M",
format!("{}/{}/network.onnx", test_dir, example_name).as_str(),
"-O",
format!("{}/{}/render.png", test_dir, example_name).as_str(),
"--lookup-range=-32768->32768",
"-K=17",
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// prove-serialize-verify, the usual full path
fn kzg_aggr_mock_prove_and_verify(test_dir: &str, example_name: String) {
prove_and_verify(
test_dir,
example_name.clone(),
"safe",
"private",
"private",
"public",
2,
None,
false,
"for-aggr",
Commitments::KZG,
2,
);
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"mock-aggregate",
"--logrows=23",
"--aggregation-snarks",
&format!("{}/{}/proof.pf", test_dir, example_name),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// prove-serialize-verify, the usual full path
fn aggr_prove_and_verify(
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
commitment: Commitments,
) {
prove_and_verify(
test_dir,
example_name.clone(),
"safe",
input_visibility,
param_visibility,
output_visibility,
2,
None,
false,
"for-aggr",
Commitments::KZG,
2,
);
download_srs(23, commitment);
// now setup-aggregate
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"setup-aggregate",
"--sample-snarks",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--logrows=23",
"--vk-path",
&format!("{}/{}/aggr.vk", test_dir, example_name),
"--pk-path",
&format!("{}/{}/aggr.pk", test_dir, example_name),
&format!("--commitment={}", commitment),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"aggregate",
"--logrows=23",
"--aggregation-snarks",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--proof-path",
&format!("{}/{}/aggr.pf", test_dir, example_name),
"--pk-path",
&format!("{}/{}/aggr.pk", test_dir, example_name),
&format!("--commitment={}", commitment),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"verify-aggr",
"--logrows=23",
"--proof-path",
&format!("{}/{}/aggr.pf", test_dir, example_name),
"--vk-path",
&format!("{}/{}/aggr.vk", test_dir, example_name),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// prove-serialize-verify, the usual full path
fn kzg_evm_aggr_prove_and_verify(
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
) {
aggr_prove_and_verify(
test_dir,
example_name.clone(),
input_visibility,
param_visibility,
output_visibility,
Commitments::KZG,
);
download_srs(23, Commitments::KZG);
let vk_arg = &format!("{}/{}/aggr.vk", test_dir, example_name);
fn build_args<'a>(base_args: Vec<&'a str>, sol_arg: &'a str) -> Vec<&'a str> {
let mut args = base_args;
args.push("--sol-code-path");
args.push(sol_arg);
args
}
let sol_arg = format!("{}/{}/kzg_aggr.sol", test_dir, example_name);
let addr_path_arg = format!("--addr-path={}/{}/addr.txt", test_dir, example_name);
let rpc_arg = format!("--rpc-url={}", *ANVIL_URL);
let settings_arg = format!("{}/{}/settings.json", test_dir, example_name);
let private_key = format!("--private-key={}", *ANVIL_DEFAULT_PRIVATE_KEY);
let base_args = vec![
"create-evm-verifier-aggr",
"--vk-path",
vk_arg.as_str(),
"--aggregation-settings",
settings_arg.as_str(),
"--logrows=23",
];
let args = build_args(base_args, &sol_arg);
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(args)
.status()
.expect("failed to execute process");
assert!(status.success());
// deploy the verifier
let args = vec![
"deploy-evm-verifier",
rpc_arg.as_str(),
addr_path_arg.as_str(),
"--sol-code-path",
sol_arg.as_str(),
private_key.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// read in the address
let addr = std::fs::read_to_string(format!("{}/{}/addr.txt", test_dir, example_name))
.expect("failed to read address file");
let deployed_addr_arg = format!("--addr-verifier={}", addr);
let pf_arg = format!("{}/{}/aggr.pf", test_dir, example_name);
let mut base_args = vec![
"verify-evm",
"--proof-path",
pf_arg.as_str(),
deployed_addr_arg.as_str(),
rpc_arg.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&base_args)
.status()
.expect("failed to execute process");
assert!(status.success());
// As sanity check, add example that should fail.
base_args[2] = PF_FAILURE_AGGR;
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(base_args)
.status()
.expect("failed to execute process");
assert!(!status.success());
}
// prove-serialize-verify, the usual full path
#[allow(clippy::too_many_arguments)]
fn prove_and_verify(
test_dir: &str,
example_name: String,
checkmode: &str,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
num_inner_columns: usize,
scales_to_use: Option<Vec<u32>>,
overflow: bool,
proof_type: &str,
commitment: Commitments,
lookup_safety_margin: usize,
) {
let target_str = if overflow {
"resources/col-overflow"
} else {
"resources"
};
gen_circuit_settings_and_witness(
test_dir,
example_name.clone(),
input_visibility,
param_visibility,
output_visibility,
1,
target_str,
scales_to_use,
num_inner_columns,
false,
&mut 0.0,
commitment,
lookup_safety_margin,
);
let settings_path = format!("{}/{}/settings.json", test_dir, example_name);
init_params(settings_path.clone().into());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"setup",
"-M",
&format!("{}/{}/network.compiled", test_dir, example_name),
"--pk-path",
&format!("{}/{}/key.pk", test_dir, example_name),
"--vk-path",
&format!("{}/{}/key.vk", test_dir, example_name),
"--disable-selector-compression",
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"prove",
"-W",
format!("{}/{}/witness.json", test_dir, example_name).as_str(),
"-M",
format!("{}/{}/network.compiled", test_dir, example_name).as_str(),
"--proof-path",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--pk-path",
&format!("{}/{}/key.pk", test_dir, example_name),
&format!("--check-mode={}", checkmode),
&format!("--proof-type={}", proof_type),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"swap-proof-commitments",
"--proof-path",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--witness-path",
format!("{}/{}/witness.json", test_dir, example_name).as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"verify",
format!("--settings-path={}", settings_path).as_str(),
"--proof-path",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--vk-path",
&format!("{}/{}/key.vk", test_dir, example_name),
])
.status()
.expect("failed to execute process");
assert!(status.success());
// load settings file
let settings =
std::fs::read_to_string(settings_path.clone()).expect("failed to read settings file");
let graph_settings = serde_json::from_str::<GraphSettings>(&settings)
.expect("failed to parse settings file");
// get_srs for the graph_settings_num_instances
download_srs(1, graph_settings.run_args.commitment.into());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"verify",
format!("--settings-path={}", settings_path).as_str(),
"--proof-path",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--vk-path",
&format!("{}/{}/key.vk", test_dir, example_name),
"--reduced-srs",
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
// prove-serialize-verify, the usual full path
fn kzg_evm_prove_and_verify(
num_inner_columns: usize,
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
) {
let anvil_url = ANVIL_URL.as_str();
prove_and_verify(
test_dir,
example_name.clone(),
"safe",
input_visibility,
param_visibility,
output_visibility,
num_inner_columns,
None,
false,
"single",
Commitments::KZG,
2,
);
let settings_path = format!("{}/{}/settings.json", test_dir, example_name);
init_params(settings_path.clone().into());
let vk_arg = format!("{}/{}/key.vk", test_dir, example_name);
let rpc_arg = format!("--rpc-url={}", anvil_url);
let addr_path_arg = format!("--addr-path={}/{}/addr.txt", test_dir, example_name);
let settings_arg = format!("--settings-path={}", settings_path);
// create the verifier
let mut args = vec!["create-evm-verifier", "--vk-path", &vk_arg, &settings_arg];
let sol_arg = format!("{}/{}/kzg.sol", test_dir, example_name);
// create everything to test the pipeline
args.push("--sol-code-path");
args.push(sol_arg.as_str());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// deploy the verifier
let mut args = vec![
"deploy-evm-verifier",
rpc_arg.as_str(),
addr_path_arg.as_str(),
];
args.push("--sol-code-path");
args.push(sol_arg.as_str());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// read in the address
let addr = std::fs::read_to_string(format!("{}/{}/addr.txt", test_dir, example_name))
.expect("failed to read address file");
let deployed_addr_arg = format!("--addr-verifier={}", addr);
// now verify the proof
let pf_arg = format!("{}/{}/proof.pf", test_dir, example_name);
let mut args = vec![
"verify-evm",
"--proof-path",
pf_arg.as_str(),
rpc_arg.as_str(),
deployed_addr_arg.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// As sanity check, add example that should fail.
args[2] = PF_FAILURE;
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(args)
.status()
.expect("failed to execute process");
assert!(!status.success());
}
// prove-serialize-verify, the usual full path
fn kzg_evm_prove_and_verify_render_seperately(
num_inner_columns: usize,
test_dir: &str,
example_name: String,
input_visibility: &str,
param_visibility: &str,
output_visibility: &str,
) {
let anvil_url = ANVIL_URL.as_str();
prove_and_verify(
test_dir,
example_name.clone(),
"safe",
input_visibility,
param_visibility,
output_visibility,
num_inner_columns,
None,
false,
"single",
Commitments::KZG,
2,
);
let settings_path = format!("{}/{}/settings.json", test_dir, example_name);
init_params(settings_path.clone().into());
let vk_arg = format!("{}/{}/key.vk", test_dir, example_name);
let rpc_arg = format!("--rpc-url={}", anvil_url);
let addr_path_arg = format!("--addr-path={}/{}/addr.txt", test_dir, example_name);
let settings_arg = format!("--settings-path={}", settings_path);
let sol_arg = format!("--sol-code-path={}/{}/kzg.sol", test_dir, example_name);
// create the verifier
let args = vec![
"create-evm-verifier",
"--vk-path",
&vk_arg,
&settings_arg,
&sol_arg,
"--render-vk-seperately",
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
let addr_path_arg_vk = format!("--addr-path={}/{}/addr_vk.txt", test_dir, example_name);
let sol_arg_vk = format!("--sol-code-path={}/{}/vk.sol", test_dir, example_name);
// create the verifier
let args = vec![
"create-evm-vk",
"--vk-path",
&vk_arg,
&settings_arg,
&sol_arg_vk,
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// deploy the verifier
let args = vec![
"deploy-evm-verifier",
rpc_arg.as_str(),
addr_path_arg.as_str(),
sol_arg.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// read in the address
let addr = std::fs::read_to_string(format!("{}/{}/addr.txt", test_dir, example_name))
.expect("failed to read address file");
let deployed_addr_arg = format!("--addr-verifier={}", addr);
// deploy the vk
let args = vec![
"deploy-evm-vk",
rpc_arg.as_str(),
addr_path_arg_vk.as_str(),
sol_arg_vk.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// read in the address
let addr_vk = std::fs::read_to_string(format!("{}/{}/addr_vk.txt", test_dir, example_name))
.expect("failed to read address file");
let deployed_addr_arg_vk = format!("--addr-vk={}", addr_vk);
// now verify the proof
let pf_arg = format!("{}/{}/proof.pf", test_dir, example_name);
let mut args = vec![
"verify-evm",
"--proof-path",
pf_arg.as_str(),
rpc_arg.as_str(),
deployed_addr_arg.as_str(),
deployed_addr_arg_vk.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// As sanity check, add example that should fail.
args[2] = PF_FAILURE;
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(args)
.status()
.expect("failed to execute process");
assert!(!status.success());
}
// run js browser evm verify tests for a given example
fn run_js_tests(test_dir: &str, example_name: String, js_test: &str, vk: bool) {
let example = format!("--example={}", example_name);
let dir = format!("--dir={}", test_dir);
let mut args = vec!["run", "test", js_test, &example, &dir];
let vk_string: String;
if vk {
vk_string = format!("--vk={}", vk);
args.push(&vk_string);
};
let status = Command::new("pnpm")
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
}
fn kzg_evm_on_chain_input_prove_and_verify(
test_dir: &str,
example_name: String,
input_source: &str,
output_source: &str,
input_visibility: &str,
output_visibility: &str,
) {
gen_circuit_settings_and_witness(
test_dir,
example_name.clone(),
input_visibility,
"private",
output_visibility,
1,
"resources",
// we need the accuracy
Some(vec![4]),
1,
false,
&mut 0.0,
Commitments::KZG,
2,
);
let model_path = format!("{}/{}/network.compiled", test_dir, example_name);
let settings_path = format!("{}/{}/settings.json", test_dir, example_name);
init_params(settings_path.clone().into());
let data_path = format!("{}/{}/input.json", test_dir, example_name);
let witness_path = format!("{}/{}/witness.json", test_dir, example_name);
let test_on_chain_data_path = format!("{}/{}/on_chain_input.json", test_dir, example_name);
let rpc_arg = format!("--rpc-url={}", LIMITLESS_ANVIL_URL.as_str());
let private_key = format!("--private-key={}", *ANVIL_DEFAULT_PRIVATE_KEY);
let test_input_source = format!("--input-source={}", input_source);
let test_output_source = format!("--output-source={}", output_source);
// load witness
let witness: GraphWitness = GraphWitness::from_path(witness_path.clone().into()).unwrap();
let mut input: GraphData = GraphData::from_path(data_path.clone().into()).unwrap();
if input_visibility == "hashed" {
let hashes = witness.processed_inputs.unwrap().poseidon_hash.unwrap();
input.input_data = DataSource::File(
hashes
.iter()
.map(|h| vec![FileSourceInner::Field(*h)])
.collect(),
);
}
if output_visibility == "hashed" {
let hashes = witness.processed_outputs.unwrap().poseidon_hash.unwrap();
input.output_data = Some(DataSource::File(
hashes
.iter()
.map(|h| vec![FileSourceInner::Field(*h)])
.collect(),
));
} else {
input.output_data = Some(DataSource::File(
witness
.pretty_elements
.unwrap()
.rescaled_outputs
.iter()
.map(|o| {
o.iter()
.map(|f| FileSourceInner::Float(f.parse().unwrap()))
.collect()
})
.collect(),
));
}
input.save(data_path.clone().into()).unwrap();
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"setup-test-evm-data",
"-D",
data_path.as_str(),
"-M",
&model_path,
"--test-data",
test_on_chain_data_path.as_str(),
rpc_arg.as_str(),
test_input_source.as_str(),
test_output_source.as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"setup",
"-M",
&model_path,
"--pk-path",
&format!("{}/{}/key.pk", test_dir, example_name),
"--vk-path",
&format!("{}/{}/key.vk", test_dir, example_name),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"prove",
"-W",
&witness_path,
"-M",
&model_path,
"--proof-path",
&format!("{}/{}/proof.pf", test_dir, example_name),
"--pk-path",
&format!("{}/{}/key.pk", test_dir, example_name),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let vk_arg = format!("{}/{}/key.vk", test_dir, example_name);
let settings_arg = format!("--settings-path={}", settings_path);
// create the verifier
let mut args = vec!["create-evm-verifier", "--vk-path", &vk_arg, &settings_arg];
let sol_arg = format!("{}/{}/kzg.sol", test_dir, example_name);
args.push("--sol-code-path");
args.push(sol_arg.as_str());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
let addr_path_verifier_arg = format!(
"--addr-path={}/{}/addr_verifier.txt",
test_dir, example_name
);
// deploy the verifier
let mut args = vec![
"deploy-evm-verifier",
rpc_arg.as_str(),
addr_path_verifier_arg.as_str(),
];
args.push("--sol-code-path");
args.push(sol_arg.as_str());
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
let sol_arg = format!("{}/{}/kzg.sol", test_dir, example_name);
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"create-evm-da",
&settings_arg,
"--sol-code-path",
sol_arg.as_str(),
"-D",
test_on_chain_data_path.as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let addr_path_da_arg = format!("--addr-path={}/{}/addr_da.txt", test_dir, example_name);
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"deploy-evm-da",
format!("--settings-path={}", settings_path).as_str(),
"-D",
test_on_chain_data_path.as_str(),
"--sol-code-path",
sol_arg.as_str(),
rpc_arg.as_str(),
addr_path_da_arg.as_str(),
private_key.as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let pf_arg = format!("{}/{}/proof.pf", test_dir, example_name);
// read in the verifier address
let addr_verifier =
std::fs::read_to_string(format!("{}/{}/addr_verifier.txt", test_dir, example_name))
.expect("failed to read address file");
let deployed_addr_verifier_arg = format!("--addr-verifier={}", addr_verifier);
// read in the da address
let addr_da = std::fs::read_to_string(format!("{}/{}/addr_da.txt", test_dir, example_name))
.expect("failed to read address file");
let deployed_addr_da_arg = format!("--addr-da={}", addr_da);
let args = vec![
"verify-evm",
"--proof-path",
pf_arg.as_str(),
deployed_addr_verifier_arg.as_str(),
deployed_addr_da_arg.as_str(),
rpc_arg.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// Create a new set of test on chain data
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args([
"setup-test-evm-data",
"-D",
data_path.as_str(),
"-M",
&model_path,
"--test-data",
test_on_chain_data_path.as_str(),
rpc_arg.as_str(),
test_input_source.as_str(),
test_output_source.as_str(),
])
.status()
.expect("failed to execute process");
assert!(status.success());
let deployed_addr_arg = format!("--addr={}", addr_da);
let args = vec![
"test-update-account-calls",
deployed_addr_arg.as_str(),
"-D",
test_on_chain_data_path.as_str(),
rpc_arg.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(&args)
.status()
.expect("failed to execute process");
assert!(status.success());
// As sanity check, add example that should fail.
let args = vec![
"verify-evm",
"--proof-path",
PF_FAILURE,
deployed_addr_verifier_arg.as_str(),
deployed_addr_da_arg.as_str(),
rpc_arg.as_str(),
];
let status = Command::new(format!("{}/release/ezkl", *CARGO_TARGET_DIR))
.args(args)
.status()
.expect("failed to execute process");
assert!(!status.success());
}
fn build_ezkl() {
#[cfg(feature = "icicle")]
let args = [
"build",
"--release",
"--bin",
"ezkl",
"--features",
"icicle",
];
#[cfg(not(feature = "icicle"))]
let args = ["build", "--release", "--bin", "ezkl"];
#[cfg(not(feature = "mv-lookup"))]
let args = [
"build",
"--release",
"--bin",
"ezkl",
"--no-default-features",
"--features",
"ezkl",
];
let status = Command::new("cargo")
.args(args)
.status()
.expect("failed to execute process");
assert!(status.success());
}
#[allow(dead_code)]
fn build_wasm_ezkl() {
// wasm-pack build --target nodejs --out-dir ./tests/wasm/nodejs . -- -Z build-std="panic_abort,std"
let status = Command::new("wasm-pack")
.args([
"build",
"--release",
"--target",
"nodejs",
"--out-dir",
"./tests/wasm/nodejs",
".",
"--",
"-Z",
"build-std=panic_abort,std",
])
.status()
.expect("failed to execute process");
assert!(status.success());
// fix the memory size
// sed -i "3s|.*|imports['env'] = {memory: new WebAssembly.Memory({initial:20,maximum:65536,shared:true})}|" tests/wasm/nodejs/ezkl.js
let status = Command::new("sed")
.args([
"-i",
// is required on macos
// "\".js\"",
"3s|.*|imports['env'] = {memory: new WebAssembly.Memory({initial:20,maximum:65536,shared:true})}|",
"./tests/wasm/nodejs/ezkl.js",
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
}
| https://github.com/zkonduit/ezkl |
tests/output_comparison.py | import ezkl
import json
import onnx
import onnxruntime
import numpy as np
import sys
def get_ezkl_output(witness_file, settings_file):
# convert the quantized ezkl output to float value
witness_output = json.load(open(witness_file))
outputs = witness_output['outputs']
with open(settings_file) as f:
settings = json.load(f)
ezkl_outputs = [[ezkl.felt_to_float(
outputs[i][j], settings['model_output_scales'][i]) for j in range(len(outputs[i]))] for i in range(len(outputs))]
return ezkl_outputs
def get_onnx_output(model_file, input_file):
# generate the ML model output from the ONNX file
onnx_model = onnx.load(model_file)
onnx.checker.check_model(onnx_model)
with open(input_file) as f:
inputs = json.load(f)
# reshape the input to the model
num_inputs = len(onnx_model.graph.input)
onnx_input = dict()
for i in range(num_inputs):
input_node = onnx_model.graph.input[i]
dims = []
elem_type = input_node.type.tensor_type.elem_type
print("elem_type: ", elem_type)
for dim in input_node.type.tensor_type.shape.dim:
if dim.dim_value == 0:
dims.append(1)
else:
dims.append(dim.dim_value)
if elem_type == 6:
inputs_onnx = np.array(inputs['input_data'][i]).astype(
np.int32).reshape(dims)
elif elem_type == 7:
inputs_onnx = np.array(inputs['input_data'][i]).astype(
np.int64).reshape(dims)
elif elem_type == 9:
inputs_onnx = np.array(inputs['input_data'][i]).astype(
bool).reshape(dims)
else:
inputs_onnx = np.array(inputs['input_data'][i]).astype(
np.float32).reshape(dims)
onnx_input[input_node.name] = inputs_onnx
try:
onnx_session = onnxruntime.InferenceSession(model_file)
onnx_output = onnx_session.run(None, onnx_input)
except Exception as e:
print("error: ", e)
onnx_output = inputs['output_data']
print("onnx ", onnx_output)
return onnx_output[0]
def compare_outputs(zk_output, onnx_output):
# calculate percentage difference between the 2 outputs (which are lists)
res = []
contains_sublist = any(isinstance(sub, list) for sub in zk_output)
print("zk ", zk_output)
if contains_sublist:
try:
if len(onnx_output) == 1:
zk_output = zk_output[0]
except Exception as e:
zk_output = zk_output[0]
print("zk ", zk_output)
zip_object = zip(np.array(zk_output).flatten(),
np.array(onnx_output).flatten())
for (i, (list1_i, list2_i)) in enumerate(zip_object):
if list1_i == 0.0 and list2_i == 0.0:
res.append(0)
else:
diff = list1_i - list2_i
res.append(100 * (diff) / (list2_i))
# iterate and print the diffs if they are greater than 0.0
if abs(diff) > 0.0:
print("------- index: ", i)
print("------- diff: ", diff)
print("------- zk_output: ", list1_i)
print("------- onnx_output: ", list2_i)
return res
if __name__ == '__main__':
# model file is first argument to script
model_file = sys.argv[1]
# input file is second argument to script
input_file = sys.argv[2]
# witness file is third argument to script
witness_file = sys.argv[3]
# settings file is fourth argument to script
settings_file = sys.argv[4]
# target
target = float(sys.argv[5])
# get the ezkl output
ezkl_output = get_ezkl_output(witness_file, settings_file)
# get the onnx output
onnx_output = get_onnx_output(model_file, input_file)
# compare the outputs
percentage_difference = compare_outputs(ezkl_output, onnx_output)
mean_percentage_difference = np.mean(np.abs(percentage_difference))
max_percentage_difference = np.max(np.abs(percentage_difference))
# print the percentage difference
print("mean percent diff: ", mean_percentage_difference)
print("max percent diff: ", max_percentage_difference)
assert mean_percentage_difference < target, "Percentage difference is too high"
| https://github.com/zkonduit/ezkl |
tests/py_integration_tests.rs | #[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod py_tests {
use lazy_static::lazy_static;
use std::env::var;
use std::process::{Child, Command};
use std::sync::Once;
use tempdir::TempDir;
static COMPILE: Once = Once::new();
static ENV_SETUP: Once = Once::new();
static DOWNLOAD_VOICE_DATA: Once = Once::new();
//Sure to run this once
lazy_static! {
static ref CARGO_TARGET_DIR: String =
var("CARGO_TARGET_DIR").unwrap_or_else(|_| "./target".to_string());
static ref ANVIL_URL: String = "http://localhost:3030".to_string();
}
fn start_anvil(limitless: bool) -> Child {
let mut args = vec!["-p", "3030"];
if limitless {
args.push("--code-size-limit=41943040");
args.push("--disable-block-gas-limit");
}
let child = Command::new("anvil")
.args(args)
// .stdout(Stdio::piped())
.spawn()
.expect("failed to start anvil process");
std::thread::sleep(std::time::Duration::from_secs(3));
child
}
fn download_voice_data() {
let voice_data_dir = shellexpand::tilde("~/data/voice_data");
DOWNLOAD_VOICE_DATA.call_once(|| {
let status = Command::new("bash")
.args(["examples/notebooks/voice_data.sh", &voice_data_dir])
.status()
.expect("failed to execute process");
assert!(status.success());
});
// set VOICE_DATA_DIR environment variable
std::env::set_var("VOICE_DATA_DIR", format!("{}", voice_data_dir));
}
fn setup_py_env() {
ENV_SETUP.call_once(|| {
// supposes that you have a virtualenv called .env and have run the following
// equivalent of python -m venv .env
// source .env/bin/activate
// pip install -r requirements.txt
// maturin develop --release --features python-bindings
// first install tf2onnx as it has protobuf conflict with onnx
let status = Command::new("pip")
.args(["install", "tf2onnx==1.16.1"])
.status()
.expect("failed to execute process");
assert!(status.success());
// now install torch, pandas, numpy, seaborn, jupyter
let status = Command::new("pip")
.args([
"install",
"torch-geometric==2.5.2",
"torch==2.2.2",
"torchvision==0.17.2",
"pandas==2.2.1",
"numpy==1.26.4",
"seaborn==0.13.2",
"notebook==7.1.2",
"nbconvert==7.16.3",
"onnx==1.16.0",
"kaggle==1.6.8",
"py-solc-x==2.0.2",
"web3==6.16.0",
"librosa==0.10.1",
"keras==3.1.1",
"tensorflow==2.16.1",
"tensorflow-datasets==4.9.4",
"pytorch-lightning==2.2.1",
"sk2torch==1.2.0",
"scikit-learn==1.4.1.post1",
"xgboost==2.0.3",
"hummingbird-ml==0.4.11",
"lightgbm==4.3.0",
])
.status()
.expect("failed to execute process");
assert!(status.success());
let status = Command::new("pip")
.args(["install", "numpy==1.23"])
.status()
.expect("failed to execute process");
assert!(status.success());
});
}
fn init_binary() {
COMPILE.call_once(|| {
println!("using cargo target dir: {}", *CARGO_TARGET_DIR);
setup_py_env();
});
}
fn mv_test_(test_dir: &str, test: &str) {
let path: std::path::PathBuf = format!("{}/{}", test_dir, test).into();
if !path.exists() {
let status = Command::new("cp")
.args([
"-R",
&format!("./examples/notebooks/{}", test),
&format!("{}/{}", test_dir, test),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
}
const TESTS: [&str; 32] = [
"proof_splitting.ipynb", // 0
"variance.ipynb",
"mnist_gan.ipynb",
// "mnist_vae.ipynb",
"keras_simple_demo.ipynb",
"mnist_gan_proof_splitting.ipynb", // 4
"hashed_vis.ipynb", // 5
"simple_demo_all_public.ipynb",
"data_attest.ipynb",
"little_transformer.ipynb",
"simple_demo_aggregated_proofs.ipynb",
"ezkl_demo.ipynb", // 10
"lstm.ipynb",
"set_membership.ipynb", // 12
"decision_tree.ipynb",
"random_forest.ipynb",
"gradient_boosted_trees.ipynb", // 15
"xgboost.ipynb",
"lightgbm.ipynb",
"svm.ipynb",
"simple_demo_public_input_output.ipynb",
"simple_demo_public_network_output.ipynb", // 20
"gcn.ipynb",
"linear_regression.ipynb",
"stacked_regression.ipynb",
"data_attest_hashed.ipynb",
"kzg_vis.ipynb", // 25
"kmeans.ipynb",
"solvency.ipynb",
"sklearn_mlp.ipynb",
"generalized_inverse.ipynb",
"mnist_classifier.ipynb", // 30
"world_rotation.ipynb",
];
macro_rules! test_func {
() => {
#[cfg(test)]
mod tests {
use seq_macro::seq;
use crate::py_tests::TESTS;
use test_case::test_case;
use super::*;
seq!(N in 0..=31 {
#(#[test_case(TESTS[N])])*
fn run_notebook_(test: &str) {
crate::py_tests::init_binary();
let mut limitless = false;
if test == TESTS[5] {
limitless = true;
}
let mut anvil_child = crate::py_tests::start_anvil(limitless);
let test_dir: TempDir = TempDir::new("nb").unwrap();
let path = test_dir.path().to_str().unwrap();
crate::py_tests::mv_test_(path, test);
run_notebook(path, test);
test_dir.close().unwrap();
anvil_child.kill().unwrap();
}
});
#[test]
fn voice_notebook_() {
crate::py_tests::init_binary();
let mut anvil_child = crate::py_tests::start_anvil(false);
crate::py_tests::download_voice_data();
let test_dir: TempDir = TempDir::new("voice_judge").unwrap();
let path = test_dir.path().to_str().unwrap();
crate::py_tests::mv_test_(path, "voice_judge.ipynb");
run_notebook(path, "voice_judge.ipynb");
test_dir.close().unwrap();
anvil_child.kill().unwrap();
}
#[test]
fn postgres_notebook_() {
crate::py_tests::init_binary();
let test_dir: TempDir = TempDir::new("mean_postgres").unwrap();
let path = test_dir.path().to_str().unwrap();
crate::py_tests::mv_test_(path, "mean_postgres.ipynb");
run_notebook(path, "mean_postgres.ipynb");
test_dir.close().unwrap();
}
#[test]
fn tictactoe_autoencoder_notebook_() {
crate::py_tests::init_binary();
let test_dir: TempDir = TempDir::new("tictactoe_autoencoder").unwrap();
let path = test_dir.path().to_str().unwrap();
crate::py_tests::mv_test_(path, "tictactoe_autoencoder.ipynb");
run_notebook(path, "tictactoe_autoencoder.ipynb");
test_dir.close().unwrap();
}
#[test]
fn tictactoe_binary_classification_notebook_() {
crate::py_tests::init_binary();
let test_dir: TempDir = TempDir::new("tictactoe_binary_classification").unwrap();
let path = test_dir.path().to_str().unwrap();
crate::py_tests::mv_test_(path, "tictactoe_binary_classification.ipynb");
run_notebook(path, "tictactoe_binary_classification.ipynb");
test_dir.close().unwrap();
}
#[test]
fn nbeats_notebook_() {
crate::py_tests::init_binary();
let test_dir: TempDir = TempDir::new("nbeats").unwrap();
let path = test_dir.path().to_str().unwrap();
crate::py_tests::mv_test_(path, "nbeats_timeseries_forecasting.ipynb");
crate::py_tests::mv_test_(path, "eth_price.csv");
run_notebook(path, "nbeats_timeseries_forecasting.ipynb");
test_dir.close().unwrap();
}
}
};
}
fn run_notebook(test_dir: &str, test: &str) {
// activate venv
let status = Command::new("bash")
.arg("-c")
.arg("source .env/bin/activate")
.status()
.expect("failed to execute process");
assert!(status.success());
let path: std::path::PathBuf = format!("{}/{}", test_dir, test).into();
let status = Command::new("jupyter")
.args([
"nbconvert",
"--to",
"notebook",
"--execute",
(path.to_str().unwrap()),
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
test_func!();
}
| https://github.com/zkonduit/ezkl |
tests/python/binding_tests.py | import ezkl
import os
import pytest
import json
import subprocess
import time
folder_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'.',
)
)
examples_path = os.path.abspath(
os.path.join(
folder_path,
'..',
'..',
'examples',
)
)
srs_path = os.path.join(folder_path, 'kzg_test.params')
params_k17_path = os.path.join(folder_path, 'kzg_test_k17.params')
params_k20_path = os.path.join(folder_path, 'kzg_test_k20.params')
anvil_url = "http://localhost:3030"
def setup_module(module):
"""setup anvil."""
global proc
# requires an anvil install
proc = subprocess.Popen(["anvil", "-p", "3030"])
time.sleep(1)
def teardown_module(module):
"""teardown anvil.
"""
proc.terminate()
def test_py_run_args():
"""
Test for PyRunArgs
"""
run_args = ezkl.PyRunArgs()
run_args.input_visibility = "hashed"
run_args.output_visibility = "hashed"
run_args.tolerance = 1.5
def test_poseidon_hash():
"""
Test for poseidon_hash
"""
message = [1.0, 2.0, 3.0, 4.0]
message = [ezkl.float_to_felt(x, 7) for x in message]
res = ezkl.poseidon_hash(message)
assert ezkl.felt_to_big_endian(
res[0]) == "0x0da7e5e5c8877242fa699f586baf770d731defd54f952d4adeb85047a0e32f45"
def test_field_serialization():
"""
Test field element serialization
"""
input = 890
scale = 7
felt = ezkl.float_to_felt(input, scale)
roundtrip_input = ezkl.felt_to_float(felt, scale)
assert input == roundtrip_input
input = -700
scale = 7
felt = ezkl.float_to_felt(input, scale)
roundtrip_input = ezkl.felt_to_float(felt, scale)
assert input == roundtrip_input
def test_buffer_to_felts():
"""
Test buffer_to_felt
"""
buffer = bytearray("a sample string!", 'utf-8')
felts = ezkl.buffer_to_felts(buffer)
ref_felt_1 = "0x0000000000000000000000000000000021676e6972747320656c706d61732061"
assert ezkl.felt_to_big_endian(felts[0]) == ref_felt_1
buffer = bytearray("a sample string!"+"high", 'utf-8')
felts = ezkl.buffer_to_felts(buffer)
ref_felt_2 = "0x0000000000000000000000000000000000000000000000000000000068676968"
assert [ezkl.felt_to_big_endian(felts[0]), ezkl.felt_to_big_endian(felts[1])] == [ref_felt_1, ref_felt_2]
def test_gen_srs():
"""
test for gen_srs() with 17 logrows and 20 logrows.
You may want to comment this test as it takes a long time to run
"""
ezkl.gen_srs(params_k17_path, 17)
assert os.path.isfile(params_k17_path)
ezkl.gen_srs(params_k20_path, 20)
assert os.path.isfile(params_k20_path)
def test_calibrate_over_user_range():
data_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'input.json'
)
model_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'network.onnx'
)
output_path = os.path.join(
folder_path,
'settings.json'
)
run_args = ezkl.PyRunArgs()
run_args.input_visibility = "hashed"
run_args.output_visibility = "hashed"
# TODO: Dictionary outputs
res = ezkl.gen_settings(
model_path, output_path, py_run_args=run_args)
assert res == True
res = ezkl.calibrate_settings(
data_path, model_path, output_path, "resources", 1, [0, 1, 2])
assert res == True
assert os.path.isfile(output_path)
def test_calibrate():
data_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'input.json'
)
model_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'network.onnx'
)
output_path = os.path.join(
folder_path,
'settings.json'
)
run_args = ezkl.PyRunArgs()
run_args.input_visibility = "hashed"
run_args.output_visibility = "hashed"
# TODO: Dictionary outputs
res = ezkl.gen_settings(
model_path, output_path, py_run_args=run_args)
assert res == True
res = ezkl.calibrate_settings(
data_path, model_path, output_path, "resources")
assert res == True
assert os.path.isfile(output_path)
def test_model_compile():
"""
Test for model compilation/serialization
"""
model_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'network.onnx'
)
compiled_model_path = os.path.join(
folder_path,
'model.compiled'
)
settings_path = os.path.join(
folder_path,
'settings.json'
)
res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)
assert res == True
def test_forward():
"""
Test for vanilla forward pass
"""
data_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'input.json'
)
model_path = os.path.join(
folder_path,
'model.compiled'
)
output_path = os.path.join(
folder_path,
'witness.json'
)
res = ezkl.gen_witness(data_path, model_path, output_path)
with open(output_path, "r") as f:
data = json.load(f)
assert data["inputs"] == res["inputs"]
assert data["outputs"] == res["outputs"]
assert data["processed_inputs"]["poseidon_hash"] == res["processed_inputs"]["poseidon_hash"]
assert data["processed_outputs"]["poseidon_hash"] == res["processed_outputs"]["poseidon_hash"]
def test_get_srs():
"""
Test for get_srs
"""
settings_path = os.path.join(folder_path, 'settings.json')
res = ezkl.get_srs(settings_path, srs_path=srs_path)
assert res == True
assert os.path.isfile(srs_path)
another_srs_path = os.path.join(folder_path, "kzg_test_k8.params")
res = ezkl.get_srs(logrows=8, srs_path=another_srs_path, commitment=ezkl.PyCommitments.KZG)
assert os.path.isfile(another_srs_path)
def test_mock():
"""
Test for mock
"""
data_path = os.path.join(
folder_path,
'witness.json'
)
model_path = os.path.join(
folder_path,
'model.compiled'
)
settings_path = os.path.join(folder_path, 'settings.json')
res = ezkl.mock(data_path, model_path)
assert res == True
def test_setup():
"""
Test for setup
"""
data_path = os.path.join(
folder_path,
'witness.json'
)
model_path = os.path.join(
folder_path,
'model.compiled'
)
pk_path = os.path.join(folder_path, 'test.pk')
vk_path = os.path.join(folder_path, 'test.vk')
settings_path = os.path.join(folder_path, 'settings.json')
res = ezkl.setup(
model_path,
vk_path,
pk_path,
srs_path=srs_path,
)
assert res == True
assert os.path.isfile(vk_path)
assert os.path.isfile(pk_path)
assert os.path.isfile(settings_path)
res = ezkl.gen_vk_from_pk_single(pk_path, settings_path, vk_path)
assert res == True
assert os.path.isfile(vk_path)
def test_setup_evm():
"""
Test for setup
"""
model_path = os.path.join(
folder_path,
'model.compiled'
)
pk_path = os.path.join(folder_path, 'test_evm.pk')
vk_path = os.path.join(folder_path, 'test_evm.vk')
res = ezkl.setup(
model_path,
vk_path,
pk_path,
srs_path=srs_path,
)
assert res == True
assert os.path.isfile(vk_path)
assert os.path.isfile(pk_path)
def test_prove_and_verify():
"""
Test for prove and verify
"""
data_path = os.path.join(
folder_path,
'witness.json'
)
model_path = os.path.join(
folder_path,
'model.compiled'
)
pk_path = os.path.join(folder_path, 'test.pk')
proof_path = os.path.join(folder_path, 'test.pf')
res = ezkl.prove(
data_path,
model_path,
pk_path,
proof_path,
"for-aggr",
srs_path=srs_path,
)
assert res['transcript_type'] == 'Poseidon'
assert os.path.isfile(proof_path)
settings_path = os.path.join(folder_path, 'settings.json')
vk_path = os.path.join(folder_path, 'test.vk')
res = ezkl.verify(proof_path, settings_path,
vk_path, srs_path)
assert res == True
assert os.path.isfile(vk_path)
def test_prove_evm():
"""
Test for prove using evm transcript
"""
data_path = os.path.join(
folder_path,
'witness.json'
)
model_path = os.path.join(
folder_path,
'model.compiled'
)
pk_path = os.path.join(folder_path, 'test_evm.pk')
proof_path = os.path.join(folder_path, 'test_evm.pf')
res = ezkl.prove(
data_path,
model_path,
pk_path,
proof_path,
"single",
srs_path=srs_path,
)
assert res['transcript_type'] == 'EVM'
assert os.path.isfile(proof_path)
def test_create_evm_verifier():
"""
Create EVM verifier with solidity code
In order to run this test you will need to install solc in your environment
"""
vk_path = os.path.join(folder_path, 'test_evm.vk')
settings_path = os.path.join(folder_path, 'settings.json')
sol_code_path = os.path.join(folder_path, 'test.sol')
abi_path = os.path.join(folder_path, 'test.abi')
res = ezkl.create_evm_verifier(
vk_path,
settings_path,
sol_code_path,
abi_path,
srs_path=srs_path,
)
assert res == True
assert os.path.isfile(sol_code_path)
def test_deploy_evm():
"""
Test deployment of the verifier smart contract
In order to run this you will need to install solc in your environment
"""
addr_path = os.path.join(folder_path, 'address.json')
sol_code_path = os.path.join(folder_path, 'test.sol')
# TODO: without optimization there will be out of gas errors
# sol_code_path = os.path.join(folder_path, 'test.sol')
res = ezkl.deploy_evm(
addr_path,
sol_code_path,
rpc_url=anvil_url,
)
assert res == True
def test_deploy_evm_with_private_key():
"""
Test deployment of the verifier smart contract using a custom private key
In order to run this you will need to install solc in your environment
"""
addr_path = os.path.join(folder_path, 'address.json')
sol_code_path = os.path.join(folder_path, 'test.sol')
# TODO: without optimization there will be out of gas errors
# sol_code_path = os.path.join(folder_path, 'test.sol')
anvil_default_private_key = "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
res = ezkl.deploy_evm(
addr_path,
sol_code_path,
rpc_url=anvil_url,
private_key=anvil_default_private_key
)
assert res == True
custom_zero_balance_private_key = "ff9dfe0b6d31e93ba13460a4d6f63b5e31dd9532b1304f1cbccea7092a042aa4"
with pytest.raises(RuntimeError, match="Failed to run deploy_evm"):
res = ezkl.deploy_evm(
addr_path,
sol_code_path,
rpc_url=anvil_url,
private_key=custom_zero_balance_private_key
)
def test_verify_evm():
"""
Verifies an evm proof
In order to run this you will need to install solc in your environment
"""
proof_path = os.path.join(folder_path, 'test_evm.pf')
addr_path = os.path.join(folder_path, 'address.json')
with open(addr_path, 'r') as file:
addr = file.read().rstrip()
print(addr)
# TODO: without optimization there will be out of gas errors
# sol_code_path = os.path.join(folder_path, 'test.sol')
res = ezkl.verify_evm(
addr,
proof_path,
rpc_url=anvil_url,
# sol_code_path
# optimizer_runs
)
assert res == True
def test_aggregate_and_verify_aggr():
data_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'input.json'
)
model_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'network.onnx'
)
compiled_model_path = os.path.join(
folder_path,
'compiled_relu.onnx'
)
pk_path = os.path.join(folder_path, '1l_relu.pk')
vk_path = os.path.join(folder_path, '1l_relu.vk')
settings_path = os.path.join(
folder_path, '1l_relu_aggr_settings.json')
# TODO: Dictionary outputs
res = ezkl.gen_settings(model_path, settings_path)
assert res == True
res = ezkl.calibrate_settings(
data_path, model_path, settings_path, "resources")
assert res == True
assert os.path.isfile(settings_path)
res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)
assert res == True
ezkl.setup(
compiled_model_path,
vk_path,
pk_path,
srs_path=srs_path,
)
proof_path = os.path.join(folder_path, '1l_relu.pf')
output_path = os.path.join(
folder_path,
'1l_relu_aggr_witness.json'
)
res = ezkl.gen_witness(data_path, compiled_model_path,
output_path)
ezkl.prove(
output_path,
compiled_model_path,
pk_path,
proof_path,
"for-aggr",
srs_path=srs_path,
)
# mock aggregate
res = ezkl.mock_aggregate([proof_path], 20)
assert res == True
aggregate_proof_path = os.path.join(folder_path, 'aggr_1l_relu.pf')
aggregate_vk_path = os.path.join(folder_path, 'aggr_1l_relu.vk')
aggregate_pk_path = os.path.join(folder_path, 'aggr_1l_relu.pk')
res = ezkl.setup_aggregate(
[proof_path],
aggregate_vk_path,
aggregate_pk_path,
20,
srs_path=params_k20_path,
)
res = ezkl.gen_vk_from_pk_aggr(aggregate_pk_path, aggregate_vk_path)
assert res == True
assert os.path.isfile(vk_path)
res = ezkl.aggregate(
[proof_path],
aggregate_proof_path,
aggregate_pk_path,
"poseidon",
20,
"unsafe",
srs_path=params_k20_path,
)
assert res == True
assert os.path.isfile(aggregate_proof_path)
assert os.path.isfile(aggregate_vk_path)
res = ezkl.verify_aggr(
aggregate_proof_path,
aggregate_vk_path,
20,
srs_path=params_k20_path,
)
assert res == True
def test_evm_aggregate_and_verify_aggr():
data_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'input.json'
)
model_path = os.path.join(
examples_path,
'onnx',
'1l_relu',
'network.onnx'
)
pk_path = os.path.join(folder_path, '1l_relu.pk')
vk_path = os.path.join(folder_path, '1l_relu.vk')
settings_path = os.path.join(
folder_path, '1l_relu_evm_aggr_settings.json')
ezkl.gen_settings(
model_path,
settings_path,
)
ezkl.calibrate_settings(
data_path,
model_path,
settings_path,
"resources",
)
compiled_model_path = os.path.join(
folder_path,
'compiled_relu.onnx'
)
res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)
assert res == True
ezkl.setup(
compiled_model_path,
vk_path,
pk_path,
srs_path=srs_path,
)
proof_path = os.path.join(folder_path, '1l_relu.pf')
output_path = os.path.join(
folder_path,
'1l_relu_aggr_evm_witness.json'
)
res = ezkl.gen_witness(data_path, compiled_model_path,
output_path)
ezkl.prove(
output_path,
compiled_model_path,
pk_path,
proof_path,
"for-aggr",
srs_path=srs_path,
)
aggregate_proof_path = os.path.join(folder_path, 'aggr_evm_1l_relu.pf')
aggregate_vk_path = os.path.join(folder_path, 'aggr_evm_1l_relu.vk')
aggregate_pk_path = os.path.join(folder_path, 'aggr_evm_1l_relu.pk')
res = ezkl.setup_aggregate(
[proof_path],
aggregate_vk_path,
aggregate_pk_path,
20,
srs_path=params_k20_path,
)
res = ezkl.aggregate(
[proof_path],
aggregate_proof_path,
aggregate_pk_path,
"evm",
20,
"unsafe",
srs_path=params_k20_path,
)
assert res == True
assert os.path.isfile(aggregate_proof_path)
assert os.path.isfile(aggregate_vk_path)
sol_code_path = os.path.join(folder_path, 'aggr_evm_1l_relu.sol')
abi_path = os.path.join(folder_path, 'aggr_evm_1l_relu.abi')
res = ezkl.create_evm_verifier_aggr(
[settings_path],
aggregate_vk_path,
sol_code_path,
abi_path,
logrows=20,
srs_path=params_k20_path,
)
assert res == True
assert os.path.isfile(sol_code_path)
addr_path = os.path.join(folder_path, 'address_aggr.json')
res = ezkl.deploy_evm(
addr_path,
sol_code_path,
rpc_url=anvil_url,
)
# as a sanity check
res = ezkl.verify_aggr(
aggregate_proof_path,
aggregate_vk_path,
20,
srs_path=params_k20_path,
)
assert res == True
# with open(addr_path, 'r') as file:
# addr_aggr = file.read().rstrip()
# res = ezkl.verify_evm(
# aggregate_proof_path,
# addr_aggr,
# rpc_url=anvil_url,
# )
# assert res == True
def get_examples():
EXAMPLES_OMIT = [
# these are too large
'mobilenet_large',
'mobilenet',
'doodles',
'nanoGPT',
"self_attention",
'multihead_attention',
'large_op_graph',
'1l_instance_norm',
'variable_cnn',
'accuracy',
'linear_regression',
"mnist_gan",
]
examples = []
for subdir, _, _ in os.walk(os.path.join(examples_path, "onnx")):
name = subdir.split('/')[-1]
if name in EXAMPLES_OMIT or name == "onnx":
continue
else:
examples.append((
os.path.join(subdir, "network.onnx"),
os.path.join(subdir, "input.json"),
))
return examples
@pytest.mark.parametrize("model_file, input_file", get_examples())
def test_all_examples(model_file, input_file):
"""Tests all examples in the examples folder"""
# gen settings
settings_path = os.path.join(folder_path, "settings.json")
compiled_model_path = os.path.join(folder_path, 'network.ezkl')
pk_path = os.path.join(folder_path, 'test.pk')
vk_path = os.path.join(folder_path, 'test.vk')
witness_path = os.path.join(folder_path, 'witness.json')
proof_path = os.path.join(folder_path, 'proof.json')
print("Testing example: ", model_file)
res = ezkl.gen_settings(model_file, settings_path)
assert res
res = ezkl.calibrate_settings(
input_file, model_file, settings_path, "resources")
assert res
print("Compiling example: ", model_file)
res = ezkl.compile_circuit(model_file, compiled_model_path, settings_path)
assert res
with open(settings_path, 'r') as f:
data = json.load(f)
logrows = data["run_args"]["logrows"]
srs_path = os.path.join(folder_path, f"srs_{logrows}")
# generate the srs file if the path does not exist
if not os.path.exists(srs_path):
print("Generating srs file: ", srs_path)
ezkl.gen_srs(os.path.join(folder_path, srs_path), logrows)
print("Setting up example: ", model_file)
res = ezkl.setup(
compiled_model_path,
vk_path,
pk_path,
srs_path
)
assert res == True
assert os.path.isfile(vk_path)
assert os.path.isfile(pk_path)
print("Generating witness for example: ", model_file)
res = ezkl.gen_witness(input_file, compiled_model_path, witness_path)
assert os.path.isfile(witness_path)
print("Proving example: ", model_file)
ezkl.prove(
witness_path,
compiled_model_path,
pk_path,
proof_path,
"single",
srs_path=srs_path,
)
assert os.path.isfile(proof_path)
print("Verifying example: ", model_file)
res = ezkl.verify(
proof_path,
settings_path,
vk_path,
srs_path=srs_path,
)
assert res == True
| https://github.com/zkonduit/ezkl |
tests/python/srs_utils.py | """
This is meant to be used locally for development.
Generating the SRS is costly so we run this instead of creating a new SRS each
time we run tests.
"""
import ezkl
import os
srs_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'.',
'kzg_test.params',
)
)
def gen_test_srs(logrows=17):
"""Generates a test srs with 17 log rows"""
ezkl.gen_srs(srs_path, logrows)
def delete_test_srs():
"""Deletes test srs after tests are done"""
os.remove(srs_path)
if __name__ == "__main__":
# gen_test_srs()
path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'..',
'examples',
'onnx',
'1l_average',
'network.onnx'
)
)
print(ezkl.table(path))
| https://github.com/zkonduit/ezkl |
tests/wasm.rs | #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
#[cfg(test)]
mod wasm32 {
use ezkl::circuit::modules::polycommit::PolyCommitChip;
use ezkl::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH};
use ezkl::circuit::modules::poseidon::PoseidonChip;
use ezkl::circuit::modules::Module;
use ezkl::graph::modules::POSEIDON_LEN_GRAPH;
use ezkl::graph::GraphCircuit;
use ezkl::graph::{GraphSettings, GraphWitness};
use ezkl::pfsys;
use ezkl::wasm::{
bufferToVecOfFelt, compiledCircuitValidation, encodeVerifierCalldata, feltToBigEndian,
feltToFloat, feltToInt, feltToLittleEndian, genPk, genVk, genWitness, inputValidation,
kzgCommit, pkValidation, poseidonHash, proofValidation, prove, settingsValidation,
srsValidation, u8_array_to_u128_le, verify, verifyAggr, vkValidation, witnessValidation,
};
use halo2_proofs::plonk::VerifyingKey;
use halo2_proofs::poly::commitment::CommitmentScheme;
use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme;
use halo2_proofs::poly::kzg::commitment::ParamsKZG;
use halo2_solidity_verifier::encode_calldata;
use halo2curves::bn256::Bn256;
use halo2curves::bn256::{Fr, G1Affine};
use snark_verifier::util::arithmetic::PrimeField;
use wasm_bindgen::JsError;
#[cfg(feature = "web")]
pub use wasm_bindgen_rayon::init_thread_pool;
use wasm_bindgen_test::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
pub const WITNESS: &[u8] = include_bytes!("../tests/wasm/witness.json");
pub const NETWORK_COMPILED: &[u8] = include_bytes!("../tests/wasm/model.compiled");
pub const NETWORK: &[u8] = include_bytes!("../tests/wasm/network.onnx");
pub const INPUT: &[u8] = include_bytes!("../tests/wasm/input.json");
pub const PROOF: &[u8] = include_bytes!("../tests/wasm/proof.json");
pub const PROOF_AGGR: &[u8] = include_bytes!("../tests/wasm/proof_aggr.json");
pub const SETTINGS: &[u8] = include_bytes!("../tests/wasm/settings.json");
pub const PK: &[u8] = include_bytes!("../tests/wasm/pk.key");
pub const VK: &[u8] = include_bytes!("../tests/wasm/vk.key");
pub const VK_AGGR: &[u8] = include_bytes!("../tests/wasm/vk_aggr.key");
pub const SRS: &[u8] = include_bytes!("../tests/wasm/kzg");
pub const SRS1: &[u8] = include_bytes!("../tests/wasm/kzg1.srs");
#[wasm_bindgen_test]
async fn can_verify_aggr() {
let value = verifyAggr(
wasm_bindgen::Clamped(PROOF_AGGR.to_vec()),
wasm_bindgen::Clamped(VK_AGGR.to_vec()),
21,
wasm_bindgen::Clamped(SRS1.to_vec()),
"kzg",
)
.map_err(|_| "failed")
.unwrap();
// should not fail
assert!(value);
}
#[wasm_bindgen_test]
async fn verify_encode_verifier_calldata() {
let ser_proof = wasm_bindgen::Clamped(PROOF.to_vec());
// with no vk address
let calldata = encodeVerifierCalldata(ser_proof.clone(), None)
.map_err(|_| "failed")
.unwrap();
let snark: pfsys::Snark<Fr, G1Affine> = serde_json::from_slice(&PROOF).unwrap();
let flattened_instances = snark.instances.into_iter().flatten();
let reference_calldata = encode_calldata(
None,
&snark.proof,
&flattened_instances.clone().collect::<Vec<_>>(),
);
assert_eq!(calldata, reference_calldata);
// with vk address
let vk_address = hex::decode("0000000000000000000000000000000000000000").unwrap();
let vk_address: [u8; 20] = {
let mut array = [0u8; 20];
array.copy_from_slice(&vk_address);
array
};
let serialized = serde_json::to_vec(&vk_address).unwrap();
let calldata = encodeVerifierCalldata(ser_proof, Some(serialized))
.map_err(|_| "failed")
.unwrap();
let reference_calldata = encode_calldata(
Some(vk_address),
&snark.proof,
&flattened_instances.collect::<Vec<_>>(),
);
assert_eq!(calldata, reference_calldata);
}
#[wasm_bindgen_test]
fn verify_kzg_commit() {
// create a vector of field elements Vec<Fr> and assign it to the message variable
let mut message: Vec<Fr> = vec![];
for i in 0..32 {
message.push(Fr::from(i as u64));
}
let message_ser = serde_json::to_vec(&message).unwrap();
let settings: GraphSettings = serde_json::from_slice(&SETTINGS).unwrap();
let mut reader = std::io::BufReader::new(SRS);
let params: ParamsKZG<Bn256> =
halo2_proofs::poly::commitment::Params::<'_, G1Affine>::read(&mut reader).unwrap();
let mut reader = std::io::BufReader::new(VK);
let vk = VerifyingKey::<G1Affine>::read::<_, GraphCircuit>(
&mut reader,
halo2_proofs::SerdeFormat::RawBytes,
settings.clone(),
)
.unwrap();
let commitment_ser = kzgCommit(
wasm_bindgen::Clamped(message_ser),
wasm_bindgen::Clamped(VK.to_vec()),
wasm_bindgen::Clamped(SETTINGS.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
)
.map_err(|_| "failed")
.unwrap();
let commitment: Vec<halo2curves::bn256::G1Affine> =
serde_json::from_slice(&commitment_ser[..]).unwrap();
let reference_commitment = PolyCommitChip::commit::<KZGCommitmentScheme<Bn256>>(
message,
(vk.cs().blinding_factors() + 1) as u32,
¶ms,
);
assert_eq!(commitment, reference_commitment);
}
#[wasm_bindgen_test]
async fn verify_field_serialization_roundtrip() {
for i in 0..32 {
let field_element = Fr::from(i);
let serialized = serde_json::to_vec(&field_element).unwrap();
let clamped = wasm_bindgen::Clamped(serialized);
let scale = 2;
let floating_point = feltToFloat(clamped.clone(), scale)
.map_err(|_| "failed")
.unwrap();
assert_eq!(floating_point, (i as f64) / 4.0);
let integer: i128 =
serde_json::from_slice(&feltToInt(clamped.clone()).map_err(|_| "failed").unwrap())
.unwrap();
assert_eq!(integer, i as i128);
let hex_string = format!("{:?}", field_element.clone());
let returned_string: String = feltToBigEndian(clamped.clone())
.map_err(|_| "failed")
.unwrap();
assert_eq!(hex_string, returned_string);
let repr = serde_json::to_string(&field_element).unwrap();
let little_endian_string: String = serde_json::from_str(&repr).unwrap();
let returned_string: String =
feltToLittleEndian(clamped).map_err(|_| "failed").unwrap();
assert_eq!(little_endian_string, returned_string);
}
}
#[wasm_bindgen_test]
async fn verify_buffer_to_field_elements() {
let string_high = String::from("high");
let mut buffer = string_high.clone().into_bytes();
let clamped = wasm_bindgen::Clamped(buffer.clone());
let field_elements_ser = bufferToVecOfFelt(clamped).map_err(|_| "failed").unwrap();
let field_elements: Vec<Fr> = serde_json::from_slice(&field_elements_ser[..]).unwrap();
buffer.resize(16, 0);
let reference_int = u8_array_to_u128_le(buffer.try_into().unwrap());
let reference_field_element_high = PrimeField::from_u128(reference_int);
assert_eq!(field_elements[0], reference_field_element_high);
// length 16 string (divisible by 16 so doesn't need padding)
let string_sample = String::from("a sample string!");
let buffer = string_sample.clone().into_bytes();
let clamped = wasm_bindgen::Clamped(buffer.clone());
let field_elements_ser = bufferToVecOfFelt(clamped).map_err(|_| "failed").unwrap();
let field_elements: Vec<Fr> = serde_json::from_slice(&field_elements_ser[..]).unwrap();
let reference_int = u8_array_to_u128_le(buffer.try_into().unwrap());
let reference_field_element_sample = PrimeField::from_u128(reference_int);
assert_eq!(field_elements[0], reference_field_element_sample);
let string_concat = string_sample + &string_high;
let buffer = string_concat.into_bytes();
let clamped = wasm_bindgen::Clamped(buffer.clone());
let field_elements_ser = bufferToVecOfFelt(clamped).map_err(|_| "failed").unwrap();
let field_elements: Vec<Fr> = serde_json::from_slice(&field_elements_ser[..]).unwrap();
assert_eq!(field_elements[0], reference_field_element_sample);
assert_eq!(field_elements[1], reference_field_element_high);
}
#[wasm_bindgen_test]
async fn verify_hash() {
let mut message: Vec<Fr> = vec![];
for i in 0..32 {
message.push(Fr::from(i as u64));
}
let message_ser = serde_json::to_vec(&message).unwrap();
let hash = poseidonHash(wasm_bindgen::Clamped(message_ser))
.map_err(|_| "failed")
.unwrap();
let hash: Vec<Vec<Fr>> = serde_json::from_slice(&hash[..]).unwrap();
let reference_hash =
PoseidonChip::<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>::run(
message.clone(),
)
.map_err(|_| "failed")
.unwrap();
assert_eq!(hash, reference_hash)
}
#[wasm_bindgen_test]
async fn verify_gen_witness() {
let witness = genWitness(
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(INPUT.to_vec()),
)
.map_err(|_| "failed")
.unwrap();
let witness: GraphWitness = serde_json::from_slice(&witness[..]).unwrap();
let reference_witness: GraphWitness = serde_json::from_slice(&WITNESS).unwrap();
// should not fail
assert_eq!(witness, reference_witness);
}
#[wasm_bindgen_test]
async fn gen_pk_test() {
let vk = genVk(
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
true,
)
.map_err(|_| "failed")
.unwrap();
let pk = genPk(
wasm_bindgen::Clamped(vk),
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
)
.map_err(|_| "failed")
.unwrap();
assert!(pk.len() > 0);
}
#[wasm_bindgen_test]
async fn gen_vk_test() {
let vk = genVk(
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
true,
)
.map_err(|_| "failed")
.unwrap();
assert!(vk.len() > 0);
}
#[wasm_bindgen_test]
async fn pk_is_valid_test() {
let vk = genVk(
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
true,
)
.map_err(|_| "failed")
.unwrap();
let pk = genPk(
wasm_bindgen::Clamped(vk.clone()),
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
)
.map_err(|_| "failed")
.unwrap();
// prove
let proof = prove(
wasm_bindgen::Clamped(WITNESS.to_vec()),
wasm_bindgen::Clamped(pk.clone()),
wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
)
.map_err(|_| "failed")
.unwrap();
assert!(proof.len() > 0);
let value = verify(
wasm_bindgen::Clamped(proof.to_vec()),
wasm_bindgen::Clamped(vk),
wasm_bindgen::Clamped(SETTINGS.to_vec()),
wasm_bindgen::Clamped(SRS.to_vec()),
)
.map_err(|_| "failed")
.unwrap();
// should not fail
assert!(value);
}
#[wasm_bindgen_test]
async fn verify_validations() {
// Run witness validation on network (should fail)
let witness = witnessValidation(wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()));
assert!(witness.is_err());
// Run witness validation on witness (should pass)
let witness = witnessValidation(wasm_bindgen::Clamped(WITNESS.to_vec()));
assert!(witness.is_ok());
// Run compiled circuit validation on onnx network (should fail)
let circuit = compiledCircuitValidation(wasm_bindgen::Clamped(NETWORK.to_vec()));
assert!(circuit.is_err());
// Run compiled circuit validation on comiled network (should pass)
let circuit = compiledCircuitValidation(wasm_bindgen::Clamped(NETWORK_COMPILED.to_vec()));
assert!(circuit.is_ok());
// Run input validation on witness (should fail)
let input = inputValidation(wasm_bindgen::Clamped(WITNESS.to_vec()));
assert!(input.is_err());
// Run input validation on input (should pass)
let input = inputValidation(wasm_bindgen::Clamped(INPUT.to_vec()));
assert!(input.is_ok());
// Run proof validation on witness (should fail)
let proof = proofValidation(wasm_bindgen::Clamped(WITNESS.to_vec()));
assert!(proof.is_err());
// Run proof validation on proof (should pass)
let proof = proofValidation(wasm_bindgen::Clamped(PROOF.to_vec()));
assert!(proof.is_ok());
// // Run vk validation on SRS (should fail)
// let vk = vkValidation(
// wasm_bindgen::Clamped(SRS.to_vec()),
// wasm_bindgen::Clamped(SETTINGS.to_vec())
// );
// assert!(vk.is_err());
// Run vk validation on vk (should pass)
let vk = vkValidation(
wasm_bindgen::Clamped(VK.to_vec()),
wasm_bindgen::Clamped(SETTINGS.to_vec()),
);
assert!(vk.is_ok());
// // Run pk validation on vk (should fail)
// let pk = pkValidation(
// wasm_bindgen::Clamped(VK.to_vec()),
// wasm_bindgen::Clamped(SETTINGS.to_vec())
// );
// assert!(pk.is_err());
// Run pk validation on pk (should pass)
let pk = pkValidation(
wasm_bindgen::Clamped(PK.to_vec()),
wasm_bindgen::Clamped(SETTINGS.to_vec()),
);
assert!(pk.is_ok());
// Run settings validation on proof (should fail)
let settings = settingsValidation(wasm_bindgen::Clamped(PROOF.to_vec()));
assert!(settings.is_err());
// Run settings validation on settings (should pass)
let settings = settingsValidation(wasm_bindgen::Clamped(SETTINGS.to_vec()));
assert!(settings.is_ok());
// // Run srs validation on vk (should fail)
// let srs = srsValidation(
// wasm_bindgen::Clamped(VK.to_vec())
// );
// assert!(srs.is_err());
// Run srs validation on srs (should pass)
let srs = srsValidation(wasm_bindgen::Clamped(SRS.to_vec()));
assert!(srs.is_ok());
}
}
| https://github.com/zkonduit/ezkl |
keras2circom/circom.py | # Ref: https://github.com/zk-ml/uchikoma/blob/main/python/uchikoma/circom.py
from __future__ import annotations
import typing
import os
from os import path
import json
from dataclasses import dataclass
import re
import numpy as np
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
# template string for circom
circom_template_string = '''pragma circom 2.0.0;
{include}
template Model() {brace_left}
{signal}
{component}
{main}
{brace_right}
component main = Model();
'''
templates: typing.Dict[str, Template] = {
}
def parse_shape(shape: typing.List[int]) -> str:
'''parse shape to integers enclosed by []'''
shape_str = ''
for dim in shape:
shape_str += '[{}]'.format(dim)
return shape_str
def parse_index(shape: typing.List[int]) -> str:
'''parse shape to indices enclosed by []'''
index_str = ''
for i in range(len(shape)):
index_str += '[i{}]'.format(i)
return index_str
@dataclass
class Template:
op_name: str
fpath: str
args: typing.Dict[str]
input_names: typing.List[str] = None
input_dims: typing.List[int] = None
output_names: typing.List[str] = None
output_dims: typing.List[int] = None
def __str__(self) -> str:
args_str = ', '.join(self.args)
args_str = '(' + args_str + ')'
return '{:>20}{:30} {}{}{}{} \t<-- {}'.format(
self.op_name, args_str,
self.input_names, self.input_dims,
self.output_names, self.output_dims,
self.fpath)
def file_parse(fpath):
'''parse circom file and register templates'''
with open(fpath, 'r') as f:
lines = f.read().split('\n')
lines = [l for l in lines if not l.strip().startswith('//')]
lines = ' '.join(lines)
lines = re.sub('/\*.*?\*/', 'IGN', lines)
funcs = re.findall('template (\w+) ?\((.*?)\) ?\{(.*?)\}', lines)
for func in funcs:
op_name = func[0].strip()
args = func[1].split(',')
main = func[2].strip()
assert op_name not in templates, \
'duplicated template: {} in {} vs. {}'.format(
op_name, templates[op_name].fpath, fpath)
signals = re.findall('signal (\w+) (\w+)(.*?);', main)
infos = [[] for i in range(4)]
for sig in signals:
sig_types = ['input', 'output']
assert sig[0] in sig_types, sig[1] + ' | ' + main
idx = sig_types.index(sig[0])
infos[idx*2+0].append(sig[1])
sig_dim = sig[2].count('[')
infos[idx*2+1].append(sig_dim)
templates[op_name] = Template(
op_name, fpath,
[a.strip() for a in args],
*infos)
def dir_parse(dir_path, skips=[]):
'''parse circom files in a directory'''
names = os.listdir(dir_path)
for name in names:
if name in skips:
continue
fpath = path.join(dir_path, name)
if os.path.isdir(fpath):
dir_parse(fpath)
elif os.path.isfile(fpath):
if fpath.endswith('.circom'):
file_parse(fpath)
@dataclass
class Signal:
name: str
shape: typing.List[int]
value: typing.Any = None
def inject_signal(self, comp_name: str) -> str:
'''inject signal into the beginning of the circuit'''
if self.value is not None or self.name == 'out' or self.name == 'remainder':
return 'signal input {}_{}{};\n'.format(
comp_name, self.name, parse_shape(self.shape))
return ''
def inject_main(self, comp_name: str, prev_comp_name: str = None, prev_signal: Signal = None) -> str:
'''inject signal into main'''
inject_str = ''
if self.value is not None or self.name == 'out' or self.name == 'remainder':
if comp_name.endswith('softmax') and self.name == 'out':
inject_str += '{}.out <== {}_out[0];\n'.format(
comp_name, comp_name)
return inject_str
for i in range(len(self.shape)):
inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\n'.format(
' '*i*4, i, i, self.shape[i], i)
if 'activation' in comp_name or 're_lu' in comp_name:
inject_str += '{}{}{}.{} <== {}_{}{};\n'.format(' '*(i+1)*4,
comp_name, parse_index(self.shape), self.name,
comp_name, self.name, parse_index(self.shape))
else:
inject_str += '{}{}.{}{} <== {}_{}{};\n'.format(' '*(i+1)*4,
comp_name, self.name, parse_index(self.shape),
comp_name, self.name, parse_index(self.shape))
inject_str += '}'*len(self.shape)+'\n'
return inject_str
if self.shape != prev_signal.shape:
raise ValueError('shape mismatch: {} vs. {}'.format(self.shape, prev_signal.shape))
for i in range(len(self.shape)):
inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\n'.format(
' '*i*4, i, i, self.shape[i], i)
if 'activation' in comp_name or 're_lu' in comp_name:
inject_str += '{}{}{}.{} <== {}.{}{};\n'.format(' '*(i+1)*4,
comp_name, parse_index(self.shape), self.name,
prev_comp_name, prev_signal.name, parse_index(self.shape))
elif 'activation' in prev_comp_name or 're_lu' in prev_comp_name:
inject_str += '{}{}.{}{} <== {}{}.{};\n'.format(' '*(i+1)*4,
comp_name, self.name, parse_index(self.shape),
prev_comp_name, parse_index(self.shape), prev_signal.name)
else:
inject_str += '{}{}.{}{} <== {}.{}{};\n'.format(' '*(i+1)*4,
comp_name, self.name, parse_index(self.shape),
prev_comp_name, prev_signal.name, parse_index(self.shape))
inject_str += '}'*len(self.shape)+'\n'
return inject_str
def inject_input_signal(self) -> str:
'''inject the circuit input signal'''
if self.value is not None:
raise ValueError('input signal should not have value')
return 'signal input in{};\n'.format(parse_shape(self.shape))
def inject_output_signal(self) -> str:
'''inject the circuit output signal'''
if self.value is not None:
raise ValueError('output signal should not have value')
return 'signal output out{};\n'.format(parse_shape(self.shape))
def inject_input_main(self, comp_name: str) -> str:
'''inject the circuit input signal into main'''
if self.value is not None:
raise ValueError('input signal should not have value')
inject_str = ''
for i in range(len(self.shape)):
inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\n'.format(
' '*i*4, i, i, self.shape[i], i)
inject_str += '{}{}.{}{} <== in{};\n'.format(' '*(i+1)*4,
comp_name, self.name, parse_index(self.shape),
parse_index(self.shape))
inject_str += '}'*len(self.shape)+'\n'
return inject_str
def inject_output_main(self, prev_comp_name: str, prev_signal: Signal) -> str:
'''inject the circuit output signal into main'''
if self.value is not None:
raise ValueError('output signal should not have value')
if self.shape != prev_signal.shape:
raise ValueError('shape mismatch: {} vs. {}'.format(self.shape, prev_signal.shape))
if 'softmax' in prev_comp_name:
return 'out[0] <== {}.out;\n'.format(prev_comp_name)
inject_str = ''
for i in range(len(self.shape)):
inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\n'.format(
' '*i*4, i, i, self.shape[i], i)
if 're_lu' in prev_comp_name:
inject_str += '{}out{} <== {}{}.{};\n'.format(' '*(i+1)*4,
parse_index(self.shape),
prev_comp_name, parse_index(self.shape), prev_signal.name)
else:
inject_str += '{}out{} <== {}.{}{};\n'.format(' '*(i+1)*4,
parse_index(self.shape),
prev_comp_name, prev_signal.name, parse_index(self.shape))
inject_str += '}'*len(self.shape)+'\n'
return inject_str
@dataclass
class Component:
name: str
template: Template
inputs: typing.List[Signal]
outputs: typing.List[Signal]
# optional args
args: typing.Dict[str, typing.Any] = None
def inject_include(self) -> str:
'''include the component template'''
return 'include "../{}";\n'.format(self.template.fpath)
def inject_signal(self, prev_comp: Component = None, last_comp: bool = False) -> str:
'''inject the component signals'''
inject_str = ''
for signal in self.inputs:
if signal.name == 'out' or signal.name == 'remainder':
inject_str += signal.inject_signal(self.name)
if last_comp is True and signal.name == 'out':
inject_str += signal.inject_output_signal()
elif signal.value is None and prev_comp is None:
inject_str += signal.inject_input_signal()
elif signal.value is not None:
inject_str += signal.inject_signal(self.name)
return inject_str
def inject_component(self) -> str:
'''inject the component declaration'''
if self.template.op_name == 'ReLU':
for signal in self.inputs:
if signal.name == 'out':
output_signal = signal
break
inject_str = 'component {}{};\n'.format(self.name, parse_shape(output_signal.shape))
for i in range(len(output_signal.shape)):
inject_str += '{}for (var i{} = 0; i{} < {}; i{}++) {{\n'.format(
' '*i*4, i, i, output_signal.shape[i], i)
inject_str += '{}{}{} = ReLU();\n'.format(' '*(i+1)*4,
self.name, parse_index(output_signal.shape))
inject_str += '}'*len(output_signal.shape)+'\n'
return inject_str
return 'component {} = {}({});\n'.format(
self.name, self.template.op_name, self.parse_args(self.template.args, self.args))
def inject_main(self, prev_comp: Component = None, last_comp: bool = False) -> str:
'''inject the component main'''
inject_str = ''
for signal in self.inputs:
if signal.value is not None or signal.name == 'out' or signal.name == 'remainder':
inject_str += signal.inject_main(self.name)
elif prev_comp is None:
inject_str += signal.inject_input_main(self.name)
else:
for sig in prev_comp.inputs:
if sig.name == 'out':
output_signal = sig
break
if output_signal is None:
output_signal = prev_comp.outputs[0]
inject_str += signal.inject_main(self.name, prev_comp.name, output_signal)
print
if last_comp:
for signal in self.inputs:
if signal.name == 'out':
inject_str += signal.inject_output_main(self.name, signal)
break
for signal in self.outputs:
inject_str += signal.inject_output_main(self.name, signal)
return inject_str
def to_json(self, dec: int) -> typing.Dict[str, typing.Any]:
'''convert the component params to json format'''
json_dict = {}
for signal in self.inputs:
if signal.value is not None:
if signal.name == 'bias' or signal.name == 'b':
scaling = float(10**(2*dec))
else:
scaling = float(10**dec)
value = [str(int(v*scaling)) for v in signal.value.flatten().tolist()]
# reshape the value to match the circom shape
if len(signal.shape) > 1:
value = np.array(value).reshape(signal.shape).tolist()
json_dict.update({f'{self.name}_{signal.name}': value})
return json_dict
@staticmethod
def parse_args(template_args: typing.List[str], args: typing.Dict[str, typing.Any]) -> str:
'''parse the args to a format string, ready to be injected'''
args_str = '{'+'}, {'.join(template_args)+'}'
return args_str.format(**args)
@dataclass
class Circuit:
components: typing.List[Component]
def __init__(self):
self.components = []
def add_component(self, component: Component):
self.components.append(component)
def add_components(self, components: typing.List[Component]):
self.components.extend(components)
def inject_include(self) -> str:
'''inject the include statements'''
inject_str = []
for component in self.components:
inject_str.append(component.inject_include())
return ''.join(set(inject_str))
def inject_signal(self) -> str:
'''inject the signal declarations'''
inject_str = self.components[0].inject_signal()
for i in range(1, len(self.components)):
inject_str += self.components[i].inject_signal(self.components[i-1], i==len(self.components)-1)
return inject_str
def inject_component(self) -> str:
'''inject the component declarations'''
inject_str = ''
for component in self.components:
inject_str += component.inject_component()
return inject_str
def inject_main(self) -> str:
'''inject the main template'''
inject_str = self.components[0].inject_main()
for i in range(1, len(self.components)):
inject_str += self.components[i].inject_main(self.components[i-1], i==len(self.components)-1)
return inject_str
def to_circom(self) -> str:
'''convert the circuit to a circom file'''
return circom_template_string.format(**{
'include': self.inject_include(),
'brace_left': '{',
'signal': self.inject_signal(),
'component': self.inject_component(),
'main': self.inject_main(),
'brace_right': '}',
})
def to_json(self, dec: int) -> str:
'''convert the model weights to json format'''
json_dict = {}
for component in self.components:
json_dict.update(component.to_json(dec))
return json.dumps(json_dict) | https://github.com/socathie/keras2circom |
keras2circom/model.py | # Read keras model into list of parameters like op, input, output, weight, bias
from __future__ import annotations
from dataclasses import dataclass
import typing
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Layer as KerasLayer
import numpy as np
supported_ops = [
'Activation',
'AveragePooling2D',
'BatchNormalization',
'Conv2D',
'Dense',
'Flatten',
'GlobalAveragePooling2D',
'GlobalMaxPooling2D',
'MaxPooling2D',
'ReLU',
'Softmax',
]
skip_ops = [
'Dropout',
'InputLayer',
]
# read each layer in a model and convert it to a class called Layer
@dataclass
class Layer:
''' A single layer in a Keras model. '''
op: str
name: str
input: typing.List[int]
output: typing.List[int]
config: typing.Dict[str, typing.Any]
weights: typing.List[np.ndarray]
def __init__(self, layer: KerasLayer):
self.op = layer.__class__.__name__
self.name = layer.name
self.input = layer.input_shape[1:]
self.output = layer.output_shape[1:]
self.config = layer.get_config()
self.weights = layer.get_weights()
class Model:
layers: typing.List[Layer]
def __init__(self, filename: str, raw: bool = False):
''' Load a Keras model from a file. '''
model = load_model(filename)
self.layers = [Layer(layer) for layer in model.layers if self._for_transpilation(layer.__class__.__name__)]
@staticmethod
def _for_transpilation(op: str) -> bool:
if op in skip_ops:
return False
if op in supported_ops:
return True
raise NotImplementedError(f'Unsupported op: {op}') | https://github.com/socathie/keras2circom |
keras2circom/script.py | from .circom import Circuit, Component
# template string for circuit.py
python_template_string = '''""" Make an interger-only circuit of the corresponding CIRCOM circuit.
Usage:
circuit.py <circuit.json> <input.json> [-o <output>]
circuit.py (-h | --help)
Options:
-h --help Show this screen.
-o <output> --output=<output> Output directory [default: output].
"""
from docopt import docopt
import json
try:
from keras2circom.util import *
except:
import sys
import os
# add parent directory to sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from keras2circom.util import *
def inference(input, circuit):
out = input['in']
output = {brackets}
{components}
return out, output
def main():
""" Main entry point of the app """
args = docopt(__doc__)
# parse input.json
with open(args['<input.json>']) as f:
input = json.load(f)
# parse circuit.json
with open(args['<circuit.json>']) as f:
circuit = json.load(f)
out, output = inference(input, circuit)
# write output.json
with open(args['--output'] + '/output.json', 'w') as f:
json.dump(output, f)
if __name__ == "__main__":
""" This is executed when run from the command line """
main()
'''
def to_py(circuit: Circuit, dec: int) -> str:
comp_str = ""
for component in circuit.components:
comp_str += transpile_component(component, dec)
return python_template_string.format(
brackets="{}",
components=comp_str,
)
def transpile_component(component: Component, dec: int) -> str:
comp_str = ""
if component.template.op_name == "AveragePooling2D":
comp_str += " out, remainder = AveragePooling2DInt({nRows}, {nCols}, {nChannels}, {poolSize}, {strides}, {input})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
poolSize=component.args["poolSize"],
strides=component.args["strides"],
input="out"
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
comp_str += " output['{name}_remainder'] = remainder\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "BatchNormalization2D":
comp_str += " out, remainder = BatchNormalizationInt({nRows}, {nCols}, {nChannels}, {n}, {input}, {a}, {b})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
n=component.args["n"],
input="out",
a="circuit['{name}_a']".format(name=component.name),
b="circuit['{name}_b']".format(name=component.name),
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
comp_str += " output['{name}_remainder'] = remainder\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "Conv1D":
comp_str += " out, remainder = Conv1DInt({nInputs}, {nChannels}, {nFilters}, {kernelSize}, {strides}, {n}, {input}, {weights}, {bias})\n".format(
nInputs=component.args["nInputs"],
nChannels=component.args["nChannels"],
nFilters=component.args["nFilters"],
kernelSize=component.args["kernelSize"],
strides=component.args["strides"],
n=component.args["n"],
input="out",
weights="circuit['{name}_weights']".format(name=component.name),
bias="circuit['{name}_bias']".format(name=component.name),
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
comp_str += " output['{name}_remainder'] = remainder\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "Conv2D":
comp_str += " out, remainder = Conv2DInt({nRows}, {nCols}, {nChannels}, {nFilters}, {kernelSize}, {strides}, {n}, {input}, {weights}, {bias})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
nFilters=component.args["nFilters"],
kernelSize=component.args["kernelSize"],
strides=component.args["strides"],
n=component.args["n"],
input="out",
weights="circuit['{name}_weights']".format(name=component.name),
bias="circuit['{name}_bias']".format(name=component.name),
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
comp_str += " output['{name}_remainder'] = remainder\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "Dense":
comp_str += " out, remainder = DenseInt({nInputs}, {nOutputs}, {n}, {input}, {weights}, {bias})\n".format(
nInputs=component.args["nInputs"],
nOutputs=component.args["nOutputs"],
n=component.args["n"],
input="out",
weights="circuit['{name}_weights']".format(name=component.name),
bias="circuit['{name}_bias']".format(name=component.name),
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
comp_str += " output['{name}_remainder'] = remainder\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "GlobalAveragePooling2D":
comp_str += " out, remainder = GlobalAveragePooling2DInt({nRows}, {nCols}, {nChannels}, {input})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
input="out"
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
comp_str += " output['{name}_remainder'] = remainder\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "GlobalMaxPooling2D":
comp_str += " out = GlobalMaxPooling2DInt({nRows}, {nCols}, {nChannels}, {input})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
input="out"
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "MaxPooling2D":
comp_str += " out = MaxPooling2DInt({nRows}, {nCols}, {nChannels}, {poolSize}, {strides}, {input})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
poolSize=component.args["poolSize"],
strides=component.args["strides"],
input="out"
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "Flatten2D":
comp_str += " out = Flatten2DInt({nRows}, {nCols}, {nChannels}, {input})\n".format(
nRows=component.args["nRows"],
nCols=component.args["nCols"],
nChannels=component.args["nChannels"],
input="out"
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "ReLU":
nRows, nCols, nChannels = component.inputs[0].shape
comp_str += " out = ReLUInt({nRows}, {nCols}, {nChannels}, {input})\n".format(
nRows=nRows,
nCols=nCols,
nChannels=nChannels,
input="out"
)
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
return comp_str+"\n"
elif component.template.op_name == "ArgMax":
comp_str += " out = ArgMaxInt(out)\n"
comp_str += " output['{name}_out'] = out\n".format(
name=component.name,
)
return comp_str+"\n"
else:
raise ValueError("Unknown component type: {}".format(component.template.op_name)) | https://github.com/socathie/keras2circom |
keras2circom/transpiler.py | from .circom import *
from .model import *
from .script import *
import os
def transpile(filename: str, output_dir: str = 'output', raw: bool = False, dec: int = 18) -> Circuit:
''' Transpile a Keras model to a CIRCOM circuit.'''
model = Model(filename, raw)
circuit = Circuit()
for layer in model.layers[:-1]:
circuit.add_components(transpile_layer(layer, dec))
circuit.add_components(transpile_layer(model.layers[-1], dec, True))
if raw:
if circuit.components[-1].template.op_name == 'ArgMax':
circuit.components.pop()
# create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(output_dir + '/circuit.circom', 'w') as f:
f.write(circuit.to_circom())
with open(output_dir + '/circuit.json', 'w') as f:
f.write(circuit.to_json(int(dec)))
with open(output_dir + '/circuit.py', 'w') as f:
f.write(to_py(circuit, int(dec)))
return circuit
def transpile_layer(layer: Layer, dec: int = 18, last: bool = False) -> typing.List[Component]:
''' Transpile a Keras layer to CIRCOM component(s).'''
if layer.op == 'Activation':
if layer.config['activation'] == 'softmax':
if last:
return transpile_ArgMax(layer)
raise ValueError('Softmax must be the last layer')
if layer.config['activation'] == 'relu':
return transpile_ReLU(layer)
if layer.config['activation'] == 'linear':
return []
raise NotImplementedError(f'Activation {layer.config["activation"]} not implemented')
if layer.op == 'Softmax':
if last:
return transpile_ArgMax(layer)
raise ValueError('Softmax must be the last layer')
if layer.op == 'ReLU':
return transpile_ReLU(layer)
if layer.op == 'AveragePooling2D':
return transpile_AveragePooling2D(layer)
if layer.op == 'BatchNormalization':
return transpile_BatchNormalization2D(layer, dec)
if layer.op == 'Conv2D':
return transpile_Conv2D(layer, dec)
if layer.op == 'Dense':
return transpile_Dense(layer, dec, last)
if layer.op == 'Flatten':
return transpile_Flatten2D(layer)
if layer.op == 'GlobalAveragePooling2D':
return transpile_GlobalAveragePooling2D(layer)
if layer.op == 'GlobalMaxPooling2D':
return transpile_GlobalMaxPooling2D(layer)
if layer.op == 'MaxPooling2D':
return transpile_MaxPooling2D(layer)
raise NotImplementedError(f'Layer {layer.op} is not supported yet.')
def transpile_ArgMax(layer: Layer) -> typing.List[Component]:
return [Component(layer.name, templates['ArgMax'], [Signal('in', layer.output), Signal('out', (1,))], [], {'n': layer.output[0]})]
def transpile_ReLU(layer: Layer) -> typing.List[Component]:
return [Component(layer.name, templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])]
def transpile_AveragePooling2D(layer: Layer) -> typing.List[Component]:
if layer.config['data_format'] != 'channels_last':
raise NotImplementedError('Only data_format="channels_last" is supported')
if layer.config['padding'] != 'valid':
raise NotImplementedError('Only padding="valid" is supported')
if layer.config['pool_size'][0] != layer.config['pool_size'][1]:
raise NotImplementedError('Only pool_size[0] == pool_size[1] is supported')
if layer.config['strides'][0] != layer.config['strides'][1]:
raise NotImplementedError('Only strides[0] == strides[1] is supported')
return [Component(layer.name, templates['AveragePooling2D'], [Signal('in', layer.input), Signal('out', layer.output), Signal('remainder', layer.output)],[],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
'poolSize': layer.config['pool_size'][0],
'strides': layer.config['strides'][0],
})]
def transpile_BatchNormalization2D(layer: Layer, dec: int) -> typing.List[Component]:
if layer.input.__len__() != 3:
raise NotImplementedError('Only 2D inputs are supported')
if layer.config['axis'][0] != 3:
raise NotImplementedError('Only axis=3 is supported')
if layer.config['center'] != True:
raise NotImplementedError('Only center=True is supported')
if layer.config['scale'] != True:
raise NotImplementedError('Only scale=True is supported')
gamma = layer.weights[0]
beta = layer.weights[1]
moving_mean = layer.weights[2]
moving_var = layer.weights[3]
epsilon = layer.config['epsilon']
a = gamma/(moving_var+epsilon)**.5
b = beta-gamma*moving_mean/(moving_var+epsilon)**.5
return [Component(layer.name, templates['BatchNormalization2D'], [
Signal('in', layer.input),
Signal('a', a.shape, a),
Signal('b', b.shape, b),
Signal('out', layer.output),
Signal('remainder', layer.output),
],[],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
'n': '10**'+dec,
})]
def transpile_Conv2D(layer: Layer, dec: int) -> typing.List[Component]:
if layer.config['data_format'] != 'channels_last':
raise NotImplementedError('Only data_format="channels_last" is supported')
if layer.config['padding'] != 'valid':
raise NotImplementedError('Only padding="valid" is supported')
if layer.config['strides'][0] != layer.config['strides'][1]:
raise NotImplementedError('Only strides[0] == strides[1] is supported')
if layer.config['kernel_size'][0] != layer.config['kernel_size'][1]:
raise NotImplementedError('Only kernel_size[0] == kernel_size[1] is supported')
if layer.config['dilation_rate'][0] != 1:
raise NotImplementedError('Only dilation_rate[0] == 1 is supported')
if layer.config['dilation_rate'][1] != 1:
raise NotImplementedError('Only dilation_rate[1] == 1 is supported')
if layer.config['groups'] != 1:
raise NotImplementedError('Only groups == 1 is supported')
if layer.config['activation'] not in ['linear', 'relu']:
raise NotImplementedError(f'Activation {layer.config["activation"]} is not supported')
if layer.config['use_bias'] == False:
layer.weights.append(np.zeros(layer.weights[0].shape[-1]))
conv = Component(layer.name, templates['Conv2D'], [
Signal('in', layer.input),
Signal('weights', layer.weights[0].shape, layer.weights[0]),
Signal('bias', layer.weights[1].shape, layer.weights[1]),
Signal('out', layer.output),
Signal('remainder', layer.output),
],[],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
'nFilters': layer.config['filters'],
'kernelSize': layer.config['kernel_size'][0],
'strides': layer.config['strides'][0],
'n': '10**'+dec,
})
if layer.config['activation'] == 'relu':
activation = Component(layer.name+'_re_lu', templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])
return [conv, activation]
return [conv]
def transpile_Dense(layer: Layer, dec: int, last: bool = False) -> typing.List[Component]:
if not last and layer.config['activation'] == 'softmax':
raise NotImplementedError('Softmax is only supported as last layer')
if layer.config['activation'] not in ['linear', 'relu', 'softmax']:
raise NotImplementedError(f'Activation {layer.config["activation"]} is not supported')
if layer.config['use_bias'] == False:
layer.weights.append(np.zeros(layer.weights[0].shape[-1]))
dense = Component(layer.name, templates['Dense'], [
Signal('in', layer.input),
Signal('weights', layer.weights[0].shape, layer.weights[0]),
Signal('bias', layer.weights[1].shape, layer.weights[1]),
Signal('out', layer.output),
Signal('remainder', layer.output),
],[],{
'nInputs': layer.input[0],
'nOutputs': layer.output[0],
'n': '10**'+dec,
})
if layer.config['activation'] == 'relu':
activation = Component(layer.name+'_re_lu', templates['ReLU'], [Signal('in', layer.output), Signal('out', layer.output)], [])
return [dense, activation]
if layer.config['activation'] == 'softmax':
activation = Component(layer.name+'_softmax', templates['ArgMax'], [Signal('in', layer.output), Signal('out', (1,))], [], {'n': layer.output[0]})
return [dense, activation]
return [dense]
def transpile_Flatten2D(layer: Layer) -> typing.List[Component]:
if layer.input.__len__() != 3:
raise NotImplementedError('Only 2D inputs are supported')
return [Component(layer.name, templates['Flatten2D'], [
Signal('in', layer.input),
Signal('out', layer.output),
],[],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
})]
def transpile_GlobalAveragePooling2D(layer: Layer) -> typing.List[Component]:
if layer.config['data_format'] != 'channels_last':
raise NotImplementedError('Only data_format="channels_last" is supported')
if layer.config['keepdims']:
raise NotImplementedError('Only keepdims=False is supported')
return [Component(layer.name, templates['GlobalAveragePooling2D'], [
Signal('in', layer.input),
Signal('out', layer.output),
Signal('remainder', layer.output),
],[],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
})]
def transpile_GlobalMaxPooling2D(layer: Layer) -> typing.List[Component]:
if layer.config['data_format'] != 'channels_last':
raise NotImplementedError('Only data_format="channels_last" is supported')
if layer.config['keepdims']:
raise NotImplementedError('Only keepdims=False is supported')
return [Component(layer.name, templates['GlobalMaxPooling2D'], [
Signal('in', layer.input),
Signal('out', layer.output),
],[],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
})]
def transpile_MaxPooling2D(layer: Layer) -> typing.List[Component]:
if layer.config['data_format'] != 'channels_last':
raise NotImplementedError('Only data_format="channels_last" is supported')
if layer.config['padding'] != 'valid':
raise NotImplementedError('Only padding="valid" is supported')
if layer.config['pool_size'][0] != layer.config['pool_size'][1]:
raise NotImplementedError('Only pool_size[0] == pool_size[1] is supported')
if layer.config['strides'][0] != layer.config['strides'][1]:
raise NotImplementedError('Only strides[0] == strides[1] is supported')
return [Component(layer.name, templates['MaxPooling2D'], [Signal('in', layer.input), Signal('out', layer.output)], [],{
'nRows': layer.input[0],
'nCols': layer.input[1],
'nChannels': layer.input[2],
'poolSize': layer.config['pool_size'][0],
'strides': layer.config['strides'][0],
})]
| https://github.com/socathie/keras2circom |
keras2circom/util.py | # assume all inputs are strings
def AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):
out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]
remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]
for i in range((nRows-poolSize)//strides + 1):
for j in range((nCols-poolSize)//strides + 1):
for k in range(nChannels):
for x in range(poolSize):
for y in range(poolSize):
out[i][j][k] += int(input[i*strides+x][j*strides+y][k])
remainder[i][j][k] = str(out[i][j][k] % poolSize**2)
out[i][j][k] = str(out[i][j][k] // poolSize**2)
return out, remainder
def BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):
out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]
remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]
for i in range(nRows):
for j in range(nCols):
for k in range(nChannels):
out[i][j][k] = int(X_in[i][j][k])*int(a_in[k]) + int(b_in[k])
remainder[i][j][k] = str(out[i][j][k] % n)
out[i][j][k] = str(out[i][j][k] // n)
return out, remainder
def Conv1DInt(nInputs, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):
out = [[0 for _ in range(nFilters)] for j in range((nInputs - kernelSize)//strides + 1)]
remainder = [[None for _ in range(nFilters)] for _ in range((nInputs - kernelSize)//strides + 1)]
for i in range((nInputs - kernelSize)//strides + 1):
for j in range(nFilters):
for k in range(kernelSize):
for l in range(nChannels):
out[i][j] += int(input[i*strides + k][l])*int(weights[k][l][j])
out[i][j] += int(bias[j])
remainder[i][j] = str(out[i][j] % n)
out[i][j] = str(out[i][j] // n)
return out, remainder
def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):
out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]
remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]
for i in range((nRows - kernelSize)//strides + 1):
for j in range((nCols - kernelSize)//strides + 1):
for m in range(nFilters):
for k in range(nChannels):
for x in range(kernelSize):
for y in range(kernelSize):
out[i][j][m] += int(input[i*strides+x][j*strides+y][k])*int(weights[x][y][k][m])
out[i][j][m] += int(bias[m])
remainder[i][j][m] = str(out[i][j][m] % n)
out[i][j][m] = str(out[i][j][m] // n)
return out, remainder
def DenseInt(nInputs, nOutputs, n, input, weights, bias):
out = [0 for _ in range(nOutputs)]
remainder = [None for _ in range(nOutputs)]
for j in range(nOutputs):
for i in range(nInputs):
out[j] += int(input[i])*int(weights[i][j])
out[j] += int(bias[j])
remainder[j] = str(out[j] % n)
out[j] = str(out[j] // n)
return out, remainder
def GlobalAveragePooling2DInt(nRows, nCols, nChannels, input):
out = [0 for _ in range(nChannels)]
remainder = [None for _ in range(nChannels)]
for k in range(nChannels):
for i in range(nRows):
for j in range(nCols):
out[k] += int(input[i][j][k])
remainder[k] = str(out[k] % (nRows * nCols))
out[k] = str(out[k] // (nRows * nCols))
return out, remainder
def GlobalMaxPooling2DInt(nRows, nCols, nChannels, input):
out = [max(int(input[i][j][k]) for i in range(nRows) for j in range(nCols)) for k in range(nChannels)]
return out
def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):
out = [[[str(max(int(input[i*strides + x][j*strides + y][k]) for x in range(poolSize) for y in range(poolSize))) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]
return out
def Flatten2DInt(nRows, nCols, nChannels, input):
out = [str(int(input[i][j][k])) for i in range(nRows) for j in range(nCols) for k in range(nChannels)]
return out
def ReLUInt(nRows, nCols, nChannels, input):
out = [[[str(max(int(input[i][j][k]), 0)) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]
return out
def ArgMaxInt(input):
return [input.index(str(max(int(input[i]) for i in range(len(input)))))] | https://github.com/socathie/keras2circom |
main.py | """ Transpile a Keras model to a CIRCOM circuit.
Usage:
main.py <model.h5> [-o <output>] [--raw] [-d <decimals>]
main.py (-h | --help)
Options:
-h --help Show this screen.
-o <output> --output=<output> Output directory [default: output].
--raw Output raw model outputs instead of the argmax of outputs [default: False].
-d <decimals> --decimals=<decimals> Number of decimals for model precision [default: 18].
"""
from docopt import docopt
from keras2circom import circom, transpiler
def main():
""" Main entry point of the app """
args = docopt(__doc__)
circom.dir_parse('node_modules/circomlib-ml/circuits/', skips=['util.circom', 'circomlib-matrix', 'circomlib', 'crypto'])
transpiler.transpile(args['<model.h5>'], args['--output'], args['--raw'], args['--decimals'])
if __name__ == "__main__":
""" This is executed when run from the command line """
main() | https://github.com/socathie/keras2circom |
models/model.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# list of supported layers\n",
"from tensorflow.keras.layers import (\n",
" Input,\n",
" Activation,\n",
" AveragePooling2D,\n",
" BatchNormalization,\n",
" Conv2D,\n",
" Dense,\n",
" Dropout,\n",
" Flatten,\n",
" GlobalAveragePooling2D,\n",
" GlobalMaxPooling2D,\n",
" MaxPooling2D,\n",
" ReLU,\n",
" Softmax,\n",
" )\n",
"from tensorflow.keras import Model\n",
"from tensorflow.keras.datasets import mnist\n",
"from tensorflow.keras.utils import to_categorical\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import tensorflow as tf"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# load MNIST dataset\n",
"(X_train, y_train), (X_test, y_test) = mnist.load_data()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# convert y_train and y_test to one-hot encoding\n",
"y_train = to_categorical(y_train)\n",
"y_test = to_categorical(y_test)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# reshape X_train and X_test to 4D tensor\n",
"X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\n",
"X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n",
"\n",
"#normalizing\n",
"X_train = X_train.astype('float32')\n",
"X_test = X_test.astype('float32')\n",
"X_train /= 255.0\n",
"X_test /= 255.0"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(28,28,1))\n",
"out = Conv2D(4, 3, use_bias=False)(inputs)\n",
"out = BatchNormalization()(out)\n",
"out = Activation('relu')(out)\n",
"out = MaxPooling2D()(out)\n",
"out = Conv2D(8, 3, use_bias=True, strides=2)(out)\n",
"out = ReLU()(out)\n",
"out = AveragePooling2D()(out)\n",
"out = Flatten()(out)\n",
"# out = Dropout(0.5)(out)\n",
"out = Dense(10, activation=\"softmax\")(out)\n",
"model = Model(inputs, out)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 28, 28, 1)] 0 \n",
" \n",
" conv2d (Conv2D) (None, 26, 26, 4) 36 \n",
" \n",
" batch_normalization (BatchN (None, 26, 26, 4) 16 \n",
" ormalization) \n",
" \n",
" activation (Activation) (None, 26, 26, 4) 0 \n",
" \n",
" max_pooling2d (MaxPooling2D (None, 13, 13, 4) 0 \n",
" ) \n",
" \n",
" conv2d_1 (Conv2D) (None, 6, 6, 8) 296 \n",
" \n",
" re_lu (ReLU) (None, 6, 6, 8) 0 \n",
" \n",
" average_pooling2d (AverageP (None, 3, 3, 8) 0 \n",
" ooling2D) \n",
" \n",
" flatten (Flatten) (None, 72) 0 \n",
" \n",
" dense (Dense) (None, 10) 730 \n",
" \n",
"=================================================================\n",
"Total params: 1,078\n",
"Trainable params: 1,070\n",
"Non-trainable params: 8\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"model.compile(\n",
" loss='categorical_crossentropy',\n",
" optimizer='adam',\n",
" metrics=['acc']\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/15\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-11-26 21:47:52.776729: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"1875/1875 [==============================] - 11s 6ms/step - loss: 0.5203 - acc: 0.8386 - val_loss: 0.2099 - val_acc: 0.9363\n",
"Epoch 2/15\n",
"1875/1875 [==============================] - 11s 6ms/step - loss: 0.1926 - acc: 0.9419 - val_loss: 0.1497 - val_acc: 0.9543\n",
"Epoch 3/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1551 - acc: 0.9522 - val_loss: 0.1263 - val_acc: 0.9591\n",
"Epoch 4/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1361 - acc: 0.9580 - val_loss: 0.1139 - val_acc: 0.9628\n",
"Epoch 5/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1253 - acc: 0.9617 - val_loss: 0.1031 - val_acc: 0.9679\n",
"Epoch 6/15\n",
"1875/1875 [==============================] - 11s 6ms/step - loss: 0.1168 - acc: 0.9636 - val_loss: 0.0976 - val_acc: 0.9697\n",
"Epoch 7/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1113 - acc: 0.9650 - val_loss: 0.0923 - val_acc: 0.9711\n",
"Epoch 8/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.1072 - acc: 0.9673 - val_loss: 0.0884 - val_acc: 0.9732\n",
"Epoch 9/15\n",
"1875/1875 [==============================] - 12s 7ms/step - loss: 0.1026 - acc: 0.9683 - val_loss: 0.0879 - val_acc: 0.9725\n",
"Epoch 10/15\n",
"1875/1875 [==============================] - 11s 6ms/step - loss: 0.0999 - acc: 0.9691 - val_loss: 0.0928 - val_acc: 0.9719\n",
"Epoch 11/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0968 - acc: 0.9702 - val_loss: 0.0954 - val_acc: 0.9699\n",
"Epoch 12/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0945 - acc: 0.9706 - val_loss: 0.0841 - val_acc: 0.9740\n",
"Epoch 13/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0926 - acc: 0.9718 - val_loss: 0.0826 - val_acc: 0.9748\n",
"Epoch 14/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0893 - acc: 0.9723 - val_loss: 0.0803 - val_acc: 0.9751\n",
"Epoch 15/15\n",
"1875/1875 [==============================] - 10s 5ms/step - loss: 0.0892 - acc: 0.9723 - val_loss: 0.0767 - val_acc: 0.9757\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x177842d60>"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test))"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"model.save('model.h5')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "71414dc221f26c27f268040756e42b4f7499507456a67f7434828e3314a20678"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/keras2circom |
test/accuracy.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!cd .. && python main.py models/model.h5"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"import os\n",
"# add parent directory to sys.path\n",
"sys.path.append(os.path.dirname((os.getcwd())))\n",
"from output.circuit import inference\n",
"import json"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"with open('../output/circuit.json') as f:\n",
" circuit = json.load(f)\n",
"\n",
"with open('y_test.json') as f:\n",
" y_test = json.load(f)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"#0: 100.00%\n",
"#1: 100.00%\n",
"#2: 100.00%\n",
"#3: 100.00%\n",
"#4: 100.00%\n",
"#5: 100.00%\n",
"#6: 100.00%\n",
"#7: 100.00%\n",
"#8: 100.00%\n",
"#9: 100.00%\n",
"#10: 100.00%\n",
"#11: 100.00%\n",
"#12: 100.00%\n",
"#13: 100.00%\n",
"#14: 100.00%\n",
"#15: 100.00%\n",
"#16: 100.00%\n",
"#17: 100.00%\n",
"#18: 94.74%\n",
"#19: 95.00%\n",
"#20: 95.24%\n",
"#21: 95.45%\n",
"#22: 95.65%\n",
"#23: 95.83%\n",
"#24: 96.00%\n",
"#25: 96.15%\n",
"#26: 96.30%\n",
"#27: 96.43%\n",
"#28: 96.55%\n",
"#29: 96.67%\n",
"#30: 96.77%\n",
"#31: 96.88%\n",
"#32: 96.97%\n",
"#33: 97.06%\n",
"#34: 97.14%\n",
"#35: 97.22%\n",
"#36: 97.30%\n",
"#37: 97.37%\n",
"#38: 97.44%\n",
"#39: 97.50%\n",
"#40: 97.56%\n",
"#41: 97.62%\n",
"#42: 97.67%\n",
"#43: 97.73%\n",
"#44: 97.78%\n",
"#45: 97.83%\n",
"#46: 97.87%\n",
"#47: 97.92%\n",
"#48: 97.96%\n",
"#49: 98.00%\n",
"#50: 98.04%\n",
"#51: 98.08%\n",
"#52: 98.11%\n",
"#53: 98.15%\n",
"#54: 98.18%\n",
"#55: 98.21%\n",
"#56: 98.25%\n",
"#57: 98.28%\n",
"#58: 98.31%\n",
"#59: 98.33%\n",
"#60: 98.36%\n",
"#61: 98.39%\n",
"#62: 98.41%\n",
"#63: 98.44%\n",
"#64: 98.46%\n",
"#65: 98.48%\n",
"#66: 98.51%\n",
"#67: 98.53%\n",
"#68: 98.55%\n",
"#69: 98.57%\n",
"#70: 98.59%\n",
"#71: 98.61%\n",
"#72: 98.63%\n",
"#73: 98.65%\n",
"#74: 98.67%\n",
"#75: 98.68%\n",
"#76: 98.70%\n",
"#77: 98.72%\n",
"#78: 98.73%\n",
"#79: 98.75%\n",
"#80: 98.77%\n",
"#81: 98.78%\n",
"#82: 98.80%\n",
"#83: 98.81%\n",
"#84: 98.82%\n",
"#85: 98.84%\n",
"#86: 98.85%\n",
"#87: 98.86%\n",
"#88: 98.88%\n",
"#89: 98.89%\n",
"#90: 98.90%\n",
"#91: 98.91%\n",
"#92: 98.92%\n",
"#93: 98.94%\n",
"#94: 98.95%\n",
"#95: 98.96%\n",
"#96: 98.97%\n",
"#97: 98.98%\n",
"#98: 98.99%\n",
"#99: 99.00%\n",
"#100: 99.01%\n",
"#101: 99.02%\n",
"#102: 99.03%\n",
"#103: 99.04%\n",
"#104: 99.05%\n",
"#105: 99.06%\n",
"#106: 99.07%\n",
"#107: 99.07%\n",
"#108: 99.08%\n",
"#109: 99.09%\n",
"#110: 99.10%\n",
"#111: 99.11%\n",
"#112: 99.12%\n",
"#113: 99.12%\n",
"#114: 99.13%\n",
"#115: 99.14%\n",
"#116: 99.15%\n",
"#117: 99.15%\n",
"#118: 99.16%\n",
"#119: 99.17%\n",
"#120: 99.17%\n",
"#121: 99.18%\n",
"#122: 99.19%\n",
"#123: 99.19%\n",
"#124: 99.20%\n",
"#125: 99.21%\n",
"#126: 99.21%\n",
"#127: 99.22%\n",
"#128: 99.22%\n",
"#129: 99.23%\n",
"#130: 99.24%\n",
"#131: 99.24%\n",
"#132: 99.25%\n",
"#133: 99.25%\n",
"#134: 99.26%\n",
"#135: 99.26%\n",
"#136: 99.27%\n",
"#137: 99.28%\n",
"#138: 99.28%\n",
"#139: 99.29%\n",
"#140: 99.29%\n",
"#141: 99.30%\n",
"#142: 99.30%\n",
"#143: 99.31%\n",
"#144: 99.31%\n",
"#145: 99.32%\n",
"#146: 99.32%\n",
"#147: 99.32%\n",
"#148: 99.33%\n",
"#149: 99.33%\n",
"#150: 99.34%\n",
"#151: 98.68%\n",
"#152: 98.69%\n",
"#153: 98.70%\n",
"#154: 98.71%\n",
"#155: 98.72%\n",
"#156: 98.73%\n",
"#157: 98.73%\n",
"#158: 98.74%\n",
"#159: 98.75%\n",
"#160: 98.76%\n",
"#161: 98.77%\n",
"#162: 98.77%\n",
"#163: 98.78%\n",
"#164: 98.79%\n",
"#165: 98.80%\n",
"#166: 98.80%\n",
"#167: 98.81%\n",
"#168: 98.82%\n",
"#169: 98.82%\n",
"#170: 98.83%\n",
"#171: 98.84%\n",
"#172: 98.84%\n",
"#173: 98.85%\n",
"#174: 98.86%\n",
"#175: 98.86%\n",
"#176: 98.87%\n",
"#177: 98.88%\n",
"#178: 98.88%\n",
"#179: 98.89%\n",
"#180: 98.90%\n",
"#181: 98.90%\n",
"#182: 98.91%\n",
"#183: 98.91%\n",
"#184: 98.92%\n",
"#185: 98.92%\n",
"#186: 98.93%\n",
"#187: 98.94%\n",
"#188: 98.94%\n",
"#189: 98.95%\n",
"#190: 98.95%\n",
"#191: 98.96%\n",
"#192: 98.96%\n",
"#193: 98.97%\n",
"#194: 98.97%\n",
"#195: 98.98%\n",
"#196: 98.98%\n",
"#197: 98.99%\n",
"#198: 98.99%\n",
"#199: 99.00%\n",
"#200: 99.00%\n",
"#201: 99.01%\n",
"#202: 99.01%\n",
"#203: 99.02%\n",
"#204: 99.02%\n",
"#205: 99.03%\n",
"#206: 99.03%\n",
"#207: 99.04%\n",
"#208: 99.04%\n",
"#209: 99.05%\n",
"#210: 99.05%\n",
"#211: 99.06%\n",
"#212: 99.06%\n",
"#213: 99.07%\n",
"#214: 99.07%\n",
"#215: 99.07%\n",
"#216: 99.08%\n",
"#217: 99.08%\n",
"#218: 99.09%\n",
"#219: 99.09%\n",
"#220: 99.10%\n",
"#221: 99.10%\n",
"#222: 99.10%\n",
"#223: 99.11%\n",
"#224: 99.11%\n",
"#225: 99.12%\n",
"#226: 99.12%\n",
"#227: 99.12%\n",
"#228: 99.13%\n",
"#229: 99.13%\n",
"#230: 99.13%\n",
"#231: 99.14%\n",
"#232: 99.14%\n",
"#233: 99.15%\n",
"#234: 99.15%\n",
"#235: 99.15%\n",
"#236: 99.16%\n",
"#237: 99.16%\n",
"#238: 99.16%\n",
"#239: 99.17%\n",
"#240: 99.17%\n",
"#241: 98.76%\n",
"#242: 98.77%\n",
"#243: 98.77%\n",
"#244: 98.78%\n",
"#245: 98.78%\n",
"#246: 98.79%\n",
"#247: 98.39%\n",
"#248: 98.39%\n",
"#249: 98.40%\n",
"#250: 98.41%\n",
"#251: 98.41%\n",
"#252: 98.42%\n",
"#253: 98.43%\n",
"#254: 98.43%\n",
"#255: 98.44%\n",
"#256: 98.44%\n",
"#257: 98.45%\n",
"#258: 98.46%\n",
"#259: 98.08%\n",
"#260: 98.08%\n",
"#261: 98.09%\n",
"#262: 98.10%\n",
"#263: 98.11%\n",
"#264: 97.74%\n",
"#265: 97.74%\n",
"#266: 97.38%\n",
"#267: 97.39%\n",
"#268: 97.40%\n",
"#269: 97.41%\n",
"#270: 97.42%\n",
"#271: 97.43%\n",
"#272: 97.44%\n",
"#273: 97.45%\n",
"#274: 97.45%\n",
"#275: 97.46%\n",
"#276: 97.47%\n",
"#277: 97.48%\n",
"#278: 97.49%\n",
"#279: 97.50%\n",
"#280: 97.51%\n",
"#281: 97.52%\n",
"#282: 97.17%\n",
"#283: 97.18%\n",
"#284: 97.19%\n",
"#285: 97.20%\n",
"#286: 97.21%\n",
"#287: 97.22%\n",
"#288: 97.23%\n",
"#289: 97.24%\n",
"#290: 97.25%\n",
"#291: 97.26%\n",
"#292: 97.27%\n",
"#293: 97.28%\n",
"#294: 97.29%\n",
"#295: 97.30%\n",
"#296: 97.31%\n",
"#297: 97.32%\n",
"#298: 97.32%\n",
"#299: 97.33%\n",
"#300: 97.34%\n",
"#301: 97.35%\n",
"#302: 97.36%\n",
"#303: 97.37%\n",
"#304: 97.38%\n",
"#305: 97.39%\n",
"#306: 97.39%\n",
"#307: 97.40%\n",
"#308: 97.41%\n",
"#309: 97.42%\n",
"#310: 97.43%\n",
"#311: 97.44%\n",
"#312: 97.44%\n",
"#313: 97.45%\n",
"#314: 97.46%\n",
"#315: 97.47%\n",
"#316: 97.48%\n",
"#317: 97.48%\n",
"#318: 97.49%\n",
"#319: 97.50%\n",
"#320: 97.20%\n",
"#321: 97.20%\n",
"#322: 97.21%\n",
"#323: 97.22%\n",
"#324: 97.23%\n",
"#325: 97.24%\n",
"#326: 97.25%\n",
"#327: 97.26%\n",
"#328: 97.26%\n",
"#329: 97.27%\n",
"#330: 97.28%\n",
"#331: 97.29%\n",
"#332: 97.30%\n",
"#333: 97.31%\n",
"#334: 97.31%\n",
"#335: 97.32%\n",
"#336: 97.33%\n",
"#337: 97.34%\n",
"#338: 97.35%\n",
"#339: 97.35%\n",
"#340: 97.36%\n",
"#341: 97.37%\n",
"#342: 97.38%\n",
"#343: 97.38%\n",
"#344: 97.39%\n",
"#345: 97.40%\n",
"#346: 97.41%\n",
"#347: 97.41%\n",
"#348: 97.42%\n",
"#349: 97.43%\n",
"#350: 97.44%\n",
"#351: 97.44%\n",
"#352: 97.45%\n",
"#353: 97.46%\n",
"#354: 97.46%\n",
"#355: 97.47%\n",
"#356: 97.48%\n",
"#357: 97.49%\n",
"#358: 97.21%\n",
"#359: 97.22%\n",
"#360: 97.23%\n",
"#361: 97.24%\n",
"#362: 97.25%\n",
"#363: 97.25%\n",
"#364: 97.26%\n",
"#365: 97.27%\n",
"#366: 97.28%\n",
"#367: 97.28%\n",
"#368: 97.29%\n",
"#369: 97.30%\n",
"#370: 97.30%\n",
"#371: 97.31%\n",
"#372: 97.32%\n",
"#373: 97.33%\n",
"#374: 97.33%\n",
"#375: 97.34%\n",
"#376: 97.35%\n",
"#377: 97.35%\n",
"#378: 97.36%\n",
"#379: 97.37%\n",
"#380: 97.38%\n",
"#381: 97.38%\n",
"#382: 97.39%\n",
"#383: 97.40%\n",
"#384: 97.40%\n",
"#385: 97.41%\n",
"#386: 97.42%\n",
"#387: 97.42%\n",
"#388: 97.43%\n",
"#389: 97.44%\n",
"#390: 97.44%\n",
"#391: 97.45%\n",
"#392: 97.46%\n",
"#393: 97.46%\n",
"#394: 97.47%\n",
"#395: 97.47%\n",
"#396: 97.48%\n",
"#397: 97.49%\n",
"#398: 97.49%\n",
"#399: 97.50%\n",
"#400: 97.51%\n",
"#401: 97.51%\n",
"#402: 97.52%\n",
"#403: 97.28%\n",
"#404: 97.28%\n",
"#405: 97.29%\n",
"#406: 97.30%\n",
"#407: 97.30%\n",
"#408: 97.31%\n",
"#409: 97.32%\n",
"#410: 97.32%\n",
"#411: 97.33%\n",
"#412: 97.34%\n",
"#413: 97.34%\n",
"#414: 97.35%\n",
"#415: 97.36%\n",
"#416: 97.36%\n",
"#417: 97.37%\n",
"#418: 97.37%\n",
"#419: 97.38%\n",
"#420: 97.39%\n",
"#421: 97.39%\n",
"#422: 97.40%\n",
"#423: 97.41%\n",
"#424: 97.41%\n",
"#425: 97.42%\n",
"#426: 97.42%\n",
"#427: 97.43%\n",
"#428: 97.44%\n",
"#429: 97.44%\n",
"#430: 97.45%\n",
"#431: 97.45%\n",
"#432: 97.46%\n",
"#433: 97.47%\n",
"#434: 97.47%\n",
"#435: 97.25%\n",
"#436: 97.25%\n",
"#437: 97.26%\n",
"#438: 97.27%\n",
"#439: 97.27%\n",
"#440: 97.28%\n",
"#441: 97.29%\n",
"#442: 97.29%\n",
"#443: 97.30%\n",
"#444: 97.30%\n",
"#445: 97.09%\n",
"#446: 97.09%\n",
"#447: 97.10%\n",
"#448: 97.10%\n",
"#449: 97.11%\n",
"#450: 97.12%\n",
"#451: 97.12%\n",
"#452: 97.13%\n",
"#453: 97.14%\n",
"#454: 97.14%\n",
"#455: 97.15%\n",
"#456: 97.16%\n",
"#457: 97.16%\n",
"#458: 97.17%\n",
"#459: 97.17%\n",
"#460: 97.18%\n",
"#461: 97.19%\n",
"#462: 97.19%\n",
"#463: 97.20%\n",
"#464: 96.99%\n",
"#465: 97.00%\n",
"#466: 97.00%\n",
"#467: 97.01%\n",
"#468: 97.01%\n",
"#469: 97.02%\n",
"#470: 97.03%\n",
"#471: 97.03%\n",
"#472: 97.04%\n",
"#473: 97.05%\n",
"#474: 97.05%\n",
"#475: 97.06%\n",
"#476: 97.06%\n",
"#477: 97.07%\n",
"#478: 97.08%\n",
"#479: 97.08%\n",
"#480: 97.09%\n",
"#481: 97.10%\n",
"#482: 97.10%\n",
"#483: 97.11%\n",
"#484: 97.11%\n",
"#485: 97.12%\n",
"#486: 97.13%\n",
"#487: 97.13%\n",
"#488: 97.14%\n",
"#489: 97.14%\n",
"#490: 97.15%\n",
"#491: 97.15%\n",
"#492: 97.16%\n",
"#493: 97.17%\n",
"#494: 97.17%\n",
"#495: 96.98%\n",
"#496: 96.98%\n",
"#497: 96.99%\n",
"#498: 96.99%\n",
"#499: 97.00%\n",
"#500: 97.01%\n",
"#501: 97.01%\n",
"#502: 97.02%\n",
"#503: 97.02%\n",
"#504: 97.03%\n",
"#505: 97.04%\n",
"#506: 97.04%\n",
"#507: 97.05%\n",
"#508: 97.05%\n",
"#509: 97.06%\n",
"#510: 97.06%\n",
"#511: 97.07%\n",
"#512: 97.08%\n",
"#513: 97.08%\n",
"#514: 97.09%\n",
"#515: 97.09%\n",
"#516: 97.10%\n",
"#517: 97.10%\n",
"#518: 97.11%\n",
"#519: 97.12%\n",
"#520: 97.12%\n",
"#521: 97.13%\n",
"#522: 97.13%\n",
"#523: 97.14%\n",
"#524: 97.14%\n",
"#525: 97.15%\n",
"#526: 97.15%\n",
"#527: 97.16%\n",
"#528: 97.16%\n",
"#529: 97.17%\n",
"#530: 97.18%\n",
"#531: 97.18%\n",
"#532: 97.19%\n",
"#533: 97.19%\n",
"#534: 97.20%\n",
"#535: 97.20%\n",
"#536: 97.21%\n",
"#537: 97.21%\n",
"#538: 97.22%\n",
"#539: 97.22%\n",
"#540: 97.23%\n",
"#541: 97.23%\n",
"#542: 97.05%\n",
"#543: 97.06%\n",
"#544: 97.06%\n",
"#545: 97.07%\n",
"#546: 97.07%\n",
"#547: 97.08%\n",
"#548: 97.09%\n",
"#549: 97.09%\n",
"#550: 97.10%\n",
"#551: 97.10%\n",
"#552: 97.11%\n",
"#553: 97.11%\n",
"#554: 97.12%\n",
"#555: 97.12%\n",
"#556: 97.13%\n",
"#557: 97.13%\n",
"#558: 97.14%\n",
"#559: 97.14%\n",
"#560: 97.15%\n",
"#561: 97.15%\n",
"#562: 97.16%\n",
"#563: 97.16%\n",
"#564: 97.17%\n",
"#565: 97.17%\n",
"#566: 97.18%\n",
"#567: 97.18%\n",
"#568: 97.19%\n",
"#569: 97.19%\n",
"#570: 97.20%\n",
"#571: 97.20%\n",
"#572: 97.21%\n",
"#573: 97.21%\n",
"#574: 97.22%\n",
"#575: 97.22%\n",
"#576: 97.23%\n",
"#577: 97.23%\n",
"#578: 97.24%\n",
"#579: 97.24%\n",
"#580: 97.25%\n",
"#581: 97.25%\n",
"#582: 97.08%\n",
"#583: 97.09%\n",
"#584: 97.09%\n",
"#585: 97.10%\n",
"#586: 97.10%\n",
"#587: 97.11%\n",
"#588: 97.11%\n",
"#589: 97.12%\n",
"#590: 97.12%\n",
"#591: 97.13%\n",
"#592: 97.13%\n",
"#593: 97.14%\n",
"#594: 97.14%\n",
"#595: 97.15%\n",
"#596: 97.15%\n",
"#597: 97.16%\n",
"#598: 97.16%\n",
"#599: 97.17%\n",
"#600: 97.17%\n",
"#601: 97.18%\n",
"#602: 97.18%\n",
"#603: 97.19%\n",
"#604: 97.19%\n",
"#605: 97.03%\n",
"#606: 97.03%\n",
"#607: 97.04%\n",
"#608: 97.04%\n",
"#609: 97.05%\n",
"#610: 97.05%\n",
"#611: 97.06%\n",
"#612: 97.06%\n",
"#613: 97.07%\n",
"#614: 97.07%\n",
"#615: 97.08%\n",
"#616: 97.08%\n",
"#617: 97.09%\n",
"#618: 97.09%\n",
"#619: 97.10%\n",
"#620: 97.10%\n",
"#621: 97.11%\n",
"#622: 97.11%\n",
"#623: 97.12%\n",
"#624: 97.12%\n",
"#625: 97.12%\n",
"#626: 97.13%\n",
"#627: 97.13%\n",
"#628: 97.14%\n",
"#629: 97.14%\n",
"#630: 97.15%\n",
"#631: 97.15%\n",
"#632: 97.16%\n",
"#633: 97.16%\n",
"#634: 97.17%\n",
"#635: 97.17%\n",
"#636: 97.17%\n",
"#637: 97.18%\n",
"#638: 97.18%\n",
"#639: 97.19%\n",
"#640: 97.19%\n",
"#641: 97.20%\n",
"#642: 97.20%\n",
"#643: 97.20%\n",
"#644: 97.21%\n",
"#645: 97.21%\n",
"#646: 97.22%\n",
"#647: 97.22%\n",
"#648: 97.23%\n",
"#649: 97.23%\n",
"#650: 97.24%\n",
"#651: 97.24%\n",
"#652: 97.24%\n",
"#653: 97.25%\n",
"#654: 97.25%\n",
"#655: 97.26%\n",
"#656: 97.26%\n",
"#657: 97.26%\n",
"#658: 97.27%\n",
"#659: 97.27%\n",
"#660: 97.28%\n",
"#661: 97.28%\n",
"#662: 97.29%\n",
"#663: 97.29%\n",
"#664: 97.29%\n",
"#665: 97.30%\n",
"#666: 97.30%\n",
"#667: 97.31%\n",
"#668: 97.31%\n",
"#669: 97.31%\n",
"#670: 97.32%\n",
"#671: 97.32%\n",
"#672: 97.33%\n",
"#673: 97.33%\n",
"#674: 97.33%\n",
"#675: 97.34%\n",
"#676: 97.34%\n",
"#677: 97.35%\n",
"#678: 97.35%\n",
"#679: 97.35%\n",
"#680: 97.36%\n",
"#681: 97.36%\n",
"#682: 97.36%\n",
"#683: 97.37%\n",
"#684: 97.23%\n",
"#685: 97.23%\n",
"#686: 97.23%\n",
"#687: 97.24%\n",
"#688: 97.24%\n",
"#689: 97.10%\n",
"#690: 97.11%\n",
"#691: 97.11%\n",
"#692: 97.11%\n",
"#693: 97.12%\n",
"#694: 97.12%\n",
"#695: 97.13%\n",
"#696: 97.13%\n",
"#697: 97.13%\n",
"#698: 97.14%\n",
"#699: 97.14%\n",
"#700: 97.15%\n",
"#701: 97.15%\n",
"#702: 97.16%\n",
"#703: 97.16%\n",
"#704: 97.16%\n",
"#705: 97.17%\n",
"#706: 97.17%\n",
"#707: 97.18%\n",
"#708: 97.18%\n",
"#709: 97.18%\n",
"#710: 97.19%\n",
"#711: 97.19%\n",
"#712: 97.19%\n",
"#713: 97.20%\n",
"#714: 97.20%\n",
"#715: 97.21%\n",
"#716: 97.21%\n",
"#717: 97.08%\n",
"#718: 97.08%\n",
"#719: 97.08%\n",
"#720: 97.09%\n",
"#721: 97.09%\n",
"#722: 97.10%\n",
"#723: 97.10%\n",
"#724: 97.10%\n",
"#725: 97.11%\n",
"#726: 96.97%\n",
"#727: 96.98%\n",
"#728: 96.98%\n",
"#729: 96.99%\n",
"#730: 96.99%\n",
"#731: 96.99%\n",
"#732: 97.00%\n",
"#733: 97.00%\n",
"#734: 97.01%\n",
"#735: 97.01%\n",
"#736: 97.01%\n",
"#737: 97.02%\n",
"#738: 97.02%\n",
"#739: 97.03%\n",
"#740: 97.03%\n",
"#741: 97.04%\n",
"#742: 97.04%\n",
"#743: 97.04%\n",
"#744: 97.05%\n",
"#745: 97.05%\n",
"#746: 97.05%\n",
"#747: 97.06%\n",
"#748: 97.06%\n",
"#749: 97.07%\n",
"#750: 97.07%\n",
"#751: 97.07%\n",
"#752: 97.08%\n",
"#753: 97.08%\n",
"#754: 97.09%\n",
"#755: 97.09%\n",
"#756: 97.09%\n",
"#757: 97.10%\n",
"#758: 97.10%\n",
"#759: 97.11%\n",
"#760: 97.11%\n",
"#761: 97.11%\n",
"#762: 97.12%\n",
"#763: 97.12%\n",
"#764: 97.12%\n",
"#765: 97.13%\n",
"#766: 97.13%\n",
"#767: 97.14%\n",
"#768: 97.14%\n",
"#769: 97.14%\n",
"#770: 97.15%\n",
"#771: 97.15%\n",
"#772: 97.15%\n",
"#773: 97.16%\n",
"#774: 97.16%\n",
"#775: 97.16%\n",
"#776: 97.17%\n",
"#777: 97.17%\n",
"#778: 97.18%\n",
"#779: 97.18%\n",
"#780: 97.18%\n",
"#781: 97.19%\n",
"#782: 97.19%\n",
"#783: 97.19%\n",
"#784: 97.20%\n",
"#785: 97.20%\n",
"#786: 97.20%\n",
"#787: 97.21%\n",
"#788: 97.21%\n",
"#789: 97.22%\n",
"#790: 97.22%\n",
"#791: 97.22%\n",
"#792: 97.23%\n",
"#793: 97.23%\n",
"#794: 97.23%\n",
"#795: 97.24%\n",
"#796: 97.24%\n",
"#797: 97.24%\n",
"#798: 97.25%\n",
"#799: 97.25%\n",
"#800: 97.25%\n",
"#801: 97.26%\n",
"#802: 97.26%\n",
"#803: 97.26%\n",
"#804: 97.27%\n",
"#805: 97.27%\n",
"#806: 97.27%\n",
"#807: 97.28%\n",
"#808: 97.28%\n",
"#809: 97.28%\n",
"#810: 97.29%\n",
"#811: 97.29%\n",
"#812: 97.29%\n",
"#813: 97.17%\n",
"#814: 97.18%\n",
"#815: 97.18%\n",
"#816: 97.18%\n",
"#817: 97.19%\n",
"#818: 97.19%\n",
"#819: 97.20%\n",
"#820: 97.20%\n",
"#821: 97.20%\n",
"#822: 97.21%\n",
"#823: 97.21%\n",
"#824: 97.21%\n",
"#825: 97.22%\n",
"#826: 97.22%\n",
"#827: 97.22%\n",
"#828: 97.23%\n",
"#829: 97.23%\n",
"#830: 97.23%\n",
"#831: 97.24%\n",
"#832: 97.24%\n",
"#833: 97.24%\n",
"#834: 97.25%\n",
"#835: 97.25%\n",
"#836: 97.25%\n",
"#837: 97.26%\n",
"#838: 97.26%\n",
"#839: 97.26%\n",
"#840: 97.27%\n",
"#841: 97.27%\n",
"#842: 97.27%\n",
"#843: 97.27%\n",
"#844: 97.28%\n",
"#845: 97.28%\n",
"#846: 97.28%\n",
"#847: 97.29%\n",
"#848: 97.29%\n",
"#849: 97.29%\n",
"#850: 97.30%\n",
"#851: 97.30%\n",
"#852: 97.30%\n",
"#853: 97.31%\n",
"#854: 97.31%\n",
"#855: 97.31%\n",
"#856: 97.32%\n",
"#857: 97.32%\n",
"#858: 97.32%\n",
"#859: 97.33%\n",
"#860: 97.33%\n",
"#861: 97.33%\n",
"#862: 97.33%\n",
"#863: 97.34%\n",
"#864: 97.34%\n",
"#865: 97.34%\n",
"#866: 97.35%\n",
"#867: 97.35%\n",
"#868: 97.35%\n",
"#869: 97.36%\n",
"#870: 97.36%\n",
"#871: 97.36%\n",
"#872: 97.37%\n",
"#873: 97.37%\n",
"#874: 97.37%\n",
"#875: 97.37%\n",
"#876: 97.38%\n",
"#877: 97.38%\n",
"#878: 97.38%\n",
"#879: 97.39%\n",
"#880: 97.39%\n",
"#881: 97.39%\n",
"#882: 97.40%\n",
"#883: 97.40%\n",
"#884: 97.40%\n",
"#885: 97.40%\n",
"#886: 97.41%\n",
"#887: 97.41%\n",
"#888: 97.41%\n",
"#889: 97.42%\n",
"#890: 97.42%\n",
"#891: 97.42%\n",
"#892: 97.42%\n",
"#893: 97.43%\n",
"#894: 97.43%\n",
"#895: 97.43%\n",
"#896: 97.44%\n",
"#897: 97.44%\n",
"#898: 97.33%\n",
"#899: 97.33%\n",
"#900: 97.34%\n",
"#901: 97.34%\n",
"#902: 97.34%\n",
"#903: 97.35%\n",
"#904: 97.35%\n",
"#905: 97.35%\n",
"#906: 97.35%\n",
"#907: 97.36%\n",
"#908: 97.36%\n",
"#909: 97.36%\n",
"#910: 97.37%\n",
"#911: 97.37%\n",
"#912: 97.37%\n",
"#913: 97.37%\n",
"#914: 97.38%\n",
"#915: 97.38%\n",
"#916: 97.38%\n",
"#917: 97.39%\n",
"#918: 97.39%\n",
"#919: 97.39%\n",
"#920: 97.39%\n",
"#921: 97.40%\n",
"#922: 97.40%\n",
"#923: 97.40%\n",
"#924: 97.41%\n",
"#925: 97.41%\n",
"#926: 97.41%\n",
"#927: 97.41%\n",
"#928: 97.42%\n",
"#929: 97.42%\n",
"#930: 97.42%\n",
"#931: 97.42%\n",
"#932: 97.43%\n",
"#933: 97.43%\n",
"#934: 97.43%\n",
"#935: 97.44%\n",
"#936: 97.44%\n",
"#937: 97.44%\n",
"#938: 97.44%\n",
"#939: 97.45%\n",
"#940: 97.45%\n",
"#941: 97.45%\n",
"#942: 97.45%\n",
"#943: 97.46%\n",
"#944: 97.46%\n",
"#945: 97.46%\n",
"#946: 97.47%\n",
"#947: 97.36%\n",
"#948: 97.37%\n",
"#949: 97.37%\n",
"#950: 97.37%\n",
"#951: 97.37%\n",
"#952: 97.38%\n",
"#953: 97.38%\n",
"#954: 97.38%\n",
"#955: 97.38%\n",
"#956: 97.28%\n",
"#957: 97.29%\n",
"#958: 97.29%\n",
"#959: 97.29%\n",
"#960: 97.29%\n",
"#961: 97.30%\n",
"#962: 97.30%\n",
"#963: 97.30%\n",
"#964: 97.31%\n",
"#965: 97.20%\n",
"#966: 97.21%\n",
"#967: 97.21%\n",
"#968: 97.21%\n",
"#969: 97.22%\n",
"#970: 97.22%\n",
"#971: 97.22%\n",
"#972: 97.23%\n",
"#973: 97.23%\n",
"#974: 97.23%\n",
"#975: 97.23%\n",
"#976: 97.24%\n",
"#977: 97.24%\n",
"#978: 97.24%\n",
"#979: 97.24%\n",
"#980: 97.25%\n",
"#981: 97.25%\n",
"#982: 97.25%\n",
"#983: 97.26%\n",
"#984: 97.26%\n",
"#985: 97.26%\n",
"#986: 97.26%\n",
"#987: 97.27%\n",
"#988: 97.27%\n",
"#989: 97.27%\n",
"#990: 97.28%\n",
"#991: 97.28%\n",
"#992: 97.28%\n",
"#993: 97.28%\n",
"#994: 97.29%\n",
"#995: 97.29%\n",
"#996: 97.29%\n",
"#997: 97.29%\n",
"#998: 97.30%\n",
"#999: 97.30%\n",
"#1000: 97.30%\n",
"#1001: 97.31%\n",
"#1002: 97.31%\n",
"#1003: 97.31%\n",
"#1004: 97.31%\n",
"#1005: 97.32%\n",
"#1006: 97.32%\n",
"#1007: 97.32%\n",
"#1008: 97.32%\n",
"#1009: 97.33%\n",
"#1010: 97.33%\n",
"#1011: 97.33%\n",
"#1012: 97.33%\n",
"#1013: 97.34%\n",
"#1014: 97.24%\n",
"#1015: 97.24%\n",
"#1016: 97.25%\n",
"#1017: 97.25%\n",
"#1018: 97.25%\n",
"#1019: 97.25%\n",
"#1020: 97.26%\n",
"#1021: 97.26%\n",
"#1022: 97.26%\n",
"#1023: 97.27%\n",
"#1024: 97.27%\n",
"#1025: 97.27%\n",
"#1026: 97.27%\n",
"#1027: 97.28%\n",
"#1028: 97.28%\n",
"#1029: 97.28%\n",
"#1030: 97.28%\n",
"#1031: 97.29%\n",
"#1032: 97.29%\n",
"#1033: 97.29%\n",
"#1034: 97.29%\n",
"#1035: 97.30%\n",
"#1036: 97.30%\n",
"#1037: 97.30%\n",
"#1038: 97.31%\n",
"#1039: 97.21%\n",
"#1040: 97.21%\n",
"#1041: 97.22%\n",
"#1042: 97.22%\n",
"#1043: 97.22%\n",
"#1044: 97.22%\n",
"#1045: 97.23%\n",
"#1046: 97.23%\n",
"#1047: 97.23%\n",
"#1048: 97.24%\n",
"#1049: 97.24%\n",
"#1050: 97.24%\n",
"#1051: 97.24%\n",
"#1052: 97.25%\n",
"#1053: 97.25%\n",
"#1054: 97.25%\n",
"#1055: 97.25%\n",
"#1056: 97.26%\n",
"#1057: 97.26%\n",
"#1058: 97.26%\n",
"#1059: 97.26%\n",
"#1060: 97.27%\n",
"#1061: 97.27%\n",
"#1062: 97.18%\n",
"#1063: 97.18%\n",
"#1064: 97.18%\n",
"#1065: 97.19%\n",
"#1066: 97.19%\n",
"#1067: 97.19%\n",
"#1068: 97.10%\n",
"#1069: 97.10%\n",
"#1070: 97.11%\n",
"#1071: 97.11%\n",
"#1072: 97.11%\n",
"#1073: 97.11%\n",
"#1074: 97.12%\n",
"#1075: 97.12%\n",
"#1076: 97.12%\n",
"#1077: 97.12%\n",
"#1078: 97.13%\n",
"#1079: 97.13%\n",
"#1080: 97.13%\n",
"#1081: 97.13%\n",
"#1082: 97.14%\n",
"#1083: 97.14%\n",
"#1084: 97.14%\n",
"#1085: 97.15%\n",
"#1086: 97.15%\n",
"#1087: 97.15%\n",
"#1088: 97.15%\n",
"#1089: 97.16%\n",
"#1090: 97.16%\n",
"#1091: 97.16%\n",
"#1092: 97.16%\n",
"#1093: 97.17%\n",
"#1094: 97.17%\n",
"#1095: 97.17%\n",
"#1096: 97.17%\n",
"#1097: 97.18%\n",
"#1098: 97.18%\n",
"#1099: 97.18%\n",
"#1100: 97.18%\n",
"#1101: 97.19%\n",
"#1102: 97.19%\n",
"#1103: 97.19%\n",
"#1104: 97.19%\n",
"#1105: 97.20%\n",
"#1106: 97.20%\n",
"#1107: 97.11%\n",
"#1108: 97.11%\n",
"#1109: 97.12%\n",
"#1110: 97.12%\n",
"#1111: 97.12%\n",
"#1112: 97.04%\n",
"#1113: 97.04%\n",
"#1114: 96.95%\n",
"#1115: 96.95%\n",
"#1116: 96.96%\n",
"#1117: 96.96%\n",
"#1118: 96.96%\n",
"#1119: 96.96%\n",
"#1120: 96.97%\n",
"#1121: 96.97%\n",
"#1122: 96.97%\n",
"#1123: 96.98%\n",
"#1124: 96.98%\n",
"#1125: 96.89%\n",
"#1126: 96.89%\n",
"#1127: 96.90%\n",
"#1128: 96.90%\n",
"#1129: 96.90%\n",
"#1130: 96.91%\n",
"#1131: 96.91%\n",
"#1132: 96.91%\n",
"#1133: 96.91%\n",
"#1134: 96.92%\n",
"#1135: 96.92%\n",
"#1136: 96.92%\n",
"#1137: 96.92%\n",
"#1138: 96.93%\n",
"#1139: 96.93%\n",
"#1140: 96.93%\n",
"#1141: 96.94%\n",
"#1142: 96.94%\n",
"#1143: 96.85%\n",
"#1144: 96.86%\n",
"#1145: 96.86%\n",
"#1146: 96.86%\n",
"#1147: 96.86%\n",
"#1148: 96.87%\n",
"#1149: 96.87%\n",
"#1150: 96.87%\n",
"#1151: 96.88%\n",
"#1152: 96.88%\n",
"#1153: 96.88%\n",
"#1154: 96.88%\n",
"#1155: 96.89%\n",
"#1156: 96.89%\n",
"#1157: 96.89%\n",
"#1158: 96.89%\n",
"#1159: 96.90%\n",
"#1160: 96.90%\n",
"#1161: 96.90%\n",
"#1162: 96.90%\n",
"#1163: 96.91%\n",
"#1164: 96.91%\n",
"#1165: 96.91%\n",
"#1166: 96.92%\n",
"#1167: 96.92%\n",
"#1168: 96.92%\n",
"#1169: 96.92%\n",
"#1170: 96.93%\n",
"#1171: 96.93%\n",
"#1172: 96.93%\n",
"#1173: 96.93%\n",
"#1174: 96.94%\n",
"#1175: 96.94%\n",
"#1176: 96.94%\n",
"#1177: 96.94%\n",
"#1178: 96.95%\n",
"#1179: 96.95%\n",
"#1180: 96.95%\n",
"#1181: 96.95%\n",
"#1182: 96.87%\n",
"#1183: 96.88%\n",
"#1184: 96.88%\n",
"#1185: 96.88%\n",
"#1186: 96.88%\n",
"#1187: 96.89%\n",
"#1188: 96.89%\n",
"#1189: 96.89%\n",
"#1190: 96.89%\n",
"#1191: 96.81%\n",
"#1192: 96.81%\n",
"#1193: 96.82%\n",
"#1194: 96.82%\n",
"#1195: 96.82%\n",
"#1196: 96.83%\n",
"#1197: 96.83%\n",
"#1198: 96.83%\n",
"#1199: 96.83%\n",
"#1200: 96.84%\n",
"#1201: 96.84%\n",
"#1202: 96.84%\n",
"#1203: 96.84%\n",
"#1204: 96.85%\n",
"#1205: 96.85%\n",
"#1206: 96.85%\n",
"#1207: 96.85%\n",
"#1208: 96.86%\n",
"#1209: 96.86%\n",
"#1210: 96.86%\n",
"#1211: 96.86%\n",
"#1212: 96.87%\n",
"#1213: 96.87%\n",
"#1214: 96.87%\n",
"#1215: 96.88%\n",
"#1216: 96.88%\n",
"#1217: 96.88%\n",
"#1218: 96.88%\n",
"#1219: 96.89%\n",
"#1220: 96.89%\n",
"#1221: 96.89%\n",
"#1222: 96.89%\n",
"#1223: 96.90%\n",
"#1224: 96.90%\n",
"#1225: 96.90%\n",
"#1226: 96.82%\n",
"#1227: 96.82%\n",
"#1228: 96.83%\n",
"#1229: 96.83%\n",
"#1230: 96.83%\n",
"#1231: 96.83%\n",
"#1232: 96.84%\n",
"#1233: 96.84%\n",
"#1234: 96.84%\n",
"#1235: 96.84%\n",
"#1236: 96.85%\n",
"#1237: 96.85%\n",
"#1238: 96.85%\n",
"#1239: 96.85%\n",
"#1240: 96.86%\n",
"#1241: 96.86%\n",
"#1242: 96.86%\n",
"#1243: 96.86%\n",
"#1244: 96.87%\n",
"#1245: 96.87%\n",
"#1246: 96.87%\n",
"#1247: 96.79%\n",
"#1248: 96.80%\n",
"#1249: 96.80%\n",
"#1250: 96.80%\n",
"#1251: 96.81%\n",
"#1252: 96.81%\n",
"#1253: 96.81%\n",
"#1254: 96.81%\n",
"#1255: 96.82%\n",
"#1256: 96.82%\n",
"#1257: 96.82%\n",
"#1258: 96.82%\n",
"#1259: 96.83%\n",
"#1260: 96.75%\n",
"#1261: 96.75%\n",
"#1262: 96.75%\n",
"#1263: 96.76%\n",
"#1264: 96.76%\n",
"#1265: 96.76%\n",
"#1266: 96.76%\n",
"#1267: 96.77%\n",
"#1268: 96.77%\n",
"#1269: 96.77%\n",
"#1270: 96.77%\n",
"#1271: 96.78%\n",
"#1272: 96.78%\n",
"#1273: 96.78%\n",
"#1274: 96.78%\n",
"#1275: 96.79%\n",
"#1276: 96.79%\n",
"#1277: 96.79%\n",
"#1278: 96.79%\n",
"#1279: 96.80%\n",
"#1280: 96.80%\n",
"#1281: 96.80%\n",
"#1282: 96.80%\n",
"#1283: 96.81%\n",
"#1284: 96.81%\n",
"#1285: 96.81%\n",
"#1286: 96.81%\n",
"#1287: 96.82%\n",
"#1288: 96.82%\n",
"#1289: 96.82%\n",
"#1290: 96.75%\n",
"#1291: 96.75%\n",
"#1292: 96.75%\n",
"#1293: 96.75%\n",
"#1294: 96.76%\n",
"#1295: 96.76%\n",
"#1296: 96.76%\n",
"#1297: 96.76%\n",
"#1298: 96.77%\n",
"#1299: 96.69%\n",
"#1300: 96.69%\n",
"#1301: 96.70%\n",
"#1302: 96.70%\n",
"#1303: 96.70%\n",
"#1304: 96.70%\n",
"#1305: 96.71%\n",
"#1306: 96.71%\n",
"#1307: 96.71%\n",
"#1308: 96.72%\n",
"#1309: 96.72%\n",
"#1310: 96.72%\n",
"#1311: 96.72%\n",
"#1312: 96.73%\n",
"#1313: 96.73%\n",
"#1314: 96.73%\n",
"#1315: 96.73%\n",
"#1316: 96.74%\n",
"#1317: 96.74%\n",
"#1318: 96.74%\n",
"#1319: 96.67%\n",
"#1320: 96.67%\n",
"#1321: 96.67%\n",
"#1322: 96.67%\n",
"#1323: 96.68%\n",
"#1324: 96.68%\n",
"#1325: 96.68%\n",
"#1326: 96.68%\n",
"#1327: 96.69%\n",
"#1328: 96.69%\n",
"#1329: 96.69%\n",
"#1330: 96.69%\n",
"#1331: 96.70%\n",
"#1332: 96.70%\n",
"#1333: 96.70%\n",
"#1334: 96.70%\n",
"#1335: 96.71%\n",
"#1336: 96.71%\n",
"#1337: 96.71%\n",
"#1338: 96.71%\n",
"#1339: 96.72%\n",
"#1340: 96.72%\n",
"#1341: 96.72%\n",
"#1342: 96.72%\n",
"#1343: 96.73%\n",
"#1344: 96.73%\n",
"#1345: 96.73%\n",
"#1346: 96.73%\n",
"#1347: 96.74%\n",
"#1348: 96.74%\n",
"#1349: 96.74%\n",
"#1350: 96.74%\n",
"#1351: 96.75%\n",
"#1352: 96.75%\n",
"#1353: 96.75%\n",
"#1354: 96.75%\n",
"#1355: 96.76%\n",
"#1356: 96.76%\n",
"#1357: 96.76%\n",
"#1358: 96.76%\n",
"#1359: 96.76%\n",
"#1360: 96.77%\n",
"#1361: 96.77%\n",
"#1362: 96.77%\n",
"#1363: 96.77%\n",
"#1364: 96.70%\n",
"#1365: 96.71%\n",
"#1366: 96.71%\n",
"#1367: 96.71%\n",
"#1368: 96.71%\n",
"#1369: 96.72%\n",
"#1370: 96.72%\n",
"#1371: 96.72%\n",
"#1372: 96.72%\n",
"#1373: 96.72%\n",
"#1374: 96.73%\n",
"#1375: 96.73%\n",
"#1376: 96.73%\n",
"#1377: 96.73%\n",
"#1378: 96.74%\n",
"#1379: 96.74%\n",
"#1380: 96.74%\n",
"#1381: 96.74%\n",
"#1382: 96.75%\n",
"#1383: 96.68%\n",
"#1384: 96.68%\n",
"#1385: 96.68%\n",
"#1386: 96.68%\n",
"#1387: 96.69%\n",
"#1388: 96.69%\n",
"#1389: 96.69%\n",
"#1390: 96.69%\n",
"#1391: 96.70%\n",
"#1392: 96.70%\n",
"#1393: 96.70%\n",
"#1394: 96.70%\n",
"#1395: 96.70%\n",
"#1396: 96.71%\n",
"#1397: 96.71%\n",
"#1398: 96.71%\n",
"#1399: 96.71%\n",
"#1400: 96.72%\n",
"#1401: 96.72%\n",
"#1402: 96.72%\n",
"#1403: 96.72%\n",
"#1404: 96.73%\n",
"#1405: 96.73%\n",
"#1406: 96.73%\n",
"#1407: 96.73%\n",
"#1408: 96.74%\n",
"#1409: 96.74%\n",
"#1410: 96.74%\n",
"#1411: 96.74%\n",
"#1412: 96.74%\n",
"#1413: 96.75%\n",
"#1414: 96.75%\n",
"#1415: 96.68%\n",
"#1416: 96.68%\n",
"#1417: 96.69%\n",
"#1418: 96.69%\n",
"#1419: 96.69%\n",
"#1420: 96.69%\n",
"#1421: 96.69%\n",
"#1422: 96.70%\n",
"#1423: 96.70%\n",
"#1424: 96.70%\n",
"#1425: 96.70%\n",
"#1426: 96.71%\n",
"#1427: 96.71%\n",
"#1428: 96.71%\n",
"#1429: 96.71%\n",
"#1430: 96.72%\n",
"#1431: 96.72%\n",
"#1432: 96.72%\n",
"#1433: 96.72%\n",
"#1434: 96.72%\n",
"#1435: 96.73%\n",
"#1436: 96.73%\n",
"#1437: 96.73%\n",
"#1438: 96.73%\n",
"#1439: 96.74%\n",
"#1440: 96.67%\n",
"#1441: 96.67%\n",
"#1442: 96.67%\n",
"#1443: 96.68%\n",
"#1444: 96.68%\n",
"#1445: 96.68%\n",
"#1446: 96.68%\n",
"#1447: 96.69%\n",
"#1448: 96.69%\n",
"#1449: 96.69%\n",
"#1450: 96.69%\n",
"#1451: 96.69%\n",
"#1452: 96.70%\n",
"#1453: 96.70%\n",
"#1454: 96.70%\n",
"#1455: 96.70%\n",
"#1456: 96.71%\n",
"#1457: 96.71%\n",
"#1458: 96.71%\n",
"#1459: 96.71%\n",
"#1460: 96.71%\n",
"#1461: 96.72%\n",
"#1462: 96.72%\n",
"#1463: 96.72%\n",
"#1464: 96.72%\n",
"#1465: 96.73%\n",
"#1466: 96.73%\n",
"#1467: 96.73%\n",
"#1468: 96.73%\n",
"#1469: 96.73%\n",
"#1470: 96.74%\n",
"#1471: 96.74%\n",
"#1472: 96.74%\n",
"#1473: 96.74%\n",
"#1474: 96.75%\n",
"#1475: 96.75%\n",
"#1476: 96.75%\n",
"#1477: 96.75%\n",
"#1478: 96.75%\n",
"#1479: 96.76%\n",
"#1480: 96.76%\n",
"#1481: 96.76%\n",
"#1482: 96.76%\n",
"#1483: 96.77%\n",
"#1484: 96.77%\n",
"#1485: 96.77%\n",
"#1486: 96.77%\n",
"#1487: 96.77%\n",
"#1488: 96.78%\n",
"#1489: 96.78%\n",
"#1490: 96.78%\n",
"#1491: 96.78%\n",
"#1492: 96.78%\n",
"#1493: 96.79%\n",
"#1494: 96.79%\n",
"#1495: 96.79%\n",
"#1496: 96.79%\n",
"#1497: 96.80%\n",
"#1498: 96.80%\n",
"#1499: 96.80%\n",
"#1500: 96.80%\n",
"#1501: 96.80%\n",
"#1502: 96.81%\n",
"#1503: 96.81%\n",
"#1504: 96.81%\n",
"#1505: 96.81%\n",
"#1506: 96.81%\n",
"#1507: 96.82%\n",
"#1508: 96.82%\n",
"#1509: 96.82%\n",
"#1510: 96.82%\n",
"#1511: 96.83%\n",
"#1512: 96.83%\n",
"#1513: 96.83%\n",
"#1514: 96.83%\n",
"#1515: 96.83%\n",
"#1516: 96.84%\n",
"#1517: 96.84%\n",
"#1518: 96.84%\n",
"#1519: 96.84%\n",
"#1520: 96.84%\n",
"#1521: 96.85%\n",
"#1522: 96.85%\n",
"#1523: 96.85%\n",
"#1524: 96.85%\n",
"#1525: 96.85%\n",
"#1526: 96.86%\n",
"#1527: 96.79%\n",
"#1528: 96.80%\n",
"#1529: 96.80%\n",
"#1530: 96.73%\n",
"#1531: 96.74%\n",
"#1532: 96.74%\n",
"#1533: 96.74%\n",
"#1534: 96.74%\n",
"#1535: 96.74%\n",
"#1536: 96.75%\n",
"#1537: 96.75%\n",
"#1538: 96.75%\n",
"#1539: 96.75%\n",
"#1540: 96.76%\n",
"#1541: 96.76%\n",
"#1542: 96.76%\n",
"#1543: 96.76%\n",
"#1544: 96.76%\n",
"#1545: 96.77%\n",
"#1546: 96.77%\n",
"#1547: 96.77%\n",
"#1548: 96.77%\n",
"#1549: 96.77%\n",
"#1550: 96.78%\n",
"#1551: 96.78%\n",
"#1552: 96.78%\n",
"#1553: 96.72%\n",
"#1554: 96.72%\n",
"#1555: 96.72%\n",
"#1556: 96.72%\n",
"#1557: 96.73%\n",
"#1558: 96.73%\n",
"#1559: 96.67%\n",
"#1560: 96.67%\n",
"#1561: 96.67%\n",
"#1562: 96.67%\n",
"#1563: 96.68%\n",
"#1564: 96.68%\n",
"#1565: 96.68%\n",
"#1566: 96.68%\n",
"#1567: 96.68%\n",
"#1568: 96.69%\n",
"#1569: 96.69%\n",
"#1570: 96.69%\n",
"#1571: 96.69%\n",
"#1572: 96.69%\n",
"#1573: 96.70%\n",
"#1574: 96.70%\n",
"#1575: 96.70%\n",
"#1576: 96.70%\n",
"#1577: 96.70%\n",
"#1578: 96.71%\n",
"#1579: 96.71%\n",
"#1580: 96.71%\n",
"#1581: 96.71%\n",
"#1582: 96.72%\n",
"#1583: 96.72%\n",
"#1584: 96.72%\n",
"#1585: 96.72%\n",
"#1586: 96.72%\n",
"#1587: 96.73%\n",
"#1588: 96.73%\n",
"#1589: 96.73%\n",
"#1590: 96.73%\n",
"#1591: 96.73%\n",
"#1592: 96.74%\n",
"#1593: 96.74%\n",
"#1594: 96.74%\n",
"#1595: 96.74%\n",
"#1596: 96.74%\n",
"#1597: 96.75%\n",
"#1598: 96.75%\n",
"#1599: 96.75%\n",
"#1600: 96.75%\n",
"#1601: 96.75%\n",
"#1602: 96.76%\n",
"#1603: 96.76%\n",
"#1604: 96.76%\n",
"#1605: 96.76%\n",
"#1606: 96.76%\n",
"#1607: 96.70%\n",
"#1608: 96.71%\n",
"#1609: 96.71%\n",
"#1610: 96.71%\n",
"#1611: 96.65%\n",
"#1612: 96.65%\n",
"#1613: 96.65%\n",
"#1614: 96.66%\n",
"#1615: 96.66%\n",
"#1616: 96.66%\n",
"#1617: 96.66%\n",
"#1618: 96.66%\n",
"#1619: 96.67%\n",
"#1620: 96.67%\n",
"#1621: 96.61%\n",
"#1622: 96.61%\n",
"#1623: 96.61%\n",
"#1624: 96.62%\n",
"#1625: 96.62%\n",
"#1626: 96.62%\n",
"#1627: 96.62%\n",
"#1628: 96.62%\n",
"#1629: 96.63%\n",
"#1630: 96.63%\n",
"#1631: 96.63%\n",
"#1632: 96.63%\n",
"#1633: 96.63%\n",
"#1634: 96.64%\n",
"#1635: 96.64%\n",
"#1636: 96.64%\n",
"#1637: 96.64%\n",
"#1638: 96.64%\n",
"#1639: 96.65%\n",
"#1640: 96.59%\n",
"#1641: 96.59%\n",
"#1642: 96.59%\n",
"#1643: 96.59%\n",
"#1644: 96.60%\n",
"#1645: 96.60%\n",
"#1646: 96.60%\n",
"#1647: 96.60%\n",
"#1648: 96.60%\n",
"#1649: 96.61%\n",
"#1650: 96.61%\n",
"#1651: 96.61%\n",
"#1652: 96.61%\n",
"#1653: 96.61%\n",
"#1654: 96.62%\n",
"#1655: 96.62%\n",
"#1656: 96.62%\n",
"#1657: 96.62%\n",
"#1658: 96.62%\n",
"#1659: 96.63%\n",
"#1660: 96.63%\n",
"#1661: 96.63%\n",
"#1662: 96.63%\n",
"#1663: 96.63%\n",
"#1664: 96.64%\n",
"#1665: 96.64%\n",
"#1666: 96.64%\n",
"#1667: 96.64%\n",
"#1668: 96.64%\n",
"#1669: 96.65%\n",
"#1670: 96.65%\n",
"#1671: 96.65%\n",
"#1672: 96.65%\n",
"#1673: 96.65%\n",
"#1674: 96.66%\n",
"#1675: 96.66%\n",
"#1676: 96.66%\n",
"#1677: 96.66%\n",
"#1678: 96.66%\n",
"#1679: 96.67%\n",
"#1680: 96.67%\n",
"#1681: 96.61%\n",
"#1682: 96.61%\n",
"#1683: 96.62%\n",
"#1684: 96.62%\n",
"#1685: 96.62%\n",
"#1686: 96.56%\n",
"#1687: 96.56%\n",
"#1688: 96.57%\n",
"#1689: 96.57%\n",
"#1690: 96.57%\n",
"#1691: 96.57%\n",
"#1692: 96.57%\n",
"#1693: 96.58%\n",
"#1694: 96.58%\n",
"#1695: 96.58%\n",
"#1696: 96.58%\n",
"#1697: 96.58%\n",
"#1698: 96.59%\n",
"#1699: 96.59%\n",
"#1700: 96.59%\n",
"#1701: 96.59%\n",
"#1702: 96.59%\n",
"#1703: 96.60%\n",
"#1704: 96.60%\n",
"#1705: 96.60%\n",
"#1706: 96.60%\n",
"#1707: 96.60%\n",
"#1708: 96.61%\n",
"#1709: 96.55%\n",
"#1710: 96.55%\n",
"#1711: 96.55%\n",
"#1712: 96.56%\n",
"#1713: 96.56%\n",
"#1714: 96.56%\n",
"#1715: 96.56%\n",
"#1716: 96.56%\n",
"#1717: 96.51%\n",
"#1718: 96.51%\n",
"#1719: 96.51%\n",
"#1720: 96.51%\n",
"#1721: 96.52%\n",
"#1722: 96.52%\n",
"#1723: 96.52%\n",
"#1724: 96.52%\n",
"#1725: 96.52%\n",
"#1726: 96.53%\n",
"#1727: 96.53%\n",
"#1728: 96.53%\n",
"#1729: 96.53%\n",
"#1730: 96.53%\n",
"#1731: 96.54%\n",
"#1732: 96.54%\n",
"#1733: 96.54%\n",
"#1734: 96.54%\n",
"#1735: 96.54%\n",
"#1736: 96.55%\n",
"#1737: 96.49%\n",
"#1738: 96.49%\n",
"#1739: 96.49%\n",
"#1740: 96.50%\n",
"#1741: 96.50%\n",
"#1742: 96.50%\n",
"#1743: 96.50%\n",
"#1744: 96.50%\n",
"#1745: 96.51%\n",
"#1746: 96.51%\n",
"#1747: 96.45%\n",
"#1748: 96.46%\n",
"#1749: 96.46%\n",
"#1750: 96.46%\n",
"#1751: 96.46%\n",
"#1752: 96.46%\n",
"#1753: 96.47%\n",
"#1754: 96.41%\n",
"#1755: 96.41%\n",
"#1756: 96.41%\n",
"#1757: 96.42%\n",
"#1758: 96.42%\n",
"#1759: 96.42%\n",
"#1760: 96.42%\n",
"#1761: 96.42%\n",
"#1762: 96.43%\n",
"#1763: 96.43%\n",
"#1764: 96.43%\n",
"#1765: 96.43%\n",
"#1766: 96.43%\n",
"#1767: 96.44%\n",
"#1768: 96.44%\n",
"#1769: 96.44%\n",
"#1770: 96.44%\n",
"#1771: 96.44%\n",
"#1772: 96.45%\n",
"#1773: 96.45%\n",
"#1774: 96.45%\n",
"#1775: 96.45%\n",
"#1776: 96.45%\n",
"#1777: 96.46%\n",
"#1778: 96.46%\n",
"#1779: 96.46%\n",
"#1780: 96.46%\n",
"#1781: 96.46%\n",
"#1782: 96.47%\n",
"#1783: 96.47%\n",
"#1784: 96.47%\n",
"#1785: 96.47%\n",
"#1786: 96.47%\n",
"#1787: 96.48%\n",
"#1788: 96.48%\n",
"#1789: 96.48%\n",
"#1790: 96.48%\n",
"#1791: 96.48%\n",
"#1792: 96.49%\n",
"#1793: 96.49%\n",
"#1794: 96.49%\n",
"#1795: 96.49%\n",
"#1796: 96.49%\n",
"#1797: 96.50%\n",
"#1798: 96.50%\n",
"#1799: 96.50%\n",
"#1800: 96.50%\n",
"#1801: 96.50%\n",
"#1802: 96.51%\n",
"#1803: 96.51%\n",
"#1804: 96.51%\n",
"#1805: 96.51%\n",
"#1806: 96.51%\n",
"#1807: 96.52%\n",
"#1808: 96.52%\n",
"#1809: 96.52%\n",
"#1810: 96.52%\n",
"#1811: 96.52%\n",
"#1812: 96.53%\n",
"#1813: 96.53%\n",
"#1814: 96.53%\n",
"#1815: 96.53%\n",
"#1816: 96.53%\n",
"#1817: 96.53%\n",
"#1818: 96.54%\n",
"#1819: 96.54%\n",
"#1820: 96.54%\n",
"#1821: 96.54%\n",
"#1822: 96.54%\n",
"#1823: 96.55%\n",
"#1824: 96.55%\n",
"#1825: 96.55%\n",
"#1826: 96.55%\n",
"#1827: 96.55%\n",
"#1828: 96.56%\n",
"#1829: 96.56%\n",
"#1830: 96.56%\n",
"#1831: 96.56%\n",
"#1832: 96.56%\n",
"#1833: 96.56%\n",
"#1834: 96.57%\n",
"#1835: 96.57%\n",
"#1836: 96.57%\n",
"#1837: 96.57%\n",
"#1838: 96.57%\n",
"#1839: 96.58%\n",
"#1840: 96.58%\n",
"#1841: 96.58%\n",
"#1842: 96.58%\n",
"#1843: 96.58%\n",
"#1844: 96.59%\n",
"#1845: 96.59%\n",
"#1846: 96.59%\n",
"#1847: 96.59%\n",
"#1848: 96.59%\n",
"#1849: 96.59%\n",
"#1850: 96.60%\n",
"#1851: 96.60%\n",
"#1852: 96.60%\n",
"#1853: 96.60%\n",
"#1854: 96.60%\n",
"#1855: 96.61%\n",
"#1856: 96.61%\n",
"#1857: 96.61%\n",
"#1858: 96.61%\n",
"#1859: 96.61%\n",
"#1860: 96.61%\n",
"#1861: 96.62%\n",
"#1862: 96.62%\n",
"#1863: 96.62%\n",
"#1864: 96.62%\n",
"#1865: 96.62%\n",
"#1866: 96.63%\n",
"#1867: 96.63%\n",
"#1868: 96.63%\n",
"#1869: 96.63%\n",
"#1870: 96.63%\n",
"#1871: 96.63%\n",
"#1872: 96.64%\n",
"#1873: 96.64%\n",
"#1874: 96.64%\n",
"#1875: 96.64%\n",
"#1876: 96.64%\n",
"#1877: 96.65%\n",
"#1878: 96.65%\n",
"#1879: 96.65%\n",
"#1880: 96.65%\n",
"#1881: 96.65%\n",
"#1882: 96.65%\n",
"#1883: 96.60%\n",
"#1884: 96.60%\n",
"#1885: 96.61%\n",
"#1886: 96.61%\n",
"#1887: 96.61%\n",
"#1888: 96.61%\n",
"#1889: 96.61%\n",
"#1890: 96.62%\n",
"#1891: 96.62%\n",
"#1892: 96.62%\n",
"#1893: 96.62%\n",
"#1894: 96.62%\n",
"#1895: 96.62%\n",
"#1896: 96.63%\n",
"#1897: 96.63%\n",
"#1898: 96.63%\n",
"#1899: 96.63%\n",
"#1900: 96.63%\n",
"#1901: 96.58%\n",
"#1902: 96.58%\n",
"#1903: 96.59%\n",
"#1904: 96.59%\n",
"#1905: 96.59%\n",
"#1906: 96.59%\n",
"#1907: 96.59%\n",
"#1908: 96.60%\n",
"#1909: 96.60%\n",
"#1910: 96.60%\n",
"#1911: 96.60%\n",
"#1912: 96.60%\n",
"#1913: 96.60%\n",
"#1914: 96.61%\n",
"#1915: 96.61%\n",
"#1916: 96.61%\n",
"#1917: 96.61%\n",
"#1918: 96.61%\n",
"#1919: 96.61%\n",
"#1920: 96.62%\n",
"#1921: 96.62%\n",
"#1922: 96.62%\n",
"#1923: 96.62%\n",
"#1924: 96.62%\n",
"#1925: 96.63%\n",
"#1926: 96.63%\n",
"#1927: 96.63%\n",
"#1928: 96.63%\n",
"#1929: 96.63%\n",
"#1930: 96.63%\n",
"#1931: 96.64%\n",
"#1932: 96.64%\n",
"#1933: 96.64%\n",
"#1934: 96.64%\n",
"#1935: 96.64%\n",
"#1936: 96.64%\n",
"#1937: 96.65%\n",
"#1938: 96.65%\n",
"#1939: 96.65%\n",
"#1940: 96.65%\n",
"#1941: 96.65%\n",
"#1942: 96.65%\n",
"#1943: 96.66%\n",
"#1944: 96.66%\n",
"#1945: 96.66%\n",
"#1946: 96.66%\n",
"#1947: 96.66%\n",
"#1948: 96.66%\n",
"#1949: 96.67%\n",
"#1950: 96.67%\n",
"#1951: 96.67%\n",
"#1952: 96.67%\n",
"#1953: 96.67%\n",
"#1954: 96.68%\n",
"#1955: 96.63%\n",
"#1956: 96.63%\n",
"#1957: 96.63%\n",
"#1958: 96.63%\n",
"#1959: 96.63%\n",
"#1960: 96.63%\n",
"#1961: 96.64%\n",
"#1962: 96.64%\n",
"#1963: 96.64%\n",
"#1964: 96.64%\n",
"#1965: 96.64%\n",
"#1966: 96.64%\n",
"#1967: 96.65%\n",
"#1968: 96.65%\n",
"#1969: 96.65%\n",
"#1970: 96.65%\n",
"#1971: 96.65%\n",
"#1972: 96.65%\n",
"#1973: 96.66%\n",
"#1974: 96.66%\n",
"#1975: 96.66%\n",
"#1976: 96.66%\n",
"#1977: 96.66%\n",
"#1978: 96.66%\n",
"#1979: 96.67%\n",
"#1980: 96.67%\n",
"#1981: 96.67%\n",
"#1982: 96.67%\n",
"#1983: 96.67%\n",
"#1984: 96.68%\n",
"#1985: 96.68%\n",
"#1986: 96.68%\n",
"#1987: 96.68%\n",
"#1988: 96.68%\n",
"#1989: 96.68%\n",
"#1990: 96.69%\n",
"#1991: 96.69%\n",
"#1992: 96.69%\n",
"#1993: 96.69%\n",
"#1994: 96.69%\n",
"#1995: 96.69%\n",
"#1996: 96.70%\n",
"#1997: 96.70%\n",
"#1998: 96.70%\n",
"#1999: 96.70%\n",
"#2000: 96.70%\n",
"#2001: 96.70%\n",
"#2002: 96.70%\n",
"#2003: 96.71%\n",
"#2004: 96.71%\n",
"#2005: 96.71%\n",
"#2006: 96.71%\n",
"#2007: 96.71%\n",
"#2008: 96.71%\n",
"#2009: 96.72%\n",
"#2010: 96.72%\n",
"#2011: 96.72%\n",
"#2012: 96.72%\n",
"#2013: 96.72%\n",
"#2014: 96.72%\n",
"#2015: 96.73%\n",
"#2016: 96.73%\n",
"#2017: 96.73%\n",
"#2018: 96.68%\n",
"#2019: 96.68%\n",
"#2020: 96.68%\n",
"#2021: 96.69%\n",
"#2022: 96.69%\n",
"#2023: 96.69%\n",
"#2024: 96.69%\n",
"#2025: 96.64%\n",
"#2026: 96.65%\n",
"#2027: 96.65%\n",
"#2028: 96.65%\n",
"#2029: 96.65%\n",
"#2030: 96.65%\n",
"#2031: 96.65%\n",
"#2032: 96.66%\n",
"#2033: 96.66%\n",
"#2034: 96.66%\n",
"#2035: 96.66%\n",
"#2036: 96.66%\n",
"#2037: 96.66%\n",
"#2038: 96.67%\n",
"#2039: 96.67%\n",
"#2040: 96.67%\n",
"#2041: 96.67%\n",
"#2042: 96.67%\n",
"#2043: 96.62%\n",
"#2044: 96.63%\n",
"#2045: 96.63%\n",
"#2046: 96.63%\n",
"#2047: 96.63%\n",
"#2048: 96.63%\n",
"#2049: 96.63%\n",
"#2050: 96.64%\n",
"#2051: 96.64%\n",
"#2052: 96.64%\n",
"#2053: 96.64%\n",
"#2054: 96.64%\n",
"#2055: 96.64%\n",
"#2056: 96.65%\n",
"#2057: 96.65%\n",
"#2058: 96.65%\n",
"#2059: 96.65%\n",
"#2060: 96.65%\n",
"#2061: 96.65%\n",
"#2062: 96.66%\n",
"#2063: 96.66%\n",
"#2064: 96.66%\n",
"#2065: 96.66%\n",
"#2066: 96.66%\n",
"#2067: 96.66%\n",
"#2068: 96.67%\n",
"#2069: 96.67%\n",
"#2070: 96.62%\n",
"#2071: 96.62%\n",
"#2072: 96.62%\n",
"#2073: 96.62%\n",
"#2074: 96.63%\n",
"#2075: 96.63%\n",
"#2076: 96.63%\n",
"#2077: 96.63%\n",
"#2078: 96.63%\n",
"#2079: 96.63%\n",
"#2080: 96.64%\n",
"#2081: 96.64%\n",
"#2082: 96.64%\n",
"#2083: 96.64%\n",
"#2084: 96.64%\n",
"#2085: 96.64%\n",
"#2086: 96.65%\n",
"#2087: 96.65%\n",
"#2088: 96.65%\n",
"#2089: 96.65%\n",
"#2090: 96.65%\n",
"#2091: 96.65%\n",
"#2092: 96.66%\n",
"#2093: 96.66%\n",
"#2094: 96.66%\n",
"#2095: 96.66%\n",
"#2096: 96.66%\n",
"#2097: 96.66%\n",
"#2098: 96.62%\n",
"#2099: 96.62%\n",
"#2100: 96.62%\n",
"#2101: 96.62%\n",
"#2102: 96.62%\n",
"#2103: 96.63%\n",
"#2104: 96.63%\n",
"#2105: 96.63%\n",
"#2106: 96.63%\n",
"#2107: 96.63%\n",
"#2108: 96.63%\n",
"#2109: 96.59%\n",
"#2110: 96.59%\n",
"#2111: 96.59%\n",
"#2112: 96.59%\n",
"#2113: 96.59%\n",
"#2114: 96.60%\n",
"#2115: 96.60%\n",
"#2116: 96.60%\n",
"#2117: 96.60%\n",
"#2118: 96.55%\n",
"#2119: 96.56%\n",
"#2120: 96.56%\n",
"#2121: 96.56%\n",
"#2122: 96.56%\n",
"#2123: 96.56%\n",
"#2124: 96.56%\n",
"#2125: 96.57%\n",
"#2126: 96.57%\n",
"#2127: 96.57%\n",
"#2128: 96.57%\n",
"#2129: 96.57%\n",
"#2130: 96.53%\n",
"#2131: 96.53%\n",
"#2132: 96.53%\n",
"#2133: 96.53%\n",
"#2134: 96.53%\n",
"#2135: 96.49%\n",
"#2136: 96.49%\n",
"#2137: 96.49%\n",
"#2138: 96.49%\n",
"#2139: 96.50%\n",
"#2140: 96.50%\n",
"#2141: 96.50%\n",
"#2142: 96.50%\n",
"#2143: 96.50%\n",
"#2144: 96.50%\n",
"#2145: 96.51%\n",
"#2146: 96.51%\n",
"#2147: 96.51%\n",
"#2148: 96.51%\n",
"#2149: 96.51%\n",
"#2150: 96.51%\n",
"#2151: 96.51%\n",
"#2152: 96.52%\n",
"#2153: 96.52%\n",
"#2154: 96.52%\n",
"#2155: 96.52%\n",
"#2156: 96.52%\n",
"#2157: 96.52%\n",
"#2158: 96.53%\n",
"#2159: 96.53%\n",
"#2160: 96.53%\n",
"#2161: 96.53%\n",
"#2162: 96.53%\n",
"#2163: 96.53%\n",
"#2164: 96.54%\n",
"#2165: 96.54%\n",
"#2166: 96.54%\n",
"#2167: 96.54%\n",
"#2168: 96.54%\n",
"#2169: 96.54%\n",
"#2170: 96.55%\n",
"#2171: 96.55%\n",
"#2172: 96.55%\n",
"#2173: 96.55%\n",
"#2174: 96.55%\n",
"#2175: 96.55%\n",
"#2176: 96.55%\n",
"#2177: 96.56%\n",
"#2178: 96.56%\n",
"#2179: 96.56%\n",
"#2180: 96.56%\n",
"#2181: 96.56%\n",
"#2182: 96.56%\n",
"#2183: 96.57%\n",
"#2184: 96.57%\n",
"#2185: 96.52%\n",
"#2186: 96.48%\n",
"#2187: 96.48%\n",
"#2188: 96.48%\n",
"#2189: 96.44%\n",
"#2190: 96.44%\n",
"#2191: 96.44%\n",
"#2192: 96.44%\n",
"#2193: 96.44%\n",
"#2194: 96.45%\n",
"#2195: 96.45%\n",
"#2196: 96.45%\n",
"#2197: 96.45%\n",
"#2198: 96.45%\n",
"#2199: 96.45%\n",
"#2200: 96.46%\n",
"#2201: 96.46%\n",
"#2202: 96.46%\n",
"#2203: 96.46%\n",
"#2204: 96.46%\n",
"#2205: 96.46%\n",
"#2206: 96.47%\n",
"#2207: 96.47%\n",
"#2208: 96.47%\n",
"#2209: 96.47%\n",
"#2210: 96.47%\n",
"#2211: 96.47%\n",
"#2212: 96.48%\n",
"#2213: 96.48%\n",
"#2214: 96.48%\n",
"#2215: 96.48%\n",
"#2216: 96.48%\n",
"#2217: 96.48%\n",
"#2218: 96.48%\n",
"#2219: 96.49%\n",
"#2220: 96.49%\n",
"#2221: 96.49%\n",
"#2222: 96.49%\n",
"#2223: 96.49%\n",
"#2224: 96.49%\n",
"#2225: 96.50%\n",
"#2226: 96.50%\n",
"#2227: 96.50%\n",
"#2228: 96.50%\n",
"#2229: 96.50%\n",
"#2230: 96.50%\n",
"#2231: 96.51%\n",
"#2232: 96.51%\n",
"#2233: 96.51%\n",
"#2234: 96.51%\n",
"#2235: 96.51%\n",
"#2236: 96.51%\n",
"#2237: 96.51%\n",
"#2238: 96.52%\n",
"#2239: 96.52%\n",
"#2240: 96.52%\n",
"#2241: 96.52%\n",
"#2242: 96.52%\n",
"#2243: 96.52%\n",
"#2244: 96.53%\n",
"#2245: 96.53%\n",
"#2246: 96.53%\n",
"#2247: 96.53%\n",
"#2248: 96.53%\n",
"#2249: 96.53%\n",
"#2250: 96.53%\n",
"#2251: 96.54%\n",
"#2252: 96.54%\n",
"#2253: 96.54%\n",
"#2254: 96.54%\n",
"#2255: 96.54%\n",
"#2256: 96.54%\n",
"#2257: 96.55%\n",
"#2258: 96.55%\n",
"#2259: 96.55%\n",
"#2260: 96.55%\n",
"#2261: 96.55%\n",
"#2262: 96.55%\n",
"#2263: 96.55%\n",
"#2264: 96.56%\n",
"#2265: 96.56%\n",
"#2266: 96.52%\n",
"#2267: 96.52%\n",
"#2268: 96.52%\n",
"#2269: 96.52%\n",
"#2270: 96.52%\n",
"#2271: 96.52%\n",
"#2272: 96.52%\n",
"#2273: 96.53%\n",
"#2274: 96.53%\n",
"#2275: 96.53%\n",
"#2276: 96.53%\n",
"#2277: 96.53%\n",
"#2278: 96.53%\n",
"#2279: 96.54%\n",
"#2280: 96.49%\n",
"#2281: 96.49%\n",
"#2282: 96.50%\n",
"#2283: 96.50%\n",
"#2284: 96.50%\n",
"#2285: 96.50%\n",
"#2286: 96.50%\n",
"#2287: 96.50%\n",
"#2288: 96.51%\n",
"#2289: 96.51%\n",
"#2290: 96.51%\n",
"#2291: 96.51%\n",
"#2292: 96.51%\n",
"#2293: 96.51%\n",
"#2294: 96.51%\n",
"#2295: 96.52%\n",
"#2296: 96.52%\n",
"#2297: 96.52%\n",
"#2298: 96.52%\n",
"#2299: 96.52%\n",
"#2300: 96.52%\n",
"#2301: 96.52%\n",
"#2302: 96.53%\n",
"#2303: 96.53%\n",
"#2304: 96.53%\n",
"#2305: 96.53%\n",
"#2306: 96.53%\n",
"#2307: 96.53%\n",
"#2308: 96.49%\n",
"#2309: 96.49%\n",
"#2310: 96.50%\n",
"#2311: 96.50%\n",
"#2312: 96.50%\n",
"#2313: 96.50%\n",
"#2314: 96.50%\n",
"#2315: 96.50%\n",
"#2316: 96.50%\n",
"#2317: 96.51%\n",
"#2318: 96.51%\n",
"#2319: 96.51%\n",
"#2320: 96.51%\n",
"#2321: 96.51%\n",
"#2322: 96.51%\n",
"#2323: 96.51%\n",
"#2324: 96.52%\n",
"#2325: 96.52%\n",
"#2326: 96.52%\n",
"#2327: 96.52%\n",
"#2328: 96.52%\n",
"#2329: 96.52%\n",
"#2330: 96.53%\n",
"#2331: 96.53%\n",
"#2332: 96.53%\n",
"#2333: 96.53%\n",
"#2334: 96.53%\n",
"#2335: 96.53%\n",
"#2336: 96.53%\n",
"#2337: 96.54%\n",
"#2338: 96.54%\n",
"#2339: 96.54%\n",
"#2340: 96.54%\n",
"#2341: 96.54%\n",
"#2342: 96.54%\n",
"#2343: 96.54%\n",
"#2344: 96.55%\n",
"#2345: 96.55%\n",
"#2346: 96.55%\n",
"#2347: 96.55%\n",
"#2348: 96.55%\n",
"#2349: 96.55%\n",
"#2350: 96.55%\n",
"#2351: 96.56%\n",
"#2352: 96.56%\n",
"#2353: 96.56%\n",
"#2354: 96.56%\n",
"#2355: 96.56%\n",
"#2356: 96.56%\n",
"#2357: 96.56%\n",
"#2358: 96.57%\n",
"#2359: 96.57%\n",
"#2360: 96.57%\n",
"#2361: 96.57%\n",
"#2362: 96.57%\n",
"#2363: 96.57%\n",
"#2364: 96.58%\n",
"#2365: 96.58%\n",
"#2366: 96.58%\n",
"#2367: 96.58%\n",
"#2368: 96.58%\n",
"#2369: 96.58%\n",
"#2370: 96.58%\n",
"#2371: 96.59%\n",
"#2372: 96.59%\n",
"#2373: 96.59%\n",
"#2374: 96.59%\n",
"#2375: 96.59%\n",
"#2376: 96.59%\n",
"#2377: 96.59%\n",
"#2378: 96.60%\n",
"#2379: 96.60%\n",
"#2380: 96.60%\n",
"#2381: 96.60%\n",
"#2382: 96.60%\n",
"#2383: 96.60%\n",
"#2384: 96.60%\n",
"#2385: 96.61%\n",
"#2386: 96.61%\n",
"#2387: 96.61%\n",
"#2388: 96.61%\n",
"#2389: 96.61%\n",
"#2390: 96.61%\n",
"#2391: 96.61%\n",
"#2392: 96.62%\n",
"#2393: 96.62%\n",
"#2394: 96.62%\n",
"#2395: 96.62%\n",
"#2396: 96.62%\n",
"#2397: 96.62%\n",
"#2398: 96.62%\n",
"#2399: 96.62%\n",
"#2400: 96.63%\n",
"#2401: 96.63%\n",
"#2402: 96.63%\n",
"#2403: 96.63%\n",
"#2404: 96.63%\n",
"#2405: 96.63%\n",
"#2406: 96.63%\n",
"#2407: 96.64%\n",
"#2408: 96.64%\n",
"#2409: 96.64%\n",
"#2410: 96.64%\n",
"#2411: 96.64%\n",
"#2412: 96.64%\n",
"#2413: 96.64%\n",
"#2414: 96.65%\n",
"#2415: 96.65%\n",
"#2416: 96.65%\n",
"#2417: 96.65%\n",
"#2418: 96.65%\n",
"#2419: 96.65%\n",
"#2420: 96.65%\n",
"#2421: 96.66%\n",
"#2422: 96.66%\n",
"#2423: 96.66%\n",
"#2424: 96.66%\n",
"#2425: 96.66%\n",
"#2426: 96.66%\n",
"#2427: 96.66%\n",
"#2428: 96.67%\n",
"#2429: 96.67%\n",
"#2430: 96.67%\n",
"#2431: 96.67%\n",
"#2432: 96.67%\n",
"#2433: 96.67%\n",
"#2434: 96.67%\n",
"#2435: 96.67%\n",
"#2436: 96.68%\n",
"#2437: 96.68%\n",
"#2438: 96.68%\n",
"#2439: 96.68%\n",
"#2440: 96.68%\n",
"#2441: 96.68%\n",
"#2442: 96.68%\n",
"#2443: 96.69%\n",
"#2444: 96.69%\n",
"#2445: 96.69%\n",
"#2446: 96.69%\n",
"#2447: 96.69%\n",
"#2448: 96.69%\n",
"#2449: 96.69%\n",
"#2450: 96.70%\n",
"#2451: 96.70%\n",
"#2452: 96.70%\n",
"#2453: 96.70%\n",
"#2454: 96.66%\n",
"#2455: 96.66%\n",
"#2456: 96.66%\n",
"#2457: 96.66%\n",
"#2458: 96.67%\n",
"#2459: 96.67%\n",
"#2460: 96.67%\n",
"#2461: 96.67%\n",
"#2462: 96.63%\n",
"#2463: 96.63%\n",
"#2464: 96.63%\n",
"#2465: 96.63%\n",
"#2466: 96.64%\n",
"#2467: 96.64%\n",
"#2468: 96.64%\n",
"#2469: 96.64%\n",
"#2470: 96.64%\n",
"#2471: 96.64%\n",
"#2472: 96.64%\n",
"#2473: 96.65%\n",
"#2474: 96.65%\n",
"#2475: 96.65%\n",
"#2476: 96.65%\n",
"#2477: 96.65%\n",
"#2478: 96.65%\n",
"#2479: 96.65%\n",
"#2480: 96.65%\n",
"#2481: 96.66%\n",
"#2482: 96.66%\n",
"#2483: 96.66%\n",
"#2484: 96.66%\n",
"#2485: 96.66%\n",
"#2486: 96.66%\n",
"#2487: 96.66%\n",
"#2488: 96.63%\n",
"#2489: 96.63%\n",
"#2490: 96.63%\n",
"#2491: 96.63%\n",
"#2492: 96.63%\n",
"#2493: 96.63%\n",
"#2494: 96.63%\n",
"#2495: 96.63%\n",
"#2496: 96.64%\n",
"#2497: 96.64%\n",
"#2498: 96.64%\n",
"#2499: 96.64%\n",
"#2500: 96.64%\n",
"#2501: 96.64%\n",
"#2502: 96.64%\n",
"#2503: 96.65%\n",
"#2504: 96.65%\n",
"#2505: 96.65%\n",
"#2506: 96.65%\n",
"#2507: 96.65%\n",
"#2508: 96.65%\n",
"#2509: 96.65%\n",
"#2510: 96.65%\n",
"#2511: 96.66%\n",
"#2512: 96.66%\n",
"#2513: 96.66%\n",
"#2514: 96.66%\n",
"#2515: 96.66%\n",
"#2516: 96.66%\n",
"#2517: 96.66%\n",
"#2518: 96.67%\n",
"#2519: 96.67%\n",
"#2520: 96.67%\n",
"#2521: 96.67%\n",
"#2522: 96.67%\n",
"#2523: 96.67%\n",
"#2524: 96.67%\n",
"#2525: 96.67%\n",
"#2526: 96.68%\n",
"#2527: 96.68%\n",
"#2528: 96.68%\n",
"#2529: 96.68%\n",
"#2530: 96.68%\n",
"#2531: 96.68%\n",
"#2532: 96.68%\n",
"#2533: 96.65%\n",
"#2534: 96.61%\n",
"#2535: 96.61%\n",
"#2536: 96.61%\n",
"#2537: 96.61%\n",
"#2538: 96.61%\n",
"#2539: 96.61%\n",
"#2540: 96.62%\n",
"#2541: 96.62%\n",
"#2542: 96.62%\n",
"#2543: 96.62%\n",
"#2544: 96.62%\n",
"#2545: 96.62%\n",
"#2546: 96.62%\n",
"#2547: 96.62%\n",
"#2548: 96.63%\n",
"#2549: 96.63%\n",
"#2550: 96.63%\n",
"#2551: 96.63%\n",
"#2552: 96.63%\n",
"#2553: 96.63%\n",
"#2554: 96.63%\n",
"#2555: 96.64%\n",
"#2556: 96.64%\n",
"#2557: 96.64%\n",
"#2558: 96.64%\n",
"#2559: 96.64%\n",
"#2560: 96.60%\n",
"#2561: 96.60%\n",
"#2562: 96.61%\n",
"#2563: 96.61%\n",
"#2564: 96.61%\n",
"#2565: 96.61%\n",
"#2566: 96.61%\n",
"#2567: 96.61%\n",
"#2568: 96.61%\n",
"#2569: 96.61%\n",
"#2570: 96.62%\n",
"#2571: 96.62%\n",
"#2572: 96.62%\n",
"#2573: 96.62%\n",
"#2574: 96.62%\n",
"#2575: 96.62%\n",
"#2576: 96.62%\n",
"#2577: 96.63%\n",
"#2578: 96.63%\n",
"#2579: 96.63%\n",
"#2580: 96.63%\n",
"#2581: 96.63%\n",
"#2582: 96.63%\n",
"#2583: 96.63%\n",
"#2584: 96.63%\n",
"#2585: 96.64%\n",
"#2586: 96.64%\n",
"#2587: 96.64%\n",
"#2588: 96.64%\n",
"#2589: 96.64%\n",
"#2590: 96.64%\n",
"#2591: 96.64%\n",
"#2592: 96.64%\n",
"#2593: 96.65%\n",
"#2594: 96.61%\n",
"#2595: 96.61%\n",
"#2596: 96.61%\n",
"#2597: 96.57%\n",
"#2598: 96.58%\n",
"#2599: 96.58%\n",
"#2600: 96.58%\n",
"#2601: 96.58%\n",
"#2602: 96.58%\n",
"#2603: 96.58%\n",
"#2604: 96.58%\n",
"#2605: 96.58%\n",
"#2606: 96.59%\n",
"#2607: 96.59%\n",
"#2608: 96.59%\n",
"#2609: 96.59%\n",
"#2610: 96.59%\n",
"#2611: 96.59%\n",
"#2612: 96.59%\n",
"#2613: 96.60%\n",
"#2614: 96.60%\n",
"#2615: 96.60%\n",
"#2616: 96.60%\n",
"#2617: 96.60%\n",
"#2618: 96.60%\n",
"#2619: 96.60%\n",
"#2620: 96.60%\n",
"#2621: 96.61%\n",
"#2622: 96.61%\n",
"#2623: 96.61%\n",
"#2624: 96.61%\n",
"#2625: 96.61%\n",
"#2626: 96.61%\n",
"#2627: 96.61%\n",
"#2628: 96.61%\n",
"#2629: 96.62%\n",
"#2630: 96.62%\n",
"#2631: 96.62%\n",
"#2632: 96.62%\n",
"#2633: 96.62%\n",
"#2634: 96.62%\n",
"#2635: 96.62%\n",
"#2636: 96.59%\n",
"#2637: 96.59%\n",
"#2638: 96.59%\n",
"#2639: 96.59%\n",
"#2640: 96.59%\n",
"#2641: 96.59%\n",
"#2642: 96.59%\n",
"#2643: 96.60%\n",
"#2644: 96.60%\n",
"#2645: 96.60%\n",
"#2646: 96.60%\n",
"#2647: 96.60%\n",
"#2648: 96.60%\n",
"#2649: 96.60%\n",
"#2650: 96.61%\n",
"#2651: 96.61%\n",
"#2652: 96.61%\n",
"#2653: 96.61%\n",
"#2654: 96.57%\n",
"#2655: 96.57%\n",
"#2656: 96.58%\n",
"#2657: 96.58%\n",
"#2658: 96.58%\n",
"#2659: 96.58%\n",
"#2660: 96.58%\n",
"#2661: 96.58%\n",
"#2662: 96.58%\n",
"#2663: 96.58%\n",
"#2664: 96.59%\n",
"#2665: 96.59%\n",
"#2666: 96.59%\n",
"#2667: 96.59%\n",
"#2668: 96.59%\n",
"#2669: 96.59%\n",
"#2670: 96.59%\n",
"#2671: 96.59%\n",
"#2672: 96.60%\n",
"#2673: 96.60%\n",
"#2674: 96.60%\n",
"#2675: 96.60%\n",
"#2676: 96.60%\n",
"#2677: 96.60%\n",
"#2678: 96.60%\n",
"#2679: 96.60%\n",
"#2680: 96.61%\n",
"#2681: 96.61%\n",
"#2682: 96.61%\n",
"#2683: 96.61%\n",
"#2684: 96.61%\n",
"#2685: 96.61%\n",
"#2686: 96.61%\n",
"#2687: 96.61%\n",
"#2688: 96.62%\n",
"#2689: 96.62%\n",
"#2690: 96.62%\n",
"#2691: 96.62%\n",
"#2692: 96.62%\n",
"#2693: 96.62%\n",
"#2694: 96.62%\n",
"#2695: 96.62%\n",
"#2696: 96.63%\n",
"#2697: 96.63%\n",
"#2698: 96.63%\n",
"#2699: 96.63%\n",
"#2700: 96.63%\n",
"#2701: 96.63%\n",
"#2702: 96.63%\n",
"#2703: 96.63%\n",
"#2704: 96.64%\n",
"#2705: 96.64%\n",
"#2706: 96.64%\n",
"#2707: 96.64%\n",
"#2708: 96.64%\n",
"#2709: 96.64%\n",
"#2710: 96.64%\n",
"#2711: 96.64%\n",
"#2712: 96.65%\n",
"#2713: 96.65%\n",
"#2714: 96.65%\n",
"#2715: 96.65%\n",
"#2716: 96.65%\n",
"#2717: 96.65%\n",
"#2718: 96.65%\n",
"#2719: 96.65%\n",
"#2720: 96.66%\n",
"#2721: 96.66%\n",
"#2722: 96.66%\n",
"#2723: 96.66%\n",
"#2724: 96.66%\n",
"#2725: 96.66%\n",
"#2726: 96.66%\n",
"#2727: 96.66%\n",
"#2728: 96.67%\n",
"#2729: 96.67%\n",
"#2730: 96.67%\n",
"#2731: 96.67%\n",
"#2732: 96.67%\n",
"#2733: 96.67%\n",
"#2734: 96.67%\n",
"#2735: 96.67%\n",
"#2736: 96.68%\n",
"#2737: 96.68%\n",
"#2738: 96.68%\n",
"#2739: 96.68%\n",
"#2740: 96.68%\n",
"#2741: 96.68%\n",
"#2742: 96.68%\n",
"#2743: 96.68%\n",
"#2744: 96.68%\n",
"#2745: 96.69%\n",
"#2746: 96.69%\n",
"#2747: 96.69%\n",
"#2748: 96.69%\n",
"#2749: 96.69%\n",
"#2750: 96.69%\n",
"#2751: 96.69%\n",
"#2752: 96.69%\n",
"#2753: 96.70%\n",
"#2754: 96.70%\n",
"#2755: 96.70%\n",
"#2756: 96.70%\n",
"#2757: 96.70%\n",
"#2758: 96.70%\n",
"#2759: 96.70%\n",
"#2760: 96.67%\n",
"#2761: 96.67%\n",
"#2762: 96.67%\n",
"#2763: 96.67%\n",
"#2764: 96.67%\n",
"#2765: 96.67%\n",
"#2766: 96.68%\n",
"#2767: 96.68%\n",
"#2768: 96.68%\n",
"#2769: 96.68%\n",
"#2770: 96.64%\n",
"#2771: 96.65%\n",
"#2772: 96.65%\n",
"#2773: 96.65%\n",
"#2774: 96.65%\n",
"#2775: 96.65%\n",
"#2776: 96.65%\n",
"#2777: 96.65%\n",
"#2778: 96.62%\n",
"#2779: 96.62%\n",
"#2780: 96.58%\n",
"#2781: 96.59%\n",
"#2782: 96.59%\n",
"#2783: 96.59%\n",
"#2784: 96.59%\n",
"#2785: 96.59%\n",
"#2786: 96.59%\n",
"#2787: 96.59%\n",
"#2788: 96.59%\n",
"#2789: 96.59%\n",
"#2790: 96.60%\n",
"#2791: 96.60%\n",
"#2792: 96.60%\n",
"#2793: 96.60%\n",
"#2794: 96.60%\n",
"#2795: 96.60%\n",
"#2796: 96.60%\n",
"#2797: 96.60%\n",
"#2798: 96.61%\n",
"#2799: 96.61%\n",
"#2800: 96.61%\n",
"#2801: 96.61%\n",
"#2802: 96.61%\n",
"#2803: 96.61%\n",
"#2804: 96.61%\n",
"#2805: 96.61%\n",
"#2806: 96.62%\n",
"#2807: 96.62%\n",
"#2808: 96.62%\n",
"#2809: 96.62%\n",
"#2810: 96.62%\n",
"#2811: 96.62%\n",
"#2812: 96.62%\n",
"#2813: 96.62%\n",
"#2814: 96.63%\n",
"#2815: 96.63%\n",
"#2816: 96.63%\n",
"#2817: 96.63%\n",
"#2818: 96.63%\n",
"#2819: 96.63%\n",
"#2820: 96.63%\n",
"#2821: 96.63%\n",
"#2822: 96.63%\n",
"#2823: 96.60%\n",
"#2824: 96.60%\n",
"#2825: 96.60%\n",
"#2826: 96.60%\n",
"#2827: 96.61%\n",
"#2828: 96.61%\n",
"#2829: 96.61%\n",
"#2830: 96.61%\n",
"#2831: 96.61%\n",
"#2832: 96.61%\n",
"#2833: 96.61%\n",
"#2834: 96.61%\n",
"#2835: 96.61%\n",
"#2836: 96.62%\n",
"#2837: 96.62%\n",
"#2838: 96.62%\n",
"#2839: 96.62%\n",
"#2840: 96.62%\n",
"#2841: 96.62%\n",
"#2842: 96.62%\n",
"#2843: 96.62%\n",
"#2844: 96.63%\n",
"#2845: 96.63%\n",
"#2846: 96.63%\n",
"#2847: 96.63%\n",
"#2848: 96.63%\n",
"#2849: 96.63%\n",
"#2850: 96.63%\n",
"#2851: 96.63%\n",
"#2852: 96.64%\n",
"#2853: 96.64%\n",
"#2854: 96.64%\n",
"#2855: 96.64%\n",
"#2856: 96.64%\n",
"#2857: 96.64%\n",
"#2858: 96.64%\n",
"#2859: 96.64%\n",
"#2860: 96.64%\n",
"#2861: 96.65%\n",
"#2862: 96.65%\n",
"#2863: 96.65%\n",
"#2864: 96.65%\n",
"#2865: 96.65%\n",
"#2866: 96.65%\n",
"#2867: 96.65%\n",
"#2868: 96.65%\n",
"#2869: 96.66%\n",
"#2870: 96.66%\n",
"#2871: 96.66%\n",
"#2872: 96.66%\n",
"#2873: 96.66%\n",
"#2874: 96.66%\n",
"#2875: 96.66%\n",
"#2876: 96.66%\n",
"#2877: 96.66%\n",
"#2878: 96.67%\n",
"#2879: 96.67%\n",
"#2880: 96.67%\n",
"#2881: 96.67%\n",
"#2882: 96.67%\n",
"#2883: 96.67%\n",
"#2884: 96.67%\n",
"#2885: 96.67%\n",
"#2886: 96.67%\n",
"#2887: 96.68%\n",
"#2888: 96.68%\n",
"#2889: 96.68%\n",
"#2890: 96.68%\n",
"#2891: 96.68%\n",
"#2892: 96.68%\n",
"#2893: 96.68%\n",
"#2894: 96.68%\n",
"#2895: 96.69%\n",
"#2896: 96.65%\n",
"#2897: 96.65%\n",
"#2898: 96.65%\n",
"#2899: 96.66%\n",
"#2900: 96.66%\n",
"#2901: 96.66%\n",
"#2902: 96.66%\n",
"#2903: 96.66%\n",
"#2904: 96.66%\n",
"#2905: 96.66%\n",
"#2906: 96.66%\n",
"#2907: 96.66%\n",
"#2908: 96.67%\n",
"#2909: 96.67%\n",
"#2910: 96.67%\n",
"#2911: 96.67%\n",
"#2912: 96.67%\n",
"#2913: 96.67%\n",
"#2914: 96.67%\n",
"#2915: 96.67%\n",
"#2916: 96.67%\n",
"#2917: 96.68%\n",
"#2918: 96.68%\n",
"#2919: 96.68%\n",
"#2920: 96.68%\n",
"#2921: 96.68%\n",
"#2922: 96.68%\n",
"#2923: 96.68%\n",
"#2924: 96.68%\n",
"#2925: 96.68%\n",
"#2926: 96.69%\n",
"#2927: 96.65%\n",
"#2928: 96.65%\n",
"#2929: 96.66%\n",
"#2930: 96.66%\n",
"#2931: 96.66%\n",
"#2932: 96.66%\n",
"#2933: 96.66%\n",
"#2934: 96.66%\n",
"#2935: 96.66%\n",
"#2936: 96.66%\n",
"#2937: 96.66%\n",
"#2938: 96.67%\n",
"#2939: 96.63%\n",
"#2940: 96.63%\n",
"#2941: 96.63%\n",
"#2942: 96.64%\n",
"#2943: 96.64%\n",
"#2944: 96.64%\n",
"#2945: 96.64%\n",
"#2946: 96.64%\n",
"#2947: 96.64%\n",
"#2948: 96.64%\n",
"#2949: 96.64%\n",
"#2950: 96.65%\n",
"#2951: 96.65%\n",
"#2952: 96.61%\n",
"#2953: 96.61%\n",
"#2954: 96.62%\n",
"#2955: 96.62%\n",
"#2956: 96.62%\n",
"#2957: 96.62%\n",
"#2958: 96.62%\n",
"#2959: 96.62%\n",
"#2960: 96.62%\n",
"#2961: 96.62%\n",
"#2962: 96.63%\n",
"#2963: 96.63%\n",
"#2964: 96.63%\n",
"#2965: 96.63%\n",
"#2966: 96.63%\n",
"#2967: 96.63%\n",
"#2968: 96.63%\n",
"#2969: 96.63%\n",
"#2970: 96.63%\n",
"#2971: 96.64%\n",
"#2972: 96.64%\n",
"#2973: 96.64%\n",
"#2974: 96.64%\n",
"#2975: 96.64%\n",
"#2976: 96.64%\n",
"#2977: 96.64%\n",
"#2978: 96.64%\n",
"#2979: 96.64%\n",
"#2980: 96.65%\n",
"#2981: 96.65%\n",
"#2982: 96.65%\n",
"#2983: 96.65%\n",
"#2984: 96.65%\n",
"#2985: 96.65%\n",
"#2986: 96.65%\n",
"#2987: 96.65%\n",
"#2988: 96.65%\n",
"#2989: 96.66%\n",
"#2990: 96.66%\n",
"#2991: 96.66%\n",
"#2992: 96.66%\n",
"#2993: 96.66%\n",
"#2994: 96.66%\n",
"#2995: 96.63%\n",
"#2996: 96.63%\n",
"#2997: 96.63%\n",
"#2998: 96.63%\n",
"#2999: 96.63%\n",
"#3000: 96.63%\n",
"#3001: 96.64%\n",
"#3002: 96.64%\n",
"#3003: 96.64%\n",
"#3004: 96.64%\n",
"#3005: 96.61%\n",
"#3006: 96.61%\n",
"#3007: 96.61%\n",
"#3008: 96.61%\n",
"#3009: 96.61%\n",
"#3010: 96.61%\n",
"#3011: 96.61%\n",
"#3012: 96.61%\n",
"#3013: 96.62%\n",
"#3014: 96.62%\n",
"#3015: 96.62%\n",
"#3016: 96.62%\n",
"#3017: 96.62%\n",
"#3018: 96.62%\n",
"#3019: 96.62%\n",
"#3020: 96.62%\n",
"#3021: 96.62%\n",
"#3022: 96.63%\n",
"#3023: 96.63%\n",
"#3024: 96.63%\n",
"#3025: 96.63%\n",
"#3026: 96.63%\n",
"#3027: 96.63%\n",
"#3028: 96.63%\n",
"#3029: 96.63%\n",
"#3030: 96.60%\n",
"#3031: 96.60%\n",
"#3032: 96.60%\n",
"#3033: 96.61%\n",
"#3034: 96.61%\n",
"#3035: 96.61%\n",
"#3036: 96.61%\n",
"#3037: 96.61%\n",
"#3038: 96.61%\n",
"#3039: 96.61%\n",
"#3040: 96.61%\n",
"#3041: 96.61%\n",
"#3042: 96.62%\n",
"#3043: 96.62%\n",
"#3044: 96.62%\n",
"#3045: 96.62%\n",
"#3046: 96.62%\n",
"#3047: 96.62%\n",
"#3048: 96.62%\n",
"#3049: 96.62%\n",
"#3050: 96.62%\n",
"#3051: 96.63%\n",
"#3052: 96.63%\n",
"#3053: 96.63%\n",
"#3054: 96.63%\n",
"#3055: 96.63%\n",
"#3056: 96.63%\n",
"#3057: 96.63%\n",
"#3058: 96.63%\n",
"#3059: 96.63%\n",
"#3060: 96.60%\n",
"#3061: 96.60%\n",
"#3062: 96.60%\n",
"#3063: 96.61%\n",
"#3064: 96.61%\n",
"#3065: 96.61%\n",
"#3066: 96.61%\n",
"#3067: 96.61%\n",
"#3068: 96.61%\n",
"#3069: 96.61%\n",
"#3070: 96.61%\n",
"#3071: 96.61%\n",
"#3072: 96.62%\n",
"#3073: 96.58%\n",
"#3074: 96.59%\n",
"#3075: 96.59%\n",
"#3076: 96.59%\n",
"#3077: 96.59%\n",
"#3078: 96.59%\n",
"#3079: 96.59%\n",
"#3080: 96.59%\n",
"#3081: 96.59%\n",
"#3082: 96.59%\n",
"#3083: 96.60%\n",
"#3084: 96.60%\n",
"#3085: 96.60%\n",
"#3086: 96.60%\n",
"#3087: 96.60%\n",
"#3088: 96.60%\n",
"#3089: 96.60%\n",
"#3090: 96.60%\n",
"#3091: 96.60%\n",
"#3092: 96.61%\n",
"#3093: 96.61%\n",
"#3094: 96.61%\n",
"#3095: 96.61%\n",
"#3096: 96.61%\n",
"#3097: 96.61%\n",
"#3098: 96.61%\n",
"#3099: 96.61%\n",
"#3100: 96.61%\n",
"#3101: 96.62%\n",
"#3102: 96.62%\n",
"#3103: 96.62%\n",
"#3104: 96.62%\n",
"#3105: 96.62%\n",
"#3106: 96.62%\n",
"#3107: 96.62%\n",
"#3108: 96.62%\n",
"#3109: 96.62%\n",
"#3110: 96.62%\n",
"#3111: 96.63%\n",
"#3112: 96.63%\n",
"#3113: 96.63%\n",
"#3114: 96.60%\n",
"#3115: 96.60%\n",
"#3116: 96.60%\n",
"#3117: 96.60%\n",
"#3118: 96.60%\n",
"#3119: 96.60%\n",
"#3120: 96.60%\n",
"#3121: 96.60%\n",
"#3122: 96.61%\n",
"#3123: 96.61%\n",
"#3124: 96.61%\n",
"#3125: 96.61%\n",
"#3126: 96.61%\n",
"#3127: 96.61%\n",
"#3128: 96.61%\n",
"#3129: 96.61%\n",
"#3130: 96.61%\n",
"#3131: 96.62%\n",
"#3132: 96.62%\n",
"#3133: 96.62%\n",
"#3134: 96.62%\n",
"#3135: 96.62%\n",
"#3136: 96.62%\n",
"#3137: 96.62%\n",
"#3138: 96.62%\n",
"#3139: 96.62%\n",
"#3140: 96.63%\n",
"#3141: 96.63%\n",
"#3142: 96.63%\n",
"#3143: 96.63%\n",
"#3144: 96.63%\n",
"#3145: 96.63%\n",
"#3146: 96.63%\n",
"#3147: 96.63%\n",
"#3148: 96.63%\n",
"#3149: 96.63%\n",
"#3150: 96.64%\n",
"#3151: 96.64%\n",
"#3152: 96.64%\n",
"#3153: 96.64%\n",
"#3154: 96.64%\n",
"#3155: 96.64%\n",
"#3156: 96.64%\n",
"#3157: 96.64%\n",
"#3158: 96.64%\n",
"#3159: 96.65%\n",
"#3160: 96.65%\n",
"#3161: 96.65%\n",
"#3162: 96.65%\n",
"#3163: 96.65%\n",
"#3164: 96.65%\n",
"#3165: 96.65%\n",
"#3166: 96.65%\n",
"#3167: 96.65%\n",
"#3168: 96.66%\n",
"#3169: 96.66%\n",
"#3170: 96.66%\n",
"#3171: 96.66%\n",
"#3172: 96.66%\n",
"#3173: 96.66%\n",
"#3174: 96.66%\n",
"#3175: 96.66%\n",
"#3176: 96.66%\n",
"#3177: 96.66%\n",
"#3178: 96.67%\n",
"#3179: 96.67%\n",
"#3180: 96.67%\n",
"#3181: 96.67%\n",
"#3182: 96.67%\n",
"#3183: 96.67%\n",
"#3184: 96.67%\n",
"#3185: 96.67%\n",
"#3186: 96.67%\n",
"#3187: 96.68%\n",
"#3188: 96.68%\n",
"#3189: 96.65%\n",
"#3190: 96.65%\n",
"#3191: 96.65%\n",
"#3192: 96.65%\n",
"#3193: 96.65%\n",
"#3194: 96.65%\n",
"#3195: 96.65%\n",
"#3196: 96.65%\n",
"#3197: 96.65%\n",
"#3198: 96.66%\n",
"#3199: 96.66%\n",
"#3200: 96.66%\n",
"#3201: 96.66%\n",
"#3202: 96.66%\n",
"#3203: 96.66%\n",
"#3204: 96.66%\n",
"#3205: 96.66%\n",
"#3206: 96.66%\n",
"#3207: 96.66%\n",
"#3208: 96.67%\n",
"#3209: 96.67%\n",
"#3210: 96.67%\n",
"#3211: 96.67%\n",
"#3212: 96.67%\n",
"#3213: 96.67%\n",
"#3214: 96.67%\n",
"#3215: 96.67%\n",
"#3216: 96.67%\n",
"#3217: 96.67%\n",
"#3218: 96.68%\n",
"#3219: 96.68%\n",
"#3220: 96.68%\n",
"#3221: 96.68%\n",
"#3222: 96.68%\n",
"#3223: 96.68%\n",
"#3224: 96.68%\n",
"#3225: 96.68%\n",
"#3226: 96.68%\n",
"#3227: 96.69%\n",
"#3228: 96.69%\n",
"#3229: 96.69%\n",
"#3230: 96.69%\n",
"#3231: 96.69%\n",
"#3232: 96.69%\n",
"#3233: 96.69%\n",
"#3234: 96.69%\n",
"#3235: 96.69%\n",
"#3236: 96.69%\n",
"#3237: 96.70%\n",
"#3238: 96.70%\n",
"#3239: 96.67%\n",
"#3240: 96.67%\n",
"#3241: 96.67%\n",
"#3242: 96.67%\n",
"#3243: 96.67%\n",
"#3244: 96.67%\n",
"#3245: 96.67%\n",
"#3246: 96.64%\n",
"#3247: 96.64%\n",
"#3248: 96.65%\n",
"#3249: 96.65%\n",
"#3250: 96.65%\n",
"#3251: 96.65%\n",
"#3252: 96.65%\n",
"#3253: 96.65%\n",
"#3254: 96.65%\n",
"#3255: 96.65%\n",
"#3256: 96.65%\n",
"#3257: 96.65%\n",
"#3258: 96.66%\n",
"#3259: 96.66%\n",
"#3260: 96.66%\n",
"#3261: 96.66%\n",
"#3262: 96.63%\n",
"#3263: 96.63%\n",
"#3264: 96.63%\n",
"#3265: 96.63%\n",
"#3266: 96.63%\n",
"#3267: 96.63%\n",
"#3268: 96.64%\n",
"#3269: 96.64%\n",
"#3270: 96.64%\n",
"#3271: 96.64%\n",
"#3272: 96.64%\n",
"#3273: 96.64%\n",
"#3274: 96.64%\n",
"#3275: 96.64%\n",
"#3276: 96.64%\n",
"#3277: 96.64%\n",
"#3278: 96.65%\n",
"#3279: 96.65%\n",
"#3280: 96.65%\n",
"#3281: 96.65%\n",
"#3282: 96.65%\n",
"#3283: 96.65%\n",
"#3284: 96.65%\n",
"#3285: 96.65%\n",
"#3286: 96.65%\n",
"#3287: 96.65%\n",
"#3288: 96.66%\n",
"#3289: 96.63%\n",
"#3290: 96.63%\n",
"#3291: 96.63%\n",
"#3292: 96.63%\n",
"#3293: 96.63%\n",
"#3294: 96.63%\n",
"#3295: 96.63%\n",
"#3296: 96.63%\n",
"#3297: 96.63%\n",
"#3298: 96.64%\n",
"#3299: 96.64%\n",
"#3300: 96.64%\n",
"#3301: 96.64%\n",
"#3302: 96.64%\n",
"#3303: 96.64%\n",
"#3304: 96.64%\n",
"#3305: 96.64%\n",
"#3306: 96.64%\n",
"#3307: 96.64%\n",
"#3308: 96.65%\n",
"#3309: 96.65%\n",
"#3310: 96.65%\n",
"#3311: 96.65%\n",
"#3312: 96.65%\n",
"#3313: 96.65%\n",
"#3314: 96.65%\n",
"#3315: 96.65%\n",
"#3316: 96.62%\n",
"#3317: 96.62%\n",
"#3318: 96.63%\n",
"#3319: 96.60%\n",
"#3320: 96.60%\n",
"#3321: 96.60%\n",
"#3322: 96.60%\n",
"#3323: 96.60%\n",
"#3324: 96.60%\n",
"#3325: 96.60%\n",
"#3326: 96.60%\n",
"#3327: 96.60%\n",
"#3328: 96.61%\n",
"#3329: 96.61%\n",
"#3330: 96.61%\n",
"#3331: 96.61%\n",
"#3332: 96.61%\n",
"#3333: 96.58%\n",
"#3334: 96.58%\n",
"#3335: 96.58%\n",
"#3336: 96.58%\n",
"#3337: 96.58%\n",
"#3338: 96.59%\n",
"#3339: 96.59%\n",
"#3340: 96.59%\n",
"#3341: 96.59%\n",
"#3342: 96.59%\n",
"#3343: 96.59%\n",
"#3344: 96.59%\n",
"#3345: 96.59%\n",
"#3346: 96.59%\n",
"#3347: 96.59%\n",
"#3348: 96.60%\n",
"#3349: 96.60%\n",
"#3350: 96.60%\n",
"#3351: 96.60%\n",
"#3352: 96.60%\n",
"#3353: 96.60%\n",
"#3354: 96.60%\n",
"#3355: 96.60%\n",
"#3356: 96.60%\n",
"#3357: 96.61%\n",
"#3358: 96.61%\n",
"#3359: 96.61%\n",
"#3360: 96.61%\n",
"#3361: 96.61%\n",
"#3362: 96.61%\n",
"#3363: 96.61%\n",
"#3364: 96.61%\n",
"#3365: 96.61%\n",
"#3366: 96.61%\n",
"#3367: 96.62%\n",
"#3368: 96.62%\n",
"#3369: 96.62%\n",
"#3370: 96.62%\n",
"#3371: 96.62%\n",
"#3372: 96.62%\n",
"#3373: 96.62%\n",
"#3374: 96.62%\n",
"#3375: 96.62%\n",
"#3376: 96.62%\n",
"#3377: 96.63%\n",
"#3378: 96.63%\n",
"#3379: 96.63%\n",
"#3380: 96.63%\n",
"#3381: 96.63%\n",
"#3382: 96.63%\n",
"#3383: 96.63%\n",
"#3384: 96.63%\n",
"#3385: 96.63%\n",
"#3386: 96.63%\n",
"#3387: 96.64%\n",
"#3388: 96.64%\n",
"#3389: 96.64%\n",
"#3390: 96.64%\n",
"#3391: 96.64%\n",
"#3392: 96.64%\n",
"#3393: 96.64%\n",
"#3394: 96.64%\n",
"#3395: 96.64%\n",
"#3396: 96.64%\n",
"#3397: 96.65%\n",
"#3398: 96.65%\n",
"#3399: 96.65%\n",
"#3400: 96.65%\n",
"#3401: 96.65%\n",
"#3402: 96.65%\n",
"#3403: 96.65%\n",
"#3404: 96.65%\n",
"#3405: 96.65%\n",
"#3406: 96.65%\n",
"#3407: 96.65%\n",
"#3408: 96.66%\n",
"#3409: 96.66%\n",
"#3410: 96.66%\n",
"#3411: 96.66%\n",
"#3412: 96.66%\n",
"#3413: 96.66%\n",
"#3414: 96.66%\n",
"#3415: 96.66%\n",
"#3416: 96.66%\n",
"#3417: 96.66%\n",
"#3418: 96.67%\n",
"#3419: 96.67%\n",
"#3420: 96.67%\n",
"#3421: 96.67%\n",
"#3422: 96.67%\n",
"#3423: 96.67%\n",
"#3424: 96.67%\n",
"#3425: 96.67%\n",
"#3426: 96.67%\n",
"#3427: 96.67%\n",
"#3428: 96.68%\n",
"#3429: 96.68%\n",
"#3430: 96.68%\n",
"#3431: 96.68%\n",
"#3432: 96.68%\n",
"#3433: 96.68%\n",
"#3434: 96.68%\n",
"#3435: 96.68%\n",
"#3436: 96.68%\n",
"#3437: 96.68%\n",
"#3438: 96.69%\n",
"#3439: 96.69%\n",
"#3440: 96.69%\n",
"#3441: 96.69%\n",
"#3442: 96.69%\n",
"#3443: 96.69%\n",
"#3444: 96.69%\n",
"#3445: 96.69%\n",
"#3446: 96.69%\n",
"#3447: 96.69%\n",
"#3448: 96.69%\n",
"#3449: 96.70%\n",
"#3450: 96.70%\n",
"#3451: 96.70%\n",
"#3452: 96.70%\n",
"#3453: 96.70%\n",
"#3454: 96.70%\n",
"#3455: 96.70%\n",
"#3456: 96.70%\n",
"#3457: 96.70%\n",
"#3458: 96.70%\n",
"#3459: 96.71%\n",
"#3460: 96.71%\n",
"#3461: 96.71%\n",
"#3462: 96.71%\n",
"#3463: 96.71%\n",
"#3464: 96.71%\n",
"#3465: 96.71%\n",
"#3466: 96.71%\n",
"#3467: 96.71%\n",
"#3468: 96.71%\n",
"#3469: 96.71%\n",
"#3470: 96.72%\n",
"#3471: 96.72%\n",
"#3472: 96.72%\n",
"#3473: 96.72%\n",
"#3474: 96.72%\n",
"#3475: 96.72%\n",
"#3476: 96.72%\n",
"#3477: 96.72%\n",
"#3478: 96.72%\n",
"#3479: 96.72%\n",
"#3480: 96.73%\n",
"#3481: 96.73%\n",
"#3482: 96.73%\n",
"#3483: 96.73%\n",
"#3484: 96.73%\n",
"#3485: 96.73%\n",
"#3486: 96.73%\n",
"#3487: 96.73%\n",
"#3488: 96.73%\n",
"#3489: 96.73%\n",
"#3490: 96.73%\n",
"#3491: 96.74%\n",
"#3492: 96.74%\n",
"#3493: 96.74%\n",
"#3494: 96.74%\n",
"#3495: 96.74%\n",
"#3496: 96.74%\n",
"#3497: 96.74%\n",
"#3498: 96.74%\n",
"#3499: 96.74%\n",
"#3500: 96.74%\n",
"#3501: 96.74%\n",
"#3502: 96.75%\n",
"#3503: 96.72%\n",
"#3504: 96.72%\n",
"#3505: 96.72%\n",
"#3506: 96.72%\n",
"#3507: 96.72%\n",
"#3508: 96.72%\n",
"#3509: 96.72%\n",
"#3510: 96.72%\n",
"#3511: 96.73%\n",
"#3512: 96.73%\n",
"#3513: 96.73%\n",
"#3514: 96.73%\n",
"#3515: 96.73%\n",
"#3516: 96.73%\n",
"#3517: 96.73%\n",
"#3518: 96.73%\n",
"#3519: 96.73%\n",
"#3520: 96.71%\n",
"#3521: 96.71%\n",
"#3522: 96.71%\n",
"#3523: 96.71%\n",
"#3524: 96.71%\n",
"#3525: 96.71%\n",
"#3526: 96.71%\n",
"#3527: 96.71%\n",
"#3528: 96.71%\n",
"#3529: 96.71%\n",
"#3530: 96.71%\n",
"#3531: 96.72%\n",
"#3532: 96.72%\n",
"#3533: 96.72%\n",
"#3534: 96.72%\n",
"#3535: 96.72%\n",
"#3536: 96.72%\n",
"#3537: 96.72%\n",
"#3538: 96.72%\n",
"#3539: 96.72%\n",
"#3540: 96.72%\n",
"#3541: 96.73%\n",
"#3542: 96.73%\n",
"#3543: 96.73%\n",
"#3544: 96.73%\n",
"#3545: 96.73%\n",
"#3546: 96.73%\n",
"#3547: 96.73%\n",
"#3548: 96.73%\n",
"#3549: 96.73%\n",
"#3550: 96.73%\n",
"#3551: 96.73%\n",
"#3552: 96.74%\n",
"#3553: 96.74%\n",
"#3554: 96.74%\n",
"#3555: 96.74%\n",
"#3556: 96.74%\n",
"#3557: 96.74%\n",
"#3558: 96.74%\n",
"#3559: 96.71%\n",
"#3560: 96.71%\n",
"#3561: 96.72%\n",
"#3562: 96.72%\n",
"#3563: 96.72%\n",
"#3564: 96.72%\n",
"#3565: 96.72%\n",
"#3566: 96.72%\n",
"#3567: 96.72%\n",
"#3568: 96.72%\n",
"#3569: 96.72%\n",
"#3570: 96.72%\n",
"#3571: 96.72%\n",
"#3572: 96.73%\n",
"#3573: 96.73%\n",
"#3574: 96.73%\n",
"#3575: 96.73%\n",
"#3576: 96.73%\n",
"#3577: 96.73%\n",
"#3578: 96.73%\n",
"#3579: 96.73%\n",
"#3580: 96.73%\n",
"#3581: 96.73%\n",
"#3582: 96.73%\n",
"#3583: 96.74%\n",
"#3584: 96.74%\n",
"#3585: 96.74%\n",
"#3586: 96.74%\n",
"#3587: 96.74%\n",
"#3588: 96.74%\n",
"#3589: 96.74%\n",
"#3590: 96.74%\n",
"#3591: 96.74%\n",
"#3592: 96.74%\n",
"#3593: 96.74%\n",
"#3594: 96.75%\n",
"#3595: 96.75%\n",
"#3596: 96.75%\n",
"#3597: 96.72%\n",
"#3598: 96.72%\n",
"#3599: 96.72%\n",
"#3600: 96.72%\n",
"#3601: 96.72%\n",
"#3602: 96.72%\n",
"#3603: 96.73%\n",
"#3604: 96.73%\n",
"#3605: 96.73%\n",
"#3606: 96.73%\n",
"#3607: 96.73%\n",
"#3608: 96.73%\n",
"#3609: 96.73%\n",
"#3610: 96.73%\n",
"#3611: 96.73%\n",
"#3612: 96.73%\n",
"#3613: 96.73%\n",
"#3614: 96.74%\n",
"#3615: 96.74%\n",
"#3616: 96.74%\n",
"#3617: 96.74%\n",
"#3618: 96.74%\n",
"#3619: 96.74%\n",
"#3620: 96.74%\n",
"#3621: 96.74%\n",
"#3622: 96.74%\n",
"#3623: 96.74%\n",
"#3624: 96.74%\n",
"#3625: 96.75%\n",
"#3626: 96.75%\n",
"#3627: 96.75%\n",
"#3628: 96.75%\n",
"#3629: 96.75%\n",
"#3630: 96.75%\n",
"#3631: 96.75%\n",
"#3632: 96.75%\n",
"#3633: 96.75%\n",
"#3634: 96.75%\n",
"#3635: 96.75%\n",
"#3636: 96.76%\n",
"#3637: 96.76%\n",
"#3638: 96.76%\n",
"#3639: 96.76%\n",
"#3640: 96.76%\n",
"#3641: 96.76%\n",
"#3642: 96.76%\n",
"#3643: 96.76%\n",
"#3644: 96.76%\n",
"#3645: 96.76%\n",
"#3646: 96.76%\n",
"#3647: 96.77%\n",
"#3648: 96.77%\n",
"#3649: 96.77%\n",
"#3650: 96.77%\n",
"#3651: 96.77%\n",
"#3652: 96.77%\n",
"#3653: 96.77%\n",
"#3654: 96.77%\n",
"#3655: 96.77%\n",
"#3656: 96.77%\n",
"#3657: 96.77%\n",
"#3658: 96.78%\n",
"#3659: 96.78%\n",
"#3660: 96.78%\n",
"#3661: 96.78%\n",
"#3662: 96.78%\n",
"#3663: 96.78%\n",
"#3664: 96.78%\n",
"#3665: 96.78%\n",
"#3666: 96.78%\n",
"#3667: 96.78%\n",
"#3668: 96.78%\n",
"#3669: 96.78%\n",
"#3670: 96.79%\n",
"#3671: 96.79%\n",
"#3672: 96.79%\n",
"#3673: 96.79%\n",
"#3674: 96.79%\n",
"#3675: 96.79%\n",
"#3676: 96.79%\n",
"#3677: 96.79%\n",
"#3678: 96.79%\n",
"#3679: 96.79%\n",
"#3680: 96.79%\n",
"#3681: 96.80%\n",
"#3682: 96.80%\n",
"#3683: 96.80%\n",
"#3684: 96.80%\n",
"#3685: 96.80%\n",
"#3686: 96.80%\n",
"#3687: 96.80%\n",
"#3688: 96.80%\n",
"#3689: 96.80%\n",
"#3690: 96.80%\n",
"#3691: 96.80%\n",
"#3692: 96.80%\n",
"#3693: 96.81%\n",
"#3694: 96.81%\n",
"#3695: 96.81%\n",
"#3696: 96.81%\n",
"#3697: 96.81%\n",
"#3698: 96.81%\n",
"#3699: 96.81%\n",
"#3700: 96.81%\n",
"#3701: 96.81%\n",
"#3702: 96.81%\n",
"#3703: 96.81%\n",
"#3704: 96.82%\n",
"#3705: 96.82%\n",
"#3706: 96.82%\n",
"#3707: 96.82%\n",
"#3708: 96.82%\n",
"#3709: 96.82%\n",
"#3710: 96.82%\n",
"#3711: 96.82%\n",
"#3712: 96.82%\n",
"#3713: 96.82%\n",
"#3714: 96.82%\n",
"#3715: 96.82%\n",
"#3716: 96.83%\n",
"#3717: 96.83%\n",
"#3718: 96.83%\n",
"#3719: 96.83%\n",
"#3720: 96.83%\n",
"#3721: 96.83%\n",
"#3722: 96.83%\n",
"#3723: 96.83%\n",
"#3724: 96.83%\n",
"#3725: 96.83%\n",
"#3726: 96.81%\n",
"#3727: 96.81%\n",
"#3728: 96.81%\n",
"#3729: 96.81%\n",
"#3730: 96.81%\n",
"#3731: 96.81%\n",
"#3732: 96.81%\n",
"#3733: 96.81%\n",
"#3734: 96.81%\n",
"#3735: 96.81%\n",
"#3736: 96.82%\n",
"#3737: 96.82%\n",
"#3738: 96.79%\n",
"#3739: 96.79%\n",
"#3740: 96.79%\n",
"#3741: 96.79%\n",
"#3742: 96.79%\n",
"#3743: 96.79%\n",
"#3744: 96.80%\n",
"#3745: 96.80%\n",
"#3746: 96.80%\n",
"#3747: 96.80%\n",
"#3748: 96.80%\n",
"#3749: 96.80%\n",
"#3750: 96.80%\n",
"#3751: 96.80%\n",
"#3752: 96.80%\n",
"#3753: 96.80%\n",
"#3754: 96.80%\n",
"#3755: 96.81%\n",
"#3756: 96.81%\n",
"#3757: 96.78%\n",
"#3758: 96.78%\n",
"#3759: 96.78%\n",
"#3760: 96.78%\n",
"#3761: 96.78%\n",
"#3762: 96.78%\n",
"#3763: 96.79%\n",
"#3764: 96.79%\n",
"#3765: 96.79%\n",
"#3766: 96.79%\n",
"#3767: 96.76%\n",
"#3768: 96.76%\n",
"#3769: 96.76%\n",
"#3770: 96.76%\n",
"#3771: 96.77%\n",
"#3772: 96.77%\n",
"#3773: 96.77%\n",
"#3774: 96.77%\n",
"#3775: 96.77%\n",
"#3776: 96.77%\n",
"#3777: 96.77%\n",
"#3778: 96.77%\n",
"#3779: 96.77%\n",
"#3780: 96.75%\n",
"#3781: 96.75%\n",
"#3782: 96.75%\n",
"#3783: 96.75%\n",
"#3784: 96.75%\n",
"#3785: 96.75%\n",
"#3786: 96.75%\n",
"#3787: 96.75%\n",
"#3788: 96.75%\n",
"#3789: 96.75%\n",
"#3790: 96.76%\n",
"#3791: 96.76%\n",
"#3792: 96.76%\n",
"#3793: 96.76%\n",
"#3794: 96.76%\n",
"#3795: 96.76%\n",
"#3796: 96.76%\n",
"#3797: 96.76%\n",
"#3798: 96.76%\n",
"#3799: 96.76%\n",
"#3800: 96.76%\n",
"#3801: 96.76%\n",
"#3802: 96.77%\n",
"#3803: 96.77%\n",
"#3804: 96.77%\n",
"#3805: 96.77%\n",
"#3806: 96.77%\n",
"#3807: 96.77%\n",
"#3808: 96.74%\n",
"#3809: 96.75%\n",
"#3810: 96.75%\n",
"#3811: 96.75%\n",
"#3812: 96.75%\n",
"#3813: 96.75%\n",
"#3814: 96.75%\n",
"#3815: 96.75%\n",
"#3816: 96.75%\n",
"#3817: 96.75%\n",
"#3818: 96.75%\n",
"#3819: 96.75%\n",
"#3820: 96.75%\n",
"#3821: 96.76%\n",
"#3822: 96.76%\n",
"#3823: 96.76%\n",
"#3824: 96.76%\n",
"#3825: 96.76%\n",
"#3826: 96.76%\n",
"#3827: 96.76%\n",
"#3828: 96.76%\n",
"#3829: 96.76%\n",
"#3830: 96.76%\n",
"#3831: 96.76%\n",
"#3832: 96.76%\n",
"#3833: 96.77%\n",
"#3834: 96.77%\n",
"#3835: 96.77%\n",
"#3836: 96.77%\n",
"#3837: 96.77%\n",
"#3838: 96.77%\n",
"#3839: 96.77%\n",
"#3840: 96.77%\n",
"#3841: 96.77%\n",
"#3842: 96.77%\n",
"#3843: 96.77%\n",
"#3844: 96.78%\n",
"#3845: 96.78%\n",
"#3846: 96.78%\n",
"#3847: 96.78%\n",
"#3848: 96.78%\n",
"#3849: 96.78%\n",
"#3850: 96.75%\n",
"#3851: 96.75%\n",
"#3852: 96.76%\n",
"#3853: 96.76%\n",
"#3854: 96.76%\n",
"#3855: 96.73%\n",
"#3856: 96.73%\n",
"#3857: 96.73%\n",
"#3858: 96.73%\n",
"#3859: 96.74%\n",
"#3860: 96.74%\n",
"#3861: 96.74%\n",
"#3862: 96.74%\n",
"#3863: 96.74%\n",
"#3864: 96.74%\n",
"#3865: 96.74%\n",
"#3866: 96.74%\n",
"#3867: 96.74%\n",
"#3868: 96.74%\n",
"#3869: 96.74%\n",
"#3870: 96.75%\n",
"#3871: 96.75%\n",
"#3872: 96.75%\n",
"#3873: 96.75%\n",
"#3874: 96.75%\n",
"#3875: 96.75%\n",
"#3876: 96.75%\n",
"#3877: 96.75%\n",
"#3878: 96.75%\n",
"#3879: 96.75%\n",
"#3880: 96.75%\n",
"#3881: 96.75%\n",
"#3882: 96.76%\n",
"#3883: 96.76%\n",
"#3884: 96.76%\n",
"#3885: 96.76%\n",
"#3886: 96.76%\n",
"#3887: 96.76%\n",
"#3888: 96.76%\n",
"#3889: 96.76%\n",
"#3890: 96.76%\n",
"#3891: 96.76%\n",
"#3892: 96.76%\n",
"#3893: 96.76%\n",
"#3894: 96.77%\n",
"#3895: 96.77%\n",
"#3896: 96.77%\n",
"#3897: 96.77%\n",
"#3898: 96.77%\n",
"#3899: 96.77%\n",
"#3900: 96.77%\n",
"#3901: 96.77%\n",
"#3902: 96.77%\n",
"#3903: 96.77%\n",
"#3904: 96.77%\n",
"#3905: 96.77%\n",
"#3906: 96.75%\n",
"#3907: 96.75%\n",
"#3908: 96.75%\n",
"#3909: 96.75%\n",
"#3910: 96.75%\n",
"#3911: 96.75%\n",
"#3912: 96.75%\n",
"#3913: 96.76%\n",
"#3914: 96.76%\n",
"#3915: 96.76%\n",
"#3916: 96.76%\n",
"#3917: 96.76%\n",
"#3918: 96.76%\n",
"#3919: 96.76%\n",
"#3920: 96.76%\n",
"#3921: 96.76%\n",
"#3922: 96.76%\n",
"#3923: 96.76%\n",
"#3924: 96.76%\n",
"#3925: 96.77%\n",
"#3926: 96.77%\n",
"#3927: 96.77%\n",
"#3928: 96.77%\n",
"#3929: 96.77%\n",
"#3930: 96.77%\n",
"#3931: 96.77%\n",
"#3932: 96.77%\n",
"#3933: 96.77%\n",
"#3934: 96.77%\n",
"#3935: 96.77%\n",
"#3936: 96.77%\n",
"#3937: 96.78%\n",
"#3938: 96.78%\n",
"#3939: 96.78%\n",
"#3940: 96.78%\n",
"#3941: 96.78%\n",
"#3942: 96.78%\n",
"#3943: 96.75%\n",
"#3944: 96.76%\n",
"#3945: 96.76%\n",
"#3946: 96.76%\n",
"#3947: 96.76%\n",
"#3948: 96.76%\n",
"#3949: 96.76%\n",
"#3950: 96.76%\n",
"#3951: 96.76%\n",
"#3952: 96.76%\n",
"#3953: 96.76%\n",
"#3954: 96.76%\n",
"#3955: 96.76%\n",
"#3956: 96.77%\n",
"#3957: 96.77%\n",
"#3958: 96.77%\n",
"#3959: 96.77%\n",
"#3960: 96.77%\n",
"#3961: 96.77%\n",
"#3962: 96.77%\n",
"#3963: 96.77%\n",
"#3964: 96.77%\n",
"#3965: 96.77%\n",
"#3966: 96.77%\n",
"#3967: 96.77%\n",
"#3968: 96.78%\n",
"#3969: 96.78%\n",
"#3970: 96.78%\n",
"#3971: 96.78%\n",
"#3972: 96.78%\n",
"#3973: 96.78%\n",
"#3974: 96.78%\n",
"#3975: 96.78%\n",
"#3976: 96.76%\n",
"#3977: 96.76%\n",
"#3978: 96.76%\n",
"#3979: 96.76%\n",
"#3980: 96.76%\n",
"#3981: 96.76%\n",
"#3982: 96.76%\n",
"#3983: 96.76%\n",
"#3984: 96.76%\n",
"#3985: 96.76%\n",
"#3986: 96.76%\n",
"#3987: 96.77%\n",
"#3988: 96.77%\n",
"#3989: 96.77%\n",
"#3990: 96.77%\n",
"#3991: 96.77%\n",
"#3992: 96.77%\n",
"#3993: 96.77%\n",
"#3994: 96.77%\n",
"#3995: 96.77%\n",
"#3996: 96.77%\n",
"#3997: 96.77%\n",
"#3998: 96.77%\n",
"#3999: 96.78%\n",
"#4000: 96.78%\n",
"#4001: 96.78%\n",
"#4002: 96.78%\n",
"#4003: 96.78%\n",
"#4004: 96.78%\n",
"#4005: 96.78%\n",
"#4006: 96.78%\n",
"#4007: 96.78%\n",
"#4008: 96.78%\n",
"#4009: 96.78%\n",
"#4010: 96.78%\n",
"#4011: 96.78%\n",
"#4012: 96.79%\n",
"#4013: 96.79%\n",
"#4014: 96.79%\n",
"#4015: 96.79%\n",
"#4016: 96.79%\n",
"#4017: 96.79%\n",
"#4018: 96.79%\n",
"#4019: 96.79%\n",
"#4020: 96.79%\n",
"#4021: 96.79%\n",
"#4022: 96.79%\n",
"#4023: 96.79%\n",
"#4024: 96.80%\n",
"#4025: 96.80%\n",
"#4026: 96.80%\n",
"#4027: 96.80%\n",
"#4028: 96.80%\n",
"#4029: 96.80%\n",
"#4030: 96.80%\n",
"#4031: 96.80%\n",
"#4032: 96.80%\n",
"#4033: 96.80%\n",
"#4034: 96.80%\n",
"#4035: 96.80%\n",
"#4036: 96.80%\n",
"#4037: 96.81%\n",
"#4038: 96.81%\n",
"#4039: 96.81%\n",
"#4040: 96.81%\n",
"#4041: 96.81%\n",
"#4042: 96.81%\n",
"#4043: 96.81%\n",
"#4044: 96.81%\n",
"#4045: 96.81%\n",
"#4046: 96.81%\n",
"#4047: 96.81%\n",
"#4048: 96.81%\n",
"#4049: 96.81%\n",
"#4050: 96.82%\n",
"#4051: 96.82%\n",
"#4052: 96.82%\n",
"#4053: 96.82%\n",
"#4054: 96.82%\n",
"#4055: 96.82%\n",
"#4056: 96.82%\n",
"#4057: 96.82%\n",
"#4058: 96.82%\n",
"#4059: 96.82%\n",
"#4060: 96.82%\n",
"#4061: 96.82%\n",
"#4062: 96.83%\n",
"#4063: 96.80%\n",
"#4064: 96.80%\n",
"#4065: 96.80%\n",
"#4066: 96.80%\n",
"#4067: 96.80%\n",
"#4068: 96.81%\n",
"#4069: 96.81%\n",
"#4070: 96.81%\n",
"#4071: 96.81%\n",
"#4072: 96.81%\n",
"#4073: 96.81%\n",
"#4074: 96.81%\n",
"#4075: 96.81%\n",
"#4076: 96.81%\n",
"#4077: 96.81%\n",
"#4078: 96.79%\n",
"#4079: 96.79%\n",
"#4080: 96.79%\n",
"#4081: 96.79%\n",
"#4082: 96.79%\n",
"#4083: 96.79%\n",
"#4084: 96.79%\n",
"#4085: 96.79%\n",
"#4086: 96.79%\n",
"#4087: 96.80%\n",
"#4088: 96.80%\n",
"#4089: 96.80%\n",
"#4090: 96.80%\n",
"#4091: 96.80%\n",
"#4092: 96.80%\n",
"#4093: 96.80%\n",
"#4094: 96.80%\n",
"#4095: 96.80%\n",
"#4096: 96.80%\n",
"#4097: 96.80%\n",
"#4098: 96.80%\n",
"#4099: 96.80%\n",
"#4100: 96.81%\n",
"#4101: 96.81%\n",
"#4102: 96.81%\n",
"#4103: 96.81%\n",
"#4104: 96.81%\n",
"#4105: 96.81%\n",
"#4106: 96.81%\n",
"#4107: 96.81%\n",
"#4108: 96.81%\n",
"#4109: 96.81%\n",
"#4110: 96.81%\n",
"#4111: 96.81%\n",
"#4112: 96.81%\n",
"#4113: 96.82%\n",
"#4114: 96.82%\n",
"#4115: 96.82%\n",
"#4116: 96.79%\n",
"#4117: 96.79%\n",
"#4118: 96.80%\n",
"#4119: 96.80%\n",
"#4120: 96.80%\n",
"#4121: 96.80%\n",
"#4122: 96.80%\n",
"#4123: 96.77%\n",
"#4124: 96.78%\n",
"#4125: 96.78%\n",
"#4126: 96.78%\n",
"#4127: 96.78%\n",
"#4128: 96.78%\n",
"#4129: 96.78%\n",
"#4130: 96.78%\n",
"#4131: 96.78%\n",
"#4132: 96.78%\n",
"#4133: 96.78%\n",
"#4134: 96.78%\n",
"#4135: 96.78%\n",
"#4136: 96.79%\n",
"#4137: 96.79%\n",
"#4138: 96.79%\n",
"#4139: 96.79%\n",
"#4140: 96.79%\n",
"#4141: 96.79%\n",
"#4142: 96.79%\n",
"#4143: 96.79%\n",
"#4144: 96.79%\n",
"#4145: 96.79%\n",
"#4146: 96.79%\n",
"#4147: 96.79%\n",
"#4148: 96.79%\n",
"#4149: 96.80%\n",
"#4150: 96.80%\n",
"#4151: 96.80%\n",
"#4152: 96.80%\n",
"#4153: 96.80%\n",
"#4154: 96.80%\n",
"#4155: 96.80%\n",
"#4156: 96.80%\n",
"#4157: 96.80%\n",
"#4158: 96.80%\n",
"#4159: 96.80%\n",
"#4160: 96.80%\n",
"#4161: 96.80%\n",
"#4162: 96.81%\n",
"#4163: 96.78%\n",
"#4164: 96.78%\n",
"#4165: 96.78%\n",
"#4166: 96.78%\n",
"#4167: 96.79%\n",
"#4168: 96.79%\n",
"#4169: 96.79%\n",
"#4170: 96.79%\n",
"#4171: 96.79%\n",
"#4172: 96.79%\n",
"#4173: 96.79%\n",
"#4174: 96.79%\n",
"#4175: 96.79%\n",
"#4176: 96.77%\n",
"#4177: 96.77%\n",
"#4178: 96.77%\n",
"#4179: 96.77%\n",
"#4180: 96.77%\n",
"#4181: 96.77%\n",
"#4182: 96.77%\n",
"#4183: 96.77%\n",
"#4184: 96.77%\n",
"#4185: 96.77%\n",
"#4186: 96.78%\n",
"#4187: 96.78%\n",
"#4188: 96.78%\n",
"#4189: 96.78%\n",
"#4190: 96.78%\n",
"#4191: 96.78%\n",
"#4192: 96.78%\n",
"#4193: 96.78%\n",
"#4194: 96.78%\n",
"#4195: 96.78%\n",
"#4196: 96.78%\n",
"#4197: 96.78%\n",
"#4198: 96.78%\n",
"#4199: 96.79%\n",
"#4200: 96.79%\n",
"#4201: 96.79%\n",
"#4202: 96.79%\n",
"#4203: 96.79%\n",
"#4204: 96.79%\n",
"#4205: 96.77%\n",
"#4206: 96.77%\n",
"#4207: 96.77%\n",
"#4208: 96.77%\n",
"#4209: 96.77%\n",
"#4210: 96.77%\n",
"#4211: 96.77%\n",
"#4212: 96.77%\n",
"#4213: 96.77%\n",
"#4214: 96.77%\n",
"#4215: 96.77%\n",
"#4216: 96.77%\n",
"#4217: 96.78%\n",
"#4218: 96.78%\n",
"#4219: 96.78%\n",
"#4220: 96.78%\n",
"#4221: 96.78%\n",
"#4222: 96.78%\n",
"#4223: 96.78%\n",
"#4224: 96.78%\n",
"#4225: 96.78%\n",
"#4226: 96.78%\n",
"#4227: 96.78%\n",
"#4228: 96.78%\n",
"#4229: 96.78%\n",
"#4230: 96.79%\n",
"#4231: 96.79%\n",
"#4232: 96.79%\n",
"#4233: 96.79%\n",
"#4234: 96.79%\n",
"#4235: 96.79%\n",
"#4236: 96.79%\n",
"#4237: 96.79%\n",
"#4238: 96.79%\n",
"#4239: 96.79%\n",
"#4240: 96.79%\n",
"#4241: 96.79%\n",
"#4242: 96.79%\n",
"#4243: 96.80%\n",
"#4244: 96.80%\n",
"#4245: 96.80%\n",
"#4246: 96.80%\n",
"#4247: 96.80%\n",
"#4248: 96.80%\n",
"#4249: 96.80%\n",
"#4250: 96.80%\n",
"#4251: 96.80%\n",
"#4252: 96.80%\n",
"#4253: 96.80%\n",
"#4254: 96.80%\n",
"#4255: 96.80%\n",
"#4256: 96.78%\n",
"#4257: 96.78%\n",
"#4258: 96.78%\n",
"#4259: 96.78%\n",
"#4260: 96.78%\n",
"#4261: 96.79%\n",
"#4262: 96.79%\n",
"#4263: 96.79%\n",
"#4264: 96.79%\n",
"#4265: 96.77%\n",
"#4266: 96.77%\n",
"#4267: 96.77%\n",
"#4268: 96.77%\n",
"#4269: 96.77%\n",
"#4270: 96.77%\n",
"#4271: 96.77%\n",
"#4272: 96.77%\n",
"#4273: 96.77%\n",
"#4274: 96.77%\n",
"#4275: 96.77%\n",
"#4276: 96.77%\n",
"#4277: 96.77%\n",
"#4278: 96.77%\n",
"#4279: 96.78%\n",
"#4280: 96.78%\n",
"#4281: 96.78%\n",
"#4282: 96.78%\n",
"#4283: 96.78%\n",
"#4284: 96.78%\n",
"#4285: 96.78%\n",
"#4286: 96.78%\n",
"#4287: 96.78%\n",
"#4288: 96.78%\n",
"#4289: 96.78%\n",
"#4290: 96.78%\n",
"#4291: 96.78%\n",
"#4292: 96.79%\n",
"#4293: 96.79%\n",
"#4294: 96.79%\n",
"#4295: 96.79%\n",
"#4296: 96.79%\n",
"#4297: 96.79%\n",
"#4298: 96.79%\n",
"#4299: 96.79%\n",
"#4300: 96.79%\n",
"#4301: 96.79%\n",
"#4302: 96.79%\n",
"#4303: 96.79%\n",
"#4304: 96.79%\n",
"#4305: 96.80%\n",
"#4306: 96.77%\n",
"#4307: 96.77%\n",
"#4308: 96.77%\n",
"#4309: 96.77%\n",
"#4310: 96.78%\n",
"#4311: 96.78%\n",
"#4312: 96.78%\n",
"#4313: 96.78%\n",
"#4314: 96.78%\n",
"#4315: 96.78%\n",
"#4316: 96.78%\n",
"#4317: 96.78%\n",
"#4318: 96.78%\n",
"#4319: 96.78%\n",
"#4320: 96.78%\n",
"#4321: 96.78%\n",
"#4322: 96.78%\n",
"#4323: 96.79%\n",
"#4324: 96.79%\n",
"#4325: 96.79%\n",
"#4326: 96.79%\n",
"#4327: 96.79%\n",
"#4328: 96.79%\n",
"#4329: 96.79%\n",
"#4330: 96.79%\n",
"#4331: 96.79%\n",
"#4332: 96.79%\n",
"#4333: 96.79%\n",
"#4334: 96.79%\n",
"#4335: 96.79%\n",
"#4336: 96.80%\n",
"#4337: 96.80%\n",
"#4338: 96.80%\n",
"#4339: 96.80%\n",
"#4340: 96.80%\n",
"#4341: 96.80%\n",
"#4342: 96.80%\n",
"#4343: 96.80%\n",
"#4344: 96.80%\n",
"#4345: 96.80%\n",
"#4346: 96.80%\n",
"#4347: 96.80%\n",
"#4348: 96.80%\n",
"#4349: 96.80%\n",
"#4350: 96.81%\n",
"#4351: 96.81%\n",
"#4352: 96.81%\n",
"#4353: 96.81%\n",
"#4354: 96.81%\n",
"#4355: 96.81%\n",
"#4356: 96.81%\n",
"#4357: 96.81%\n",
"#4358: 96.81%\n",
"#4359: 96.81%\n",
"#4360: 96.81%\n",
"#4361: 96.81%\n",
"#4362: 96.81%\n",
"#4363: 96.81%\n",
"#4364: 96.82%\n",
"#4365: 96.82%\n",
"#4366: 96.82%\n",
"#4367: 96.82%\n",
"#4368: 96.82%\n",
"#4369: 96.82%\n",
"#4370: 96.82%\n",
"#4371: 96.82%\n",
"#4372: 96.82%\n",
"#4373: 96.82%\n",
"#4374: 96.82%\n",
"#4375: 96.82%\n",
"#4376: 96.82%\n",
"#4377: 96.83%\n",
"#4378: 96.83%\n",
"#4379: 96.83%\n",
"#4380: 96.83%\n",
"#4381: 96.83%\n",
"#4382: 96.83%\n",
"#4383: 96.83%\n",
"#4384: 96.83%\n",
"#4385: 96.83%\n",
"#4386: 96.83%\n",
"#4387: 96.83%\n",
"#4388: 96.83%\n",
"#4389: 96.83%\n",
"#4390: 96.83%\n",
"#4391: 96.81%\n",
"#4392: 96.81%\n",
"#4393: 96.81%\n",
"#4394: 96.81%\n",
"#4395: 96.82%\n",
"#4396: 96.82%\n",
"#4397: 96.82%\n",
"#4398: 96.82%\n",
"#4399: 96.82%\n",
"#4400: 96.80%\n",
"#4401: 96.80%\n",
"#4402: 96.80%\n",
"#4403: 96.80%\n",
"#4404: 96.80%\n",
"#4405: 96.80%\n",
"#4406: 96.80%\n",
"#4407: 96.80%\n",
"#4408: 96.80%\n",
"#4409: 96.80%\n",
"#4410: 96.80%\n",
"#4411: 96.80%\n",
"#4412: 96.80%\n",
"#4413: 96.81%\n",
"#4414: 96.81%\n",
"#4415: 96.81%\n",
"#4416: 96.81%\n",
"#4417: 96.81%\n",
"#4418: 96.81%\n",
"#4419: 96.81%\n",
"#4420: 96.81%\n",
"#4421: 96.81%\n",
"#4422: 96.81%\n",
"#4423: 96.81%\n",
"#4424: 96.81%\n",
"#4425: 96.81%\n",
"#4426: 96.81%\n",
"#4427: 96.82%\n",
"#4428: 96.82%\n",
"#4429: 96.82%\n",
"#4430: 96.82%\n",
"#4431: 96.82%\n",
"#4432: 96.82%\n",
"#4433: 96.82%\n",
"#4434: 96.82%\n",
"#4435: 96.82%\n",
"#4436: 96.82%\n",
"#4437: 96.82%\n",
"#4438: 96.82%\n",
"#4439: 96.82%\n",
"#4440: 96.83%\n",
"#4441: 96.83%\n",
"#4442: 96.83%\n",
"#4443: 96.80%\n",
"#4444: 96.81%\n",
"#4445: 96.81%\n",
"#4446: 96.81%\n",
"#4447: 96.81%\n",
"#4448: 96.81%\n",
"#4449: 96.81%\n",
"#4450: 96.81%\n",
"#4451: 96.81%\n",
"#4452: 96.81%\n",
"#4453: 96.81%\n",
"#4454: 96.81%\n",
"#4455: 96.81%\n",
"#4456: 96.81%\n",
"#4457: 96.81%\n",
"#4458: 96.82%\n",
"#4459: 96.82%\n",
"#4460: 96.82%\n",
"#4461: 96.82%\n",
"#4462: 96.82%\n",
"#4463: 96.82%\n",
"#4464: 96.82%\n",
"#4465: 96.82%\n",
"#4466: 96.82%\n",
"#4467: 96.82%\n",
"#4468: 96.82%\n",
"#4469: 96.82%\n",
"#4470: 96.82%\n",
"#4471: 96.82%\n",
"#4472: 96.83%\n",
"#4473: 96.83%\n",
"#4474: 96.83%\n",
"#4475: 96.83%\n",
"#4476: 96.83%\n",
"#4477: 96.83%\n",
"#4478: 96.83%\n",
"#4479: 96.83%\n",
"#4480: 96.83%\n",
"#4481: 96.83%\n",
"#4482: 96.83%\n",
"#4483: 96.83%\n",
"#4484: 96.83%\n",
"#4485: 96.83%\n",
"#4486: 96.84%\n",
"#4487: 96.84%\n",
"#4488: 96.84%\n",
"#4489: 96.84%\n",
"#4490: 96.84%\n",
"#4491: 96.84%\n",
"#4492: 96.84%\n",
"#4493: 96.84%\n",
"#4494: 96.84%\n",
"#4495: 96.84%\n",
"#4496: 96.84%\n",
"#4497: 96.82%\n",
"#4498: 96.82%\n",
"#4499: 96.82%\n",
"#4500: 96.80%\n",
"#4501: 96.80%\n",
"#4502: 96.80%\n",
"#4503: 96.80%\n",
"#4504: 96.80%\n",
"#4505: 96.78%\n",
"#4506: 96.78%\n",
"#4507: 96.78%\n",
"#4508: 96.78%\n",
"#4509: 96.78%\n",
"#4510: 96.79%\n",
"#4511: 96.79%\n",
"#4512: 96.79%\n",
"#4513: 96.79%\n",
"#4514: 96.79%\n",
"#4515: 96.79%\n",
"#4516: 96.79%\n",
"#4517: 96.79%\n",
"#4518: 96.79%\n",
"#4519: 96.79%\n",
"#4520: 96.79%\n",
"#4521: 96.79%\n",
"#4522: 96.79%\n",
"#4523: 96.79%\n",
"#4524: 96.80%\n",
"#4525: 96.80%\n",
"#4526: 96.80%\n",
"#4527: 96.80%\n",
"#4528: 96.80%\n",
"#4529: 96.80%\n",
"#4530: 96.80%\n",
"#4531: 96.80%\n",
"#4532: 96.80%\n",
"#4533: 96.80%\n",
"#4534: 96.80%\n",
"#4535: 96.80%\n",
"#4536: 96.78%\n",
"#4537: 96.78%\n",
"#4538: 96.78%\n",
"#4539: 96.78%\n",
"#4540: 96.78%\n",
"#4541: 96.79%\n",
"#4542: 96.79%\n",
"#4543: 96.79%\n",
"#4544: 96.79%\n",
"#4545: 96.79%\n",
"#4546: 96.79%\n",
"#4547: 96.79%\n",
"#4548: 96.79%\n",
"#4549: 96.79%\n",
"#4550: 96.79%\n",
"#4551: 96.79%\n",
"#4552: 96.79%\n",
"#4553: 96.79%\n",
"#4554: 96.79%\n",
"#4555: 96.80%\n",
"#4556: 96.80%\n",
"#4557: 96.80%\n",
"#4558: 96.80%\n",
"#4559: 96.80%\n",
"#4560: 96.80%\n",
"#4561: 96.80%\n",
"#4562: 96.80%\n",
"#4563: 96.80%\n",
"#4564: 96.80%\n",
"#4565: 96.80%\n",
"#4566: 96.80%\n",
"#4567: 96.80%\n",
"#4568: 96.80%\n",
"#4569: 96.81%\n",
"#4570: 96.81%\n",
"#4571: 96.78%\n",
"#4572: 96.79%\n",
"#4573: 96.79%\n",
"#4574: 96.79%\n",
"#4575: 96.79%\n",
"#4576: 96.79%\n",
"#4577: 96.79%\n",
"#4578: 96.77%\n",
"#4579: 96.77%\n",
"#4580: 96.77%\n",
"#4581: 96.77%\n",
"#4582: 96.77%\n",
"#4583: 96.77%\n",
"#4584: 96.77%\n",
"#4585: 96.77%\n",
"#4586: 96.77%\n",
"#4587: 96.77%\n",
"#4588: 96.77%\n",
"#4589: 96.78%\n",
"#4590: 96.78%\n",
"#4591: 96.78%\n",
"#4592: 96.78%\n",
"#4593: 96.78%\n",
"#4594: 96.78%\n",
"#4595: 96.78%\n",
"#4596: 96.78%\n",
"#4597: 96.78%\n",
"#4598: 96.78%\n",
"#4599: 96.78%\n",
"#4600: 96.78%\n",
"#4601: 96.78%\n",
"#4602: 96.78%\n",
"#4603: 96.79%\n",
"#4604: 96.79%\n",
"#4605: 96.79%\n",
"#4606: 96.79%\n",
"#4607: 96.79%\n",
"#4608: 96.79%\n",
"#4609: 96.79%\n",
"#4610: 96.79%\n",
"#4611: 96.79%\n",
"#4612: 96.79%\n",
"#4613: 96.79%\n",
"#4614: 96.79%\n",
"#4615: 96.77%\n",
"#4616: 96.77%\n",
"#4617: 96.77%\n",
"#4618: 96.77%\n",
"#4619: 96.77%\n",
"#4620: 96.78%\n",
"#4621: 96.78%\n",
"#4622: 96.78%\n",
"#4623: 96.78%\n",
"#4624: 96.78%\n",
"#4625: 96.78%\n",
"#4626: 96.78%\n",
"#4627: 96.78%\n",
"#4628: 96.78%\n",
"#4629: 96.78%\n",
"#4630: 96.78%\n",
"#4631: 96.78%\n",
"#4632: 96.78%\n",
"#4633: 96.78%\n",
"#4634: 96.79%\n",
"#4635: 96.79%\n",
"#4636: 96.79%\n",
"#4637: 96.79%\n",
"#4638: 96.79%\n",
"#4639: 96.77%\n",
"#4640: 96.77%\n",
"#4641: 96.77%\n",
"#4642: 96.77%\n",
"#4643: 96.77%\n",
"#4644: 96.77%\n",
"#4645: 96.77%\n",
"#4646: 96.77%\n",
"#4647: 96.77%\n",
"#4648: 96.77%\n",
"#4649: 96.77%\n",
"#4650: 96.77%\n",
"#4651: 96.78%\n",
"#4652: 96.78%\n",
"#4653: 96.78%\n",
"#4654: 96.78%\n",
"#4655: 96.78%\n",
"#4656: 96.78%\n",
"#4657: 96.78%\n",
"#4658: 96.78%\n",
"#4659: 96.78%\n",
"#4660: 96.78%\n",
"#4661: 96.78%\n",
"#4662: 96.78%\n",
"#4663: 96.78%\n",
"#4664: 96.78%\n",
"#4665: 96.79%\n",
"#4666: 96.79%\n",
"#4667: 96.79%\n",
"#4668: 96.79%\n",
"#4669: 96.79%\n",
"#4670: 96.79%\n",
"#4671: 96.79%\n",
"#4672: 96.79%\n",
"#4673: 96.79%\n",
"#4674: 96.79%\n",
"#4675: 96.79%\n",
"#4676: 96.79%\n",
"#4677: 96.79%\n",
"#4678: 96.79%\n",
"#4679: 96.79%\n",
"#4680: 96.80%\n",
"#4681: 96.80%\n",
"#4682: 96.80%\n",
"#4683: 96.80%\n",
"#4684: 96.80%\n",
"#4685: 96.80%\n",
"#4686: 96.80%\n",
"#4687: 96.80%\n",
"#4688: 96.80%\n",
"#4689: 96.80%\n",
"#4690: 96.80%\n",
"#4691: 96.80%\n",
"#4692: 96.80%\n",
"#4693: 96.80%\n",
"#4694: 96.81%\n",
"#4695: 96.81%\n",
"#4696: 96.81%\n",
"#4697: 96.81%\n",
"#4698: 96.81%\n",
"#4699: 96.81%\n",
"#4700: 96.81%\n",
"#4701: 96.81%\n",
"#4702: 96.81%\n",
"#4703: 96.81%\n",
"#4704: 96.81%\n",
"#4705: 96.81%\n",
"#4706: 96.81%\n",
"#4707: 96.81%\n",
"#4708: 96.81%\n",
"#4709: 96.82%\n",
"#4710: 96.82%\n",
"#4711: 96.82%\n",
"#4712: 96.82%\n",
"#4713: 96.82%\n",
"#4714: 96.82%\n",
"#4715: 96.82%\n",
"#4716: 96.82%\n",
"#4717: 96.82%\n",
"#4718: 96.82%\n",
"#4719: 96.82%\n",
"#4720: 96.82%\n",
"#4721: 96.82%\n",
"#4722: 96.82%\n",
"#4723: 96.82%\n",
"#4724: 96.83%\n",
"#4725: 96.83%\n",
"#4726: 96.83%\n",
"#4727: 96.83%\n",
"#4728: 96.83%\n",
"#4729: 96.83%\n",
"#4730: 96.83%\n",
"#4731: 96.83%\n",
"#4732: 96.83%\n",
"#4733: 96.83%\n",
"#4734: 96.83%\n",
"#4735: 96.83%\n",
"#4736: 96.83%\n",
"#4737: 96.81%\n",
"#4738: 96.81%\n",
"#4739: 96.81%\n",
"#4740: 96.79%\n",
"#4741: 96.79%\n",
"#4742: 96.80%\n",
"#4743: 96.80%\n",
"#4744: 96.80%\n",
"#4745: 96.80%\n",
"#4746: 96.80%\n",
"#4747: 96.80%\n",
"#4748: 96.80%\n",
"#4749: 96.80%\n",
"#4750: 96.80%\n",
"#4751: 96.78%\n",
"#4752: 96.78%\n",
"#4753: 96.78%\n",
"#4754: 96.78%\n",
"#4755: 96.78%\n",
"#4756: 96.78%\n",
"#4757: 96.78%\n",
"#4758: 96.79%\n",
"#4759: 96.79%\n",
"#4760: 96.79%\n",
"#4761: 96.77%\n",
"#4762: 96.77%\n",
"#4763: 96.77%\n",
"#4764: 96.77%\n",
"#4765: 96.77%\n",
"#4766: 96.77%\n",
"#4767: 96.77%\n",
"#4768: 96.77%\n",
"#4769: 96.77%\n",
"#4770: 96.77%\n",
"#4771: 96.77%\n",
"#4772: 96.77%\n",
"#4773: 96.77%\n",
"#4774: 96.77%\n",
"#4775: 96.78%\n",
"#4776: 96.78%\n",
"#4777: 96.78%\n",
"#4778: 96.78%\n",
"#4779: 96.78%\n",
"#4780: 96.78%\n",
"#4781: 96.78%\n",
"#4782: 96.78%\n",
"#4783: 96.76%\n",
"#4784: 96.76%\n",
"#4785: 96.76%\n",
"#4786: 96.76%\n",
"#4787: 96.76%\n",
"#4788: 96.76%\n",
"#4789: 96.76%\n",
"#4790: 96.76%\n",
"#4791: 96.77%\n",
"#4792: 96.77%\n",
"#4793: 96.77%\n",
"#4794: 96.77%\n",
"#4795: 96.77%\n",
"#4796: 96.77%\n",
"#4797: 96.77%\n",
"#4798: 96.77%\n",
"#4799: 96.77%\n",
"#4800: 96.77%\n",
"#4801: 96.77%\n",
"#4802: 96.77%\n",
"#4803: 96.77%\n",
"#4804: 96.77%\n",
"#4805: 96.77%\n",
"#4806: 96.78%\n",
"#4807: 96.76%\n",
"#4808: 96.74%\n",
"#4809: 96.74%\n",
"#4810: 96.74%\n",
"#4811: 96.74%\n",
"#4812: 96.74%\n",
"#4813: 96.74%\n",
"#4814: 96.74%\n",
"#4815: 96.74%\n",
"#4816: 96.74%\n",
"#4817: 96.74%\n",
"#4818: 96.74%\n",
"#4819: 96.74%\n",
"#4820: 96.74%\n",
"#4821: 96.74%\n",
"#4822: 96.74%\n",
"#4823: 96.75%\n",
"#4824: 96.75%\n",
"#4825: 96.75%\n",
"#4826: 96.75%\n",
"#4827: 96.75%\n",
"#4828: 96.75%\n",
"#4829: 96.75%\n",
"#4830: 96.75%\n",
"#4831: 96.75%\n",
"#4832: 96.75%\n",
"#4833: 96.75%\n",
"#4834: 96.75%\n",
"#4835: 96.75%\n",
"#4836: 96.75%\n",
"#4837: 96.75%\n",
"#4838: 96.73%\n",
"#4839: 96.74%\n",
"#4840: 96.74%\n",
"#4841: 96.74%\n",
"#4842: 96.74%\n",
"#4843: 96.74%\n",
"#4844: 96.74%\n",
"#4845: 96.74%\n",
"#4846: 96.74%\n",
"#4847: 96.74%\n",
"#4848: 96.74%\n",
"#4849: 96.74%\n",
"#4850: 96.74%\n",
"#4851: 96.74%\n",
"#4852: 96.72%\n",
"#4853: 96.72%\n",
"#4854: 96.73%\n",
"#4855: 96.73%\n",
"#4856: 96.73%\n",
"#4857: 96.73%\n",
"#4858: 96.73%\n",
"#4859: 96.73%\n",
"#4860: 96.71%\n",
"#4861: 96.71%\n",
"#4862: 96.71%\n",
"#4863: 96.71%\n",
"#4864: 96.71%\n",
"#4865: 96.71%\n",
"#4866: 96.71%\n",
"#4867: 96.71%\n",
"#4868: 96.71%\n",
"#4869: 96.71%\n",
"#4870: 96.72%\n",
"#4871: 96.72%\n",
"#4872: 96.72%\n",
"#4873: 96.72%\n",
"#4874: 96.70%\n",
"#4875: 96.70%\n",
"#4876: 96.70%\n",
"#4877: 96.70%\n",
"#4878: 96.70%\n",
"#4879: 96.68%\n",
"#4880: 96.68%\n",
"#4881: 96.68%\n",
"#4882: 96.68%\n",
"#4883: 96.68%\n",
"#4884: 96.68%\n",
"#4885: 96.68%\n",
"#4886: 96.69%\n",
"#4887: 96.69%\n",
"#4888: 96.69%\n",
"#4889: 96.69%\n",
"#4890: 96.67%\n",
"#4891: 96.67%\n",
"#4892: 96.67%\n",
"#4893: 96.67%\n",
"#4894: 96.67%\n",
"#4895: 96.67%\n",
"#4896: 96.67%\n",
"#4897: 96.67%\n",
"#4898: 96.67%\n",
"#4899: 96.67%\n",
"#4900: 96.67%\n",
"#4901: 96.67%\n",
"#4902: 96.68%\n",
"#4903: 96.68%\n",
"#4904: 96.68%\n",
"#4905: 96.68%\n",
"#4906: 96.68%\n",
"#4907: 96.68%\n",
"#4908: 96.68%\n",
"#4909: 96.68%\n",
"#4910: 96.68%\n",
"#4911: 96.68%\n",
"#4912: 96.68%\n",
"#4913: 96.68%\n",
"#4914: 96.68%\n",
"#4915: 96.68%\n",
"#4916: 96.68%\n",
"#4917: 96.69%\n",
"#4918: 96.69%\n",
"#4919: 96.69%\n",
"#4920: 96.69%\n",
"#4921: 96.69%\n",
"#4922: 96.69%\n",
"#4923: 96.69%\n",
"#4924: 96.69%\n",
"#4925: 96.69%\n",
"#4926: 96.69%\n",
"#4927: 96.69%\n",
"#4928: 96.69%\n",
"#4929: 96.69%\n",
"#4930: 96.69%\n",
"#4931: 96.70%\n",
"#4932: 96.70%\n",
"#4933: 96.70%\n",
"#4934: 96.70%\n",
"#4935: 96.70%\n",
"#4936: 96.70%\n",
"#4937: 96.70%\n",
"#4938: 96.70%\n",
"#4939: 96.70%\n",
"#4940: 96.70%\n",
"#4941: 96.70%\n",
"#4942: 96.70%\n",
"#4943: 96.70%\n",
"#4944: 96.70%\n",
"#4945: 96.70%\n",
"#4946: 96.71%\n",
"#4947: 96.71%\n",
"#4948: 96.71%\n",
"#4949: 96.71%\n",
"#4950: 96.71%\n",
"#4951: 96.71%\n",
"#4952: 96.71%\n",
"#4953: 96.71%\n",
"#4954: 96.71%\n",
"#4955: 96.71%\n",
"#4956: 96.69%\n",
"#4957: 96.69%\n",
"#4958: 96.69%\n",
"#4959: 96.69%\n",
"#4960: 96.69%\n",
"#4961: 96.69%\n",
"#4962: 96.70%\n",
"#4963: 96.70%\n",
"#4964: 96.70%\n",
"#4965: 96.70%\n",
"#4966: 96.70%\n",
"#4967: 96.70%\n",
"#4968: 96.70%\n",
"#4969: 96.70%\n",
"#4970: 96.70%\n",
"#4971: 96.70%\n",
"#4972: 96.70%\n",
"#4973: 96.70%\n",
"#4974: 96.70%\n",
"#4975: 96.70%\n",
"#4976: 96.70%\n",
"#4977: 96.71%\n",
"#4978: 96.69%\n",
"#4979: 96.69%\n",
"#4980: 96.69%\n",
"#4981: 96.69%\n",
"#4982: 96.69%\n",
"#4983: 96.69%\n",
"#4984: 96.69%\n",
"#4985: 96.69%\n",
"#4986: 96.69%\n",
"#4987: 96.69%\n",
"#4988: 96.69%\n",
"#4989: 96.69%\n",
"#4990: 96.69%\n",
"#4991: 96.69%\n",
"#4992: 96.70%\n",
"#4993: 96.70%\n",
"#4994: 96.70%\n",
"#4995: 96.70%\n",
"#4996: 96.70%\n",
"#4997: 96.70%\n",
"#4998: 96.70%\n",
"#4999: 96.70%\n",
"#5000: 96.70%\n",
"#5001: 96.70%\n",
"#5002: 96.70%\n",
"#5003: 96.70%\n",
"#5004: 96.70%\n",
"#5005: 96.70%\n",
"#5006: 96.70%\n",
"#5007: 96.71%\n",
"#5008: 96.71%\n",
"#5009: 96.71%\n",
"#5010: 96.71%\n",
"#5011: 96.71%\n",
"#5012: 96.71%\n",
"#5013: 96.71%\n",
"#5014: 96.71%\n",
"#5015: 96.71%\n",
"#5016: 96.71%\n",
"#5017: 96.71%\n",
"#5018: 96.71%\n",
"#5019: 96.71%\n",
"#5020: 96.71%\n",
"#5021: 96.71%\n",
"#5022: 96.72%\n",
"#5023: 96.72%\n",
"#5024: 96.72%\n",
"#5025: 96.72%\n",
"#5026: 96.72%\n",
"#5027: 96.72%\n",
"#5028: 96.72%\n",
"#5029: 96.72%\n",
"#5030: 96.72%\n",
"#5031: 96.72%\n",
"#5032: 96.72%\n",
"#5033: 96.72%\n",
"#5034: 96.72%\n",
"#5035: 96.72%\n",
"#5036: 96.72%\n",
"#5037: 96.72%\n",
"#5038: 96.73%\n",
"#5039: 96.73%\n",
"#5040: 96.73%\n",
"#5041: 96.73%\n",
"#5042: 96.73%\n",
"#5043: 96.73%\n",
"#5044: 96.73%\n",
"#5045: 96.73%\n",
"#5046: 96.73%\n",
"#5047: 96.73%\n",
"#5048: 96.73%\n",
"#5049: 96.73%\n",
"#5050: 96.73%\n",
"#5051: 96.73%\n",
"#5052: 96.73%\n",
"#5053: 96.74%\n",
"#5054: 96.74%\n",
"#5055: 96.74%\n",
"#5056: 96.74%\n",
"#5057: 96.74%\n",
"#5058: 96.74%\n",
"#5059: 96.74%\n",
"#5060: 96.74%\n",
"#5061: 96.74%\n",
"#5062: 96.74%\n",
"#5063: 96.74%\n",
"#5064: 96.74%\n",
"#5065: 96.74%\n",
"#5066: 96.74%\n",
"#5067: 96.74%\n",
"#5068: 96.74%\n",
"#5069: 96.75%\n",
"#5070: 96.75%\n",
"#5071: 96.75%\n",
"#5072: 96.75%\n",
"#5073: 96.75%\n",
"#5074: 96.75%\n",
"#5075: 96.75%\n",
"#5076: 96.75%\n",
"#5077: 96.75%\n",
"#5078: 96.75%\n",
"#5079: 96.75%\n",
"#5080: 96.75%\n",
"#5081: 96.75%\n",
"#5082: 96.75%\n",
"#5083: 96.75%\n",
"#5084: 96.76%\n",
"#5085: 96.76%\n",
"#5086: 96.76%\n",
"#5087: 96.76%\n",
"#5088: 96.76%\n",
"#5089: 96.76%\n",
"#5090: 96.76%\n",
"#5091: 96.76%\n",
"#5092: 96.76%\n",
"#5093: 96.76%\n",
"#5094: 96.76%\n",
"#5095: 96.76%\n",
"#5096: 96.76%\n",
"#5097: 96.76%\n",
"#5098: 96.76%\n",
"#5099: 96.76%\n",
"#5100: 96.77%\n",
"#5101: 96.77%\n",
"#5102: 96.77%\n",
"#5103: 96.77%\n",
"#5104: 96.77%\n",
"#5105: 96.77%\n",
"#5106: 96.77%\n",
"#5107: 96.77%\n",
"#5108: 96.77%\n",
"#5109: 96.77%\n",
"#5110: 96.77%\n",
"#5111: 96.77%\n",
"#5112: 96.77%\n",
"#5113: 96.77%\n",
"#5114: 96.77%\n",
"#5115: 96.77%\n",
"#5116: 96.78%\n",
"#5117: 96.78%\n",
"#5118: 96.78%\n",
"#5119: 96.78%\n",
"#5120: 96.78%\n",
"#5121: 96.78%\n",
"#5122: 96.78%\n",
"#5123: 96.78%\n",
"#5124: 96.78%\n",
"#5125: 96.78%\n",
"#5126: 96.78%\n",
"#5127: 96.78%\n",
"#5128: 96.78%\n",
"#5129: 96.78%\n",
"#5130: 96.78%\n",
"#5131: 96.78%\n",
"#5132: 96.79%\n",
"#5133: 96.79%\n",
"#5134: 96.79%\n",
"#5135: 96.79%\n",
"#5136: 96.79%\n",
"#5137: 96.79%\n",
"#5138: 96.79%\n",
"#5139: 96.79%\n",
"#5140: 96.77%\n",
"#5141: 96.77%\n",
"#5142: 96.77%\n",
"#5143: 96.77%\n",
"#5144: 96.77%\n",
"#5145: 96.77%\n",
"#5146: 96.77%\n",
"#5147: 96.78%\n",
"#5148: 96.78%\n",
"#5149: 96.78%\n",
"#5150: 96.78%\n",
"#5151: 96.78%\n",
"#5152: 96.78%\n",
"#5153: 96.78%\n",
"#5154: 96.78%\n",
"#5155: 96.78%\n",
"#5156: 96.78%\n",
"#5157: 96.78%\n",
"#5158: 96.78%\n",
"#5159: 96.76%\n",
"#5160: 96.76%\n",
"#5161: 96.76%\n",
"#5162: 96.77%\n",
"#5163: 96.77%\n",
"#5164: 96.77%\n",
"#5165: 96.77%\n",
"#5166: 96.77%\n",
"#5167: 96.77%\n",
"#5168: 96.77%\n",
"#5169: 96.77%\n",
"#5170: 96.77%\n",
"#5171: 96.77%\n",
"#5172: 96.77%\n",
"#5173: 96.77%\n",
"#5174: 96.77%\n",
"#5175: 96.77%\n",
"#5176: 96.75%\n",
"#5177: 96.76%\n",
"#5178: 96.76%\n",
"#5179: 96.76%\n",
"#5180: 96.76%\n",
"#5181: 96.76%\n",
"#5182: 96.76%\n",
"#5183: 96.74%\n",
"#5184: 96.74%\n",
"#5185: 96.74%\n",
"#5186: 96.74%\n",
"#5187: 96.74%\n",
"#5188: 96.74%\n",
"#5189: 96.74%\n",
"#5190: 96.74%\n",
"#5191: 96.74%\n",
"#5192: 96.75%\n",
"#5193: 96.75%\n",
"#5194: 96.75%\n",
"#5195: 96.75%\n",
"#5196: 96.75%\n",
"#5197: 96.75%\n",
"#5198: 96.75%\n",
"#5199: 96.75%\n",
"#5200: 96.75%\n",
"#5201: 96.75%\n",
"#5202: 96.75%\n",
"#5203: 96.75%\n",
"#5204: 96.75%\n",
"#5205: 96.75%\n",
"#5206: 96.75%\n",
"#5207: 96.75%\n",
"#5208: 96.76%\n",
"#5209: 96.76%\n",
"#5210: 96.76%\n",
"#5211: 96.76%\n",
"#5212: 96.76%\n",
"#5213: 96.76%\n",
"#5214: 96.76%\n",
"#5215: 96.76%\n",
"#5216: 96.76%\n",
"#5217: 96.76%\n",
"#5218: 96.76%\n",
"#5219: 96.76%\n",
"#5220: 96.76%\n",
"#5221: 96.76%\n",
"#5222: 96.76%\n",
"#5223: 96.76%\n",
"#5224: 96.77%\n",
"#5225: 96.77%\n",
"#5226: 96.77%\n",
"#5227: 96.77%\n",
"#5228: 96.77%\n",
"#5229: 96.77%\n",
"#5230: 96.77%\n",
"#5231: 96.77%\n",
"#5232: 96.77%\n",
"#5233: 96.77%\n",
"#5234: 96.77%\n",
"#5235: 96.77%\n",
"#5236: 96.77%\n",
"#5237: 96.77%\n",
"#5238: 96.77%\n",
"#5239: 96.77%\n",
"#5240: 96.78%\n",
"#5241: 96.78%\n",
"#5242: 96.78%\n",
"#5243: 96.78%\n",
"#5244: 96.78%\n",
"#5245: 96.78%\n",
"#5246: 96.78%\n",
"#5247: 96.78%\n",
"#5248: 96.78%\n",
"#5249: 96.78%\n",
"#5250: 96.78%\n",
"#5251: 96.78%\n",
"#5252: 96.78%\n",
"#5253: 96.78%\n",
"#5254: 96.78%\n",
"#5255: 96.78%\n",
"#5256: 96.79%\n",
"#5257: 96.79%\n",
"#5258: 96.79%\n",
"#5259: 96.79%\n",
"#5260: 96.79%\n",
"#5261: 96.79%\n",
"#5262: 96.79%\n",
"#5263: 96.79%\n",
"#5264: 96.79%\n",
"#5265: 96.79%\n",
"#5266: 96.79%\n",
"#5267: 96.79%\n",
"#5268: 96.79%\n",
"#5269: 96.79%\n",
"#5270: 96.79%\n",
"#5271: 96.79%\n",
"#5272: 96.79%\n",
"#5273: 96.80%\n",
"#5274: 96.80%\n",
"#5275: 96.80%\n",
"#5276: 96.80%\n",
"#5277: 96.80%\n",
"#5278: 96.80%\n",
"#5279: 96.80%\n",
"#5280: 96.80%\n",
"#5281: 96.80%\n",
"#5282: 96.80%\n",
"#5283: 96.80%\n",
"#5284: 96.80%\n",
"#5285: 96.80%\n",
"#5286: 96.80%\n",
"#5287: 96.80%\n",
"#5288: 96.80%\n",
"#5289: 96.81%\n",
"#5290: 96.81%\n",
"#5291: 96.81%\n",
"#5292: 96.81%\n",
"#5293: 96.81%\n",
"#5294: 96.81%\n",
"#5295: 96.81%\n",
"#5296: 96.81%\n",
"#5297: 96.81%\n",
"#5298: 96.81%\n",
"#5299: 96.81%\n",
"#5300: 96.81%\n",
"#5301: 96.81%\n",
"#5302: 96.81%\n",
"#5303: 96.81%\n",
"#5304: 96.81%\n",
"#5305: 96.81%\n",
"#5306: 96.82%\n",
"#5307: 96.82%\n",
"#5308: 96.82%\n",
"#5309: 96.82%\n",
"#5310: 96.82%\n",
"#5311: 96.82%\n",
"#5312: 96.82%\n",
"#5313: 96.82%\n",
"#5314: 96.82%\n",
"#5315: 96.82%\n",
"#5316: 96.82%\n",
"#5317: 96.82%\n",
"#5318: 96.82%\n",
"#5319: 96.82%\n",
"#5320: 96.82%\n",
"#5321: 96.82%\n",
"#5322: 96.83%\n",
"#5323: 96.83%\n",
"#5324: 96.83%\n",
"#5325: 96.83%\n",
"#5326: 96.83%\n",
"#5327: 96.83%\n",
"#5328: 96.83%\n",
"#5329: 96.83%\n",
"#5330: 96.83%\n",
"#5331: 96.83%\n",
"#5332: 96.83%\n",
"#5333: 96.83%\n",
"#5334: 96.83%\n",
"#5335: 96.83%\n",
"#5336: 96.83%\n",
"#5337: 96.83%\n",
"#5338: 96.83%\n",
"#5339: 96.84%\n",
"#5340: 96.84%\n",
"#5341: 96.84%\n",
"#5342: 96.84%\n",
"#5343: 96.84%\n",
"#5344: 96.84%\n",
"#5345: 96.84%\n",
"#5346: 96.84%\n",
"#5347: 96.84%\n",
"#5348: 96.84%\n",
"#5349: 96.84%\n",
"#5350: 96.84%\n",
"#5351: 96.84%\n",
"#5352: 96.84%\n",
"#5353: 96.84%\n",
"#5354: 96.84%\n",
"#5355: 96.84%\n",
"#5356: 96.85%\n",
"#5357: 96.85%\n",
"#5358: 96.85%\n",
"#5359: 96.85%\n",
"#5360: 96.85%\n",
"#5361: 96.85%\n",
"#5362: 96.85%\n",
"#5363: 96.85%\n",
"#5364: 96.85%\n",
"#5365: 96.85%\n",
"#5366: 96.85%\n",
"#5367: 96.85%\n",
"#5368: 96.85%\n",
"#5369: 96.85%\n",
"#5370: 96.85%\n",
"#5371: 96.85%\n",
"#5372: 96.85%\n",
"#5373: 96.86%\n",
"#5374: 96.86%\n",
"#5375: 96.86%\n",
"#5376: 96.86%\n",
"#5377: 96.86%\n",
"#5378: 96.86%\n",
"#5379: 96.86%\n",
"#5380: 96.86%\n",
"#5381: 96.86%\n",
"#5382: 96.86%\n",
"#5383: 96.86%\n",
"#5384: 96.86%\n",
"#5385: 96.86%\n",
"#5386: 96.86%\n",
"#5387: 96.86%\n",
"#5388: 96.86%\n",
"#5389: 96.86%\n",
"#5390: 96.87%\n",
"#5391: 96.87%\n",
"#5392: 96.87%\n",
"#5393: 96.87%\n",
"#5394: 96.87%\n",
"#5395: 96.87%\n",
"#5396: 96.87%\n",
"#5397: 96.87%\n",
"#5398: 96.87%\n",
"#5399: 96.87%\n",
"#5400: 96.87%\n",
"#5401: 96.87%\n",
"#5402: 96.87%\n",
"#5403: 96.87%\n",
"#5404: 96.87%\n",
"#5405: 96.87%\n",
"#5406: 96.87%\n",
"#5407: 96.88%\n",
"#5408: 96.88%\n",
"#5409: 96.88%\n",
"#5410: 96.88%\n",
"#5411: 96.88%\n",
"#5412: 96.88%\n",
"#5413: 96.88%\n",
"#5414: 96.88%\n",
"#5415: 96.88%\n",
"#5416: 96.88%\n",
"#5417: 96.88%\n",
"#5418: 96.88%\n",
"#5419: 96.88%\n",
"#5420: 96.88%\n",
"#5421: 96.88%\n",
"#5422: 96.88%\n",
"#5423: 96.88%\n",
"#5424: 96.88%\n",
"#5425: 96.89%\n",
"#5426: 96.89%\n",
"#5427: 96.89%\n",
"#5428: 96.89%\n",
"#5429: 96.89%\n",
"#5430: 96.89%\n",
"#5431: 96.89%\n",
"#5432: 96.89%\n",
"#5433: 96.89%\n",
"#5434: 96.89%\n",
"#5435: 96.89%\n",
"#5436: 96.89%\n",
"#5437: 96.89%\n",
"#5438: 96.89%\n",
"#5439: 96.89%\n",
"#5440: 96.89%\n",
"#5441: 96.89%\n",
"#5442: 96.90%\n",
"#5443: 96.90%\n",
"#5444: 96.90%\n",
"#5445: 96.90%\n",
"#5446: 96.90%\n",
"#5447: 96.90%\n",
"#5448: 96.90%\n",
"#5449: 96.90%\n",
"#5450: 96.90%\n",
"#5451: 96.90%\n",
"#5452: 96.90%\n",
"#5453: 96.90%\n",
"#5454: 96.90%\n",
"#5455: 96.90%\n",
"#5456: 96.90%\n",
"#5457: 96.90%\n",
"#5458: 96.90%\n",
"#5459: 96.90%\n",
"#5460: 96.91%\n",
"#5461: 96.91%\n",
"#5462: 96.91%\n",
"#5463: 96.91%\n",
"#5464: 96.91%\n",
"#5465: 96.91%\n",
"#5466: 96.91%\n",
"#5467: 96.91%\n",
"#5468: 96.91%\n",
"#5469: 96.91%\n",
"#5470: 96.91%\n",
"#5471: 96.91%\n",
"#5472: 96.91%\n",
"#5473: 96.91%\n",
"#5474: 96.91%\n",
"#5475: 96.91%\n",
"#5476: 96.91%\n",
"#5477: 96.91%\n",
"#5478: 96.92%\n",
"#5479: 96.92%\n",
"#5480: 96.92%\n",
"#5481: 96.92%\n",
"#5482: 96.92%\n",
"#5483: 96.92%\n",
"#5484: 96.92%\n",
"#5485: 96.92%\n",
"#5486: 96.92%\n",
"#5487: 96.92%\n",
"#5488: 96.92%\n",
"#5489: 96.92%\n",
"#5490: 96.92%\n",
"#5491: 96.92%\n",
"#5492: 96.92%\n",
"#5493: 96.92%\n",
"#5494: 96.92%\n",
"#5495: 96.93%\n",
"#5496: 96.93%\n",
"#5497: 96.93%\n",
"#5498: 96.93%\n",
"#5499: 96.93%\n",
"#5500: 96.93%\n",
"#5501: 96.93%\n",
"#5502: 96.93%\n",
"#5503: 96.93%\n",
"#5504: 96.93%\n",
"#5505: 96.93%\n",
"#5506: 96.93%\n",
"#5507: 96.93%\n",
"#5508: 96.93%\n",
"#5509: 96.93%\n",
"#5510: 96.93%\n",
"#5511: 96.93%\n",
"#5512: 96.93%\n",
"#5513: 96.94%\n",
"#5514: 96.94%\n",
"#5515: 96.94%\n",
"#5516: 96.94%\n",
"#5517: 96.94%\n",
"#5518: 96.94%\n",
"#5519: 96.94%\n",
"#5520: 96.94%\n",
"#5521: 96.94%\n",
"#5522: 96.94%\n",
"#5523: 96.94%\n",
"#5524: 96.94%\n",
"#5525: 96.94%\n",
"#5526: 96.94%\n",
"#5527: 96.94%\n",
"#5528: 96.94%\n",
"#5529: 96.94%\n",
"#5530: 96.94%\n",
"#5531: 96.95%\n",
"#5532: 96.95%\n",
"#5533: 96.95%\n",
"#5534: 96.95%\n",
"#5535: 96.95%\n",
"#5536: 96.95%\n",
"#5537: 96.95%\n",
"#5538: 96.95%\n",
"#5539: 96.95%\n",
"#5540: 96.95%\n",
"#5541: 96.95%\n",
"#5542: 96.95%\n",
"#5543: 96.95%\n",
"#5544: 96.95%\n",
"#5545: 96.95%\n",
"#5546: 96.95%\n",
"#5547: 96.95%\n",
"#5548: 96.95%\n",
"#5549: 96.95%\n",
"#5550: 96.96%\n",
"#5551: 96.96%\n",
"#5552: 96.96%\n",
"#5553: 96.96%\n",
"#5554: 96.96%\n",
"#5555: 96.96%\n",
"#5556: 96.96%\n",
"#5557: 96.96%\n",
"#5558: 96.96%\n",
"#5559: 96.96%\n",
"#5560: 96.96%\n",
"#5561: 96.96%\n",
"#5562: 96.96%\n",
"#5563: 96.96%\n",
"#5564: 96.96%\n",
"#5565: 96.96%\n",
"#5566: 96.96%\n",
"#5567: 96.96%\n",
"#5568: 96.97%\n",
"#5569: 96.97%\n",
"#5570: 96.97%\n",
"#5571: 96.97%\n",
"#5572: 96.97%\n",
"#5573: 96.97%\n",
"#5574: 96.97%\n",
"#5575: 96.97%\n",
"#5576: 96.97%\n",
"#5577: 96.97%\n",
"#5578: 96.97%\n",
"#5579: 96.97%\n",
"#5580: 96.97%\n",
"#5581: 96.97%\n",
"#5582: 96.97%\n",
"#5583: 96.97%\n",
"#5584: 96.97%\n",
"#5585: 96.97%\n",
"#5586: 96.98%\n",
"#5587: 96.98%\n",
"#5588: 96.98%\n",
"#5589: 96.98%\n",
"#5590: 96.98%\n",
"#5591: 96.98%\n",
"#5592: 96.98%\n",
"#5593: 96.98%\n",
"#5594: 96.98%\n",
"#5595: 96.98%\n",
"#5596: 96.98%\n",
"#5597: 96.98%\n",
"#5598: 96.98%\n",
"#5599: 96.98%\n",
"#5600: 96.96%\n",
"#5601: 96.97%\n",
"#5602: 96.97%\n",
"#5603: 96.97%\n",
"#5604: 96.97%\n",
"#5605: 96.97%\n",
"#5606: 96.97%\n",
"#5607: 96.97%\n",
"#5608: 96.97%\n",
"#5609: 96.97%\n",
"#5610: 96.97%\n",
"#5611: 96.97%\n",
"#5612: 96.97%\n",
"#5613: 96.97%\n",
"#5614: 96.97%\n",
"#5615: 96.97%\n",
"#5616: 96.97%\n",
"#5617: 96.97%\n",
"#5618: 96.97%\n",
"#5619: 96.98%\n",
"#5620: 96.98%\n",
"#5621: 96.98%\n",
"#5622: 96.98%\n",
"#5623: 96.98%\n",
"#5624: 96.98%\n",
"#5625: 96.98%\n",
"#5626: 96.98%\n",
"#5627: 96.98%\n",
"#5628: 96.98%\n",
"#5629: 96.98%\n",
"#5630: 96.98%\n",
"#5631: 96.98%\n",
"#5632: 96.98%\n",
"#5633: 96.98%\n",
"#5634: 96.98%\n",
"#5635: 96.98%\n",
"#5636: 96.98%\n",
"#5637: 96.98%\n",
"#5638: 96.99%\n",
"#5639: 96.99%\n",
"#5640: 96.99%\n",
"#5641: 96.99%\n",
"#5642: 96.99%\n",
"#5643: 96.99%\n",
"#5644: 96.99%\n",
"#5645: 96.99%\n",
"#5646: 96.99%\n",
"#5647: 96.99%\n",
"#5648: 96.99%\n",
"#5649: 96.99%\n",
"#5650: 96.99%\n",
"#5651: 96.99%\n",
"#5652: 96.99%\n",
"#5653: 96.99%\n",
"#5654: 96.99%\n",
"#5655: 96.99%\n",
"#5656: 96.99%\n",
"#5657: 97.00%\n",
"#5658: 97.00%\n",
"#5659: 97.00%\n",
"#5660: 97.00%\n",
"#5661: 97.00%\n",
"#5662: 97.00%\n",
"#5663: 97.00%\n",
"#5664: 97.00%\n",
"#5665: 97.00%\n",
"#5666: 97.00%\n",
"#5667: 97.00%\n",
"#5668: 97.00%\n",
"#5669: 97.00%\n",
"#5670: 97.00%\n",
"#5671: 97.00%\n",
"#5672: 97.00%\n",
"#5673: 97.00%\n",
"#5674: 97.00%\n",
"#5675: 97.00%\n",
"#5676: 97.01%\n",
"#5677: 97.01%\n",
"#5678: 97.01%\n",
"#5679: 97.01%\n",
"#5680: 97.01%\n",
"#5681: 97.01%\n",
"#5682: 97.01%\n",
"#5683: 97.01%\n",
"#5684: 97.01%\n",
"#5685: 97.01%\n",
"#5686: 97.01%\n",
"#5687: 97.01%\n",
"#5688: 97.01%\n",
"#5689: 97.01%\n",
"#5690: 97.01%\n",
"#5691: 97.01%\n",
"#5692: 97.01%\n",
"#5693: 97.01%\n",
"#5694: 97.01%\n",
"#5695: 97.02%\n",
"#5696: 97.02%\n",
"#5697: 97.02%\n",
"#5698: 97.02%\n",
"#5699: 97.02%\n",
"#5700: 97.02%\n",
"#5701: 97.02%\n",
"#5702: 97.02%\n",
"#5703: 97.02%\n",
"#5704: 97.02%\n",
"#5705: 97.02%\n",
"#5706: 97.02%\n",
"#5707: 97.02%\n",
"#5708: 97.02%\n",
"#5709: 97.02%\n",
"#5710: 97.02%\n",
"#5711: 97.02%\n",
"#5712: 97.02%\n",
"#5713: 97.02%\n",
"#5714: 97.03%\n",
"#5715: 97.03%\n",
"#5716: 97.03%\n",
"#5717: 97.03%\n",
"#5718: 97.03%\n",
"#5719: 97.03%\n",
"#5720: 97.03%\n",
"#5721: 97.03%\n",
"#5722: 97.03%\n",
"#5723: 97.03%\n",
"#5724: 97.03%\n",
"#5725: 97.03%\n",
"#5726: 97.03%\n",
"#5727: 97.03%\n",
"#5728: 97.03%\n",
"#5729: 97.03%\n",
"#5730: 97.03%\n",
"#5731: 97.03%\n",
"#5732: 97.03%\n",
"#5733: 97.04%\n",
"#5734: 97.02%\n",
"#5735: 97.02%\n",
"#5736: 97.02%\n",
"#5737: 97.02%\n",
"#5738: 97.02%\n",
"#5739: 97.02%\n",
"#5740: 97.02%\n",
"#5741: 97.02%\n",
"#5742: 97.02%\n",
"#5743: 97.02%\n",
"#5744: 97.02%\n",
"#5745: 97.02%\n",
"#5746: 97.02%\n",
"#5747: 97.03%\n",
"#5748: 97.03%\n",
"#5749: 97.03%\n",
"#5750: 97.03%\n",
"#5751: 97.03%\n",
"#5752: 97.03%\n",
"#5753: 97.03%\n",
"#5754: 97.03%\n",
"#5755: 97.03%\n",
"#5756: 97.03%\n",
"#5757: 97.03%\n",
"#5758: 97.03%\n",
"#5759: 97.03%\n",
"#5760: 97.03%\n",
"#5761: 97.03%\n",
"#5762: 97.03%\n",
"#5763: 97.03%\n",
"#5764: 97.03%\n",
"#5765: 97.03%\n",
"#5766: 97.03%\n",
"#5767: 97.04%\n",
"#5768: 97.04%\n",
"#5769: 97.04%\n",
"#5770: 97.04%\n",
"#5771: 97.04%\n",
"#5772: 97.04%\n",
"#5773: 97.04%\n",
"#5774: 97.04%\n",
"#5775: 97.04%\n",
"#5776: 97.04%\n",
"#5777: 97.04%\n",
"#5778: 97.04%\n",
"#5779: 97.04%\n",
"#5780: 97.04%\n",
"#5781: 97.04%\n",
"#5782: 97.04%\n",
"#5783: 97.04%\n",
"#5784: 97.04%\n",
"#5785: 97.04%\n",
"#5786: 97.05%\n",
"#5787: 97.05%\n",
"#5788: 97.05%\n",
"#5789: 97.05%\n",
"#5790: 97.05%\n",
"#5791: 97.05%\n",
"#5792: 97.05%\n",
"#5793: 97.05%\n",
"#5794: 97.05%\n",
"#5795: 97.05%\n",
"#5796: 97.05%\n",
"#5797: 97.05%\n",
"#5798: 97.05%\n",
"#5799: 97.05%\n",
"#5800: 97.05%\n",
"#5801: 97.05%\n",
"#5802: 97.05%\n",
"#5803: 97.05%\n",
"#5804: 97.05%\n",
"#5805: 97.05%\n",
"#5806: 97.06%\n",
"#5807: 97.06%\n",
"#5808: 97.06%\n",
"#5809: 97.06%\n",
"#5810: 97.06%\n",
"#5811: 97.06%\n",
"#5812: 97.06%\n",
"#5813: 97.06%\n",
"#5814: 97.06%\n",
"#5815: 97.06%\n",
"#5816: 97.06%\n",
"#5817: 97.06%\n",
"#5818: 97.06%\n",
"#5819: 97.06%\n",
"#5820: 97.06%\n",
"#5821: 97.06%\n",
"#5822: 97.06%\n",
"#5823: 97.06%\n",
"#5824: 97.06%\n",
"#5825: 97.06%\n",
"#5826: 97.07%\n",
"#5827: 97.07%\n",
"#5828: 97.07%\n",
"#5829: 97.07%\n",
"#5830: 97.07%\n",
"#5831: 97.07%\n",
"#5832: 97.07%\n",
"#5833: 97.07%\n",
"#5834: 97.07%\n",
"#5835: 97.07%\n",
"#5836: 97.07%\n",
"#5837: 97.07%\n",
"#5838: 97.07%\n",
"#5839: 97.07%\n",
"#5840: 97.07%\n",
"#5841: 97.06%\n",
"#5842: 97.04%\n",
"#5843: 97.04%\n",
"#5844: 97.04%\n",
"#5845: 97.04%\n",
"#5846: 97.04%\n",
"#5847: 97.04%\n",
"#5848: 97.04%\n",
"#5849: 97.04%\n",
"#5850: 97.04%\n",
"#5851: 97.04%\n",
"#5852: 97.04%\n",
"#5853: 97.04%\n",
"#5854: 97.05%\n",
"#5855: 97.05%\n",
"#5856: 97.05%\n",
"#5857: 97.05%\n",
"#5858: 97.05%\n",
"#5859: 97.05%\n",
"#5860: 97.05%\n",
"#5861: 97.05%\n",
"#5862: 97.05%\n",
"#5863: 97.05%\n",
"#5864: 97.05%\n",
"#5865: 97.05%\n",
"#5866: 97.05%\n",
"#5867: 97.05%\n",
"#5868: 97.05%\n",
"#5869: 97.05%\n",
"#5870: 97.05%\n",
"#5871: 97.05%\n",
"#5872: 97.05%\n",
"#5873: 97.05%\n",
"#5874: 97.06%\n",
"#5875: 97.06%\n",
"#5876: 97.06%\n",
"#5877: 97.06%\n",
"#5878: 97.06%\n",
"#5879: 97.06%\n",
"#5880: 97.06%\n",
"#5881: 97.06%\n",
"#5882: 97.06%\n",
"#5883: 97.06%\n",
"#5884: 97.06%\n",
"#5885: 97.06%\n",
"#5886: 97.06%\n",
"#5887: 97.04%\n",
"#5888: 97.05%\n",
"#5889: 97.05%\n",
"#5890: 97.05%\n",
"#5891: 97.05%\n",
"#5892: 97.05%\n",
"#5893: 97.05%\n",
"#5894: 97.05%\n",
"#5895: 97.05%\n",
"#5896: 97.05%\n",
"#5897: 97.05%\n",
"#5898: 97.05%\n",
"#5899: 97.05%\n",
"#5900: 97.05%\n",
"#5901: 97.05%\n",
"#5902: 97.05%\n",
"#5903: 97.05%\n",
"#5904: 97.05%\n",
"#5905: 97.05%\n",
"#5906: 97.05%\n",
"#5907: 97.05%\n",
"#5908: 97.06%\n",
"#5909: 97.06%\n",
"#5910: 97.06%\n",
"#5911: 97.06%\n",
"#5912: 97.06%\n",
"#5913: 97.06%\n",
"#5914: 97.06%\n",
"#5915: 97.06%\n",
"#5916: 97.06%\n",
"#5917: 97.06%\n",
"#5918: 97.06%\n",
"#5919: 97.06%\n",
"#5920: 97.06%\n",
"#5921: 97.06%\n",
"#5922: 97.06%\n",
"#5923: 97.06%\n",
"#5924: 97.06%\n",
"#5925: 97.06%\n",
"#5926: 97.06%\n",
"#5927: 97.06%\n",
"#5928: 97.07%\n",
"#5929: 97.07%\n",
"#5930: 97.07%\n",
"#5931: 97.07%\n",
"#5932: 97.07%\n",
"#5933: 97.07%\n",
"#5934: 97.07%\n",
"#5935: 97.07%\n",
"#5936: 97.07%\n",
"#5937: 97.07%\n",
"#5938: 97.07%\n",
"#5939: 97.07%\n",
"#5940: 97.07%\n",
"#5941: 97.07%\n",
"#5942: 97.07%\n",
"#5943: 97.07%\n",
"#5944: 97.07%\n",
"#5945: 97.07%\n",
"#5946: 97.07%\n",
"#5947: 97.07%\n",
"#5948: 97.08%\n",
"#5949: 97.08%\n",
"#5950: 97.08%\n",
"#5951: 97.08%\n",
"#5952: 97.08%\n",
"#5953: 97.08%\n",
"#5954: 97.08%\n",
"#5955: 97.06%\n",
"#5956: 97.06%\n",
"#5957: 97.06%\n",
"#5958: 97.06%\n",
"#5959: 97.06%\n",
"#5960: 97.06%\n",
"#5961: 97.06%\n",
"#5962: 97.07%\n",
"#5963: 97.07%\n",
"#5964: 97.07%\n",
"#5965: 97.07%\n",
"#5966: 97.07%\n",
"#5967: 97.07%\n",
"#5968: 97.07%\n",
"#5969: 97.07%\n",
"#5970: 97.07%\n",
"#5971: 97.07%\n",
"#5972: 97.07%\n",
"#5973: 97.05%\n",
"#5974: 97.05%\n",
"#5975: 97.05%\n",
"#5976: 97.06%\n",
"#5977: 97.06%\n",
"#5978: 97.06%\n",
"#5979: 97.06%\n",
"#5980: 97.06%\n",
"#5981: 97.06%\n",
"#5982: 97.06%\n",
"#5983: 97.06%\n",
"#5984: 97.06%\n",
"#5985: 97.06%\n",
"#5986: 97.06%\n",
"#5987: 97.06%\n",
"#5988: 97.06%\n",
"#5989: 97.06%\n",
"#5990: 97.06%\n",
"#5991: 97.06%\n",
"#5992: 97.06%\n",
"#5993: 97.06%\n",
"#5994: 97.06%\n",
"#5995: 97.06%\n",
"#5996: 97.07%\n",
"#5997: 97.05%\n",
"#5998: 97.05%\n",
"#5999: 97.05%\n",
"#6000: 97.05%\n",
"#6001: 97.05%\n",
"#6002: 97.05%\n",
"#6003: 97.05%\n",
"#6004: 97.05%\n",
"#6005: 97.05%\n",
"#6006: 97.05%\n",
"#6007: 97.05%\n",
"#6008: 97.05%\n",
"#6009: 97.05%\n",
"#6010: 97.06%\n",
"#6011: 97.06%\n",
"#6012: 97.06%\n",
"#6013: 97.06%\n",
"#6014: 97.06%\n",
"#6015: 97.06%\n",
"#6016: 97.06%\n",
"#6017: 97.06%\n",
"#6018: 97.06%\n",
"#6019: 97.06%\n",
"#6020: 97.06%\n",
"#6021: 97.06%\n",
"#6022: 97.06%\n",
"#6023: 97.05%\n",
"#6024: 97.05%\n",
"#6025: 97.05%\n",
"#6026: 97.05%\n",
"#6027: 97.05%\n",
"#6028: 97.05%\n",
"#6029: 97.05%\n",
"#6030: 97.05%\n",
"#6031: 97.05%\n",
"#6032: 97.05%\n",
"#6033: 97.05%\n",
"#6034: 97.05%\n",
"#6035: 97.05%\n",
"#6036: 97.05%\n",
"#6037: 97.05%\n",
"#6038: 97.05%\n",
"#6039: 97.05%\n",
"#6040: 97.05%\n",
"#6041: 97.05%\n",
"#6042: 97.05%\n",
"#6043: 97.05%\n",
"#6044: 97.06%\n",
"#6045: 97.06%\n",
"#6046: 97.06%\n",
"#6047: 97.06%\n",
"#6048: 97.06%\n",
"#6049: 97.06%\n",
"#6050: 97.06%\n",
"#6051: 97.06%\n",
"#6052: 97.06%\n",
"#6053: 97.06%\n",
"#6054: 97.06%\n",
"#6055: 97.06%\n",
"#6056: 97.06%\n",
"#6057: 97.06%\n",
"#6058: 97.06%\n",
"#6059: 97.05%\n",
"#6060: 97.05%\n",
"#6061: 97.05%\n",
"#6062: 97.05%\n",
"#6063: 97.05%\n",
"#6064: 97.05%\n",
"#6065: 97.03%\n",
"#6066: 97.03%\n",
"#6067: 97.03%\n",
"#6068: 97.03%\n",
"#6069: 97.03%\n",
"#6070: 97.04%\n",
"#6071: 97.04%\n",
"#6072: 97.04%\n",
"#6073: 97.04%\n",
"#6074: 97.04%\n",
"#6075: 97.04%\n",
"#6076: 97.04%\n",
"#6077: 97.04%\n",
"#6078: 97.04%\n",
"#6079: 97.04%\n",
"#6080: 97.04%\n",
"#6081: 97.04%\n",
"#6082: 97.04%\n",
"#6083: 97.04%\n",
"#6084: 97.04%\n",
"#6085: 97.03%\n",
"#6086: 97.03%\n",
"#6087: 97.03%\n",
"#6088: 97.03%\n",
"#6089: 97.03%\n",
"#6090: 97.03%\n",
"#6091: 97.01%\n",
"#6092: 97.01%\n",
"#6093: 97.01%\n",
"#6094: 97.01%\n",
"#6095: 97.01%\n",
"#6096: 97.01%\n",
"#6097: 97.02%\n",
"#6098: 97.02%\n",
"#6099: 97.02%\n",
"#6100: 97.02%\n",
"#6101: 97.02%\n",
"#6102: 97.02%\n",
"#6103: 97.02%\n",
"#6104: 97.02%\n",
"#6105: 97.02%\n",
"#6106: 97.02%\n",
"#6107: 97.02%\n",
"#6108: 97.02%\n",
"#6109: 97.02%\n",
"#6110: 97.02%\n",
"#6111: 97.02%\n",
"#6112: 97.02%\n",
"#6113: 97.02%\n",
"#6114: 97.02%\n",
"#6115: 97.02%\n",
"#6116: 97.02%\n",
"#6117: 97.03%\n",
"#6118: 97.03%\n",
"#6119: 97.03%\n",
"#6120: 97.03%\n",
"#6121: 97.03%\n",
"#6122: 97.03%\n",
"#6123: 97.03%\n",
"#6124: 97.03%\n",
"#6125: 97.03%\n",
"#6126: 97.03%\n",
"#6127: 97.03%\n",
"#6128: 97.03%\n",
"#6129: 97.03%\n",
"#6130: 97.03%\n",
"#6131: 97.03%\n",
"#6132: 97.03%\n",
"#6133: 97.03%\n",
"#6134: 97.03%\n",
"#6135: 97.03%\n",
"#6136: 97.03%\n",
"#6137: 97.03%\n",
"#6138: 97.04%\n",
"#6139: 97.04%\n",
"#6140: 97.04%\n",
"#6141: 97.04%\n",
"#6142: 97.04%\n",
"#6143: 97.04%\n",
"#6144: 97.04%\n",
"#6145: 97.04%\n",
"#6146: 97.04%\n",
"#6147: 97.04%\n",
"#6148: 97.04%\n",
"#6149: 97.04%\n",
"#6150: 97.04%\n",
"#6151: 97.04%\n",
"#6152: 97.04%\n",
"#6153: 97.04%\n",
"#6154: 97.04%\n",
"#6155: 97.04%\n",
"#6156: 97.04%\n",
"#6157: 97.04%\n",
"#6158: 97.04%\n",
"#6159: 97.05%\n",
"#6160: 97.05%\n",
"#6161: 97.05%\n",
"#6162: 97.05%\n",
"#6163: 97.05%\n",
"#6164: 97.05%\n",
"#6165: 97.05%\n",
"#6166: 97.05%\n",
"#6167: 97.05%\n",
"#6168: 97.05%\n",
"#6169: 97.05%\n",
"#6170: 97.05%\n",
"#6171: 97.05%\n",
"#6172: 97.04%\n",
"#6173: 97.04%\n",
"#6174: 97.04%\n",
"#6175: 97.04%\n",
"#6176: 97.04%\n",
"#6177: 97.04%\n",
"#6178: 97.04%\n",
"#6179: 97.04%\n",
"#6180: 97.04%\n",
"#6181: 97.04%\n",
"#6182: 97.04%\n",
"#6183: 97.04%\n",
"#6184: 97.04%\n",
"#6185: 97.04%\n",
"#6186: 97.04%\n",
"#6187: 97.04%\n",
"#6188: 97.04%\n",
"#6189: 97.04%\n",
"#6190: 97.04%\n",
"#6191: 97.04%\n",
"#6192: 97.05%\n",
"#6193: 97.05%\n",
"#6194: 97.05%\n",
"#6195: 97.05%\n",
"#6196: 97.05%\n",
"#6197: 97.05%\n",
"#6198: 97.05%\n",
"#6199: 97.05%\n",
"#6200: 97.05%\n",
"#6201: 97.05%\n",
"#6202: 97.05%\n",
"#6203: 97.05%\n",
"#6204: 97.05%\n",
"#6205: 97.05%\n",
"#6206: 97.05%\n",
"#6207: 97.05%\n",
"#6208: 97.05%\n",
"#6209: 97.05%\n",
"#6210: 97.05%\n",
"#6211: 97.05%\n",
"#6212: 97.05%\n",
"#6213: 97.06%\n",
"#6214: 97.06%\n",
"#6215: 97.06%\n",
"#6216: 97.06%\n",
"#6217: 97.06%\n",
"#6218: 97.06%\n",
"#6219: 97.06%\n",
"#6220: 97.06%\n",
"#6221: 97.06%\n",
"#6222: 97.06%\n",
"#6223: 97.06%\n",
"#6224: 97.06%\n",
"#6225: 97.06%\n",
"#6226: 97.06%\n",
"#6227: 97.06%\n",
"#6228: 97.06%\n",
"#6229: 97.06%\n",
"#6230: 97.06%\n",
"#6231: 97.06%\n",
"#6232: 97.06%\n",
"#6233: 97.06%\n",
"#6234: 97.06%\n",
"#6235: 97.07%\n",
"#6236: 97.07%\n",
"#6237: 97.07%\n",
"#6238: 97.07%\n",
"#6239: 97.07%\n",
"#6240: 97.07%\n",
"#6241: 97.07%\n",
"#6242: 97.07%\n",
"#6243: 97.07%\n",
"#6244: 97.07%\n",
"#6245: 97.07%\n",
"#6246: 97.07%\n",
"#6247: 97.07%\n",
"#6248: 97.07%\n",
"#6249: 97.07%\n",
"#6250: 97.07%\n",
"#6251: 97.07%\n",
"#6252: 97.07%\n",
"#6253: 97.07%\n",
"#6254: 97.07%\n",
"#6255: 97.07%\n",
"#6256: 97.08%\n",
"#6257: 97.08%\n",
"#6258: 97.08%\n",
"#6259: 97.08%\n",
"#6260: 97.08%\n",
"#6261: 97.08%\n",
"#6262: 97.08%\n",
"#6263: 97.08%\n",
"#6264: 97.08%\n",
"#6265: 97.08%\n",
"#6266: 97.08%\n",
"#6267: 97.08%\n",
"#6268: 97.08%\n",
"#6269: 97.08%\n",
"#6270: 97.08%\n",
"#6271: 97.08%\n",
"#6272: 97.08%\n",
"#6273: 97.08%\n",
"#6274: 97.08%\n",
"#6275: 97.08%\n",
"#6276: 97.08%\n",
"#6277: 97.09%\n",
"#6278: 97.09%\n",
"#6279: 97.09%\n",
"#6280: 97.09%\n",
"#6281: 97.09%\n",
"#6282: 97.09%\n",
"#6283: 97.09%\n",
"#6284: 97.09%\n",
"#6285: 97.09%\n",
"#6286: 97.09%\n",
"#6287: 97.09%\n",
"#6288: 97.09%\n",
"#6289: 97.09%\n",
"#6290: 97.09%\n",
"#6291: 97.09%\n",
"#6292: 97.09%\n",
"#6293: 97.09%\n",
"#6294: 97.09%\n",
"#6295: 97.09%\n",
"#6296: 97.09%\n",
"#6297: 97.09%\n",
"#6298: 97.09%\n",
"#6299: 97.10%\n",
"#6300: 97.10%\n",
"#6301: 97.10%\n",
"#6302: 97.10%\n",
"#6303: 97.10%\n",
"#6304: 97.10%\n",
"#6305: 97.10%\n",
"#6306: 97.10%\n",
"#6307: 97.10%\n",
"#6308: 97.10%\n",
"#6309: 97.10%\n",
"#6310: 97.10%\n",
"#6311: 97.10%\n",
"#6312: 97.10%\n",
"#6313: 97.10%\n",
"#6314: 97.10%\n",
"#6315: 97.10%\n",
"#6316: 97.10%\n",
"#6317: 97.10%\n",
"#6318: 97.10%\n",
"#6319: 97.10%\n",
"#6320: 97.10%\n",
"#6321: 97.11%\n",
"#6322: 97.11%\n",
"#6323: 97.11%\n",
"#6324: 97.11%\n",
"#6325: 97.11%\n",
"#6326: 97.11%\n",
"#6327: 97.11%\n",
"#6328: 97.11%\n",
"#6329: 97.11%\n",
"#6330: 97.11%\n",
"#6331: 97.11%\n",
"#6332: 97.11%\n",
"#6333: 97.11%\n",
"#6334: 97.11%\n",
"#6335: 97.11%\n",
"#6336: 97.11%\n",
"#6337: 97.11%\n",
"#6338: 97.11%\n",
"#6339: 97.11%\n",
"#6340: 97.11%\n",
"#6341: 97.11%\n",
"#6342: 97.11%\n",
"#6343: 97.12%\n",
"#6344: 97.12%\n",
"#6345: 97.12%\n",
"#6346: 97.12%\n",
"#6347: 97.12%\n",
"#6348: 97.12%\n",
"#6349: 97.12%\n",
"#6350: 97.12%\n",
"#6351: 97.12%\n",
"#6352: 97.12%\n",
"#6353: 97.12%\n",
"#6354: 97.12%\n",
"#6355: 97.12%\n",
"#6356: 97.12%\n",
"#6357: 97.12%\n",
"#6358: 97.12%\n",
"#6359: 97.12%\n",
"#6360: 97.12%\n",
"#6361: 97.12%\n",
"#6362: 97.12%\n",
"#6363: 97.12%\n",
"#6364: 97.12%\n",
"#6365: 97.13%\n",
"#6366: 97.13%\n",
"#6367: 97.13%\n",
"#6368: 97.13%\n",
"#6369: 97.13%\n",
"#6370: 97.13%\n",
"#6371: 97.13%\n",
"#6372: 97.13%\n",
"#6373: 97.13%\n",
"#6374: 97.13%\n",
"#6375: 97.13%\n",
"#6376: 97.13%\n",
"#6377: 97.13%\n",
"#6378: 97.13%\n",
"#6379: 97.13%\n",
"#6380: 97.13%\n",
"#6381: 97.13%\n",
"#6382: 97.13%\n",
"#6383: 97.13%\n",
"#6384: 97.13%\n",
"#6385: 97.13%\n",
"#6386: 97.13%\n",
"#6387: 97.14%\n",
"#6388: 97.14%\n",
"#6389: 97.14%\n",
"#6390: 97.14%\n",
"#6391: 97.14%\n",
"#6392: 97.14%\n",
"#6393: 97.14%\n",
"#6394: 97.14%\n",
"#6395: 97.14%\n",
"#6396: 97.14%\n",
"#6397: 97.14%\n",
"#6398: 97.14%\n",
"#6399: 97.14%\n",
"#6400: 97.14%\n",
"#6401: 97.14%\n",
"#6402: 97.14%\n",
"#6403: 97.14%\n",
"#6404: 97.14%\n",
"#6405: 97.14%\n",
"#6406: 97.14%\n",
"#6407: 97.14%\n",
"#6408: 97.14%\n",
"#6409: 97.15%\n",
"#6410: 97.15%\n",
"#6411: 97.15%\n",
"#6412: 97.15%\n",
"#6413: 97.15%\n",
"#6414: 97.15%\n",
"#6415: 97.15%\n",
"#6416: 97.15%\n",
"#6417: 97.15%\n",
"#6418: 97.15%\n",
"#6419: 97.15%\n",
"#6420: 97.15%\n",
"#6421: 97.15%\n",
"#6422: 97.15%\n",
"#6423: 97.15%\n",
"#6424: 97.15%\n",
"#6425: 97.15%\n",
"#6426: 97.15%\n",
"#6427: 97.15%\n",
"#6428: 97.15%\n",
"#6429: 97.15%\n",
"#6430: 97.15%\n",
"#6431: 97.15%\n",
"#6432: 97.16%\n",
"#6433: 97.16%\n",
"#6434: 97.16%\n",
"#6435: 97.16%\n",
"#6436: 97.16%\n",
"#6437: 97.16%\n",
"#6438: 97.16%\n",
"#6439: 97.16%\n",
"#6440: 97.16%\n",
"#6441: 97.16%\n",
"#6442: 97.16%\n",
"#6443: 97.16%\n",
"#6444: 97.16%\n",
"#6445: 97.16%\n",
"#6446: 97.16%\n",
"#6447: 97.16%\n",
"#6448: 97.16%\n",
"#6449: 97.16%\n",
"#6450: 97.16%\n",
"#6451: 97.16%\n",
"#6452: 97.16%\n",
"#6453: 97.16%\n",
"#6454: 97.16%\n",
"#6455: 97.17%\n",
"#6456: 97.17%\n",
"#6457: 97.17%\n",
"#6458: 97.17%\n",
"#6459: 97.17%\n",
"#6460: 97.17%\n",
"#6461: 97.17%\n",
"#6462: 97.17%\n",
"#6463: 97.17%\n",
"#6464: 97.17%\n",
"#6465: 97.17%\n",
"#6466: 97.17%\n",
"#6467: 97.17%\n",
"#6468: 97.17%\n",
"#6469: 97.17%\n",
"#6470: 97.17%\n",
"#6471: 97.17%\n",
"#6472: 97.17%\n",
"#6473: 97.17%\n",
"#6474: 97.17%\n",
"#6475: 97.17%\n",
"#6476: 97.17%\n",
"#6477: 97.18%\n",
"#6478: 97.18%\n",
"#6479: 97.18%\n",
"#6480: 97.18%\n",
"#6481: 97.18%\n",
"#6482: 97.18%\n",
"#6483: 97.18%\n",
"#6484: 97.18%\n",
"#6485: 97.18%\n",
"#6486: 97.18%\n",
"#6487: 97.18%\n",
"#6488: 97.18%\n",
"#6489: 97.18%\n",
"#6490: 97.18%\n",
"#6491: 97.18%\n",
"#6492: 97.18%\n",
"#6493: 97.18%\n",
"#6494: 97.18%\n",
"#6495: 97.18%\n",
"#6496: 97.18%\n",
"#6497: 97.18%\n",
"#6498: 97.18%\n",
"#6499: 97.18%\n",
"#6500: 97.19%\n",
"#6501: 97.19%\n",
"#6502: 97.19%\n",
"#6503: 97.19%\n",
"#6504: 97.19%\n",
"#6505: 97.17%\n",
"#6506: 97.17%\n",
"#6507: 97.17%\n",
"#6508: 97.17%\n",
"#6509: 97.17%\n",
"#6510: 97.17%\n",
"#6511: 97.17%\n",
"#6512: 97.17%\n",
"#6513: 97.18%\n",
"#6514: 97.18%\n",
"#6515: 97.18%\n",
"#6516: 97.18%\n",
"#6517: 97.18%\n",
"#6518: 97.18%\n",
"#6519: 97.18%\n",
"#6520: 97.18%\n",
"#6521: 97.18%\n",
"#6522: 97.18%\n",
"#6523: 97.18%\n",
"#6524: 97.18%\n",
"#6525: 97.18%\n",
"#6526: 97.18%\n",
"#6527: 97.18%\n",
"#6528: 97.18%\n",
"#6529: 97.18%\n",
"#6530: 97.18%\n",
"#6531: 97.18%\n",
"#6532: 97.18%\n",
"#6533: 97.18%\n",
"#6534: 97.18%\n",
"#6535: 97.18%\n",
"#6536: 97.19%\n",
"#6537: 97.19%\n",
"#6538: 97.19%\n",
"#6539: 97.19%\n",
"#6540: 97.19%\n",
"#6541: 97.19%\n",
"#6542: 97.19%\n",
"#6543: 97.19%\n",
"#6544: 97.19%\n",
"#6545: 97.19%\n",
"#6546: 97.19%\n",
"#6547: 97.19%\n",
"#6548: 97.19%\n",
"#6549: 97.19%\n",
"#6550: 97.19%\n",
"#6551: 97.19%\n",
"#6552: 97.19%\n",
"#6553: 97.19%\n",
"#6554: 97.19%\n",
"#6555: 97.18%\n",
"#6556: 97.18%\n",
"#6557: 97.18%\n",
"#6558: 97.18%\n",
"#6559: 97.18%\n",
"#6560: 97.18%\n",
"#6561: 97.18%\n",
"#6562: 97.18%\n",
"#6563: 97.18%\n",
"#6564: 97.18%\n",
"#6565: 97.18%\n",
"#6566: 97.18%\n",
"#6567: 97.18%\n",
"#6568: 97.18%\n",
"#6569: 97.18%\n",
"#6570: 97.18%\n",
"#6571: 97.19%\n",
"#6572: 97.17%\n",
"#6573: 97.17%\n",
"#6574: 97.17%\n",
"#6575: 97.17%\n",
"#6576: 97.17%\n",
"#6577: 97.17%\n",
"#6578: 97.16%\n",
"#6579: 97.16%\n",
"#6580: 97.16%\n",
"#6581: 97.16%\n",
"#6582: 97.16%\n",
"#6583: 97.16%\n",
"#6584: 97.16%\n",
"#6585: 97.16%\n",
"#6586: 97.16%\n",
"#6587: 97.16%\n",
"#6588: 97.16%\n",
"#6589: 97.16%\n",
"#6590: 97.16%\n",
"#6591: 97.16%\n",
"#6592: 97.16%\n",
"#6593: 97.16%\n",
"#6594: 97.16%\n",
"#6595: 97.16%\n",
"#6596: 97.17%\n",
"#6597: 97.15%\n",
"#6598: 97.15%\n",
"#6599: 97.14%\n",
"#6600: 97.14%\n",
"#6601: 97.14%\n",
"#6602: 97.14%\n",
"#6603: 97.14%\n",
"#6604: 97.14%\n",
"#6605: 97.14%\n",
"#6606: 97.14%\n",
"#6607: 97.14%\n",
"#6608: 97.14%\n",
"#6609: 97.14%\n",
"#6610: 97.14%\n",
"#6611: 97.14%\n",
"#6612: 97.14%\n",
"#6613: 97.14%\n",
"#6614: 97.14%\n",
"#6615: 97.14%\n",
"#6616: 97.14%\n",
"#6617: 97.14%\n",
"#6618: 97.14%\n",
"#6619: 97.15%\n",
"#6620: 97.15%\n",
"#6621: 97.15%\n",
"#6622: 97.15%\n",
"#6623: 97.15%\n",
"#6624: 97.15%\n",
"#6625: 97.15%\n",
"#6626: 97.15%\n",
"#6627: 97.15%\n",
"#6628: 97.15%\n",
"#6629: 97.15%\n",
"#6630: 97.15%\n",
"#6631: 97.15%\n",
"#6632: 97.15%\n",
"#6633: 97.15%\n",
"#6634: 97.15%\n",
"#6635: 97.15%\n",
"#6636: 97.15%\n",
"#6637: 97.15%\n",
"#6638: 97.15%\n",
"#6639: 97.15%\n",
"#6640: 97.15%\n",
"#6641: 97.15%\n",
"#6642: 97.15%\n",
"#6643: 97.16%\n",
"#6644: 97.16%\n",
"#6645: 97.16%\n",
"#6646: 97.16%\n",
"#6647: 97.16%\n",
"#6648: 97.16%\n",
"#6649: 97.16%\n",
"#6650: 97.16%\n",
"#6651: 97.16%\n",
"#6652: 97.16%\n",
"#6653: 97.16%\n",
"#6654: 97.16%\n",
"#6655: 97.16%\n",
"#6656: 97.16%\n",
"#6657: 97.16%\n",
"#6658: 97.16%\n",
"#6659: 97.16%\n",
"#6660: 97.16%\n",
"#6661: 97.16%\n",
"#6662: 97.16%\n",
"#6663: 97.16%\n",
"#6664: 97.16%\n",
"#6665: 97.16%\n",
"#6666: 97.17%\n",
"#6667: 97.17%\n",
"#6668: 97.17%\n",
"#6669: 97.17%\n",
"#6670: 97.17%\n",
"#6671: 97.17%\n",
"#6672: 97.17%\n",
"#6673: 97.17%\n",
"#6674: 97.17%\n",
"#6675: 97.17%\n",
"#6676: 97.17%\n",
"#6677: 97.17%\n",
"#6678: 97.17%\n",
"#6679: 97.17%\n",
"#6680: 97.17%\n",
"#6681: 97.17%\n",
"#6682: 97.17%\n",
"#6683: 97.17%\n",
"#6684: 97.17%\n",
"#6685: 97.17%\n",
"#6686: 97.17%\n",
"#6687: 97.17%\n",
"#6688: 97.17%\n",
"#6689: 97.17%\n",
"#6690: 97.18%\n",
"#6691: 97.18%\n",
"#6692: 97.18%\n",
"#6693: 97.18%\n",
"#6694: 97.18%\n",
"#6695: 97.18%\n",
"#6696: 97.18%\n",
"#6697: 97.18%\n",
"#6698: 97.18%\n",
"#6699: 97.18%\n",
"#6700: 97.18%\n",
"#6701: 97.18%\n",
"#6702: 97.18%\n",
"#6703: 97.18%\n",
"#6704: 97.18%\n",
"#6705: 97.18%\n",
"#6706: 97.18%\n",
"#6707: 97.18%\n",
"#6708: 97.18%\n",
"#6709: 97.18%\n",
"#6710: 97.18%\n",
"#6711: 97.18%\n",
"#6712: 97.18%\n",
"#6713: 97.18%\n",
"#6714: 97.19%\n",
"#6715: 97.19%\n",
"#6716: 97.19%\n",
"#6717: 97.19%\n",
"#6718: 97.19%\n",
"#6719: 97.19%\n",
"#6720: 97.19%\n",
"#6721: 97.19%\n",
"#6722: 97.19%\n",
"#6723: 97.19%\n",
"#6724: 97.19%\n",
"#6725: 97.19%\n",
"#6726: 97.19%\n",
"#6727: 97.19%\n",
"#6728: 97.19%\n",
"#6729: 97.19%\n",
"#6730: 97.19%\n",
"#6731: 97.19%\n",
"#6732: 97.19%\n",
"#6733: 97.19%\n",
"#6734: 97.19%\n",
"#6735: 97.19%\n",
"#6736: 97.19%\n",
"#6737: 97.20%\n",
"#6738: 97.20%\n",
"#6739: 97.20%\n",
"#6740: 97.18%\n",
"#6741: 97.18%\n",
"#6742: 97.18%\n",
"#6743: 97.18%\n",
"#6744: 97.18%\n",
"#6745: 97.18%\n",
"#6746: 97.18%\n",
"#6747: 97.18%\n",
"#6748: 97.18%\n",
"#6749: 97.19%\n",
"#6750: 97.19%\n",
"#6751: 97.19%\n",
"#6752: 97.19%\n",
"#6753: 97.19%\n",
"#6754: 97.19%\n",
"#6755: 97.17%\n",
"#6756: 97.16%\n",
"#6757: 97.16%\n",
"#6758: 97.16%\n",
"#6759: 97.16%\n",
"#6760: 97.16%\n",
"#6761: 97.16%\n",
"#6762: 97.16%\n",
"#6763: 97.16%\n",
"#6764: 97.16%\n",
"#6765: 97.16%\n",
"#6766: 97.16%\n",
"#6767: 97.16%\n",
"#6768: 97.16%\n",
"#6769: 97.16%\n",
"#6770: 97.16%\n",
"#6771: 97.16%\n",
"#6772: 97.17%\n",
"#6773: 97.17%\n",
"#6774: 97.17%\n",
"#6775: 97.17%\n",
"#6776: 97.17%\n",
"#6777: 97.17%\n",
"#6778: 97.17%\n",
"#6779: 97.17%\n",
"#6780: 97.17%\n",
"#6781: 97.17%\n",
"#6782: 97.17%\n",
"#6783: 97.16%\n",
"#6784: 97.16%\n",
"#6785: 97.16%\n",
"#6786: 97.16%\n",
"#6787: 97.16%\n",
"#6788: 97.16%\n",
"#6789: 97.16%\n",
"#6790: 97.16%\n",
"#6791: 97.16%\n",
"#6792: 97.16%\n",
"#6793: 97.16%\n",
"#6794: 97.16%\n",
"#6795: 97.16%\n",
"#6796: 97.16%\n",
"#6797: 97.16%\n",
"#6798: 97.16%\n",
"#6799: 97.16%\n",
"#6800: 97.16%\n",
"#6801: 97.16%\n",
"#6802: 97.16%\n",
"#6803: 97.16%\n",
"#6804: 97.16%\n",
"#6805: 97.16%\n",
"#6806: 97.16%\n",
"#6807: 97.17%\n",
"#6808: 97.17%\n",
"#6809: 97.17%\n",
"#6810: 97.17%\n",
"#6811: 97.17%\n",
"#6812: 97.17%\n",
"#6813: 97.17%\n",
"#6814: 97.17%\n",
"#6815: 97.17%\n",
"#6816: 97.17%\n",
"#6817: 97.17%\n",
"#6818: 97.17%\n",
"#6819: 97.17%\n",
"#6820: 97.17%\n",
"#6821: 97.17%\n",
"#6822: 97.17%\n",
"#6823: 97.17%\n",
"#6824: 97.17%\n",
"#6825: 97.17%\n",
"#6826: 97.17%\n",
"#6827: 97.17%\n",
"#6828: 97.17%\n",
"#6829: 97.17%\n",
"#6830: 97.17%\n",
"#6831: 97.18%\n",
"#6832: 97.18%\n",
"#6833: 97.18%\n",
"#6834: 97.18%\n",
"#6835: 97.18%\n",
"#6836: 97.18%\n",
"#6837: 97.18%\n",
"#6838: 97.18%\n",
"#6839: 97.18%\n",
"#6840: 97.18%\n",
"#6841: 97.18%\n",
"#6842: 97.18%\n",
"#6843: 97.18%\n",
"#6844: 97.18%\n",
"#6845: 97.18%\n",
"#6846: 97.18%\n",
"#6847: 97.18%\n",
"#6848: 97.18%\n",
"#6849: 97.18%\n",
"#6850: 97.18%\n",
"#6851: 97.18%\n",
"#6852: 97.18%\n",
"#6853: 97.18%\n",
"#6854: 97.18%\n",
"#6855: 97.18%\n",
"#6856: 97.19%\n",
"#6857: 97.19%\n",
"#6858: 97.19%\n",
"#6859: 97.19%\n",
"#6860: 97.19%\n",
"#6861: 97.19%\n",
"#6862: 97.19%\n",
"#6863: 97.19%\n",
"#6864: 97.19%\n",
"#6865: 97.19%\n",
"#6866: 97.19%\n",
"#6867: 97.19%\n",
"#6868: 97.19%\n",
"#6869: 97.19%\n",
"#6870: 97.19%\n",
"#6871: 97.19%\n",
"#6872: 97.19%\n",
"#6873: 97.19%\n",
"#6874: 97.19%\n",
"#6875: 97.19%\n",
"#6876: 97.19%\n",
"#6877: 97.19%\n",
"#6878: 97.19%\n",
"#6879: 97.19%\n",
"#6880: 97.20%\n",
"#6881: 97.20%\n",
"#6882: 97.20%\n",
"#6883: 97.20%\n",
"#6884: 97.20%\n",
"#6885: 97.20%\n",
"#6886: 97.20%\n",
"#6887: 97.20%\n",
"#6888: 97.20%\n",
"#6889: 97.20%\n",
"#6890: 97.20%\n",
"#6891: 97.20%\n",
"#6892: 97.20%\n",
"#6893: 97.20%\n",
"#6894: 97.20%\n",
"#6895: 97.20%\n",
"#6896: 97.20%\n",
"#6897: 97.20%\n",
"#6898: 97.20%\n",
"#6899: 97.20%\n",
"#6900: 97.20%\n",
"#6901: 97.20%\n",
"#6902: 97.20%\n",
"#6903: 97.20%\n",
"#6904: 97.20%\n",
"#6905: 97.21%\n",
"#6906: 97.21%\n",
"#6907: 97.21%\n",
"#6908: 97.21%\n",
"#6909: 97.21%\n",
"#6910: 97.21%\n",
"#6911: 97.21%\n",
"#6912: 97.21%\n",
"#6913: 97.21%\n",
"#6914: 97.21%\n",
"#6915: 97.21%\n",
"#6916: 97.21%\n",
"#6917: 97.21%\n",
"#6918: 97.21%\n",
"#6919: 97.21%\n",
"#6920: 97.21%\n",
"#6921: 97.21%\n",
"#6922: 97.21%\n",
"#6923: 97.21%\n",
"#6924: 97.21%\n",
"#6925: 97.21%\n",
"#6926: 97.21%\n",
"#6927: 97.21%\n",
"#6928: 97.21%\n",
"#6929: 97.22%\n",
"#6930: 97.22%\n",
"#6931: 97.22%\n",
"#6932: 97.22%\n",
"#6933: 97.22%\n",
"#6934: 97.22%\n",
"#6935: 97.22%\n",
"#6936: 97.22%\n",
"#6937: 97.22%\n",
"#6938: 97.22%\n",
"#6939: 97.22%\n",
"#6940: 97.22%\n",
"#6941: 97.22%\n",
"#6942: 97.22%\n",
"#6943: 97.22%\n",
"#6944: 97.22%\n",
"#6945: 97.22%\n",
"#6946: 97.22%\n",
"#6947: 97.22%\n",
"#6948: 97.22%\n",
"#6949: 97.22%\n",
"#6950: 97.22%\n",
"#6951: 97.22%\n",
"#6952: 97.22%\n",
"#6953: 97.22%\n",
"#6954: 97.23%\n",
"#6955: 97.23%\n",
"#6956: 97.23%\n",
"#6957: 97.23%\n",
"#6958: 97.23%\n",
"#6959: 97.23%\n",
"#6960: 97.23%\n",
"#6961: 97.23%\n",
"#6962: 97.23%\n",
"#6963: 97.23%\n",
"#6964: 97.23%\n",
"#6965: 97.23%\n",
"#6966: 97.23%\n",
"#6967: 97.23%\n",
"#6968: 97.23%\n",
"#6969: 97.23%\n",
"#6970: 97.23%\n",
"#6971: 97.23%\n",
"#6972: 97.23%\n",
"#6973: 97.23%\n",
"#6974: 97.23%\n",
"#6975: 97.23%\n",
"#6976: 97.23%\n",
"#6977: 97.23%\n",
"#6978: 97.23%\n",
"#6979: 97.23%\n",
"#6980: 97.24%\n",
"#6981: 97.24%\n",
"#6982: 97.24%\n",
"#6983: 97.24%\n",
"#6984: 97.24%\n",
"#6985: 97.24%\n",
"#6986: 97.24%\n",
"#6987: 97.24%\n",
"#6988: 97.24%\n",
"#6989: 97.24%\n",
"#6990: 97.24%\n",
"#6991: 97.24%\n",
"#6992: 97.24%\n",
"#6993: 97.24%\n",
"#6994: 97.24%\n",
"#6995: 97.24%\n",
"#6996: 97.24%\n",
"#6997: 97.24%\n",
"#6998: 97.24%\n",
"#6999: 97.24%\n",
"#7000: 97.24%\n",
"#7001: 97.24%\n",
"#7002: 97.24%\n",
"#7003: 97.24%\n",
"#7004: 97.24%\n",
"#7005: 97.25%\n",
"#7006: 97.25%\n",
"#7007: 97.25%\n",
"#7008: 97.25%\n",
"#7009: 97.25%\n",
"#7010: 97.25%\n",
"#7011: 97.25%\n",
"#7012: 97.25%\n",
"#7013: 97.25%\n",
"#7014: 97.25%\n",
"#7015: 97.25%\n",
"#7016: 97.25%\n",
"#7017: 97.25%\n",
"#7018: 97.25%\n",
"#7019: 97.25%\n",
"#7020: 97.25%\n",
"#7021: 97.25%\n",
"#7022: 97.25%\n",
"#7023: 97.25%\n",
"#7024: 97.25%\n",
"#7025: 97.25%\n",
"#7026: 97.25%\n",
"#7027: 97.25%\n",
"#7028: 97.25%\n",
"#7029: 97.25%\n",
"#7030: 97.26%\n",
"#7031: 97.26%\n",
"#7032: 97.26%\n",
"#7033: 97.26%\n",
"#7034: 97.26%\n",
"#7035: 97.26%\n",
"#7036: 97.26%\n",
"#7037: 97.26%\n",
"#7038: 97.26%\n",
"#7039: 97.26%\n",
"#7040: 97.24%\n",
"#7041: 97.25%\n",
"#7042: 97.25%\n",
"#7043: 97.25%\n",
"#7044: 97.25%\n",
"#7045: 97.25%\n",
"#7046: 97.25%\n",
"#7047: 97.25%\n",
"#7048: 97.25%\n",
"#7049: 97.25%\n",
"#7050: 97.25%\n",
"#7051: 97.25%\n",
"#7052: 97.25%\n",
"#7053: 97.25%\n",
"#7054: 97.25%\n",
"#7055: 97.25%\n",
"#7056: 97.25%\n",
"#7057: 97.25%\n",
"#7058: 97.25%\n",
"#7059: 97.25%\n",
"#7060: 97.25%\n",
"#7061: 97.25%\n",
"#7062: 97.25%\n",
"#7063: 97.25%\n",
"#7064: 97.25%\n",
"#7065: 97.25%\n",
"#7066: 97.25%\n",
"#7067: 97.26%\n",
"#7068: 97.26%\n",
"#7069: 97.26%\n",
"#7070: 97.26%\n",
"#7071: 97.26%\n",
"#7072: 97.26%\n",
"#7073: 97.26%\n",
"#7074: 97.26%\n",
"#7075: 97.26%\n",
"#7076: 97.26%\n",
"#7077: 97.26%\n",
"#7078: 97.26%\n",
"#7079: 97.26%\n",
"#7080: 97.26%\n",
"#7081: 97.26%\n",
"#7082: 97.26%\n",
"#7083: 97.26%\n",
"#7084: 97.26%\n",
"#7085: 97.26%\n",
"#7086: 97.26%\n",
"#7087: 97.26%\n",
"#7088: 97.26%\n",
"#7089: 97.26%\n",
"#7090: 97.26%\n",
"#7091: 97.26%\n",
"#7092: 97.26%\n",
"#7093: 97.27%\n",
"#7094: 97.27%\n",
"#7095: 97.27%\n",
"#7096: 97.27%\n",
"#7097: 97.27%\n",
"#7098: 97.27%\n",
"#7099: 97.27%\n",
"#7100: 97.27%\n",
"#7101: 97.27%\n",
"#7102: 97.27%\n",
"#7103: 97.27%\n",
"#7104: 97.27%\n",
"#7105: 97.27%\n",
"#7106: 97.27%\n",
"#7107: 97.27%\n",
"#7108: 97.27%\n",
"#7109: 97.27%\n",
"#7110: 97.27%\n",
"#7111: 97.27%\n",
"#7112: 97.27%\n",
"#7113: 97.27%\n",
"#7114: 97.27%\n",
"#7115: 97.27%\n",
"#7116: 97.27%\n",
"#7117: 97.27%\n",
"#7118: 97.27%\n",
"#7119: 97.28%\n",
"#7120: 97.28%\n",
"#7121: 97.26%\n",
"#7122: 97.26%\n",
"#7123: 97.26%\n",
"#7124: 97.26%\n",
"#7125: 97.26%\n",
"#7126: 97.26%\n",
"#7127: 97.26%\n",
"#7128: 97.26%\n",
"#7129: 97.27%\n",
"#7130: 97.27%\n",
"#7131: 97.27%\n",
"#7132: 97.27%\n",
"#7133: 97.27%\n",
"#7134: 97.27%\n",
"#7135: 97.27%\n",
"#7136: 97.27%\n",
"#7137: 97.27%\n",
"#7138: 97.27%\n",
"#7139: 97.27%\n",
"#7140: 97.27%\n",
"#7141: 97.27%\n",
"#7142: 97.27%\n",
"#7143: 97.27%\n",
"#7144: 97.27%\n",
"#7145: 97.27%\n",
"#7146: 97.27%\n",
"#7147: 97.27%\n",
"#7148: 97.27%\n",
"#7149: 97.27%\n",
"#7150: 97.27%\n",
"#7151: 97.27%\n",
"#7152: 97.27%\n",
"#7153: 97.27%\n",
"#7154: 97.27%\n",
"#7155: 97.28%\n",
"#7156: 97.28%\n",
"#7157: 97.28%\n",
"#7158: 97.28%\n",
"#7159: 97.28%\n",
"#7160: 97.28%\n",
"#7161: 97.28%\n",
"#7162: 97.28%\n",
"#7163: 97.28%\n",
"#7164: 97.28%\n",
"#7165: 97.28%\n",
"#7166: 97.28%\n",
"#7167: 97.28%\n",
"#7168: 97.28%\n",
"#7169: 97.28%\n",
"#7170: 97.28%\n",
"#7171: 97.28%\n",
"#7172: 97.28%\n",
"#7173: 97.28%\n",
"#7174: 97.28%\n",
"#7175: 97.28%\n",
"#7176: 97.28%\n",
"#7177: 97.28%\n",
"#7178: 97.28%\n",
"#7179: 97.28%\n",
"#7180: 97.28%\n",
"#7181: 97.28%\n",
"#7182: 97.29%\n",
"#7183: 97.29%\n",
"#7184: 97.29%\n",
"#7185: 97.29%\n",
"#7186: 97.29%\n",
"#7187: 97.29%\n",
"#7188: 97.29%\n",
"#7189: 97.29%\n",
"#7190: 97.29%\n",
"#7191: 97.29%\n",
"#7192: 97.29%\n",
"#7193: 97.29%\n",
"#7194: 97.29%\n",
"#7195: 97.29%\n",
"#7196: 97.29%\n",
"#7197: 97.29%\n",
"#7198: 97.29%\n",
"#7199: 97.29%\n",
"#7200: 97.29%\n",
"#7201: 97.29%\n",
"#7202: 97.29%\n",
"#7203: 97.29%\n",
"#7204: 97.29%\n",
"#7205: 97.29%\n",
"#7206: 97.29%\n",
"#7207: 97.29%\n",
"#7208: 97.30%\n",
"#7209: 97.30%\n",
"#7210: 97.30%\n",
"#7211: 97.30%\n",
"#7212: 97.30%\n",
"#7213: 97.30%\n",
"#7214: 97.30%\n",
"#7215: 97.30%\n",
"#7216: 97.30%\n",
"#7217: 97.30%\n",
"#7218: 97.30%\n",
"#7219: 97.30%\n",
"#7220: 97.30%\n",
"#7221: 97.30%\n",
"#7222: 97.30%\n",
"#7223: 97.30%\n",
"#7224: 97.30%\n",
"#7225: 97.30%\n",
"#7226: 97.30%\n",
"#7227: 97.30%\n",
"#7228: 97.30%\n",
"#7229: 97.30%\n",
"#7230: 97.30%\n",
"#7231: 97.30%\n",
"#7232: 97.30%\n",
"#7233: 97.30%\n",
"#7234: 97.30%\n",
"#7235: 97.31%\n",
"#7236: 97.31%\n",
"#7237: 97.31%\n",
"#7238: 97.31%\n",
"#7239: 97.31%\n",
"#7240: 97.31%\n",
"#7241: 97.31%\n",
"#7242: 97.31%\n",
"#7243: 97.31%\n",
"#7244: 97.31%\n",
"#7245: 97.31%\n",
"#7246: 97.31%\n",
"#7247: 97.31%\n",
"#7248: 97.31%\n",
"#7249: 97.31%\n",
"#7250: 97.31%\n",
"#7251: 97.31%\n",
"#7252: 97.31%\n",
"#7253: 97.31%\n",
"#7254: 97.31%\n",
"#7255: 97.31%\n",
"#7256: 97.31%\n",
"#7257: 97.31%\n",
"#7258: 97.31%\n",
"#7259: 97.31%\n",
"#7260: 97.31%\n",
"#7261: 97.31%\n",
"#7262: 97.32%\n",
"#7263: 97.32%\n",
"#7264: 97.32%\n",
"#7265: 97.32%\n",
"#7266: 97.32%\n",
"#7267: 97.32%\n",
"#7268: 97.32%\n",
"#7269: 97.32%\n",
"#7270: 97.32%\n",
"#7271: 97.32%\n",
"#7272: 97.32%\n",
"#7273: 97.32%\n",
"#7274: 97.32%\n",
"#7275: 97.32%\n",
"#7276: 97.32%\n",
"#7277: 97.32%\n",
"#7278: 97.32%\n",
"#7279: 97.32%\n",
"#7280: 97.32%\n",
"#7281: 97.32%\n",
"#7282: 97.32%\n",
"#7283: 97.32%\n",
"#7284: 97.32%\n",
"#7285: 97.32%\n",
"#7286: 97.32%\n",
"#7287: 97.32%\n",
"#7288: 97.32%\n",
"#7289: 97.33%\n",
"#7290: 97.33%\n",
"#7291: 97.33%\n",
"#7292: 97.33%\n",
"#7293: 97.33%\n",
"#7294: 97.33%\n",
"#7295: 97.33%\n",
"#7296: 97.33%\n",
"#7297: 97.33%\n",
"#7298: 97.33%\n",
"#7299: 97.33%\n",
"#7300: 97.33%\n",
"#7301: 97.33%\n",
"#7302: 97.33%\n",
"#7303: 97.33%\n",
"#7304: 97.33%\n",
"#7305: 97.33%\n",
"#7306: 97.33%\n",
"#7307: 97.33%\n",
"#7308: 97.33%\n",
"#7309: 97.33%\n",
"#7310: 97.33%\n",
"#7311: 97.33%\n",
"#7312: 97.33%\n",
"#7313: 97.33%\n",
"#7314: 97.33%\n",
"#7315: 97.33%\n",
"#7316: 97.33%\n",
"#7317: 97.34%\n",
"#7318: 97.34%\n",
"#7319: 97.34%\n",
"#7320: 97.34%\n",
"#7321: 97.34%\n",
"#7322: 97.34%\n",
"#7323: 97.34%\n",
"#7324: 97.34%\n",
"#7325: 97.34%\n",
"#7326: 97.34%\n",
"#7327: 97.34%\n",
"#7328: 97.34%\n",
"#7329: 97.34%\n",
"#7330: 97.34%\n",
"#7331: 97.34%\n",
"#7332: 97.34%\n",
"#7333: 97.34%\n",
"#7334: 97.34%\n",
"#7335: 97.34%\n",
"#7336: 97.34%\n",
"#7337: 97.34%\n",
"#7338: 97.34%\n",
"#7339: 97.34%\n",
"#7340: 97.34%\n",
"#7341: 97.34%\n",
"#7342: 97.34%\n",
"#7343: 97.34%\n",
"#7344: 97.35%\n",
"#7345: 97.35%\n",
"#7346: 97.35%\n",
"#7347: 97.35%\n",
"#7348: 97.35%\n",
"#7349: 97.35%\n",
"#7350: 97.35%\n",
"#7351: 97.35%\n",
"#7352: 97.35%\n",
"#7353: 97.35%\n",
"#7354: 97.35%\n",
"#7355: 97.35%\n",
"#7356: 97.35%\n",
"#7357: 97.35%\n",
"#7358: 97.35%\n",
"#7359: 97.35%\n",
"#7360: 97.35%\n",
"#7361: 97.35%\n",
"#7362: 97.35%\n",
"#7363: 97.35%\n",
"#7364: 97.35%\n",
"#7365: 97.35%\n",
"#7366: 97.35%\n",
"#7367: 97.35%\n",
"#7368: 97.35%\n",
"#7369: 97.35%\n",
"#7370: 97.35%\n",
"#7371: 97.35%\n",
"#7372: 97.36%\n",
"#7373: 97.36%\n",
"#7374: 97.36%\n",
"#7375: 97.36%\n",
"#7376: 97.36%\n",
"#7377: 97.36%\n",
"#7378: 97.36%\n",
"#7379: 97.36%\n",
"#7380: 97.36%\n",
"#7381: 97.36%\n",
"#7382: 97.36%\n",
"#7383: 97.36%\n",
"#7384: 97.36%\n",
"#7385: 97.36%\n",
"#7386: 97.36%\n",
"#7387: 97.36%\n",
"#7388: 97.36%\n",
"#7389: 97.36%\n",
"#7390: 97.36%\n",
"#7391: 97.36%\n",
"#7392: 97.36%\n",
"#7393: 97.36%\n",
"#7394: 97.36%\n",
"#7395: 97.36%\n",
"#7396: 97.36%\n",
"#7397: 97.36%\n",
"#7398: 97.36%\n",
"#7399: 97.36%\n",
"#7400: 97.37%\n",
"#7401: 97.37%\n",
"#7402: 97.37%\n",
"#7403: 97.37%\n",
"#7404: 97.37%\n",
"#7405: 97.37%\n",
"#7406: 97.37%\n",
"#7407: 97.37%\n",
"#7408: 97.37%\n",
"#7409: 97.37%\n",
"#7410: 97.37%\n",
"#7411: 97.37%\n",
"#7412: 97.37%\n",
"#7413: 97.37%\n",
"#7414: 97.37%\n",
"#7415: 97.37%\n",
"#7416: 97.37%\n",
"#7417: 97.37%\n",
"#7418: 97.37%\n",
"#7419: 97.37%\n",
"#7420: 97.37%\n",
"#7421: 97.37%\n",
"#7422: 97.37%\n",
"#7423: 97.37%\n",
"#7424: 97.37%\n",
"#7425: 97.37%\n",
"#7426: 97.37%\n",
"#7427: 97.37%\n",
"#7428: 97.38%\n",
"#7429: 97.38%\n",
"#7430: 97.38%\n",
"#7431: 97.38%\n",
"#7432: 97.38%\n",
"#7433: 97.38%\n",
"#7434: 97.38%\n",
"#7435: 97.38%\n",
"#7436: 97.38%\n",
"#7437: 97.38%\n",
"#7438: 97.38%\n",
"#7439: 97.38%\n",
"#7440: 97.38%\n",
"#7441: 97.38%\n",
"#7442: 97.38%\n",
"#7443: 97.38%\n",
"#7444: 97.38%\n",
"#7445: 97.38%\n",
"#7446: 97.38%\n",
"#7447: 97.38%\n",
"#7448: 97.38%\n",
"#7449: 97.38%\n",
"#7450: 97.38%\n",
"#7451: 97.37%\n",
"#7452: 97.37%\n",
"#7453: 97.37%\n",
"#7454: 97.37%\n",
"#7455: 97.37%\n",
"#7456: 97.37%\n",
"#7457: 97.37%\n",
"#7458: 97.37%\n",
"#7459: 97.37%\n",
"#7460: 97.37%\n",
"#7461: 97.37%\n",
"#7462: 97.37%\n",
"#7463: 97.37%\n",
"#7464: 97.37%\n",
"#7465: 97.37%\n",
"#7466: 97.38%\n",
"#7467: 97.38%\n",
"#7468: 97.38%\n",
"#7469: 97.38%\n",
"#7470: 97.38%\n",
"#7471: 97.38%\n",
"#7472: 97.38%\n",
"#7473: 97.38%\n",
"#7474: 97.38%\n",
"#7475: 97.38%\n",
"#7476: 97.38%\n",
"#7477: 97.38%\n",
"#7478: 97.38%\n",
"#7479: 97.38%\n",
"#7480: 97.38%\n",
"#7481: 97.38%\n",
"#7482: 97.38%\n",
"#7483: 97.38%\n",
"#7484: 97.38%\n",
"#7485: 97.38%\n",
"#7486: 97.38%\n",
"#7487: 97.38%\n",
"#7488: 97.38%\n",
"#7489: 97.38%\n",
"#7490: 97.38%\n",
"#7491: 97.38%\n",
"#7492: 97.38%\n",
"#7493: 97.38%\n",
"#7494: 97.38%\n",
"#7495: 97.39%\n",
"#7496: 97.39%\n",
"#7497: 97.39%\n",
"#7498: 97.39%\n",
"#7499: 97.39%\n",
"#7500: 97.39%\n",
"#7501: 97.39%\n",
"#7502: 97.39%\n",
"#7503: 97.39%\n",
"#7504: 97.39%\n",
"#7505: 97.39%\n",
"#7506: 97.39%\n",
"#7507: 97.39%\n",
"#7508: 97.39%\n",
"#7509: 97.39%\n",
"#7510: 97.39%\n",
"#7511: 97.39%\n",
"#7512: 97.39%\n",
"#7513: 97.39%\n",
"#7514: 97.38%\n",
"#7515: 97.38%\n",
"#7516: 97.38%\n",
"#7517: 97.38%\n",
"#7518: 97.38%\n",
"#7519: 97.38%\n",
"#7520: 97.38%\n",
"#7521: 97.38%\n",
"#7522: 97.38%\n",
"#7523: 97.38%\n",
"#7524: 97.38%\n",
"#7525: 97.38%\n",
"#7526: 97.38%\n",
"#7527: 97.38%\n",
"#7528: 97.38%\n",
"#7529: 97.38%\n",
"#7530: 97.38%\n",
"#7531: 97.38%\n",
"#7532: 97.38%\n",
"#7533: 97.39%\n",
"#7534: 97.39%\n",
"#7535: 97.39%\n",
"#7536: 97.39%\n",
"#7537: 97.39%\n",
"#7538: 97.39%\n",
"#7539: 97.39%\n",
"#7540: 97.39%\n",
"#7541: 97.39%\n",
"#7542: 97.39%\n",
"#7543: 97.39%\n",
"#7544: 97.39%\n",
"#7545: 97.39%\n",
"#7546: 97.39%\n",
"#7547: 97.39%\n",
"#7548: 97.39%\n",
"#7549: 97.39%\n",
"#7550: 97.39%\n",
"#7551: 97.39%\n",
"#7552: 97.39%\n",
"#7553: 97.39%\n",
"#7554: 97.39%\n",
"#7555: 97.39%\n",
"#7556: 97.39%\n",
"#7557: 97.39%\n",
"#7558: 97.39%\n",
"#7559: 97.39%\n",
"#7560: 97.39%\n",
"#7561: 97.39%\n",
"#7562: 97.40%\n",
"#7563: 97.40%\n",
"#7564: 97.40%\n",
"#7565: 97.40%\n",
"#7566: 97.40%\n",
"#7567: 97.40%\n",
"#7568: 97.40%\n",
"#7569: 97.40%\n",
"#7570: 97.40%\n",
"#7571: 97.40%\n",
"#7572: 97.40%\n",
"#7573: 97.40%\n",
"#7574: 97.40%\n",
"#7575: 97.40%\n",
"#7576: 97.40%\n",
"#7577: 97.40%\n",
"#7578: 97.40%\n",
"#7579: 97.40%\n",
"#7580: 97.40%\n",
"#7581: 97.40%\n",
"#7582: 97.40%\n",
"#7583: 97.40%\n",
"#7584: 97.40%\n",
"#7585: 97.40%\n",
"#7586: 97.40%\n",
"#7587: 97.40%\n",
"#7588: 97.40%\n",
"#7589: 97.40%\n",
"#7590: 97.40%\n",
"#7591: 97.41%\n",
"#7592: 97.41%\n",
"#7593: 97.41%\n",
"#7594: 97.41%\n",
"#7595: 97.41%\n",
"#7596: 97.41%\n",
"#7597: 97.41%\n",
"#7598: 97.41%\n",
"#7599: 97.41%\n",
"#7600: 97.41%\n",
"#7601: 97.41%\n",
"#7602: 97.41%\n",
"#7603: 97.41%\n",
"#7604: 97.41%\n",
"#7605: 97.41%\n",
"#7606: 97.41%\n",
"#7607: 97.41%\n",
"#7608: 97.41%\n",
"#7609: 97.41%\n",
"#7610: 97.41%\n",
"#7611: 97.41%\n",
"#7612: 97.41%\n",
"#7613: 97.41%\n",
"#7614: 97.41%\n",
"#7615: 97.41%\n",
"#7616: 97.41%\n",
"#7617: 97.41%\n",
"#7618: 97.41%\n",
"#7619: 97.41%\n",
"#7620: 97.42%\n",
"#7621: 97.42%\n",
"#7622: 97.42%\n",
"#7623: 97.42%\n",
"#7624: 97.42%\n",
"#7625: 97.42%\n",
"#7626: 97.42%\n",
"#7627: 97.42%\n",
"#7628: 97.42%\n",
"#7629: 97.42%\n",
"#7630: 97.42%\n",
"#7631: 97.42%\n",
"#7632: 97.42%\n",
"#7633: 97.42%\n",
"#7634: 97.42%\n",
"#7635: 97.42%\n",
"#7636: 97.42%\n",
"#7637: 97.42%\n",
"#7638: 97.42%\n",
"#7639: 97.42%\n",
"#7640: 97.42%\n",
"#7641: 97.42%\n",
"#7642: 97.42%\n",
"#7643: 97.42%\n",
"#7644: 97.42%\n",
"#7645: 97.42%\n",
"#7646: 97.42%\n",
"#7647: 97.42%\n",
"#7648: 97.42%\n",
"#7649: 97.42%\n",
"#7650: 97.43%\n",
"#7651: 97.43%\n",
"#7652: 97.43%\n",
"#7653: 97.43%\n",
"#7654: 97.43%\n",
"#7655: 97.43%\n",
"#7656: 97.43%\n",
"#7657: 97.43%\n",
"#7658: 97.43%\n",
"#7659: 97.43%\n",
"#7660: 97.43%\n",
"#7661: 97.43%\n",
"#7662: 97.43%\n",
"#7663: 97.43%\n",
"#7664: 97.43%\n",
"#7665: 97.43%\n",
"#7666: 97.43%\n",
"#7667: 97.43%\n",
"#7668: 97.43%\n",
"#7669: 97.43%\n",
"#7670: 97.43%\n",
"#7671: 97.43%\n",
"#7672: 97.43%\n",
"#7673: 97.43%\n",
"#7674: 97.43%\n",
"#7675: 97.43%\n",
"#7676: 97.43%\n",
"#7677: 97.43%\n",
"#7678: 97.43%\n",
"#7679: 97.43%\n",
"#7680: 97.44%\n",
"#7681: 97.44%\n",
"#7682: 97.44%\n",
"#7683: 97.44%\n",
"#7684: 97.44%\n",
"#7685: 97.44%\n",
"#7686: 97.44%\n",
"#7687: 97.44%\n",
"#7688: 97.44%\n",
"#7689: 97.44%\n",
"#7690: 97.44%\n",
"#7691: 97.44%\n",
"#7692: 97.44%\n",
"#7693: 97.44%\n",
"#7694: 97.44%\n",
"#7695: 97.44%\n",
"#7696: 97.44%\n",
"#7697: 97.44%\n",
"#7698: 97.44%\n",
"#7699: 97.44%\n",
"#7700: 97.44%\n",
"#7701: 97.44%\n",
"#7702: 97.44%\n",
"#7703: 97.44%\n",
"#7704: 97.44%\n",
"#7705: 97.44%\n",
"#7706: 97.44%\n",
"#7707: 97.44%\n",
"#7708: 97.44%\n",
"#7709: 97.44%\n",
"#7710: 97.45%\n",
"#7711: 97.45%\n",
"#7712: 97.45%\n",
"#7713: 97.45%\n",
"#7714: 97.45%\n",
"#7715: 97.45%\n",
"#7716: 97.45%\n",
"#7717: 97.45%\n",
"#7718: 97.45%\n",
"#7719: 97.45%\n",
"#7720: 97.45%\n",
"#7721: 97.45%\n",
"#7722: 97.45%\n",
"#7723: 97.45%\n",
"#7724: 97.45%\n",
"#7725: 97.45%\n",
"#7726: 97.45%\n",
"#7727: 97.45%\n",
"#7728: 97.45%\n",
"#7729: 97.45%\n",
"#7730: 97.45%\n",
"#7731: 97.45%\n",
"#7732: 97.45%\n",
"#7733: 97.45%\n",
"#7734: 97.45%\n",
"#7735: 97.45%\n",
"#7736: 97.45%\n",
"#7737: 97.45%\n",
"#7738: 97.45%\n",
"#7739: 97.45%\n",
"#7740: 97.46%\n",
"#7741: 97.46%\n",
"#7742: 97.46%\n",
"#7743: 97.46%\n",
"#7744: 97.46%\n",
"#7745: 97.46%\n",
"#7746: 97.46%\n",
"#7747: 97.46%\n",
"#7748: 97.46%\n",
"#7749: 97.46%\n",
"#7750: 97.46%\n",
"#7751: 97.46%\n",
"#7752: 97.46%\n",
"#7753: 97.46%\n",
"#7754: 97.46%\n",
"#7755: 97.46%\n",
"#7756: 97.46%\n",
"#7757: 97.46%\n",
"#7758: 97.46%\n",
"#7759: 97.46%\n",
"#7760: 97.46%\n",
"#7761: 97.46%\n",
"#7762: 97.46%\n",
"#7763: 97.46%\n",
"#7764: 97.46%\n",
"#7765: 97.46%\n",
"#7766: 97.46%\n",
"#7767: 97.46%\n",
"#7768: 97.46%\n",
"#7769: 97.46%\n",
"#7770: 97.46%\n",
"#7771: 97.47%\n",
"#7772: 97.47%\n",
"#7773: 97.47%\n",
"#7774: 97.47%\n",
"#7775: 97.47%\n",
"#7776: 97.47%\n",
"#7777: 97.47%\n",
"#7778: 97.47%\n",
"#7779: 97.47%\n",
"#7780: 97.47%\n",
"#7781: 97.47%\n",
"#7782: 97.47%\n",
"#7783: 97.47%\n",
"#7784: 97.47%\n",
"#7785: 97.47%\n",
"#7786: 97.47%\n",
"#7787: 97.47%\n",
"#7788: 97.47%\n",
"#7789: 97.47%\n",
"#7790: 97.47%\n",
"#7791: 97.47%\n",
"#7792: 97.47%\n",
"#7793: 97.47%\n",
"#7794: 97.47%\n",
"#7795: 97.47%\n",
"#7796: 97.47%\n",
"#7797: 97.47%\n",
"#7798: 97.47%\n",
"#7799: 97.47%\n",
"#7800: 97.47%\n",
"#7801: 97.48%\n",
"#7802: 97.48%\n",
"#7803: 97.48%\n",
"#7804: 97.48%\n",
"#7805: 97.48%\n",
"#7806: 97.48%\n",
"#7807: 97.48%\n",
"#7808: 97.48%\n",
"#7809: 97.48%\n",
"#7810: 97.48%\n",
"#7811: 97.48%\n",
"#7812: 97.48%\n",
"#7813: 97.48%\n",
"#7814: 97.48%\n",
"#7815: 97.48%\n",
"#7816: 97.48%\n",
"#7817: 97.48%\n",
"#7818: 97.48%\n",
"#7819: 97.48%\n",
"#7820: 97.48%\n",
"#7821: 97.48%\n",
"#7822: 97.48%\n",
"#7823: 97.48%\n",
"#7824: 97.48%\n",
"#7825: 97.48%\n",
"#7826: 97.48%\n",
"#7827: 97.48%\n",
"#7828: 97.48%\n",
"#7829: 97.48%\n",
"#7830: 97.48%\n",
"#7831: 97.48%\n",
"#7832: 97.48%\n",
"#7833: 97.49%\n",
"#7834: 97.49%\n",
"#7835: 97.49%\n",
"#7836: 97.49%\n",
"#7837: 97.49%\n",
"#7838: 97.49%\n",
"#7839: 97.49%\n",
"#7840: 97.49%\n",
"#7841: 97.49%\n",
"#7842: 97.49%\n",
"#7843: 97.49%\n",
"#7844: 97.49%\n",
"#7845: 97.48%\n",
"#7846: 97.48%\n",
"#7847: 97.48%\n",
"#7848: 97.48%\n",
"#7849: 97.48%\n",
"#7850: 97.48%\n",
"#7851: 97.48%\n",
"#7852: 97.48%\n",
"#7853: 97.48%\n",
"#7854: 97.48%\n",
"#7855: 97.48%\n",
"#7856: 97.48%\n",
"#7857: 97.48%\n",
"#7858: 97.48%\n",
"#7859: 97.48%\n",
"#7860: 97.48%\n",
"#7861: 97.48%\n",
"#7862: 97.48%\n",
"#7863: 97.48%\n",
"#7864: 97.48%\n",
"#7865: 97.48%\n",
"#7866: 97.48%\n",
"#7867: 97.48%\n",
"#7868: 97.48%\n",
"#7869: 97.48%\n",
"#7870: 97.48%\n",
"#7871: 97.48%\n",
"#7872: 97.49%\n",
"#7873: 97.49%\n",
"#7874: 97.49%\n",
"#7875: 97.49%\n",
"#7876: 97.49%\n",
"#7877: 97.49%\n",
"#7878: 97.49%\n",
"#7879: 97.49%\n",
"#7880: 97.49%\n",
"#7881: 97.49%\n",
"#7882: 97.49%\n",
"#7883: 97.49%\n",
"#7884: 97.49%\n",
"#7885: 97.49%\n",
"#7886: 97.48%\n",
"#7887: 97.48%\n",
"#7888: 97.48%\n",
"#7889: 97.48%\n",
"#7890: 97.48%\n",
"#7891: 97.48%\n",
"#7892: 97.48%\n",
"#7893: 97.48%\n",
"#7894: 97.48%\n",
"#7895: 97.48%\n",
"#7896: 97.48%\n",
"#7897: 97.48%\n",
"#7898: 97.48%\n",
"#7899: 97.48%\n",
"#7900: 97.48%\n",
"#7901: 97.48%\n",
"#7902: 97.48%\n",
"#7903: 97.48%\n",
"#7904: 97.48%\n",
"#7905: 97.48%\n",
"#7906: 97.48%\n",
"#7907: 97.48%\n",
"#7908: 97.48%\n",
"#7909: 97.48%\n",
"#7910: 97.48%\n",
"#7911: 97.48%\n",
"#7912: 97.49%\n",
"#7913: 97.49%\n",
"#7914: 97.49%\n",
"#7915: 97.47%\n",
"#7916: 97.47%\n",
"#7917: 97.47%\n",
"#7918: 97.47%\n",
"#7919: 97.47%\n",
"#7920: 97.48%\n",
"#7921: 97.48%\n",
"#7922: 97.48%\n",
"#7923: 97.48%\n",
"#7924: 97.48%\n",
"#7925: 97.48%\n",
"#7926: 97.48%\n",
"#7927: 97.46%\n",
"#7928: 97.47%\n",
"#7929: 97.47%\n",
"#7930: 97.47%\n",
"#7931: 97.47%\n",
"#7932: 97.47%\n",
"#7933: 97.47%\n",
"#7934: 97.47%\n",
"#7935: 97.47%\n",
"#7936: 97.47%\n",
"#7937: 97.47%\n",
"#7938: 97.47%\n",
"#7939: 97.47%\n",
"#7940: 97.47%\n",
"#7941: 97.47%\n",
"#7942: 97.47%\n",
"#7943: 97.47%\n",
"#7944: 97.47%\n",
"#7945: 97.47%\n",
"#7946: 97.47%\n",
"#7947: 97.47%\n",
"#7948: 97.47%\n",
"#7949: 97.47%\n",
"#7950: 97.47%\n",
"#7951: 97.47%\n",
"#7952: 97.47%\n",
"#7953: 97.47%\n",
"#7954: 97.47%\n",
"#7955: 97.47%\n",
"#7956: 97.47%\n",
"#7957: 97.47%\n",
"#7958: 97.47%\n",
"#7959: 97.47%\n",
"#7960: 97.48%\n",
"#7961: 97.48%\n",
"#7962: 97.48%\n",
"#7963: 97.48%\n",
"#7964: 97.48%\n",
"#7965: 97.48%\n",
"#7966: 97.48%\n",
"#7967: 97.48%\n",
"#7968: 97.48%\n",
"#7969: 97.48%\n",
"#7970: 97.48%\n",
"#7971: 97.48%\n",
"#7972: 97.48%\n",
"#7973: 97.48%\n",
"#7974: 97.48%\n",
"#7975: 97.48%\n",
"#7976: 97.48%\n",
"#7977: 97.48%\n",
"#7978: 97.48%\n",
"#7979: 97.48%\n",
"#7980: 97.48%\n",
"#7981: 97.48%\n",
"#7982: 97.48%\n",
"#7983: 97.48%\n",
"#7984: 97.48%\n",
"#7985: 97.48%\n",
"#7986: 97.48%\n",
"#7987: 97.48%\n",
"#7988: 97.48%\n",
"#7989: 97.48%\n",
"#7990: 97.48%\n",
"#7991: 97.48%\n",
"#7992: 97.49%\n",
"#7993: 97.49%\n",
"#7994: 97.49%\n",
"#7995: 97.49%\n",
"#7996: 97.49%\n",
"#7997: 97.49%\n",
"#7998: 97.49%\n",
"#7999: 97.49%\n",
"#8000: 97.49%\n",
"#8001: 97.49%\n",
"#8002: 97.49%\n",
"#8003: 97.49%\n",
"#8004: 97.49%\n",
"#8005: 97.49%\n",
"#8006: 97.49%\n",
"#8007: 97.49%\n",
"#8008: 97.49%\n",
"#8009: 97.49%\n",
"#8010: 97.49%\n",
"#8011: 97.49%\n",
"#8012: 97.49%\n",
"#8013: 97.49%\n",
"#8014: 97.49%\n",
"#8015: 97.49%\n",
"#8016: 97.49%\n",
"#8017: 97.49%\n",
"#8018: 97.49%\n",
"#8019: 97.49%\n",
"#8020: 97.49%\n",
"#8021: 97.49%\n",
"#8022: 97.49%\n",
"#8023: 97.50%\n",
"#8024: 97.50%\n",
"#8025: 97.50%\n",
"#8026: 97.50%\n",
"#8027: 97.50%\n",
"#8028: 97.50%\n",
"#8029: 97.50%\n",
"#8030: 97.50%\n",
"#8031: 97.50%\n",
"#8032: 97.50%\n",
"#8033: 97.50%\n",
"#8034: 97.50%\n",
"#8035: 97.50%\n",
"#8036: 97.50%\n",
"#8037: 97.50%\n",
"#8038: 97.50%\n",
"#8039: 97.50%\n",
"#8040: 97.50%\n",
"#8041: 97.50%\n",
"#8042: 97.50%\n",
"#8043: 97.50%\n",
"#8044: 97.50%\n",
"#8045: 97.50%\n",
"#8046: 97.50%\n",
"#8047: 97.49%\n",
"#8048: 97.49%\n",
"#8049: 97.49%\n",
"#8050: 97.49%\n",
"#8051: 97.49%\n",
"#8052: 97.49%\n",
"#8053: 97.49%\n",
"#8054: 97.49%\n",
"#8055: 97.49%\n",
"#8056: 97.49%\n",
"#8057: 97.49%\n",
"#8058: 97.49%\n",
"#8059: 97.48%\n",
"#8060: 97.48%\n",
"#8061: 97.48%\n",
"#8062: 97.48%\n",
"#8063: 97.48%\n",
"#8064: 97.48%\n",
"#8065: 97.48%\n",
"#8066: 97.48%\n",
"#8067: 97.48%\n",
"#8068: 97.48%\n",
"#8069: 97.48%\n",
"#8070: 97.48%\n",
"#8071: 97.49%\n",
"#8072: 97.49%\n",
"#8073: 97.49%\n",
"#8074: 97.49%\n",
"#8075: 97.49%\n",
"#8076: 97.49%\n",
"#8077: 97.49%\n",
"#8078: 97.49%\n",
"#8079: 97.49%\n",
"#8080: 97.49%\n",
"#8081: 97.49%\n",
"#8082: 97.49%\n",
"#8083: 97.49%\n",
"#8084: 97.49%\n",
"#8085: 97.49%\n",
"#8086: 97.49%\n",
"#8087: 97.49%\n",
"#8088: 97.49%\n",
"#8089: 97.49%\n",
"#8090: 97.49%\n",
"#8091: 97.48%\n",
"#8092: 97.48%\n",
"#8093: 97.48%\n",
"#8094: 97.47%\n",
"#8095: 97.47%\n",
"#8096: 97.47%\n",
"#8097: 97.47%\n",
"#8098: 97.47%\n",
"#8099: 97.47%\n",
"#8100: 97.47%\n",
"#8101: 97.47%\n",
"#8102: 97.47%\n",
"#8103: 97.47%\n",
"#8104: 97.47%\n",
"#8105: 97.47%\n",
"#8106: 97.47%\n",
"#8107: 97.47%\n",
"#8108: 97.47%\n",
"#8109: 97.47%\n",
"#8110: 97.47%\n",
"#8111: 97.47%\n",
"#8112: 97.47%\n",
"#8113: 97.47%\n",
"#8114: 97.47%\n",
"#8115: 97.47%\n",
"#8116: 97.47%\n",
"#8117: 97.47%\n",
"#8118: 97.48%\n",
"#8119: 97.48%\n",
"#8120: 97.48%\n",
"#8121: 97.48%\n",
"#8122: 97.48%\n",
"#8123: 97.48%\n",
"#8124: 97.48%\n",
"#8125: 97.48%\n",
"#8126: 97.48%\n",
"#8127: 97.48%\n",
"#8128: 97.48%\n",
"#8129: 97.48%\n",
"#8130: 97.48%\n",
"#8131: 97.48%\n",
"#8132: 97.48%\n",
"#8133: 97.48%\n",
"#8134: 97.48%\n",
"#8135: 97.48%\n",
"#8136: 97.48%\n",
"#8137: 97.48%\n",
"#8138: 97.48%\n",
"#8139: 97.48%\n",
"#8140: 97.48%\n",
"#8141: 97.48%\n",
"#8142: 97.48%\n",
"#8143: 97.48%\n",
"#8144: 97.48%\n",
"#8145: 97.48%\n",
"#8146: 97.48%\n",
"#8147: 97.48%\n",
"#8148: 97.48%\n",
"#8149: 97.48%\n",
"#8150: 97.48%\n",
"#8151: 97.49%\n",
"#8152: 97.49%\n",
"#8153: 97.49%\n",
"#8154: 97.49%\n",
"#8155: 97.49%\n",
"#8156: 97.49%\n",
"#8157: 97.49%\n",
"#8158: 97.49%\n",
"#8159: 97.49%\n",
"#8160: 97.49%\n",
"#8161: 97.49%\n",
"#8162: 97.49%\n",
"#8163: 97.49%\n",
"#8164: 97.49%\n",
"#8165: 97.49%\n",
"#8166: 97.49%\n",
"#8167: 97.49%\n",
"#8168: 97.49%\n",
"#8169: 97.49%\n",
"#8170: 97.49%\n",
"#8171: 97.49%\n",
"#8172: 97.49%\n",
"#8173: 97.49%\n",
"#8174: 97.49%\n",
"#8175: 97.49%\n",
"#8176: 97.49%\n",
"#8177: 97.49%\n",
"#8178: 97.49%\n",
"#8179: 97.49%\n",
"#8180: 97.49%\n",
"#8181: 97.49%\n",
"#8182: 97.49%\n",
"#8183: 97.50%\n",
"#8184: 97.50%\n",
"#8185: 97.50%\n",
"#8186: 97.50%\n",
"#8187: 97.50%\n",
"#8188: 97.50%\n",
"#8189: 97.50%\n",
"#8190: 97.50%\n",
"#8191: 97.50%\n",
"#8192: 97.50%\n",
"#8193: 97.50%\n",
"#8194: 97.50%\n",
"#8195: 97.50%\n",
"#8196: 97.50%\n",
"#8197: 97.50%\n",
"#8198: 97.50%\n",
"#8199: 97.50%\n",
"#8200: 97.50%\n",
"#8201: 97.50%\n",
"#8202: 97.50%\n",
"#8203: 97.50%\n",
"#8204: 97.50%\n",
"#8205: 97.50%\n",
"#8206: 97.50%\n",
"#8207: 97.50%\n",
"#8208: 97.50%\n",
"#8209: 97.50%\n",
"#8210: 97.50%\n",
"#8211: 97.50%\n",
"#8212: 97.50%\n",
"#8213: 97.50%\n",
"#8214: 97.50%\n",
"#8215: 97.50%\n",
"#8216: 97.51%\n",
"#8217: 97.51%\n",
"#8218: 97.51%\n",
"#8219: 97.51%\n",
"#8220: 97.51%\n",
"#8221: 97.51%\n",
"#8222: 97.51%\n",
"#8223: 97.51%\n",
"#8224: 97.51%\n",
"#8225: 97.51%\n",
"#8226: 97.51%\n",
"#8227: 97.51%\n",
"#8228: 97.51%\n",
"#8229: 97.51%\n",
"#8230: 97.51%\n",
"#8231: 97.51%\n",
"#8232: 97.51%\n",
"#8233: 97.51%\n",
"#8234: 97.51%\n",
"#8235: 97.51%\n",
"#8236: 97.51%\n",
"#8237: 97.51%\n",
"#8238: 97.51%\n",
"#8239: 97.51%\n",
"#8240: 97.51%\n",
"#8241: 97.51%\n",
"#8242: 97.51%\n",
"#8243: 97.51%\n",
"#8244: 97.51%\n",
"#8245: 97.51%\n",
"#8246: 97.51%\n",
"#8247: 97.51%\n",
"#8248: 97.51%\n",
"#8249: 97.52%\n",
"#8250: 97.52%\n",
"#8251: 97.52%\n",
"#8252: 97.52%\n",
"#8253: 97.52%\n",
"#8254: 97.52%\n",
"#8255: 97.52%\n",
"#8256: 97.52%\n",
"#8257: 97.52%\n",
"#8258: 97.52%\n",
"#8259: 97.52%\n",
"#8260: 97.52%\n",
"#8261: 97.52%\n",
"#8262: 97.52%\n",
"#8263: 97.52%\n",
"#8264: 97.52%\n",
"#8265: 97.52%\n",
"#8266: 97.52%\n",
"#8267: 97.52%\n",
"#8268: 97.52%\n",
"#8269: 97.52%\n",
"#8270: 97.52%\n",
"#8271: 97.52%\n",
"#8272: 97.52%\n",
"#8273: 97.52%\n",
"#8274: 97.52%\n",
"#8275: 97.52%\n",
"#8276: 97.52%\n",
"#8277: 97.52%\n",
"#8278: 97.51%\n",
"#8279: 97.51%\n",
"#8280: 97.51%\n",
"#8281: 97.51%\n",
"#8282: 97.51%\n",
"#8283: 97.51%\n",
"#8284: 97.51%\n",
"#8285: 97.51%\n",
"#8286: 97.51%\n",
"#8287: 97.51%\n",
"#8288: 97.51%\n",
"#8289: 97.52%\n",
"#8290: 97.52%\n",
"#8291: 97.52%\n",
"#8292: 97.52%\n",
"#8293: 97.52%\n",
"#8294: 97.52%\n",
"#8295: 97.52%\n",
"#8296: 97.52%\n",
"#8297: 97.52%\n",
"#8298: 97.52%\n",
"#8299: 97.52%\n",
"#8300: 97.52%\n",
"#8301: 97.52%\n",
"#8302: 97.52%\n",
"#8303: 97.52%\n",
"#8304: 97.52%\n",
"#8305: 97.52%\n",
"#8306: 97.52%\n",
"#8307: 97.52%\n",
"#8308: 97.52%\n",
"#8309: 97.52%\n",
"#8310: 97.52%\n",
"#8311: 97.52%\n",
"#8312: 97.52%\n",
"#8313: 97.52%\n",
"#8314: 97.52%\n",
"#8315: 97.52%\n",
"#8316: 97.51%\n",
"#8317: 97.51%\n",
"#8318: 97.51%\n",
"#8319: 97.51%\n",
"#8320: 97.51%\n",
"#8321: 97.51%\n",
"#8322: 97.50%\n",
"#8323: 97.50%\n",
"#8324: 97.50%\n",
"#8325: 97.49%\n",
"#8326: 97.49%\n",
"#8327: 97.49%\n",
"#8328: 97.49%\n",
"#8329: 97.49%\n",
"#8330: 97.49%\n",
"#8331: 97.49%\n",
"#8332: 97.49%\n",
"#8333: 97.49%\n",
"#8334: 97.49%\n",
"#8335: 97.49%\n",
"#8336: 97.49%\n",
"#8337: 97.49%\n",
"#8338: 97.49%\n",
"#8339: 97.49%\n",
"#8340: 97.49%\n",
"#8341: 97.49%\n",
"#8342: 97.49%\n",
"#8343: 97.50%\n",
"#8344: 97.50%\n",
"#8345: 97.50%\n",
"#8346: 97.50%\n",
"#8347: 97.50%\n",
"#8348: 97.50%\n",
"#8349: 97.50%\n",
"#8350: 97.50%\n",
"#8351: 97.50%\n",
"#8352: 97.50%\n",
"#8353: 97.49%\n",
"#8354: 97.49%\n",
"#8355: 97.49%\n",
"#8356: 97.49%\n",
"#8357: 97.49%\n",
"#8358: 97.49%\n",
"#8359: 97.49%\n",
"#8360: 97.49%\n",
"#8361: 97.49%\n",
"#8362: 97.49%\n",
"#8363: 97.49%\n",
"#8364: 97.49%\n",
"#8365: 97.49%\n",
"#8366: 97.49%\n",
"#8367: 97.49%\n",
"#8368: 97.49%\n",
"#8369: 97.49%\n",
"#8370: 97.49%\n",
"#8371: 97.49%\n",
"#8372: 97.49%\n",
"#8373: 97.49%\n",
"#8374: 97.49%\n",
"#8375: 97.48%\n",
"#8376: 97.48%\n",
"#8377: 97.48%\n",
"#8378: 97.48%\n",
"#8379: 97.48%\n",
"#8380: 97.48%\n",
"#8381: 97.48%\n",
"#8382: 97.48%\n",
"#8383: 97.48%\n",
"#8384: 97.48%\n",
"#8385: 97.48%\n",
"#8386: 97.48%\n",
"#8387: 97.48%\n",
"#8388: 97.48%\n",
"#8389: 97.49%\n",
"#8390: 97.49%\n",
"#8391: 97.49%\n",
"#8392: 97.49%\n",
"#8393: 97.49%\n",
"#8394: 97.49%\n",
"#8395: 97.49%\n",
"#8396: 97.49%\n",
"#8397: 97.49%\n",
"#8398: 97.49%\n",
"#8399: 97.49%\n",
"#8400: 97.49%\n",
"#8401: 97.49%\n",
"#8402: 97.49%\n",
"#8403: 97.49%\n",
"#8404: 97.49%\n",
"#8405: 97.49%\n",
"#8406: 97.49%\n",
"#8407: 97.49%\n",
"#8408: 97.48%\n",
"#8409: 97.48%\n",
"#8410: 97.47%\n",
"#8411: 97.47%\n",
"#8412: 97.47%\n",
"#8413: 97.47%\n",
"#8414: 97.47%\n",
"#8415: 97.47%\n",
"#8416: 97.47%\n",
"#8417: 97.47%\n",
"#8418: 97.47%\n",
"#8419: 97.47%\n",
"#8420: 97.47%\n",
"#8421: 97.47%\n",
"#8422: 97.47%\n",
"#8423: 97.47%\n",
"#8424: 97.47%\n",
"#8425: 97.47%\n",
"#8426: 97.47%\n",
"#8427: 97.47%\n",
"#8428: 97.47%\n",
"#8429: 97.47%\n",
"#8430: 97.47%\n",
"#8431: 97.47%\n",
"#8432: 97.47%\n",
"#8433: 97.47%\n",
"#8434: 97.47%\n",
"#8435: 97.48%\n",
"#8436: 97.48%\n",
"#8437: 97.48%\n",
"#8438: 97.48%\n",
"#8439: 97.48%\n",
"#8440: 97.48%\n",
"#8441: 97.48%\n",
"#8442: 97.48%\n",
"#8443: 97.48%\n",
"#8444: 97.48%\n",
"#8445: 97.48%\n",
"#8446: 97.48%\n",
"#8447: 97.48%\n",
"#8448: 97.48%\n",
"#8449: 97.48%\n",
"#8450: 97.48%\n",
"#8451: 97.48%\n",
"#8452: 97.48%\n",
"#8453: 97.48%\n",
"#8454: 97.48%\n",
"#8455: 97.48%\n",
"#8456: 97.48%\n",
"#8457: 97.48%\n",
"#8458: 97.48%\n",
"#8459: 97.48%\n",
"#8460: 97.48%\n",
"#8461: 97.48%\n",
"#8462: 97.48%\n",
"#8463: 97.48%\n",
"#8464: 97.48%\n",
"#8465: 97.48%\n",
"#8466: 97.48%\n",
"#8467: 97.48%\n",
"#8468: 97.48%\n",
"#8469: 97.49%\n",
"#8470: 97.49%\n",
"#8471: 97.49%\n",
"#8472: 97.49%\n",
"#8473: 97.49%\n",
"#8474: 97.49%\n",
"#8475: 97.49%\n",
"#8476: 97.49%\n",
"#8477: 97.49%\n",
"#8478: 97.49%\n",
"#8479: 97.49%\n",
"#8480: 97.49%\n",
"#8481: 97.49%\n",
"#8482: 97.49%\n",
"#8483: 97.49%\n",
"#8484: 97.49%\n",
"#8485: 97.49%\n",
"#8486: 97.49%\n",
"#8487: 97.49%\n",
"#8488: 97.49%\n",
"#8489: 97.49%\n",
"#8490: 97.49%\n",
"#8491: 97.49%\n",
"#8492: 97.49%\n",
"#8493: 97.49%\n",
"#8494: 97.49%\n",
"#8495: 97.49%\n",
"#8496: 97.49%\n",
"#8497: 97.49%\n",
"#8498: 97.49%\n",
"#8499: 97.49%\n",
"#8500: 97.49%\n",
"#8501: 97.49%\n",
"#8502: 97.50%\n",
"#8503: 97.50%\n",
"#8504: 97.50%\n",
"#8505: 97.50%\n",
"#8506: 97.50%\n",
"#8507: 97.50%\n",
"#8508: 97.50%\n",
"#8509: 97.50%\n",
"#8510: 97.50%\n",
"#8511: 97.50%\n",
"#8512: 97.50%\n",
"#8513: 97.50%\n",
"#8514: 97.50%\n",
"#8515: 97.50%\n",
"#8516: 97.50%\n",
"#8517: 97.50%\n",
"#8518: 97.50%\n",
"#8519: 97.50%\n",
"#8520: 97.50%\n",
"#8521: 97.50%\n",
"#8522: 97.49%\n",
"#8523: 97.49%\n",
"#8524: 97.49%\n",
"#8525: 97.49%\n",
"#8526: 97.49%\n",
"#8527: 97.49%\n",
"#8528: 97.49%\n",
"#8529: 97.49%\n",
"#8530: 97.49%\n",
"#8531: 97.49%\n",
"#8532: 97.49%\n",
"#8533: 97.49%\n",
"#8534: 97.49%\n",
"#8535: 97.49%\n",
"#8536: 97.49%\n",
"#8537: 97.49%\n",
"#8538: 97.49%\n",
"#8539: 97.49%\n",
"#8540: 97.49%\n",
"#8541: 97.49%\n",
"#8542: 97.50%\n",
"#8543: 97.50%\n",
"#8544: 97.50%\n",
"#8545: 97.50%\n",
"#8546: 97.50%\n",
"#8547: 97.50%\n",
"#8548: 97.50%\n",
"#8549: 97.50%\n",
"#8550: 97.50%\n",
"#8551: 97.50%\n",
"#8552: 97.50%\n",
"#8553: 97.50%\n",
"#8554: 97.50%\n",
"#8555: 97.50%\n",
"#8556: 97.50%\n",
"#8557: 97.50%\n",
"#8558: 97.50%\n",
"#8559: 97.50%\n",
"#8560: 97.50%\n",
"#8561: 97.50%\n",
"#8562: 97.50%\n",
"#8563: 97.50%\n",
"#8564: 97.50%\n",
"#8565: 97.50%\n",
"#8566: 97.50%\n",
"#8567: 97.50%\n",
"#8568: 97.50%\n",
"#8569: 97.50%\n",
"#8570: 97.50%\n",
"#8571: 97.50%\n",
"#8572: 97.50%\n",
"#8573: 97.50%\n",
"#8574: 97.50%\n",
"#8575: 97.50%\n",
"#8576: 97.50%\n",
"#8577: 97.51%\n",
"#8578: 97.51%\n",
"#8579: 97.51%\n",
"#8580: 97.51%\n",
"#8581: 97.51%\n",
"#8582: 97.51%\n",
"#8583: 97.51%\n",
"#8584: 97.51%\n",
"#8585: 97.51%\n",
"#8586: 97.51%\n",
"#8587: 97.51%\n",
"#8588: 97.51%\n",
"#8589: 97.51%\n",
"#8590: 97.51%\n",
"#8591: 97.51%\n",
"#8592: 97.51%\n",
"#8593: 97.51%\n",
"#8594: 97.51%\n",
"#8595: 97.51%\n",
"#8596: 97.51%\n",
"#8597: 97.51%\n",
"#8598: 97.51%\n",
"#8599: 97.51%\n",
"#8600: 97.51%\n",
"#8601: 97.51%\n",
"#8602: 97.51%\n",
"#8603: 97.51%\n",
"#8604: 97.51%\n",
"#8605: 97.51%\n",
"#8606: 97.51%\n",
"#8607: 97.51%\n",
"#8608: 97.51%\n",
"#8609: 97.51%\n",
"#8610: 97.51%\n",
"#8611: 97.52%\n",
"#8612: 97.52%\n",
"#8613: 97.52%\n",
"#8614: 97.52%\n",
"#8615: 97.52%\n",
"#8616: 97.52%\n",
"#8617: 97.52%\n",
"#8618: 97.52%\n",
"#8619: 97.52%\n",
"#8620: 97.52%\n",
"#8621: 97.52%\n",
"#8622: 97.52%\n",
"#8623: 97.52%\n",
"#8624: 97.52%\n",
"#8625: 97.52%\n",
"#8626: 97.52%\n",
"#8627: 97.52%\n",
"#8628: 97.52%\n",
"#8629: 97.52%\n",
"#8630: 97.52%\n",
"#8631: 97.52%\n",
"#8632: 97.52%\n",
"#8633: 97.52%\n",
"#8634: 97.52%\n",
"#8635: 97.52%\n",
"#8636: 97.52%\n",
"#8637: 97.52%\n",
"#8638: 97.52%\n",
"#8639: 97.52%\n",
"#8640: 97.52%\n",
"#8641: 97.52%\n",
"#8642: 97.52%\n",
"#8643: 97.52%\n",
"#8644: 97.52%\n",
"#8645: 97.52%\n",
"#8646: 97.53%\n",
"#8647: 97.53%\n",
"#8648: 97.53%\n",
"#8649: 97.53%\n",
"#8650: 97.53%\n",
"#8651: 97.53%\n",
"#8652: 97.53%\n",
"#8653: 97.53%\n",
"#8654: 97.53%\n",
"#8655: 97.53%\n",
"#8656: 97.53%\n",
"#8657: 97.53%\n",
"#8658: 97.53%\n",
"#8659: 97.53%\n",
"#8660: 97.53%\n",
"#8661: 97.53%\n",
"#8662: 97.53%\n",
"#8663: 97.53%\n",
"#8664: 97.53%\n",
"#8665: 97.53%\n",
"#8666: 97.53%\n",
"#8667: 97.53%\n",
"#8668: 97.53%\n",
"#8669: 97.53%\n",
"#8670: 97.53%\n",
"#8671: 97.53%\n",
"#8672: 97.53%\n",
"#8673: 97.53%\n",
"#8674: 97.53%\n",
"#8675: 97.53%\n",
"#8676: 97.53%\n",
"#8677: 97.53%\n",
"#8678: 97.53%\n",
"#8679: 97.53%\n",
"#8680: 97.53%\n",
"#8681: 97.54%\n",
"#8682: 97.54%\n",
"#8683: 97.54%\n",
"#8684: 97.54%\n",
"#8685: 97.54%\n",
"#8686: 97.54%\n",
"#8687: 97.54%\n",
"#8688: 97.54%\n",
"#8689: 97.54%\n",
"#8690: 97.54%\n",
"#8691: 97.54%\n",
"#8692: 97.54%\n",
"#8693: 97.54%\n",
"#8694: 97.54%\n",
"#8695: 97.54%\n",
"#8696: 97.54%\n",
"#8697: 97.54%\n",
"#8698: 97.54%\n",
"#8699: 97.54%\n",
"#8700: 97.54%\n",
"#8701: 97.54%\n",
"#8702: 97.54%\n",
"#8703: 97.54%\n",
"#8704: 97.54%\n",
"#8705: 97.54%\n",
"#8706: 97.54%\n",
"#8707: 97.54%\n",
"#8708: 97.54%\n",
"#8709: 97.54%\n",
"#8710: 97.54%\n",
"#8711: 97.54%\n",
"#8712: 97.54%\n",
"#8713: 97.54%\n",
"#8714: 97.54%\n",
"#8715: 97.54%\n",
"#8716: 97.55%\n",
"#8717: 97.55%\n",
"#8718: 97.55%\n",
"#8719: 97.55%\n",
"#8720: 97.55%\n",
"#8721: 97.55%\n",
"#8722: 97.55%\n",
"#8723: 97.55%\n",
"#8724: 97.55%\n",
"#8725: 97.55%\n",
"#8726: 97.55%\n",
"#8727: 97.55%\n",
"#8728: 97.55%\n",
"#8729: 97.55%\n",
"#8730: 97.55%\n",
"#8731: 97.55%\n",
"#8732: 97.55%\n",
"#8733: 97.55%\n",
"#8734: 97.55%\n",
"#8735: 97.55%\n",
"#8736: 97.55%\n",
"#8737: 97.55%\n",
"#8738: 97.55%\n",
"#8739: 97.55%\n",
"#8740: 97.55%\n",
"#8741: 97.55%\n",
"#8742: 97.55%\n",
"#8743: 97.55%\n",
"#8744: 97.55%\n",
"#8745: 97.55%\n",
"#8746: 97.55%\n",
"#8747: 97.55%\n",
"#8748: 97.55%\n",
"#8749: 97.55%\n",
"#8750: 97.55%\n",
"#8751: 97.55%\n",
"#8752: 97.56%\n",
"#8753: 97.56%\n",
"#8754: 97.56%\n",
"#8755: 97.56%\n",
"#8756: 97.56%\n",
"#8757: 97.56%\n",
"#8758: 97.56%\n",
"#8759: 97.56%\n",
"#8760: 97.56%\n",
"#8761: 97.56%\n",
"#8762: 97.56%\n",
"#8763: 97.56%\n",
"#8764: 97.56%\n",
"#8765: 97.56%\n",
"#8766: 97.56%\n",
"#8767: 97.56%\n",
"#8768: 97.56%\n",
"#8769: 97.56%\n",
"#8770: 97.56%\n",
"#8771: 97.56%\n",
"#8772: 97.56%\n",
"#8773: 97.56%\n",
"#8774: 97.56%\n",
"#8775: 97.56%\n",
"#8776: 97.56%\n",
"#8777: 97.56%\n",
"#8778: 97.56%\n",
"#8779: 97.56%\n",
"#8780: 97.56%\n",
"#8781: 97.56%\n",
"#8782: 97.56%\n",
"#8783: 97.56%\n",
"#8784: 97.56%\n",
"#8785: 97.56%\n",
"#8786: 97.56%\n",
"#8787: 97.56%\n",
"#8788: 97.57%\n",
"#8789: 97.57%\n",
"#8790: 97.57%\n",
"#8791: 97.57%\n",
"#8792: 97.57%\n",
"#8793: 97.57%\n",
"#8794: 97.57%\n",
"#8795: 97.57%\n",
"#8796: 97.57%\n",
"#8797: 97.57%\n",
"#8798: 97.57%\n",
"#8799: 97.57%\n",
"#8800: 97.57%\n",
"#8801: 97.57%\n",
"#8802: 97.57%\n",
"#8803: 97.57%\n",
"#8804: 97.57%\n",
"#8805: 97.57%\n",
"#8806: 97.57%\n",
"#8807: 97.57%\n",
"#8808: 97.57%\n",
"#8809: 97.57%\n",
"#8810: 97.57%\n",
"#8811: 97.57%\n",
"#8812: 97.57%\n",
"#8813: 97.57%\n",
"#8814: 97.57%\n",
"#8815: 97.57%\n",
"#8816: 97.57%\n",
"#8817: 97.57%\n",
"#8818: 97.57%\n",
"#8819: 97.57%\n",
"#8820: 97.57%\n",
"#8821: 97.57%\n",
"#8822: 97.57%\n",
"#8823: 97.57%\n",
"#8824: 97.58%\n",
"#8825: 97.58%\n",
"#8826: 97.58%\n",
"#8827: 97.58%\n",
"#8828: 97.58%\n",
"#8829: 97.58%\n",
"#8830: 97.58%\n",
"#8831: 97.58%\n",
"#8832: 97.58%\n",
"#8833: 97.58%\n",
"#8834: 97.58%\n",
"#8835: 97.58%\n",
"#8836: 97.58%\n",
"#8837: 97.58%\n",
"#8838: 97.58%\n",
"#8839: 97.58%\n",
"#8840: 97.58%\n",
"#8841: 97.58%\n",
"#8842: 97.58%\n",
"#8843: 97.58%\n",
"#8844: 97.58%\n",
"#8845: 97.58%\n",
"#8846: 97.58%\n",
"#8847: 97.58%\n",
"#8848: 97.58%\n",
"#8849: 97.58%\n",
"#8850: 97.58%\n",
"#8851: 97.58%\n",
"#8852: 97.58%\n",
"#8853: 97.58%\n",
"#8854: 97.58%\n",
"#8855: 97.58%\n",
"#8856: 97.58%\n",
"#8857: 97.58%\n",
"#8858: 97.58%\n",
"#8859: 97.58%\n",
"#8860: 97.58%\n",
"#8861: 97.59%\n",
"#8862: 97.59%\n",
"#8863: 97.59%\n",
"#8864: 97.59%\n",
"#8865: 97.59%\n",
"#8866: 97.59%\n",
"#8867: 97.59%\n",
"#8868: 97.59%\n",
"#8869: 97.59%\n",
"#8870: 97.59%\n",
"#8871: 97.59%\n",
"#8872: 97.59%\n",
"#8873: 97.59%\n",
"#8874: 97.59%\n",
"#8875: 97.59%\n",
"#8876: 97.59%\n",
"#8877: 97.59%\n",
"#8878: 97.59%\n",
"#8879: 97.59%\n",
"#8880: 97.59%\n",
"#8881: 97.59%\n",
"#8882: 97.59%\n",
"#8883: 97.59%\n",
"#8884: 97.59%\n",
"#8885: 97.59%\n",
"#8886: 97.59%\n",
"#8887: 97.59%\n",
"#8888: 97.59%\n",
"#8889: 97.59%\n",
"#8890: 97.59%\n",
"#8891: 97.59%\n",
"#8892: 97.59%\n",
"#8893: 97.59%\n",
"#8894: 97.59%\n",
"#8895: 97.59%\n",
"#8896: 97.59%\n",
"#8897: 97.59%\n",
"#8898: 97.60%\n",
"#8899: 97.60%\n",
"#8900: 97.60%\n",
"#8901: 97.60%\n",
"#8902: 97.60%\n",
"#8903: 97.60%\n",
"#8904: 97.60%\n",
"#8905: 97.60%\n",
"#8906: 97.60%\n",
"#8907: 97.60%\n",
"#8908: 97.60%\n",
"#8909: 97.60%\n",
"#8910: 97.60%\n",
"#8911: 97.60%\n",
"#8912: 97.60%\n",
"#8913: 97.60%\n",
"#8914: 97.60%\n",
"#8915: 97.60%\n",
"#8916: 97.60%\n",
"#8917: 97.60%\n",
"#8918: 97.60%\n",
"#8919: 97.60%\n",
"#8920: 97.60%\n",
"#8921: 97.60%\n",
"#8922: 97.60%\n",
"#8923: 97.60%\n",
"#8924: 97.60%\n",
"#8925: 97.60%\n",
"#8926: 97.60%\n",
"#8927: 97.60%\n",
"#8928: 97.60%\n",
"#8929: 97.60%\n",
"#8930: 97.60%\n",
"#8931: 97.60%\n",
"#8932: 97.60%\n",
"#8933: 97.60%\n",
"#8934: 97.60%\n",
"#8935: 97.61%\n",
"#8936: 97.61%\n",
"#8937: 97.61%\n",
"#8938: 97.61%\n",
"#8939: 97.61%\n",
"#8940: 97.61%\n",
"#8941: 97.61%\n",
"#8942: 97.61%\n",
"#8943: 97.61%\n",
"#8944: 97.61%\n",
"#8945: 97.61%\n",
"#8946: 97.61%\n",
"#8947: 97.61%\n",
"#8948: 97.61%\n",
"#8949: 97.61%\n",
"#8950: 97.61%\n",
"#8951: 97.61%\n",
"#8952: 97.61%\n",
"#8953: 97.61%\n",
"#8954: 97.61%\n",
"#8955: 97.61%\n",
"#8956: 97.61%\n",
"#8957: 97.61%\n",
"#8958: 97.61%\n",
"#8959: 97.61%\n",
"#8960: 97.61%\n",
"#8961: 97.61%\n",
"#8962: 97.61%\n",
"#8963: 97.61%\n",
"#8964: 97.61%\n",
"#8965: 97.61%\n",
"#8966: 97.61%\n",
"#8967: 97.61%\n",
"#8968: 97.61%\n",
"#8969: 97.61%\n",
"#8970: 97.61%\n",
"#8971: 97.61%\n",
"#8972: 97.62%\n",
"#8973: 97.62%\n",
"#8974: 97.62%\n",
"#8975: 97.62%\n",
"#8976: 97.62%\n",
"#8977: 97.62%\n",
"#8978: 97.62%\n",
"#8979: 97.62%\n",
"#8980: 97.62%\n",
"#8981: 97.62%\n",
"#8982: 97.62%\n",
"#8983: 97.62%\n",
"#8984: 97.62%\n",
"#8985: 97.62%\n",
"#8986: 97.62%\n",
"#8987: 97.62%\n",
"#8988: 97.62%\n",
"#8989: 97.62%\n",
"#8990: 97.62%\n",
"#8991: 97.62%\n",
"#8992: 97.62%\n",
"#8993: 97.62%\n",
"#8994: 97.62%\n",
"#8995: 97.62%\n",
"#8996: 97.62%\n",
"#8997: 97.62%\n",
"#8998: 97.62%\n",
"#8999: 97.62%\n",
"#9000: 97.62%\n",
"#9001: 97.62%\n",
"#9002: 97.62%\n",
"#9003: 97.62%\n",
"#9004: 97.62%\n",
"#9005: 97.62%\n",
"#9006: 97.62%\n",
"#9007: 97.62%\n",
"#9008: 97.62%\n",
"#9009: 97.61%\n",
"#9010: 97.61%\n",
"#9011: 97.61%\n",
"#9012: 97.61%\n",
"#9013: 97.61%\n",
"#9014: 97.62%\n",
"#9015: 97.60%\n",
"#9016: 97.60%\n",
"#9017: 97.60%\n",
"#9018: 97.61%\n",
"#9019: 97.59%\n",
"#9020: 97.59%\n",
"#9021: 97.59%\n",
"#9022: 97.60%\n",
"#9023: 97.60%\n",
"#9024: 97.58%\n",
"#9025: 97.58%\n",
"#9026: 97.59%\n",
"#9027: 97.59%\n",
"#9028: 97.59%\n",
"#9029: 97.59%\n",
"#9030: 97.59%\n",
"#9031: 97.59%\n",
"#9032: 97.59%\n",
"#9033: 97.59%\n",
"#9034: 97.59%\n",
"#9035: 97.59%\n",
"#9036: 97.58%\n",
"#9037: 97.58%\n",
"#9038: 97.58%\n",
"#9039: 97.58%\n",
"#9040: 97.58%\n",
"#9041: 97.58%\n",
"#9042: 97.58%\n",
"#9043: 97.58%\n",
"#9044: 97.58%\n",
"#9045: 97.58%\n",
"#9046: 97.58%\n",
"#9047: 97.58%\n",
"#9048: 97.58%\n",
"#9049: 97.58%\n",
"#9050: 97.58%\n",
"#9051: 97.58%\n",
"#9052: 97.58%\n",
"#9053: 97.58%\n",
"#9054: 97.58%\n",
"#9055: 97.58%\n",
"#9056: 97.58%\n",
"#9057: 97.58%\n",
"#9058: 97.58%\n",
"#9059: 97.58%\n",
"#9060: 97.58%\n",
"#9061: 97.58%\n",
"#9062: 97.58%\n",
"#9063: 97.58%\n",
"#9064: 97.58%\n",
"#9065: 97.58%\n",
"#9066: 97.58%\n",
"#9067: 97.58%\n",
"#9068: 97.59%\n",
"#9069: 97.59%\n",
"#9070: 97.59%\n",
"#9071: 97.57%\n",
"#9072: 97.58%\n",
"#9073: 97.58%\n",
"#9074: 97.58%\n",
"#9075: 97.58%\n",
"#9076: 97.58%\n",
"#9077: 97.58%\n",
"#9078: 97.58%\n",
"#9079: 97.58%\n",
"#9080: 97.58%\n",
"#9081: 97.58%\n",
"#9082: 97.58%\n",
"#9083: 97.58%\n",
"#9084: 97.58%\n",
"#9085: 97.58%\n",
"#9086: 97.58%\n",
"#9087: 97.58%\n",
"#9088: 97.58%\n",
"#9089: 97.58%\n",
"#9090: 97.58%\n",
"#9091: 97.58%\n",
"#9092: 97.58%\n",
"#9093: 97.58%\n",
"#9094: 97.58%\n",
"#9095: 97.58%\n",
"#9096: 97.58%\n",
"#9097: 97.58%\n",
"#9098: 97.58%\n",
"#9099: 97.58%\n",
"#9100: 97.58%\n",
"#9101: 97.58%\n",
"#9102: 97.58%\n",
"#9103: 97.58%\n",
"#9104: 97.58%\n",
"#9105: 97.58%\n",
"#9106: 97.58%\n",
"#9107: 97.58%\n",
"#9108: 97.58%\n",
"#9109: 97.59%\n",
"#9110: 97.59%\n",
"#9111: 97.59%\n",
"#9112: 97.59%\n",
"#9113: 97.59%\n",
"#9114: 97.59%\n",
"#9115: 97.59%\n",
"#9116: 97.59%\n",
"#9117: 97.59%\n",
"#9118: 97.59%\n",
"#9119: 97.59%\n",
"#9120: 97.59%\n",
"#9121: 97.59%\n",
"#9122: 97.59%\n",
"#9123: 97.59%\n",
"#9124: 97.59%\n",
"#9125: 97.59%\n",
"#9126: 97.59%\n",
"#9127: 97.59%\n",
"#9128: 97.59%\n",
"#9129: 97.59%\n",
"#9130: 97.59%\n",
"#9131: 97.59%\n",
"#9132: 97.59%\n",
"#9133: 97.59%\n",
"#9134: 97.59%\n",
"#9135: 97.59%\n",
"#9136: 97.59%\n",
"#9137: 97.59%\n",
"#9138: 97.59%\n",
"#9139: 97.59%\n",
"#9140: 97.59%\n",
"#9141: 97.59%\n",
"#9142: 97.59%\n",
"#9143: 97.59%\n",
"#9144: 97.59%\n",
"#9145: 97.59%\n",
"#9146: 97.59%\n",
"#9147: 97.60%\n",
"#9148: 97.60%\n",
"#9149: 97.60%\n",
"#9150: 97.60%\n",
"#9151: 97.60%\n",
"#9152: 97.60%\n",
"#9153: 97.60%\n",
"#9154: 97.60%\n",
"#9155: 97.60%\n",
"#9156: 97.60%\n",
"#9157: 97.60%\n",
"#9158: 97.60%\n",
"#9159: 97.60%\n",
"#9160: 97.60%\n",
"#9161: 97.60%\n",
"#9162: 97.60%\n",
"#9163: 97.60%\n",
"#9164: 97.60%\n",
"#9165: 97.60%\n",
"#9166: 97.60%\n",
"#9167: 97.60%\n",
"#9168: 97.60%\n",
"#9169: 97.60%\n",
"#9170: 97.60%\n",
"#9171: 97.60%\n",
"#9172: 97.60%\n",
"#9173: 97.60%\n",
"#9174: 97.60%\n",
"#9175: 97.60%\n",
"#9176: 97.60%\n",
"#9177: 97.60%\n",
"#9178: 97.60%\n",
"#9179: 97.60%\n",
"#9180: 97.60%\n",
"#9181: 97.60%\n",
"#9182: 97.60%\n",
"#9183: 97.60%\n",
"#9184: 97.60%\n",
"#9185: 97.61%\n",
"#9186: 97.61%\n",
"#9187: 97.61%\n",
"#9188: 97.61%\n",
"#9189: 97.61%\n",
"#9190: 97.61%\n",
"#9191: 97.61%\n",
"#9192: 97.61%\n",
"#9193: 97.61%\n",
"#9194: 97.61%\n",
"#9195: 97.61%\n",
"#9196: 97.61%\n",
"#9197: 97.61%\n",
"#9198: 97.61%\n",
"#9199: 97.61%\n",
"#9200: 97.61%\n",
"#9201: 97.61%\n",
"#9202: 97.60%\n",
"#9203: 97.60%\n",
"#9204: 97.60%\n",
"#9205: 97.60%\n",
"#9206: 97.60%\n",
"#9207: 97.60%\n",
"#9208: 97.60%\n",
"#9209: 97.60%\n",
"#9210: 97.60%\n",
"#9211: 97.60%\n",
"#9212: 97.60%\n",
"#9213: 97.60%\n",
"#9214: 97.60%\n",
"#9215: 97.60%\n",
"#9216: 97.60%\n",
"#9217: 97.60%\n",
"#9218: 97.60%\n",
"#9219: 97.60%\n",
"#9220: 97.60%\n",
"#9221: 97.60%\n",
"#9222: 97.60%\n",
"#9223: 97.60%\n",
"#9224: 97.60%\n",
"#9225: 97.60%\n",
"#9226: 97.60%\n",
"#9227: 97.61%\n",
"#9228: 97.61%\n",
"#9229: 97.61%\n",
"#9230: 97.61%\n",
"#9231: 97.61%\n",
"#9232: 97.61%\n",
"#9233: 97.61%\n",
"#9234: 97.61%\n",
"#9235: 97.61%\n",
"#9236: 97.61%\n",
"#9237: 97.61%\n",
"#9238: 97.61%\n",
"#9239: 97.61%\n",
"#9240: 97.61%\n",
"#9241: 97.61%\n",
"#9242: 97.61%\n",
"#9243: 97.61%\n",
"#9244: 97.61%\n",
"#9245: 97.61%\n",
"#9246: 97.61%\n",
"#9247: 97.61%\n",
"#9248: 97.61%\n",
"#9249: 97.61%\n",
"#9250: 97.61%\n",
"#9251: 97.61%\n",
"#9252: 97.61%\n",
"#9253: 97.61%\n",
"#9254: 97.61%\n",
"#9255: 97.61%\n",
"#9256: 97.61%\n",
"#9257: 97.61%\n",
"#9258: 97.61%\n",
"#9259: 97.61%\n",
"#9260: 97.61%\n",
"#9261: 97.61%\n",
"#9262: 97.61%\n",
"#9263: 97.61%\n",
"#9264: 97.61%\n",
"#9265: 97.61%\n",
"#9266: 97.62%\n",
"#9267: 97.62%\n",
"#9268: 97.62%\n",
"#9269: 97.62%\n",
"#9270: 97.62%\n",
"#9271: 97.62%\n",
"#9272: 97.62%\n",
"#9273: 97.62%\n",
"#9274: 97.62%\n",
"#9275: 97.62%\n",
"#9276: 97.62%\n",
"#9277: 97.62%\n",
"#9278: 97.62%\n",
"#9279: 97.62%\n",
"#9280: 97.62%\n",
"#9281: 97.62%\n",
"#9282: 97.62%\n",
"#9283: 97.62%\n",
"#9284: 97.62%\n",
"#9285: 97.62%\n",
"#9286: 97.62%\n",
"#9287: 97.62%\n",
"#9288: 97.62%\n",
"#9289: 97.62%\n",
"#9290: 97.62%\n",
"#9291: 97.62%\n",
"#9292: 97.62%\n",
"#9293: 97.62%\n",
"#9294: 97.62%\n",
"#9295: 97.62%\n",
"#9296: 97.62%\n",
"#9297: 97.62%\n",
"#9298: 97.62%\n",
"#9299: 97.62%\n",
"#9300: 97.62%\n",
"#9301: 97.62%\n",
"#9302: 97.62%\n",
"#9303: 97.62%\n",
"#9304: 97.62%\n",
"#9305: 97.63%\n",
"#9306: 97.63%\n",
"#9307: 97.63%\n",
"#9308: 97.63%\n",
"#9309: 97.63%\n",
"#9310: 97.63%\n",
"#9311: 97.63%\n",
"#9312: 97.63%\n",
"#9313: 97.63%\n",
"#9314: 97.63%\n",
"#9315: 97.63%\n",
"#9316: 97.63%\n",
"#9317: 97.63%\n",
"#9318: 97.63%\n",
"#9319: 97.63%\n",
"#9320: 97.63%\n",
"#9321: 97.63%\n",
"#9322: 97.63%\n",
"#9323: 97.63%\n",
"#9324: 97.63%\n",
"#9325: 97.63%\n",
"#9326: 97.63%\n",
"#9327: 97.63%\n",
"#9328: 97.63%\n",
"#9329: 97.63%\n",
"#9330: 97.63%\n",
"#9331: 97.63%\n",
"#9332: 97.63%\n",
"#9333: 97.63%\n",
"#9334: 97.63%\n",
"#9335: 97.63%\n",
"#9336: 97.63%\n",
"#9337: 97.63%\n",
"#9338: 97.63%\n",
"#9339: 97.63%\n",
"#9340: 97.63%\n",
"#9341: 97.63%\n",
"#9342: 97.63%\n",
"#9343: 97.63%\n",
"#9344: 97.64%\n",
"#9345: 97.64%\n",
"#9346: 97.64%\n",
"#9347: 97.64%\n",
"#9348: 97.64%\n",
"#9349: 97.64%\n",
"#9350: 97.64%\n",
"#9351: 97.64%\n",
"#9352: 97.64%\n",
"#9353: 97.64%\n",
"#9354: 97.64%\n",
"#9355: 97.64%\n",
"#9356: 97.64%\n",
"#9357: 97.64%\n",
"#9358: 97.64%\n",
"#9359: 97.64%\n",
"#9360: 97.64%\n",
"#9361: 97.64%\n",
"#9362: 97.64%\n",
"#9363: 97.64%\n",
"#9364: 97.64%\n",
"#9365: 97.64%\n",
"#9366: 97.64%\n",
"#9367: 97.64%\n",
"#9368: 97.64%\n",
"#9369: 97.64%\n",
"#9370: 97.64%\n",
"#9371: 97.64%\n",
"#9372: 97.64%\n",
"#9373: 97.64%\n",
"#9374: 97.64%\n",
"#9375: 97.64%\n",
"#9376: 97.64%\n",
"#9377: 97.64%\n",
"#9378: 97.64%\n",
"#9379: 97.64%\n",
"#9380: 97.64%\n",
"#9381: 97.64%\n",
"#9382: 97.64%\n",
"#9383: 97.64%\n",
"#9384: 97.65%\n",
"#9385: 97.65%\n",
"#9386: 97.65%\n",
"#9387: 97.65%\n",
"#9388: 97.65%\n",
"#9389: 97.65%\n",
"#9390: 97.65%\n",
"#9391: 97.65%\n",
"#9392: 97.65%\n",
"#9393: 97.65%\n",
"#9394: 97.65%\n",
"#9395: 97.65%\n",
"#9396: 97.65%\n",
"#9397: 97.65%\n",
"#9398: 97.65%\n",
"#9399: 97.65%\n",
"#9400: 97.65%\n",
"#9401: 97.65%\n",
"#9402: 97.65%\n",
"#9403: 97.65%\n",
"#9404: 97.65%\n",
"#9405: 97.65%\n",
"#9406: 97.65%\n",
"#9407: 97.65%\n",
"#9408: 97.65%\n",
"#9409: 97.65%\n",
"#9410: 97.65%\n",
"#9411: 97.65%\n",
"#9412: 97.65%\n",
"#9413: 97.65%\n",
"#9414: 97.65%\n",
"#9415: 97.65%\n",
"#9416: 97.65%\n",
"#9417: 97.65%\n",
"#9418: 97.65%\n",
"#9419: 97.65%\n",
"#9420: 97.65%\n",
"#9421: 97.65%\n",
"#9422: 97.65%\n",
"#9423: 97.65%\n",
"#9424: 97.66%\n",
"#9425: 97.66%\n",
"#9426: 97.66%\n",
"#9427: 97.66%\n",
"#9428: 97.66%\n",
"#9429: 97.66%\n",
"#9430: 97.66%\n",
"#9431: 97.66%\n",
"#9432: 97.66%\n",
"#9433: 97.66%\n",
"#9434: 97.66%\n",
"#9435: 97.66%\n",
"#9436: 97.66%\n",
"#9437: 97.66%\n",
"#9438: 97.66%\n",
"#9439: 97.66%\n",
"#9440: 97.66%\n",
"#9441: 97.66%\n",
"#9442: 97.66%\n",
"#9443: 97.66%\n",
"#9444: 97.66%\n",
"#9445: 97.66%\n",
"#9446: 97.66%\n",
"#9447: 97.66%\n",
"#9448: 97.66%\n",
"#9449: 97.66%\n",
"#9450: 97.66%\n",
"#9451: 97.66%\n",
"#9452: 97.66%\n",
"#9453: 97.66%\n",
"#9454: 97.66%\n",
"#9455: 97.66%\n",
"#9456: 97.66%\n",
"#9457: 97.66%\n",
"#9458: 97.66%\n",
"#9459: 97.66%\n",
"#9460: 97.66%\n",
"#9461: 97.66%\n",
"#9462: 97.66%\n",
"#9463: 97.66%\n",
"#9464: 97.67%\n",
"#9465: 97.67%\n",
"#9466: 97.67%\n",
"#9467: 97.67%\n",
"#9468: 97.67%\n",
"#9469: 97.67%\n",
"#9470: 97.67%\n",
"#9471: 97.67%\n",
"#9472: 97.67%\n",
"#9473: 97.67%\n",
"#9474: 97.67%\n",
"#9475: 97.67%\n",
"#9476: 97.67%\n",
"#9477: 97.67%\n",
"#9478: 97.67%\n",
"#9479: 97.67%\n",
"#9480: 97.67%\n",
"#9481: 97.67%\n",
"#9482: 97.67%\n",
"#9483: 97.67%\n",
"#9484: 97.67%\n",
"#9485: 97.67%\n",
"#9486: 97.67%\n",
"#9487: 97.67%\n",
"#9488: 97.67%\n",
"#9489: 97.67%\n",
"#9490: 97.67%\n",
"#9491: 97.67%\n",
"#9492: 97.67%\n",
"#9493: 97.67%\n",
"#9494: 97.67%\n",
"#9495: 97.67%\n",
"#9496: 97.67%\n",
"#9497: 97.67%\n",
"#9498: 97.67%\n",
"#9499: 97.67%\n",
"#9500: 97.67%\n",
"#9501: 97.67%\n",
"#9502: 97.67%\n",
"#9503: 97.67%\n",
"#9504: 97.67%\n",
"#9505: 97.68%\n",
"#9506: 97.68%\n",
"#9507: 97.68%\n",
"#9508: 97.68%\n",
"#9509: 97.68%\n",
"#9510: 97.68%\n",
"#9511: 97.68%\n",
"#9512: 97.68%\n",
"#9513: 97.68%\n",
"#9514: 97.68%\n",
"#9515: 97.68%\n",
"#9516: 97.68%\n",
"#9517: 97.68%\n",
"#9518: 97.68%\n",
"#9519: 97.68%\n",
"#9520: 97.68%\n",
"#9521: 97.68%\n",
"#9522: 97.68%\n",
"#9523: 97.68%\n",
"#9524: 97.68%\n",
"#9525: 97.68%\n",
"#9526: 97.68%\n",
"#9527: 97.68%\n",
"#9528: 97.68%\n",
"#9529: 97.68%\n",
"#9530: 97.67%\n",
"#9531: 97.67%\n",
"#9532: 97.67%\n",
"#9533: 97.67%\n",
"#9534: 97.67%\n",
"#9535: 97.67%\n",
"#9536: 97.67%\n",
"#9537: 97.67%\n",
"#9538: 97.67%\n",
"#9539: 97.67%\n",
"#9540: 97.66%\n",
"#9541: 97.66%\n",
"#9542: 97.66%\n",
"#9543: 97.66%\n",
"#9544: 97.66%\n",
"#9545: 97.66%\n",
"#9546: 97.66%\n",
"#9547: 97.66%\n",
"#9548: 97.66%\n",
"#9549: 97.66%\n",
"#9550: 97.67%\n",
"#9551: 97.67%\n",
"#9552: 97.67%\n",
"#9553: 97.67%\n",
"#9554: 97.67%\n",
"#9555: 97.67%\n",
"#9556: 97.67%\n",
"#9557: 97.67%\n",
"#9558: 97.67%\n",
"#9559: 97.67%\n",
"#9560: 97.67%\n",
"#9561: 97.67%\n",
"#9562: 97.67%\n",
"#9563: 97.67%\n",
"#9564: 97.67%\n",
"#9565: 97.67%\n",
"#9566: 97.67%\n",
"#9567: 97.67%\n",
"#9568: 97.67%\n",
"#9569: 97.67%\n",
"#9570: 97.67%\n",
"#9571: 97.67%\n",
"#9572: 97.67%\n",
"#9573: 97.67%\n",
"#9574: 97.67%\n",
"#9575: 97.67%\n",
"#9576: 97.67%\n",
"#9577: 97.67%\n",
"#9578: 97.67%\n",
"#9579: 97.67%\n",
"#9580: 97.67%\n",
"#9581: 97.67%\n",
"#9582: 97.67%\n",
"#9583: 97.67%\n",
"#9584: 97.67%\n",
"#9585: 97.67%\n",
"#9586: 97.67%\n",
"#9587: 97.66%\n",
"#9588: 97.66%\n",
"#9589: 97.66%\n",
"#9590: 97.66%\n",
"#9591: 97.66%\n",
"#9592: 97.66%\n",
"#9593: 97.67%\n",
"#9594: 97.67%\n",
"#9595: 97.67%\n",
"#9596: 97.67%\n",
"#9597: 97.67%\n",
"#9598: 97.67%\n",
"#9599: 97.67%\n",
"#9600: 97.67%\n",
"#9601: 97.67%\n",
"#9602: 97.67%\n",
"#9603: 97.67%\n",
"#9604: 97.67%\n",
"#9605: 97.67%\n",
"#9606: 97.67%\n",
"#9607: 97.67%\n",
"#9608: 97.67%\n",
"#9609: 97.67%\n",
"#9610: 97.67%\n",
"#9611: 97.67%\n",
"#9612: 97.67%\n",
"#9613: 97.67%\n",
"#9614: 97.66%\n",
"#9615: 97.66%\n",
"#9616: 97.66%\n",
"#9617: 97.66%\n",
"#9618: 97.66%\n",
"#9619: 97.66%\n",
"#9620: 97.66%\n",
"#9621: 97.66%\n",
"#9622: 97.66%\n",
"#9623: 97.66%\n",
"#9624: 97.66%\n",
"#9625: 97.66%\n",
"#9626: 97.66%\n",
"#9627: 97.66%\n",
"#9628: 97.66%\n",
"#9629: 97.66%\n",
"#9630: 97.66%\n",
"#9631: 97.66%\n",
"#9632: 97.66%\n",
"#9633: 97.66%\n",
"#9634: 97.66%\n",
"#9635: 97.67%\n",
"#9636: 97.67%\n",
"#9637: 97.67%\n",
"#9638: 97.67%\n",
"#9639: 97.67%\n",
"#9640: 97.67%\n",
"#9641: 97.67%\n",
"#9642: 97.66%\n",
"#9643: 97.66%\n",
"#9644: 97.66%\n",
"#9645: 97.66%\n",
"#9646: 97.66%\n",
"#9647: 97.66%\n",
"#9648: 97.66%\n",
"#9649: 97.66%\n",
"#9650: 97.66%\n",
"#9651: 97.66%\n",
"#9652: 97.66%\n",
"#9653: 97.66%\n",
"#9654: 97.66%\n",
"#9655: 97.66%\n",
"#9656: 97.66%\n",
"#9657: 97.66%\n",
"#9658: 97.66%\n",
"#9659: 97.66%\n",
"#9660: 97.66%\n",
"#9661: 97.66%\n",
"#9662: 97.66%\n",
"#9663: 97.66%\n",
"#9664: 97.66%\n",
"#9665: 97.66%\n",
"#9666: 97.66%\n",
"#9667: 97.66%\n",
"#9668: 97.66%\n",
"#9669: 97.66%\n",
"#9670: 97.66%\n",
"#9671: 97.66%\n",
"#9672: 97.66%\n",
"#9673: 97.66%\n",
"#9674: 97.66%\n",
"#9675: 97.66%\n",
"#9676: 97.66%\n",
"#9677: 97.66%\n",
"#9678: 97.67%\n",
"#9679: 97.67%\n",
"#9680: 97.67%\n",
"#9681: 97.67%\n",
"#9682: 97.67%\n",
"#9683: 97.67%\n",
"#9684: 97.67%\n",
"#9685: 97.67%\n",
"#9686: 97.67%\n",
"#9687: 97.67%\n",
"#9688: 97.67%\n",
"#9689: 97.67%\n",
"#9690: 97.67%\n",
"#9691: 97.67%\n",
"#9692: 97.67%\n",
"#9693: 97.67%\n",
"#9694: 97.67%\n",
"#9695: 97.67%\n",
"#9696: 97.67%\n",
"#9697: 97.67%\n",
"#9698: 97.66%\n",
"#9699: 97.66%\n",
"#9700: 97.66%\n",
"#9701: 97.66%\n",
"#9702: 97.66%\n",
"#9703: 97.66%\n",
"#9704: 97.66%\n",
"#9705: 97.66%\n",
"#9706: 97.66%\n",
"#9707: 97.66%\n",
"#9708: 97.66%\n",
"#9709: 97.66%\n",
"#9710: 97.66%\n",
"#9711: 97.66%\n",
"#9712: 97.66%\n",
"#9713: 97.66%\n",
"#9714: 97.66%\n",
"#9715: 97.66%\n",
"#9716: 97.66%\n",
"#9717: 97.66%\n",
"#9718: 97.66%\n",
"#9719: 97.66%\n",
"#9720: 97.66%\n",
"#9721: 97.67%\n",
"#9722: 97.67%\n",
"#9723: 97.67%\n",
"#9724: 97.67%\n",
"#9725: 97.67%\n",
"#9726: 97.67%\n",
"#9727: 97.67%\n",
"#9728: 97.67%\n",
"#9729: 97.66%\n",
"#9730: 97.66%\n",
"#9731: 97.66%\n",
"#9732: 97.66%\n",
"#9733: 97.66%\n",
"#9734: 97.66%\n",
"#9735: 97.66%\n",
"#9736: 97.66%\n",
"#9737: 97.66%\n",
"#9738: 97.66%\n",
"#9739: 97.66%\n",
"#9740: 97.66%\n",
"#9741: 97.66%\n",
"#9742: 97.66%\n",
"#9743: 97.66%\n",
"#9744: 97.66%\n",
"#9745: 97.65%\n",
"#9746: 97.65%\n",
"#9747: 97.65%\n",
"#9748: 97.65%\n",
"#9749: 97.65%\n",
"#9750: 97.65%\n",
"#9751: 97.65%\n",
"#9752: 97.65%\n",
"#9753: 97.65%\n",
"#9754: 97.65%\n",
"#9755: 97.65%\n",
"#9756: 97.65%\n",
"#9757: 97.65%\n",
"#9758: 97.65%\n",
"#9759: 97.65%\n",
"#9760: 97.65%\n",
"#9761: 97.65%\n",
"#9762: 97.64%\n",
"#9763: 97.64%\n",
"#9764: 97.64%\n",
"#9765: 97.64%\n",
"#9766: 97.65%\n",
"#9767: 97.65%\n",
"#9768: 97.64%\n",
"#9769: 97.64%\n",
"#9770: 97.63%\n",
"#9771: 97.63%\n",
"#9772: 97.63%\n",
"#9773: 97.63%\n",
"#9774: 97.63%\n",
"#9775: 97.63%\n",
"#9776: 97.63%\n",
"#9777: 97.63%\n",
"#9778: 97.63%\n",
"#9779: 97.63%\n",
"#9780: 97.63%\n",
"#9781: 97.63%\n",
"#9782: 97.62%\n",
"#9783: 97.62%\n",
"#9784: 97.62%\n",
"#9785: 97.62%\n",
"#9786: 97.62%\n",
"#9787: 97.62%\n",
"#9788: 97.62%\n",
"#9789: 97.62%\n",
"#9790: 97.62%\n",
"#9791: 97.62%\n",
"#9792: 97.61%\n",
"#9793: 97.61%\n",
"#9794: 97.61%\n",
"#9795: 97.61%\n",
"#9796: 97.61%\n",
"#9797: 97.61%\n",
"#9798: 97.61%\n",
"#9799: 97.61%\n",
"#9800: 97.61%\n",
"#9801: 97.61%\n",
"#9802: 97.61%\n",
"#9803: 97.61%\n",
"#9804: 97.61%\n",
"#9805: 97.61%\n",
"#9806: 97.61%\n",
"#9807: 97.61%\n",
"#9808: 97.61%\n",
"#9809: 97.61%\n",
"#9810: 97.61%\n",
"#9811: 97.60%\n",
"#9812: 97.61%\n",
"#9813: 97.61%\n",
"#9814: 97.61%\n",
"#9815: 97.61%\n",
"#9816: 97.61%\n",
"#9817: 97.61%\n",
"#9818: 97.61%\n",
"#9819: 97.61%\n",
"#9820: 97.61%\n",
"#9821: 97.61%\n",
"#9822: 97.61%\n",
"#9823: 97.61%\n",
"#9824: 97.61%\n",
"#9825: 97.61%\n",
"#9826: 97.61%\n",
"#9827: 97.61%\n",
"#9828: 97.61%\n",
"#9829: 97.61%\n",
"#9830: 97.61%\n",
"#9831: 97.61%\n",
"#9832: 97.61%\n",
"#9833: 97.61%\n",
"#9834: 97.61%\n",
"#9835: 97.61%\n",
"#9836: 97.61%\n",
"#9837: 97.61%\n",
"#9838: 97.61%\n",
"#9839: 97.60%\n",
"#9840: 97.60%\n",
"#9841: 97.60%\n",
"#9842: 97.60%\n",
"#9843: 97.60%\n",
"#9844: 97.60%\n",
"#9845: 97.60%\n",
"#9846: 97.60%\n",
"#9847: 97.60%\n",
"#9848: 97.60%\n",
"#9849: 97.60%\n",
"#9850: 97.60%\n",
"#9851: 97.60%\n",
"#9852: 97.60%\n",
"#9853: 97.61%\n",
"#9854: 97.61%\n",
"#9855: 97.61%\n",
"#9856: 97.60%\n",
"#9857: 97.60%\n",
"#9858: 97.60%\n",
"#9859: 97.60%\n",
"#9860: 97.60%\n",
"#9861: 97.60%\n",
"#9862: 97.60%\n",
"#9863: 97.60%\n",
"#9864: 97.60%\n",
"#9865: 97.60%\n",
"#9866: 97.60%\n",
"#9867: 97.59%\n",
"#9868: 97.59%\n",
"#9869: 97.59%\n",
"#9870: 97.59%\n",
"#9871: 97.59%\n",
"#9872: 97.59%\n",
"#9873: 97.59%\n",
"#9874: 97.59%\n",
"#9875: 97.59%\n",
"#9876: 97.59%\n",
"#9877: 97.59%\n",
"#9878: 97.59%\n",
"#9879: 97.59%\n",
"#9880: 97.59%\n",
"#9881: 97.59%\n",
"#9882: 97.59%\n",
"#9883: 97.59%\n",
"#9884: 97.59%\n",
"#9885: 97.59%\n",
"#9886: 97.59%\n",
"#9887: 97.59%\n",
"#9888: 97.59%\n",
"#9889: 97.59%\n",
"#9890: 97.59%\n",
"#9891: 97.59%\n",
"#9892: 97.58%\n",
"#9893: 97.57%\n",
"#9894: 97.57%\n",
"#9895: 97.57%\n",
"#9896: 97.58%\n",
"#9897: 97.58%\n",
"#9898: 97.58%\n",
"#9899: 97.58%\n",
"#9900: 97.58%\n",
"#9901: 97.58%\n",
"#9902: 97.58%\n",
"#9903: 97.58%\n",
"#9904: 97.58%\n",
"#9905: 97.57%\n",
"#9906: 97.57%\n",
"#9907: 97.57%\n",
"#9908: 97.57%\n",
"#9909: 97.57%\n",
"#9910: 97.57%\n",
"#9911: 97.57%\n",
"#9912: 97.57%\n",
"#9913: 97.57%\n",
"#9914: 97.57%\n",
"#9915: 97.57%\n",
"#9916: 97.57%\n",
"#9917: 97.57%\n",
"#9918: 97.57%\n",
"#9919: 97.57%\n",
"#9920: 97.57%\n",
"#9921: 97.57%\n",
"#9922: 97.57%\n",
"#9923: 97.57%\n",
"#9924: 97.57%\n",
"#9925: 97.57%\n",
"#9926: 97.57%\n",
"#9927: 97.57%\n",
"#9928: 97.57%\n",
"#9929: 97.57%\n",
"#9930: 97.57%\n",
"#9931: 97.57%\n",
"#9932: 97.57%\n",
"#9933: 97.57%\n",
"#9934: 97.57%\n",
"#9935: 97.57%\n",
"#9936: 97.57%\n",
"#9937: 97.57%\n",
"#9938: 97.58%\n",
"#9939: 97.58%\n",
"#9940: 97.58%\n",
"#9941: 97.58%\n",
"#9942: 97.57%\n",
"#9943: 97.57%\n",
"#9944: 97.57%\n",
"#9945: 97.57%\n",
"#9946: 97.57%\n",
"#9947: 97.57%\n",
"#9948: 97.57%\n",
"#9949: 97.57%\n",
"#9950: 97.57%\n",
"#9951: 97.57%\n",
"#9952: 97.57%\n",
"#9953: 97.57%\n",
"#9954: 97.57%\n",
"#9955: 97.57%\n",
"#9956: 97.57%\n",
"#9957: 97.57%\n",
"#9958: 97.57%\n",
"#9959: 97.57%\n",
"#9960: 97.57%\n",
"#9961: 97.57%\n",
"#9962: 97.57%\n",
"#9963: 97.57%\n",
"#9964: 97.57%\n",
"#9965: 97.57%\n",
"#9966: 97.57%\n",
"#9967: 97.57%\n",
"#9968: 97.57%\n",
"#9969: 97.57%\n",
"#9970: 97.57%\n",
"#9971: 97.57%\n",
"#9972: 97.57%\n",
"#9973: 97.57%\n",
"#9974: 97.57%\n",
"#9975: 97.57%\n",
"#9976: 97.57%\n",
"#9977: 97.57%\n",
"#9978: 97.57%\n",
"#9979: 97.58%\n",
"#9980: 97.58%\n",
"#9981: 97.58%\n",
"#9982: 97.57%\n",
"#9983: 97.57%\n",
"#9984: 97.57%\n",
"#9985: 97.57%\n",
"#9986: 97.57%\n",
"#9987: 97.57%\n",
"#9988: 97.57%\n",
"#9989: 97.57%\n",
"#9990: 97.57%\n",
"#9991: 97.57%\n",
"#9992: 97.57%\n",
"#9993: 97.57%\n",
"#9994: 97.57%\n",
"#9995: 97.57%\n",
"#9996: 97.57%\n",
"#9997: 97.57%\n",
"#9998: 97.57%\n",
"#9999: 97.57%\n"
]
}
],
"source": [
"correct = 0\n",
"for i in range(10000):\n",
" with open(f\"X_test/{i}.json\", \"r\") as f:\n",
" input = json.load(f)\n",
" out, _ = inference(input, circuit)\n",
" correct += 1 if out[0] == y_test[i] else 0\n",
" print(f\"#{i}: {correct / (i + 1) * 100:.2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/keras2circom |
test/circuit.js | const chai = require('chai');
const fs = require('fs');
const wasm_tester = require('circom_tester').wasm;
const F1Field = require('ffjavascript').F1Field;
const Scalar = require('ffjavascript').Scalar;
exports.p = Scalar.fromString('21888242871839275222246405745257275088548364400416034343698204186575808495617');
const Fr = new F1Field(exports.p);
const assert = chai.assert;
const exec = require('await-exec');
const input = require('../test/X_test/0.json');
describe('keras2circom test', function () {
this.timeout(100000000);
describe('softmax output', async () => {
it('softmax output test', async () => {
await exec('python main.py models/model.h5 && python output/circuit.py output/circuit.json test/X_test/0.json');
const model = JSON.parse(fs.readFileSync('./output/circuit.json'));
const output = JSON.parse(fs.readFileSync('./output/output.json'));
const INPUT = {...model, ...input, ...output};
const circuit = await wasm_tester('./output/circuit.circom');
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
assert(Fr.eq(Fr.e(witness[1]),Fr.e(7)));
});
});
describe('raw output', async () => {
it('raw output test', async () => {
await exec('python main.py models/model.h5 --raw && python output/circuit.py output/circuit.json test/X_test/0.json');
const model = JSON.parse(fs.readFileSync('./output/circuit.json'));
const output = JSON.parse(fs.readFileSync('./output/output.json'));
const INPUT = {...model, ...input, ...output};
const circuit = await wasm_tester('./output/circuit.circom');
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
});
}); | https://github.com/socathie/keras2circom |
test/load_input.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.datasets import mnist\n",
"import json\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# load MNIST dataset\n",
"_, (X_test, y_test) = mnist.load_data()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"#normalizing\n",
"X_test = X_test.astype('float32')\n",
"X_test /= 255.0"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"for i in range(len(X_test)):\n",
" X = [str(int(x * float(10**18))) for x in X_test[i].flatten().tolist()]\n",
" X = np.array(X).reshape(28, 28, 1).tolist()\n",
" with open(f'X_test/{i}.json', 'w') as f:\n",
" json.dump({\"in\": X}, f)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"with open('y_test.json', 'w') as f:\n",
" json.dump(y_test.tolist(), f)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/keras2circom |
circuits/ArgMax.circom | // from 0xZKML/zk-mnist
pragma circom 2.0.0;
include "./circomlib/comparators.circom";
include "./circomlib/switcher.circom";
template ArgMax (n) {
signal input in[n];
signal input out;
assert (out < n);
component gts[n]; // store comparators
component switchers[n+1]; // switcher for comparing maxs
component aswitchers[n+1]; // switcher for arg max
signal maxs[n+1];
signal amaxs[n+1];
maxs[0] <== in[0];
amaxs[0] <== 0;
for(var i = 0; i < n; i++) {
gts[i] = GreaterThan(252); // changed to 252 (maximum) for better compatibility
switchers[i+1] = Switcher();
aswitchers[i+1] = Switcher();
gts[i].in[1] <== maxs[i];
gts[i].in[0] <== in[i];
switchers[i+1].sel <== gts[i].out;
switchers[i+1].L <== maxs[i];
switchers[i+1].R <== in[i];
aswitchers[i+1].sel <== gts[i].out;
aswitchers[i+1].L <== amaxs[i];
aswitchers[i+1].R <== i;
amaxs[i+1] <== aswitchers[i+1].outL;
maxs[i+1] <== switchers[i+1].outL;
}
out === amaxs[n];
}
// component main { public [ out ] } = ArgMax(5);
/* INPUT = {
"in": ["2","3","1","5","4"],
"out": "3"
} */ | https://github.com/socathie/circomlib-ml |
circuits/AveragePooling2D.circom | pragma circom 2.0.0;
include "./SumPooling2D.circom";
// AveragePooling2D layer, poolSize is required to be equal for both dimensions, might lose precision compared to SumPooling2D
template AveragePooling2D (nRows, nCols, nChannels, poolSize, strides) {
signal input in[nRows][nCols][nChannels];
signal input out[(nRows-poolSize)\strides+1][(nCols-poolSize)\strides+1][nChannels];
signal input remainder[(nRows-poolSize)\strides+1][(nCols-poolSize)\strides+1][nChannels];
component sumPooling2D = SumPooling2D (nRows, nCols, nChannels, poolSize, strides);
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
for (var k=0; k<nChannels; k++) {
sumPooling2D.in[i][j][k] <== in[i][j][k];
}
}
}
for (var i=0; i<(nRows-poolSize)\strides+1; i++) {
for (var j=0; j<(nCols-poolSize)\strides+1; j++) {
for (var k=0; k<nChannels; k++) {
assert(remainder[i][j][k] < poolSize * poolSize);
out[i][j][k] * poolSize * poolSize + remainder[i][j][k] === sumPooling2D.out[i][j][k];
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/BatchNormalization2D.circom | pragma circom 2.0.0;
// BatchNormalization layer for 2D inputs
// a = gamma/(moving_var+epsilon)**.5
// b = beta-gamma*moving_mean/(moving_var+epsilon)**.5
// n = 10 to the power of the number of decimal places
template BatchNormalization2D(nRows, nCols, nChannels, n) {
signal input in[nRows][nCols][nChannels];
signal input a[nChannels];
signal input b[nChannels];
signal input out[nRows][nCols][nChannels];
signal input remainder[nRows][nCols][nChannels];
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
for (var k=0; k<nChannels; k++) {
assert(remainder[i][j][k] < n);
out[i][j][k] * n + remainder[i][j][k] === a[k]*in[i][j][k]+b[k];
}
}
}
}
// component main { public [ out ] } = BatchNormalization2D(1, 1, 1, 1000);
/* INPUT = {
"in": ["123"],
"a": ["234"],
"b": ["345678"],
"out": ["374"],
"remainder": ["460"]
} */ | https://github.com/socathie/circomlib-ml |
circuits/Conv1D.circom | pragma circom 2.0.0;
include "./circomlib-matrix/matElemMul.circom";
include "./circomlib-matrix/matElemSum.circom";
include "./util.circom";
// Conv1D layer with valid padding
// n = 10 to the power of the number of decimal places
template Conv1D (nInputs, nChannels, nFilters, kernelSize, strides, n) {
signal input in[nInputs][nChannels];
signal input weights[kernelSize][nChannels][nFilters];
signal input bias[nFilters];
signal input out[(nInputs-kernelSize)\strides+1][nFilters];
signal input remainder[(nInputs-kernelSize)\strides+1][nFilters];
component mul[(nInputs-kernelSize)\strides+1][nChannels][nFilters];
component elemSum[(nInputs-kernelSize)\strides+1][nChannels][nFilters];
component sum[(nInputs-kernelSize)\strides+1][nFilters];
for (var i=0; i<(nInputs-kernelSize)\strides+1; i++) {
for (var j=0; j<nChannels; j++) {
for (var k=0; k<nFilters; k++) {
mul[i][j][k] = matElemMul(kernelSize,1);
for (var x=0; x<kernelSize; x++) {
mul[i][j][k].a[x][0] <== in[i*strides+x][j];
mul[i][j][k].b[x][0] <== weights[x][j][k];
}
elemSum[i][j][k] = matElemSum(kernelSize,1);
for (var x=0; x<kernelSize; x++) {
elemSum[i][j][k].a[x][0] <== mul[i][j][k].out[x][0];
}
}
}
for (var k=0; k<nFilters; k++) {
assert (remainder[i][k] < n);
sum[i][k] = Sum(nChannels);
for (var j=0; j<nChannels; j++) {
sum[i][k].in[j] <== elemSum[i][j][k].out;
}
out[i][k] * n + remainder[i][k] === sum[i][k].out + bias[k];
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/Conv2D.circom | pragma circom 2.0.0;
include "./circomlib-matrix/matElemMul.circom";
include "./circomlib-matrix/matElemSum.circom";
include "./util.circom";
// Conv2D layer with valid padding
// n = 10 to the power of the number of decimal places
template Conv2D (nRows, nCols, nChannels, nFilters, kernelSize, strides, n) {
signal input in[nRows][nCols][nChannels];
signal input weights[kernelSize][kernelSize][nChannels][nFilters];
signal input bias[nFilters];
signal input out[(nRows-kernelSize)\strides+1][(nCols-kernelSize)\strides+1][nFilters];
signal input remainder[(nRows-kernelSize)\strides+1][(nCols-kernelSize)\strides+1][nFilters];
component mul[(nRows-kernelSize)\strides+1][(nCols-kernelSize)\strides+1][nChannels][nFilters];
component elemSum[(nRows-kernelSize)\strides+1][(nCols-kernelSize)\strides+1][nChannels][nFilters];
component sum[(nRows-kernelSize)\strides+1][(nCols-kernelSize)\strides+1][nFilters];
for (var i=0; i<(nRows-kernelSize)\strides+1; i++) {
for (var j=0; j<(nCols-kernelSize)\strides+1; j++) {
for (var k=0; k<nChannels; k++) {
for (var m=0; m<nFilters; m++) {
mul[i][j][k][m] = matElemMul(kernelSize,kernelSize);
for (var x=0; x<kernelSize; x++) {
for (var y=0; y<kernelSize; y++) {
mul[i][j][k][m].a[x][y] <== in[i*strides+x][j*strides+y][k];
mul[i][j][k][m].b[x][y] <== weights[x][y][k][m];
}
}
elemSum[i][j][k][m] = matElemSum(kernelSize,kernelSize);
for (var x=0; x<kernelSize; x++) {
for (var y=0; y<kernelSize; y++) {
elemSum[i][j][k][m].a[x][y] <== mul[i][j][k][m].out[x][y];
}
}
}
}
for (var m=0; m<nFilters; m++) {
assert (remainder[i][j][m] < n);
sum[i][j][m] = Sum(nChannels);
for (var k=0; k<nChannels; k++) {
sum[i][j][m].in[k] <== elemSum[i][j][k][m].out;
}
out[i][j][m] * n + remainder[i][j][m] === sum[i][j][m].out + bias[m];
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/Conv2Dsame.circom | pragma circom 2.0.0;
include "./Conv2D.circom";
template Conv2Dsame (nRows, nCols, nChannels, nFilters, kernelSize, strides, n) {
signal input in[nRows][nCols][nChannels];
signal input weights[kernelSize][kernelSize][nChannels][nFilters];
signal input bias[nFilters];
var rowPadding, colPadding;
if (nRows % strides == 0) {
rowPadding = (kernelSize - strides) > 0 ? (kernelSize - strides) : 0;
} else {
rowPadding = (kernelSize - (nRows % strides)) > 0 ? (kernelSize - (nRows % strides)) : 0;
}
if (nCols % strides == 0) {
colPadding = (kernelSize - strides) > 0 ? (kernelSize - strides) : 0;
} else {
colPadding = (kernelSize - (nCols % strides)) > 0 ? (kernelSize - (nCols % strides)) : 0;
}
signal input out[(nRows+rowPadding-kernelSize)\strides+1][(nCols+colPadding-kernelSize)\strides+1][nFilters];
signal input remainder[(nRows+rowPadding-kernelSize)\strides+1][(nCols+colPadding-kernelSize)\strides+1][nFilters];
component conv2d = Conv2D(nRows+rowPadding, nCols+colPadding, nChannels, nFilters, kernelSize, strides, n);
for (var i = rowPadding\2; i < rowPadding\2+nRows; i++) {
for (var j = colPadding\2; j < colPadding\2+nCols; j++) {
for (var k = 0; k < nChannels; k++) {
conv2d.in[i][j][k] <== in[i-rowPadding\2][j-colPadding\2][k];
}
}
}
for (var i = 0; i< rowPadding\2; i++) {
for (var j = 0; j < nCols+colPadding; j++) {
for (var k = 0; k < nChannels; k++) {
conv2d.in[i][j][k] <== 0;
}
}
}
for (var i = nRows+rowPadding\2; i < nRows+rowPadding; i++) {
for (var j = 0; j < nCols+colPadding; j++) {
for (var k = 0; k < nChannels; k++) {
conv2d.in[i][j][k] <== 0;
}
}
}
for (var i = rowPadding\2; i < nRows+rowPadding\2; i++) {
for (var j = 0; j < colPadding\2; j++) {
for (var k = 0; k < nChannels; k++) {
conv2d.in[i][j][k] <== 0;
}
}
}
for (var i = rowPadding\2; i < nRows+rowPadding\2; i++) {
for (var j = nCols+colPadding\2; j < nCols+colPadding; j++) {
for (var k = 0; k < nChannels; k++) {
conv2d.in[i][j][k] <== 0;
}
}
}
for (var i = 0; i < kernelSize; i++) {
for (var j = 0; j < kernelSize; j++) {
for (var k = 0; k < nChannels; k++) {
for (var l = 0; l < nFilters; l++) {
conv2d.weights[i][j][k][l] <== weights[i][j][k][l];
}
}
}
}
for (var i = 0; i < nFilters; i++) {
conv2d.bias[i] <== bias[i];
}
for (var i = 0; i < (nRows+rowPadding-kernelSize)\strides+1; i++) {
for (var j = 0; j < (nCols+colPadding-kernelSize)\strides+1; j++) {
for (var k = 0; k < nFilters; k++) {
conv2d.out[i][j][k] <== out[i][j][k];
conv2d.remainder[i][j][k] <== remainder[i][j][k];
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/Dense.circom | pragma circom 2.0.0;
include "./circomlib-matrix/matMul.circom";
// Dense layer
// n = 10 to the power of the number of decimal places
template Dense (nInputs, nOutputs, n) {
signal input in[nInputs];
signal input weights[nInputs][nOutputs];
signal input bias[nOutputs];
signal input out[nOutputs];
signal input remainder[nOutputs];
component dot[nOutputs];
for (var i=0; i<nOutputs; i++) {
assert (remainder[i] < n);
dot[i] = matMul(1,nInputs,1);
for (var j=0; j<nInputs; j++) {
dot[i].a[0][j] <== in[j];
dot[i].b[j][0] <== weights[j][i];
}
out[i] * n + remainder[i] === dot[i].out[0][0] + bias[i];
}
} | https://github.com/socathie/circomlib-ml |
circuits/DepthwiseConv2D.circom | pragma circom 2.1.1;
// include "./Conv2D.circom";
include "./circomlib/sign.circom";
include "./circomlib/bitify.circom";
include "./circomlib/comparators.circom";
include "./circomlib-matrix/matElemMul.circom";
include "./circomlib-matrix/matElemSum.circom";
include "./util.circom";
// Depthwise Convolution layer with valid padding
// Note that nFilters must be a multiple of nChannels
// n = 10 to the power of the number of decimal places
// component main = DepthwiseConv2D(34, 34, 8, 8, 3, 1);
template DepthwiseConv2D (nRows, nCols, nChannels, nFilters, kernelSize, strides, n) {
var outRows = (nRows-kernelSize)\strides+1;
var outCols = (nCols-kernelSize)\strides+1;
signal input in[nRows][nCols][nChannels];
signal input weights[kernelSize][kernelSize][nFilters]; // weights are 3d because depth is 1
signal input bias[nFilters];
signal input remainder[outRows][outCols][nFilters];
signal input out[outRows][outCols][nFilters];
component mul[outRows][outCols][nFilters];
component elemSum[outRows][outCols][nFilters];
var valid_groups = nFilters % nChannels;
var filtersPerChannel = nFilters / nChannels;
signal groups;
groups <== valid_groups;
component is_zero = IsZero();
is_zero.in <== groups;
is_zero.out === 1;
for (var row=0; row<outRows; row++) {
for (var col=0; col<outCols; col++) {
for (var filterMultiplier=1; filterMultiplier<=filtersPerChannel; filterMultiplier++) {
for (var channel=0; channel<nChannels; channel++) {
var filter = filterMultiplier*channel;
mul[row][col][filter] = matElemMul(kernelSize,kernelSize);
for (var x=0; x<kernelSize; x++) {
for (var y=0; y<kernelSize; y++) {
mul[row][col][filter].a[x][y] <== in[row*strides+x][col*strides+y][channel];
mul[row][col][filter].b[x][y] <== weights[x][y][filter];
}
}
elemSum[row][col][filter] = matElemSum(kernelSize,kernelSize);
for (var x=0; x<kernelSize; x++) {
for (var y=0; y<kernelSize; y++) {
elemSum[row][col][filter].a[x][y] <== mul[row][col][filter].out[x][y];
}
}
out[row][col][filter] * n + remainder[row][col][filter] === elemSum[row][col][filter].out + bias[filter];
}
}
}
}
}
| https://github.com/socathie/circomlib-ml |
circuits/Flatten2D.circom | pragma circom 2.0.0;
// Flatten layer with that accepts a 2D input
template Flatten2D (nRows, nCols, nChannels) {
signal input in[nRows][nCols][nChannels];
signal input out[nRows*nCols*nChannels];
var idx = 0;
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
for (var k=0; k<nChannels; k++) {
out[idx] === in[i][j][k];
idx++;
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/GlobalAveragePooling2D.circom | pragma circom 2.0.0;
include "./GlobalSumPooling2D.circom";
// GlobalAveragePooling2D layer, might lose precision compared to GlobalSumPooling2D
template GlobalAveragePooling2D (nRows, nCols, nChannels) {
signal input in[nRows][nCols][nChannels];
signal input out[nChannels];
signal input remainder[nChannels];
component globalSumPooling2D = GlobalSumPooling2D (nRows, nCols, nChannels);
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
for (var k=0; k<nChannels; k++) {
globalSumPooling2D.in[i][j][k] <== in[i][j][k];
}
}
}
for (var k=0; k<nChannels; k++) {
assert (remainder[k] < nRows*nCols);
out[k] * nRows * nCols + remainder[k] === globalSumPooling2D.out[k];
}
} | https://github.com/socathie/circomlib-ml |
circuits/GlobalMaxPooling2D.circom | pragma circom 2.0.0;
include "./util.circom";
// GlobalMaxPooling2D layer
template GlobalMaxPooling2D (nRows, nCols, nChannels) {
signal input in[nRows][nCols][nChannels];
signal input out[nChannels];
component max[nChannels];
for (var k=0; k<nChannels; k++) {
max[k] = Max(nRows*nCols);
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
max[k].in[i*nCols+j] <== in[i][j][k];
}
}
out[k] === max[k].out;
}
} | https://github.com/socathie/circomlib-ml |
circuits/GlobalSumPooling2D.circom | pragma circom 2.0.0;
include "./circomlib-matrix/matElemSum.circom";
include "./util.circom";
// GlobalSumPooling2D layer, basically GlobalAveragePooling2D layer with a constant scaling, more optimized for circom
template GlobalSumPooling2D (nRows, nCols, nChannels) {
signal input in[nRows][nCols][nChannels];
signal output out[nChannels];
component elemSum[nChannels];
for (var k=0; k<nChannels; k++) {
elemSum[k] = matElemSum(nRows,nCols);
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
elemSum[k].a[i][j] <== in[i][j][k];
}
}
out[k] <== elemSum[k].out;
}
} | https://github.com/socathie/circomlib-ml |
circuits/LeakyReLU.circom | pragma circom 2.0.0;
include "./util.circom";
// LeakyReLU layer
template LeakyReLU (alpha) { // alpha is 10 times the actual alpha, since usual alpha is 0.2, 0.3, etc.
signal input in;
signal input out;
signal input remainder;
component isNegative = IsNegative();
isNegative.in <== in;
signal neg;
neg <== isNegative.out * alpha * in;
out * 10 + remainder === neg + 10 * in * (1 - isNegative.out);
} | https://github.com/socathie/circomlib-ml |
circuits/MaxPooling2D.circom | pragma circom 2.0.0;
include "./util.circom";
// MaxPooling2D layer
template MaxPooling2D (nRows, nCols, nChannels, poolSize, strides) {
signal input in[nRows][nCols][nChannels];
signal input out[(nRows-poolSize)\strides+1][(nCols-poolSize)\strides+1][nChannels];
component max[(nRows-poolSize)\strides+1][(nCols-poolSize)\strides+1][nChannels];
for (var i=0; i<(nRows-poolSize)\strides+1; i++) {
for (var j=0; j<(nCols-poolSize)\strides+1; j++) {
for (var k=0; k<nChannels; k++) {
max[i][j][k] = Max(poolSize*poolSize);
for (var x=0; x<poolSize; x++) {
for (var y=0; y<poolSize; y++) {
max[i][j][k].in[x*poolSize+y] <== in[i*strides+x][j*strides+y][k];
}
}
out[i][j][k] === max[i][j][k].out;
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/MaxPooling2Dsame.circom | pragma circom 2.0.0;
include "./MaxPooling2D.circom";
template MaxPooling2Dsame (nRows, nCols, nChannels, poolSize, strides) {
signal input in[nRows][nCols][nChannels];
var rowPadding, colPadding;
if (nRows % strides == 0) {
rowPadding = (poolSize - strides) > 0 ? (poolSize - strides) : 0;
} else {
rowPadding = (poolSize - (nRows % strides)) > 0 ? (poolSize - (nRows % strides)) : 0;
}
if (nCols % strides == 0) {
colPadding = (poolSize - strides) > 0 ? (poolSize - strides) : 0;
} else {
colPadding = (poolSize - (nCols % strides)) > 0 ? (poolSize - (nCols % strides)) : 0;
}
signal input out[(nRows+rowPadding-poolSize)\strides+1][(nCols+colPadding-poolSize)\strides+1][nChannels];
component max2d = MaxPooling2D(nRows+rowPadding, nCols+colPadding, nChannels, poolSize, strides);
for (var i = rowPadding\2; i < rowPadding\2+nRows; i++) {
for (var j = colPadding\2; j < colPadding\2+nCols; j++) {
for (var k = 0; k < nChannels; k++) {
max2d.in[i][j][k] <== in[i-rowPadding\2][j-colPadding\2][k];
}
}
}
for (var i = 0; i< rowPadding\2; i++) {
for (var j = 0; j < nCols+colPadding; j++) {
for (var k = 0; k < nChannels; k++) {
max2d.in[i][j][k] <== 0;
}
}
}
for (var i = nRows+rowPadding\2; i< nRows+rowPadding; i++) {
for (var j = 0; j < nCols+colPadding; j++) {
for (var k = 0; k < nChannels; k++) {
max2d.in[i][j][k] <== 0;
}
}
}
for (var i = rowPadding\2; i < nRows+rowPadding\2; i++) {
for (var j = 0; j < colPadding\2; j++) {
for (var k = 0; k < nChannels; k++) {
max2d.in[i][j][k] <== 0;
}
}
}
for (var i = rowPadding\2; i < nRows+rowPadding\2; i++) {
for (var j = nCols+colPadding\2; j < nCols+colPadding; j++) {
for (var k = 0; k < nChannels; k++) {
max2d.in[i][j][k] <== 0;
}
}
}
for (var i = 0; i < (nRows+rowPadding-poolSize)\strides+1; i++) {
for (var j = 0; j < (nCols+colPadding-poolSize)\strides+1; j++) {
for (var k = 0; k < nChannels; k++) {
max2d.out[i][j][k] <== out[i][j][k];
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/PointwiseConv2D.circom | pragma circom 2.1.1;
// include "./Conv2D.circom";
include "./circomlib/sign.circom";
include "./circomlib/bitify.circom";
include "./circomlib/comparators.circom";
include "./circomlib-matrix/matElemMul.circom";
include "./circomlib-matrix/matElemSum.circom";
include "./util.circom";
// Pointwise Convolution layer
// Note that nFilters must be a multiple of nChannels
template PointwiseConv2D (nRows, nCols, nChannels, nFilters, n) {
var outRows = nRows; // kernel size and strides are 1
var outCols = nCols;
signal input in[nRows][nCols][nChannels];
signal input weights[nChannels][nFilters]; // weights are 2d because kernel_size is 1
signal input bias[nFilters];
signal input out[outRows][outCols][nFilters];
signal input remainder[outRows][outCols][nFilters];
component sum[outRows][outCols][nFilters];
for (var row=0; row<outRows; row++) {
for (var col=0; col<outCols; col++) {
for (var filter=0; filter<nFilters; filter++) {
sum[row][col][filter] = Sum(nChannels);
for (var channel=0; channel<nChannels; channel++) {
sum[row][col][filter].in[channel] <== in[row][col][channel] * weights[channel][filter];
}
out[row][col][filter] * n + remainder[row][col][filter] === sum[row][col][filter].out + bias[filter];
}
}
}
}
// component main = PointwiseConv2D(32, 32, 8, 16);
| https://github.com/socathie/circomlib-ml |
circuits/ReLU.circom | pragma circom 2.0.0;
include "./util.circom";
// ReLU layer
template ReLU () {
signal input in;
signal input out;
component isPositive = IsPositive();
isPositive.in <== in;
out === in * isPositive.out;
} | https://github.com/socathie/circomlib-ml |
circuits/Reshape2D.circom | pragma circom 2.0.0;
// Reshape layer with that accepts a 1D input
template Reshape2D (nRows, nCols, nChannels) {
signal input in[nRows*nCols*nChannels];
signal input out[nRows][nCols][nChannels];
for (var i=0; i<nRows; i++) {
for (var j=0; j<nCols; j++) {
for (var k=0; k<nChannels; k++) {
out[i][j][k] === in[i*nCols*nChannels + j*nChannels + k];
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/SeparableConv2D.circom | pragma circom 2.1.1;
include "./PointwiseConv2D.circom";
include "./DepthwiseConv2D.circom";
// Separable convolution layer with valid padding.
// Quantization is done by the caller by multiplying float values by 10**exp.
template SeparableConv2D (nRows, nCols, nChannels, nDepthFilters, nPointFilters, depthKernelSize, strides, n) {
var outRows = (nRows-depthKernelSize)\strides+1;
var outCols = (nCols-depthKernelSize)\strides+1;
signal input in[nRows][nCols][nChannels];
signal input depthWeights[depthKernelSize][depthKernelSize][nDepthFilters]; // weights are 3d because depth is 1
signal input depthBias[nDepthFilters];
signal input depthRemainder[outRows][outCols][nDepthFilters];
signal input depthOut[outRows][outCols][nDepthFilters];
signal input pointWeights[nChannels][nPointFilters]; // weights are 2d because depthKernelSize is one
signal input pointBias[nPointFilters];
signal input pointRemainder[outRows][outCols][nPointFilters];
signal input pointOut[outRows][outCols][nPointFilters];
component depthConv = DepthwiseConv2D(nRows, nCols, nChannels, nDepthFilters, depthKernelSize, strides, n);
component pointConv = PointwiseConv2D(outRows, outCols, nDepthFilters, nPointFilters, n);
for (var filter=0; filter<nDepthFilters; filter++) {
for (var x=0; x<depthKernelSize; x++) {
for (var y=0; y<depthKernelSize; y++) {
depthConv.weights[x][y][filter] <== depthWeights[x][y][filter];
}
}
depthConv.bias[filter] <== depthBias[filter];
}
for (var row=0; row < nRows; row++) {
for (var col=0; col < nCols; col++) {
for (var channel=0; channel < nChannels; channel++) {
depthConv.in[row][col][channel] <== in[row][col][channel];
}
}
}
for (var row=0; row < outRows; row++) {
for (var col=0; col < outCols; col++) {
for (var filter=0; filter < nDepthFilters; filter++) {
depthConv.remainder[row][col][filter] <== depthRemainder[row][col][filter];
depthConv.out[row][col][filter] <== depthOut[row][col][filter];
pointConv.in[row][col][filter] <== depthOut[row][col][filter];
}
}
}
for (var filter=0; filter < nPointFilters; filter++) {
for (var channel=0; channel < nChannels; channel++) {
pointConv.weights[channel][filter] <== pointWeights[channel][filter];
}
pointConv.bias[filter] <== pointBias[filter];
}
for (var row=0; row < outRows; row++) {
for (var col=0; col < outCols; col++) {
for (var filter=0; filter < nPointFilters; filter++) {
pointConv.remainder[row][col][filter] <== pointRemainder[row][col][filter];
pointConv.out[row][col][filter] <== pointOut[row][col][filter];
}
}
}
}
| https://github.com/socathie/circomlib-ml |
circuits/SumPooling2D.circom | pragma circom 2.0.0;
include "./circomlib-matrix/matElemSum.circom";
include "./util.circom";
// SumPooling2D layer, basically AveragePooling2D layer with a constant scaling, more optimized for circom
template SumPooling2D (nRows, nCols, nChannels, poolSize, strides) {
signal input in[nRows][nCols][nChannels];
signal output out[(nRows-poolSize)\strides+1][(nCols-poolSize)\strides+1][nChannels];
component elemSum[(nRows-poolSize)\strides+1][(nCols-poolSize)\strides+1][nChannels];
for (var i=0; i<(nRows-poolSize)\strides+1; i++) {
for (var j=0; j<(nCols-poolSize)\strides+1; j++) {
for (var k=0; k<nChannels; k++) {
elemSum[i][j][k] = matElemSum(poolSize,poolSize);
for (var x=0; x<poolSize; x++) {
for (var y=0; y<poolSize; y++) {
elemSum[i][j][k].a[x][y] <== in[i*strides+x][j*strides+y][k];
}
}
out[i][j][k] <== elemSum[i][j][k].out;
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/UpSampling2D.circom | pragma circom 2.0.0;
template UpSampling2D(nRows, nCols, nChannels, size) {
signal input in[nRows][nCols][nChannels];
signal input out[nRows * size][nCols * size][nChannels];
// nearest neighbor interpolation
for (var i = 0; i < nRows; i++) {
for (var j = 0; j < nCols; j++) {
for (var c = 0; c < nChannels; c++) {
for (var k = 0; k < size; k++) {
for (var l = 0; l < size; l++) {
out[i * size + k][j * size + l][c] === in[i][j][c];
}
}
}
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/Zanh.circom | pragma circom 2.0.0;
// Polynomial approximation for the tanh layer
// 0.006769816 + 0.554670504 * x - 0.009411195 * x**2 - 0.014187547 * x**3
// 6769816 + 554670504 * x - 9411195 * x**2 - 14187547 * x**3
// 6769816 + x * (554670504 - 9411195 * x - 14187547 * x**2)
// n = 10 to the power of the number of decimal places
// out and remainder are from division by n**2 so out has the same number of decimal places as in
template Zanh (n) {
signal input in;
signal input out;
signal input remainder;
assert(remainder < (n**2) * (10**9));
signal tmp;
tmp <== 554670504 * n**2 - 9411195 * n * in - 14187547 * in * in;
// log(6769816 * n**3 + in * tmp);
out * (n**2) * (10**9) + remainder === 6769816 * n**3 + in * tmp;
}
// component main { public [ out ] } = Zanh(10**9);
/* INPUT = {
"in": "123456789",
"out": "750775175",
"remainder": "35162208611038149371400257"
} */ | https://github.com/socathie/circomlib-ml |
circuits/ZeLU.circom | pragma circom 2.0.0;
// Poly activation layer: https://arxiv.org/abs/2011.05530
// n = 10 to the power of the number of decimal places
// out and remainder are from division by n so out has the same number of decimal places as in
template ZeLU (n) {
signal input in;
signal input out;
signal input remainder;
assert(remainder < n);
signal tmp;
tmp <== in * in + n*in;
out * n + remainder === tmp;
}
// component main { public [ out ] } = ZeLU(10**9);
/* INPUT = {
"in": "123456789",
"out": "138698367",
"remainder": "750190521"
} */ | https://github.com/socathie/circomlib-ml |
circuits/Zigmoid.circom | pragma circom 2.0.0;
// Polynomial approximation for the sigmoid layer
// 0.502073021 + 0.198695283 * x - 0.001570683 * x**2 - 0.004001354 * x**3
// 502073021 + 198695283 * x - 1570683 * x**2 - 4001354 * x**3
// 502073021 + x * (198695283 - 1570683 * x - 4001354 * x**2)
// n = 10 to the power of the number of decimal places
// out and remainder are from division by n**2 so out has the same number of decimal places as in
template Zigmoid (n) {
signal input in;
signal input out;
signal input remainder;
assert(remainder < (n**2) * (10**9));
signal tmp;
tmp <== 198695283 * n**2 - 1570683 * n * in - 4001354 * in * in;
// log(502073021 * n**3 + in * tmp);
out * (n**2) * (10**9) + remainder === 502073021 * n**3 + in * tmp;
}
// component main { public [ out ] } = Zigmoid(10**9);
/* INPUT = {
"in": "123456789",
"out": "526571833",
"remainder": "686713237479944887069368574"
} */ | https://github.com/socathie/circomlib-ml |
circuits/circomlib-matrix/matElemMul.circom | pragma circom 2.0.0;
// matrix multiplication by element
template matElemMul (m,n) {
signal input a[m][n];
signal input b[m][n];
signal output out[m][n];
for (var i=0; i < m; i++) {
for (var j=0; j < n; j++) {
out[i][j] <== a[i][j] * b[i][j];
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/circomlib-matrix/matElemSum.circom | pragma circom 2.0.0;
// sum of all elements in a matrix
template matElemSum (m,n) {
signal input a[m][n];
signal output out;
signal sum[m*n];
sum[0] <== a[0][0];
var idx = 0;
for (var i=0; i < m; i++) {
for (var j=0; j < n; j++) {
if (idx > 0) {
sum[idx] <== sum[idx-1] + a[i][j];
}
idx++;
}
}
out <== sum[m*n-1];
} | https://github.com/socathie/circomlib-ml |
circuits/circomlib-matrix/matMul.circom | pragma circom 2.0.0;
include "matElemMul.circom";
include "matElemSum.circom";
// matrix multiplication
template matMul (m,n,p) {
signal input a[m][n];
signal input b[n][p];
signal output out[m][p];
component matElemMulComp[m][p];
component matElemSumComp[m][p];
for (var i=0; i < m; i++) {
for (var j=0; j < p; j++) {
matElemMulComp[i][j] = matElemMul(1,n);
matElemSumComp[i][j] = matElemSum(1,n);
for (var k=0; k < n; k++) {
matElemMulComp[i][j].a[0][k] <== a[i][k];
matElemMulComp[i][j].b[0][k] <== b[k][j];
}
for (var k=0; k < n; k++) {
matElemSumComp[i][j].a[0][k] <== matElemMulComp[i][j].out[0][k];
}
out[i][j] <== matElemSumComp[i][j].out;
}
}
} | https://github.com/socathie/circomlib-ml |
circuits/circomlib/aliascheck.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "compconstant.circom";
template AliasCheck() {
signal input in[254];
component compConstant = CompConstant(-1);
for (var i=0; i<254; i++) in[i] ==> compConstant.in[i];
compConstant.out === 0;
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/babyjub.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "bitify.circom";
include "escalarmulfix.circom";
template BabyAdd() {
signal input x1;
signal input y1;
signal input x2;
signal input y2;
signal output xout;
signal output yout;
signal beta;
signal gamma;
signal delta;
signal tau;
var a = 168700;
var d = 168696;
beta <== x1*y2;
gamma <== y1*x2;
delta <== (-a*x1+y1)*(x2 + y2);
tau <== beta * gamma;
xout <-- (beta + gamma) / (1+ d*tau);
(1+ d*tau) * xout === (beta + gamma);
yout <-- (delta + a*beta - gamma) / (1-d*tau);
(1-d*tau)*yout === (delta + a*beta - gamma);
}
template BabyDbl() {
signal input x;
signal input y;
signal output xout;
signal output yout;
component adder = BabyAdd();
adder.x1 <== x;
adder.y1 <== y;
adder.x2 <== x;
adder.y2 <== y;
adder.xout ==> xout;
adder.yout ==> yout;
}
template BabyCheck() {
signal input x;
signal input y;
signal x2;
signal y2;
var a = 168700;
var d = 168696;
x2 <== x*x;
y2 <== y*y;
a*x2 + y2 === 1 + d*x2*y2;
}
// Extracts the public key from private key
template BabyPbk() {
signal input in;
signal output Ax;
signal output Ay;
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component pvkBits = Num2Bits(253);
pvkBits.in <== in;
component mulFix = EscalarMulFix(253, BASE8);
var i;
for (i=0; i<253; i++) {
mulFix.e[i] <== pvkBits.out[i];
}
Ax <== mulFix.out[0];
Ay <== mulFix.out[1];
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/binsum.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Binary Sum
==========
This component creates a binary sum componet of ops operands and n bits each operand.
e is Number of carries: Depends on the number of operands in the input.
Main Constraint:
in[0][0] * 2^0 + in[0][1] * 2^1 + ..... + in[0][n-1] * 2^(n-1) +
+ in[1][0] * 2^0 + in[1][1] * 2^1 + ..... + in[1][n-1] * 2^(n-1) +
+ ..
+ in[ops-1][0] * 2^0 + in[ops-1][1] * 2^1 + ..... + in[ops-1][n-1] * 2^(n-1) +
===
out[0] * 2^0 + out[1] * 2^1 + + out[n+e-1] *2(n+e-1)
To waranty binary outputs:
out[0] * (out[0] - 1) === 0
out[1] * (out[0] - 1) === 0
.
.
.
out[n+e-1] * (out[n+e-1] - 1) == 0
*/
/*
This function calculates the number of extra bits in the output to do the full sum.
*/
pragma circom 2.0.0;
function nbits(a) {
var n = 1;
var r = 0;
while (n-1<a) {
r++;
n *= 2;
}
return r;
}
template BinSum(n, ops) {
var nout = nbits((2**n -1)*ops);
signal input in[ops][n];
signal output out[nout];
var lin = 0;
var lout = 0;
var k;
var j;
var e2;
e2 = 1;
for (k=0; k<n; k++) {
for (j=0; j<ops; j++) {
lin += in[j][k] * e2;
}
e2 = e2 + e2;
}
e2 = 1;
for (k=0; k<nout; k++) {
out[k] <-- (lin >> k) & 1;
// Ensure out is binary
out[k] * (out[k] - 1) === 0;
lout += out[k] * e2;
e2 = e2+e2;
}
// Ensure the sum;
lin === lout;
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/bitify.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "comparators.circom";
include "aliascheck.circom";
template Num2Bits(n) {
signal input in;
signal output out[n];
var lc1=0;
var e2=1;
for (var i = 0; i<n; i++) {
out[i] <-- (in >> i) & 1;
out[i] * (out[i] -1 ) === 0;
lc1 += out[i] * e2;
e2 = e2+e2;
}
lc1 === in;
}
template Num2Bits_strict() {
signal input in;
signal output out[254];
component aliasCheck = AliasCheck();
component n2b = Num2Bits(254);
in ==> n2b.in;
for (var i=0; i<254; i++) {
n2b.out[i] ==> out[i];
n2b.out[i] ==> aliasCheck.in[i];
}
}
template Bits2Num(n) {
signal input in[n];
signal output out;
var lc1=0;
var e2 = 1;
for (var i = 0; i<n; i++) {
lc1 += in[i] * e2;
e2 = e2 + e2;
}
lc1 ==> out;
}
template Bits2Num_strict() {
signal input in[254];
signal output out;
component aliasCheck = AliasCheck();
component b2n = Bits2Num(254);
for (var i=0; i<254; i++) {
in[i] ==> b2n.in[i];
in[i] ==> aliasCheck.in[i];
}
b2n.out ==> out;
}
template Num2BitsNeg(n) {
signal input in;
signal output out[n];
var lc1=0;
component isZero;
isZero = IsZero();
var neg = n == 0 ? 0 : 2**n - in;
for (var i = 0; i<n; i++) {
out[i] <-- (neg >> i) & 1;
out[i] * (out[i] -1 ) === 0;
lc1 += out[i] * 2**i;
}
in ==> isZero.in;
lc1 + isZero.out * 2**n === 2**n - in;
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/comparators.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "bitify.circom";
include "binsum.circom";
template IsZero() {
signal input in;
signal output out;
signal inv;
inv <-- in!=0 ? 1/in : 0;
out <== -in*inv +1;
in*out === 0;
}
template IsEqual() {
signal input in[2];
signal output out;
component isz = IsZero();
in[1] - in[0] ==> isz.in;
isz.out ==> out;
}
template ForceEqualIfEnabled() {
signal input enabled;
signal input in[2];
component isz = IsZero();
in[1] - in[0] ==> isz.in;
(1 - isz.out)*enabled === 0;
}
/*
// N is the number of bits the input have.
// The MSF is the sign bit.
template LessThan(n) {
signal input in[2];
signal output out;
component num2Bits0;
component num2Bits1;
component adder;
adder = BinSum(n, 2);
num2Bits0 = Num2Bits(n);
num2Bits1 = Num2BitsNeg(n);
in[0] ==> num2Bits0.in;
in[1] ==> num2Bits1.in;
var i;
for (i=0;i<n;i++) {
num2Bits0.out[i] ==> adder.in[0][i];
num2Bits1.out[i] ==> adder.in[1][i];
}
adder.out[n-1] ==> out;
}
*/
template LessThan(n) {
assert(n <= 252);
signal input in[2];
signal output out;
component n2b = Num2Bits(n+1);
n2b.in <== in[0]+ (1<<n) - in[1];
out <== 1-n2b.out[n];
}
// N is the number of bits the input have.
// The MSF is the sign bit.
template LessEqThan(n) {
signal input in[2];
signal output out;
component lt = LessThan(n);
lt.in[0] <== in[0];
lt.in[1] <== in[1]+1;
lt.out ==> out;
}
// N is the number of bits the input have.
// The MSF is the sign bit.
template GreaterThan(n) {
signal input in[2];
signal output out;
component lt = LessThan(n);
lt.in[0] <== in[1];
lt.in[1] <== in[0];
lt.out ==> out;
}
// N is the number of bits the input have.
// The MSF is the sign bit.
template GreaterEqThan(n) {
signal input in[2];
signal output out;
component lt = LessThan(n);
lt.in[0] <== in[1];
lt.in[1] <== in[0]+1;
lt.out ==> out;
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/compconstant.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "bitify.circom";
// Returns 1 if in (in binary) > ct
template CompConstant(ct) {
signal input in[254];
signal output out;
signal parts[127];
signal sout;
var clsb;
var cmsb;
var slsb;
var smsb;
var sum=0;
var b = (1 << 128) -1;
var a = 1;
var e = 1;
var i;
for (i=0;i<127; i++) {
clsb = (ct >> (i*2)) & 1;
cmsb = (ct >> (i*2+1)) & 1;
slsb = in[i*2];
smsb = in[i*2+1];
if ((cmsb==0)&&(clsb==0)) {
parts[i] <== -b*smsb*slsb + b*smsb + b*slsb;
} else if ((cmsb==0)&&(clsb==1)) {
parts[i] <== a*smsb*slsb - a*slsb + b*smsb - a*smsb + a;
} else if ((cmsb==1)&&(clsb==0)) {
parts[i] <== b*smsb*slsb - a*smsb + a;
} else {
parts[i] <== -a*smsb*slsb + a;
}
sum = sum + parts[i];
b = b -e;
a = a +e;
e = e*2;
}
sout <== sum;
component num2bits = Num2Bits(135);
num2bits.in <== sout;
out <== num2bits.out[127];
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/escalarmulany.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "montgomery.circom";
include "babyjub.circom";
include "comparators.circom";
template Multiplexor2() {
signal input sel;
signal input in[2][2];
signal output out[2];
out[0] <== (in[1][0] - in[0][0])*sel + in[0][0];
out[1] <== (in[1][1] - in[0][1])*sel + in[0][1];
}
template BitElementMulAny() {
signal input sel;
signal input dblIn[2];
signal input addIn[2];
signal output dblOut[2];
signal output addOut[2];
component doubler = MontgomeryDouble();
component adder = MontgomeryAdd();
component selector = Multiplexor2();
sel ==> selector.sel;
dblIn[0] ==> doubler.in[0];
dblIn[1] ==> doubler.in[1];
doubler.out[0] ==> adder.in1[0];
doubler.out[1] ==> adder.in1[1];
addIn[0] ==> adder.in2[0];
addIn[1] ==> adder.in2[1];
addIn[0] ==> selector.in[0][0];
addIn[1] ==> selector.in[0][1];
adder.out[0] ==> selector.in[1][0];
adder.out[1] ==> selector.in[1][1];
doubler.out[0] ==> dblOut[0];
doubler.out[1] ==> dblOut[1];
selector.out[0] ==> addOut[0];
selector.out[1] ==> addOut[1];
}
// p is montgomery point
// n must be <= 248
// returns out in twisted edwards
// Double is in montgomery to be linked;
template SegmentMulAny(n) {
signal input e[n];
signal input p[2];
signal output out[2];
signal output dbl[2];
component bits[n-1];
component e2m = Edwards2Montgomery();
p[0] ==> e2m.in[0];
p[1] ==> e2m.in[1];
var i;
bits[0] = BitElementMulAny();
e2m.out[0] ==> bits[0].dblIn[0];
e2m.out[1] ==> bits[0].dblIn[1];
e2m.out[0] ==> bits[0].addIn[0];
e2m.out[1] ==> bits[0].addIn[1];
e[1] ==> bits[0].sel;
for (i=1; i<n-1; i++) {
bits[i] = BitElementMulAny();
bits[i-1].dblOut[0] ==> bits[i].dblIn[0];
bits[i-1].dblOut[1] ==> bits[i].dblIn[1];
bits[i-1].addOut[0] ==> bits[i].addIn[0];
bits[i-1].addOut[1] ==> bits[i].addIn[1];
e[i+1] ==> bits[i].sel;
}
bits[n-2].dblOut[0] ==> dbl[0];
bits[n-2].dblOut[1] ==> dbl[1];
component m2e = Montgomery2Edwards();
bits[n-2].addOut[0] ==> m2e.in[0];
bits[n-2].addOut[1] ==> m2e.in[1];
component eadder = BabyAdd();
m2e.out[0] ==> eadder.x1;
m2e.out[1] ==> eadder.y1;
-p[0] ==> eadder.x2;
p[1] ==> eadder.y2;
component lastSel = Multiplexor2();
e[0] ==> lastSel.sel;
eadder.xout ==> lastSel.in[0][0];
eadder.yout ==> lastSel.in[0][1];
m2e.out[0] ==> lastSel.in[1][0];
m2e.out[1] ==> lastSel.in[1][1];
lastSel.out[0] ==> out[0];
lastSel.out[1] ==> out[1];
}
// This function assumes that p is in the subgroup and it is different to 0
template EscalarMulAny(n) {
signal input e[n]; // Input in binary format
signal input p[2]; // Point (Twisted format)
signal output out[2]; // Point (Twisted format)
var nsegments = (n-1)\148 +1;
var nlastsegment = n - (nsegments-1)*148;
component segments[nsegments];
component doublers[nsegments-1];
component m2e[nsegments-1];
component adders[nsegments-1];
component zeropoint = IsZero();
zeropoint.in <== p[0];
var s;
var i;
var nseg;
for (s=0; s<nsegments; s++) {
nseg = (s < nsegments-1) ? 148 : nlastsegment;
segments[s] = SegmentMulAny(nseg);
for (i=0; i<nseg; i++) {
e[s*148+i] ==> segments[s].e[i];
}
if (s==0) {
// force G8 point if input point is zero
segments[s].p[0] <== p[0] + (5299619240641551281634865583518297030282874472190772894086521144482721001553 - p[0])*zeropoint.out;
segments[s].p[1] <== p[1] + (16950150798460657717958625567821834550301663161624707787222815936182638968203 - p[1])*zeropoint.out;
} else {
doublers[s-1] = MontgomeryDouble();
m2e[s-1] = Montgomery2Edwards();
adders[s-1] = BabyAdd();
segments[s-1].dbl[0] ==> doublers[s-1].in[0];
segments[s-1].dbl[1] ==> doublers[s-1].in[1];
doublers[s-1].out[0] ==> m2e[s-1].in[0];
doublers[s-1].out[1] ==> m2e[s-1].in[1];
m2e[s-1].out[0] ==> segments[s].p[0];
m2e[s-1].out[1] ==> segments[s].p[1];
if (s==1) {
segments[s-1].out[0] ==> adders[s-1].x1;
segments[s-1].out[1] ==> adders[s-1].y1;
} else {
adders[s-2].xout ==> adders[s-1].x1;
adders[s-2].yout ==> adders[s-1].y1;
}
segments[s].out[0] ==> adders[s-1].x2;
segments[s].out[1] ==> adders[s-1].y2;
}
}
if (nsegments == 1) {
segments[0].out[0]*(1-zeropoint.out) ==> out[0];
segments[0].out[1]+(1-segments[0].out[1])*zeropoint.out ==> out[1];
} else {
adders[nsegments-2].xout*(1-zeropoint.out) ==> out[0];
adders[nsegments-2].yout+(1-adders[nsegments-2].yout)*zeropoint.out ==> out[1];
}
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/escalarmulfix.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "mux3.circom";
include "montgomery.circom";
include "babyjub.circom";
/*
Window of 3 elements, it calculates
out = base + base*in[0] + 2*base*in[1] + 4*base*in[2]
out4 = 4*base
The result should be compensated.
*/
/*
The scalar is s = a0 + a1*2^3 + a2*2^6 + ...... + a81*2^243
First We calculate Q = B + 2^3*B + 2^6*B + ......... + 2^246*B
Then we calculate S1 = 2*2^246*B + (1 + a0)*B + (2^3 + a1)*B + .....+ (2^243 + a81)*B
And Finaly we compute the result: RES = SQ - Q
As you can see the input of the adders cannot be equal nor zero, except for the last
substraction that it's done in montgomery.
A good way to see it is that the accumulator input of the adder >= 2^247*B and the other input
is the output of the windows that it's going to be <= 2^246*B
*/
template WindowMulFix() {
signal input in[3];
signal input base[2];
signal output out[2];
signal output out8[2]; // Returns 8*Base (To be linked)
component mux = MultiMux3(2);
mux.s[0] <== in[0];
mux.s[1] <== in[1];
mux.s[2] <== in[2];
component dbl2 = MontgomeryDouble();
component adr3 = MontgomeryAdd();
component adr4 = MontgomeryAdd();
component adr5 = MontgomeryAdd();
component adr6 = MontgomeryAdd();
component adr7 = MontgomeryAdd();
component adr8 = MontgomeryAdd();
// in[0] -> 1*BASE
mux.c[0][0] <== base[0];
mux.c[1][0] <== base[1];
// in[1] -> 2*BASE
dbl2.in[0] <== base[0];
dbl2.in[1] <== base[1];
mux.c[0][1] <== dbl2.out[0];
mux.c[1][1] <== dbl2.out[1];
// in[2] -> 3*BASE
adr3.in1[0] <== base[0];
adr3.in1[1] <== base[1];
adr3.in2[0] <== dbl2.out[0];
adr3.in2[1] <== dbl2.out[1];
mux.c[0][2] <== adr3.out[0];
mux.c[1][2] <== adr3.out[1];
// in[3] -> 4*BASE
adr4.in1[0] <== base[0];
adr4.in1[1] <== base[1];
adr4.in2[0] <== adr3.out[0];
adr4.in2[1] <== adr3.out[1];
mux.c[0][3] <== adr4.out[0];
mux.c[1][3] <== adr4.out[1];
// in[4] -> 5*BASE
adr5.in1[0] <== base[0];
adr5.in1[1] <== base[1];
adr5.in2[0] <== adr4.out[0];
adr5.in2[1] <== adr4.out[1];
mux.c[0][4] <== adr5.out[0];
mux.c[1][4] <== adr5.out[1];
// in[5] -> 6*BASE
adr6.in1[0] <== base[0];
adr6.in1[1] <== base[1];
adr6.in2[0] <== adr5.out[0];
adr6.in2[1] <== adr5.out[1];
mux.c[0][5] <== adr6.out[0];
mux.c[1][5] <== adr6.out[1];
// in[6] -> 7*BASE
adr7.in1[0] <== base[0];
adr7.in1[1] <== base[1];
adr7.in2[0] <== adr6.out[0];
adr7.in2[1] <== adr6.out[1];
mux.c[0][6] <== adr7.out[0];
mux.c[1][6] <== adr7.out[1];
// in[7] -> 8*BASE
adr8.in1[0] <== base[0];
adr8.in1[1] <== base[1];
adr8.in2[0] <== adr7.out[0];
adr8.in2[1] <== adr7.out[1];
mux.c[0][7] <== adr8.out[0];
mux.c[1][7] <== adr8.out[1];
out8[0] <== adr8.out[0];
out8[1] <== adr8.out[1];
out[0] <== mux.out[0];
out[1] <== mux.out[1];
}
/*
This component does a multiplication of a escalar times a fix base
Signals:
e: The scalar in bits
base: the base point in edwards format
out: The result
dbl: Point in Edwards to be linked to the next segment.
*/
template SegmentMulFix(nWindows) {
signal input e[nWindows*3];
signal input base[2];
signal output out[2];
signal output dbl[2];
var i;
var j;
// Convert the base to montgomery
component e2m = Edwards2Montgomery();
e2m.in[0] <== base[0];
e2m.in[1] <== base[1];
component windows[nWindows];
component adders[nWindows];
component cadders[nWindows];
// In the last step we add an extra doubler so that numbers do not match.
component dblLast = MontgomeryDouble();
for (i=0; i<nWindows; i++) {
windows[i] = WindowMulFix();
cadders[i] = MontgomeryAdd();
if (i==0) {
windows[i].base[0] <== e2m.out[0];
windows[i].base[1] <== e2m.out[1];
cadders[i].in1[0] <== e2m.out[0];
cadders[i].in1[1] <== e2m.out[1];
} else {
windows[i].base[0] <== windows[i-1].out8[0];
windows[i].base[1] <== windows[i-1].out8[1];
cadders[i].in1[0] <== cadders[i-1].out[0];
cadders[i].in1[1] <== cadders[i-1].out[1];
}
for (j=0; j<3; j++) {
windows[i].in[j] <== e[3*i+j];
}
if (i<nWindows-1) {
cadders[i].in2[0] <== windows[i].out8[0];
cadders[i].in2[1] <== windows[i].out8[1];
} else {
dblLast.in[0] <== windows[i].out8[0];
dblLast.in[1] <== windows[i].out8[1];
cadders[i].in2[0] <== dblLast.out[0];
cadders[i].in2[1] <== dblLast.out[1];
}
}
for (i=0; i<nWindows; i++) {
adders[i] = MontgomeryAdd();
if (i==0) {
adders[i].in1[0] <== dblLast.out[0];
adders[i].in1[1] <== dblLast.out[1];
} else {
adders[i].in1[0] <== adders[i-1].out[0];
adders[i].in1[1] <== adders[i-1].out[1];
}
adders[i].in2[0] <== windows[i].out[0];
adders[i].in2[1] <== windows[i].out[1];
}
component m2e = Montgomery2Edwards();
component cm2e = Montgomery2Edwards();
m2e.in[0] <== adders[nWindows-1].out[0];
m2e.in[1] <== adders[nWindows-1].out[1];
cm2e.in[0] <== cadders[nWindows-1].out[0];
cm2e.in[1] <== cadders[nWindows-1].out[1];
component cAdd = BabyAdd();
cAdd.x1 <== m2e.out[0];
cAdd.y1 <== m2e.out[1];
cAdd.x2 <== -cm2e.out[0];
cAdd.y2 <== cm2e.out[1];
cAdd.xout ==> out[0];
cAdd.yout ==> out[1];
windows[nWindows-1].out8[0] ==> dbl[0];
windows[nWindows-1].out8[1] ==> dbl[1];
}
/*
This component multiplies a escalar times a fixed point BASE (twisted edwards format)
Signals
e: The escalar in binary format
out: The output point in twisted edwards
*/
template EscalarMulFix(n, BASE) {
signal input e[n]; // Input in binary format
signal output out[2]; // Point (Twisted format)
var nsegments = (n-1)\246 +1; // 249 probably would work. But I'm not sure and for security I keep 246
var nlastsegment = n - (nsegments-1)*249;
component segments[nsegments];
component m2e[nsegments-1];
component adders[nsegments-1];
var s;
var i;
var nseg;
var nWindows;
for (s=0; s<nsegments; s++) {
nseg = (s < nsegments-1) ? 249 : nlastsegment;
nWindows = ((nseg - 1)\3)+1;
segments[s] = SegmentMulFix(nWindows);
for (i=0; i<nseg; i++) {
segments[s].e[i] <== e[s*249+i];
}
for (i = nseg; i<nWindows*3; i++) {
segments[s].e[i] <== 0;
}
if (s==0) {
segments[s].base[0] <== BASE[0];
segments[s].base[1] <== BASE[1];
} else {
m2e[s-1] = Montgomery2Edwards();
adders[s-1] = BabyAdd();
segments[s-1].dbl[0] ==> m2e[s-1].in[0];
segments[s-1].dbl[1] ==> m2e[s-1].in[1];
m2e[s-1].out[0] ==> segments[s].base[0];
m2e[s-1].out[1] ==> segments[s].base[1];
if (s==1) {
segments[s-1].out[0] ==> adders[s-1].x1;
segments[s-1].out[1] ==> adders[s-1].y1;
} else {
adders[s-2].xout ==> adders[s-1].x1;
adders[s-2].yout ==> adders[s-1].y1;
}
segments[s].out[0] ==> adders[s-1].x2;
segments[s].out[1] ==> adders[s-1].y2;
}
}
if (nsegments == 1) {
segments[0].out[0] ==> out[0];
segments[0].out[1] ==> out[1];
} else {
adders[nsegments-2].xout ==> out[0];
adders[nsegments-2].yout ==> out[1];
}
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/mimc.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
template MiMC7(nrounds) {
signal input x_in;
signal input k;
signal output out;
var c[91] = [
0,
20888961410941983456478427210666206549300505294776164667214940546594746570981,
15265126113435022738560151911929040668591755459209400716467504685752745317193,
8334177627492981984476504167502758309043212251641796197711684499645635709656,
1374324219480165500871639364801692115397519265181803854177629327624133579404,
11442588683664344394633565859260176446561886575962616332903193988751292992472,
2558901189096558760448896669327086721003508630712968559048179091037845349145,
11189978595292752354820141775598510151189959177917284797737745690127318076389,
3262966573163560839685415914157855077211340576201936620532175028036746741754,
17029914891543225301403832095880481731551830725367286980611178737703889171730,
4614037031668406927330683909387957156531244689520944789503628527855167665518,
19647356996769918391113967168615123299113119185942498194367262335168397100658,
5040699236106090655289931820723926657076483236860546282406111821875672148900,
2632385916954580941368956176626336146806721642583847728103570779270161510514,
17691411851977575435597871505860208507285462834710151833948561098560743654671,
11482807709115676646560379017491661435505951727793345550942389701970904563183,
8360838254132998143349158726141014535383109403565779450210746881879715734773,
12663821244032248511491386323242575231591777785787269938928497649288048289525,
3067001377342968891237590775929219083706800062321980129409398033259904188058,
8536471869378957766675292398190944925664113548202769136103887479787957959589,
19825444354178182240559170937204690272111734703605805530888940813160705385792,
16703465144013840124940690347975638755097486902749048533167980887413919317592,
13061236261277650370863439564453267964462486225679643020432589226741411380501,
10864774797625152707517901967943775867717907803542223029967000416969007792571,
10035653564014594269791753415727486340557376923045841607746250017541686319774,
3446968588058668564420958894889124905706353937375068998436129414772610003289,
4653317306466493184743870159523234588955994456998076243468148492375236846006,
8486711143589723036499933521576871883500223198263343024003617825616410932026,
250710584458582618659378487568129931785810765264752039738223488321597070280,
2104159799604932521291371026105311735948154964200596636974609406977292675173,
16313562605837709339799839901240652934758303521543693857533755376563489378839,
6032365105133504724925793806318578936233045029919447519826248813478479197288,
14025118133847866722315446277964222215118620050302054655768867040006542798474,
7400123822125662712777833064081316757896757785777291653271747396958201309118,
1744432620323851751204287974553233986555641872755053103823939564833813704825,
8316378125659383262515151597439205374263247719876250938893842106722210729522,
6739722627047123650704294650168547689199576889424317598327664349670094847386,
21211457866117465531949733809706514799713333930924902519246949506964470524162,
13718112532745211817410303291774369209520657938741992779396229864894885156527,
5264534817993325015357427094323255342713527811596856940387954546330728068658,
18884137497114307927425084003812022333609937761793387700010402412840002189451,
5148596049900083984813839872929010525572543381981952060869301611018636120248,
19799686398774806587970184652860783461860993790013219899147141137827718662674,
19240878651604412704364448729659032944342952609050243268894572835672205984837,
10546185249390392695582524554167530669949955276893453512788278945742408153192,
5507959600969845538113649209272736011390582494851145043668969080335346810411,
18177751737739153338153217698774510185696788019377850245260475034576050820091,
19603444733183990109492724100282114612026332366576932662794133334264283907557,
10548274686824425401349248282213580046351514091431715597441736281987273193140,
1823201861560942974198127384034483127920205835821334101215923769688644479957,
11867589662193422187545516240823411225342068709600734253659804646934346124945,
18718569356736340558616379408444812528964066420519677106145092918482774343613,
10530777752259630125564678480897857853807637120039176813174150229243735996839,
20486583726592018813337145844457018474256372770211860618687961310422228379031,
12690713110714036569415168795200156516217175005650145422920562694422306200486,
17386427286863519095301372413760745749282643730629659997153085139065756667205,
2216432659854733047132347621569505613620980842043977268828076165669557467682,
6309765381643925252238633914530877025934201680691496500372265330505506717193,
20806323192073945401862788605803131761175139076694468214027227878952047793390,
4037040458505567977365391535756875199663510397600316887746139396052445718861,
19948974083684238245321361840704327952464170097132407924861169241740046562673,
845322671528508199439318170916419179535949348988022948153107378280175750024,
16222384601744433420585982239113457177459602187868460608565289920306145389382,
10232118865851112229330353999139005145127746617219324244541194256766741433339,
6699067738555349409504843460654299019000594109597429103342076743347235369120,
6220784880752427143725783746407285094967584864656399181815603544365010379208,
6129250029437675212264306655559561251995722990149771051304736001195288083309,
10773245783118750721454994239248013870822765715268323522295722350908043393604,
4490242021765793917495398271905043433053432245571325177153467194570741607167,
19596995117319480189066041930051006586888908165330319666010398892494684778526,
837850695495734270707668553360118467905109360511302468085569220634750561083,
11803922811376367215191737026157445294481406304781326649717082177394185903907,
10201298324909697255105265958780781450978049256931478989759448189112393506592,
13564695482314888817576351063608519127702411536552857463682060761575100923924,
9262808208636973454201420823766139682381973240743541030659775288508921362724,
173271062536305557219323722062711383294158572562695717740068656098441040230,
18120430890549410286417591505529104700901943324772175772035648111937818237369,
20484495168135072493552514219686101965206843697794133766912991150184337935627,
19155651295705203459475805213866664350848604323501251939850063308319753686505,
11971299749478202793661982361798418342615500543489781306376058267926437157297,
18285310723116790056148596536349375622245669010373674803854111592441823052978,
7069216248902547653615508023941692395371990416048967468982099270925308100727,
6465151453746412132599596984628739550147379072443683076388208843341824127379,
16143532858389170960690347742477978826830511669766530042104134302796355145785,
19362583304414853660976404410208489566967618125972377176980367224623492419647,
1702213613534733786921602839210290505213503664731919006932367875629005980493,
10781825404476535814285389902565833897646945212027592373510689209734812292327,
4212716923652881254737947578600828255798948993302968210248673545442808456151,
7594017890037021425366623750593200398174488805473151513558919864633711506220,
18979889247746272055963929241596362599320706910852082477600815822482192194401,
13602139229813231349386885113156901793661719180900395818909719758150455500533
];
var t;
signal t2[nrounds];
signal t4[nrounds];
signal t6[nrounds];
signal t7[nrounds-1];
for (var i=0; i<nrounds; i++) {
t = (i==0) ? k+x_in : k + t7[i-1] + c[i];
t2[i] <== t*t;
t4[i] <== t2[i]*t2[i];
t6[i] <== t4[i]*t2[i];
if (i<nrounds-1) {
t7[i] <== t6[i]*t;
} else {
out <== t6[i]*t + k;
}
}
}
template MultiMiMC7(nInputs, nRounds) {
signal input in[nInputs];
signal input k;
signal output out;
signal r[nInputs +1];
component mims[nInputs];
r[0] <== k;
for (var i=0; i<nInputs; i++) {
mims[i] = MiMC7(nRounds);
mims[i].x_in <== in[i];
mims[i].k <== r[i];
r[i+1] <== r[i] + in[i] + mims[i].out;
}
out <== r[nInputs];
} | https://github.com/socathie/circomlib-ml |
circuits/circomlib/montgomery.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Source: https://en.wikipedia.org/wiki/Montgomery_curve
1 + y 1 + y
[u, v] = [ ------- , ---------- ]
1 - y (1 - y)x
*/
pragma circom 2.0.0;
template Edwards2Montgomery() {
signal input in[2];
signal output out[2];
out[0] <-- (1 + in[1]) / (1 - in[1]);
out[1] <-- out[0] / in[0];
out[0] * (1-in[1]) === (1 + in[1]);
out[1] * in[0] === out[0];
}
/*
u u - 1
[x, y] = [ ---, ------- ]
v u + 1
*/
template Montgomery2Edwards() {
signal input in[2];
signal output out[2];
out[0] <-- in[0] / in[1];
out[1] <-- (in[0] - 1) / (in[0] + 1);
out[0] * in[1] === in[0];
out[1] * (in[0] + 1) === in[0] - 1;
}
/*
x2 - x1
lamda = ---------
y2 - y1
x3 + A + x1 + x2
x3 = B * lamda^2 - A - x1 -x2 => lamda^2 = ------------------
B
y3 = (2*x1 + x2 + A)*lamda - B*lamda^3 - y1 =>
=> y3 = lamda * ( 2*x1 + x2 + A - x3 - A - x1 - x2) - y1 =>
=> y3 = lamda * ( x1 - x3 ) - y1
----------
y2 - y1
lamda = ---------
x2 - x1
x3 = B * lamda^2 - A - x1 -x2
y3 = lamda * ( x1 - x3 ) - y1
*/
template MontgomeryAdd() {
signal input in1[2];
signal input in2[2];
signal output out[2];
var a = 168700;
var d = 168696;
var A = (2 * (a + d)) / (a - d);
var B = 4 / (a - d);
signal lamda;
lamda <-- (in2[1] - in1[1]) / (in2[0] - in1[0]);
lamda * (in2[0] - in1[0]) === (in2[1] - in1[1]);
out[0] <== B*lamda*lamda - A - in1[0] -in2[0];
out[1] <== lamda * (in1[0] - out[0]) - in1[1];
}
/*
x1_2 = x1*x1
3*x1_2 + 2*A*x1 + 1
lamda = ---------------------
2*B*y1
x3 = B * lamda^2 - A - x1 -x1
y3 = lamda * ( x1 - x3 ) - y1
*/
template MontgomeryDouble() {
signal input in[2];
signal output out[2];
var a = 168700;
var d = 168696;
var A = (2 * (a + d)) / (a - d);
var B = 4 / (a - d);
signal lamda;
signal x1_2;
x1_2 <== in[0] * in[0];
lamda <-- (3*x1_2 + 2*A*in[0] + 1 ) / (2*B*in[1]);
lamda * (2*B*in[1]) === (3*x1_2 + 2*A*in[0] + 1 );
out[0] <== B*lamda*lamda - A - 2*in[0];
out[1] <== lamda * (in[0] - out[0]) - in[1];
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/mux3.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
template MultiMux3(n) {
signal input c[n][8]; // Constants
signal input s[3]; // Selector
signal output out[n];
signal a210[n];
signal a21[n];
signal a20[n];
signal a2[n];
signal a10[n];
signal a1[n];
signal a0[n];
signal a[n];
// 4 constrains for the intermediary variables
signal s10;
s10 <== s[1] * s[0];
for (var i=0; i<n; i++) {
a210[i] <== ( c[i][ 7]-c[i][ 6]-c[i][ 5]+c[i][ 4] - c[i][ 3]+c[i][ 2]+c[i][ 1]-c[i][ 0] ) * s10;
a21[i] <== ( c[i][ 6]-c[i][ 4]-c[i][ 2]+c[i][ 0] ) * s[1];
a20[i] <== ( c[i][ 5]-c[i][ 4]-c[i][ 1]+c[i][ 0] ) * s[0];
a2[i] <== ( c[i][ 4]-c[i][ 0] );
a10[i] <== ( c[i][ 3]-c[i][ 2]-c[i][ 1]+c[i][ 0] ) * s10;
a1[i] <== ( c[i][ 2]-c[i][ 0] ) * s[1];
a0[i] <== ( c[i][ 1]-c[i][ 0] ) * s[0];
a[i] <== ( c[i][ 0] );
out[i] <== ( a210[i] + a21[i] + a20[i] + a2[i] ) * s[2] +
( a10[i] + a1[i] + a0[i] + a[i] );
}
}
template Mux3() {
var i;
signal input c[8]; // Constants
signal input s[3]; // Selector
signal output out;
component mux = MultiMux3(1);
for (i=0; i<8; i++) {
mux.c[0][i] <== c[i];
}
for (i=0; i<3; i++) {
s[i] ==> mux.s[i];
}
mux.out[0] ==> out;
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/sign.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
pragma circom 2.0.0;
include "compconstant.circom";
template Sign() {
signal input in[254];
signal output sign;
component comp = CompConstant(10944121435919637611123202872628637544274182200208017171849102093287904247808);
var i;
for (i=0; i<254; i++) {
comp.in[i] <== in[i];
}
sign <== comp.out;
}
| https://github.com/socathie/circomlib-ml |
circuits/circomlib/switcher.circom | /*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Assume sel is binary.
If sel == 0 then outL = L and outR=R
If sel == 1 then outL = R and outR=L
*/
pragma circom 2.0.0;
template Switcher() {
signal input sel;
signal input L;
signal input R;
signal output outL;
signal output outR;
signal aux;
aux <== (R-L)*sel; // We create aux in order to have only one multiplication
outL <== aux + L;
outR <== -aux + R;
}
| https://github.com/socathie/circomlib-ml |
circuits/crypto/ecdh.circom | // from privacy-scaling-explorations/maci
pragma circom 2.0.0;
include "../circomlib/bitify.circom";
include "../circomlib/escalarmulany.circom";
template Ecdh() {
// Note: private key
// Needs to be hashed, and then pruned before
// supplying it to the circuit
signal input private_key;
signal input public_key[2];
signal output shared_key;
component privBits = Num2Bits(253);
privBits.in <== private_key;
component mulFix = EscalarMulAny(253);
mulFix.p[0] <== public_key[0];
mulFix.p[1] <== public_key[1];
for (var i = 0; i < 253; i++) {
mulFix.e[i] <== privBits.out[i];
}
shared_key <== mulFix.out[0];
} | https://github.com/socathie/circomlib-ml |
circuits/crypto/encrypt.circom | //from zk-ml/linear-regression-demo
pragma circom 2.0.0;
include "../circomlib/mimc.circom";
template EncryptBits(N) {
signal input plaintext[N];
signal input shared_key;
signal output out[N+1];
component mimc = MultiMiMC7(N, 91);
for (var i=0; i<N; i++) {
mimc.in[i] <== plaintext[i];
}
mimc.k <== 0;
out[0] <== mimc.out;
component hasher[N];
for(var i=0; i<N; i++) {
hasher[i] = MiMC7(91);
hasher[i].x_in <== shared_key;
hasher[i].k <== out[0] + i;
out[i+1] <== plaintext[i] + hasher[i].out;
}
}
template Encrypt() {
signal input plaintext;
signal input shared_key;
signal output out[2];
component mimc = MultiMiMC7(1, 91);
mimc.in[0] <== plaintext;
mimc.k <== 0;
out[0] <== mimc.out;
component hasher;
hasher = MiMC7(91);
hasher.x_in <== shared_key;
hasher.k <== out[0];
out[1] <== plaintext + hasher.out;
}
template DecryptBits(N) {
signal input message[N+1];
signal input shared_key;
signal output out[N];
component hasher[N];
// iv is message[0]
for(var i=0; i<N; i++) {
hasher[i] = MiMC7(91);
hasher[i].x_in <== shared_key;
hasher[i].k <== message[0] + i;
out[i] <== message[i+1] - hasher[i].out;
}
}
template Decrypt() {
signal input message[2];
signal input shared_key;
signal output out;
component hasher;
// iv is message[0]
hasher = MiMC7(91);
hasher.x_in <== shared_key;
hasher.k <== message[0];
out <== message[1] - hasher.out;
} | https://github.com/socathie/circomlib-ml |
circuits/crypto/publickey_derivation.circom | // from privacy-scaling-explorations/maci
pragma circom 2.0.0;
include "../circomlib/bitify.circom";
include "../circomlib/escalarmulfix.circom";
template PublicKey() {
// Note: private key
// Needs to be hashed, and then pruned before
// supplying it to the circuit
signal input private_key;
signal output public_key[2];
component privBits = Num2Bits(253);
privBits.in <== private_key;
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component mulFix = EscalarMulFix(253, BASE8);
for (var i = 0; i < 253; i++) {
mulFix.e[i] <== privBits.out[i];
}
public_key[0] <== mulFix.out[0];
public_key[1] <== mulFix.out[1];
} | https://github.com/socathie/circomlib-ml |
circuits/util.circom | pragma circom 2.0.0;
include "./circomlib/sign.circom";
include "./circomlib/bitify.circom";
include "./circomlib/comparators.circom";
include "./circomlib/switcher.circom";
template IsNegative() {
signal input in;
signal output out;
component num2Bits = Num2Bits(254);
num2Bits.in <== in;
component sign = Sign();
for (var i = 0; i < 254; i++) {
sign.in[i] <== num2Bits.out[i];
}
out <== sign.sign;
}
/* Currently, IsPositive() treats zero as a positive number for better performance.
The following is the correct version which output is 1 when the signal in is a positive number, 0 when it is zero or a negative number
template IsPositive() {
signal input in;
signal output out;
component num2Bits = Num2Bits(254);
num2Bits.in <== in;
component sign = Sign();
for (var i = 0; i < 254; i++) {
sign.in[i] <== num2Bits.out[i];
}
component isz = IsZero();
isz.in <== in;
out <== (1 - sign.sign) * (1 - isz.out);
}
*/
template IsPositive() {
signal input in;
signal output out;
component num2Bits = Num2Bits(254);
num2Bits.in <== in;
component sign = Sign();
for (var i = 0; i < 254; i++) {
sign.in[i] <== num2Bits.out[i];
}
out <== 1 - sign.sign;
}
template Sum(nInputs) {
signal input in[nInputs];
signal output out;
signal partialSum[nInputs];
partialSum[0] <== in[0];
for (var i=1; i<nInputs; i++) {
partialSum[i] <== partialSum[i-1] + in[i];
}
out <== partialSum[nInputs-1];
}
template Max(n) {
signal input in[n];
signal output out;
component gts[n]; // store comparators
component switchers[n+1]; // switcher for comparing maxs
signal maxs[n+1];
maxs[0] <== in[0];
for(var i = 0; i < n; i++) {
gts[i] = GreaterThan(252); // changed to 252 (maximum) for better compatibility
switchers[i+1] = Switcher();
gts[i].in[1] <== maxs[i];
gts[i].in[0] <== in[i];
switchers[i+1].sel <== gts[i].out;
switchers[i+1].L <== maxs[i];
switchers[i+1].R <== in[i];
maxs[i+1] <== switchers[i+1].outL;
}
out <== maxs[n];
}
| https://github.com/socathie/circomlib-ml |
index.js | https://github.com/socathie/circomlib-ml |
|
models/averagePooling2d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, AveragePooling2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = AveragePooling2D(pool_size=2)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" average_pooling2d (AverageP (None, 2, 2, 3) 0 \n",
" ooling2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.4697424 , 0.26405168, 0.50556795],\n",
" [0.31879275, 0.10661064, 0.89969558],\n",
" [0.51674454, 0.44716256, 0.84376492],\n",
" [0.70730021, 0.23034467, 0.21298659],\n",
" [0.39270991, 0.26666702, 0.20998017]],\n",
"\n",
" [[0.06338963, 0.40992356, 0.65531956],\n",
" [0.65641348, 0.61781921, 0.71094249],\n",
" [0.66084759, 0.01212395, 0.96300368],\n",
" [0.05580187, 0.96245161, 0.20798007],\n",
" [0.94943203, 0.05702934, 0.37272236]],\n",
"\n",
" [[0.35969427, 0.24114588, 0.40254835],\n",
" [0.87560584, 0.29480004, 0.71005672],\n",
" [0.89799237, 0.03862642, 0.41636709],\n",
" [0.60385376, 0.00368971, 0.73375191],\n",
" [0.39912794, 0.02359739, 0.58151196]],\n",
"\n",
" [[0.75162628, 0.57732706, 0.51714415],\n",
" [0.42886868, 0.4817775 , 0.55461973],\n",
" [0.96844644, 0.72937866, 0.96170145],\n",
" [0.09311228, 0.70769801, 0.37766384],\n",
" [0.22594407, 0.64493633, 0.84161072]],\n",
"\n",
" [[0.94736999, 0.95913254, 0.66551587],\n",
" [0.12700579, 0.80182768, 0.24940166],\n",
" [0.26694546, 0.07422724, 0.87879383],\n",
" [0.26784968, 0.33568869, 0.71071351],\n",
" [0.36125259, 0.89039872, 0.57815661]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 28ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 19:58:12.306880: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.37708455, 0.34960127, 0.6928814 ],\n",
" [0.48517358, 0.41302067, 0.5569338 ]],\n",
"\n",
" [[0.6039488 , 0.39876258, 0.5460923 ],\n",
" [0.6408512 , 0.3698482 , 0.6223711 ]]]], dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n",
" remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n",
" for i in range((nRows-poolSize)//strides + 1):\n",
" for j in range((nCols-poolSize)//strides + 1):\n",
" for k in range(nChannels):\n",
" for x in range(poolSize):\n",
" for y in range(poolSize):\n",
" out[i][j][k] += input[i*strides+x][j*strides+y][k]\n",
" remainder[i][j][k] = str(out[i][j][k] % poolSize**2 % p)\n",
" out[i][j][k] = str(out[i][j][k] // poolSize**2 % p)\n",
" return Input, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['377084566964233814727207747512696832',\n",
" '349601274166158063422211165597466624',\n",
" '692881395085479491591287820028739584'],\n",
" ['485173550880783982864257598131011584',\n",
" '413020696901266553234304779809718272',\n",
" '556933813298750165384079226175488000']],\n",
" [['603948769893606922513439699094208512',\n",
" '398762621026204510661452706879635456',\n",
" '546092235924829818623026255726903296'],\n",
" ['640851212450790063364758949182046208',\n",
" '369848200094279040953444891822653440',\n",
" '622371069389430669959468896315506688']]],\n",
" [[['0', '0', '0'], ['0', '0', '0']], [['0', '0', '0'], ['0', '0', '0']]])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, out, remainder = AveragePooling2DInt(5, 5, 3, 2, 2, X_in)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out,\n",
" \"remainder\": remainder \n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"with open(\"averagePooling2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(10,10,3))\n",
"x = AveragePooling2D(pool_size=3, strides=2)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_1\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n",
" \n",
" average_pooling2d_1 (Averag (None, 4, 4, 3) 0 \n",
" ePooling2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"X = np.random.rand(1,10,10,3)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 20ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.49083894, 0.6503702 , 0.45121744],\n",
" [0.3731585 , 0.55850077, 0.5209063 ],\n",
" [0.392081 , 0.4962937 , 0.44958603],\n",
" [0.5062166 , 0.5363207 , 0.5836957 ]],\n",
"\n",
" [[0.4387001 , 0.51550937, 0.4842767 ],\n",
" [0.36599833, 0.6358112 , 0.42103994],\n",
" [0.45892367, 0.48430002, 0.48299968],\n",
" [0.47987926, 0.51054746, 0.48522002]],\n",
"\n",
" [[0.4337698 , 0.5966541 , 0.34484175],\n",
" [0.50603914, 0.54209197, 0.3464988 ],\n",
" [0.5383602 , 0.40848657, 0.5954534 ],\n",
" [0.39340922, 0.5384207 , 0.6712477 ]],\n",
"\n",
" [[0.52239245, 0.61681217, 0.5948292 ],\n",
" [0.6456814 , 0.56172687, 0.5704497 ],\n",
" [0.5970895 , 0.65395427, 0.61463684],\n",
" [0.49751964, 0.57090425, 0.50965226]]]], dtype=float32)"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['490838913202839647482031788613930552',\n",
" '650370206452327739765809362325238215',\n",
" '451217443243932157150820354890924032'],\n",
" ['373158499178459549901037286246696732',\n",
" '558500757386374812373354359379751367',\n",
" '520906395265463287758066336793158542'],\n",
" ['392081032582640205401569336636735488',\n",
" '496293715863929836162024945736366307',\n",
" '449586010677657401563374125861539384'],\n",
" ['506216538770442893696705511483535815',\n",
" '536320651604328640569669741910920760',\n",
" '583695794530695154314058797408758442']],\n",
" [['438700122269240629018040116487826090',\n",
" '515509373055967873846597732290585486',\n",
" '484276697106518139982691888834194090'],\n",
" ['365998311298275897695359121353838136',\n",
" '635811225512657877386382358476401322',\n",
" '421039958668517212332658528902359722'],\n",
" ['458923652827692860008536397550744007',\n",
" '484300011977437346144682467789664711',\n",
" '482999719051088512471698660426980465'],\n",
" ['479879293099700576539663622281305201',\n",
" '510547498500066698646970955137781304',\n",
" '485220023120638790352795312775961713']],\n",
" [['433769787149101139024853526875005838',\n",
" '596654066230626723871865644707566933',\n",
" '344841746939097107506453705665223793'],\n",
" ['506039134280922806908200932494569927',\n",
" '542091990692138506014454460431291733',\n",
" '346498783957661696012159449997712497'],\n",
" ['538360180533623713187861074538630712',\n",
" '408486572499003056002511420888099498',\n",
" '595453351874211229959940839550251463'],\n",
" ['393409252869458006979621409013687182',\n",
" '538420708502221204218833774810030990',\n",
" '671247738849324010704751775607772501']],\n",
" [['522392440772653872755969912709229226',\n",
" '616812156272961914033749036925481415',\n",
" '594829232057008563695532312541731953'],\n",
" ['645681406847045116741310894926637738',\n",
" '561726846190701362338877345898226574',\n",
" '570449710887660887892445378356008277'],\n",
" ['597089469987715047812261496899676842',\n",
" '653954298836488871344502997077750215',\n",
" '614636841404824230076303162630384298'],\n",
" ['497519650100367473493056256852390343',\n",
" '570904266316369826537673219489981326',\n",
" '509652208506601100112410974135488056']]],\n",
" [[['8', '1', '0'], ['4', '1', '2'], ['0', '5', '8'], ['1', '8', '6']],\n",
" [['6', '2', '6'], ['8', '6', '6'], ['1', '1', '7'], ['7', '8', '7']],\n",
" [['2', '3', '7'], ['1', '3', '7'], ['8', '6', '1'], ['2', '2', '3']],\n",
" [['6', '1', '7'], ['6', '2', '3'], ['6', '1', '6'], ['1', '2', '8']]])"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, out, remainder = AveragePooling2DInt(10, 10, 3, 3, 2, X_in)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"with open(\"averagePooling2D_stride_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/batchNormalization.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, BatchNormalization, Dense, Flatten\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"out = BatchNormalization()(inputs)\n",
"out = Flatten()(out)\n",
"out = Dense(1)(out)\n",
"model = Model(inputs, out)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" batch_normalization (BatchN (None, 5, 5, 3) 12 \n",
" ormalization) \n",
" \n",
" flatten (Flatten) (None, 75) 0 \n",
" \n",
" dense (Dense) (None, 1) 76 \n",
" \n",
"=================================================================\n",
"Total params: 88\n",
"Trainable params: 82\n",
"Non-trainable params: 6\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.51546565, 0.46651282, 0.78133227],\n",
" [0.29092001, 0.15424294, 0.31568105],\n",
" [0.42554169, 0.17798232, 0.88401623],\n",
" [0.89061342, 0.56954272, 0.0481971 ],\n",
" [0.91385411, 0.87839928, 0.54333657]],\n",
"\n",
" [[0.06954288, 0.9189417 , 0.16824991],\n",
" [0.61834797, 0.48611683, 0.05698664],\n",
" [0.54958275, 0.40614748, 0.93471022],\n",
" [0.96738304, 0.9310907 , 0.05346684],\n",
" [0.01504873, 0.45594357, 0.92055095]],\n",
"\n",
" [[0.11021081, 0.40673465, 0.56412873],\n",
" [0.5385549 , 0.06119234, 0.5499304 ],\n",
" [0.409637 , 0.72651771, 0.71666944],\n",
" [0.99635655, 0.13653654, 0.10949123],\n",
" [0.2601131 , 0.70956364, 0.51173637]],\n",
"\n",
" [[0.29500952, 0.50029805, 0.48711255],\n",
" [0.58302715, 0.07682466, 0.06070311],\n",
" [0.63143749, 0.55553472, 0.62363371],\n",
" [0.34286961, 0.28562232, 0.10381272],\n",
" [0.5267341 , 0.44532117, 0.74259914]],\n",
"\n",
" [[0.89833895, 0.70393118, 0.3390096 ],\n",
" [0.31743696, 0.27991868, 0.41889825],\n",
" [0.88849899, 0.36099248, 0.8606479 ],\n",
" [0.8115506 , 0.9383675 , 0.29448095],\n",
" [0.97113074, 0.58140933, 0.96698766]]],\n",
"\n",
"\n",
" [[[0.22152899, 0.69173392, 0.10892224],\n",
" [0.45291025, 0.87475282, 0.78825403],\n",
" [0.30206652, 0.65193234, 0.74018285],\n",
" [0.28822764, 0.82794295, 0.88511038],\n",
" [0.65083834, 0.65900742, 0.37215784]],\n",
"\n",
" [[0.42637533, 0.82491213, 0.99759185],\n",
" [0.5311499 , 0.71585492, 0.35118 ],\n",
" [0.24486032, 0.91171808, 0.77877967],\n",
" [0.1899115 , 0.01429132, 0.53225576],\n",
" [0.26831007, 0.3223111 , 0.2793977 ]],\n",
"\n",
" [[0.43628462, 0.855694 , 0.45144496],\n",
" [0.17713725, 0.6788593 , 0.53221073],\n",
" [0.24239035, 0.29885874, 0.00793102],\n",
" [0.47036933, 0.83716811, 0.01747103],\n",
" [0.52148184, 0.88785307, 0.19371033]],\n",
"\n",
" [[0.45964463, 0.11785621, 0.71888447],\n",
" [0.37170738, 0.91271932, 0.28649456],\n",
" [0.3974761 , 0.54316076, 0.56468016],\n",
" [0.65716588, 0.00913184, 0.42107159],\n",
" [0.62804608, 0.19359813, 0.13687296]],\n",
"\n",
" [[0.15432216, 0.24376177, 0.73777443],\n",
" [0.37740194, 0.51219611, 0.18536464],\n",
" [0.00561986, 0.63145406, 0.57055781],\n",
" [0.45424905, 0.46157587, 0.87326481],\n",
" [0.44888708, 0.09268558, 0.54308092]]],\n",
"\n",
"\n",
" [[[0.44003404, 0.82605955, 0.53120479],\n",
" [0.34508592, 0.54358359, 0.63107103],\n",
" [0.18258236, 0.5828249 , 0.35215564],\n",
" [0.35995517, 0.58247612, 0.866913 ],\n",
" [0.37331628, 0.72105525, 0.86011076]],\n",
"\n",
" [[0.0037806 , 0.80184814, 0.19458159],\n",
" [0.01779705, 0.68048193, 0.08877037],\n",
" [0.72192341, 0.94542319, 0.7099795 ],\n",
" [0.38773382, 0.0054821 , 0.86694736],\n",
" [0.59622908, 0.88670846, 0.54186724]],\n",
"\n",
" [[0.91125128, 0.24628816, 0.91306807],\n",
" [0.20544878, 0.6600348 , 0.02261235],\n",
" [0.08034128, 0.50809017, 0.37310936],\n",
" [0.66526679, 0.6763669 , 0.3438879 ],\n",
" [0.54922619, 0.05982564, 0.21239447]],\n",
"\n",
" [[0.09812086, 0.36775343, 0.23264159],\n",
" [0.07952414, 0.14821264, 0.30500863],\n",
" [0.78574487, 0.20629136, 0.28249732],\n",
" [0.18532948, 0.62820359, 0.40885501],\n",
" [0.53428171, 0.01419418, 0.96868481]],\n",
"\n",
" [[0.46122128, 0.60562586, 0.19714442],\n",
" [0.83266218, 0.62255273, 0.48534285],\n",
" [0.78304596, 0.63898229, 0.91084764],\n",
" [0.04902518, 0.69016331, 0.16760015],\n",
" [0.88179687, 0.02644824, 0.78977572]]],\n",
"\n",
"\n",
" ...,\n",
"\n",
"\n",
" [[[0.17074279, 0.10103348, 0.63216146],\n",
" [0.32308489, 0.88627716, 0.84782501],\n",
" [0.1032571 , 0.02331302, 0.36067615],\n",
" [0.01463099, 0.89390044, 0.7491627 ],\n",
" [0.94200448, 0.90298754, 0.55947368]],\n",
"\n",
" [[0.7041535 , 0.39417727, 0.07809514],\n",
" [0.52135847, 0.0290839 , 0.45233884],\n",
" [0.71856329, 0.81167091, 0.9178133 ],\n",
" [0.02404749, 0.49104236, 0.21492727],\n",
" [0.15136666, 0.01310515, 0.29748093]],\n",
"\n",
" [[0.88120014, 0.16076401, 0.44107649],\n",
" [0.25002897, 0.68659302, 0.01653978],\n",
" [0.96055884, 0.40286758, 0.11771713],\n",
" [0.66927334, 0.77825925, 0.30680967],\n",
" [0.31482238, 0.7749523 , 0.11406879]],\n",
"\n",
" [[0.53919419, 0.60783489, 0.55848085],\n",
" [0.32747631, 0.09879024, 0.28296219],\n",
" [0.65211663, 0.70552049, 0.55715698],\n",
" [0.31646225, 0.26783995, 0.47998016],\n",
" [0.37794728, 0.42765623, 0.97190187]],\n",
"\n",
" [[0.53879646, 0.45261775, 0.46913403],\n",
" [0.2670922 , 0.79348712, 0.49027602],\n",
" [0.25085863, 0.10323594, 0.15697154],\n",
" [0.31783142, 0.54529695, 0.90404337],\n",
" [0.11790291, 0.15503706, 0.86422424]]],\n",
"\n",
"\n",
" [[[0.16965053, 0.19585652, 0.57609002],\n",
" [0.88591501, 0.90486881, 0.29608075],\n",
" [0.4261748 , 0.91284255, 0.40807448],\n",
" [0.9686301 , 0.74409545, 0.1479126 ],\n",
" [0.76802611, 0.07944974, 0.7871578 ]],\n",
"\n",
" [[0.77475062, 0.40398437, 0.22643119],\n",
" [0.0104928 , 0.38809633, 0.48776304],\n",
" [0.22491731, 0.94079457, 0.97114209],\n",
" [0.65810206, 0.9100557 , 0.24727223],\n",
" [0.05758432, 0.54125367, 0.01468728]],\n",
"\n",
" [[0.71953982, 0.17153423, 0.74242277],\n",
" [0.69007692, 0.16985619, 0.40592314],\n",
" [0.54681391, 0.5548588 , 0.47674301],\n",
" [0.57911416, 0.28571978, 0.39200726],\n",
" [0.11671085, 0.35797023, 0.65890719]],\n",
"\n",
" [[0.85257004, 0.7955835 , 0.66530167],\n",
" [0.60683054, 0.66667651, 0.58183113],\n",
" [0.95010415, 0.77982033, 0.48321958],\n",
" [0.73954001, 0.21177226, 0.40730859],\n",
" [0.58235681, 0.54621676, 0.72576091]],\n",
"\n",
" [[0.78679585, 0.07508165, 0.7500122 ],\n",
" [0.52093211, 0.58039123, 0.46972807],\n",
" [0.96323894, 0.99445506, 0.73634561],\n",
" [0.79991676, 0.66932491, 0.83293889],\n",
" [0.20586253, 0.41194998, 0.43086448]]],\n",
"\n",
"\n",
" [[[0.39755238, 0.44572733, 0.14839841],\n",
" [0.85064056, 0.46063306, 0.48205451],\n",
" [0.71843235, 0.16096294, 0.68091537],\n",
" [0.53677884, 0.1177746 , 0.2540637 ],\n",
" [0.27248667, 0.53513208, 0.88182579]],\n",
"\n",
" [[0.41187651, 0.77931731, 0.24484454],\n",
" [0.79766554, 0.41731159, 0.95576332],\n",
" [0.72876755, 0.27933312, 0.3082945 ],\n",
" [0.76694795, 0.74242235, 0.62142724],\n",
" [0.97480578, 0.35289907, 0.64357369]],\n",
"\n",
" [[0.00510661, 0.36997422, 0.16220858],\n",
" [0.9872583 , 0.95501977, 0.15935416],\n",
" [0.78867534, 0.54122521, 0.54486478],\n",
" [0.03354764, 0.05670898, 0.47520133],\n",
" [0.04376703, 0.69549825, 0.3957491 ]],\n",
"\n",
" [[0.84051762, 0.79462166, 0.30602544],\n",
" [0.25025524, 0.08666752, 0.69194498],\n",
" [0.67076409, 0.13492286, 0.4590991 ],\n",
" [0.20405993, 0.07903494, 0.70707305],\n",
" [0.83720425, 0.75953423, 0.81481202]],\n",
"\n",
" [[0.19551102, 0.46499979, 0.50975971],\n",
" [0.81569678, 0.34130601, 0.76208935],\n",
" [0.82885678, 0.10476159, 0.13018122],\n",
" [0.26689358, 0.79482095, 0.75352521],\n",
" [0.58703011, 0.11749016, 0.19427432]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_train = np.random.rand(100,5,5,3)\n",
"X_train"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.21946477],\n",
" [0.3711923 ],\n",
" [0.24737705],\n",
" [0.16344551],\n",
" [0.57433513],\n",
" [0.76673914],\n",
" [0.7049643 ],\n",
" [0.67571894],\n",
" [0.15141958],\n",
" [0.84983105],\n",
" [0.05552415],\n",
" [0.95604334],\n",
" [0.70679183],\n",
" [0.86247509],\n",
" [0.01407803],\n",
" [0.55736261],\n",
" [0.19422897],\n",
" [0.86008897],\n",
" [0.2779906 ],\n",
" [0.55527211],\n",
" [0.16247257],\n",
" [0.13970005],\n",
" [0.92248072],\n",
" [0.93564244],\n",
" [0.28634139],\n",
" [0.23594509],\n",
" [0.44848018],\n",
" [0.35401733],\n",
" [0.99775489],\n",
" [0.1732102 ],\n",
" [0.81910272],\n",
" [0.46522896],\n",
" [0.99489404],\n",
" [0.55781089],\n",
" [0.13592596],\n",
" [0.43879534],\n",
" [0.81024602],\n",
" [0.94877655],\n",
" [0.75248092],\n",
" [0.30265859],\n",
" [0.42836091],\n",
" [0.59454105],\n",
" [0.43154069],\n",
" [0.67468033],\n",
" [0.58606549],\n",
" [0.1744458 ],\n",
" [0.49333982],\n",
" [0.06740779],\n",
" [0.00943958],\n",
" [0.4099619 ],\n",
" [0.49609765],\n",
" [0.31434293],\n",
" [0.24492819],\n",
" [0.27013361],\n",
" [0.69482176],\n",
" [0.93217975],\n",
" [0.57115641],\n",
" [0.64785497],\n",
" [0.09918379],\n",
" [0.55192952],\n",
" [0.81989582],\n",
" [0.05051461],\n",
" [0.93054128],\n",
" [0.67387306],\n",
" [0.76534683],\n",
" [0.6162766 ],\n",
" [0.96975296],\n",
" [0.79504513],\n",
" [0.42467985],\n",
" [0.11096869],\n",
" [0.22852679],\n",
" [0.65542355],\n",
" [0.35148172],\n",
" [0.77244589],\n",
" [0.35624866],\n",
" [0.2630125 ],\n",
" [0.20241856],\n",
" [0.35342962],\n",
" [0.4200376 ],\n",
" [0.21397308],\n",
" [0.38814001],\n",
" [0.82781448],\n",
" [0.14303959],\n",
" [0.83622505],\n",
" [0.19489373],\n",
" [0.50839397],\n",
" [0.94387189],\n",
" [0.26870297],\n",
" [0.66940445],\n",
" [0.31928558],\n",
" [0.25835398],\n",
" [0.59484484],\n",
" [0.21550068],\n",
" [0.19920632],\n",
" [0.85037438],\n",
" [0.64880356],\n",
" [0.19659417],\n",
" [0.12815503],\n",
" [0.70278136],\n",
" [0.65639473]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_train = np.random.rand(100,1)\n",
"y_train"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/10\n",
"4/4 [==============================] - 0s 2ms/step - loss: 2.7752\n",
"Epoch 2/10\n",
"4/4 [==============================] - 0s 979us/step - loss: 2.6586\n",
"Epoch 3/10\n",
"4/4 [==============================] - 0s 649us/step - loss: 2.5723\n",
"Epoch 4/10\n",
"4/4 [==============================] - 0s 2ms/step - loss: 2.4804\n",
"Epoch 5/10\n",
"4/4 [==============================] - 0s 1ms/step - loss: 2.3874\n",
"Epoch 6/10\n",
"4/4 [==============================] - 0s 762us/step - loss: 2.2941\n",
"Epoch 7/10\n",
"4/4 [==============================] - 0s 889us/step - loss: 2.2374\n",
"Epoch 8/10\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 20:00:14.999431: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"4/4 [==============================] - 0s 15ms/step - loss: 2.1879\n",
"Epoch 9/10\n",
"4/4 [==============================] - 0s 987us/step - loss: 2.1199\n",
"Epoch 10/10\n",
"4/4 [==============================] - 0s 1ms/step - loss: 2.0514\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x12dea6fa0>"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.compile(\"adam\", \"mse\")\n",
"model.fit(X_train, y_train, epochs=10)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<tf.Variable 'batch_normalization/gamma:0' shape=(3,) dtype=float32, numpy=array([0.9704942, 0.9639488, 0.9704298], dtype=float32)>,\n",
" <tf.Variable 'batch_normalization/beta:0' shape=(3,) dtype=float32, numpy=array([ 0.02682306, -0.02748435, 0.02756111], dtype=float32)>,\n",
" <tf.Variable 'batch_normalization/moving_mean:0' shape=(3,) dtype=float32, numpy=array([0.16209687, 0.1706537 , 0.16507432], dtype=float32)>,\n",
" <tf.Variable 'batch_normalization/moving_variance:0' shape=(3,) dtype=float32, numpy=array([0.6963565, 0.6966989, 0.6962899], dtype=float32)>]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.layers[1].weights"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.27455621, 0.27884516, 0.7259278 ],\n",
" [0.53377714, 0.6519488 , 0.86514377],\n",
" [0.49080768, 0.65021787, 0.68419028],\n",
" [0.0618392 , 0.02673969, 0.57868236],\n",
" [0.85494917, 0.71864642, 0.38163087]],\n",
"\n",
" [[0.22703165, 0.33350008, 0.85208601],\n",
" [0.86850824, 0.43578265, 0.70671478],\n",
" [0.75415054, 0.97444638, 0.48606382],\n",
" [0.14784358, 0.45406111, 0.08556609],\n",
" [0.20530247, 0.25450988, 0.51542351]],\n",
"\n",
" [[0.13544047, 0.01932561, 0.22823691],\n",
" [0.64891188, 0.18616972, 0.46087849],\n",
" [0.81283055, 0.5325164 , 0.32305024],\n",
" [0.75351508, 0.14501534, 0.44999686],\n",
" [0.42234362, 0.06347228, 0.63881747]],\n",
"\n",
" [[0.85467296, 0.80260163, 0.14398915],\n",
" [0.57931829, 0.53329564, 0.7187654 ],\n",
" [0.80024988, 0.96224997, 0.8937722 ],\n",
" [0.33025203, 0.91751174, 0.62203916],\n",
" [0.93176317, 0.72790829, 0.14862771]],\n",
"\n",
" [[0.60466651, 0.567648 , 0.37182924],\n",
" [0.76271487, 0.11624398, 0.81946002],\n",
" [0.4389968 , 0.90003205, 0.19711127],\n",
" [0.67622958, 0.53012144, 0.37373778],\n",
" [0.97509719, 0.48172791, 0.63218788]]]])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 32ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[ 0.1575187 , 0.09737267, 0.67934984],\n",
" [ 0.45877463, 0.5279483 , 0.8411379 ],\n",
" [ 0.40883726, 0.52595073, 0.63084507],\n",
" [-0.0896923 , -0.19356653, 0.50823045],\n",
" [ 0.83202755, 0.60491985, 0.27922952]],\n",
"\n",
" [[ 0.10228759, 0.16044651, 0.8259631 ],\n",
" [ 0.84778535, 0.2784844 , 0.65702164],\n",
" [ 0.7148835 , 0.9001226 , 0.40059495],\n",
" [ 0.01025847, 0.29957846, -0.06483836],\n",
" [ 0.07703484, 0.06928882, 0.43471497]],\n",
"\n",
" [[-0.00415592, -0.20212264, 0.10096472],\n",
" [ 0.5925795 , -0.00957828, 0.37132615],\n",
" [ 0.7830791 , 0.39011884, 0.21115081],\n",
" [ 0.714145 , -0.05707199, 0.3586802 ],\n",
" [ 0.32927114, -0.15117574, 0.5781157 ]],\n",
"\n",
" [[ 0.8317066 , 0.7018073 , 0.00305727],\n",
" [ 0.5117007 , 0.39101806, 0.6710261 ],\n",
" [ 0.7684583 , 0.88604754, 0.8744081 ],\n",
" [ 0.22224607, 0.83441794, 0.558617 ],\n",
" [ 0.92129767, 0.6156084 , 0.0084479 ]],\n",
"\n",
" [[ 0.54115933, 0.43066198, 0.26783872],\n",
" [ 0.72483665, -0.09027521, 0.78804713],\n",
" [ 0.34862483, 0.81424564, 0.06479244],\n",
" [ 0.624327 , 0.38735494, 0.2700567 ],\n",
" [ 0.97165865, 0.33150697, 0.5704112 ]]]], dtype=float32)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"new_model = Model(inputs, model.layers[1].output)\n",
"y = new_model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"gamma = model.layers[1].weights[0].numpy()\n",
"beta = model.layers[1].weights[1].numpy()\n",
"moving_mean = model.layers[1].weights[2].numpy()\n",
"moving_var = model.layers[1].weights[3].numpy()\n",
"epsilon = model.layers[1].epsilon"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"a = gamma/(moving_var+epsilon)**.5\n",
"b = beta-gamma*moving_mean/(moving_var+epsilon)**.5"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[ 1.38897775e-08, -4.41621682e-09, -1.46314817e-08],\n",
" [ 1.22362858e-08, 2.73325588e-08, -4.77779197e-08],\n",
" [-1.14818392e-08, -8.60447691e-09, -5.83081214e-08],\n",
" [-5.10371694e-09, -8.67723293e-09, 2.98262304e-10],\n",
" [-7.37144357e-09, -6.87929902e-09, -3.09108445e-08]],\n",
"\n",
" [[-3.70238870e-09, 9.08749898e-09, 6.04406457e-08],\n",
" [-8.04363320e-09, -2.61427017e-08, -4.75678711e-08],\n",
" [-2.29807172e-08, -3.35601555e-08, -3.61847423e-08],\n",
" [ 1.76612667e-09, -8.73801476e-10, 2.36584587e-09],\n",
" [ 5.96964625e-09, -1.35698691e-08, -2.09152273e-09]],\n",
"\n",
" [[-2.18008088e-09, 3.40718009e-09, 1.14725877e-09],\n",
" [ 7.83470533e-09, -4.13062541e-09, -2.05064118e-08],\n",
" [ 5.68865103e-08, 3.01907888e-08, -1.38190100e-08],\n",
" [-2.30006845e-08, -8.84019241e-09, -3.75235497e-08],\n",
" [-1.33667987e-08, 2.45791437e-09, 1.05576055e-08]],\n",
"\n",
" [[ 1.63983768e-08, 4.34060976e-09, 7.69416812e-09],\n",
" [ 1.96461017e-08, -2.64836226e-08, -5.55432413e-08],\n",
" [ 1.60446652e-08, 3.83262573e-08, 3.27252936e-08],\n",
" [-1.79053708e-08, 3.49677078e-08, 2.28655761e-09],\n",
" [ 3.06888477e-08, -6.37458319e-09, -7.83266337e-10]],\n",
"\n",
" [[ 3.44015694e-09, -2.27795071e-08, -3.66268776e-09],\n",
" [ 8.27864410e-09, -8.66295551e-09, -9.44552192e-09],\n",
" [ 3.77712691e-08, -4.68591560e-08, -7.31272758e-09],\n",
" [ 1.90310351e-08, 2.21921187e-09, -1.20205449e-08],\n",
" [-1.50930767e-08, -1.72539832e-08, 6.61672261e-09]]]])"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y-(gamma*(X-moving_mean)/((moving_var+epsilon)**.5)+beta)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[ 6.29271463e-09, -1.51612348e-08, 4.78305939e-09],\n",
" [ 2.53706245e-09, 1.56956936e-08, -2.51350980e-08],\n",
" [-2.08326003e-08, -2.02372046e-08, -3.98614322e-08],\n",
" [-1.09757444e-08, -1.88196314e-08, 1.62983274e-08],\n",
" [-1.96752217e-08, -1.86755947e-08, -1.94802087e-08]],\n",
"\n",
" [[-1.09140497e-08, -1.78816328e-09, 8.27806710e-08],\n",
" [-2.04573691e-08, -3.72628548e-08, -2.85988609e-08],\n",
" [-3.44670656e-08, -4.59679019e-08, -2.23324095e-08],\n",
" [-4.80335610e-09, -1.20376463e-08, 6.93103225e-09],\n",
" [-1.06580120e-09, -2.42567173e-08, 1.24416322e-08]],\n",
"\n",
" [[-8.64898020e-09, -6.71749611e-09, 9.02084041e-09],\n",
" [-2.79820678e-09, -1.46541169e-08, -7.23810212e-09],\n",
" [ 4.49242945e-08, 1.88394085e-08, -3.74680098e-09],\n",
" [-3.44818796e-08, -1.92653107e-08, -2.45075741e-08],\n",
" [-2.21623482e-08, -7.77228767e-09, 2.79521442e-08]],\n",
"\n",
" [[ 4.09683865e-09, -7.65636798e-09, 1.36141277e-08],\n",
" [ 9.57756097e-09, -3.78368655e-08, -3.62947893e-08],\n",
" [ 4.18447266e-09, 2.59476647e-08, 5.60319802e-08],\n",
" [-2.59541007e-08, 2.26960550e-08, 1.92920239e-08],\n",
" [ 1.77621440e-08, -1.81930180e-08, 5.24425681e-09]],\n",
"\n",
" [[-6.83394596e-09, -3.42148641e-08, 7.54065804e-09],\n",
" [-3.27715710e-09, -1.90193002e-08, 1.21379391e-08],\n",
" [ 2.88406700e-08, -5.90890261e-08, -1.60918778e-10],\n",
" [ 8.17658918e-09, -9.12644371e-09, -7.72941988e-10],\n",
" [-2.83711992e-08, -2.84839613e-08, 2.38575276e-08]]]])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y-(a*X+b)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\n",
"a_in = [int(a[i]*1e36) for i in range(3)]\n",
"b_in = [int(b[i]*1e72) for i in range(3)]"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"def BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\n",
" X = [[[str(X_in[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" A = [str(a_in[k] % p) for k in range(nChannels)]\n",
" B = [str(b_in[k] % p) for k in range(nChannels)]\n",
" out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n",
" remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n",
" for i in range(nRows):\n",
" for j in range(nCols):\n",
" for k in range(nChannels):\n",
" out[i][j][k] = (X_in[i][j][k]*a_in[k] + b_in[k])\n",
" remainder[i][j][k] = str(out[i][j][k] % n)\n",
" out[i][j][k] = str(out[i][j][k] // n % p)\n",
" return X, A, B, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['157518693472490790243750538747957882',\n",
" '97372681162554733176887955075564208',\n",
" '679349834904288174010983420548472594'],\n",
" ['458774623717973004897590573896222594',\n",
" '527948304216263291457870336316333444',\n",
" '841137911182461164557826291121517336'],\n",
" ['408837279648365652067755038590177210',\n",
" '525950750084159001810559673300027574',\n",
" '630845109746686169695072155498068928'],\n",
" ['21888242871839275222246405745257275088548274708124961881757683904418357553907',\n",
" '21888242871839275222246405745257275088548170833903911058199291157862382757945',\n",
" '508230431470837755985412821877993851'],\n",
" ['832027574187245701393604967574752718',\n",
" '604919869501858267645833548353564313',\n",
" '279229541231612628393358090302516442']],\n",
" [['102287601417742280387289538163651204',\n",
" '160446511507058261099060517183710523',\n",
" '825962997148680811368987640325934077'],\n",
" ['847785374117952740336862359672140583',\n",
" '278484441349921535654657902103684959',\n",
" '657021670330123182657390893609651294'],\n",
" ['714883540765130856969303509707571514',\n",
" '900122628880346975580290622927866446',\n",
" '400594972054699631420351232955312561'],\n",
" ['10258476396616863842152239203344050',\n",
" '299578470108401435866442829726136156',\n",
" '21888242871839275222246405745257275088548299562044382966913364566037249574881'],\n",
" ['77034839563439930876087711734475167',\n",
" '69288844285022374454862035586080571',\n",
" '434714960531237722761063240822063770']],\n",
" [['21888242871839275222246405745257275088548360244503864875852868041600221908663',\n",
" '21888242871839275222246405745257275088548162277779161866355363655040683885335',\n",
" '100964708546126595514097434616933959'],\n",
" ['592579486784107682988589813640686405',\n",
" '21888242871839275222246405745257275088548354822146812280026576875315705275880',\n",
" '371326155748081420061854877950882957'],\n",
" ['783079042809927963587133644460156189',\n",
" '390118818517159008054052294744317319',\n",
" '211150813869290941494836799384423040'],\n",
" ['714145039231177651343799972971259701',\n",
" '21888242871839275222246405745257275088548307328444034834297413996208073048117',\n",
" '358680213163427345690379627175515214'],\n",
" ['329271159876734251530552022145153369',\n",
" '21888242871839275222246405745257275088548213224686425649934303811174716724822',\n",
" '578115673723270972200332905482236663']],\n",
" [['831706579403069869857935985454018004',\n",
" '701807327774318518191690249279384790',\n",
" '3057252040078645241914286618837645'],\n",
" ['511700680215072064258322477636183971',\n",
" '391018100666836853673874037122153517',\n",
" '671026146943898182863942504121469642'],\n",
" ['768458302604925592394191747899082690',\n",
" '886047516147519780735326653713713464',\n",
" '874408069845400225234489253410344667'],\n",
" ['222246091689917701515896532244187761',\n",
" '834417916490041372048913944859818527',\n",
" '558616976519438572914283702703657983'],\n",
" ['921297651648561583336105580618598710',\n",
" '615608412338983701988855791011481577',\n",
" '8447895170210076430444298018909113']],\n",
" [['541159338632499440419779390078898826',\n",
" '430662010552296997105829163483722657',\n",
" '267838708966299969534341921959286450'],\n",
" ['724836650787685688836352855376326828',\n",
" '21888242871839275222246405745257275088548274125221931276103456351742703907060',\n",
" '788047122738312175009071698929184108'],\n",
" ['348624796636930142430096079480218740',\n",
" '814245700320563240509607601046393243',\n",
" '64792439502463893211811777556988475'],\n",
" ['624326995779251861311046568986208844',\n",
" '387354949302453930827325825546488462',\n",
" '270056695518959509623672894764882809'],\n",
" ['971658675431593506453919504060069966',\n",
" '331506996028517098372582336349879273',\n",
" '570411181434220420525142442837712479']]],\n",
" [[['960480586600175329574532373343633408',\n",
" '16700446728492295766061281370439680',\n",
" '379639810818394963719156481312948224'],\n",
" ['388476442819984282074088736716488704',\n",
" '605933780470969152068605021142384640',\n",
" '798916055303936274984266387226099712'],\n",
" ['468208661324380829760178449488543744',\n",
" '819358397205938578920215010284142592',\n",
" '21589625405262166471345886990434304'],\n",
" ['697307730873745656946722950128599040',\n",
" '484544812284374194987581109665005568',\n",
" '165375951315867937763795967171100672'],\n",
" ['245646470350672698747537604682448896',\n",
" '516198956417707676498067467442061312',\n",
" '851127713155083345720389185963032576']],\n",
" [['963964631181695048142847483580514304',\n",
" '717110020036717348293837961318891520',\n",
" '559953044877040683984591286389702656'],\n",
" ['18430124250391465600117066342334464',\n",
" '132070511117078294010171654032850944',\n",
" '159098461579690714866905242830635008'],\n",
" ['627161913358867337554883287034363904',\n",
" '214447136123138332377227662874116096',\n",
" '882093469775889964276298230664265728'],\n",
" ['506592892690571316134013534512087040',\n",
" '120413569434570423403255788841467904',\n",
" '363677450590533494361708506394918912'],\n",
" ['1589009160702191880025766302318592',\n",
" '606881345580479787255639207307116544',\n",
" '959500312602351349459070457955221504']],\n",
" [['269867103629848361043137830460588032',\n",
" '990156537691794618122141045295677440',\n",
" '865669682192046160291865685070446592'],\n",
" ['290313896548079828952332075043651584',\n",
" '864848850508538634449993085726228480',\n",
" '602632316683732661972508737477279744'],\n",
" ['522550745079433503690896029362683904',\n",
" '360374127352021396321849249139523584',\n",
" '232224328255243390445419547970240512'],\n",
" ['605064041602877244147525705785147392',\n",
" '199177740608395626314729675502387200',\n",
" '919073451728990826614299904488505344'],\n",
" ['360317325587177670121175102173216768',\n",
" '320159996958358401900225542972506112',\n",
" '149208972882417206108392691362430976']],\n",
" [['403450033176818573530952678489718784',\n",
" '489675097836673889083870450733285376',\n",
" '878348273706607180847862755205578752'],\n",
" ['971247092328484848039979691100078080',\n",
" '614717678863967773495129714821431296',\n",
" '354994706810685515240551471042789376'],\n",
" ['175120840317815376550047548614639616',\n",
" '256810812410679590717730062889648128',\n",
" '32500220595245784184833778997264384'],\n",
" ['820630970242119026496832796320858112',\n",
" '450959634440169857524579916622856192',\n",
" '993116187387119510197936862871420928'],\n",
" ['141575526471072789135353484131958784',\n",
" '424325045683895850778427312979312640',\n",
" '504193266510591745485938882812837888']],\n",
" [['58216472724137800358267959826710528',\n",
" '768052861880136122281533170251726848',\n",
" '416638974419576874572829739330830336'],\n",
" ['257711363123831457072460090222575616',\n",
" '770799881808654090050761531714437120',\n",
" '553150637395247721839782017066074112'],\n",
" ['576779513601307433086800237942538240',\n",
" '70762290041252423558033638227443712',\n",
" '501500349611164148444025032284307456'],\n",
" ['213252321414434873609495117362626560',\n",
" '168126301731513097227967825069473792',\n",
" '210589547132072037234216859745648640'],\n",
" ['192717389299758634733578375953121280',\n",
" '629763589047996081611699278760116224',\n",
" '631810269670576590942597092109975552']]])"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, a_in, b_in, out, remainder = BatchNormalizationInt(5, 5, 3, 10**36, X_in, a_in, b_in)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"a\": a_in,\n",
" \"b\": b_in,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"with open(\"batchNormalization_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.8.6 ('tf24')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "11280bdb37aa6bc5d4cf1e4de756386eb1f9eecd8dcdefa77636dfac7be2370d"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/conv1d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Conv1D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(20,3))\n",
"x = Conv1D(2,4,3)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 20, 3)] 0 \n",
" \n",
" conv1d (Conv1D) (None, 6, 2) 26 \n",
" \n",
"=================================================================\n",
"Total params: 26\n",
"Trainable params: 26\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<tf.Variable 'conv1d/kernel:0' shape=(4, 3, 2) dtype=float32, numpy=\n",
" array([[[-0.05840281, -0.33957317],\n",
" [ 0.2264623 , 0.05825561],\n",
" [ 0.16525698, 0.23405397]],\n",
" \n",
" [[-0.5258953 , -0.3936214 ],\n",
" [ 0.13454366, -0.22821242],\n",
" [ 0.03147739, -0.01196778]],\n",
" \n",
" [[ 0.35090238, 0.1396572 ],\n",
" [ 0.40993017, -0.27508488],\n",
" [ 0.116602 , -0.148987 ]],\n",
" \n",
" [[ 0.37122232, 0.08273119],\n",
" [-0.29717228, 0.53457487],\n",
" [ 0.49348652, -0.04242468]]], dtype=float32)>,\n",
" <tf.Variable 'conv1d/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.weights"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[0.66937516, 0.6907002 , 0.96996117],\n",
" [0.19520127, 0.13998107, 0.09311981],\n",
" [0.75079076, 0.02970836, 0.07441652],\n",
" [0.17415405, 0.83571587, 0.60334393],\n",
" [0.10381228, 0.77579617, 0.2255741 ],\n",
" [0.13918275, 0.12624822, 0.16357286],\n",
" [0.69068874, 0.44852818, 0.23029813],\n",
" [0.31139241, 0.79853943, 0.48135381],\n",
" [0.40343184, 0.82898376, 0.89517967],\n",
" [0.28514992, 0.60441284, 0.27842517],\n",
" [0.77636577, 0.32528131, 0.3163831 ],\n",
" [0.86428116, 0.89781672, 0.31025656],\n",
" [0.50292735, 0.79692487, 0.12686924],\n",
" [0.86170435, 0.41107323, 0.27543757],\n",
" [0.84957032, 0.38557172, 0.99614999],\n",
" [0.88438519, 0.51217387, 0.40840027],\n",
" [0.4354065 , 0.75060067, 0.30749656],\n",
" [0.18944417, 0.52536988, 0.2426369 ],\n",
" [0.75967469, 0.98044579, 0.15048149],\n",
" [0.80339604, 0.65717107, 0.64046179]]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,20,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 35ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 20:02:12.254810: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[ 0.59507644, 0.45122126],\n",
" [ 0.69210184, 0.1576352 ],\n",
" [ 0.70753413, -0.43526217],\n",
" [ 0.53165036, -0.09032159],\n",
" [ 0.7328447 , -0.33714917],\n",
" [ 0.38855883, -0.09487797]]], dtype=float32)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[int(X[0][i][j]*1e36) for j in range(3)] for i in range(20)]\n",
"weights = [[[int(model.weights[0].numpy()[i][j][k]*1e36) for k in range(2)] for j in range(3)] for i in range(4)]\n",
"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"def Conv1DInt(nInputs, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" Input = [[str(input[i][j] % p) for j in range(nChannels)] for i in range(nInputs)]\n",
" Weights = [[[str(weights[i][j][k] % p) for k in range(nFilters)] for j in range(nChannels)] for i in range(kernelSize)]\n",
" Bias = [str(bias[i] % p) for i in range(nFilters)]\n",
" out = [[0 for _ in range(nFilters)] for j in range((nInputs - kernelSize)//strides + 1)]\n",
" remainder = [[None for _ in range(nFilters)] for _ in range((nInputs - kernelSize)//strides + 1)]\n",
" for i in range((nInputs - kernelSize)//strides + 1):\n",
" for j in range(nFilters):\n",
" for k in range(kernelSize):\n",
" for l in range(nChannels):\n",
" out[i][j] += input[i*strides + k][l]*weights[k][l][j]\n",
" out[i][j] += bias[j]\n",
" remainder[i][j] = str(out[i][j] % n)\n",
" out[i][j] = str(out[i][j] // n % p)\n",
" return Input, Weights, Bias, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([['595076432565314636873373017613140151',\n",
" '451221242188051044982898155310089176'],\n",
" ['692101791264109605416098691984234110',\n",
" '157635196511948127458268143134517909'],\n",
" ['707534041076922026686504470881153950',\n",
" '21888242871839275222246405745257275088547929138190672685567302106918640005237'],\n",
" ['531650362682809033665109229370302980',\n",
" '21888242871839275222246405745257275088548274078760710220327439407996310078926'],\n",
" ['732844672853217673574394205962948992',\n",
" '21888242871839275222246405745257275088548027251228401034660957748100577552406'],\n",
" ['388558804761306031693830030956978129',\n",
" '21888242871839275222246405745257275088548269522397035548207044857128138122494']],\n",
" [['559476430118783401148220455172177920',\n",
" '798629717274041486200430078621384704'],\n",
" ['222725218484853070285693236889518080',\n",
" '703236219970385258366708181735833600'],\n",
" ['935243375755259327550534863114207232',\n",
" '629676730817043015262169534306451456'],\n",
" ['168613979210646022892058708579188736',\n",
" '20078824844870090673720198793527296'],\n",
" ['382452121618037097983987448914378752',\n",
" '384848670804947558045463129800835072'],\n",
" ['997624818969376769735560795535704064',\n",
" '607655476452490925911677042723651584']])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, weights, bias, out, remainder = Conv1DInt(20, 3, 2, 4, 3, 10**36, X_in, weights, bias)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"weights\": weights,\n",
" \"bias\": bias,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"with open(\"conv1D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/conv2d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Conv2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = Conv2D(2, 3)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" conv2d (Conv2D) (None, 3, 3, 2) 56 \n",
" \n",
"=================================================================\n",
"Total params: 56\n",
"Trainable params: 56\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<tf.Variable 'conv2d/kernel:0' shape=(3, 3, 3, 2) dtype=float32, numpy=\n",
" array([[[[-0.2214439 , -0.15195417],\n",
" [-0.33063164, -0.2934303 ],\n",
" [ 0.05383286, -0.29145738]],\n",
" \n",
" [[-0.03459874, -0.18074483],\n",
" [ 0.0829632 , -0.18525888],\n",
" [-0.30195278, 0.28627008]],\n",
" \n",
" [[-0.16308369, -0.00504276],\n",
" [ 0.3425789 , 0.23431945],\n",
" [ 0.3600672 , -0.12323308]]],\n",
" \n",
" \n",
" [[[-0.32080007, 0.34273505],\n",
" [ 0.18235081, 0.10385716],\n",
" [-0.1344554 , -0.33093956]],\n",
" \n",
" [[ 0.26645142, 0.13327193],\n",
" [ 0.14260197, -0.01873457],\n",
" [ 0.04164705, 0.09329805]],\n",
" \n",
" [[ 0.22617143, 0.00685191],\n",
" [ 0.04963994, 0.23333359],\n",
" [ 0.35556698, -0.2943074 ]]],\n",
" \n",
" \n",
" [[[-0.01687273, -0.23511177],\n",
" [ 0.3297963 , 0.34760195],\n",
" [ 0.03496316, 0.09493944]],\n",
" \n",
" [[ 0.15188134, -0.36046585],\n",
" [ 0.03922135, 0.09752569],\n",
" [-0.07491425, 0.22700274]],\n",
" \n",
" [[ 0.32842422, 0.10250565],\n",
" [-0.32919353, 0.12664899],\n",
" [-0.16168171, 0.34737545]]]], dtype=float32)>,\n",
" <tf.Variable 'conv2d/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.weights"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.01897312, 0.08743388, 0.86222637],\n",
" [0.10109003, 0.28028469, 0.47527166],\n",
" [0.01512083, 0.32085385, 0.55800198],\n",
" [0.4642667 , 0.30473978, 0.4908111 ],\n",
" [0.35508257, 0.37433134, 0.78504401]],\n",
"\n",
" [[0.86741939, 0.20455078, 0.75628909],\n",
" [0.49125544, 0.77870243, 0.00276785],\n",
" [0.15663838, 0.57212579, 0.99557935],\n",
" [0.94449608, 0.24962475, 0.12299833],\n",
" [0.99733666, 0.01757025, 0.78783541]],\n",
"\n",
" [[0.48878705, 0.12012174, 0.9315336 ],\n",
" [0.21785634, 0.36211795, 0.66387035],\n",
" [0.90845156, 0.08354312, 0.49792257],\n",
" [0.89275096, 0.48364178, 0.29199137],\n",
" [0.42604607, 0.48339958, 0.24699135]],\n",
"\n",
" [[0.49614912, 0.82873805, 0.51174584],\n",
" [0.40336063, 0.91275723, 0.98636519],\n",
" [0.77062345, 0.9014581 , 0.37892572],\n",
" [0.70837991, 0.13523834, 0.27672346],\n",
" [0.80903352, 0.01406841, 0.65278234]],\n",
"\n",
" [[0.04710218, 0.17104368, 0.60839461],\n",
" [0.15986631, 0.37473407, 0.20861406],\n",
" [0.53476587, 0.31278845, 0.93248025],\n",
" [0.62650735, 0.05244101, 0.57899892],\n",
" [0.24521627, 0.01355308, 0.20119521]]]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 31ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 20:04:35.358347: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[[ 0.7669913 , 0.15274508],\n",
" [ 0.7217935 , 0.43549562],\n",
" [ 0.956968 , -0.7293344 ]],\n",
"\n",
" [[ 0.82161874, -0.08652828],\n",
" [ 0.45854256, 0.37499383],\n",
" [ 0.6369549 , -0.12588985]],\n",
"\n",
" [[ 0.3617655 , 0.5265081 ],\n",
" [ 0.5842541 , 0.11949164],\n",
" [ 0.6298134 , -0.148645 ]]]], dtype=float32)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\n",
"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(3)] for i in range(3)]\n",
"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" Weights = [[[[str(weights[i][j][k][l] % p) for l in range(nFilters)] for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\n",
" Bias = [str(bias[i] % p) for i in range(nFilters)]\n",
" out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n",
" remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n",
" for i in range((nRows - kernelSize)//strides + 1):\n",
" for j in range((nCols - kernelSize)//strides + 1):\n",
" for m in range(nFilters):\n",
" for k in range(nChannels):\n",
" for x in range(kernelSize):\n",
" for y in range(kernelSize):\n",
" out[i][j][m] += input[i*strides+x][j*strides+y][k] * weights[x][y][k][m]\n",
" out[i][j][m] += bias[m]\n",
" remainder[i][j][m] = str(out[i][j][m] % n)\n",
" out[i][j][m] = str(out[i][j][m] // n % p)\n",
" return Input, Weights, Bias, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['766991308610348168697678317289253491',\n",
" '152745147346569443334783280814065046'],\n",
" ['721793514622685877535765261453578285',\n",
" '435495635689848419191313701414477907'],\n",
" ['956968022633247456612037533749279884',\n",
" '21888242871839275222246405745257275088547635065957648765434334612742599273530']],\n",
" [['821618728955717473031173417522483642',\n",
" '21888242871839275222246405745257275088548277872099372923381843387091765217066'],\n",
" ['458542547820893552234319995890476448',\n",
" '374993810980093272528286581550476085'],\n",
" ['636954799020811143676097566965150012',\n",
" '21888242871839275222246405745257275088548238510569604144298779927709876426450']],\n",
" [['361765493481699222011118768701693995',\n",
" '526508029475490175970042650793369367'],\n",
" ['584254113344261709635215513635894572',\n",
" '119491582294697734028918864863442650'],\n",
" ['629813449657849355217882687452958040',\n",
" '21888242871839275222246405745257275088548215755396606066460162924422748870356']]],\n",
" [[['917380913441791641383057190580912128',\n",
" '941668043113108989243166859307515904'],\n",
" ['830888825756591443304789567910969344',\n",
" '959036987931483834969450172534226944'],\n",
" ['807238014162219891553337682966872064',\n",
" '654744816405601974137858933743681536']],\n",
" [['495502502940535931874336973827080192',\n",
" '508085363950388829219862699527110656'],\n",
" ['570521634763453322817882508314542080',\n",
" '580659632640246114717880425476259840'],\n",
" ['730760440116275911813925660727967744',\n",
" '404713594680872184361509627048755200']],\n",
" [['285034561505172240143276776062189568',\n",
" '246179226164944809810447582952947712'],\n",
" ['383405024202190176779250406231375872',\n",
" '48073795245569756634196992877133824'],\n",
" ['41512468028555336013994905783238656',\n",
" '807192458327115051492426645956984832']]])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, weights, bias, out, remainder = Conv2DInt(5, 5, 3, 2, 3, 1, 10**36, X_in, weights, bias)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"weights\": weights,\n",
" \"bias\": bias,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"with open(\"conv2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(10,10,3))\n",
"x = Conv2D(2, 4, 3)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_1\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n",
" \n",
" conv2d_1 (Conv2D) (None, 3, 3, 2) 98 \n",
" \n",
"=================================================================\n",
"Total params: 98\n",
"Trainable params: 98\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<tf.Variable 'conv2d_1/kernel:0' shape=(4, 4, 3, 2) dtype=float32, numpy=\n",
" array([[[[-0.2644725 , -0.06314689],\n",
" [-0.19228128, -0.15511811],\n",
" [ 0.11695373, 0.15373573]],\n",
" \n",
" [[-0.25127184, -0.03327389],\n",
" [ 0.06582499, 0.13954943],\n",
" [-0.02274385, -0.24024239]],\n",
" \n",
" [[-0.27345484, 0.07233012],\n",
" [ 0.03240535, -0.1362924 ],\n",
" [ 0.16554734, -0.19980597]],\n",
" \n",
" [[ 0.12271923, -0.16348948],\n",
" [-0.24399345, 0.11112538],\n",
" [ 0.04153693, 0.09944585]]],\n",
" \n",
" \n",
" [[[ 0.07061589, 0.08067289],\n",
" [-0.25938636, -0.04698843],\n",
" [-0.18615322, -0.18926641]],\n",
" \n",
" [[ 0.06828818, 0.10024589],\n",
" [-0.06301631, -0.21391404],\n",
" [ 0.17798159, 0.16077739]],\n",
" \n",
" [[-0.18883933, -0.24141382],\n",
" [-0.1410877 , -0.1870578 ],\n",
" [-0.17638391, 0.12909776]],\n",
" \n",
" [[ 0.24995095, -0.27214956],\n",
" [-0.16633804, -0.24534652],\n",
" [ 0.09470761, -0.1752578 ]]],\n",
" \n",
" \n",
" [[[-0.26973695, -0.16573134],\n",
" [ 0.0093652 , 0.23317659],\n",
" [ 0.13521832, -0.18823144]],\n",
" \n",
" [[ 0.1731261 , 0.15210795],\n",
" [ 0.11972865, 0.11824197],\n",
" [-0.20316267, -0.01294529]],\n",
" \n",
" [[ 0.14585042, 0.22254854],\n",
" [ 0.15764701, 0.0891107 ],\n",
" [ 0.00702351, 0.17262942]],\n",
" \n",
" [[ 0.06677854, -0.07873373],\n",
" [-0.26536292, -0.1721809 ],\n",
" [-0.12418044, -0.11808449]]],\n",
" \n",
" \n",
" [[[ 0.09153298, 0.18611383],\n",
" [ 0.14009333, -0.19381046],\n",
" [-0.27251363, 0.07429421]],\n",
" \n",
" [[ 0.12720028, -0.08216412],\n",
" [ 0.14116141, -0.10473494],\n",
" [-0.01652202, -0.11998361]],\n",
" \n",
" [[-0.010129 , 0.12356687],\n",
" [-0.00215057, 0.17525265],\n",
" [ 0.26925737, 0.18551975]],\n",
" \n",
" [[-0.1616565 , -0.14463529],\n",
" [-0.18055108, 0.2564476 ],\n",
" [ 0.19239256, -0.11366163]]]], dtype=float32)>,\n",
" <tf.Variable 'conv2d_1/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.weights"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.74916437, 0.48058547, 0.76332072],\n",
" [0.12424725, 0.17444765, 0.23397784],\n",
" [0.05504572, 0.73761126, 0.8872156 ],\n",
" [0.49900099, 0.92746041, 0.53705474],\n",
" [0.55972545, 0.16210532, 0.48132197],\n",
" [0.5848511 , 0.49854495, 0.08101739],\n",
" [0.18151106, 0.19916602, 0.72216404],\n",
" [0.8740212 , 0.76936566, 0.77574156],\n",
" [0.640459 , 0.97982307, 0.28733369],\n",
" [0.72894846, 0.08559827, 0.88796122]],\n",
"\n",
" [[0.72655621, 0.74204472, 0.22625834],\n",
" [0.04455912, 0.02637621, 0.7410693 ],\n",
" [0.59282978, 0.27570664, 0.76839831],\n",
" [0.98853958, 0.32472733, 0.07214331],\n",
" [0.18975449, 0.50827871, 0.61454778],\n",
" [0.04411632, 0.5425321 , 0.08095671],\n",
" [0.98276969, 0.93905031, 0.27580299],\n",
" [0.01991902, 0.18288148, 0.56430848],\n",
" [0.60873785, 0.76133969, 0.94420434],\n",
" [0.29177495, 0.60971797, 0.75330394]],\n",
"\n",
" [[0.73958658, 0.86792802, 0.38199042],\n",
" [0.60758291, 0.04444527, 0.89773701],\n",
" [0.81378908, 0.74925507, 0.94127002],\n",
" [0.52276966, 0.71515635, 0.0673889 ],\n",
" [0.88674225, 0.85171248, 0.25796752],\n",
" [0.06304501, 0.02557175, 0.7862988 ],\n",
" [0.13024858, 0.03026337, 0.53165512],\n",
" [0.98698478, 0.10343698, 0.14793739],\n",
" [0.19595613, 0.4755287 , 0.69081615],\n",
" [0.63616236, 0.64746281, 0.70686306]],\n",
"\n",
" [[0.90697061, 0.70755438, 0.17101648],\n",
" [0.91618436, 0.75457803, 0.3753285 ],\n",
" [0.10891312, 0.63256771, 0.66998965],\n",
" [0.0031363 , 0.8577421 , 0.44313256],\n",
" [0.97431053, 0.31491313, 0.52870403],\n",
" [0.84949509, 0.57476833, 0.35833646],\n",
" [0.3259322 , 0.61810256, 0.97382616],\n",
" [0.92587238, 0.93189425, 0.02385008],\n",
" [0.91665173, 0.21392593, 0.48478448],\n",
" [0.43780191, 0.31732276, 0.10383084]],\n",
"\n",
" [[0.40302491, 0.18641359, 0.28439078],\n",
" [0.80467361, 0.95795027, 0.76525912],\n",
" [0.09050706, 0.05142721, 0.5484936 ],\n",
" [0.72498561, 0.5350264 , 0.47320043],\n",
" [0.83032011, 0.36968621, 0.17519239],\n",
" [0.80183789, 0.53486298, 0.63113123],\n",
" [0.98299635, 0.17220543, 0.99893277],\n",
" [0.98120285, 0.15965491, 0.11500732],\n",
" [0.50294074, 0.54067477, 0.58704542],\n",
" [0.30811939, 0.86034992, 0.96053741]],\n",
"\n",
" [[0.51231231, 0.36679594, 0.6387736 ],\n",
" [0.39364612, 0.65398604, 0.18194537],\n",
" [0.53904627, 0.31794439, 0.95598346],\n",
" [0.8201467 , 0.01759052, 0.21272062],\n",
" [0.8265654 , 0.62113986, 0.56095777],\n",
" [0.24749834, 0.71107743, 0.22825303],\n",
" [0.17445456, 0.27443303, 0.53532667],\n",
" [0.46250432, 0.81471236, 0.01852107],\n",
" [0.86219207, 0.21628477, 0.98052948],\n",
" [0.34121289, 0.33599059, 0.95218908]],\n",
"\n",
" [[0.37520805, 0.46358272, 0.96812602],\n",
" [0.08123441, 0.61637145, 0.90839157],\n",
" [0.40060218, 0.47543454, 0.64913812],\n",
" [0.90053796, 0.70871333, 0.55043711],\n",
" [0.39746646, 0.30778257, 0.88554719],\n",
" [0.86349263, 0.11219438, 0.85574671],\n",
" [0.62224992, 0.48989345, 0.63991367],\n",
" [0.99134928, 0.98989598, 0.6173012 ],\n",
" [0.04768804, 0.33779174, 0.18604113],\n",
" [0.01957013, 0.57973428, 0.7495305 ]],\n",
"\n",
" [[0.10672299, 0.71601061, 0.03377451],\n",
" [0.87905429, 0.78474207, 0.59381131],\n",
" [0.90857691, 0.96590608, 0.56500479],\n",
" [0.13149743, 0.52407683, 0.23988054],\n",
" [0.56993435, 0.26299209, 0.7549793 ],\n",
" [0.52225825, 0.6448658 , 0.04444777],\n",
" [0.03641049, 0.37206738, 0.94614889],\n",
" [0.51144329, 0.88620609, 0.59531982],\n",
" [0.45414305, 0.41827663, 0.08097343],\n",
" [0.40615607, 0.26751879, 0.03898047]],\n",
"\n",
" [[0.89224853, 0.12348574, 0.32034526],\n",
" [0.64800157, 0.82504082, 0.19296447],\n",
" [0.88471839, 0.64119493, 0.03698128],\n",
" [0.99176407, 0.59193617, 0.30150652],\n",
" [0.72020934, 0.56545044, 0.91065986],\n",
" [0.80514643, 0.29937785, 0.74242392],\n",
" [0.09456567, 0.46145516, 0.554788 ],\n",
" [0.46704768, 0.33370513, 0.56795916],\n",
" [0.55089935, 0.89252818, 0.01030941],\n",
" [0.68112324, 0.5390893 , 0.31510111]],\n",
"\n",
" [[0.94967068, 0.7825868 , 0.22214195],\n",
" [0.8453802 , 0.98304469, 0.98455021],\n",
" [0.50376912, 0.29307285, 0.78424416],\n",
" [0.26351673, 0.24259793, 0.48663014],\n",
" [0.42359605, 0.48513857, 0.55338817],\n",
" [0.22229073, 0.02676846, 0.15701487],\n",
" [0.35682851, 0.72597313, 0.64578716],\n",
" [0.60649997, 0.55222217, 0.01019997],\n",
" [0.28450479, 0.20816085, 0.19723797],\n",
" [0.95701904, 0.54230762, 0.38779384]]]])"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,10,10,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 22ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[-0.02103192, -0.00251862],\n",
" [-0.13590473, -0.43280643],\n",
" [-0.46592993, -0.6076722 ]],\n",
"\n",
" [[-0.41985548, -0.28316095],\n",
" [-0.5124401 , -0.67603445],\n",
" [-0.30362517, -0.35066307]],\n",
"\n",
" [[ 0.04719239, -0.77217025],\n",
" [-0.90729254, -0.5460546 ],\n",
" [-0.6157329 , -0.56018454]]]], dtype=float32)"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\n",
"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(4)] for i in range(4)]\n",
"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['21888242871839275222246405745257275088548343368429240512769054624061005959510',\n",
" '21888242871839275222246405745257275088548361881856976212445268734113123308000'],\n",
" ['21888242871839275222246405745257275088548228495669861064087547662558271715284',\n",
" '21888242871839275222246405745257275088547931594040764149614699120473995978124'],\n",
" ['21888242871839275222246405745257275088547898470480336398546468994244949638791',\n",
" '21888242871839275222246405745257275088547756728190784802798484857861334105370']],\n",
" [['21888242871839275222246405745257275088547944544909737422432087456874316949324',\n",
" '21888242871839275222246405745257275088548081239515185091772880603232052577114'],\n",
" ['21888242871839275222246405745257275088547851960358367500079371782793385911358',\n",
" '21888242871839275222246405745257275088547688365801627855012444638213091512422'],\n",
" ['21888242871839275222246405745257275088548060775297780413313747663983226225838',\n",
" '21888242871839275222246405745257275088548013737249302248990923589248334943730']],\n",
" [['47192436853842599651386952076755831',\n",
" '21888242871839275222246405745257275088547592230115531216981433877552691800835'],\n",
" ['21888242871839275222246405745257275088547457107943733886642827877231280519319',\n",
" '21888242871839275222246405745257275088547818345751775722192552561821918626804'],\n",
" ['21888242871839275222246405745257275088547748667480051924165721939129997507240',\n",
" '21888242871839275222246405745257275088547804215881906491939765109262983554318']]],\n",
" [[['268679458635749205024295605371928576',\n",
" '388806143166359782280358980933910528'],\n",
" ['587604291442575449740007779803856896',\n",
" '881363922854357799836717369522126848'],\n",
" ['861312932060957897553390674280185856',\n",
" '857846252928472736899563405831045120']],\n",
" [['84829649070177990320832563715768320',\n",
" '765867543468158475751770347286822912'],\n",
" ['238136771858729786452041694885969920',\n",
" '231361799849937010319349760697303040'],\n",
" ['357728239843398972090727278133116928',\n",
" '121546057864506428255684370605539328']],\n",
" [['568749905268752884676825625665732608',\n",
" '218395840383827537600516408079286272'],\n",
" ['390713141622087796116893701035261952',\n",
" '52043981850152859332227036686057472'],\n",
" ['355515461237650726718816599152787456',\n",
" '178351211698736250757067221797699584']]])"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, weights, bias, out, remainder = Conv2DInt(10, 10, 3, 2, 4, 3, 10**36, X_in, weights, bias)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"weights\": weights,\n",
" \"bias\": bias,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"with open(\"conv2D_stride_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/conv2d_same.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Conv2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = Conv2D(2, 3, padding=\"same\")(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" conv2d (Conv2D) (None, 5, 5, 2) 56 \n",
" \n",
"=================================================================\n",
"Total params: 56\n",
"Trainable params: 56\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<tf.Variable 'conv2d/kernel:0' shape=(3, 3, 3, 2) dtype=float32, numpy=\n",
" array([[[[-0.22388998, 0.18217945],\n",
" [-0.31254017, 0.13933456],\n",
" [-0.14491144, 0.01168695]],\n",
" \n",
" [[-0.18442051, 0.16668755],\n",
" [-0.15052032, -0.1277689 ],\n",
" [-0.17660408, -0.25577286]],\n",
" \n",
" [[-0.3273484 , 0.06551823],\n",
" [ 0.02335805, 0.30579627],\n",
" [ 0.05012453, 0.05196694]]],\n",
" \n",
" \n",
" [[[-0.15296353, -0.28653675],\n",
" [ 0.31760007, 0.27596015],\n",
" [ 0.06140944, 0.28459537]],\n",
" \n",
" [[-0.271937 , 0.3022167 ],\n",
" [ 0.34724104, 0.3508402 ],\n",
" [-0.26121286, -0.10477605]],\n",
" \n",
" [[ 0.18311954, 0.15618789],\n",
" [ 0.21608043, 0.07763481],\n",
" [-0.17695144, -0.29946056]]],\n",
" \n",
" \n",
" [[[ 0.2186423 , 0.2389586 ],\n",
" [-0.2976641 , -0.30056122],\n",
" [-0.35727727, -0.3631401 ]],\n",
" \n",
" [[-0.04230955, -0.15279846],\n",
" [ 0.06897295, -0.08147189],\n",
" [-0.30367035, 0.21289521]],\n",
" \n",
" [[-0.2920769 , -0.22767249],\n",
" [-0.29041147, -0.2403323 ],\n",
" [-0.20408599, -0.23004377]]]], dtype=float32)>,\n",
" <tf.Variable 'conv2d/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.weights"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.57357832, 0.79689708, 0.54481385],\n",
" [0.95096481, 0.06302099, 0.53424686],\n",
" [0.14555327, 0.16801407, 0.91837743],\n",
" [0.14042694, 0.26466775, 0.0754911 ],\n",
" [0.19354151, 0.89796698, 0.18080666]],\n",
"\n",
" [[0.84893864, 0.94689375, 0.76889793],\n",
" [0.91280106, 0.81211903, 0.50614878],\n",
" [0.72629997, 0.09620774, 0.05074255],\n",
" [0.30178926, 0.4854865 , 0.46486629],\n",
" [0.87558861, 0.93289185, 0.33965317]],\n",
"\n",
" [[0.23726595, 0.09253935, 0.08598877],\n",
" [0.24484708, 0.00811252, 0.23642884],\n",
" [0.65975124, 0.63633904, 0.82507772],\n",
" [0.53100731, 0.72433054, 0.66373751],\n",
" [0.43916625, 0.74347257, 0.6772263 ]],\n",
"\n",
" [[0.87412193, 0.53853422, 0.34772628],\n",
" [0.7738511 , 0.97565729, 0.94426861],\n",
" [0.21537231, 0.65774623, 0.89405016],\n",
" [0.7411118 , 0.68792609, 0.3272619 ],\n",
" [0.44887834, 0.924486 , 0.48269841]],\n",
"\n",
" [[0.13952337, 0.79659803, 0.97603335],\n",
" [0.66099459, 0.06934143, 0.99854059],\n",
" [0.31609368, 0.49596104, 0.93797069],\n",
" [0.04941322, 0.24709554, 0.58384416],\n",
" [0.71527804, 0.48976864, 0.98763569]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 51ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2024-02-04 01:25:53.532541: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[[-0.7382064 , -0.17332056],\n",
" [-1.034698 , -0.43408912],\n",
" [-0.83073455, -0.6865788 ],\n",
" [-0.28542495, 0.0770359 ],\n",
" [-0.04129319, 0.02877748]],\n",
"\n",
" [[-0.60671365, 0.38846642],\n",
" [-1.1027374 , 0.71167284],\n",
" [-1.2792461 , -0.10405768],\n",
" [-1.1375024 , -0.28573734],\n",
" [-0.7037988 , 0.3554073 ]],\n",
"\n",
" [[-1.5469512 , -0.50975496],\n",
" [-2.0071907 , -0.25512454],\n",
" [-1.9879558 , 0.09278526],\n",
" [-1.5013543 , -0.14000578],\n",
" [-0.7585893 , 0.43752092]],\n",
"\n",
" [[-0.7614179 , 0.09177176],\n",
" [-1.688165 , -0.25309083],\n",
" [-0.8684121 , 0.42702955],\n",
" [-1.6322078 , 0.3133433 ],\n",
" [-1.1236074 , 0.2770568 ]],\n",
"\n",
" [[-0.54382604, 0.415062 ],\n",
" [-1.0068984 , 0.6469521 ],\n",
" [-1.3391564 , 0.42430705],\n",
" [-0.6338484 , 0.63813394],\n",
" [-0.9111921 , 0.5726407 ]]]], dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]\n",
"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(3)] for i in range(3)]\n",
"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n",
" remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n",
" for i in range((nRows - kernelSize)//strides + 1):\n",
" for j in range((nCols - kernelSize)//strides + 1):\n",
" for m in range(nFilters):\n",
" for k in range(nChannels):\n",
" for x in range(kernelSize):\n",
" for y in range(kernelSize):\n",
" out[i][j][m] += int(input[i*strides+x][j*strides+y][k])*int(weights[x][y][k][m])\n",
" out[i][j][m] += int(bias[m])\n",
" remainder[i][j][m] = str(out[i][j][m] % n)\n",
" out[i][j][m] = str(out[i][j][m] // n)\n",
" return out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"def Conv2DsameInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" if nRows % strides == 0:\n",
" rowPadding = max(kernelSize - strides, 0)\n",
" else:\n",
" rowPadding = max(kernelSize - nRows % strides, 0)\n",
" if nCols % strides == 0:\n",
" colPadding = max(kernelSize - strides, 0)\n",
" else:\n",
" colPadding = max(kernelSize - nCols % strides, 0)\n",
" \n",
" _input = [[[0 for _ in range(nChannels)] for _ in range(nCols + colPadding)] for _ in range(nRows + rowPadding)]\n",
"\n",
" for i in range(nRows):\n",
" for j in range(nCols):\n",
" for k in range(nChannels):\n",
" _input[i+rowPadding//2][j+colPadding//2][k] = input[i][j][k]\n",
" \n",
" out, remainder = Conv2DInt(nRows + rowPadding, nCols + colPadding, nChannels, nFilters, kernelSize, strides, n, _input, weights, bias)\n",
" return out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['-738206413373029545006965393527124494',\n",
" '-173320559228639935825945330543413025'],\n",
" ['-1034698083357167138897799627355946893',\n",
" '-434089078628623353676508551211157060'],\n",
" ['-830734559502817036444813835112148949',\n",
" '-686578771866623630758607927275546159'],\n",
" ['-285424960673894669036410085848276078',\n",
" '77035899885765173133597720803628368'],\n",
" ['-41293201078409047199874417933080796',\n",
" '28777494655737863382696013669386951']],\n",
" [['-606713676308333020774846244444307246',\n",
" '388466467207809267549922375129065936'],\n",
" ['-1102737485952039787132334772316590877',\n",
" '711672842283067459049106389539428334'],\n",
" ['-1279246107747464951673577203827572661',\n",
" '-104057682619248993879676863654015882'],\n",
" ['-1137502411882990109129978808062308003',\n",
" '-285737283216816113761016693211231047'],\n",
" ['-703798773277911056745141956845225462',\n",
" '355407338114374779173330249858051758']],\n",
" [['-1546951103062535866431703941066730304',\n",
" '-509754977574520651977576289008629976'],\n",
" ['-2007190678249673958423804906616390874',\n",
" '-255124530399913653884258580354194679'],\n",
" ['-1987955686599915815112948301772925117',\n",
" '92785353760923841311068732708486389'],\n",
" ['-1501354303867896914042548115076362343',\n",
" '-140005761885967356612636419407991713'],\n",
" ['-758589315783580773280487949446211355',\n",
" '437520880361906870599644364227465106']],\n",
" [['-761417923444182653301008173638043967',\n",
" '91771720385437306243354293205033102'],\n",
" ['-1688165103880073226811051249397561256',\n",
" '-253090840416308272240635021911178871'],\n",
" ['-868411975706764838263900420928401111',\n",
" '427029536451544469306217379046517378'],\n",
" ['-1632207770832291707418877818442334628',\n",
" '313343146963309014974813849350304619'],\n",
" ['-1123607486465218134583708408995464790',\n",
" '277056825693143901704758542110909098']],\n",
" [['-543826042689234949496060048498817249',\n",
" '415061953419939109346123158429653654'],\n",
" ['-1006898403524974693098527575437710832',\n",
" '646952095929760474345606121011841547'],\n",
" ['-1339156364320875137533821288468963984',\n",
" '424307047679243230200796457433761030'],\n",
" ['-633848388019879384336947814123500320',\n",
" '638133921526842615943818078787826079'],\n",
" ['-911192101070039979166490878519403558',\n",
" '572640728975516234503728848776059996']]],\n",
" [[['732636700329184288172821299452706816',\n",
" '163633766656393366871975061931163648'],\n",
" ['106376739450670706774435272610283520',\n",
" '224263678919132314456428282264944640'],\n",
" ['302563808180207575103565765357338624',\n",
" '724302115124451087131827274648649728'],\n",
" ['414653571797565705485911652130881536',\n",
" '793412538503882240528593488489480192'],\n",
" ['802744020509610387937821108140507136',\n",
" '304480836101726291197711385865748480']],\n",
" [['859770729700736535878340696623546368',\n",
" '892305185639885971968166660350672896'],\n",
" ['159017773966938546227144022541991936',\n",
" '243286973980475632014665402361577472'],\n",
" ['45707991996386548824583584683655168',\n",
" '305057405020119480420035216424304640'],\n",
" ['513655874550133048911800632902418432',\n",
" '966709976332017469863264280209522688'],\n",
" ['198125756383956075595551934970331136',\n",
" '988945351929415067553212891893071872']],\n",
" [['787267116688540528237625132699353088',\n",
" '820149329025927193528840575260819456'],\n",
" ['472980868351632170335228269959315456',\n",
" '763189020330031063201267188022378496'],\n",
" ['644197050565810210754859371753111552',\n",
" '989731482915520051484045079570546688'],\n",
" ['948204822800878014118539586611183616',\n",
" '748247265754602884949081086979211264'],\n",
" ['716169397100995271731495802811449344',\n",
" '485403242675801265137341039288254464']],\n",
" [['43352138962814326789218918981435392',\n",
" '405166142631707980272441068569493504'],\n",
" ['810091229170266512829629243259355136',\n",
" '269653910662555626980942633563586560'],\n",
" ['676839398629154231820514533721505792',\n",
" '419805522694742694500594416384737280'],\n",
" ['745383827341964610018052023030644736',\n",
" '256049836598014041054468595098058752'],\n",
" ['675940914936064095590762595072606208',\n",
" '261569026192941931124614732445646848']],\n",
" [['945584600952117166014909825389953024',\n",
" '419123852798410471873927944123449344'],\n",
" ['610870231548665514822003410375540736',\n",
" '444338394948450192884055088832708608'],\n",
" ['392811864299264176482313886100357120',\n",
" '482398655357498430014877178936688640'],\n",
" ['865948833234167064622566980785799168',\n",
" '886966130974971444248685772183437312'],\n",
" ['195220905237827872879130999353507840',\n",
" '356250510761353797733544351900893184']]])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out, remainder = Conv2DsameInt(5, 5, 3, 2, 3, 1, 10**36, X_in, weights, bias)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"weights\": weights,\n",
" \"bias\": bias,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"with open(\"conv2Dsame_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(10,10,3))\n",
"x = Conv2D(2, 4, 3, padding=\"same\")(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_1\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n",
" \n",
" conv2d_1 (Conv2D) (None, 4, 4, 2) 98 \n",
" \n",
"=================================================================\n",
"Total params: 98\n",
"Trainable params: 98\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.15917131, 0.77313235, 0.70732347],\n",
" [0.85210236, 0.77747055, 0.9126757 ],\n",
" [0.93479056, 0.819227 , 0.70156189],\n",
" [0.79143794, 0.87801591, 0.82904976],\n",
" [0.68619248, 0.52939185, 0.9781374 ],\n",
" [0.60719573, 0.89925314, 0.76945961],\n",
" [0.87552557, 0.90534932, 0.87889951],\n",
" [0.3906682 , 0.95580616, 0.31789736],\n",
" [0.76477277, 0.81754225, 0.69839668],\n",
" [0.83091809, 0.08929047, 0.41690024]],\n",
"\n",
" [[0.02156404, 0.1248342 , 0.10101914],\n",
" [0.89801399, 0.26753341, 0.07441736],\n",
" [0.02208311, 0.63957509, 0.89741475],\n",
" [0.34053784, 0.26694358, 0.75715605],\n",
" [0.53780638, 0.65565436, 0.91504456],\n",
" [0.25938895, 0.93164592, 0.89508771],\n",
" [0.59673249, 0.83579125, 0.43718874],\n",
" [0.15159799, 0.74559263, 0.75890839],\n",
" [0.14960964, 0.72981249, 0.3738258 ],\n",
" [0.77609438, 0.61152145, 0.26743727]],\n",
"\n",
" [[0.86386277, 0.08854458, 0.1881181 ],\n",
" [0.44605901, 0.5362032 , 0.35993523],\n",
" [0.30153601, 0.2052692 , 0.94686662],\n",
" [0.19258428, 0.29545743, 0.67123322],\n",
" [0.64059575, 0.25641094, 0.1195399 ],\n",
" [0.38441147, 0.12147883, 0.39661277],\n",
" [0.58068678, 0.99196337, 0.80942971],\n",
" [0.42854507, 0.58075105, 0.17898182],\n",
" [0.59835861, 0.53916735, 0.58269423],\n",
" [0.73442298, 0.50103808, 0.55618813]],\n",
"\n",
" [[0.70220035, 0.65299784, 0.06720906],\n",
" [0.98439586, 0.49217928, 0.29110757],\n",
" [0.40362701, 0.31214552, 0.33877257],\n",
" [0.63058855, 0.35760424, 0.46940153],\n",
" [0.13804137, 0.06058852, 0.55080509],\n",
" [0.76085309, 0.65603233, 0.76855789],\n",
" [0.82109332, 0.28625298, 0.5198722 ],\n",
" [0.52934891, 0.98676823, 0.45172351],\n",
" [0.26726209, 0.85657565, 0.95955236],\n",
" [0.19110728, 0.50206147, 0.05049411]],\n",
"\n",
" [[0.01880872, 0.25428751, 0.32772514],\n",
" [0.1303663 , 0.75804367, 0.53268895],\n",
" [0.37711957, 0.72274233, 0.95032399],\n",
" [0.07563836, 0.93359311, 0.15796125],\n",
" [0.62045146, 0.64580923, 0.1557714 ],\n",
" [0.78905608, 0.85432612, 0.87425904],\n",
" [0.80316626, 0.51924423, 0.45801054],\n",
" [0.64371903, 0.55673077, 0.85455273],\n",
" [0.42522451, 0.75796177, 0.73794332],\n",
" [0.9042132 , 0.94432526, 0.84180072]],\n",
"\n",
" [[0.77346326, 0.84811549, 0.97897457],\n",
" [0.9229139 , 0.8745595 , 0.81151275],\n",
" [0.31466683, 0.22968788, 0.32937946],\n",
" [0.32265255, 0.60866667, 0.74966551],\n",
" [0.89690681, 0.22652098, 0.38790477],\n",
" [0.73330962, 0.60714074, 0.53581188],\n",
" [0.492162 , 0.4240943 , 0.7783657 ],\n",
" [0.0186855 , 0.69752848, 0.52908628],\n",
" [0.84273096, 0.30658396, 0.70465779],\n",
" [0.8684895 , 0.06929279, 0.73560357]],\n",
"\n",
" [[0.41183525, 0.06309388, 0.03012547],\n",
" [0.04789855, 0.39528684, 0.14238964],\n",
" [0.37892587, 0.73618744, 0.70410196],\n",
" [0.54405706, 0.07672244, 0.10798353],\n",
" [0.10530593, 0.46345768, 0.95231357],\n",
" [0.14640745, 0.47792646, 0.6955056 ],\n",
" [0.39633502, 0.68247493, 0.7154005 ],\n",
" [0.89354067, 0.92889669, 0.18524983],\n",
" [0.85684736, 0.40546574, 0.08902131],\n",
" [0.45694739, 0.57720739, 0.10578621]],\n",
"\n",
" [[0.36785594, 0.17667226, 0.46407189],\n",
" [0.11640223, 0.37587536, 0.93314522],\n",
" [0.03840141, 0.7311801 , 0.23603065],\n",
" [0.54117032, 0.85714659, 0.0495661 ],\n",
" [0.08494766, 0.87966438, 0.37650164],\n",
" [0.95011446, 0.23333771, 0.26889821],\n",
" [0.86136317, 0.16072138, 0.03323276],\n",
" [0.31658215, 0.25675017, 0.59240392],\n",
" [0.07867128, 0.73161337, 0.96039619],\n",
" [0.95476936, 0.68330006, 0.99581875]],\n",
"\n",
" [[0.73541155, 0.30482595, 0.11167008],\n",
" [0.20315806, 0.45939058, 0.90883005],\n",
" [0.62037448, 0.07781508, 0.85993374],\n",
" [0.1662502 , 0.96140805, 0.4741485 ],\n",
" [0.10682937, 0.36184028, 0.52263044],\n",
" [0.55662028, 0.01836474, 0.90787543],\n",
" [0.79930707, 0.76048754, 0.12106902],\n",
" [0.45491329, 0.94061578, 0.48757815],\n",
" [0.12918205, 0.18806973, 0.58812925],\n",
" [0.80431 , 0.97299797, 0.05632223]],\n",
"\n",
" [[0.33911369, 0.9949053 , 0.61461519],\n",
" [0.78384667, 0.73316864, 0.85913351],\n",
" [0.38492166, 0.56317432, 0.59637715],\n",
" [0.3607973 , 0.05332751, 0.59008779],\n",
" [0.80225702, 0.88927018, 0.87653115],\n",
" [0.62173867, 0.62184283, 0.90795477],\n",
" [0.15894814, 0.54661812, 0.83119993],\n",
" [0.44861376, 0.28122679, 0.37193476],\n",
" [0.40747786, 0.24497888, 0.55174409],\n",
" [0.3188501 , 0.47713174, 0.23614857]]]])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,10,10,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 28ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[-0.811051 , -1.4721096 ],\n",
" [-0.52853954, -0.47991082],\n",
" [-0.8595364 , -0.6705183 ],\n",
" [-0.07767564, -0.1320289 ]],\n",
"\n",
" [[-0.9737919 , -0.5298958 ],\n",
" [-1.0687585 , -0.33069813],\n",
" [-0.96858287, -0.61539143],\n",
" [-0.34952405, -0.3947128 ]],\n",
"\n",
" [[-1.1950083 , -0.39145365],\n",
" [-1.0355395 , 0.37544912],\n",
" [-0.46857417, -0.46149284],\n",
" [-0.1579878 , -0.14529735]],\n",
"\n",
" [[-0.7178327 , -0.6407934 ],\n",
" [-0.81823504, -0.48652953],\n",
" [-0.48897535, -0.5935499 ],\n",
" [-0.0888171 , -0.18892495]]]], dtype=float32)"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]\n",
"weights = [[[[int(model.weights[0].numpy()[i][j][k][l]*1e36) for l in range(2)] for k in range(3)] for j in range(4)] for i in range(4)]\n",
"bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"([[['-811051029307312151898080091259013408',\n",
" '-1472109697883872855085104222700990006'],\n",
" ['-528539552873451841296887387802887946',\n",
" '-479910753097361964472240108640655029'],\n",
" ['-859536355090285293603582494722226955',\n",
" '-670518221637687591501448018045711492'],\n",
" ['-77675673238639598916850751879067826',\n",
" '-132028915984577730731287477184728367']],\n",
" [['-973791923027617402137438972479106354',\n",
" '-529895757470201620182206632643141082'],\n",
" ['-1068758558577939368141318995900977305',\n",
" '-330698196577790148366400564712521445'],\n",
" ['-968582927650604267027127767242160672',\n",
" '-615391447297339813950840270560399175'],\n",
" ['-349524047948521414307381813385449474',\n",
" '-394712802987869376369174007174918150']],\n",
" [['-1195008336948108945640918772722080227',\n",
" '-391453675833271485890705066425298906'],\n",
" ['-1035539474474336745928350434338370235',\n",
" '375449144451453718974060701074107917'],\n",
" ['-468574096206261610672918401549766744',\n",
" '-461492881731804944422419395904964084'],\n",
" ['-157987822858060281896825874562638157',\n",
" '-145297327207434479738146166840718303']],\n",
" [['-717832718354692660291274590189907309',\n",
" '-640793387586819749749055661801718428'],\n",
" ['-818234976163909363095633653303124629',\n",
" '-486529556567947364827511906932334658'],\n",
" ['-488975320390965478682141686514332960',\n",
" '-593549900211690891912136829366038418'],\n",
" ['-88817120440234533520269026413841619',\n",
" '-188924963686509380494214483287084738']]],\n",
" [[['57546413369690632436021828010377216',\n",
" '844338365610010970536479881582084096'],\n",
" ['713605335486457688719381102919155712',\n",
" '375215677051519710413966252668092416'],\n",
" ['755914587195177990836477246220271616',\n",
" '818027579922420637827386176052396032'],\n",
" ['66541310804045710582849369230278656',\n",
" '347409709477862532129959056406216704']],\n",
" [['289886146631823524117043901901045760',\n",
" '747073207457187946361744580709187584'],\n",
" ['596964332285599153985153944246026240',\n",
" '55475850457661407668048488535425024'],\n",
" ['170834380408647470600498462609899520',\n",
" '509441462772270674298218142377181184'],\n",
" ['34071275330636135911467390225874944',\n",
" '138225886497714127955769149616029696']],\n",
" [['799025578005122329965199425850572800',\n",
" '638105259408657768502010079451545600'],\n",
" ['646664651333832093639422680485593088',\n",
" '675100193761157594649844145046159360'],\n",
" ['445458083786331341876221205003894784',\n",
" '502163711096538860296377604167958528'],\n",
" ['47026304856349756806446693973229568',\n",
" '831593504386261794099030491582693376']],\n",
" [['939137107020160348118700928203227136',\n",
" '113237806886600667494639994056736768'],\n",
" ['659213932223174550761216604282814464',\n",
" '197300411875572149344585017353830400'],\n",
" ['421437083594697043343248459305058304',\n",
" '120269150227163283149044634810843136'],\n",
" ['198117022230724190125402300398698496',\n",
" '310521369112965179461249563143176192']]])"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out, remainder = Conv2DsameInt(10, 10, 3, 2, 4, 3, 10**36, X_in, weights, bias)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"weights\": weights,\n",
" \"bias\": bias,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"with open(\"conv2Dsame_stride_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/dense.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Dense\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(20,))\n",
"out = Dense(10)(inputs)\n",
"model = Model(inputs, out)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 20)] 0 \n",
" \n",
" dense (Dense) (None, 10) 210 \n",
" \n",
"=================================================================\n",
"Total params: 210\n",
"Trainable params: 210\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.91709806, 0.82830839, 0.93914066, 0.57037095, 0.04271652,\n",
" 0.35534695, 0.29179199, 0.80227101, 0.65690956, 0.59359125,\n",
" 0.57083799, 0.64906287, 0.08615951, 0.20494363, 0.98687436,\n",
" 0.70022373, 0.8282763 , 0.38845018, 0.1025627 , 0.46584396]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,20)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 31ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 20:08:46.369862: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[-0.9478299 , -0.2901961 , 1.2173429 , 0.9856129 , 0.44817972,\n",
" 0.8500049 , 1.2243729 , 1.1230452 , -0.8100219 , 0.65824366]],\n",
" dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"X_in = [int(x*1e36) for x in X[0]]\n",
"weights = [[None for _ in range(10)] for _ in range(20)]\n",
"for i in range(20):\n",
" for j in range(10):\n",
" weights[i][j] = int(model.get_weights()[0][i][j]*1e36)\n",
"bias = [int(b*1e72) for b in model.get_weights()[1]]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def DenseInt(nInputs, nOutputs, n, input, weights, bias):\n",
" Input = [str(input[i] % p) for i in range(nInputs)]\n",
" Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\n",
" Bias = [str(bias[i] % p) for i in range(nOutputs)]\n",
" out = [0 for _ in range(nOutputs)]\n",
" remainder = [None for _ in range(nOutputs)]\n",
" for j in range(nOutputs):\n",
" for i in range(nInputs):\n",
" out[j] += input[i] * weights[i][j]\n",
" out[j] += bias[j]\n",
" remainder[j] = str(out[j] % n)\n",
" out[j] = str(out[j] // n % p)\n",
" return Input, Weights, Bias, out, remainder\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(['21888242871839275222246405745257275088547416570344934017690618098050994599407',\n",
" '21888242871839275222246405745257275088548074204322728883645171911568575253269',\n",
" '1217342773824182708964164664298235747',\n",
" '985612918881516198369842470059289901',\n",
" '448179765935532159653151439285979820',\n",
" '850005025728080684762697042708611430',\n",
" '1224373017260726380443809993782617513',\n",
" '1123045202502242457956309189904120564',\n",
" '21888242871839275222246405745257275088547554378545433689485043918282349046950',\n",
" '658243650814707862463466520227993190'],\n",
" ['51492294878586576180273547728388096',\n",
" '777789140836427041572477556551057408',\n",
" '890475291130181473765283908913463296',\n",
" '963682024802736049277914862344732672',\n",
" '180838407593997560156976766263492608',\n",
" '458215330546393498330258578539020288',\n",
" '738904904497555276279419263936102400',\n",
" '770453107465054933435045502301241344',\n",
" '616225701137188004915996184419500032',\n",
" '106851476518473341575934978717384704'])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, weights, bias, out, remainder = DenseInt(20, 10, 10**36, X_in, weights, bias)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"weights\": weights,\n",
" \"bias\": bias,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"with open(\"dense_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/depthwiseConv2D.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "4d60427f-21e9-41b1-a5eb-0d36d2c395ea",
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"import numpy as np\n",
"import json"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "b1962e3f-18b6-43b2-88f8-e81a49f4edbc",
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n",
"CIRCOM_PRIME = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n",
"MAX_POSITIVE = CIRCOM_PRIME // 2\n",
"MAX_NEGATIVE = MAX_POSITIVE + 1 # The most positive number\n",
"\n",
"EXPONENT = 15\n",
"\n",
"def from_circom(x):\n",
" if type(x) != int:\n",
" x = int(x)\n",
" if x > MAX_POSITIVE: \n",
" return x - CIRCOM_PRIME\n",
" return x\n",
" \n",
"def to_circom(x):\n",
" if type(x) != int:\n",
" x = int(x)\n",
" if x < 0:\n",
" return x + CIRCOM_PRIME \n",
" return x\n",
"\n",
"class SeparableConv2D(nn.Module):\n",
" '''Separable convolution'''\n",
" def __init__(self, in_channels, out_channels, stride=1):\n",
" super(SeparableConv2D, self).__init__()\n",
" self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\n",
" self.pw_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\n",
"\n",
" def forward(self, x):\n",
" x = self.dw_conv(x)\n",
" x = self.pw_conv(x)\n",
" return x"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a7ad1f77-24e0-470e-b4de-63234ac9542b",
"metadata": {},
"outputs": [],
"source": [
"input = torch.randn((1, 3, 5, 5))\n",
"model = SeparableConv2D(3, 6)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "88e91743-d234-4e55-bd65-f4a5b0f5b350",
"metadata": {},
"outputs": [],
"source": [
"def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" assert(nFilters % nChannels == 0)\n",
" outRows = (nRows - kernelSize)//strides + 1\n",
" outCols = (nCols - kernelSize)//strides + 1\n",
" \n",
" # out = np.zeros((outRows, outCols, nFilters))\n",
" out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" remainder = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" # remainder = np.zeros((outRows, outCols, nFilters))\n",
" \n",
" for row in range(outRows):\n",
" for col in range(outCols):\n",
" for channel in range(nChannels):\n",
" for x in range(kernelSize):\n",
" for y in range(kernelSize):\n",
" out[row][col][channel] += int(input[row*strides+x, col*strides+y, channel]) * int(weights[x, y, channel])\n",
" \n",
" out[row][col][channel] += int(bias[channel])\n",
" remainder[row][col][channel] = str(int(out[row][col][channel] % n))\n",
" out[row][col][channel] = int(out[row][col][channel] // n)\n",
" \n",
" return out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "e666c225-f618-43d4-b003-56f9b4699d2e",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"weights = model.dw_conv.weight.squeeze().detach().numpy()\n",
"bias = torch.zeros(weights.shape[0]).numpy()\n",
"\n",
"expected = model.dw_conv(input).detach().numpy()\n",
"\n",
"padded = F.pad(input, (1,1,1,1), \"constant\", 0)\n",
"padded = padded.squeeze().numpy().transpose((1, 2, 0))\n",
"weights = weights.transpose((1, 2, 0))\n",
"\n",
"quantized_image = padded * 10**EXPONENT\n",
"quantized_weights = weights * 10**EXPONENT\n",
"\n",
"actual, rem = DepthwiseConv(7, 7, 3, 3, 3, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\n",
"\n",
"expected = expected.squeeze().transpose((1, 2, 0))\n",
"expected = expected * 10**EXPONENT\n",
"\n",
"assert(np.allclose(expected, actual, atol=0.00001))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "904ce6c4-f1d4-43f3-80f0-5e3df61d5546",
"metadata": {},
"outputs": [],
"source": [
"weights = model.dw_conv.weight.squeeze().detach().numpy()\n",
"bias = torch.zeros(weights.shape[0]).numpy()\n",
"\n",
"padded = F.pad(input, (1,1,1,1), \"constant\", 0)\n",
"padded = padded.squeeze().numpy().transpose((1, 2, 0))\n",
"weights = weights.transpose((1, 2, 0))\n",
"\n",
"quantized_image = padded * 10**EXPONENT\n",
"quantized_weights = weights * 10**EXPONENT\n",
"\n",
"out, remainder = DepthwiseConv(7, 7, 3, 3, 3, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\n",
"\n",
"circuit_in = quantized_image.round().astype(int).astype(str).tolist()\n",
"circuit_weights = quantized_weights.round().astype(int).astype(str).tolist()\n",
"circuit_bias = bias.round().astype(int).astype(str).tolist()\n",
"\n",
"input_json_path = \"depthwiseConv2D_input.json\"\n",
"with open(input_json_path, \"w\") as input_file:\n",
" json.dump({\"in\": circuit_in,\n",
" \"weights\": circuit_weights,\n",
" \"remainder\": remainder,\n",
" \"out\": out,\n",
" \"bias\": circuit_bias,\n",
" },\n",
" input_file)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "523588d7-4c81-4bb9-9dbd-e626b6d2a8a9",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
| https://github.com/socathie/circomlib-ml |
models/flatten.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Flatten\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = Flatten()(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" flatten (Flatten) (None, 75) 0 \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.weights"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.9191584 , 0.41015604, 0.0493302 ],\n",
" [0.20412956, 0.14984944, 0.71595293],\n",
" [0.57980447, 0.28233206, 0.30881941],\n",
" [0.98703541, 0.91977126, 0.89591016],\n",
" [0.29365768, 0.89541076, 0.97098122]],\n",
"\n",
" [[0.28270309, 0.85760979, 0.12266525],\n",
" [0.2386079 , 0.93741419, 0.83312648],\n",
" [0.02935679, 0.68497567, 0.37248647],\n",
" [0.76807667, 0.72347087, 0.84375984],\n",
" [0.89233681, 0.87703334, 0.53846864]],\n",
"\n",
" [[0.14028452, 0.61585222, 0.34271206],\n",
" [0.45404173, 0.26365195, 0.05140719],\n",
" [0.36253999, 0.51529482, 0.15006 ],\n",
" [0.82061228, 0.08937872, 0.65234282],\n",
" [0.31024437, 0.09785702, 0.40629764]],\n",
"\n",
" [[0.75192339, 0.55825739, 0.86978978],\n",
" [0.76105885, 0.54160411, 0.72517187],\n",
" [0.28701856, 0.31868524, 0.46890464],\n",
" [0.0902 , 0.3022873 , 0.48529066],\n",
" [0.24453082, 0.93271481, 0.08555694]],\n",
"\n",
" [[0.52171579, 0.22363436, 0.85212827],\n",
" [0.9823001 , 0.64424366, 0.96495129],\n",
" [0.61750385, 0.53921774, 0.75703119],\n",
" [0.57267588, 0.18643057, 0.26532282],\n",
" [0.22546175, 0.0340469 , 0.19259163]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 95ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 17:09:53.715790: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[0.9191584 , 0.41015604, 0.0493302 , 0.20412956, 0.14984943,\n",
" 0.71595293, 0.5798045 , 0.28233206, 0.3088194 , 0.9870354 ,\n",
" 0.91977125, 0.89591014, 0.2936577 , 0.8954108 , 0.97098124,\n",
" 0.2827031 , 0.8576098 , 0.12266525, 0.2386079 , 0.93741417,\n",
" 0.8331265 , 0.02935679, 0.6849757 , 0.37248647, 0.76807666,\n",
" 0.72347087, 0.84375983, 0.8923368 , 0.87703335, 0.53846866,\n",
" 0.14028452, 0.61585224, 0.34271204, 0.45404172, 0.26365197,\n",
" 0.05140718, 0.36253998, 0.5152948 , 0.15006 , 0.82061225,\n",
" 0.08937872, 0.6523428 , 0.31024438, 0.09785703, 0.40629762,\n",
" 0.7519234 , 0.5582574 , 0.8697898 , 0.76105887, 0.5416041 ,\n",
" 0.72517186, 0.28701857, 0.31868523, 0.46890464, 0.0902 ,\n",
" 0.3022873 , 0.48529068, 0.24453081, 0.9327148 , 0.08555695,\n",
" 0.5217158 , 0.22363436, 0.85212827, 0.9823001 , 0.64424366,\n",
" 0.9649513 , 0.6175039 , 0.5392177 , 0.7570312 , 0.5726759 ,\n",
" 0.18643057, 0.26532283, 0.22546175, 0.0340469 , 0.19259164]],\n",
" dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": (X*1e36).round().astype(int).flatten().tolist(),\n",
" \"out\": (X*1e36).round().astype(int).flatten().tolist()\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"with open(\"flatten2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/globalAveragePooling2D.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, GlobalAveragePooling2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"out = GlobalAveragePooling2D()(inputs)\n",
"model = Model(inputs, out)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" global_average_pooling2d (G (None, 3) 0 \n",
" lobalAveragePooling2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.20867486, 0.38680755, 0.84218508],\n",
" [0.23655331, 0.33771458, 0.73516473],\n",
" [0.49345271, 0.95094652, 0.25402692],\n",
" [0.22771833, 0.97688694, 0.52917136],\n",
" [0.5871173 , 0.50441061, 0.97392083]],\n",
"\n",
" [[0.93934312, 0.52666508, 0.31051829],\n",
" [0.2163095 , 0.79177499, 0.3108483 ],\n",
" [0.53926143, 0.15753146, 0.99773704],\n",
" [0.12234007, 0.20568095, 0.11838809],\n",
" [0.9248088 , 0.52638782, 0.81404877]],\n",
"\n",
" [[0.01465677, 0.32765939, 0.74282836],\n",
" [0.6800781 , 0.40869424, 0.62145002],\n",
" [0.67374829, 0.81617885, 0.39987386],\n",
" [0.82099264, 0.35918735, 0.47107381],\n",
" [0.83104015, 0.83004572, 0.28737773]],\n",
"\n",
" [[0.74027671, 0.85697829, 0.49504698],\n",
" [0.94596904, 0.25070827, 0.22236492],\n",
" [0.00357426, 0.35882451, 0.32972314],\n",
" [0.57254891, 0.86380467, 0.30862848],\n",
" [0.93720522, 0.4496124 , 0.74115158]],\n",
"\n",
" [[0.12640468, 0.76330103, 0.35499368],\n",
" [0.37773597, 0.016954 , 0.43058637],\n",
" [0.94290805, 0.06019639, 0.95692684],\n",
" [0.09562172, 0.61791084, 0.47187214],\n",
" [0.67092949, 0.27421069, 0.85342606]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 36ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 20:10:13.674664: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[0.5171708 , 0.5047629 , 0.54293334]], dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k] * 1e36) for k in range(3)] for j in range(5)] for i in range(5)]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def GlobalAveragePooling2DInt(nRows, nCols, nChannels, input):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" out = [0 for _ in range(nChannels)]\n",
" remainder = [None for _ in range(nChannels)]\n",
" for k in range(nChannels):\n",
" for i in range(nRows):\n",
" for j in range(nCols):\n",
" out[k] += input[i][j][k]\n",
" remainder[k] = str(out[k] % (nRows * nCols))\n",
" out[k] = str(out[k] // (nRows * nCols) % p)\n",
" return Input, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(['517170777415975145178424005003973754',\n",
" '504762926219743484887371893374996971',\n",
" '542933334573104965421804807186892718'],\n",
" ['22', '13', '2'])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, out, remainder = GlobalAveragePooling2DInt(5, 5, 3, X_in)\n",
"out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out,\n",
" \"remainder\": remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"with open(\"globalAveragePooling2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/globalMaxPooling2D.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, GlobalMaxPooling2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = GlobalMaxPooling2D()(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" global_max_pooling2d (Globa (None, 3) 0 \n",
" lMaxPooling2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.91518641, 0.66718006, 0.92376279],\n",
" [0.97385149, 0.35848662, 0.25065166],\n",
" [0.02434808, 0.66270045, 0.51526436],\n",
" [0.97110905, 0.49335089, 0.27623285],\n",
" [0.88055993, 0.91070856, 0.89195416]],\n",
"\n",
" [[0.7950447 , 0.42411655, 0.66516519],\n",
" [0.18674268, 0.3046312 , 0.77807526],\n",
" [0.13333453, 0.68076544, 0.64069414],\n",
" [0.63039814, 0.71725918, 0.74384312],\n",
" [0.48789065, 0.68079997, 0.25869622]],\n",
"\n",
" [[0.55852658, 0.78138444, 0.0772444 ],\n",
" [0.71960766, 0.01860611, 0.63859032],\n",
" [0.04100894, 0.007163 , 0.28648401],\n",
" [0.70371242, 0.8565901 , 0.73254654],\n",
" [0.35201173, 0.3338802 , 0.83269692]],\n",
"\n",
" [[0.31146493, 0.11242401, 0.46909255],\n",
" [0.785379 , 0.69905536, 0.99196427],\n",
" [0.29254832, 0.04347593, 0.40404928],\n",
" [0.64393514, 0.6579046 , 0.44890337],\n",
" [0.25879095, 0.64296721, 0.65792656]],\n",
"\n",
" [[0.7972691 , 0.77522241, 0.02028976],\n",
" [0.71408815, 0.2214879 , 0.07804482],\n",
" [0.65261239, 0.62851164, 0.12214903],\n",
" [0.31611407, 0.18022595, 0.97735959],\n",
" [0.57391523, 0.8818251 , 0.06020382]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 31ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 20:16:54.369715: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[0.9738515 , 0.91070855, 0.9919643 ]], dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def GlobalMaxPooling2DInt(nRows, nCols, nChannels, input):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" out = [max(input[i][j][k] for i in range(nRows) for j in range(nCols)) for k in range(nChannels)]\n",
" return Input, out"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[973851490313537338484516198430015488,\n",
" 910708561343324144695836121136889856,\n",
" 991964273065568131927416012428804096]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, out = GlobalMaxPooling2DInt(5,5,3,X_in)\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"with open(\"globalMaxPooling2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/lr_zanh.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# example from https://towardsdatascience.com/replicate-a-logistic-regression-model-as-an-artificial-neural-network-in-keras-cd6f49cf4b2c"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import LogisticRegression\n",
"from tensorflow.keras.models import Sequential\n",
"from tensorflow.keras.layers import InputLayer\n",
"from tensorflow.keras.layers import Dense\n",
"import tensorflow as tf"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>mean radius</th>\n",
" <th>mean texture</th>\n",
" <th>mean perimeter</th>\n",
" <th>mean area</th>\n",
" <th>mean smoothness</th>\n",
" <th>mean compactness</th>\n",
" <th>mean concavity</th>\n",
" <th>mean concave points</th>\n",
" <th>mean symmetry</th>\n",
" <th>mean fractal dimension</th>\n",
" <th>...</th>\n",
" <th>worst radius</th>\n",
" <th>worst texture</th>\n",
" <th>worst perimeter</th>\n",
" <th>worst area</th>\n",
" <th>worst smoothness</th>\n",
" <th>worst compactness</th>\n",
" <th>worst concavity</th>\n",
" <th>worst concave points</th>\n",
" <th>worst symmetry</th>\n",
" <th>worst fractal dimension</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>17.99</td>\n",
" <td>10.38</td>\n",
" <td>122.80</td>\n",
" <td>1001.0</td>\n",
" <td>0.11840</td>\n",
" <td>0.27760</td>\n",
" <td>0.3001</td>\n",
" <td>0.14710</td>\n",
" <td>0.2419</td>\n",
" <td>0.07871</td>\n",
" <td>...</td>\n",
" <td>25.38</td>\n",
" <td>17.33</td>\n",
" <td>184.60</td>\n",
" <td>2019.0</td>\n",
" <td>0.1622</td>\n",
" <td>0.6656</td>\n",
" <td>0.7119</td>\n",
" <td>0.2654</td>\n",
" <td>0.4601</td>\n",
" <td>0.11890</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>20.57</td>\n",
" <td>17.77</td>\n",
" <td>132.90</td>\n",
" <td>1326.0</td>\n",
" <td>0.08474</td>\n",
" <td>0.07864</td>\n",
" <td>0.0869</td>\n",
" <td>0.07017</td>\n",
" <td>0.1812</td>\n",
" <td>0.05667</td>\n",
" <td>...</td>\n",
" <td>24.99</td>\n",
" <td>23.41</td>\n",
" <td>158.80</td>\n",
" <td>1956.0</td>\n",
" <td>0.1238</td>\n",
" <td>0.1866</td>\n",
" <td>0.2416</td>\n",
" <td>0.1860</td>\n",
" <td>0.2750</td>\n",
" <td>0.08902</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>19.69</td>\n",
" <td>21.25</td>\n",
" <td>130.00</td>\n",
" <td>1203.0</td>\n",
" <td>0.10960</td>\n",
" <td>0.15990</td>\n",
" <td>0.1974</td>\n",
" <td>0.12790</td>\n",
" <td>0.2069</td>\n",
" <td>0.05999</td>\n",
" <td>...</td>\n",
" <td>23.57</td>\n",
" <td>25.53</td>\n",
" <td>152.50</td>\n",
" <td>1709.0</td>\n",
" <td>0.1444</td>\n",
" <td>0.4245</td>\n",
" <td>0.4504</td>\n",
" <td>0.2430</td>\n",
" <td>0.3613</td>\n",
" <td>0.08758</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>11.42</td>\n",
" <td>20.38</td>\n",
" <td>77.58</td>\n",
" <td>386.1</td>\n",
" <td>0.14250</td>\n",
" <td>0.28390</td>\n",
" <td>0.2414</td>\n",
" <td>0.10520</td>\n",
" <td>0.2597</td>\n",
" <td>0.09744</td>\n",
" <td>...</td>\n",
" <td>14.91</td>\n",
" <td>26.50</td>\n",
" <td>98.87</td>\n",
" <td>567.7</td>\n",
" <td>0.2098</td>\n",
" <td>0.8663</td>\n",
" <td>0.6869</td>\n",
" <td>0.2575</td>\n",
" <td>0.6638</td>\n",
" <td>0.17300</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>20.29</td>\n",
" <td>14.34</td>\n",
" <td>135.10</td>\n",
" <td>1297.0</td>\n",
" <td>0.10030</td>\n",
" <td>0.13280</td>\n",
" <td>0.1980</td>\n",
" <td>0.10430</td>\n",
" <td>0.1809</td>\n",
" <td>0.05883</td>\n",
" <td>...</td>\n",
" <td>22.54</td>\n",
" <td>16.67</td>\n",
" <td>152.20</td>\n",
" <td>1575.0</td>\n",
" <td>0.1374</td>\n",
" <td>0.2050</td>\n",
" <td>0.4000</td>\n",
" <td>0.1625</td>\n",
" <td>0.2364</td>\n",
" <td>0.07678</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>5 rows × 30 columns</p>\n",
"</div>"
],
"text/plain": [
" mean radius mean texture mean perimeter mean area mean smoothness \\\n",
"0 17.99 10.38 122.80 1001.0 0.11840 \n",
"1 20.57 17.77 132.90 1326.0 0.08474 \n",
"2 19.69 21.25 130.00 1203.0 0.10960 \n",
"3 11.42 20.38 77.58 386.1 0.14250 \n",
"4 20.29 14.34 135.10 1297.0 0.10030 \n",
"\n",
" mean compactness mean concavity mean concave points mean symmetry \\\n",
"0 0.27760 0.3001 0.14710 0.2419 \n",
"1 0.07864 0.0869 0.07017 0.1812 \n",
"2 0.15990 0.1974 0.12790 0.2069 \n",
"3 0.28390 0.2414 0.10520 0.2597 \n",
"4 0.13280 0.1980 0.10430 0.1809 \n",
"\n",
" mean fractal dimension ... worst radius worst texture worst perimeter \\\n",
"0 0.07871 ... 25.38 17.33 184.60 \n",
"1 0.05667 ... 24.99 23.41 158.80 \n",
"2 0.05999 ... 23.57 25.53 152.50 \n",
"3 0.09744 ... 14.91 26.50 98.87 \n",
"4 0.05883 ... 22.54 16.67 152.20 \n",
"\n",
" worst area worst smoothness worst compactness worst concavity \\\n",
"0 2019.0 0.1622 0.6656 0.7119 \n",
"1 1956.0 0.1238 0.1866 0.2416 \n",
"2 1709.0 0.1444 0.4245 0.4504 \n",
"3 567.7 0.2098 0.8663 0.6869 \n",
"4 1575.0 0.1374 0.2050 0.4000 \n",
"\n",
" worst concave points worst symmetry worst fractal dimension \n",
"0 0.2654 0.4601 0.11890 \n",
"1 0.1860 0.2750 0.08902 \n",
"2 0.2430 0.3613 0.08758 \n",
"3 0.2575 0.6638 0.17300 \n",
"4 0.1625 0.2364 0.07678 \n",
"\n",
"[5 rows x 30 columns]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cancer = load_breast_cancer()\n",
"df = pd.DataFrame(cancer.data,\n",
" columns=cancer.feature_names)\n",
"df.head()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"X = (df-df.mean())/df.std()\n",
"# X = 2*(df-df.min())/(df.max()-df.min()) - 1\n",
"# X = df\n",
"y = pd.Series(cancer.target)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# change 0 to -1\n",
"# y = y.apply(lambda x: -1 if x==0 else 1)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# Make train and test sets\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, \n",
" shuffle=True, random_state=2)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accuracy: 0.97\n",
"Precision: 0.99\n",
"Recall: 0.97\n",
"F-Score: 0.98\n"
]
}
],
"source": [
"# Initialize a logistic regression model\n",
"log_reg_model = LogisticRegression(max_iter=2500,\n",
" random_state=42)\n",
"\n",
"# Train (fit) the model\n",
"log_reg_model.fit(X_train, y_train)\n",
"\n",
"# Make predictions\n",
"y_pred = log_reg_model.predict(X_test) # Predictions\n",
"y_true = y_test # True values\n",
"\n",
"# Model evaluation\n",
"from sklearn.metrics import accuracy_score\n",
"from sklearn.metrics import precision_recall_fscore_support\n",
"import numpy as np\n",
"\n",
"print(\"Accuracy:\", np.round(accuracy_score(y_true, y_pred), 2))\n",
"precision, recall, fscore, _ = precision_recall_fscore_support(y_true, y_pred,\n",
" average='binary')\n",
"print(\"Precision:\", np.round(precision, 2))\n",
"print(\"Recall:\", np.round(recall, 2))\n",
"print(\"F-Score:\", np.round(fscore, 2))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"model = Sequential()\n",
"\n",
"model.add(InputLayer(input_shape=(30, )))\n",
"# No hidden layers\n",
"model.add(Dense(1, activation='tanh'))\n",
"\n",
"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\n",
"model.compile(optimizer=optimizer,\n",
" loss='binary_crossentropy',\n",
" metrics=['accuracy'])"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/10\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-12 14:44:16.741589: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"12/12 [==============================] - 0s 12ms/step - loss: 2.0170 - accuracy: 0.7747 - val_loss: 0.9741 - val_accuracy: 0.8901\n",
"Epoch 2/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 1.0516 - accuracy: 0.8929 - val_loss: 0.7816 - val_accuracy: 0.9011\n",
"Epoch 3/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.8193 - accuracy: 0.9093 - val_loss: 0.7534 - val_accuracy: 0.9121\n",
"Epoch 4/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.6689 - accuracy: 0.9341 - val_loss: 0.7462 - val_accuracy: 0.9121\n",
"Epoch 5/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.6168 - accuracy: 0.9423 - val_loss: 0.7404 - val_accuracy: 0.9231\n",
"Epoch 6/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.3145 - accuracy: 0.9560 - val_loss: 0.2055 - val_accuracy: 0.9670\n",
"Epoch 7/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2109 - accuracy: 0.9505 - val_loss: 0.2063 - val_accuracy: 0.9670\n",
"Epoch 8/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.1104 - accuracy: 0.9670 - val_loss: 0.0447 - val_accuracy: 0.9780\n",
"Epoch 9/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0851 - accuracy: 0.9698 - val_loss: 0.0443 - val_accuracy: 0.9780\n",
"Epoch 10/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.0745 - accuracy: 0.9698 - val_loss: 0.0453 - val_accuracy: 0.9670\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x15fd9eeb0>"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.fit(X_train, y_train,\n",
" epochs=10, batch_size=32,\n",
" validation_split=0.2,\n",
" shuffle=False)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4/4 [==============================] - 0s 1ms/step - loss: 0.4077 - accuracy: 0.9474\n",
"Test loss: 0.4076523780822754\n",
"Test accuracy: 0.9473684430122375\n"
]
}
],
"source": [
"test_loss, test_acc = model.evaluate(X_test, y_test)\n",
"print(\"Test loss:\", test_loss)\n",
"print(\"Test accuracy:\", test_acc)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"def zanh(x):\n",
" return 0.006769816 + 0.554670504 * x - 0.009411195 * x**2 - 0.014187547 * x**3\n",
"\n",
"zanh_model = Sequential()\n",
"\n",
"zanh_model.add(InputLayer(input_shape=(30, )))\n",
"# No hidden layers\n",
"zanh_model.add(Dense(1, activation=zanh))\n",
"\n",
"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\n",
"zanh_model.compile(optimizer=optimizer,\n",
" loss='binary_crossentropy',\n",
" metrics=['accuracy'])"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/10\n",
"12/12 [==============================] - 0s 12ms/step - loss: 2.7550 - accuracy: 0.6978 - val_loss: 1.5429 - val_accuracy: 0.7912\n",
"Epoch 2/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 1.5446 - accuracy: 0.8297 - val_loss: 0.5988 - val_accuracy: 0.9341\n",
"Epoch 3/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.6857 - accuracy: 0.8791 - val_loss: 0.1382 - val_accuracy: 0.9670\n",
"Epoch 4/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.2950 - accuracy: 0.9258 - val_loss: 0.1452 - val_accuracy: 0.9451\n",
"Epoch 5/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.2493 - accuracy: 0.9478 - val_loss: 0.1188 - val_accuracy: 0.9670\n",
"Epoch 6/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.1930 - accuracy: 0.9588 - val_loss: 0.1023 - val_accuracy: 0.9670\n",
"Epoch 7/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.1749 - accuracy: 0.9643 - val_loss: 0.0879 - val_accuracy: 0.9670\n",
"Epoch 8/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.1841 - accuracy: 0.9643 - val_loss: 0.0996 - val_accuracy: 0.9780\n",
"Epoch 9/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.1695 - accuracy: 0.9670 - val_loss: 0.0836 - val_accuracy: 0.9670\n",
"Epoch 10/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2076 - accuracy: 0.9588 - val_loss: 0.0839 - val_accuracy: 0.9780\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x15ff92ca0>"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"zanh_model.fit(X_train, y_train,\n",
" epochs=10, batch_size=32,\n",
" validation_split=0.2,\n",
" shuffle=False)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4/4 [==============================] - 0s 1ms/step - loss: 0.2434 - accuracy: 0.9649\n",
"Test loss: 0.24344508349895477\n",
"Test accuracy: 0.9649122953414917\n"
]
}
],
"source": [
"test_loss, test_acc = zanh_model.evaluate(X_test, y_test)\n",
"print(\"Test loss:\", test_loss)\n",
"print(\"Test accuracy:\", test_acc)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/lr_zigmoid.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# example from https://towardsdatascience.com/replicate-a-logistic-regression-model-as-an-artificial-neural-network-in-keras-cd6f49cf4b2c"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import LogisticRegression\n",
"from tensorflow.keras.models import Sequential\n",
"from tensorflow.keras.layers import InputLayer\n",
"from tensorflow.keras.layers import Dense\n",
"import tensorflow as tf"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>mean radius</th>\n",
" <th>mean texture</th>\n",
" <th>mean perimeter</th>\n",
" <th>mean area</th>\n",
" <th>mean smoothness</th>\n",
" <th>mean compactness</th>\n",
" <th>mean concavity</th>\n",
" <th>mean concave points</th>\n",
" <th>mean symmetry</th>\n",
" <th>mean fractal dimension</th>\n",
" <th>...</th>\n",
" <th>worst radius</th>\n",
" <th>worst texture</th>\n",
" <th>worst perimeter</th>\n",
" <th>worst area</th>\n",
" <th>worst smoothness</th>\n",
" <th>worst compactness</th>\n",
" <th>worst concavity</th>\n",
" <th>worst concave points</th>\n",
" <th>worst symmetry</th>\n",
" <th>worst fractal dimension</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>17.99</td>\n",
" <td>10.38</td>\n",
" <td>122.80</td>\n",
" <td>1001.0</td>\n",
" <td>0.11840</td>\n",
" <td>0.27760</td>\n",
" <td>0.3001</td>\n",
" <td>0.14710</td>\n",
" <td>0.2419</td>\n",
" <td>0.07871</td>\n",
" <td>...</td>\n",
" <td>25.38</td>\n",
" <td>17.33</td>\n",
" <td>184.60</td>\n",
" <td>2019.0</td>\n",
" <td>0.1622</td>\n",
" <td>0.6656</td>\n",
" <td>0.7119</td>\n",
" <td>0.2654</td>\n",
" <td>0.4601</td>\n",
" <td>0.11890</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>20.57</td>\n",
" <td>17.77</td>\n",
" <td>132.90</td>\n",
" <td>1326.0</td>\n",
" <td>0.08474</td>\n",
" <td>0.07864</td>\n",
" <td>0.0869</td>\n",
" <td>0.07017</td>\n",
" <td>0.1812</td>\n",
" <td>0.05667</td>\n",
" <td>...</td>\n",
" <td>24.99</td>\n",
" <td>23.41</td>\n",
" <td>158.80</td>\n",
" <td>1956.0</td>\n",
" <td>0.1238</td>\n",
" <td>0.1866</td>\n",
" <td>0.2416</td>\n",
" <td>0.1860</td>\n",
" <td>0.2750</td>\n",
" <td>0.08902</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>19.69</td>\n",
" <td>21.25</td>\n",
" <td>130.00</td>\n",
" <td>1203.0</td>\n",
" <td>0.10960</td>\n",
" <td>0.15990</td>\n",
" <td>0.1974</td>\n",
" <td>0.12790</td>\n",
" <td>0.2069</td>\n",
" <td>0.05999</td>\n",
" <td>...</td>\n",
" <td>23.57</td>\n",
" <td>25.53</td>\n",
" <td>152.50</td>\n",
" <td>1709.0</td>\n",
" <td>0.1444</td>\n",
" <td>0.4245</td>\n",
" <td>0.4504</td>\n",
" <td>0.2430</td>\n",
" <td>0.3613</td>\n",
" <td>0.08758</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>11.42</td>\n",
" <td>20.38</td>\n",
" <td>77.58</td>\n",
" <td>386.1</td>\n",
" <td>0.14250</td>\n",
" <td>0.28390</td>\n",
" <td>0.2414</td>\n",
" <td>0.10520</td>\n",
" <td>0.2597</td>\n",
" <td>0.09744</td>\n",
" <td>...</td>\n",
" <td>14.91</td>\n",
" <td>26.50</td>\n",
" <td>98.87</td>\n",
" <td>567.7</td>\n",
" <td>0.2098</td>\n",
" <td>0.8663</td>\n",
" <td>0.6869</td>\n",
" <td>0.2575</td>\n",
" <td>0.6638</td>\n",
" <td>0.17300</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>20.29</td>\n",
" <td>14.34</td>\n",
" <td>135.10</td>\n",
" <td>1297.0</td>\n",
" <td>0.10030</td>\n",
" <td>0.13280</td>\n",
" <td>0.1980</td>\n",
" <td>0.10430</td>\n",
" <td>0.1809</td>\n",
" <td>0.05883</td>\n",
" <td>...</td>\n",
" <td>22.54</td>\n",
" <td>16.67</td>\n",
" <td>152.20</td>\n",
" <td>1575.0</td>\n",
" <td>0.1374</td>\n",
" <td>0.2050</td>\n",
" <td>0.4000</td>\n",
" <td>0.1625</td>\n",
" <td>0.2364</td>\n",
" <td>0.07678</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>5 rows × 30 columns</p>\n",
"</div>"
],
"text/plain": [
" mean radius mean texture mean perimeter mean area mean smoothness \\\n",
"0 17.99 10.38 122.80 1001.0 0.11840 \n",
"1 20.57 17.77 132.90 1326.0 0.08474 \n",
"2 19.69 21.25 130.00 1203.0 0.10960 \n",
"3 11.42 20.38 77.58 386.1 0.14250 \n",
"4 20.29 14.34 135.10 1297.0 0.10030 \n",
"\n",
" mean compactness mean concavity mean concave points mean symmetry \\\n",
"0 0.27760 0.3001 0.14710 0.2419 \n",
"1 0.07864 0.0869 0.07017 0.1812 \n",
"2 0.15990 0.1974 0.12790 0.2069 \n",
"3 0.28390 0.2414 0.10520 0.2597 \n",
"4 0.13280 0.1980 0.10430 0.1809 \n",
"\n",
" mean fractal dimension ... worst radius worst texture worst perimeter \\\n",
"0 0.07871 ... 25.38 17.33 184.60 \n",
"1 0.05667 ... 24.99 23.41 158.80 \n",
"2 0.05999 ... 23.57 25.53 152.50 \n",
"3 0.09744 ... 14.91 26.50 98.87 \n",
"4 0.05883 ... 22.54 16.67 152.20 \n",
"\n",
" worst area worst smoothness worst compactness worst concavity \\\n",
"0 2019.0 0.1622 0.6656 0.7119 \n",
"1 1956.0 0.1238 0.1866 0.2416 \n",
"2 1709.0 0.1444 0.4245 0.4504 \n",
"3 567.7 0.2098 0.8663 0.6869 \n",
"4 1575.0 0.1374 0.2050 0.4000 \n",
"\n",
" worst concave points worst symmetry worst fractal dimension \n",
"0 0.2654 0.4601 0.11890 \n",
"1 0.1860 0.2750 0.08902 \n",
"2 0.2430 0.3613 0.08758 \n",
"3 0.2575 0.6638 0.17300 \n",
"4 0.1625 0.2364 0.07678 \n",
"\n",
"[5 rows x 30 columns]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cancer = load_breast_cancer()\n",
"df = pd.DataFrame(cancer.data,\n",
" columns=cancer.feature_names)\n",
"df.head()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"X = (df-df.mean())/df.std()\n",
"# X = 2*(df-df.min())/(df.max()-df.min()) - 1\n",
"# X = df\n",
"y = pd.Series(cancer.target)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# Make train and test sets\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, \n",
" shuffle=True, random_state=2)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accuracy: 0.97\n",
"Precision: 0.99\n",
"Recall: 0.97\n",
"F-Score: 0.98\n"
]
}
],
"source": [
"# Initialize a logistic regression model\n",
"log_reg_model = LogisticRegression(max_iter=2500,\n",
" random_state=42)\n",
"\n",
"# Train (fit) the model\n",
"log_reg_model.fit(X_train, y_train)\n",
"\n",
"# Make predictions\n",
"y_pred = log_reg_model.predict(X_test) # Predictions\n",
"y_true = y_test # True values\n",
"\n",
"# Model evaluation\n",
"from sklearn.metrics import accuracy_score\n",
"from sklearn.metrics import precision_recall_fscore_support\n",
"import numpy as np\n",
"\n",
"print(\"Accuracy:\", np.round(accuracy_score(y_true, y_pred), 2))\n",
"precision, recall, fscore, _ = precision_recall_fscore_support(y_true, y_pred,\n",
" average='binary')\n",
"print(\"Precision:\", np.round(precision, 2))\n",
"print(\"Recall:\", np.round(recall, 2))\n",
"print(\"F-Score:\", np.round(fscore, 2))"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"model = Sequential()\n",
"\n",
"model.add(InputLayer(input_shape=(30, )))\n",
"# No hidden layers\n",
"model.add(Dense(1, activation='sigmoid'))\n",
"\n",
"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\n",
"model.compile(optimizer=optimizer,\n",
" loss='binary_crossentropy',\n",
" metrics=['accuracy'])"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/10\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-12 14:37:31.395427: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"12/12 [==============================] - 0s 15ms/step - loss: 0.3646 - accuracy: 0.8407 - val_loss: 0.1326 - val_accuracy: 0.9341\n",
"Epoch 2/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0995 - accuracy: 0.9643 - val_loss: 0.0896 - val_accuracy: 0.9560\n",
"Epoch 3/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0793 - accuracy: 0.9808 - val_loss: 0.0776 - val_accuracy: 0.9670\n",
"Epoch 4/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0734 - accuracy: 0.9808 - val_loss: 0.0749 - val_accuracy: 0.9560\n",
"Epoch 5/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0705 - accuracy: 0.9780 - val_loss: 0.0735 - val_accuracy: 0.9560\n",
"Epoch 6/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.0684 - accuracy: 0.9808 - val_loss: 0.0713 - val_accuracy: 0.9670\n",
"Epoch 7/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0667 - accuracy: 0.9835 - val_loss: 0.0687 - val_accuracy: 0.9780\n",
"Epoch 8/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0653 - accuracy: 0.9835 - val_loss: 0.0665 - val_accuracy: 0.9670\n",
"Epoch 9/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0640 - accuracy: 0.9835 - val_loss: 0.0648 - val_accuracy: 0.9670\n",
"Epoch 10/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.0628 - accuracy: 0.9835 - val_loss: 0.0635 - val_accuracy: 0.9670\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x160461eb0>"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.fit(X_train, y_train,\n",
" epochs=10, batch_size=32,\n",
" validation_split=0.2,\n",
" shuffle=False)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4/4 [==============================] - 0s 1ms/step - loss: 0.0719 - accuracy: 0.9737\n",
"Test loss: 0.07194967567920685\n",
"Test accuracy: 0.9736841917037964\n"
]
}
],
"source": [
"test_loss, test_acc = model.evaluate(X_test, y_test)\n",
"print(\"Test loss:\", test_loss)\n",
"print(\"Test accuracy:\", test_acc)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"def zigmoid(x):\n",
" return 0.502073021 + 0.198695283 * x - 0.001570683 * x**2 - 0.004001354 * x**3\n",
"zigmoid_model = Sequential()\n",
"\n",
"zigmoid_model.add(InputLayer(input_shape=(30, )))\n",
"# No hidden layers\n",
"zigmoid_model.add(Dense(1, activation=zigmoid))\n",
"\n",
"optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\n",
"zigmoid_model.compile(optimizer=optimizer,\n",
" loss='binary_crossentropy',\n",
" metrics=['accuracy'])"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/10\n",
"12/12 [==============================] - 0s 11ms/step - loss: 1.1248 - accuracy: 0.7720 - val_loss: 0.5485 - val_accuracy: 0.9011\n",
"Epoch 2/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.5224 - accuracy: 0.9121 - val_loss: 0.2269 - val_accuracy: 0.9780\n",
"Epoch 3/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2841 - accuracy: 0.9423 - val_loss: 0.1875 - val_accuracy: 0.9560\n",
"Epoch 4/10\n",
"12/12 [==============================] - 0s 3ms/step - loss: 0.2715 - accuracy: 0.9588 - val_loss: 0.1772 - val_accuracy: 0.9560\n",
"Epoch 5/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2591 - accuracy: 0.9560 - val_loss: 0.1714 - val_accuracy: 0.9670\n",
"Epoch 6/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2549 - accuracy: 0.9560 - val_loss: 0.1657 - val_accuracy: 0.9670\n",
"Epoch 7/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2559 - accuracy: 0.9533 - val_loss: 0.1639 - val_accuracy: 0.9670\n",
"Epoch 8/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2508 - accuracy: 0.9533 - val_loss: 0.1605 - val_accuracy: 0.9670\n",
"Epoch 9/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2475 - accuracy: 0.9560 - val_loss: 0.1590 - val_accuracy: 0.9670\n",
"Epoch 10/10\n",
"12/12 [==============================] - 0s 2ms/step - loss: 0.2490 - accuracy: 0.9588 - val_loss: 0.1591 - val_accuracy: 0.9560\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x1604f03a0>"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"zigmoid_model.fit(X_train, y_train,\n",
" epochs=10, batch_size=32,\n",
" validation_split=0.2,\n",
" shuffle=False)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4/4 [==============================] - 0s 1ms/step - loss: 0.1795 - accuracy: 0.9561\n",
"Test loss: 0.1795477569103241\n",
"Test accuracy: 0.9561403393745422\n"
]
}
],
"source": [
"test_loss, test_acc = zigmoid_model.evaluate(X_test, y_test)\n",
"print(\"Test loss:\", test_loss)\n",
"print(\"Test accuracy:\", test_acc)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/maxPooling2d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, MaxPooling2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = MaxPooling2D(pool_size=2)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" max_pooling2d (MaxPooling2D (None, 2, 2, 3) 0 \n",
" ) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.44076837, 0.4645178 , 0.88532658],\n",
" [0.98571178, 0.36091035, 0.37878294],\n",
" [0.09039054, 0.43555648, 0.70723494],\n",
" [0.75087575, 0.46161156, 0.27621923],\n",
" [0.3658674 , 0.76096207, 0.85368763]],\n",
"\n",
" [[0.53353854, 0.18599507, 0.85547589],\n",
" [0.83705565, 0.3310797 , 0.42121576],\n",
" [0.97948862, 0.58870474, 0.022469 ],\n",
" [0.40446888, 0.15924946, 0.39474075],\n",
" [0.39336331, 0.83113873, 0.58711273]],\n",
"\n",
" [[0.00324599, 0.84351736, 0.65574229],\n",
" [0.00423293, 0.09477659, 0.85111496],\n",
" [0.84792575, 0.32417744, 0.52031854],\n",
" [0.78577668, 0.63963473, 0.66767045],\n",
" [0.6838523 , 0.40963437, 0.296101 ]],\n",
"\n",
" [[0.25513283, 0.21434056, 0.139309 ],\n",
" [0.61281984, 0.77039643, 0.3830965 ],\n",
" [0.52747206, 0.60847264, 0.60792949],\n",
" [0.63030064, 0.5966706 , 0.05825615],\n",
" [0.78633397, 0.4404418 , 0.30296519]],\n",
"\n",
" [[0.4233433 , 0.2882031 , 0.85232675],\n",
" [0.60716483, 0.95202431, 0.39592074],\n",
" [0.55245804, 0.00922525, 0.50775513],\n",
" [0.65796373, 0.01939091, 0.10486254],\n",
" [0.06172721, 0.64735306, 0.22485494]]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 29ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-23 21:44:15.505331: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.98571175, 0.4645178 , 0.88532656],\n",
" [0.9794886 , 0.58870476, 0.7072349 ]],\n",
"\n",
" [[0.61281985, 0.84351736, 0.851115 ],\n",
" [0.8479257 , 0.6396347 , 0.6676704 ]]]], dtype=float32)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" out = [[[str(max(input[i*strides + x][j*strides + y][k] for x in range(poolSize) for y in range(poolSize)) % p) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]\n",
" return Input, out"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[['985711776216457240221750775571808256',\n",
" '464517795839652376609037137683152896',\n",
" '885326582306963556558255153072832512'],\n",
" ['979488619923621857462245439242764288',\n",
" '588704741840418336217153490575687680',\n",
" '707234940167889112717525758819434496']],\n",
" [['612819836329411865644509177766215680',\n",
" '843517362609097245279278883187720192',\n",
" '851114962252709222552843081379479552'],\n",
" ['847925751912674500468804749306626048',\n",
" '639634733901388366288661852182282240',\n",
" '667670451847854954465177838892875776']]]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, out = MaxPooling2DInt(5, 5, 3, 2, 2, X_in)\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"with open(\"maxPooling2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(10,10,3))\n",
"x = MaxPooling2D(pool_size=2, strides=3)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_1\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n",
" \n",
" max_pooling2d_1 (MaxPooling (None, 3, 3, 3) 0 \n",
" 2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.9790171 , 0.49837833, 0.23951505],\n",
" [0.85478487, 0.10183569, 0.57204256],\n",
" [0.12906496, 0.12259599, 0.61308313],\n",
" [0.68956844, 0.27468499, 0.73800473],\n",
" [0.97031435, 0.65275678, 0.57039273],\n",
" [0.48422669, 0.62184484, 0.12322611],\n",
" [0.45518299, 0.70342415, 0.77375435],\n",
" [0.1334539 , 0.78283045, 0.48137776],\n",
" [0.97002355, 0.70346344, 0.04099013],\n",
" [0.34556716, 0.30939804, 0.12870492]],\n",
"\n",
" [[0.55049916, 0.15188193, 0.514953 ],\n",
" [0.07403779, 0.906408 , 0.20947497],\n",
" [0.57003003, 0.93417836, 0.09306473],\n",
" [0.17917856, 0.67291796, 0.4088607 ],\n",
" [0.10408118, 0.55822855, 0.62854813],\n",
" [0.20925919, 0.68269696, 0.60650138],\n",
" [0.94999975, 0.12429107, 0.41003125],\n",
" [0.16150869, 0.35470003, 0.54676562],\n",
" [0.14792857, 0.78346031, 0.25734593],\n",
" [0.89233997, 0.28742825, 0.13791151]],\n",
"\n",
" [[0.79274313, 0.99061523, 0.68711779],\n",
" [0.57504418, 0.32618382, 0.16722838],\n",
" [0.09678065, 0.3591776 , 0.62750915],\n",
" [0.68795545, 0.01609884, 0.97099217],\n",
" [0.23381142, 0.84909675, 0.88405792],\n",
" [0.73191384, 0.98947014, 0.52221912],\n",
" [0.89714287, 0.03510341, 0.20639419],\n",
" [0.38323203, 0.16914071, 0.41209687],\n",
" [0.13122496, 0.53340704, 0.60455243],\n",
" [0.71565705, 0.67219914, 0.92696397]],\n",
"\n",
" [[0.55416618, 0.74973965, 0.59748271],\n",
" [0.10440772, 0.32236564, 0.92791157],\n",
" [0.41841302, 0.27220821, 0.61662229],\n",
" [0.7338952 , 0.37152599, 0.31517472],\n",
" [0.20252929, 0.67581558, 0.34286098],\n",
" [0.01504774, 0.04681701, 0.14321044],\n",
" [0.3653292 , 0.25028834, 0.33848712],\n",
" [0.29191385, 0.34659568, 0.98273622],\n",
" [0.50778695, 0.7199723 , 0.05608854],\n",
" [0.72340647, 0.76685192, 0.37388969]],\n",
"\n",
" [[0.52331559, 0.62356855, 0.26878584],\n",
" [0.15838795, 0.90184899, 0.23912789],\n",
" [0.41272637, 0.7610872 , 0.12672697],\n",
" [0.70626725, 0.98208145, 0.60164227],\n",
" [0.35664872, 0.41128872, 0.09382977],\n",
" [0.70544007, 0.82240552, 0.90325495],\n",
" [0.72007321, 0.24536308, 0.60690892],\n",
" [0.48655372, 0.46328671, 0.60648263],\n",
" [0.18854088, 0.45044603, 0.69043293],\n",
" [0.1217475 , 0.655353 , 0.87733639]],\n",
"\n",
" [[0.02353603, 0.18097275, 0.19114613],\n",
" [0.72104431, 0.65310589, 0.48925075],\n",
" [0.26145721, 0.95118427, 0.64482692],\n",
" [0.08753618, 0.2596348 , 0.53771786],\n",
" [0.07314132, 0.06774864, 0.34392025],\n",
" [0.16282229, 0.95993633, 0.79667906],\n",
" [0.74674627, 0.53217006, 0.65900082],\n",
" [0.87522692, 0.13258819, 0.16230994],\n",
" [0.44525752, 0.67365898, 0.51766928],\n",
" [0.72182701, 0.43780393, 0.98069118]],\n",
"\n",
" [[0.25691084, 0.11661927, 0.67618617],\n",
" [0.66069801, 0.9045992 , 0.86337172],\n",
" [0.08042041, 0.78517436, 0.69269604],\n",
" [0.44734739, 0.30140176, 0.18295808],\n",
" [0.07556447, 0.4891693 , 0.20302939],\n",
" [0.22243138, 0.65584446, 0.56134481],\n",
" [0.91535994, 0.429726 , 0.89466843],\n",
" [0.25180203, 0.12145168, 0.26456649],\n",
" [0.56398398, 0.18346371, 0.034341 ],\n",
" [0.37802503, 0.22614985, 0.85292929]],\n",
"\n",
" [[0.19171201, 0.46156136, 0.78027617],\n",
" [0.1697258 , 0.36865057, 0.30921552],\n",
" [0.63491691, 0.76223827, 0.91491496],\n",
" [0.68871028, 0.86998105, 0.79183476],\n",
" [0.50452778, 0.27036477, 0.19829515],\n",
" [0.82527008, 0.35258264, 0.42346427],\n",
" [0.73552096, 0.76506646, 0.50324396],\n",
" [0.08392757, 0.11886597, 0.31341576],\n",
" [0.42816313, 0.8535268 , 0.59585608],\n",
" [0.00429868, 0.66229572, 0.07715835]],\n",
"\n",
" [[0.95901268, 0.85618315, 0.47768876],\n",
" [0.66614175, 0.08345771, 0.80790147],\n",
" [0.29208239, 0.4360204 , 0.18332789],\n",
" [0.28169483, 0.63096452, 0.96729756],\n",
" [0.07859661, 0.92728092, 0.80810303],\n",
" [0.97020859, 0.87780948, 0.83993202],\n",
" [0.68006058, 0.68787335, 0.70198168],\n",
" [0.31865081, 0.97290491, 0.13625889],\n",
" [0.80537841, 0.03953296, 0.16870381],\n",
" [0.90864186, 0.54762421, 0.71436361]],\n",
"\n",
" [[0.19054836, 0.34380661, 0.68153459],\n",
" [0.16505021, 0.0412163 , 0.36928843],\n",
" [0.38454084, 0.30131942, 0.29021317],\n",
" [0.74076099, 0.97099106, 0.30053946],\n",
" [0.62869618, 0.12455381, 0.62562719],\n",
" [0.91303674, 0.39900546, 0.92873058],\n",
" [0.7949276 , 0.00620029, 0.17023317],\n",
" [0.40570501, 0.1780136 , 0.19150324],\n",
" [0.56676977, 0.84413934, 0.73247166],\n",
" [0.0028076 , 0.26181396, 0.70691029]]]])"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,10,10,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 21ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.9790171 , 0.906408 , 0.5720426 ],\n",
" [0.9703143 , 0.67291796, 0.73800474],\n",
" [0.94999975, 0.7828305 , 0.77375436]],\n",
"\n",
" [[0.5541662 , 0.901849 , 0.9279116 ],\n",
" [0.7338952 , 0.9820815 , 0.60164225],\n",
" [0.7200732 , 0.46328673, 0.98273623]],\n",
"\n",
" [[0.660698 , 0.9045992 , 0.86337173],\n",
" [0.6887103 , 0.86998105, 0.7918348 ],\n",
" [0.9153599 , 0.76506644, 0.89466846]]]], dtype=float32)"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[['979017099491110018942067312821272576',\n",
" '906408000806632452114797174150135808',\n",
" '572042560577051270101001688850628608'],\n",
" ['970314350513558277989324779994218496',\n",
" '672917960272193945175567190387064832',\n",
" '738004729474624730341896972922781696'],\n",
" ['949999745668024165489517038806237184',\n",
" '782830451141896167400921576545189888',\n",
" '773754352982266439136539456512720896']],\n",
" [['554166181126147404440246990770536448',\n",
" '901848991352918850169033731149398016',\n",
" '927911571088135929200009259356520448'],\n",
" ['733895199634136636354978553303924736',\n",
" '982081449688638090663868389740511232',\n",
" '601642265832659125360941789945528320'],\n",
" ['720073208604618054954869080641765376',\n",
" '463286712794445136678401315688153088',\n",
" '982736221843810664156369288039497728']],\n",
" [['660698008644203700473074429819092992',\n",
" '904599195577579897660922571020828672',\n",
" '863371715944324158495051960144625664'],\n",
" ['688710284469165685404738243641999360',\n",
" '869981053223066390571414093008207872',\n",
" '791834758925232104719097862035603456'],\n",
" ['915359938539886757509738228069957632',\n",
" '765066456516048413755703502695301120',\n",
" '894668431976368139307673421153828864']]]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, out = MaxPooling2DInt(10, 10, 3, 2, 3, X_in)\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"with open(\"maxPooling2D_stride_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/maxPooling2d_same.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, MaxPooling2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = MaxPooling2D(pool_size=2, padding='same')(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
" \n",
" max_pooling2d (MaxPooling2D (None, 3, 3, 3) 0 \n",
" ) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.9854169 , 0.80569586, 0.63268445],\n",
" [0.96206047, 0.00886907, 0.67775967],\n",
" [0.46792544, 0.81360698, 0.34777212],\n",
" [0.90835439, 0.69174656, 0.98172619],\n",
" [0.10715328, 0.91657229, 0.81624555]],\n",
"\n",
" [[0.57038264, 0.90280394, 0.77766336],\n",
" [0.63409067, 0.82595812, 0.38151341],\n",
" [0.79552045, 0.2163596 , 0.87461672],\n",
" [0.74681147, 0.47584101, 0.93002867],\n",
" [0.11400012, 0.97409111, 0.87404365]],\n",
"\n",
" [[0.53957961, 0.50863284, 0.89012595],\n",
" [0.27801669, 0.55281537, 0.50004972],\n",
" [0.31374426, 0.41849849, 0.81763357],\n",
" [0.68099263, 0.21715725, 0.60245081],\n",
" [0.23044868, 0.89402184, 0.73802917]],\n",
"\n",
" [[0.65681518, 0.45431134, 0.11186951],\n",
" [0.63232732, 0.09914006, 0.469778 ],\n",
" [0.53980327, 0.00999922, 0.32385368],\n",
" [0.51189833, 0.23540886, 0.48827071],\n",
" [0.97347711, 0.16329774, 0.73404494]],\n",
"\n",
" [[0.02010803, 0.73200388, 0.75296659],\n",
" [0.47080583, 0.89997758, 0.77754373],\n",
" [0.45047643, 0.60846601, 0.22025449],\n",
" [0.81318524, 0.86405236, 0.44136216],\n",
" [0.53790431, 0.45931736, 0.00951743]]]])"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 42ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2024-02-05 01:27:05.945781: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.9854169 , 0.90280396, 0.77766335],\n",
" [0.9083544 , 0.813607 , 0.98172617],\n",
" [0.11400012, 0.9740911 , 0.87404364]],\n",
"\n",
" [[0.6568152 , 0.5528154 , 0.89012593],\n",
" [0.6809926 , 0.4184985 , 0.81763357],\n",
" [0.9734771 , 0.89402187, 0.7380292 ]],\n",
"\n",
" [[0.47080582, 0.89997756, 0.7775437 ],\n",
" [0.8131852 , 0.86405236, 0.44136214],\n",
" [0.5379043 , 0.45931736, 0.00951743]]]], dtype=float32)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\n",
" out = [[[str(max(int(input[i*strides + x][j*strides + y][k]) for x in range(poolSize) for y in range(poolSize))) for k in range(nChannels)] for j in range((nCols - poolSize) // strides + 1)] for i in range((nRows - poolSize) // strides + 1)]\n",
" return out"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def MaxPooling2DsameInt(nRows, nCols, nChannels, poolSize, strides, input):\n",
" if nRows % strides == 0:\n",
" rowPadding = max(poolSize - strides, 0)\n",
" else:\n",
" rowPadding = max(poolSize - nRows % strides, 0)\n",
" if nCols % strides == 0:\n",
" colPadding = max(poolSize - strides, 0)\n",
" else:\n",
" colPadding = max(poolSize - nCols % strides, 0)\n",
" \n",
" _input = [[[0 for _ in range(nChannels)] for _ in range(nCols + colPadding)] for _ in range(nRows + rowPadding)]\n",
"\n",
" for i in range(nRows):\n",
" for j in range(nCols):\n",
" for k in range(nChannels):\n",
" _input[i+rowPadding//2][j+colPadding//2][k] = input[i][j][k]\n",
" \n",
" out = MaxPooling2DInt(nRows + rowPadding, nCols + colPadding, nChannels, poolSize, strides, _input)\n",
" return out"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[['985416895178787714183661703755988992',\n",
" '902803940435826284139749932730941440',\n",
" '777663362123877860598598645145665536'],\n",
" ['908354388868282470618698257109352448',\n",
" '813606982115283460844798537969434624',\n",
" '981726193592448973649175667344932864'],\n",
" ['114000116831430861403008392105033728',\n",
" '974091109200621567612816335791194112',\n",
" '874043654050301690820171495435665408']],\n",
" [['656815180323522869339469446928924672',\n",
" '552815374291668108366329210074038272',\n",
" '890125946940297760199841005954924544'],\n",
" ['680992631793690390926240128859897856',\n",
" '418498494396639822766365224919367680',\n",
" '817633569064628434285947918592507904'],\n",
" ['973477114549060379932212627888930816',\n",
" '894021844181003495121759207996522496',\n",
" '738029169437394307130485433159385088']],\n",
" [['470805829710577633964522992960536576',\n",
" '899977578211573860664606514781093888',\n",
" '777543729617406477245147183797239808'],\n",
" ['813185240376988213714402965620523008',\n",
" '864052363876363850452980196205133824',\n",
" '441362157036501413461183215236546560'],\n",
" ['537904308558723633624141672348647424',\n",
" '459317359421049476909261905824055296',\n",
" '9517425402804758462154346481057792']]]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out = MaxPooling2DsameInt(5, 5, 3, 2, 2, X_in)\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"with open(\"maxPooling2Dsame_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(10,10,3))\n",
"x = MaxPooling2D(pool_size=2, strides=3, padding='same')(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_1\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n",
" \n",
" max_pooling2d_1 (MaxPooling (None, 4, 4, 3) 0 \n",
" 2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[1.81060846e-01, 8.73335066e-01, 4.66591631e-01],\n",
" [4.19512826e-01, 5.04687534e-01, 5.55108518e-01],\n",
" [8.89727395e-01, 3.04715421e-01, 3.96868333e-01],\n",
" [3.19583099e-01, 7.59947198e-04, 8.95376898e-01],\n",
" [1.86082695e-01, 5.89361183e-01, 2.29939007e-01],\n",
" [3.77869457e-01, 5.93831349e-01, 6.17898741e-01],\n",
" [2.08890055e-01, 4.52999632e-02, 4.81015031e-02],\n",
" [9.68292068e-01, 4.24571806e-01, 4.18124731e-02],\n",
" [3.30703359e-02, 6.13358807e-01, 9.62525235e-01],\n",
" [8.80909151e-01, 3.16377883e-02, 4.07229564e-01]],\n",
"\n",
" [[7.22047037e-01, 2.87769873e-01, 6.33057960e-01],\n",
" [5.87593115e-01, 9.95928671e-01, 9.47646805e-02],\n",
" [6.73764008e-01, 4.41940517e-01, 2.05872675e-01],\n",
" [2.74105248e-01, 3.41288944e-01, 7.03928155e-01],\n",
" [2.53407876e-01, 9.54086619e-01, 6.95949832e-01],\n",
" [7.72974380e-01, 6.94646688e-01, 2.39040667e-01],\n",
" [7.61119704e-01, 8.41368944e-01, 9.12971104e-01],\n",
" [3.19331761e-01, 2.36474093e-01, 3.11432211e-01],\n",
" [6.18384476e-01, 2.23794997e-01, 7.33884991e-01],\n",
" [1.00735392e-01, 7.42390580e-01, 7.43563278e-01]],\n",
"\n",
" [[1.82788443e-01, 9.69266407e-01, 6.79896409e-02],\n",
" [5.47375743e-01, 7.00178164e-01, 1.62010347e-02],\n",
" [2.70368172e-01, 9.53685968e-01, 4.62933777e-01],\n",
" [4.80574859e-01, 1.55085614e-01, 2.38047469e-01],\n",
" [4.86919140e-01, 1.94033355e-02, 1.80402947e-01],\n",
" [3.96449294e-01, 4.95605585e-01, 2.26605072e-01],\n",
" [1.74141020e-02, 3.46487475e-03, 8.98099350e-01],\n",
" [7.85190855e-01, 3.05525061e-01, 2.04565391e-01],\n",
" [8.23700964e-01, 2.97490709e-01, 6.50482927e-02],\n",
" [1.26448774e-01, 8.10615035e-01, 5.09045959e-01]],\n",
"\n",
" [[7.13680159e-01, 8.45319480e-01, 9.11203285e-01],\n",
" [8.27233800e-01, 4.12657299e-01, 6.97025851e-01],\n",
" [2.81018305e-01, 6.48955744e-01, 8.91153606e-01],\n",
" [6.29371477e-01, 7.75929101e-01, 7.79093686e-01],\n",
" [1.23716197e-01, 3.10122093e-01, 8.37055316e-01],\n",
" [1.68089475e-01, 9.54284278e-01, 3.18407200e-01],\n",
" [3.62606007e-01, 7.78830849e-01, 3.99089020e-01],\n",
" [8.51653764e-02, 5.34511941e-01, 6.04920400e-01],\n",
" [2.71115350e-01, 4.36692189e-01, 6.96241628e-01],\n",
" [8.65780466e-01, 3.22369175e-01, 7.43159548e-01]],\n",
"\n",
" [[9.28690706e-02, 3.94089568e-01, 5.61323421e-01],\n",
" [5.90368083e-01, 9.74901900e-01, 9.47030261e-01],\n",
" [6.30178577e-01, 5.13484751e-01, 1.18185924e-01],\n",
" [4.38458544e-01, 5.63764554e-01, 7.66318218e-01],\n",
" [7.18648243e-01, 1.70367043e-01, 7.70642982e-01],\n",
" [2.22980409e-01, 3.74329609e-01, 4.80409175e-01],\n",
" [9.45617766e-01, 8.81617847e-01, 1.19580346e-01],\n",
" [9.15676461e-01, 9.70518691e-01, 2.43214092e-01],\n",
" [2.41451379e-01, 4.88548632e-01, 3.70190637e-01],\n",
" [4.59905504e-01, 3.80889550e-01, 3.85698952e-01]],\n",
"\n",
" [[2.72104416e-01, 7.98516947e-01, 2.72194053e-01],\n",
" [9.48709871e-01, 2.66222380e-01, 9.42522429e-01],\n",
" [7.33569990e-01, 3.47061477e-01, 5.33050356e-01],\n",
" [6.11738759e-01, 8.68186611e-02, 3.75463635e-01],\n",
" [2.14948078e-01, 3.99863394e-01, 1.90922352e-01],\n",
" [5.10853285e-01, 8.50874635e-01, 3.81366847e-01],\n",
" [8.39025985e-01, 6.98107126e-01, 8.44114497e-01],\n",
" [6.99026648e-01, 6.91391860e-01, 5.95508900e-01],\n",
" [3.75264962e-01, 2.19625912e-02, 9.65963233e-01],\n",
" [8.73625070e-01, 1.70130110e-02, 4.28592791e-01]],\n",
"\n",
" [[5.30376524e-01, 5.19931919e-01, 8.79621802e-01],\n",
" [5.93691399e-01, 9.43767391e-01, 3.85923387e-01],\n",
" [2.66910663e-02, 9.36911794e-01, 1.02611787e-01],\n",
" [3.59377042e-01, 2.67568222e-01, 5.35446422e-01],\n",
" [5.51850227e-01, 6.35787754e-01, 1.98619411e-01],\n",
" [8.49409850e-01, 6.72271595e-01, 2.39559395e-01],\n",
" [1.73809713e-02, 6.90213328e-01, 4.68996474e-01],\n",
" [2.98860826e-01, 9.70887693e-02, 7.59385182e-01],\n",
" [2.57726817e-01, 9.57823991e-01, 7.18212290e-01],\n",
" [7.01041664e-01, 7.78681302e-01, 2.83077120e-01]],\n",
"\n",
" [[7.26341251e-01, 9.88746010e-02, 8.11023617e-01],\n",
" [5.17637504e-01, 1.22369589e-01, 6.26059218e-01],\n",
" [8.89381042e-01, 4.69513890e-01, 4.41358856e-01],\n",
" [1.31543858e-01, 2.52923839e-02, 4.59211802e-01],\n",
" [2.97316029e-01, 3.74157507e-01, 1.46629093e-01],\n",
" [5.42787121e-01, 4.83436833e-01, 6.48266145e-01],\n",
" [5.87451856e-01, 6.62348938e-01, 9.09155419e-01],\n",
" [4.19004871e-01, 1.82945864e-02, 6.63249102e-01],\n",
" [2.32421673e-01, 6.30460531e-01, 6.90273718e-02],\n",
" [1.00823603e-01, 6.38197200e-01, 1.54316174e-01]],\n",
"\n",
" [[3.95104675e-01, 9.54576105e-01, 7.18833793e-01],\n",
" [6.55325673e-01, 2.09750597e-01, 5.08179296e-01],\n",
" [8.35434924e-01, 3.11732329e-01, 2.53760179e-01],\n",
" [6.01300571e-01, 1.74387890e-01, 1.28901152e-01],\n",
" [3.60114137e-01, 6.03481824e-01, 6.42517616e-01],\n",
" [4.74822395e-01, 4.06953697e-02, 8.06656676e-01],\n",
" [2.35227783e-01, 1.86636675e-01, 2.92355800e-01],\n",
" [7.57334531e-01, 3.02550198e-01, 8.78392401e-01],\n",
" [9.89429375e-01, 9.17356225e-01, 9.94972892e-01],\n",
" [3.38833764e-01, 2.39923972e-01, 2.49753676e-02]],\n",
"\n",
" [[5.34504729e-02, 2.60437560e-01, 4.75257720e-01],\n",
" [5.10602046e-01, 7.24407672e-01, 1.27708925e-01],\n",
" [8.89866378e-01, 7.68391514e-01, 8.10330840e-01],\n",
" [9.04964699e-01, 9.07169014e-01, 3.30947299e-01],\n",
" [3.25628891e-01, 3.62460672e-01, 6.09180261e-01],\n",
" [3.97278800e-01, 2.87846815e-01, 9.51001737e-01],\n",
" [3.94260450e-01, 3.00806280e-01, 8.51360452e-01],\n",
" [3.62097670e-01, 2.24539340e-01, 7.61618704e-01],\n",
" [2.50380406e-01, 7.56360963e-01, 1.16230049e-01],\n",
" [9.01240322e-01, 3.73212987e-01, 7.36122529e-01]]]])"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,10,10,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 30ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.72204703, 0.99592865, 0.63305795],\n",
" [0.3195831 , 0.9540866 , 0.8953769 ],\n",
" [0.96829206, 0.841369 , 0.9129711 ],\n",
" [0.88090914, 0.7423906 , 0.7435633 ]],\n",
"\n",
" [[0.8272338 , 0.9749019 , 0.94703025],\n",
" [0.71864825, 0.7759291 , 0.8370553 ],\n",
" [0.9456178 , 0.9705187 , 0.6049204 ],\n",
" [0.8657805 , 0.38088953, 0.74315953]],\n",
"\n",
" [[0.72634125, 0.94376737, 0.8796218 ],\n",
" [0.5518502 , 0.6357877 , 0.5354464 ],\n",
" [0.5874519 , 0.6902133 , 0.9091554 ],\n",
" [0.70104164, 0.7786813 , 0.28307712]],\n",
"\n",
" [[0.51060206, 0.7244077 , 0.47525772],\n",
" [0.9049647 , 0.90716904, 0.6091803 ],\n",
" [0.39426044, 0.30080628, 0.85136044],\n",
" [0.90124035, 0.373213 , 0.73612255]]]], dtype=float32)"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[['722047037048510692294577429613117440',\n",
" '995928671466629356695108803213918208',\n",
" '633057959701190742109452742097371136'],\n",
" ['319583098696415993297833594590330880',\n",
" '954086618948581700566160227891675136',\n",
" '895376897621437771937017335681908736'],\n",
" ['968292067860118608616536728156504064',\n",
" '841368944375512546814487235963912192',\n",
" '912971104374087013640201200717529088'],\n",
" ['880909150990983977881328708709515264',\n",
" '742390579543848987849194909946871808',\n",
" '743563277676321729157199064014520320']],\n",
" [['827233800468269198331599375468331008',\n",
" '974901899794306633179826070214410240',\n",
" '947030261209948995604238219295588352'],\n",
" ['718648242610498931670595372570378240',\n",
" '775929100688812511565570103251566592',\n",
" '837055315861977089490188905893330944'],\n",
" ['945617766167062485510007332488085504',\n",
" '970518691217475177799962810208223232',\n",
" '604920400036749440823474048758448128'],\n",
" ['865780466166194901147341462043623424',\n",
" '380889549714929988856634904844173312',\n",
" '743159547886228828110355377787240448']],\n",
" [['726341250795347218817727679288049664',\n",
" '943767390679553173919884888860786688',\n",
" '879621802069332614144323070292131840'],\n",
" ['551850226842807715717985301323317248',\n",
" '635787754066812906470475510293987328',\n",
" '535446422069610157460354392595103744'],\n",
" ['587451855996849487170757966572814336',\n",
" '690213328307762114218988812757893120',\n",
" '909155419360394098803395006243536896'],\n",
" ['701041664244132545037467114551640064',\n",
" '778681301680931345113753214299144192',\n",
" '283077119909484707357592139667079168']],\n",
" [['510602045587970767184337129422454784',\n",
" '724407671943644015539146665914007552',\n",
" '475257720371555822213696431964815360'],\n",
" ['904964699224751401721193296243458048',\n",
" '907169014433129231084536890038157312',\n",
" '609180260647294075284256963443032064'],\n",
" ['394260450257245198773068562662686720',\n",
" '300806280328724832256760381278519296',\n",
" '851360451534335061119480218741899264'],\n",
" ['901240322382283207026350889182953472',\n",
" '373212986501062202469532290256994304',\n",
" '736122528767077629789884872958935040']]]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out = MaxPooling2DsameInt(10, 10, 3, 2, 3, X_in)\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"with open(\"maxPooling2Dsame_stride_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/mnist.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Conv2D, AveragePooling2D, Flatten, Softmax, Dense, Lambda, BatchNormalization, ReLU\n",
"from tensorflow.keras import Model\n",
"from tensorflow.keras.datasets import mnist\n",
"from tensorflow.keras.utils import to_categorical\n",
"from tensorflow.keras.optimizers.legacy import SGD\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import tensorflow as tf"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"(X_train, y_train), (X_test, y_test) = mnist.load_data()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# Convert y_train into one-hot format\n",
"temp = []\n",
"for i in range(len(y_train)):\n",
" temp.append(to_categorical(y_train[i], num_classes=10))\n",
"y_train = np.array(temp)\n",
"# Convert y_test into one-hot format\n",
"temp = []\n",
"for i in range(len(y_test)): \n",
" temp.append(to_categorical(y_test[i], num_classes=10))\n",
"y_test = np.array(temp)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"#reshaping\n",
"X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\n",
"X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n",
"\n",
"#normalizing\n",
"X_train = X_train.astype('float32')\n",
"X_test = X_test.astype('float32')\n",
"X_train /= 255.0\n",
"X_test /= 255.0"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(28,28,1))\n",
"out = Conv2D(4, 3, use_bias=True)(inputs)\n",
"out = BatchNormalization()(out)\n",
"out = ReLU()(out)\n",
"out = AveragePooling2D()(out)\n",
"out = Conv2D(8, 3, use_bias=True)(out)\n",
"out = BatchNormalization()(out)\n",
"out = ReLU()(out)\n",
"out = AveragePooling2D()(out)\n",
"out = Flatten()(out)\n",
"out = Dense(10, activation=None)(out)\n",
"out = Softmax()(out)\n",
"model = Model(inputs, out)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 28, 28, 1)] 0 \n",
" \n",
" conv2d (Conv2D) (None, 26, 26, 4) 40 \n",
" \n",
" batch_normalization (BatchN (None, 26, 26, 4) 16 \n",
" ormalization) \n",
" \n",
" re_lu (ReLU) (None, 26, 26, 4) 0 \n",
" \n",
" average_pooling2d (AverageP (None, 13, 13, 4) 0 \n",
" ooling2D) \n",
" \n",
" conv2d_1 (Conv2D) (None, 11, 11, 8) 296 \n",
" \n",
" batch_normalization_1 (Batc (None, 11, 11, 8) 32 \n",
" hNormalization) \n",
" \n",
" re_lu_1 (ReLU) (None, 11, 11, 8) 0 \n",
" \n",
" average_pooling2d_1 (Averag (None, 5, 5, 8) 0 \n",
" ePooling2D) \n",
" \n",
" flatten (Flatten) (None, 200) 0 \n",
" \n",
" dense (Dense) (None, 10) 2010 \n",
" \n",
" softmax (Softmax) (None, 10) 0 \n",
" \n",
"=================================================================\n",
"Total params: 2,394\n",
"Trainable params: 2,370\n",
"Non-trainable params: 24\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"model.compile(\n",
" loss='categorical_crossentropy',\n",
" optimizer=SGD(learning_rate=0.01, momentum=0.9),\n",
" metrics=['acc']\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/15\n",
" 1/1875 [..............................] - ETA: 5:16 - loss: 2.6515 - acc: 0.0625"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-24 02:23:16.557845: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.1896 - acc: 0.9434 - val_loss: 0.0808 - val_acc: 0.9753\n",
"Epoch 2/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0787 - acc: 0.9761 - val_loss: 0.0602 - val_acc: 0.9808\n",
"Epoch 3/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0650 - acc: 0.9803 - val_loss: 0.0546 - val_acc: 0.9831\n",
"Epoch 4/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0592 - acc: 0.9816 - val_loss: 0.0613 - val_acc: 0.9812\n",
"Epoch 5/15\n",
"1875/1875 [==============================] - 7s 4ms/step - loss: 0.0536 - acc: 0.9837 - val_loss: 0.0594 - val_acc: 0.9808\n",
"Epoch 6/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0497 - acc: 0.9847 - val_loss: 0.0618 - val_acc: 0.9794\n",
"Epoch 7/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0470 - acc: 0.9855 - val_loss: 0.0824 - val_acc: 0.9748\n",
"Epoch 8/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0451 - acc: 0.9863 - val_loss: 0.0410 - val_acc: 0.9843\n",
"Epoch 9/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0433 - acc: 0.9865 - val_loss: 0.0561 - val_acc: 0.9822\n",
"Epoch 10/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0425 - acc: 0.9871 - val_loss: 0.0455 - val_acc: 0.9847\n",
"Epoch 11/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0397 - acc: 0.9875 - val_loss: 0.0524 - val_acc: 0.9825\n",
"Epoch 12/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0391 - acc: 0.9879 - val_loss: 0.0382 - val_acc: 0.9875\n",
"Epoch 13/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0381 - acc: 0.9879 - val_loss: 0.0371 - val_acc: 0.9868\n",
"Epoch 14/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0360 - acc: 0.9887 - val_loss: 0.0371 - val_acc: 0.9870\n",
"Epoch 15/15\n",
"1875/1875 [==============================] - 8s 4ms/step - loss: 0.0354 - acc: 0.9887 - val_loss: 0.0378 - val_acc: 0.9874\n"
]
},
{
"data": {
"text/plain": [
"<keras.callbacks.History at 0x143103e80>"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test))"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((28, 28, 1), 0.0, 1.0)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = X_test[0]\n",
"X.shape, X.min(), X.max()"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 45ms/step\n"
]
},
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.predict(X.reshape(1,28,28,1)).argmax()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" Weights = [[[[str(weights[i][j][k][l] % p) for l in range(nFilters)] for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\n",
" Bias = [str(bias[i] % p) for i in range(nFilters)]\n",
" out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n",
" remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize)//strides + 1)] for _ in range((nRows - kernelSize)//strides + 1)]\n",
" for i in range((nRows - kernelSize)//strides + 1):\n",
" for j in range((nCols - kernelSize)//strides + 1):\n",
" for m in range(nFilters):\n",
" for k in range(nChannels):\n",
" for x in range(kernelSize):\n",
" for y in range(kernelSize):\n",
" out[i][j][m] += input[i*strides+x][j*strides+y][k] * weights[x][y][k][m]\n",
" out[i][j][m] += bias[m]\n",
" remainder[i][j][m] = str(out[i][j][m] % n)\n",
" out[i][j][m] = str(out[i][j][m] // n % p)\n",
" return Input, Weights, Bias, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[i][j][0]*1e18)] for j in range(28)] for i in range(28)]\n",
"conv2d_1_weights = [[[[int(model.layers[1].weights[0][i][j][k][l]*1e18) for l in range(4)] for k in range(1)] for j in range(3)] for i in range(3)]\n",
"conv2d_1_bias = [int(model.layers[1].weights[1][i]*1e36) for i in range(4)]"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['21888242871839275222246405745257275088548364400416034343698204178650554445275',\n",
" '21888242871839275222246405745257275088548364400416034343698203817637026120037',\n",
" '21888242871839275222246405745257275088548364400416034343698204118313744391231',\n",
" '48458611567652']"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, conv2d_1_weights, conv2d_1_bias, conv2d_1_out, conv2d_1_remainder = Conv2DInt(28, 28, 1, 4, 3, 1, 10**18, X_in, conv2d_1_weights, conv2d_1_bias)\n",
"conv2d_1_out[0][0]"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 18ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([-7.9252541e-06, -3.6893881e-04, -6.8262067e-05, 4.8458613e-05],\n",
" dtype=float32)"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conv2d_model = Model(inputs, model.layers[1].output)\n",
"conv2d_model.predict(X.reshape(1,28,28,1))[0][0][0]"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"gamma = model.layers[2].weights[0].numpy()\n",
"beta = model.layers[2].weights[1].numpy()\n",
"moving_mean = model.layers[2].weights[2].numpy()\n",
"moving_var = model.layers[2].weights[3].numpy()\n",
"epsilon = model.layers[2].epsilon"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(array([2.841136 , 2.7350745, 2.0774858, 1.246628 ], dtype=float32),\n",
" array([ 0.9730277 , -0.0507403 , -0.07507665, -0.5589396 ], dtype=float32))"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a1 = gamma/(moving_var+epsilon)**.5\n",
"b1 = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n",
"a1, b1"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"def BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\n",
" X = [[[str(X_in[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" A = [str(a_in[k] % p) for k in range(nChannels)]\n",
" B = [str(b_in[k] % p) for k in range(nChannels)]\n",
" out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n",
" remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n",
" for i in range(nRows):\n",
" for j in range(nCols):\n",
" for k in range(nChannels):\n",
" out[i][j][k] = (X_in[i][j][k]*a_in[k] + b_in[k])\n",
" remainder[i][j][k] = str(out[i][j][k] % n)\n",
" out[i][j][k] = str(out[i][j][k] // n % p)\n",
" return X, A, B, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"bn_1_in = [[[int(conv2d_1_out[i][j][k]) if int(conv2d_1_out[i][j][k]) < p//2 else int(conv2d_1_out[i][j][k]) - p for k in range(4)] for j in range(26)] for i in range(26)]\n",
"bn_1_a = [int(a1[i]*1e18) for i in range(4)]\n",
"bn_1_b = [int(b1[i]*1e36) for i in range(4)]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['973005189421817592',\n",
" '21888242871839275222246405745257275088548364400416034343698152437199136300055',\n",
" '21888242871839275222246405745257275088548364400416034343698128968107786241045',\n",
" '21888242871839275222246405745257275088548364400416034343697645307409523760974']"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, bn_1_a, bn_1_b, bn_1_out, bn_1_remainder = BatchNormalizationInt(26, 26, 4, 10**18, bn_1_in, bn_1_a, bn_1_b)\n",
"bn_1_out[0][0]"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 22ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([ 0.97300524, -0.05174941, -0.07521845, -0.55887914], dtype=float32)"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bn_1_model = Model(inputs, model.layers[2].output)\n",
"bn_1_model.predict(X.reshape(1,28,28,1))[0][0][0]"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"relu_1_in = [[[int(bn_1_out[i][j][k]) for k in range(4)] for j in range(26)] for i in range(26)]\n",
"relu_1_out = [[[str(relu_1_in[i][j][k]) if relu_1_in[i][j][k] < p//2 else 0 for k in range(4)] for j in range(26)] for i in range(26)]"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"avg2d_1_in = [[[int(relu_1_out[i][j][k]) for k in range(4)] for j in range(26)] for i in range(26)]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"def AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\n",
" Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
" out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n",
" remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize)//strides + 1)] for _ in range((nRows-poolSize)//strides + 1)]\n",
" for i in range((nRows-poolSize)//strides + 1):\n",
" for j in range((nCols-poolSize)//strides + 1):\n",
" for k in range(nChannels):\n",
" for x in range(poolSize):\n",
" for y in range(poolSize):\n",
" out[i][j][k] += input[i*strides+x][j*strides+y][k]\n",
" remainder[i][j][k] = str(out[i][j][k] % poolSize**2 % p)\n",
" out[i][j][k] = str(out[i][j][k] // poolSize**2 % p)\n",
" return Input, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['1312195747641412224', '17351024717876988', '381448215010339593', '0']"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, avg2d_1_out, avg2d_1_remainder = AveragePooling2DInt(26, 26, 4, 2, 2, avg2d_1_in)\n",
"avg2d_1_out[5][6]"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 28ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([1.3121958 , 0.01735102, 0.38144833, 0. ], dtype=float32)"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"avg2d_1_model = Model(inputs, model.layers[4].output)\n",
"avg2d_1_model.predict(X.reshape(1,28,28,1))[0][5][6]"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"conv2d_2_in = [[[int(avg2d_1_out[i][j][k]) for k in range(4)] for j in range(13)] for i in range(13)]\n",
"conv2d_2_weights = [[[[int(model.layers[5].weights[0][i][j][k][l]*1e18) for l in range(8)] for k in range(4)] for j in range(3)] for i in range(3)]\n",
"conv2d_2_bias = [int(model.layers[5].weights[1][i]*1e36) for i in range(8)]"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['151443532606342120',\n",
" '21888242871839275222246405745257275088548364400416034343695445103896159586204',\n",
" '1368543458414900467',\n",
" '21888242871839275222246405745257275088548364400416034343697889320797389307844',\n",
" '21888242871839275222246405745257275088548364400416034343696909822999783625702',\n",
" '3064925807006993607',\n",
" '273553711551724155',\n",
" '21888242871839275222246405745257275088548364400416034343697690313879935243528']"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, conv2d_2_weights, conv2d_2_bias, conv2d_2_out, conv2d_2_remainder = Conv2DInt(13, 13, 4, 8, 3, 1, 10**18, conv2d_2_in, conv2d_2_weights, conv2d_2_bias)\n",
"conv2d_2_out[0][0]"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x147387d30> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n",
"1/1 [==============================] - 0s 27ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([ 0.15144362, -2.7590828 , 1.3685436 , -0.3148657 , -1.2943636 ,\n",
" 3.064926 , 0.27355385, -0.5138727 ], dtype=float32)"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conv2d_2_model = Model(inputs, model.layers[5].output)\n",
"conv2d_2_model.predict(X.reshape(1,28,28,1))[0][0][0]"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"gamma = model.layers[6].weights[0].numpy()\n",
"beta = model.layers[6].weights[1].numpy()\n",
"moving_mean = model.layers[6].weights[2].numpy()\n",
"moving_var = model.layers[6].weights[3].numpy()\n",
"epsilon = model.layers[6].epsilon"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(array([1.4172864, 1.0896717, 1.2455306, 1.9744203, 1.5216775, 1.6048892,\n",
" 1.5560555, 1.5188278], dtype=float32),\n",
" array([ 0.9693597 , 2.5460322 , -2.3216164 , 1.1771976 , 1.7650728 ,\n",
" -5.5845942 , -0.36191303, 0.58835894], dtype=float32))"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a2 = gamma/(moving_var+epsilon)**.5\n",
"b2 = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n",
"a2, b2"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"bn_2_in = [[[int(conv2d_2_out[i][j][k]) if int(conv2d_2_out[i][j][k]) < p//2 else int(conv2d_2_out[i][j][k]) - p for k in range(8)] for j in range(11)] for i in range(11)]\n",
"bn_2_a = [int(a2[i]*1e18) for i in range(8)]\n",
"bn_2_b = [int(b2[i]*1e36) for i in range(8)]"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['1183998554440588778',\n",
" '21888242871839275222246405745257275088548364400416034343697743724366639529790',\n",
" '21888242871839275222246405745257275088548364400416034343697587132926760373824',\n",
" '555520188028190246',\n",
" '21888242871839275222246405745257275088548364400416034343697999655475625376512',\n",
" '21888242871839275222246405745257275088548364400416034343697538458512894177905',\n",
" '63751744556936369',\n",
" '21888242871839275222246405745257275088548364400416034343698012061380413810399']"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, bn_2_a, bn_2_b, bn_2_out, bn_2_remainder = BatchNormalizationInt(11, 11, 8, 10**18, bn_2_in, bn_2_a, bn_2_b)\n",
"bn_2_out[0][0]"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_predict_function.<locals>.predict_function at 0x1475103a0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n",
"1/1 [==============================] - 0s 32ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([ 1.1839986 , -0.46046233, -0.61705345, 0.5555204 , -0.20453101,\n",
" -0.66572803, 0.06375193, -0.1921252 ], dtype=float32)"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bn_2_model = Model(inputs, model.layers[6].output)\n",
"bn_2_model.predict(X.reshape(1,28,28,1))[0][0][0]"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['1183998554440588778',\n",
" 0,\n",
" 0,\n",
" '555520188028190246',\n",
" 0,\n",
" 0,\n",
" '63751744556936369',\n",
" 0]"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"relu_2_in = [[[int(bn_2_out[i][j][k]) for k in range(8)] for j in range(11)] for i in range(11)]\n",
"relu_2_out = [[[str(relu_2_in[i][j][k]) if relu_2_in[i][j][k] < p//2 else 0 for k in range(8)] for j in range(11)] for i in range(11)]\n",
"relu_2_out[0][0]"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 30ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([1.1839986 , 0. , 0. , 0.5555204 , 0. ,\n",
" 0. , 0.06375193, 0. ], dtype=float32)"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"relu_2_model = Model(inputs, model.layers[7].output)\n",
"relu_2_model.predict(X.reshape(1,28,28,1))[0][0][0]"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"avg2d_2_in = [[[int(relu_2_out[i][j][k]) if int(relu_2_out[i][j][k]) < p//2 else int(relu_2_out[i][j][k]) - p for k in range(8)] for j in range(11)] for i in range(11)]"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['0',\n",
" '3041275199357812815',\n",
" '880404200542187368',\n",
" '751626574290071696',\n",
" '4631629684299696339',\n",
" '0',\n",
" '0',\n",
" '141002623674408652']"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, avg2d_2_out, avg2d_2_remainder = AveragePooling2DInt(11, 11, 8, 2, 2, avg2d_2_in)\n",
"avg2d_2_out[3][3]"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 30ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([0. , 3.0412755 , 0.88040376, 0.7516271 , 4.6316295 ,\n",
" 0. , 0. , 0.14100271], dtype=float32)"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"avg2d_2_model = Model(inputs, model.layers[8].output)\n",
"avg2d_2_model.predict(X.reshape(1,28,28,1))[0][3][3]"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['240465720017978049',\n",
" '312962931075997403',\n",
" '16422062895818568',\n",
" '0',\n",
" '0',\n",
" '1115397662044723147',\n",
" '3743826354975568930',\n",
" '1282135426254877774',\n",
" '2558492900397241085',\n",
" '0',\n",
" '69224497325539673',\n",
" '0',\n",
" '60798814494206494',\n",
" '2302583886918782205',\n",
" '379552091654971946',\n",
" '0',\n",
" '1609754191355983350',\n",
" '0',\n",
" '27599924897036794',\n",
" '30247813336316648']"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"flatten_out = [avg2d_2_out[i][j][k] for i in range(5) for j in range(5) for k in range(8)]\n",
"flatten_out[100:120]"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 32ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([0.24046564, 0.312963 , 0.0164221 , 0. , 0. ,\n",
" 1.1153977 , 3.7438262 , 1.2821352 , 2.5584927 , 0. ,\n",
" 0.0692246 , 0. , 0.06079884, 2.3025842 , 0.37955213,\n",
" 0. , 1.6097541 , 0. , 0.02759986, 0.03024786],\n",
" dtype=float32)"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"flatten_model = Model(inputs, model.layers[9].output)\n",
"flatten_model.predict(X.reshape(1,28,28,1))[0][100:120]"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"dense_in = [int(flatten_out[i]) if int(flatten_out[i]) < p//2 else int(flatten_out[i]) - p for i in range(200)]\n",
"dense_weights = [[int(model.layers[10].weights[0][i][j]*1e18) for j in range(10)] for i in range(200)]\n",
"dense_bias = [int(model.layers[10].weights[1][i]*1e36) for i in range(10)]"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"def DenseInt(nInputs, nOutputs, n, input, weights, bias):\n",
" Input = [str(input[i] % p) for i in range(nInputs)]\n",
" Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\n",
" Bias = [str(bias[i] % p) for i in range(nOutputs)]\n",
" out = [0 for _ in range(nOutputs)]\n",
" remainder = [None for _ in range(nOutputs)]\n",
" for j in range(nOutputs):\n",
" for i in range(nInputs):\n",
" out[j] += input[i] * weights[i][j]\n",
" out[j] += bias[j]\n",
" remainder[j] = str(out[j] % n)\n",
" out[j] = str(out[j] // n % p)\n",
" return Input, Weights, Bias, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['21888242871839275222246405745257275088548364400416034343696001558406187208579',\n",
" '21888242871839275222246405745257275088548364400416034343694494011253998843463',\n",
" '2502586410316628302',\n",
" '7723360444146681933',\n",
" '21888242871839275222246405745257275088548364400416034343688179933383346961393',\n",
" '21888242871839275222246405745257275088548364400416034343697101907583287035462',\n",
" '21888242871839275222246405745257275088548364400416034343680804147065276585857',\n",
" '21047995401855287971',\n",
" '21888242871839275222246405745257275088548364400416034343695951614145619839501',\n",
" '4230622081176419220']"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, dense_weights, dense_bias, dense_out, dense_remainder = DenseInt(200, 10, 10**18, dense_in, dense_weights, dense_bias)\n",
"dense_out"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['21888242871839275222246405745257275088548364400416034343696001558406187208579',\n",
" '21888242871839275222246405745257275088548364400416034343694494011253998843463',\n",
" '2502586410316628302',\n",
" '7723360444146681933',\n",
" '21888242871839275222246405745257275088548364400416034343688179933383346961393',\n",
" '21888242871839275222246405745257275088548364400416034343697101907583287035462',\n",
" '21888242871839275222246405745257275088548364400416034343680804147065276585857',\n",
" '21047995401855287971',\n",
" '21888242871839275222246405745257275088548364400416034343695951614145619839501',\n",
" '4230622081176419220']"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dense_out"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 35ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([ -2.2026286, -3.7101758, 2.5025864, 7.7233634, -10.024254 ,\n",
" -1.1022782, -17.40004 , 21.047997 , -2.2525737, 4.230623 ],\n",
" dtype=float32)"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dense_model = Model(inputs, model.layers[-2].output)\n",
"dense_model.predict(X.reshape(1,28,28,1))[0]"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"conv2d_1_weights\": conv2d_1_weights,\n",
" \"conv2d_1_bias\": conv2d_1_bias,\n",
" \"conv2d_1_out\": conv2d_1_out,\n",
" \"conv2d_1_remainder\": conv2d_1_remainder,\n",
" \"bn_1_a\": bn_1_a,\n",
" \"bn_1_b\": bn_1_b,\n",
" \"bn_1_out\": bn_1_out,\n",
" \"bn_1_remainder\": bn_1_remainder,\n",
" \"relu_1_out\": relu_1_out,\n",
" \"avg2d_1_out\": avg2d_1_out,\n",
" \"avg2d_1_remainder\": avg2d_1_remainder,\n",
" \"conv2d_2_weights\": conv2d_2_weights,\n",
" \"conv2d_2_bias\": conv2d_2_bias,\n",
" \"conv2d_2_out\": conv2d_2_out,\n",
" \"conv2d_2_remainder\": conv2d_2_remainder,\n",
" \"bn_2_a\": bn_2_a,\n",
" \"bn_2_b\": bn_2_b,\n",
" \"bn_2_out\": bn_2_out,\n",
" \"bn_2_remainder\": bn_2_remainder,\n",
" \"relu_2_out\": relu_2_out,\n",
" \"avg2d_2_out\": avg2d_2_out,\n",
" \"avg2d_2_remainder\": avg2d_2_remainder,\n",
" \"flatten_out\": flatten_out,\n",
" \"dense_weights\": dense_weights,\n",
" \"dense_bias\": dense_bias,\n",
" \"dense_out\": dense_out,\n",
" \"dense_remainder\": dense_remainder,\n",
" \"argmax_out\": \"7\"\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [],
"source": [
"with open(\"mnist_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"interpreter": {
"hash": "11280bdb37aa6bc5d4cf1e4de756386eb1f9eecd8dcdefa77636dfac7be2370d"
},
"kernelspec": {
"display_name": "Python 3.8.6 ('tf24')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/model1.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Dense\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(3,))\n",
"x = Dense(2, activation='relu')(inputs)\n",
"outputs = Dense(1)(x)\n",
"model = Model(inputs, outputs)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 3)] 0 \n",
" \n",
" dense (Dense) (None, 2) 8 \n",
" \n",
" dense_1 (Dense) (None, 1) 3 \n",
" \n",
"=================================================================\n",
"Total params: 11\n",
"Trainable params: 11\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<tf.Variable 'dense/kernel:0' shape=(3, 2) dtype=float32, numpy=\n",
" array([[-0.72784126, 0.33670223],\n",
" [-0.7780691 , 0.62421453],\n",
" [-1.0269804 , 0.49905217]], dtype=float32)>,\n",
" <tf.Variable 'dense/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>,\n",
" <tf.Variable 'dense_1/kernel:0' shape=(2, 1) dtype=float32, numpy=\n",
" array([[-0.00755942],\n",
" [ 0.58352613]], dtype=float32)>,\n",
" <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.weights"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.5545958 , 0.48267873, 0.46073158]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 36ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2023-10-24 01:16:53.952999: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[0.41894716]], dtype=float32)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"X_in = [int(x*1e36) for x in X[0]]\n",
"Dense32weights = [[int(model.weights[0].numpy()[i][j]*1e36) for j in range(2)] for i in range(3)]\n",
"Dense32bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\n",
"Dense21weights = [[int(model.weights[2].numpy()[i][j]*1e36) for j in range(1)] for i in range(2)]\n",
"Dense21bias = [int(model.weights[3].numpy()[i]*1e72) for i in range(1)]\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"def DenseInt(nInputs, nOutputs, n, input, weights, bias):\n",
" Input = [str(input[i] % p) for i in range(nInputs)]\n",
" Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\n",
" Bias = [str(bias[i] % p) for i in range(nOutputs)]\n",
" out = [0 for _ in range(nOutputs)]\n",
" remainder = [None for _ in range(nOutputs)]\n",
" for j in range(nOutputs):\n",
" for i in range(nInputs):\n",
" out[j] += input[i] * weights[i][j]\n",
" out[j] += bias[j]\n",
" remainder[j] = str(out[j] % n)\n",
" out[j] = str(out[j] // n % p)\n",
" return Input, Weights, Bias, out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(['21888242871839275222246405745257275088547112023011337864689255117657466434208',\n",
" '717957812208694328223024234032338630'],\n",
" ['749712352190261448543726154832412672',\n",
" '264894409627262887048751218981601280'])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_in, Dense32weights, Dense32bias, Dense32out, Dense32remainder = DenseInt(3, 2, 10**36, X_in, Dense32weights, Dense32bias)\n",
"Dense32out, Dense32remainder"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"ReLUout = [Dense32out[i] if int(Dense32out[i]) < p//2 else 0 for i in range(2)]\n",
"Dense21in = [int(ReLUout[i]) for i in range(2)]"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(['418947146885730875576316926961913803'],\n",
" ['695849152206718637828300508516843520'])"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, Dense21weights, Dense21bias, Dense21out, Dense21remainder = DenseInt(2, 1, 10**36, Dense21in, Dense21weights, Dense21bias)\n",
"Dense21out, Dense21remainder"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"Dense32weights\": Dense32weights,\n",
" \"Dense32bias\": Dense32bias,\n",
" \"Dense32out\": Dense32out,\n",
" \"Dense32remainder\": Dense32remainder,\n",
" \"ReLUout\": ReLUout,\n",
" \"Dense21weights\": Dense21weights,\n",
" \"Dense21bias\": Dense21bias,\n",
" \"Dense21out\": Dense21out,\n",
" \"Dense21remainder\": Dense21remainder\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"with open(\"model1_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/pointwiseConv2D.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "2b70084b-44da-4142-9e24-c9c8231828db",
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"import numpy as np\n",
"import json"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e7533193-266d-4a59-b9aa-54179d40aa41",
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n",
"EXPONENT = 15\n",
"\n",
"class SeparableConv2D(nn.Module):\n",
" '''Separable convolution'''\n",
" def __init__(self, in_channels, out_channels, stride=1):\n",
" super(SeparableConv2D, self).__init__()\n",
" self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\n",
" self.pw_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\n",
"\n",
" def forward(self, x):\n",
" x = self.dw_conv(x)\n",
" x = self.pw_conv(x)\n",
" return x"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "4dec98ed-cd14-442b-93b5-8f3660726773",
"metadata": {},
"outputs": [],
"source": [
"input = torch.randn((1, 3, 5, 5))\n",
"model = SeparableConv2D(3, 6)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "92b62f7c-5ac1-4c69-9add-9a859d66c327",
"metadata": {},
"outputs": [],
"source": [
"def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\n",
" kernelSize = 1\n",
" outRows = (nRows - kernelSize)//strides + 1\n",
" outCols = (nCols - kernelSize)//strides + 1\n",
" out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" for row in range(outRows):\n",
" for col in range(outCols):\n",
" for filter in range(nFilters):\n",
" for k in range(nChannels):\n",
" out[row][col][filter] += int(input[row*strides, col*strides, k]) * int(weights[k, filter])\n",
" \n",
" out[row][col][filter] += int(bias[filter])\n",
" remainder[row][col][filter] = str(int(out[row][col][filter] % n))\n",
" out[row][col][filter] = int(out[row][col][filter] // n)\n",
" str_out[row][col][filter] = str(out[row][col][filter] % p)\n",
" \n",
" return out, str_out, remainder"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0c664ba3-b722-482b-84f4-f83bab1d1bdb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"quantized_image.shape=(5, 5, 3)\n",
"quantized_weights.shape=(3, 6)\n",
"expected.shape=(1, 6, 5, 5)\n",
"expected.shape=(5, 5, 6)\n"
]
}
],
"source": [
"weights = model.pw_conv.weight.detach().numpy()\n",
"bias = torch.zeros(weights.shape[0]).numpy()\n",
"\n",
"expected = model.pw_conv(input).detach().numpy()\n",
"\n",
"weights = weights.transpose((2, 3, 1, 0)).squeeze()\n",
"\n",
"quantized_image = input.squeeze().numpy().transpose((1, 2, 0)) * 10**EXPONENT\n",
"quantized_weights = weights * 10**EXPONENT\n",
"print(f\"{quantized_image.shape=}\")\n",
"print(f\"{quantized_weights.shape=}\")\n",
"\n",
"actual, str_actual, remainder = PointwiseConv2d(5, 5, 3, 6, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\n",
"\n",
"actual_scaled = [[[actual[i][j][k] / 10**EXPONENT for k in range(6)] for j in range(5)] for i in range(5)]\n",
"\n",
"expected = expected.squeeze().transpose((1, 2, 0))\n",
"\n",
"assert(np.allclose(expected, actual_scaled, atol=0.00001))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8b595d39-ca92-4c45-b04e-e7eb85b4c843",
"metadata": {},
"outputs": [],
"source": [
"circuit_in = quantized_image.round().astype(int).astype(str).tolist()\n",
"circuit_weights = quantized_weights.round().astype(int).astype(str).tolist()\n",
"circuit_bias = bias.round().astype(int).astype(str).tolist()\n",
"\n",
"input_json_path = \"pointwiseConv2D_input.json\"\n",
"with open(input_json_path, \"w\") as input_file:\n",
" json.dump({\"in\": circuit_in,\n",
" \"weights\": circuit_weights,\n",
" \"remainder\": remainder,\n",
" \"out\": str_actual,\n",
" \"bias\": circuit_bias,\n",
" },\n",
" input_file)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cd6f84d3-4d70-421c-9067-5ed314c967a8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
| https://github.com/socathie/circomlib-ml |
models/remez.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from mpmath import mp\n",
"import numpy as np\n",
"\n",
"# from https://github.com/DKenefake/OptimalPoly\n",
"\n",
"def bisection_search(f, low:float, high:float):\n",
" \"\"\"\n",
" A root finding method that does not rely on derivatives\n",
"\n",
" :param f: a function f: X -> R\n",
" :param low: the lower bracket\n",
" :param high: the upper limit bracket\n",
" :return: the location of the root, e.g. f(mid) ~ 0\n",
" \"\"\"\n",
" # flip high and low if out of order\n",
" if f(high) < f(low):\n",
" low, high = high, low\n",
"\n",
" # find mid point\n",
" mid = .5 * (low + high)\n",
"\n",
" while True:\n",
"\n",
" # bracket up\n",
" if f(mid) < 0:\n",
" low = mid\n",
" # braket down\n",
" else:\n",
" high = mid\n",
"\n",
" # update mid point\n",
" mid = .5 * (high + low)\n",
"\n",
" # break if condition met\n",
" if abs(high - low) < 10 ** (-(mp.dps / 2)):\n",
" break\n",
"\n",
" return mid\n",
"\n",
"\n",
"def concave_max(f, low:float, high:float):\n",
" \"\"\"\n",
" Forms a lambda for the approximate derivative and finds the root\n",
"\n",
" :param f: a function f: X -> R\n",
" :param low: the lower bracket\n",
" :param high: the upper limit bracket\n",
" :return: the location of the root f'(mid) ~ 0\n",
" \"\"\"\n",
" # create an approximate derivative expression\n",
" scale = high - low\n",
"\n",
" h = mp.mpf('0.' + ''.join(['0' for i in range(int(mp.dps / 1.5))]) + '1') * scale\n",
" df = lambda x: (f(x + h) - f(x - h)) / (2.0 * h)\n",
"\n",
" return bisection_search(df, low, high)\n",
"\n",
"def chev_points(n:int, lower:float = -1, upper:float = 1):\n",
" \"\"\"\n",
" Generates a set of chebychev points spaced in the range [lower, upper]\n",
" :param n: number of points\n",
" :param lower: lower limit\n",
" :param upper: upper limit\n",
" :return: a list of multipressison chebychev points that are in the range [lower, upper]\n",
" \"\"\"\n",
" #generate chebeshev points on a range [-1, 1]\n",
" index = np.arange(1, n+1)\n",
" range_ = abs(upper - lower)\n",
" return [(.5*(mp.cos((2*i-1)/(2*n)*mp.pi)+1))*range_ + lower for i in index]\n",
"\n",
"\n",
"def remez(func, n_degree:int, lower:float=-1, upper:float=1, max_iter:int = 10):\n",
" \"\"\"\n",
" :param func: a function (or lambda) f: X -> R\n",
" :param n_degree: the degree of the polynomial to approximate the function f\n",
" :param lower: lower range of the approximation\n",
" :param upper: upper range of the approximation\n",
" :return: the polynomial coefficients, and an approximate maximum error associated with this approximation\n",
" \"\"\"\n",
" # initialize the node points\n",
"\n",
" x_points = chev_points(n_degree + 2, lower, upper)\n",
"\n",
" A = mp.matrix(n_degree + 2)\n",
" coeffs = np.zeros(n_degree + 2)\n",
"\n",
" # place in the E column\n",
" mean_error = float('inf')\n",
"\n",
" for i in range(n_degree + 2):\n",
" A[i, n_degree + 1] = (-1) ** (i + 1)\n",
"\n",
" for i in range(max_iter):\n",
"\n",
" # build the system\n",
" vander = np.polynomial.chebyshev.chebvander(x_points, n_degree)\n",
"\n",
" for i in range(n_degree + 2):\n",
" for j in range(n_degree + 1):\n",
" A[i, j] = vander[i, j]\n",
"\n",
" b = mp.matrix([func(x) for x in x_points])\n",
" l = mp.lu_solve(A, b)\n",
"\n",
" coeffs = l[:-1]\n",
"\n",
" # build the residual expression\n",
" r_i = lambda x: (func(x) - np.polynomial.chebyshev.chebval(x, coeffs))\n",
"\n",
" interval_list = list(zip(x_points, x_points[1:]))\n",
" # interval_list = [[x_points[i], x_points[i+1]] for i in range(len(x_points)-1)]\n",
"\n",
" intervals = [upper]\n",
" intervals.extend([bisection_search(r_i, *i) for i in interval_list])\n",
" intervals.append(lower)\n",
"\n",
" extermum_interval = [[intervals[i], intervals[i + 1]] for i in range(len(intervals) - 1)]\n",
"\n",
" extremums = [concave_max(r_i, *i) for i in extermum_interval]\n",
"\n",
" extremums[0] = mp.mpf(upper)\n",
" extremums[-1] = mp.mpf(lower)\n",
"\n",
" errors = [abs(r_i(i)) for i in extremums]\n",
" mean_error = np.mean(errors)\n",
"\n",
" if np.max([abs(error - mean_error) for error in errors]) < 0.000001 * mean_error:\n",
" break\n",
"\n",
" x_points = extremums\n",
"\n",
" return [float(i) for i in np.polynomial.chebyshev.cheb2poly(coeffs)], float(mean_error)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['0.502073021', '0.198695283', '-0.001570683', '-0.004001354']"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"function = lambda x: mp.sigmoid(x)\n",
"poly_coeffs, max_error = remez(function, 3, -5, 5)\n",
"[np.format_float_positional(c, precision=9) for c in poly_coeffs]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['0.006769816', '0.554670504', '-0.009411195', '-0.014187547']"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"function = lambda x: mp.tanh(x)\n",
"poly_coeffs, max_error = remez(function, 3, -5, 5)\n",
"[np.format_float_positional(c, precision=9) for c in poly_coeffs]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "sklearn",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/reshape2d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, Reshape\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(75,))\n",
"x = Reshape((5, 5, 3))(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_1 (InputLayer) [(None, 75)] 0 \n",
" \n",
" reshape (Reshape) (None, 5, 5, 3) 0 \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.72327659, 0.97464849, 0.2592479 , 0.63799774, 0.89013732,\n",
" 0.95867971, 0.06431743, 0.55685192, 0.77031965, 0.09982323,\n",
" 0.10704737, 0.40713332, 0.57294341, 0.21883552, 0.22967276,\n",
" 0.6221842 , 0.64159904, 0.684413 , 0.59126341, 0.88438877,\n",
" 0.56715972, 0.93006015, 0.85704814, 0.79864291, 0.39604054,\n",
" 0.30495253, 0.38333952, 0.69453548, 0.59207958, 0.30889659,\n",
" 0.17302571, 0.41351124, 0.37527957, 0.43118255, 0.31526054,\n",
" 0.12925303, 0.30129156, 0.73921834, 0.98336451, 0.03352392,\n",
" 0.27839826, 0.6811155 , 0.96320785, 0.16882282, 0.68572833,\n",
" 0.20924115, 0.30604142, 0.09080768, 0.63244108, 0.55914947,\n",
" 0.60870048, 0.49377892, 0.9710362 , 0.12959508, 0.62162852,\n",
" 0.26827067, 0.84771621, 0.40895646, 0.52476578, 0.48532215,\n",
" 0.27144489, 0.19194784, 0.85410267, 0.11912042, 0.37034274,\n",
" 0.25759208, 0.88306728, 0.98917787, 0.61814043, 0.49141046,\n",
" 0.74162286, 0.81722887, 0.4728493 , 0.19955073, 0.42201694]])"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,75)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 44ms/step\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2024-02-04 00:14:24.910151: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
]
},
{
"data": {
"text/plain": [
"array([[[[0.7232766 , 0.9746485 , 0.2592479 ],\n",
" [0.63799775, 0.8901373 , 0.9586797 ],\n",
" [0.06431743, 0.5568519 , 0.77031964],\n",
" [0.09982323, 0.10704737, 0.4071333 ],\n",
" [0.5729434 , 0.21883552, 0.22967276]],\n",
"\n",
" [[0.6221842 , 0.64159906, 0.684413 ],\n",
" [0.5912634 , 0.88438874, 0.5671597 ],\n",
" [0.93006015, 0.85704815, 0.79864293],\n",
" [0.39604053, 0.30495253, 0.38333952],\n",
" [0.6945355 , 0.5920796 , 0.3088966 ]],\n",
"\n",
" [[0.17302571, 0.41351125, 0.37527958],\n",
" [0.43118253, 0.31526053, 0.12925303],\n",
" [0.30129156, 0.73921835, 0.9833645 ],\n",
" [0.03352392, 0.27839825, 0.6811155 ],\n",
" [0.96320784, 0.16882282, 0.6857283 ]],\n",
"\n",
" [[0.20924115, 0.30604142, 0.09080768],\n",
" [0.6324411 , 0.55914944, 0.60870045],\n",
" [0.4937789 , 0.9710362 , 0.12959507],\n",
" [0.6216285 , 0.26827067, 0.8477162 ],\n",
" [0.40895647, 0.5247658 , 0.48532215]],\n",
"\n",
" [[0.2714449 , 0.19194785, 0.8541027 ],\n",
" [0.11912042, 0.37034273, 0.25759208],\n",
" [0.8830673 , 0.9891779 , 0.6181404 ],\n",
" [0.49141046, 0.74162287, 0.81722885],\n",
" [0.4728493 , 0.19955073, 0.42201695]]]], dtype=float32)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": (X*1e36).round().astype(int).flatten().tolist(),\n",
" \"out\": (X*1e36).round().astype(int).flatten().tolist()\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"with open(\"reshape2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/separableConv2D.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "aa5be75a-ee5f-45b0-891b-da2dd340dd00",
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"import numpy as np\n",
"import json"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "f85ed78d-97ef-4979-acac-8d95b34a84ae",
"metadata": {},
"outputs": [],
"source": [
"p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n",
"CIRCOM_PRIME = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n",
"MAX_POSITIVE = CIRCOM_PRIME // 2\n",
"MAX_NEGATIVE = MAX_POSITIVE + 1 # The most positive number\n",
"CIRCOM_NEGATIVE_1 = 21888242871839275222246405745257275088548364400416034343698204186575808495617 - 1\n",
"EXPONENT = 15\n",
"\n",
"class SeparableConv2D(nn.Module):\n",
" '''Separable convolution'''\n",
" def __init__(self, in_channels, out_channels, stride=1):\n",
" super(SeparableConv2D, self).__init__()\n",
" self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\n",
" self.pw_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\n",
"\n",
" def forward(self, x):\n",
" x = self.dw_conv(x)\n",
" x = self.pw_conv(x)\n",
" return x\n",
"\n",
"def from_circom(x):\n",
" if type(x) != int:\n",
" x = int(x)\n",
" if x > MAX_POSITIVE: \n",
" return x - CIRCOM_PRIME\n",
" return x\n",
" \n",
"def to_circom(x):\n",
" if type(x) != int:\n",
" x = int(x)\n",
" if x < 0:\n",
" return x + CIRCOM_PRIME \n",
" return x"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "32e117a1-32aa-4b4b-91d0-4b4b78071b6b",
"metadata": {},
"outputs": [],
"source": [
"# def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
"# assert(nFilters % nChannels == 0)\n",
"# outRows = (nRows - kernelSize)//strides + 1\n",
"# outCols = (nCols - kernelSize)//strides + 1\n",
" \n",
"# out = np.zeros((outRows, outCols, nFilters))\n",
"# remainder = np.zeros((outRows, outCols, nFilters))\n",
" \n",
"# for row in range(outRows):\n",
"# for col in range(outCols):\n",
"# for channel in range(nChannels):\n",
"# for x in range(kernelSize):\n",
"# for y in range(kernelSize):\n",
"# out[row, col, channel] += input[row*strides+x, col*strides+y, channel] * weights[x, y, channel]\n",
" \n",
"# out[row][col][channel] += bias[channel]\n",
"# remainder[row][col][channel] = out[row][col][channel] % n\n",
"# out[row][col][channel] = out[row][col][channel] / n\n",
" \n",
"# return out, remainder\n",
" \n",
"# def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\n",
"# kernelSize = 1\n",
"# outRows = (nRows - kernelSize)//strides + 1\n",
"# outCols = (nCols - kernelSize)//strides + 1\n",
"# out = np.zeros((outRows, outCols, nFilters))\n",
"# for row in range(outRows):\n",
"# for col in range(outCols):\n",
"# for filter in range(nFilters):\n",
"# for k in range(nChannels):\n",
"# out[row, col, filter] += input[row*strides, col*strides, k] * weights[k, filter]\n",
" \n",
"# out[row][col][filter] += bias[filter]\n",
"# out[row][col][filter] = out[row][col][filter] / n\n",
" \n",
"# return out\n",
"\n",
"# def SeparableConvImpl(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\n",
"# outRows = (nRows - kernelSize)//strides + 1\n",
"# outCols = (nCols - kernelSize)//strides + 1\n",
"\n",
"# depthOut, rem = DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\n",
"# pointOut = PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, depthOut, pointWeights, pointBias)\n",
"# return pointOut"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "e3dfadfd-2587-4708-9dd5-535a999ed359",
"metadata": {},
"outputs": [],
"source": [
"# def DepthwiseConvInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
"# assert(nFilters % nChannels == 0)\n",
"# outRows = (nRows - kernelSize)//strides + 1\n",
"# outCols = (nCols - kernelSize)//strides + 1\n",
" \n",
"# Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
"# Weights = [[[str(weights[i][j][k] % p) for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\n",
"# Bias = [str(bias[i] % p) for i in range(nFilters)]\n",
"# out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
"# str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
"# remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" \n",
"# for row in range(outRows):\n",
"# for col in range(outCols):\n",
"# for channel in range(nChannels):\n",
"# for x in range(kernelSize):\n",
"# for y in range(kernelSize):\n",
"# out[row][col][channel] += int(input[row*strides+x][col*strides+y][channel]) * int(weights[x][y][channel])\n",
" \n",
"# out[row][col][channel] += int(bias[channel])\n",
"# remainder[row][col][channel] = str(int(out[row][col][channel] % n))\n",
"# out[row][col][channel] = int((out[row][col][channel] // n))\n",
"# str_out[row][col][channel] = str(out[row][col][channel] % p)\n",
" \n",
"# return Input, Weights, Bias, out, str_out, remainder\n",
" \n",
"# def PointwiseConv2dInt(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\n",
"# kernelSize = 1\n",
"# outRows = (nRows - kernelSize)//strides + 1\n",
"# outCols = (nCols - kernelSize)//strides + 1\n",
" \n",
"# Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n",
"# Weights = [[str(weights[k][l] % p) for l in range(nFilters)] for k in range(nChannels)]\n",
"# Bias = [str(bias[i] % p) for i in range(nFilters)]\n",
"# out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
"# str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
"# remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" \n",
"# for row in range(outRows):\n",
"# for col in range(outCols):\n",
"# for filter in range(nFilters):\n",
"# for channel in range(nChannels):\n",
"# out[row][col][filter] += int(input[row*strides][col*strides][channel]) * int(weights[channel][filter])\n",
" \n",
"# out[row][col][filter] += int(bias[filter])\n",
"# remainder[row][col][filter] = str(int(out[row][col][filter] % n))\n",
"# out[row][col][filter] = str(out[row][col][filter] // n % p)\n",
"# return Input, Weights, Bias, out, remainder\n",
"\n",
"# def SeparableConvInt(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\n",
"# outRows = (nRows - kernelSize)//strides + 1\n",
"# outCols = (nCols - kernelSize)//strides + 1\n",
"\n",
"# Input, DepthWeights, DepthBias, depthOut, depthStrOut, depthRemainder = DepthwiseConvInt(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\n",
"# test = [[[from_circom(int(depthStrOut[i][j][k])) for k in range(3)] for j in range(5)] for i in range(5)]\n",
"# assert(test == depthOut)\n",
"# pInput, PointWeights, PointBias, pointOut, pointRem = PointwiseConv2dInt(outRows, outCols, nChannels, nPointFilters, strides, n, depthOut, pointWeights, pointBias)\n",
" \n",
"# return Input, DepthWeights, DepthBias, depthOut, depthStrOut, depthRemainder, PointWeights, PointBias, pointOut, pointRem"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cc1a4a27-a1dc-4565-90e3-12e6d7122157",
"metadata": {},
"outputs": [],
"source": [
"def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n",
" assert(nFilters % nChannels == 0)\n",
" outRows = (nRows - kernelSize)//strides + 1\n",
" outCols = (nCols - kernelSize)//strides + 1\n",
" \n",
" # out = np.zeros((outRows, outCols, nFilters))\n",
" out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" remainder = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" # remainder = np.zeros((outRows, outCols, nFilters))\n",
" \n",
" for row in range(outRows):\n",
" for col in range(outCols):\n",
" for channel in range(nChannels):\n",
" for x in range(kernelSize):\n",
" for y in range(kernelSize):\n",
" out[row][col][channel] += int(input[row*strides+x, col*strides+y, channel]) * int(weights[x, y, channel])\n",
" \n",
" out[row][col][channel] += int(bias[channel])\n",
" remainder[row][col][channel] = str(int(out[row][col][channel] % n))\n",
" out[row][col][channel] = int(out[row][col][channel] // n)\n",
" \n",
" return out, remainder\n",
" \n",
"def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\n",
" kernelSize = 1\n",
" outRows = (nRows - kernelSize)//strides + 1\n",
" outCols = (nCols - kernelSize)//strides + 1\n",
" out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n",
" for row in range(outRows):\n",
" for col in range(outCols):\n",
" for filter in range(nFilters):\n",
" for k in range(nChannels):\n",
" out[row][col][filter] += int(input[row*strides][col*strides][k]) * int(weights[k, filter])\n",
" \n",
" out[row][col][filter] += int(bias[filter])\n",
" remainder[row][col][filter] = str(int(out[row][col][filter] % n))\n",
" out[row][col][filter] = int(out[row][col][filter] // n)\n",
" str_out[row][col][filter] = str(out[row][col][filter] % p)\n",
" \n",
" return out, str_out, remainder\n",
" \n",
"def SeparableConvImpl(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\n",
" outRows = (nRows - kernelSize)//strides + 1\n",
" outCols = (nCols - kernelSize)//strides + 1\n",
"\n",
" depth_out, depth_remainder = DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\n",
" point_out, point_str_out, point_remainder = PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, depth_out, pointWeights, pointBias)\n",
" return depth_out, depth_remainder, point_out, point_str_out, point_remainder"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cfa6df6a-9a0c-4150-9df0-30e2700d4f6b",
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'torch' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[2], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[43mtorch\u001b[49m\u001b[38;5;241m.\u001b[39mrandn((\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m5\u001b[39m, \u001b[38;5;241m5\u001b[39m))\n\u001b[1;32m 2\u001b[0m model \u001b[38;5;241m=\u001b[39m SeparableConv2D(\u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m6\u001b[39m)\n",
"\u001b[0;31mNameError\u001b[0m: name 'torch' is not defined"
]
}
],
"source": [
"input = torch.randn((1, 3, 5, 5))\n",
"model = SeparableConv2D(3, 6)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "5db59f3a-e610-473a-8dfc-1d5e812748f4",
"metadata": {},
"outputs": [],
"source": [
"# weights = model.dw_conv.weight.squeeze().detach().numpy()\n",
"# bias = torch.zeros(weights.shape[0]).numpy()\n",
"\n",
"# expected = model.dw_conv(input).detach().numpy()\n",
"\n",
"# padded = F.pad(input, (1,1,1,1), \"constant\", 0) # Padding for convolution with \"same\" configuration\n",
"# padded = padded.squeeze().numpy().transpose((1, 2, 0))\n",
"# weights = weights.transpose((1, 2, 0))\n",
"\n",
"# actual, rem = DepthwiseConv(7, 7, 3, 3, 3, 1, 1, padded, weights, bias)\n",
"# expected = expected.squeeze().transpose((1, 2, 0))\n",
"\n",
"# assert(np.allclose(expected, actual, atol=0.00001))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "47ce42c7-b417-46ba-a31b-1ae23234a2cd",
"metadata": {},
"outputs": [],
"source": [
"# weights = model.pw_conv.weight.detach().numpy()\n",
"# print(f\"{weights.shape=}\")\n",
"# bias = torch.zeros(weights.shape[0]).numpy()\n",
"\n",
"# expected = model.pw_conv(input).detach().numpy()\n",
"\n",
"# padded = input.squeeze().numpy().transpose((1, 2, 0))\n",
"# print(padded.shape)\n",
"# weights = weights.transpose((2, 3, 1, 0)).squeeze()\n",
"\n",
"# actual = PointwiseConv2d(5, 5, 3, 6, 1, 1, padded, weights, bias)\n",
"\n",
"# expected = expected.squeeze().transpose((1, 2, 0))\n",
"\n",
"# assert(np.allclose(expected, actual, atol=0.00001))"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "7a36a0a1-6965-4184-93a5-5d121d6d1856",
"metadata": {},
"outputs": [],
"source": [
"# depthWeights = model.dw_conv.weight.squeeze().detach().numpy()\n",
"# depthBias = torch.zeros(depthWeights.shape[0]).numpy()\n",
"\n",
"# depthWeights = depthWeights.transpose((1, 2, 0))\n",
"\n",
"# pointWeights = model.pw_conv.weight.detach().numpy()\n",
"# print(f\"{depthWeights.shape=}\")\n",
"# pointBias = torch.zeros(pointWeights.shape[0]).numpy()\n",
"# pointWeights = pointWeights.transpose((2, 3, 1, 0)).squeeze()\n",
"\n",
"# expected = model(input).detach().numpy()\n",
"# print(f\"{expected.shape=}\")\n",
"\n",
"# padded = F.pad(input, (1,1,1,1), \"constant\", 0) # Padding for convolution with \"same\" configuration\n",
"# padded = padded.squeeze().numpy().transpose((1, 2, 0))\n",
"\n",
"# print(pointBias.shape)\n",
"# actual = SeparableConvImpl(7, 7, 3, 3, 6, 3, 1, 1, padded, depthWeights, pointWeights, depthBias, pointBias)\n",
"# expected = expected.squeeze().transpose((1, 2, 0))\n",
"\n",
"# assert(np.allclose(expected, actual, atol=0.00001))"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "fd587b58-1646-4ec8-9a79-4f891dab0276",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"depthWeights.shape=(3, 3, 3)\n",
"expected.shape=(1, 6, 5, 5)\n",
"(6,)\n"
]
},
{
"ename": "NameError",
"evalue": "name 'depthOut' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[10], line 23\u001b[0m\n\u001b[1;32m 20\u001b[0m quantized_depth_weights \u001b[38;5;241m=\u001b[39m depthWeights \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m10\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mEXPONENT\n\u001b[1;32m 21\u001b[0m quantized_point_weights \u001b[38;5;241m=\u001b[39m pointWeights \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m10\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mEXPONENT\n\u001b[0;32m---> 23\u001b[0m depth_out, depth_remainder, point_out, point_str_out, point_remainder \u001b[38;5;241m=\u001b[39m \u001b[43mSeparableConvImpl\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m7\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m7\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m6\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mEXPONENT\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquantized_image\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mround\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquantized_depth_weights\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mround\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquantized_point_weights\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mround\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdepthBias\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpointBias\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 25\u001b[0m actual_scaled \u001b[38;5;241m=\u001b[39m [[[point_out[i][j][k] \u001b[38;5;241m/\u001b[39m \u001b[38;5;241m10\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mEXPONENT \u001b[38;5;28;01mfor\u001b[39;00m k \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m6\u001b[39m)] \u001b[38;5;28;01mfor\u001b[39;00m j \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m5\u001b[39m)] \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m5\u001b[39m)]\n\u001b[1;32m 27\u001b[0m expected \u001b[38;5;241m=\u001b[39m expected\u001b[38;5;241m.\u001b[39msqueeze()\u001b[38;5;241m.\u001b[39mtranspose((\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m0\u001b[39m))\n",
"Cell \u001b[0;32mIn[5], line 60\u001b[0m, in \u001b[0;36mSeparableConvImpl\u001b[0;34m(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias)\u001b[0m\n\u001b[1;32m 57\u001b[0m outCols \u001b[38;5;241m=\u001b[39m (nCols \u001b[38;5;241m-\u001b[39m kernelSize)\u001b[38;5;241m/\u001b[39m\u001b[38;5;241m/\u001b[39mstrides \u001b[38;5;241m+\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[1;32m 59\u001b[0m depth_out, depth_remainder \u001b[38;5;241m=\u001b[39m DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, \u001b[38;5;28minput\u001b[39m, depthWeights, depthBias)\n\u001b[0;32m---> 60\u001b[0m point_out, point_str_out, point_remainder \u001b[38;5;241m=\u001b[39m PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, \u001b[43mdepthOut\u001b[49m, pointWeights, pointBias)\n\u001b[1;32m 61\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m depth_out, depth_remainder, point_out, point_str_out, point_remainder\n",
"\u001b[0;31mNameError\u001b[0m: name 'depthOut' is not defined"
]
}
],
"source": [
"depthWeights = model.dw_conv.weight.squeeze().detach().numpy()\n",
"depthBias = torch.zeros(depthWeights.shape[0]).numpy()\n",
"\n",
"depthWeights = depthWeights.transpose((1, 2, 0))\n",
"\n",
"pointWeights = model.pw_conv.weight.detach().numpy()\n",
"print(f\"{depthWeights.shape=}\")\n",
"pointBias = torch.zeros(pointWeights.shape[0]).numpy()\n",
"pointWeights = pointWeights.transpose((2, 3, 1, 0)).squeeze()\n",
"\n",
"expected = model(input).detach().numpy()\n",
"print(f\"{expected.shape=}\")\n",
"\n",
"padded = F.pad(input, (1,1,1,1), \"constant\", 0) # Padding for convolution with \"same\" configuration\n",
"padded = padded.squeeze().numpy().transpose((1, 2, 0))\n",
"\n",
"print(pointBias.shape)\n",
"# actual = SeparableConvImpl(7, 7, 3, 3, 6, 3, 1, 1, padded, depthWeights, pointWeights, depthBias, pointBias)\n",
"quantized_image = padded * 10**EXPONENT\n",
"quantized_depth_weights = depthWeights * 10**EXPONENT\n",
"quantized_point_weights = pointWeights * 10**EXPONENT\n",
"\n",
"depth_out, depth_remainder, point_out, point_str_out, point_remainder = SeparableConvImpl(7, 7, 3, 3, 6, 3, 1, 10**EXPONENT, quantized_image.round().astype(int), quantized_depth_weights.round().astype(int), quantized_point_weights.round().astype(int), depthBias.astype(int), pointBias.astype(int))\n",
"\n",
"actual_scaled = [[[point_out[i][j][k] / 10**EXPONENT for k in range(6)] for j in range(5)] for i in range(5)]\n",
"\n",
"expected = expected.squeeze().transpose((1, 2, 0))\n",
"\n",
"assert(np.allclose(expected, actual_scaled, atol=0.00001))\n",
"\n",
"\n",
"# Input, DepthWeights, DepthBias, depthOut, depthStrOut, DepthRem, PointWeights, PointBias, pointOut, pointRem = SeparableConvInt(7, 7, 3, 3, 6, 3, 1, 10**EXPONENT, quantized_image.round().astype(int), quantized_depth_weights.round().astype(int), quantized_point_weights.round().astype(int), depthBias.astype(int), pointBias.astype(int))\n",
"\n",
"circuit_in = quantized_image.round().astype(int).astype(str).tolist()\n",
"circuit_depth_weights = quantized_depth_weights.round().astype(int).astype(str).tolist()\n",
"circuit_point_weights = quantized_point_weights.round().astype(int).astype(str).tolist()\n",
"circuit_depth_bias = depthBias.round().astype(int).astype(str).tolist()\n",
"circuit_point_bias = pointBias.round().astype(int).astype(str).tolist()\n",
"\n",
"\n",
"input_json_path = \"separableConv2D_input.json\"\n",
"with open(input_json_path, \"w\") as input_file:\n",
" json.dump({\"in\": circuit_in,\n",
" \"depthWeights\": circuit_depth_weights,\n",
" \"depthBias\": circuit_depth_bias,\n",
" \"depthRemainder\": depth_remainder,\n",
" \"depthOut\": depth_out,\n",
" \n",
" \"pointWeights\": circuit_point_weights,\n",
" \"pointBias\": circuit_point_bias,\n",
" \"pointRemainder\": point_remainder,\n",
" \"pointOut\": point_str_out,\n",
" },\n",
" input_file)\n"
]
},
{
"cell_type": "code",
"execution_count": 44,
"id": "f0dcbca8-7f2f-47ea-b662-29a8560774b1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 289246014266912, 458852178050435, -104551710192411,\n",
" -85286796832706, 70991076566637, -373719950995314])"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test = np.array(actual)\n",
"test[0][0]"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "3a652322-2fa0-4f51-bb2f-ed49bd94c65a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0.289246 , 0.45885214, -0.10455171, -0.0852868 , 0.07099106,\n",
" -0.37371993], dtype=float32)"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"expected[0][0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "56d3dda8-af64-402e-9c86-b333ca6782ba",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
| https://github.com/socathie/circomlib-ml |
models/sumPooling2d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, AveragePooling2D, Lambda\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(5,5,3))\n",
"x = AveragePooling2D(pool_size=2)(inputs)\n",
"x = Lambda(lambda x: x*4)(x)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
"Layer (type) Output Shape Param # \n",
"=================================================================\n",
"input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n",
"_________________________________________________________________\n",
"average_pooling2d (AveragePo (None, 2, 2, 3) 0 \n",
"_________________________________________________________________\n",
"lambda (Lambda) (None, 2, 2, 3) 0 \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.83128186, 0.15650764, 0.23798145],\n",
" [0.00277366, 0.8374127 , 0.95278315],\n",
" [0.3074389 , 0.21931738, 0.14886067],\n",
" [0.13590018, 0.98728255, 0.12085182],\n",
" [0.47212572, 0.51380922, 0.74891219]],\n",
"\n",
" [[0.74680338, 0.2533205 , 0.5039968 ],\n",
" [0.14475403, 0.00791911, 0.4361197 ],\n",
" [0.69925568, 0.77507624, 0.40388991],\n",
" [0.29508251, 0.99375606, 0.84959701],\n",
" [0.88844918, 0.33910189, 0.9617212 ]],\n",
"\n",
" [[0.76480625, 0.591287 , 0.0714191 ],\n",
" [0.94371681, 0.1695303 , 0.4476252 ],\n",
" [0.54372616, 0.83818804, 0.95211573],\n",
" [0.30485104, 0.15165265, 0.94709317],\n",
" [0.90827137, 0.58854675, 0.01857002]],\n",
"\n",
" [[0.70123418, 0.43090173, 0.7096038 ],\n",
" [0.20637783, 0.20096581, 0.22956612],\n",
" [0.81978383, 0.16775403, 0.67412096],\n",
" [0.1011535 , 0.35596916, 0.36702071],\n",
" [0.5874605 , 0.79341372, 0.93292159]],\n",
"\n",
" [[0.77997124, 0.46311399, 0.5465576 ],\n",
" [0.20406287, 0.37547625, 0.59862253],\n",
" [0.52933135, 0.84249092, 0.02969684],\n",
" [0.29114617, 0.10405779, 0.5359062 ],\n",
" [0.25197146, 0.83297465, 0.67025403]]]])"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,5,5,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[1.7256129, 1.2551599, 2.1308813],\n",
" [1.4376774, 2.9754324, 1.5231993]],\n",
"\n",
" [[2.6161351, 1.3926848, 1.4582142],\n",
" [1.7695144, 1.5135639, 2.9403505]]]], dtype=float32)"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": (X*1000).round().astype(int).flatten().tolist()\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"out_json = {\n",
" \"out\": (y*1000).round().astype(int).flatten().tolist()\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import json"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"with open(\"sumPooling2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"with open(\"sumPooling2D_output.json\", \"w\") as f:\n",
" json.dump(out_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(10,10,3))\n",
"x = AveragePooling2D(pool_size=2, strides=3)(inputs)\n",
"x = Lambda(lambda x: x*4)(x)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_2\"\n",
"_________________________________________________________________\n",
"Layer (type) Output Shape Param # \n",
"=================================================================\n",
"input_3 (InputLayer) [(None, 10, 10, 3)] 0 \n",
"_________________________________________________________________\n",
"average_pooling2d_2 (Average (None, 3, 3, 3) 0 \n",
"_________________________________________________________________\n",
"lambda_2 (Lambda) (None, 3, 3, 3) 0 \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.31514958, 0.03200121, 0.29129004],\n",
" [0.35725668, 0.87252739, 0.77162311],\n",
" [0.61707883, 0.7945887 , 0.48907944],\n",
" [0.98197306, 0.88814753, 0.69652672],\n",
" [0.2518265 , 0.82753267, 0.57464263],\n",
" [0.62115028, 0.76805041, 0.65967975],\n",
" [0.32491691, 0.93353364, 0.74831234],\n",
" [0.45570461, 0.96830864, 0.8476189 ],\n",
" [0.02149766, 0.27808247, 0.18207897],\n",
" [0.15949257, 0.69372265, 0.43455872]],\n",
"\n",
" [[0.70915807, 0.60410698, 0.94721792],\n",
" [0.5621233 , 0.65546021, 0.27357865],\n",
" [0.00414209, 0.08635782, 0.30528659],\n",
" [0.11492599, 0.15002234, 0.58496289],\n",
" [0.72848003, 0.55169839, 0.91708802],\n",
" [0.43479205, 0.08069621, 0.68404234],\n",
" [0.3946513 , 0.20447291, 0.10467492],\n",
" [0.78817621, 0.63518792, 0.00827133],\n",
" [0.0853401 , 0.75656605, 0.95034115],\n",
" [0.92239164, 0.06871402, 0.37783711]],\n",
"\n",
" [[0.36000095, 0.35659628, 0.6507159 ],\n",
" [0.29486935, 0.49464939, 0.40502335],\n",
" [0.09509896, 0.08726498, 0.39326876],\n",
" [0.38827707, 0.50908505, 0.63443643],\n",
" [0.27030144, 0.67783072, 0.09309034],\n",
" [0.76360544, 0.67003754, 0.28767228],\n",
" [0.55305299, 0.60216561, 0.3544107 ],\n",
" [0.55839884, 0.86964781, 0.26053367],\n",
" [0.87306012, 0.78756102, 0.04817508],\n",
" [0.72406774, 0.67679246, 0.82272016]],\n",
"\n",
" [[0.71765743, 0.50852032, 0.52047892],\n",
" [0.7484707 , 0.97207503, 0.08778545],\n",
" [0.15780167, 0.73192822, 0.40718403],\n",
" [0.93263197, 0.8772701 , 0.34486053],\n",
" [0.42436095, 0.80504181, 0.39139203],\n",
" [0.81358273, 0.56754054, 0.12608038],\n",
" [0.11843567, 0.61136361, 0.81339895],\n",
" [0.27636648, 0.57453166, 0.10632468],\n",
" [0.53090786, 0.14594835, 0.08140653],\n",
" [0.34118642, 0.27554414, 0.19515355]],\n",
"\n",
" [[0.12974003, 0.6264065 , 0.56250089],\n",
" [0.05655555, 0.93847961, 0.71849845],\n",
" [0.57644684, 0.37077012, 0.53949152],\n",
" [0.45904117, 0.30854737, 0.73517714],\n",
" [0.64076017, 0.59373326, 0.83758554],\n",
" [0.80707699, 0.79461191, 0.69655474],\n",
" [0.79872758, 0.26420269, 0.29237624],\n",
" [0.45087863, 0.28258419, 0.50447663],\n",
" [0.29494657, 0.31770288, 0.49309187],\n",
" [0.82460949, 0.3940875 , 0.33865267]],\n",
"\n",
" [[0.1108653 , 0.35294351, 0.44014634],\n",
" [0.4988099 , 0.34405962, 0.77622373],\n",
" [0.76444373, 0.88689451, 0.05756076],\n",
" [0.57160174, 0.0752442 , 0.5098132 ],\n",
" [0.22539676, 0.47741414, 0.28993556],\n",
" [0.43298235, 0.58710277, 0.69306001],\n",
" [0.9521223 , 0.87239108, 0.10672981],\n",
" [0.93125144, 0.19405455, 0.95483289],\n",
" [0.91030892, 0.85961313, 0.67439157],\n",
" [0.09377237, 0.75818836, 0.61985122]],\n",
"\n",
" [[0.4344654 , 0.97297157, 0.89560878],\n",
" [0.91664946, 0.68966445, 0.0530751 ],\n",
" [0.72099738, 0.05779864, 0.30259649],\n",
" [0.55598956, 0.11611106, 0.24856552],\n",
" [0.40690072, 0.66148966, 0.22159354],\n",
" [0.53035294, 0.23237414, 0.82781172],\n",
" [0.20375017, 0.23486322, 0.36461596],\n",
" [0.05525619, 0.59671011, 0.08001122],\n",
" [0.11250979, 0.98519728, 0.57553523],\n",
" [0.6117834 , 0.65811775, 0.78386287]],\n",
"\n",
" [[0.39532528, 0.78660638, 0.37617851],\n",
" [0.86246711, 0.59398046, 0.50843286],\n",
" [0.41395181, 0.96399598, 0.8374128 ],\n",
" [0.76981858, 0.41760042, 0.17438256],\n",
" [0.05937649, 0.93289121, 0.63833505],\n",
" [0.97571178, 0.06364159, 0.34572432],\n",
" [0.42278241, 0.52111442, 0.62746908],\n",
" [0.0401781 , 0.80713288, 0.26990436],\n",
" [0.21850787, 0.19009324, 0.04497292],\n",
" [0.16176602, 0.20893733, 0.34094974]],\n",
"\n",
" [[0.13094336, 0.90151022, 0.82541695],\n",
" [0.73192844, 0.24791076, 0.3587372 ],\n",
" [0.88818939, 0.92023872, 0.69098959],\n",
" [0.08104613, 0.6361497 , 0.42552169],\n",
" [0.44517886, 0.99055202, 0.15580116],\n",
" [0.78742252, 0.04735346, 0.46423316],\n",
" [0.53474903, 0.79917168, 0.33019955],\n",
" [0.31087978, 0.65384266, 0.77275665],\n",
" [0.56393354, 0.5761927 , 0.4287843 ],\n",
" [0.57457285, 0.67154059, 0.52881047]],\n",
"\n",
" [[0.78373278, 0.15164648, 0.92791502],\n",
" [0.0999971 , 0.47319914, 0.44424683],\n",
" [0.74758969, 0.04583226, 0.0579972 ],\n",
" [0.37325021, 0.12464474, 0.61199188],\n",
" [0.07404238, 0.65504221, 0.18787021],\n",
" [0.16955187, 0.12750002, 0.48252436],\n",
" [0.17829354, 0.85701326, 0.41402596],\n",
" [0.21677806, 0.18949005, 0.27735136],\n",
" [0.06721647, 0.16941253, 0.46916978],\n",
" [0.39921131, 0.17705116, 0.94534667]]]])"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.random.rand(1,10,10,3)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[1.9436876 , 2.1640959 , 2.2837098 ],\n",
" [2.0772057 , 2.4174008 , 2.7732203 ],\n",
" [1.963449 , 2.741503 , 1.7088774 ]],\n",
"\n",
" [[1.6524236 , 3.0454814 , 1.8892637 ],\n",
" [2.4567943 , 2.5845926 , 2.3090153 ],\n",
" [1.6444083 , 1.7326821 , 1.7165766 ]],\n",
"\n",
" [[2.6089072 , 3.043223 , 1.8332952 ],\n",
" [1.7920854 , 2.1280923 , 1.2828767 ],\n",
" [0.72196686, 2.1598206 , 1.3420006 ]]]], dtype=float32)"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": (X*1000).round().astype(int).flatten().tolist()\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"out_json = {\n",
" \"out\": (y*1000).round().astype(int).flatten().tolist()\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"with open(\"sumPooling2D_stride_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"with open(\"sumPooling2D_stride_output.json\", \"w\") as f:\n",
" json.dump(out_json, f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "tf24",
"language": "python",
"name": "tf24"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
models/upSampling2d.ipynb | {
"cells": [
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.layers import Input, UpSampling2D\n",
"from tensorflow.keras import Model\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"inputs = Input(shape=(1,2,3))\n",
"x = UpSampling2D(size=2)(inputs)\n",
"model = Model(inputs, x)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model_1\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 1, 2, 3)] 0 \n",
" \n",
" up_sampling2d_1 (UpSampling (None, 2, 4, 3) 0 \n",
" 2D) \n",
" \n",
"=================================================================\n",
"Total params: 0\n",
"Trainable params: 0\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n"
]
}
],
"source": [
"model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[842674, 497907, 66624],\n",
" [875287, 832625, 34934]]]])"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = (np.random.rand(1,1,2,3)*1e6).astype(int)\n",
"X"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 27ms/step\n"
]
},
{
"data": {
"text/plain": [
"array([[[[842674., 497907., 66624.],\n",
" [842674., 497907., 66624.],\n",
" [875287., 832625., 34934.],\n",
" [875287., 832625., 34934.]],\n",
"\n",
" [[842674., 497907., 66624.],\n",
" [842674., 497907., 66624.],\n",
" [875287., 832625., 34934.],\n",
" [875287., 832625., 34934.]]]], dtype=float32)"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = model.predict(X)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"def UpSampling2DInt(nRows, nCols, nChannels, size, input):\n",
" out = [[[None for _ in range(nChannels)] for _ in range(nCols*size)] for _ in range(nRows*size)]\n",
" for i in range(nRows):\n",
" for j in range(nCols):\n",
" for c in range(nChannels):\n",
" for k in range(size):\n",
" for l in range(size):\n",
" out[i*size+k][j*size+l][c] = input[i][j][c]\n",
" return out\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"X_in = [[[int(X[0][i][j][k]) for k in range(3)] for j in range(2)] for i in range(1)]"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[[842674, 497907, 66624],\n",
" [842674, 497907, 66624],\n",
" [875287, 832625, 34934],\n",
" [875287, 832625, 34934]],\n",
" [[842674, 497907, 66624],\n",
" [842674, 497907, 66624],\n",
" [875287, 832625, 34934],\n",
" [875287, 832625, 34934]]]"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out = UpSampling2DInt(1, 2, 3, 2, X_in)\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"assert np.all(y[0].astype(int) == np.array(out))"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"in_json = {\n",
" \"in\": X_in,\n",
" \"out\": out\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"with open(\"upSampling2D_input.json\", \"w\") as f:\n",
" json.dump(in_json, f)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| https://github.com/socathie/circomlib-ml |
test/AveragePooling2D.js | const chai = require("chai");
const path = require("path");
const wasm_tester = require("circom_tester").wasm;
const F1Field = require("ffjavascript").F1Field;
const Scalar = require("ffjavascript").Scalar;
exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Fr = new F1Field(exports.p);
const assert = chai.assert;
describe("AveragePooling2D layer test", function () {
this.timeout(100000000);
// AveragePooling with strides==poolSize
it("(5,5,3) -> (2,2,3)", async () => {
const INPUT = require("../models/averagePooling2D_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "AveragePooling2D_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
// AveragePooling with strides!=poolSize
it("(10,10,3) -> (4,4,3)", async () => {
const INPUT = require("../models/averagePooling2D_stride_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "AveragePooling2D_stride_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
}); | https://github.com/socathie/circomlib-ml |
test/BatchNormalization.js | const chai = require("chai");
const path = require("path");
const wasm_tester = require("circom_tester").wasm;
const F1Field = require("ffjavascript").F1Field;
const Scalar = require("ffjavascript").Scalar;
exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Fr = new F1Field(exports.p);
const assert = chai.assert;
describe("BatchNormalization layer test", function () {
this.timeout(100000000);
it("(5,5,3) -> (5,5,3)", async () => {
const INPUT = require("../models/batchNormalization_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "BatchNormalization_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
});
| https://github.com/socathie/circomlib-ml |
test/Conv1D.js | const chai = require("chai");
const path = require("path");
const wasm_tester = require("circom_tester").wasm;
const F1Field = require("ffjavascript").F1Field;
const Scalar = require("ffjavascript").Scalar;
exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Fr = new F1Field(exports.p);
const assert = chai.assert;
const INPUT = require("../models/conv1D_input.json");
describe("Conv1D layer test", function () {
this.timeout(100000000);
it("(20,3) -> (6,2)", async () => {
const circuit = await wasm_tester(path.join(__dirname, "circuits", "Conv1D_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
}); | https://github.com/socathie/circomlib-ml |
test/Conv2D.js | const chai = require("chai");
const path = require("path");
const wasm_tester = require("circom_tester").wasm;
const F1Field = require("ffjavascript").F1Field;
const Scalar = require("ffjavascript").Scalar;
exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Fr = new F1Field(exports.p);
const assert = chai.assert;
describe("Conv2D layer test", function () {
this.timeout(100000000);
it("(5,5,3) -> (3,3,2)", async () => {
const INPUT = require("../models/conv2D_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "Conv2D_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
it("(10,10,3) -> (3,3,2)", async () => {
const INPUT = require("../models/conv2D_stride_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "Conv2D_stride_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
}); | https://github.com/socathie/circomlib-ml |
test/Conv2Dsame.js | const chai = require("chai");
const path = require("path");
const wasm_tester = require("circom_tester").wasm;
const F1Field = require("ffjavascript").F1Field;
const Scalar = require("ffjavascript").Scalar;
exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Fr = new F1Field(exports.p);
const assert = chai.assert;
describe("Conv2Dsame layer test", function () {
this.timeout(100000000);
it("(5,5,3) -> (5,5,2)", async () => {
const INPUT = require("../models/Conv2Dsame_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "Conv2Dsame_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
it("(10,10,3) -> (4,4,2)", async () => {
const INPUT = require("../models/Conv2Dsame_stride_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "Conv2Dsame_stride_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
}); | https://github.com/socathie/circomlib-ml |
test/Dense.js | const chai = require("chai");
const path = require("path");
const wasm_tester = require("circom_tester").wasm;
const F1Field = require("ffjavascript").F1Field;
const Scalar = require("ffjavascript").Scalar;
exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Fr = new F1Field(exports.p);
const assert = chai.assert;
describe("Dense layer test", function () {
this.timeout(100000000);
it("20 nodes -> 10 nodes", async () => {
const INPUT = require("../models/dense_input.json");
const circuit = await wasm_tester(path.join(__dirname, "circuits", "Dense_test.circom"));
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
}); | https://github.com/socathie/circomlib-ml |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.